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
improve focus tracking
Nick Sweeting3bb8fb0feea3
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 39c0786ca..70bffe5db 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -483,7 +483,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):_browser_session_id = self.browser_session.id if self.browser_session else self.id_current_page_id = (- self.browser_session.cdp_session.target_id[-2:] if self.browser_session and self.browser_session.cdp_session else '--'+ self.browser_session.agent_focus.target_id[-2:] if self.browser_session and self.browser_session.agent_focus else '--')return logging.getLogger(f'browser_use.Agentπ ° {self.task_id[-4:]} on π {_browser_session_id[-4:]} π {_current_page_id}')@@ -1210,6 +1210,12 @@ class Agent(Generic[Context, AgentStructuredOutput]):url = 'https://' + urlreturn url+ # If no URL found, check if task mentions Google or search+ task_lower = task.lower()+ if 'google' in task_lower or 'search' in task_lower:+ self.logger.debug('π Task mentions "google" or "search", defaulting to https://google.com')+ return 'https://google.com'+return None@observe(name='agent.run', metadata={'task': '{{task}}', 'debug': '{{debug}}'})diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.pyindex 031793314..8b4cd71ce 100644--- a/browser_use/browser/aboutblank_watchdog.py+++ b/browser_use/browser/aboutblank_watchdog.py@@ -155,8 +155,8 @@ class AboutBlankWatchdog(BaseWatchdog):This is used to visually indicate that the browser is setting up or waiting."""try:- # Get cached session- cdp_session = await self.browser_session.attach_cdp_session(target_id)+ # Create temporary session for this target without switching focus+ temp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False)# Inject the DVD screensaver script (from main branch with idempotency added)script = f"""@@ -268,7 +268,7 @@ class AboutBlankWatchdog(BaseWatchdog):}})('{browser_session_label}');"""- await cdp_session.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=cdp_session.session_id)+ await temp_session.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=temp_session.session_id)# No need to detach - session is cacheddiff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.pyindex 515e44dcf..310df1973 100644--- a/browser_use/browser/crash_watchdog.py+++ b/browser_use/browser/crash_watchdog.py@@ -68,14 +68,14 @@ class CrashWatchdog(BaseWatchdog):async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:"""Attach to new tab."""- assert self.browser_session.cdp_session is not None, 'No current target ID'- await self.attach_to_target(self.browser_session.cdp_session.target_id)+ 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)async def attach_to_target(self, target_id: str) -> None:"""Set up crash monitoring for a specific target using CDP."""try:- # Get cached session (domains already enabled by attach_cdp_session)- cdp_session = await self.browser_session.attach_cdp_session(target_id)+ # Create temporary session for monitoring without switching focus+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False)# Check if we already have listeners for this sessionif cdp_session.session_id in self._sessions_with_listeners:@@ -173,11 +173,11 @@ class CrashWatchdog(BaseWatchdog):target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)if (target_info- and self.browser_session.cdp_session- and target_info['targetId'] == self.browser_session.cdp_session.target_id+ and self.browser_session.agent_focus+ and target_info['targetId'] == self.browser_session.agent_focus.target_id):- self.browser_session.cdp_session.target_id = None # type: ignore- self.browser_session.cdp_session.session_id = None # type: ignore+ self.browser_session.agent_focus.target_id = None # type: ignore+ self.browser_session.agent_focus.session_id = None # type: ignoreself.logger.error(f'[CrashWatchdog] π₯ Target crashed, navigating Agent to a new tab: {target_info.get("url", "unknown")}')@@ -290,15 +290,15 @@ class CrashWatchdog(BaseWatchdog):"""Check if browser and targets are still responsive."""try:- cdp_session = await self.browser_session.attach_cdp_session()+ cdp_session = await self.browser_session.get_or_create_cdp_session()# Quick ping to check if session is aliveawait asyncio.wait_for(cdp_session.cdp_client.send.Runtime.evaluate(params={'expression': '1'}, session_id=cdp_session.session_id),timeout=1.0,)except Exception as e:- self.logger.error(f'[CrashWatchdog] β Crashed session detected for target {self.browser_session.cdp_session}')- self.browser_session.cdp_session.target_id = None # type: ignore+ self.logger.error(f'[CrashWatchdog] β Crashed session detected for target {self.browser_session.agent_focus}')+ self.browser_session.agent_focus.target_id = None # type: ignore# Check browser process if we have PIDif self.browser_session._local_browser_watchdog and (proc := self.browser_session._local_browser_watchdog._subprocess):diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.pyindex 972cd8056..b6c6e1a9a 100644--- a/browser_use/browser/default_action_watchdog.py+++ b/browser_use/browser/default_action_watchdog.py@@ -77,6 +77,13 @@ class DefaultActionWatchdog(BaseWatchdog):# Wait a bit for potential new tab to be created# This is necessary because tab creation is async and might not be immediateawait asyncio.sleep(0.5)++ # Clear cached state after click action since DOM might have changed+ self.logger.debug('π Click action completed, clearing cached browser state')+ self.browser_session._cached_browser_state_summary = None+ self.browser_session._cached_selector_map.clear()+ if self.browser_session._dom_watchdog:+ self.browser_session._dom_watchdog.clear_cache()# Check if a new tab was openedafter_target_ids = await self.browser_session._cdp_get_all_pages()@@ -116,6 +123,14 @@ class DefaultActionWatchdog(BaseWatchdog):# Log successself.logger.info(f'β¨οΈ Typed "{event.text}" into element with index {index_for_logging}')self.logger.debug(f'Element xpath: {element_node.xpath}')++ # Clear cached state after type action since DOM might have changed+ self.logger.debug('π Type action completed, clearing cached browser state')+ self.browser_session._cached_browser_state_summary = None+ self.browser_session._cached_selector_map.clear()+ if self.browser_session._dom_watchdog:+ self.browser_session._dom_watchdog.clear_cache()+return {'success': True}except Exception as e:self.event_bus.dispatch(@@ -130,7 +145,7 @@ class DefaultActionWatchdog(BaseWatchdog):"""Handle scroll request with CDP."""try:# Check if we have a current target for scrolling- if not self.browser_session.cdp_session:+ if not self.browser_session.agent_focus:raise ValueError('No active target for scrolling')except ValueError as e:self.event_bus.dispatch(@@ -149,7 +164,7 @@ class DefaultActionWatchdog(BaseWatchdog):# Element-specific scrolling if node is providedif event.node is not None:element_node = event.node- index_for_logging = element_node.element_index or 'unknown'+ index_for_logging = element_node.backend_node_id or 'unknown'# Try to scroll the element's containersuccess = await self._scroll_element_container(element_node, pixels)@@ -173,6 +188,7 @@ class DefaultActionWatchdog(BaseWatchdog):details={'direction': event.direction, 'amount': event.amount},))+ return {'success': False, 'error': f'Scroll failed: {str(e)}'}# ========== Implementation Methods ==========@@ -191,7 +207,7 @@ class DefaultActionWatchdog(BaseWatchdog):try:# Get CDP client- cdp_session = await self.browser_session.attach_cdp_session()+ cdp_session = await self.browser_session.get_or_create_cdp_session()# Get the correct session ID for the element's frame# session_id = await self._get_session_id_for_element(element_node)@@ -464,9 +480,9 @@ class DefaultActionWatchdog(BaseWatchdog):"""try:# Get CDP client and session- assert self.browser_session.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'- cdp_client = self.browser_session.cdp_session.cdp_client- session_id = self.browser_session.cdp_session.session_id+ 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# Get viewport dimensionslayout_metrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)@@ -543,10 +559,10 @@ class DefaultActionWatchdog(BaseWatchdog):# Find the target for this framefor target in targets['targetInfos']:if target['type'] == 'iframe' and element_node.frame_id in str(target.get('targetId', '')):- # Get cached session for this target+ # Create temporary session for iframe target without switching focustarget_id = target['targetId']- cdp_session = await self.browser_session.attach_cdp_session(target_id)- return cdp_session.session_id+ temp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False)+ return temp_session.session_id# If frame not found in targets, use main target sessionself.logger.debug(f'Frame {element_node.frame_id} not found in targets, using main session')@@ -554,12 +570,12 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.debug(f'Error getting frame session: {e}, using main session')# Use main target session- assert self.browser_session.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'- return self.browser_session.cdp_session.session_id+ 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_idasync def on_GoBackEvent(self, event: GoBackEvent) -> None:"""Handle navigate back request with CDP."""- cdp_session = await self.browser_session.attach_cdp_session()+ cdp_session = await self.browser_session.get_or_create_cdp_session()try:# Get CDP client and session@@ -594,7 +610,7 @@ class DefaultActionWatchdog(BaseWatchdog):async def on_GoForwardEvent(self, event: GoForwardEvent) -> None:"""Handle navigate forward request with CDP."""- cdp_session = await self.browser_session.attach_cdp_session()+ cdp_session = await self.browser_session.get_or_create_cdp_session()try:# Get navigation historyhistory = await cdp_session.cdp_client.send.Page.getNavigationHistory(session_id=cdp_session.session_id)@@ -627,13 +643,21 @@ class DefaultActionWatchdog(BaseWatchdog):async def on_RefreshEvent(self, event: RefreshEvent) -> None:"""Handle target refresh request with CDP."""- cdp_session = await self.browser_session.attach_cdp_session()+ cdp_session = await self.browser_session.get_or_create_cdp_session()try:# Reload the targetawait cdp_session.cdp_client.send.Page.reload(session_id=cdp_session.session_id)# Wait for reloadawait asyncio.sleep(1.0)++ # Clear cached state after refresh since DOM has been reloaded+ self.logger.debug('π Page refreshed, clearing cached browser state')+ self.browser_session._cached_browser_state_summary = None+ self.browser_session._cached_selector_map.clear()+ if self.browser_session._dom_watchdog:+ self.browser_session._dom_watchdog.clear_cache()+# Navigation is handled by NavigationWatchdog via eventsself.logger.info('π Target refreshed')@@ -666,7 +690,7 @@ class DefaultActionWatchdog(BaseWatchdog):async def on_SendKeysEvent(self, event: SendKeysEvent) -> None:"""Handle send keys request with CDP."""- cdp_session = await self.browser_session.attach_cdp_session()+ cdp_session = await self.browser_session.get_or_create_cdp_session()try:# Parse key combinationkeys = event.keys.lower()@@ -746,6 +770,14 @@ class DefaultActionWatchdog(BaseWatchdog):)self.logger.info(f'β¨οΈ Sent keys: {event.keys}')++ # Clear cached state if Enter key was pressed (might submit form and change DOM)+ if 'enter' in event.keys.lower() or 'return' in event.keys.lower():+ self.logger.debug('π Enter key pressed, clearing cached browser state')+ self.browser_session._cached_browser_state_summary = None+ self.browser_session._cached_selector_map.clear()+ if self.browser_session._dom_watchdog:+ self.browser_session._dom_watchdog.clear_cache()except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -795,8 +827,8 @@ class DefaultActionWatchdog(BaseWatchdog):try:# Get CDP client and sessioncdp_client = self.browser_session.cdp_client- assert self.browser_session.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'- session_id = self.browser_session.cdp_session.session_id+ assert self.browser_session.agent_focus is not None, 'CDP session not initialized - browser may not be connected yet'+ session_id = self.browser_session.agent_focus.session_id# Enable DOMawait cdp_client.send.DOM.enable(session_id=session_id)diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex 6d53bf6eb..6c74ca76a 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -95,7 +95,18 @@ class DOMWatchdog(BaseWatchdog):})();}"""- await self.browser_session._cdp_add_init_script(init_script)++ # Try to inject the script, but don't fail if the Page domain isn't ready yet+ # This can happen when a new tab is created and the CDP session isn't fully attached+ try:+ await self.browser_session._cdp_add_init_script(init_script)+ except Exception as e:+ if "'Page.addScriptToEvaluateOnNewDocument' wasn't found" in str(e):+ self.logger.debug(f'Page domain not ready for new tab, skipping init script injection: {e}')+ # The script will be injected when the page actually navigates+ else:+ # Re-raise other errors+ raiseasync def on_BrowserStateRequestEvent(self, event: BrowserStateRequestEvent) -> 'BrowserStateSummary':"""Handle browser state request by coordinating DOM building and screenshot capture.@@ -111,6 +122,10 @@ class DOMWatchdog(BaseWatchdog):from browser_use.browser.views import BrowserStateSummary, PageInfopage_url = await self.browser_session.get_current_page_url()+ if self.browser_session.agent_focus:+ 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}')+ else:+ self.logger.debug(f'π Current page URL: {page_url}, no cdp_session attached')# check if we should skip DOM tree build for pointless pagesnot_a_meaningful_website = page_url.lower().split(':', 1)[0] not in ('http', 'https')@@ -124,6 +139,7 @@ class DOMWatchdog(BaseWatchdog):# Fast path for empty pagesif not_a_meaningful_website:self.logger.debug(f'β‘ Skipping BuildDOMTree for empty target: {page_url}')+ self.logger.info(f'πΈ Not taking screenshot for empty page: {page_url} (non-http/https URL)')# Create minimal DOM statecontent = SerializedDOMState(_root=None, selector_map={})@@ -192,7 +208,8 @@ class DOMWatchdog(BaseWatchdog):try:# Check if handler is registeredhandlers = self.event_bus.handlers.get('ScreenshotEvent', [])- self.logger.debug(f'πΈ ScreenshotEvent handlers registered: {len(handlers)} - {[h.__name__ for h in handlers]}')+ handler_names = [getattr(h, '__name__', str(h)) for h in handlers]+ self.logger.debug(f'πΈ ScreenshotEvent handlers registered: {len(handlers)} - {handler_names}')screenshot_event = self.event_bus.dispatch(ScreenshotEvent(full_page=False, event_timeout=6.0))self.logger.debug(f'πΈ Dispatched ScreenshotEvent, waiting for event to complete...')diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.pyindex fcde6d71d..63652d993 100644--- a/browser_use/browser/downloads_watchdog.py+++ b/browser_use/browser/downloads_watchdog.py@@ -454,14 +454,13 @@ class DownloadsWatchdog(BaseWatchdog):return self._pdf_viewer_cache[page_url]try:- # Get cached session- cdp_session = await self.browser_session.attach_cdp_session(target_id)-- # Add timeout to prevent hanging on unresponsive pages+ # Create a temporary CDP session for this target without switching focusimport asyncio++ temp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False)result = await asyncio.wait_for(- cdp_session.cdp_client.send.Runtime.evaluate(+ temp_session.cdp_client.send.Runtime.evaluate(params={'expression': """(() => {@@ -518,7 +517,7 @@ class DownloadsWatchdog(BaseWatchdog):""",'returnByValue': True,},- session_id=cdp_session.session_id,+ session_id=temp_session.session_id,),timeout=5.0, # 5 second timeout to prevent hanging)@@ -556,14 +555,14 @@ class DownloadsWatchdog(BaseWatchdog):return Nonetry:- # Get cached session- cdp_session = await self.browser_session.attach_cdp_session(target_id)-- # Try to get the PDF URL with timeout+ # Create a temporary CDP session for this target without switching focusimport asyncio++ temp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False)+ # Try to get the PDF URL with timeoutresult = await asyncio.wait_for(- cdp_session.cdp_client.send.Runtime.evaluate(+ temp_session.cdp_client.send.Runtime.evaluate(params={'expression': """(() => {@@ -577,7 +576,7 @@ class DownloadsWatchdog(BaseWatchdog):""",'returnByValue': True,},- session_id=cdp_session.session_id,+ session_id=temp_session.session_id,),timeout=5.0, # 5 second timeout to prevent hanging)@@ -612,7 +611,7 @@ class DownloadsWatchdog(BaseWatchdog):escaped_pdf_url = json.dumps(pdf_url)result = await asyncio.wait_for(- cdp_session.cdp_client.send.Runtime.evaluate(+ temp_session.cdp_client.send.Runtime.evaluate(params={'expression': f"""(async () => {{@@ -649,7 +648,7 @@ class DownloadsWatchdog(BaseWatchdog):'awaitPromise': True,'returnByValue': True,},- session_id=cdp_session.session_id,+ session_id=temp_session.session_id,),timeout=10.0, # 10 second timeout for download operation)diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 6a9ca796e..fd8ce8fbf 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -21,7 +21,9 @@ class ElementSelectedEvent(BaseEvent[T_EventResultType]):@field_validator('node', mode='before')@classmethod- def serialize_node(cls, data: EnhancedDOMTreeNode) -> EnhancedDOMTreeNode:+ def serialize_node(cls, data: EnhancedDOMTreeNode | None) -> EnhancedDOMTreeNode | None:+ if data is None:+ return Nonereturn EnhancedDOMTreeNode(element_index=data.element_index,node_id=data.node_id,diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.pyindex dacdf6f93..13e970905 100644--- a/browser_use/browser/navigation_watchdog.py+++ b/browser_use/browser/navigation_watchdog.py@@ -64,8 +64,8 @@ class NavigationWatchdog(BaseWatchdog):"""Clear agent focus when browser stops."""# Clear target handlersself._target_close_handlers.clear()- if self.browser_session.cdp_session:- self.browser_session.cdp_session.target_id = None # type: ignore+ if self.browser_session.agent_focus:+ self.browser_session.agent_focus.target_id = '' # Clear target_id# ========== Tab Lifecycle Events ==========@@ -82,8 +82,12 @@ class NavigationWatchdog(BaseWatchdog):except Exception as e:self.logger.error(f'[NavigationWatchdog] Error tracking new target: {e}')- # When a new tab is created, agent typically focuses on it immediately- await self._update_agent_focus_to_latest_tab()+ # Only update focus if we're not already focused on this tab+ # (NavigateToUrlEvent with new_tab=True already handles focus change)+ current_tab_index = await self._get_current_tab_index()+ if current_tab_index != event.tab_index:+ # When a new tab is created by other means, agent typically focuses on it immediately+ await self._update_agent_focus_to_latest_tab()async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:"""Handle tab closure."""@@ -98,6 +102,16 @@ class NavigationWatchdog(BaseWatchdog):async def on_SwitchTabEvent(self, event: SwitchTabEvent) -> None:"""Handle explicit tab switches by the agent."""self.logger.debug(f'[NavigationWatchdog] Agent switching to tab {event.tab_index}')++ # Clear cached browser state when switching tabs since DOM will be different+ self.logger.debug('π Tab switch, clearing cached browser state and DOM')+ self.browser_session._cached_browser_state_summary = None+ self.browser_session._cached_selector_map.clear()++ # Clear DOM watchdog cache if available+ if self.browser_session._dom_watchdog:+ self.browser_session._dom_watchdog.clear_cache()+await self._switch_agent_focus_to_tab(event.tab_index)async def on_NavigateToUrlEvent(self, event: NavigateToUrlEvent) -> None:@@ -123,15 +137,40 @@ class NavigationWatchdog(BaseWatchdog):try:# Handle new tab navigationif event.new_tab:- # Create new tab using CDP- target_id = await self.browser_session._cdp_create_new_page(event.url or 'about:blank')- self._track_target(target_id)-- # Get tab index for events (after adding the target)+ # Check if we can reuse an existing about:blank tab+ target_id = None+ tab_index = Nonetargets = await self.browser_session._cdp_get_all_pages()- tab_index = len(targets) - 1++ # Look for a reusable about:blank tab (not the current one)+ current_target_id = self.browser_session.agent_focus.target_id if self.browser_session.agent_focus else None+ for idx, target in enumerate(targets):+ target_url = target.get('url', '')+ # Reuse if it's about:blank and not the current tab+ if target_url == 'about:blank' and target['targetId'] != current_target_id:+ target_id = target['targetId']+ tab_index = idx+ self.logger.info(f'[NavigationWatchdog] Reusing existing about:blank tab at index {tab_index}')+ break++ # Create new tab if no reusable one found+ if target_id is None:+ target_id = await self.browser_session._cdp_create_new_page(event.url or 'about:blank')+ self._track_target(target_id)+ # Get updated targets list and tab index+ targets = await self.browser_session._cdp_get_all_pages()+ tab_index = len(targets) - 1+ self.logger.info(f'[NavigationWatchdog] Created new tab at index {tab_index}')- # Navigate to URL if provided (already done in create_new_page if URL was provided)+ # Update agent focus to the new/reused tab FIRST before dispatching any events+ # This ensures the agent is looking at the right tab when events are processed+ self.logger.info(f'[NavigationWatchdog] Attaching CDP session to tab target: {target_id}')+ await self.browser_session.get_or_create_cdp_session(target_id)+ await self._dispatch_focus_changed()++ # Navigate to URL if provided+ # Note: For new tabs, navigation already happened in _cdp_create_new_page if URL was provided+ # For reused tabs, we need to navigate them nowif event.url:# Dispatch navigation started eventfrom browser_use.browser.events import NavigationStartedEvent@@ -144,7 +183,17 @@ class NavigationWatchdog(BaseWatchdog):)try:- # Navigation already happened in _cdp_create_new_page+ # For reused tabs, navigate to the URL+ # For new tabs, navigation already happened in _cdp_create_new_page+ current_url = await self._get_target_url(target_id)+ if current_url == 'about:blank':+ # This is a reused tab, need to navigate it+ self.logger.info(f'[NavigationWatchdog] Navigating reused tab to {event.url}')+ await self.browser_session._cdp_navigate(event.url, target_id)++ # Wait a bit to ensure the page has loaded+ await asyncio.sleep(0.5)+# Just dispatch completionresponse_status = None # CDP doesn't return response status directly@@ -190,17 +239,13 @@ class NavigationWatchdog(BaseWatchdog):loading_status=loading_status,))-- # Update agent focus to the new tab immediately- assert self.browser_session.cdp_session is not None, 'No current target ID'- self.browser_session.cdp_session.target_id = target_id- await self._dispatch_focus_changed()-- # ONLY dispatch TabCreatedEvent for NEW tabs (not existing tab navigation)- from browser_use.browser.events import TabCreatedEvent-- # Get the actual URL from the target++ # Get the actual URL from the target (may still be navigating)target_url = await self._get_target_url(target_id)+ self.logger.info(f'[NavigationWatchdog] New tab URL: {target_url or event.url}')++ # ONLY dispatch TabCreatedEvent for NEW tabs AFTER focus has been updated+ from browser_use.browser.events import TabCreatedEventself.event_bus.dispatch(TabCreatedEvent(tab_index=tab_index,@@ -323,6 +368,15 @@ class NavigationWatchdog(BaseWatchdog):async def on_NavigationCompleteEvent(self, event: NavigationCompleteEvent) -> None:"""Update agent focus when navigation completes and enforce security."""+ # Clear cached browser state and DOM after navigation+ self.logger.debug('π Navigation complete, clearing cached browser state and DOM')+ self.browser_session._cached_browser_state_summary = None+ self.browser_session._cached_selector_map.clear()++ # Clear DOM watchdog cache if available+ if self.browser_session._dom_watchdog:+ self.browser_session._dom_watchdog.clear_cache()+# Check if the navigated URL is allowedif not self._is_url_allowed(event.url):self.logger.warning(f'βοΈ Navigation to non-allowed URL detected: {event.url}')@@ -345,10 +399,9 @@ class NavigationWatchdog(BaseWatchdog):self.logger.error(f'βοΈ Failed to close target with non-allowed URL: {str(e)}')return- # Agent focus stays on the tab that navigated- current_tab_index = await self._get_current_tab_index()- if event.tab_index != current_tab_index:- await self._switch_agent_focus_to_tab(event.tab_index)+ # Don't switch focus - the tab that navigated should already have focus+ # This prevents incorrectly switching back to the wrong tab after new tab creation+ self.logger.debug(f'[NavigationWatchdog] Navigation complete for tab {event.tab_index}, keeping current focus')# ========== Tab Tracking Methods ==========@@ -453,7 +506,7 @@ class NavigationWatchdog(BaseWatchdog):@propertydef current_agent_target(self) -> str | None:"""Get the current target ID the agent is focused on."""- return self.browser_session.cdp_session.target_id if self.browser_session.cdp_session else None+ return self.browser_session.agent_focus.target_id if self.browser_session.agent_focus else None@propertydef current_agent_tab_index(self) -> int:@@ -467,9 +520,9 @@ class NavigationWatchdog(BaseWatchdog):async def _get_current_tab_index(self) -> int:"""Get the current tab index from target position."""- if self.browser_session.cdp_session is None or self.browser_session.cdp_session.target_id is None:+ if self.browser_session.agent_focus is None or self.browser_session.agent_focus.target_id is None:return 0- return await self._get_tab_index_for_target(self.browser_session.cdp_session.target_id)+ return await self._get_tab_index_for_target(self.browser_session.agent_focus.target_id)async def _get_tab_index_for_target(self, target_id: str) -> int:"""Get tab index for a specific target ID."""@@ -505,7 +558,7 @@ class NavigationWatchdog(BaseWatchdog):if targets:# Set initial focus to first target BEFORE dispatching events- await self.browser_session.attach_cdp_session(targets[0]['targetId'])+ await self.browser_session.get_or_create_cdp_session(targets[0]['targetId'])# Dispatch TabCreatedEvent for all initial pages so watchdogs can process themfrom browser_use.browser.events import TabCreatedEvent@@ -517,7 +570,7 @@ class NavigationWatchdog(BaseWatchdog):# Dispatch focus changed eventawait self._dispatch_focus_changed()- target_url = self.browser_session.cdp_session.url if self.browser_session.cdp_session else ''+ target_url = self.browser_session.agent_focus.url if self.browser_session.agent_focus else ''self.logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {target_url}')async def _update_agent_focus_to_latest_tab(self) -> None:@@ -525,12 +578,12 @@ class NavigationWatchdog(BaseWatchdog):targets = await self.browser_session._cdp_get_all_pages()if targets:# Focus on the last target (most recently created)- if self.browser_session.cdp_session:- self.browser_session.cdp_session.target_id = targets[-1]['targetId']+ # Properly attach CDP session to the new target+ await self.browser_session.get_or_create_cdp_session(targets[-1]['targetId'])await self._dispatch_focus_changed()- target_url = await self._get_target_url(- self.browser_session.cdp_session.target_id if self.browser_session.cdp_session else None- )+ target_url = None+ if self.browser_session.agent_focus and self.browser_session.agent_focus.target_id:+ target_url = await self._get_target_url(self.browser_session.agent_focus.target_id)tab_index = await self._get_current_tab_index()self.logger.info(f'[NavigationWatchdog] π Agent focus moved to new tab {tab_index}: {target_url}')@@ -538,12 +591,11 @@ class NavigationWatchdog(BaseWatchdog):"""Switch agent focus to a specific tab index."""targets = await self.browser_session._cdp_get_all_pages()if 0 <= tab_index < len(targets):- if self.browser_session.cdp_session:- self.browser_session.cdp_session.target_id = targets[tab_index]['targetId']+ target_id = targets[tab_index]['targetId']+ # Properly attach CDP session to the new target+ await self.browser_session.get_or_create_cdp_session(target_id)await self._dispatch_focus_changed()- target_url = await self._get_target_url(- self.browser_session.cdp_session.target_id if self.browser_session.cdp_session else None- )+ target_url = await self._get_target_url(target_id)self.logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {target_url}')async def _find_new_agent_target(self) -> None:@@ -553,21 +605,32 @@ class NavigationWatchdog(BaseWatchdog):# Try to stay at the same index, or go to the previous onecurrent_index = await self._get_current_tab_index()new_index = min(current_index, len(targets) - 1)- if self.browser_session.cdp_session:- self.browser_session.cdp_session.target_id = targets[new_index]['targetId']+ # Properly attach CDP session to the new target+ await self.browser_session.get_or_create_cdp_session(targets[new_index]['targetId'])await self._dispatch_focus_changed()- target_url = await self._get_target_url(self.browser_session.cdp_session.target_id if self.browser_session.cdp_session else None)+ target_url = None+ if self.browser_session.agent_focus and self.browser_session.agent_focus.target_id:+ target_url = await self._get_target_url(self.browser_session.agent_focus.target_id)self.logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {target_url}')else:- if self.browser_session:- self.browser_session.cdp_session.target_id = None+ if self.browser_session and self.browser_session.agent_focus:+ self.browser_session.agent_focus.target_id = ''async def _dispatch_focus_changed(self) -> None:"""Dispatch event when agent focus changes."""- if self.browser_session.cdp_session.target_id:+ # Clear cached browser state when focus changes since we're on a different tab now+ self.logger.debug('π Agent focus changed, clearing cached browser state and DOM')+ self.browser_session._cached_browser_state_summary = None+ self.browser_session._cached_selector_map.clear()++ # Clear DOM watchdog cache if available+ if self.browser_session._dom_watchdog:+ self.browser_session._dom_watchdog.clear_cache()++ if self.browser_session.agent_focus and self.browser_session.agent_focus.target_id:try:# Get URL asynchronously- target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)+ target_url = await self._get_target_url(self.browser_session.agent_focus.target_id)tab_index = await self._get_current_tab_index()self.event_bus.dispatch(AgentFocusChangedEvent(@@ -580,28 +643,30 @@ class NavigationWatchdog(BaseWatchdog):async def get_or_create_target(self) -> str:"""Get current agent target or create a new one if none exists."""- if self.browser_session.cdp_session.target_id:+ if self.browser_session.agent_focus and self.browser_session.agent_focus.target_id:# Check if current target URL is still allowed- target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)+ target_url = await self._get_target_url(self.browser_session.agent_focus.target_id)if target_url and not self._is_url_allowed(target_url):self.logger.warning(f'βοΈ Current target URL no longer allowed: {target_url}')# Close the current target and find/create a new onetry:- await self.browser_session._cdp_close_page(self.browser_session.cdp_session.target_id)+ await self.browser_session._cdp_close_page(self.browser_session.agent_focus.target_id)except Exception:pass- self.browser_session.cdp_session.target_id = None+ self.browser_session.agent_focus.target_id = ''else:- return self.browser_session.cdp_session.target_id+ return self.browser_session.agent_focus.target_idtry:targets = await self.browser_session._cdp_get_all_pages()for target in targets:target_url = target.get('url', '')if self._is_url_allowed(target_url):- self.browser_session.cdp_session.target_id = target['targetId']+ # Properly attach CDP session to the target+ await self.browser_session.get_or_create_cdp_session(target['targetId'])await self._dispatch_focus_changed()- return self.browser_session.cdp_session.target_id+ if self.browser_session.agent_focus:+ return self.browser_session.agent_focus.target_idexcept Exception as e:self.logger.warning(f'[NavigationWatchdog] Failed to get targets: {e}')# Don't pass TimeoutError, re-raise other exceptions@@ -617,8 +682,10 @@ class NavigationWatchdog(BaseWatchdog):# Try to get the new targettargets = await self.browser_session._cdp_get_all_pages()if targets:- self.browser_session.cdp_session.target_id = targets[-1]['targetId']+ # Properly attach CDP session to the new target+ await self.browser_session.get_or_create_cdp_session(targets[-1]['targetId'])await self._dispatch_focus_changed()- return self.browser_session.cdp_session.target_id+ if self.browser_session.agent_focus:+ return self.browser_session.agent_focus.target_idraise ValueError('Failed to create or find an active target')diff --git a/browser_use/browser/screenshot_watchdog.py b/browser_use/browser/screenshot_watchdog.pyindex a0130581b..8e867d509 100644--- a/browser_use/browser/screenshot_watchdog.py+++ b/browser_use/browser/screenshot_watchdog.py@@ -33,7 +33,7 @@ class ScreenshotWatchdog(BaseWatchdog):self.logger.debug('[ScreenshotWatchdog] Handler START - on_ScreenshotEvent called')try:# Get CDP client and session for current target- cdp_session = await self.browser_session.attach_cdp_session()+ cdp_session = await self.browser_session.get_or_create_cdp_session()# Activate the target to ensure it's focusedself.logger.debug(f'[ScreenshotWatchdog] Activating target: {cdp_session.target_id}')diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 0428874fb..9ce0171f0 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -152,10 +152,11 @@ class BrowserSession(BaseModel):event_bus: EventBus = Field(default_factory=EventBus)# Mutable public state- cdp_session: CDPSession | None = None+ agent_focus: CDPSession | None = None# Mutable private state shared between watchdogs_cdp_client_root: CDPClient | None = PrivateAttr(default=None)+ _cdp_session_pool: dict[str, CDPSession] = PrivateAttr(default_factory=dict)_cached_browser_state_summary: Any = PrivateAttr(default=None)_cached_selector_map: dict[int, EnhancedDOMTreeNode] = PrivateAttr(default_factory=dict)@@ -200,7 +201,7 @@ class BrowserSession(BaseModel):self._cached_browser_state_summary = Noneself._cached_selector_map.clear()- self.cdp_session = None+ self.agent_focus = Noneif self.is_local:self.cdp_url = None@@ -330,24 +331,60 @@ class BrowserSession(BaseModel):assert self._cdp_client_root is not None, 'CDP client not initialized - browser may not be connected yet'return self._cdp_client_root- async def attach_cdp_session(self, target_id: str | None = None) -> CDPSession:+ async def get_or_create_cdp_session(self, target_id: str | None = None, focus: bool = True) -> CDPSession:+ """Get or create a CDP session for a target.++ Args:+ target_id: Target ID to get session for. If None, uses current agent focus.+ focus: If True, switches agent focus to this target. If False, just returns session without changing focus.++ Returns:+ CDPSession for the specified target.+ """assert self.cdp_url is not None, 'CDP URL not set - browser may not be configured or launched yet'assert self._cdp_client_root is not None, 'Root CDP client not initialized - browser may not be connected yet'- assert self.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'-- if self.cdp_session.target_id == target_id:- return self.cdp_session+ assert self.agent_focus is not None, 'CDP session not initialized - browser may not be connected yet'- self.cdp_session = await CDPSession.for_target(self._cdp_client_root, target_id or self.cdp_session.target_id)- return self.cdp_session+ # If no target_id specified, use the current target_id+ if target_id is None:+ target_id = self.agent_focus.target_id++ # Check if we already have a session for this target in the pool+ if target_id in self._cdp_session_pool:+ session = self._cdp_session_pool[target_id]+ if focus and self.agent_focus.target_id != target_id:+ self.logger.debug(f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}')+ self.agent_focus = session+ else:+ self.logger.debug(f'[get_or_create_cdp_session] Reusing existing session for {target_id} (focus={focus})')+ return session++ # If it's the current focus target, return that session+ if self.agent_focus.target_id == target_id:+ self._cdp_session_pool[target_id] = self.agent_focus+ return self.agent_focus++ # Create new session for this target+ self.logger.debug(f'[get_or_create_cdp_session] Creating new CDP session for target {target_id}')+ session = await CDPSession.for_target(self._cdp_client_root, target_id)+ self._cdp_session_pool[target_id] = session++ # Only change agent focus if requested+ if focus:+ self.logger.debug(f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}')+ self.agent_focus = session+ else:+ self.logger.debug(f'[get_or_create_cdp_session] Created session for {target_id} without changing focus (still on {self.agent_focus.target_id})')++ return session@propertydef current_target_id(self) -> str | None:- return self.cdp_session.target_id if self.cdp_session else None+ return self.agent_focus.target_id if self.agent_focus else None@propertydef current_session_id(self) -> str | None:- return self.cdp_session.session_id if self.cdp_session else None+ return self.agent_focus.session_id if self.agent_focus else None# ========== Helper Methods ==========@@ -542,6 +579,8 @@ class BrowserSession(BaseModel):# to about:blank to avoid JS issues from CDP on chrome://* urlsfrom browser_use.utils import is_new_tab_page+ # Collect all targets that need redirection+ redirected_targets = []for target in page_targets:target_url = target.get('url', '')if is_new_tab_page(target_url) and target_url != 'about:blank':@@ -549,13 +588,23 @@ class BrowserSession(BaseModel):target_id = target['targetId']self.logger.info(f'π Redirecting {target_url} to about:blank for target {target_id}')try:- # navigate to about:blank- cdp_session = await self.attach_cdp_session(target_id)- await cdp_session.cdp_client.send.Page.navigate(- params={'url': 'about:blank'}, session_id=cdp_session.session_id+ # Create a CDP session for this target+ temp_session = await CDPSession.for_target(self._cdp_client_root, target_id)+ # Navigate to about:blank+ await temp_session.cdp_client.send.Page.navigate(+ params={'url': 'about:blank'}, session_id=temp_session.session_id)+ redirected_targets.append(target_id)+ # Update the target's URL in our list for later use+ target['url'] = 'about:blank'+ # Small delay to ensure navigation completes+ await asyncio.sleep(0.1)except Exception as e:self.logger.warning(f'Failed to redirect {target_url} to about:blank: {e}')++ # Log summary of redirections+ if redirected_targets:+ self.logger.info(f'β Redirected {len(redirected_targets)} chrome://newtab pages to about:blank')if not page_targets:# No pages found, create a new one@@ -567,13 +616,13 @@ class BrowserSession(BaseModel):target_id = page_targets[0]['targetId']self.logger.info(f'π Using existing page with target ID: {target_id}')- # Store the current page target ID- self.cdp_session = await CDPSession.for_target(self._cdp_client_root, target_id)+ # Store the current page target ID and add to pool+ self.agent_focus = await CDPSession.for_target(self._cdp_client_root, target_id)+ self._cdp_session_pool[target_id] = self.agent_focus- # Pre-create cached session for the current target (enables all domains)+ # Verify the session is workingtry:- cdp_session = await self.attach_cdp_session(target_id)- assert self.cdp_session.title != 'Unknown title'+ assert self.agent_focus.title != 'Unknown title'except Exception as e:self.logger.warning(f'Failed to create CDP session: {e}')raise@@ -584,7 +633,7 @@ class BrowserSession(BaseModel):self.logger.error('β Browser cannot continue without CDP connection')# Clean up any partial stateself._cdp_client_root = None- self.cdp_session = None+ self.agent_focus = None# Re-raise as a fatal errorraise RuntimeError(f'Failed to establish CDP connection to browser: {e}') from e@@ -671,12 +720,12 @@ class BrowserSession(BaseModel):async def get_current_target_info(self) -> TargetInfo | None:"""Get info about the current active target using CDP."""- if not self.cdp_session or not self.cdp_session.target_id:+ if not self.agent_focus or not self.agent_focus.target_id:return Nonetargets = await self.cdp_client.send.Target.getTargets()for target in targets.get('targetInfos', []):- if target.get('targetId') == self.cdp_session.target_id:+ if target.get('targetId') == self.agent_focus.target_id:# Still return even if it's not a "valid" target since we're looking for a specific IDreturn targetreturn None@@ -782,11 +831,11 @@ class BrowserSession(BaseModel):async def remove_highlights(self) -> None:"""Remove highlights from the page using CDP."""try:- if not self.cdp_session or not self.cdp_session.target_id:+ if not self.agent_focus or not self.agent_focus.target_id:return# Get cached session- cdp_session = await self.attach_cdp_session()+ cdp_session = await self.get_or_create_cdp_session()# Remove highlights via JavaScriptscript = """@@ -855,16 +904,16 @@ class BrowserSession(BaseModel):async def _cdp_get_cookies(self) -> list[Cookie]:"""Get cookies using CDP Network.getCookies."""- cdp_session = await self.attach_cdp_session()+ cdp_session = await self.get_or_create_cdp_session()result = await cdp_session.cdp_client.send.Storage.getCookies(session_id=cdp_session.session_id)return result.get('cookies', [])async def _cdp_set_cookies(self, cookies: list[Cookie]) -> None:"""Set cookies using CDP Storage.setCookies."""- if not self.cdp_session or not cookies:+ if not self.agent_focus or not cookies:return- cdp_session = await self.attach_cdp_session()+ cdp_session = await self.get_or_create_cdp_session()# Storage.setCookies expects params dict with 'cookies' keyawait cdp_session.cdp_client.send.Storage.setCookies(params={'cookies': cookies}, # type: ignore[arg-type]@@ -873,15 +922,15 @@ class BrowserSession(BaseModel):async def _cdp_clear_cookies(self) -> None:"""Clear all cookies using CDP Network.clearBrowserCookies."""- cdp_session = await self.attach_cdp_session()+ cdp_session = await self.get_or_create_cdp_session()await cdp_session.cdp_client.send.Storage.clearCookies(session_id=cdp_session.session_id)async def _cdp_set_extra_headers(self, headers: dict[str, str]) -> None:"""Set extra HTTP headers using CDP Network.setExtraHTTPHeaders."""- if not self.cdp_session:+ if not self.agent_focus:return- cdp_session = await self.attach_cdp_session()+ cdp_session = await self.get_or_create_cdp_session()# await cdp_session.cdp_client.send.Network.setExtraHTTPHeaders(params={'headers': headers}, session_id=cdp_session.session_id)raise NotImplementedError('Not implemented yet')@@ -890,7 +939,7 @@ class BrowserSession(BaseModel):params = {'permissions': permissions}# if origin:# params['origin'] = origin- cdp_session = await self.attach_cdp_session()+ cdp_session = await self.get_or_create_cdp_session()# await cdp_session.cdp_client.send.Browser.grantPermissions(params=params, session_id=cdp_session.session_id)raise NotImplementedError('Not implemented yet')@@ -907,7 +956,7 @@ class BrowserSession(BaseModel):async def _cdp_add_init_script(self, script: str) -> str:"""Add script to evaluate on new document using CDP Page.addScriptToEvaluateOnNewDocument."""assert self._cdp_client_root is not None- cdp_session = await self.attach_cdp_session()+ cdp_session = await self.get_or_create_cdp_session()result = await cdp_session.cdp_client.send.Page.addScriptToEvaluateOnNewDocument(params={'source': script, 'runImmediately': True}@@ -916,7 +965,7 @@ class BrowserSession(BaseModel):async def _cdp_remove_init_script(self, identifier: str) -> None:"""Remove script added with addScriptToEvaluateOnNewDocument."""- cdp_session = await self.attach_cdp_session(target_id='main')+ cdp_session = await self.get_or_create_cdp_session(target_id='main')await cdp_session.cdp_client.send.Page.removeScriptToEvaluateOnNewDocument(params={'identifier': identifier}, session_id=cdp_session.session_id)@@ -944,12 +993,12 @@ class BrowserSession(BaseModel):# Use provided target_id or fall back to current_target_idassert self._cdp_client_root is not None, 'CDP client not initialized - browser may not be connected yet'- assert self.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'+ assert self.agent_focus is not None, 'CDP session not initialized - browser may not be connected yet'- self.cdp_session = await CDPSession.for_target(self._cdp_client_root, target_id or self.cdp_session.target_id)+ self.agent_focus = await CDPSession.for_target(self._cdp_client_root, target_id or self.agent_focus.target_id)# Use helper to navigate on the target- await self.cdp_session.cdp_client.send.Page.navigate(params={'url': url}, session_id=self.cdp_session.session_id)+ await self.agent_focus.cdp_client.send.Page.navigate(params={'url': url}, session_id=self.agent_focus.session_id)@staticmethoddef _is_valid_target(@@ -1031,8 +1080,8 @@ class BrowserSession(BaseModel):for target in all_targets:target_id = target['targetId']- # Get cached session for this target- cdp_session = await self.attach_cdp_session(target_id)+ # Get cached session for this target (don't change focus - iterating frames)+ cdp_session = await self.get_or_create_cdp_session(target_id, focus=False)target_sessions[target_id] = cdp_session.session_idtry:@@ -1173,7 +1222,7 @@ class BrowserSession(BaseModel):return all_frames.get(frame_id)async def cdp_client_for_target(self, target_id: str) -> CDPSession:- return await self.attach_cdp_session(target_id)+ return await self.get_or_create_cdp_session(target_id, focus=False)async def cdp_client_for_frame(self, frame_id: str) -> CDPSession:"""Get a CDP client attached to the target containing the specified frame.@@ -1203,8 +1252,8 @@ class BrowserSession(BaseModel):assert target_id is not None# Use existing sessionsession_id = target_sessions[target_id]- # Return the client with session attached- return await self.attach_cdp_session(target_id)+ # Return the client with session attached (don't change focus)+ return await self.get_or_create_cdp_session(target_id, focus=False)# Frame not foundraise ValueError(f"Frame with ID '{frame_id}' not found in any target")@@ -1213,7 +1262,7 @@ class BrowserSession(BaseModel):"""Get CDP client for a specific DOM node based on its frame."""if node.frame_id:return await self.cdp_client_for_frame(node.frame_id)- return await self.attach_cdp_session()+ return await self.get_or_create_cdp_session()# Fix Pydantic circular dependency for all watchdogsdiff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.pyindex 5f6d5a0fd..fcbe697a5 100644--- a/browser_use/browser/storage_state_watchdog.py+++ b/browser_use/browser/storage_state_watchdog.py@@ -325,8 +325,8 @@ class StorageStateWatchdog(BaseWatchdog):try:cookies = await self.browser_session._cdp_get_cookies()- # Convert Cookie objects to dicts- return [cookie.model_dump() if hasattr(cookie, 'model_dump') else dict(cookie) for cookie in cookies]+ # Cookie is a TypedDict, cast to dict for compatibility+ return [dict(cookie) for cookie in cookies]except Exception as e:self.logger.error(f'[StorageStateWatchdog] Failed to get cookies: {e}')return []diff --git a/browser_use/cli.py b/browser_use/cli.pyindex 14ca87151..c2de399c3 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -743,11 +743,13 @@ class BrowserUseApp(App):browser_status = '[red]Disconnected[/]'try:- # Check if browser PID is available- if hasattr(browser_session, 'browser_pid') and browser_session.browser_pid:- browser_pid = str(browser_session.browser_pid)- connected = True- browser_status = '[green]Connected[/]'+ # Check if browser PID is available through LocalBrowserWatchdog+ if hasattr(browser_session, '_local_browser_watchdog') and browser_session._local_browser_watchdog:+ local_watchdog = browser_session._local_browser_watchdog+ if hasattr(local_watchdog, 'browser_pid') and local_watchdog.browser_pid:+ browser_pid = str(local_watchdog.browser_pid)+ connected = True+ browser_status = '[green]Connected[/]'# Otherwise just check if we have a CDP URLelif browser_session.cdp_url:connected = True@@ -1348,13 +1350,7 @@ async def textual_interface(config: dict[str, Any]):)logger.debug('BrowserSession initialized successfully')- # Log browser version if available- try:- if hasattr(browser_session, 'browser') and browser_session.browser:- version = browser_session.browser.version- logger.info(f'Browser version: {version}')- except Exception as e:- logger.debug(f'Could not determine browser version: {e}')+ # Browser version logging not available with CDP implementationexcept Exception as e:logger.error(f'Error initializing BrowserSession: {str(e)}', exc_info=True)raise RuntimeError(f'Failed to initialize BrowserSession: {str(e)}')diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex f3b444403..fe204a259 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -19,6 +19,7 @@ from browser_use.browser.events import (GoBackEvent,NavigateToUrlEvent,ScrollEvent,+ ScrollToTextEvent,SendKeysEvent,SwitchTabEvent,TypeTextEvent,@@ -80,11 +81,48 @@ class Controller(Generic[Context]):async def search_google(params: SearchGoogleAction, browser_session: BrowserSession):search_url = f'https://www.google.com/search?q={params.query}&udm=14'+ # Check if there's already a tab open on Google or agent's about:blank+ use_new_tab = True+ try:+ tabs = await browser_session.get_tabs()+ # Get last 4 chars of browser session ID to identify agent's tabs+ browser_session_label = str(browser_session.id)[-4:]++ for i, tab in enumerate(tabs):+ # Check if tab is on Google domain+ if tab.url and 'google.com' in tab.url:+ # Found existing Google tab, navigate in it+ logger.debug(f'Found existing Google tab at index {i}: {tab.url}, reusing it')++ # Switch to this tab first if it's not the current one+ from browser_use.browser.events import SwitchTabEvent+ if browser_session.agent_focus and tab.id != browser_session.agent_focus.target_id:+ switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=i))+ await switch_event++ use_new_tab = False+ break+ # Check if it's an agent-owned about:blank page (has "Starting agent XXXX..." title)+ elif tab.url == 'about:blank' and tab.title and browser_session_label in tab.title:+ # This is our agent's about:blank page with DVD animation+ logger.debug(f'Found agent-owned about:blank tab at index {i} with title: {tab.title}, reusing it')++ # Switch to this tab first+ from browser_use.browser.events import SwitchTabEvent+ if browser_session.agent_focus and tab.id != browser_session.agent_focus.target_id:+ switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=i))+ await switch_event++ use_new_tab = False+ break+ except Exception as e:+ logger.debug(f'Could not check for existing tabs: {e}, using new tab')+# Dispatch navigation eventevent = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=search_url,- new_tab=True, # Always use new tab for Google searches+ new_tab=use_new_tab,))await event@@ -319,7 +357,7 @@ class Controller(Generic[Context]):# Run markdownify in a thread pool to avoid blocking the event looploop = asyncio.get_event_loop()- cdp_session = await browser_session.attach_cdp_session()+ cdp_session = await browser_session.get_or_create_cdp_session()try:page_html_result = await cdp_session.cdp_client.send.Page.captureSnapshot(@@ -423,9 +461,14 @@ Explain the content of the page and that the requested information is not availa# Look up the node from the selector map if index is providednode = Noneif params.index is not None:- node = await browser_session.get_element_by_index(params.index)- if node is None:- raise ValueError(f'Element index {params.index} not found in DOM')+ try:+ node = await browser_session.get_element_by_index(params.index)+ if node is None:+ # Element not found - return error+ raise ValueError(f'Element index {params.index} not found in DOM')+ except Exception as e:+ # Error getting element - return error+ raise ValueError(f'Failed to get element {params.index}: {e}') from e# Dispatch scroll event with node - the complex logic is handled in the event handler# Convert pages to pixels (assuming 800px per page as standard viewport height)@@ -474,32 +517,32 @@ Explain the content of the page and that the requested information is not availalogger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Sent keys: {params.keys}')- # @self.registry.action(- # description='Scroll to a text in the current page',- # )- # async def scroll_to_text(text: str, browser_session: BrowserSession): # type: ignore- # # Dispatch scroll to text event- # event = browser_session.event_bus.dispatch(- # ScrollToTextEvent(text=text)- # )- # await event+ @self.registry.action(+ description='Scroll to a text in the current page',+ )+ async def scroll_to_text(text: str, browser_session: BrowserSession): # type: ignore+ # Dispatch scroll to text event+ event = browser_session.event_bus.dispatch(+ ScrollToTextEvent(text=text)+ )+ await event- # # Check result to see if text was found- # result = await event.event_result()- # if result and result.get('found'):- # msg = f'π Scrolled to text: {text}'- # logger.info(msg)- # return ActionResult(- # extracted_content=msg, include_in_memory=True, long_term_memory=f'Scrolled to text: {text}'- # )- # else:- # msg = f"Text '{text}' not found or not visible on page"- # logger.info(msg)- # return ActionResult(- # extracted_content=msg,- # include_in_memory=True,- # long_term_memory=f"Tried scrolling to text '{text}' but it was not found",- # )+ # Check result to see if text was found+ result = await event.event_result()+ if result and result.get('found'):+ msg = f'π Scrolled to text: {text}'+ logger.info(msg)+ return ActionResult(+ extracted_content=msg, include_in_memory=True, long_term_memory=f'Scrolled to text: {text}'+ )+ else:+ msg = f"Text '{text}' not found or not visible on page"+ logger.info(msg)+ return ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ long_term_memory=f"Tried scrolling to text '{text}' but it was not found",+ )# # File System Actions# @self.registry.action(@@ -567,114 +610,114 @@ Explain the content of the page and that the requested information is not availa# description='Get all options from a native dropdown or ARIA menu',# )# async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult:- # """Get all options from a native dropdown or ARIA menu"""- # page = await browser_session.get_current_page()- # dom_element = await browser_session.get_dom_element_by_index(index)- # if dom_element is None:- # raise Exception(f'Element index {index} does not exist - retry or use alternative actions')-- # try:- # # Frame-aware approach since we know it works- # all_options = []- # frame_index = 0-- # for frame in page.frames:- # try:- # # First check if it's a native select element- # options = await frame.evaluate(- # """- # (xpath) => {- # const element = document.evaluate(xpath, document, null,- # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;- # if (!element) return null;-- # // Check if it's a native select element- # if (element.tagName.toLowerCase() === 'select') {- # return {- # type: 'select',- # options: Array.from(element.options).map(opt => ({- # text: opt.text, //do not trim, because we are doing exact match in select_dropdown_option- # value: opt.value,- # index: opt.index- # })),- # id: element.id,- # name: element.name- # };- # }+ # """Get all options from a native dropdown or ARIA menu"""- # // Check if it's an ARIA menu- # if (element.getAttribute('role') === 'menu' ||- # element.getAttribute('role') === 'listbox' ||- # element.getAttribute('role') === 'combobox') {- # // Find all menu items- # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');- # const options = [];-- # menuItems.forEach((item, idx) => {- # // Get the text content of the menu item- # const text = item.textContent.trim();- # if (text) {- # options.push({- # text: text,- # value: text, // For ARIA menus, use text as value- # index: idx- # });- # }- # });-- # return {- # type: 'aria',- # options: options,- # id: element.id || '',- # name: element.getAttribute('aria-label') || ''- # };+ # dom_element = await browser_session.get_dom_element_by_index(index)+ # if dom_element is None:+ # raise Exception(f'Element index {index} does not exist - retry or use alternative actions')++ # try:+ # # Frame-aware approach since we know it works+ # all_options = []+ # frame_index = 0++ # for frame in page.frames:+ # try:+ # # First check if it's a native select element+ # options = await frame.evaluate(+ # """+ # (xpath) => {+ # const element = document.evaluate(xpath, document, null,+ # XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;+ # if (!element) return null;++ # // Check if it's a native select element+ # if (element.tagName.toLowerCase() === 'select') {+ # return {+ # type: 'select',+ # options: Array.from(element.options).map(opt => ({+ # text: opt.text, //do not trim, because we are doing exact match in select_dropdown_option+ # value: opt.value,+ # index: opt.index+ # })),+ # id: element.id,+ # name: element.name+ # };+ # }++ # // Check if it's an ARIA menu+ # if (element.getAttribute('role') === 'menu' ||+ # element.getAttribute('role') === 'listbox' ||+ # element.getAttribute('role') === 'combobox') {+ # // Find all menu items+ # const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');+ # const options = [];++ # menuItems.forEach((item, idx) => {+ # // Get the text content of the menu item+ # const text = item.textContent.trim();+ # if (text) {+ # options.push({+ # text: text,+ # value: text, // For ARIA menus, use text as value+ # index: idx+ # });+ # }+ # });++ # return {+ # type: 'aria',+ # options: options,+ # id: element.id || '',+ # name: element.getAttribute('aria-label') || ''+ # };+ # }++ # return null;# }+ # """,+ # dom_element.xpath,+ # )- # return null;- # }- # """,- # dom_element.xpath,- # )+ # if options:+ # logger.debug(f'Found {options["type"]} dropdown in frame {frame_index}')+ # logger.debug(f'Element ID: {options["id"]}, Name: {options["name"]}')- # if options:- # logger.debug(f'Found {options["type"]} dropdown in frame {frame_index}')- # logger.debug(f'Element ID: {options["id"]}, Name: {options["name"]}')+ # formatted_options = []+ # for opt in options['options']:+ # # encoding ensures AI uses the exact string in select_dropdown_option+ # encoded_text = json.dumps(opt['text'])+ # formatted_options.append(f'{opt["index"]}: text={encoded_text}')- # formatted_options = []- # for opt in options['options']:- # # encoding ensures AI uses the exact string in select_dropdown_option- # encoded_text = json.dumps(opt['text'])- # formatted_options.append(f'{opt["index"]}: text={encoded_text}')+ # all_options.extend(formatted_options)- # all_options.extend(formatted_options)+ # except Exception as frame_e:+ # logger.debug(f'Frame {frame_index} evaluation failed: {str(frame_e)}')- # except Exception as frame_e:- # logger.debug(f'Frame {frame_index} evaluation failed: {str(frame_e)}')+ # frame_index += 1- # frame_index += 1+ # if all_options:+ # msg = '\n'.join(all_options)+ # msg += '\nUse the exact text string in select_dropdown_option'+ # logger.info(msg)+ # return ActionResult(+ # extracted_content=msg,+ # include_in_memory=True,+ # long_term_memory=f'Found dropdown options for index {index}.',+ # include_extracted_content_only_once=True,+ # )+ # else:+ # msg = 'No options found in any frame for dropdown'+ # logger.info(msg)+ # return ActionResult(+ # extracted_content=msg, include_in_memory=True, long_term_memory='No dropdown options found'+ # )- # if all_options:- # msg = '\n'.join(all_options)- # msg += '\nUse the exact text string in select_dropdown_option'- # logger.info(msg)- # return ActionResult(- # extracted_content=msg,- # include_in_memory=True,- # long_term_memory=f'Found dropdown options for index {index}.',- # include_extracted_content_only_once=True,- # )- # else:- # msg = 'No options found in any frame for dropdown'+ # except Exception as e:+ # logger.error(f'Failed to get dropdown options: {str(e)}')+ # msg = f'Error getting options: {str(e)}'# logger.info(msg)- # return ActionResult(- # extracted_content=msg, include_in_memory=True, long_term_memory='No dropdown options found'- # )-- # except Exception as e:- # logger.error(f'Failed to get dropdown options: {str(e)}')- # msg = f'Error getting options: {str(e)}'- # logger.info(msg)- # return ActionResult(extracted_content=msg, include_in_memory=True)+ # return ActionResult(extracted_content=msg, include_in_memory=True)# TODO: Refactor to use events instead of direct page/dom access# @self.registry.action(diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.pyindex 188777ff7..78a9bd26c 100644--- a/browser_use/dom/debug/highlights.py+++ b/browser_use/dom/debug/highlights.py@@ -53,7 +53,7 @@ async def remove_highlighting_script(dom_service: DomService) -> None:"""Remove all browser-use highlighting elements from the page."""try:# Get CDP client and session ID- cdp_session = await dom_service.browser_session.attach_cdp_session()+ cdp_session = await dom_service.browser_session.get_or_create_cdp_session()print('π§Ή Removing browser-use highlighting elements')@@ -361,7 +361,7 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen}})();"""- cdp_session = await dom_service.browser_session.attach_cdp_session()+ cdp_session = await dom_service.browser_session.get_or_create_cdp_session()# Inject the enhanced CSP-safe script via CDPawait cdp_session.cdp_client.send.Runtime.evaluate(diff --git a/browser_use/dom/playground/tree.py b/browser_use/dom/playground/tree.pyindex 255600cb4..1936ed309 100644--- a/browser_use/dom/playground/tree.py+++ b/browser_use/dom/playground/tree.py@@ -34,18 +34,35 @@ async def main():# await browser.create_new_tab('https://en.wikipedia.org/wiki/Apple_Inc.')# await browser.create_new_tab('https://semantic-ui.com/modules/dropdown.html#/definition')# await browser.navigate('https://v0-website-with-clickable-elements.vercel.app/iframe-buttons')- await browser.navigate('https://v0-website-with-clickable-elements.vercel.app/nested-iframe')-- await browser._wait_for_page_and_frames_load()-- page = await browser.get_current_page()+ from browser_use.browser.events import NavigateToUrlEvent+ nav_event = browser.event_bus.dispatch(NavigateToUrlEvent(url='https://v0-website-with-clickable-elements.vercel.app/nested-iframe'))+ await nav_event++ # Wait a moment for page to fully load+ await asyncio.sleep(2)while True:async with DomService(browser) as dom_service:await remove_highlighting_script(dom_service)start = time.time()- dom_tree, dom_timing = await dom_service.get_dom_tree()+ # Get current target ID from browser session+ if browser.agent_focus and browser.agent_focus.target_id:+ target_id = browser.agent_focus.target_id+ else:+ # Get first available target+ targets = await browser._cdp_get_all_pages()+ if not targets:+ raise ValueError('No targets available')+ target_id = targets[0]['targetId']++ result = await dom_service.get_dom_tree(target_id)+ if isinstance(result, tuple):+ dom_tree = result[0]+ dom_timing = result[1] if len(result) > 1 else {}+ else:+ dom_tree = result+ dom_timing = {}end = time.time()print(f'Time taken: {end - start} seconds')diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 317401941..f56728b74 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -124,7 +124,7 @@ class DomService:async def _get_viewport_ratio(self, target_id: str) -> float:"""Get viewport dimensions, device pixel ratio, and scroll position using CDP."""- cdp_session = await self.browser_session.attach_cdp_session(target_id=target_id)+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=False)try:# Get the layout metrics which includes the visual viewport@@ -224,7 +224,7 @@ class DomService:async def _get_ax_tree_for_all_frames(self, target_id: str) -> GetFullAXTreeReturns:"""Recursively collect all frames and merge their accessibility trees into a single array."""- cdp_session = await self.browser_session.attach_cdp_session(target_id=target_id)+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=False)frame_tree = await cdp_session.cdp_client.send.Page.getFrameTree(session_id=cdp_session.session_id)def collect_all_frame_ids(frame_tree_node) -> list[str]:@@ -259,7 +259,7 @@ class DomService:return {'nodes': merged_nodes}async def _get_all_trees(self, target_id: str) -> TargetAllTrees:- cdp_session = await self.browser_session.attach_cdp_session(target_id=target_id)+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=target_id, focus=False)# Wait for the page to be ready firsttry:@@ -409,7 +409,7 @@ class DomService:attributes=attributes or {},is_scrollable=node.get('isScrollable', None),frame_id=node.get('frameId', None),- session_id=self.browser_session.cdp_session.session_id if self.browser_session.cdp_session else None,+ session_id=self.browser_session.agent_focus.session_id if self.browser_session.agent_focus else None,target_id=target_id,content_document=None,shadow_root_type=shadow_root_type,diff --git a/browser_use/llm/tests/test_single_step.py b/browser_use/llm/tests/test_single_step.pyindex d14e4a265..eec24bfc5 100644--- a/browser_use/llm/tests/test_single_step.py+++ b/browser_use/llm/tests/test_single_step.py@@ -32,6 +32,10 @@ def create_mock_state_message(temp_dir: str):node_value='Click Me',attributes={'id': 'test-button'},is_scrollable=False,+ is_visible=True,+ absolute_position=None,+ session_id=None,+ target_id='test-target',frame_id=None,content_document=None,shadow_root_type=None,diff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.pyindex 315ccb480..7f387482d 100644--- a/browser_use/mcp/server.py+++ b/browser_use/mcp/server.py@@ -740,8 +740,10 @@ class BrowserUseServer:from browser_use.browser.events import ScrollEvent# Scroll by a standard amount (500 pixels)- dy = 500 if direction == 'down' else -500- event = self.browser_session.event_bus.dispatch(ScrollEvent(dx=0, dy=dy))+ event = self.browser_session.event_bus.dispatch(ScrollEvent(+ direction=direction, # type: ignore+ amount=500+ ))await eventreturn f'Scrolled {direction}'@@ -774,7 +776,7 @@ class BrowserUseServer:tabs_info = await self.browser_session.get_tabs()tabs = []for i, tab in enumerate(tabs_info):- tabs.append({'index': i, 'url': tab['url'], 'title': tab.get('title', '')})+ tabs.append({'index': i, 'url': tab.url, 'title': tab.title or ''})return json.dumps(tabs, indent=2)async def _switch_tab(self, tab_index: int) -> str:@@ -795,7 +797,7 @@ class BrowserUseServer:tabs = await self.browser_session.get_tabs()if 0 <= tab_index < len(tabs):- url = tabs[tab_index]['url']+ url = tabs[tab_index].urlfrom browser_use.browser.events import CloseTabEventevent = self.browser_session.event_bus.dispatch(CloseTabEvent(tab_index=tab_index))await eventdiff --git a/examples/browser/real_browser.py b/examples/browser/real_browser.pyindex e232ebea2..9d5cae8b0 100644--- a/examples/browser/real_browser.py+++ b/examples/browser/real_browser.py@@ -29,7 +29,7 @@ async def main():)await agent.run()- await browser_session.close()+ await browser_session.kill()input('Press Enter to close...')diff --git a/examples/browser/stealth.py b/examples/browser/stealth.pyindex 73ac7366a..e7afd8bc6 100644--- a/examples/browser/stealth.py+++ b/examples/browser/stealth.py@@ -43,7 +43,7 @@ async def main():await asyncio.sleep(5)await (await normal_browser_session.get_current_page()).screenshot(path='normal_browser.png')imgcat(Path('normal_browser.png').read_bytes(), height=max(terminal_height - 15, 40))- await normal_browser_session.close()+ await normal_browser_session.kill()print('\n\nPATCHRIGHT STEALTH BROWSER:')patchright_browser_session = BrowserSession(@@ -62,7 +62,7 @@ async def main():await asyncio.sleep(5)await (await patchright_browser_session.get_current_page()).screenshot(path='patchright_browser.png')imgcat(Path('patchright_browser.png').read_bytes(), height=max(terminal_height - 15, 40))- await patchright_browser_session.close()+ await patchright_browser_session.kill()# Brave Browserif Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():@@ -81,7 +81,7 @@ async def main():await asyncio.sleep(5)await (await brave_browser_session.get_current_page()).screenshot(path='brave_browser.png')imgcat(Path('brave_browser.png').read_bytes(), height=max(terminal_height - 15, 40))- await brave_browser_session.close()+ await brave_browser_session.kill()if Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():print('\n\nBRAVE + PATCHRIGHT STEALTH BROWSER:')@@ -103,7 +103,7 @@ async def main():imgcat(Path('brave_patchright_browser.png').read_bytes(), height=max(terminal_height - 15, 40))input('Press [Enter] to close the browser...')- await brave_patchright_browser_session.close()+ await brave_patchright_browser_session.kill()# print()# agent = Agent(diff --git a/examples/browser/using_cdp.py b/examples/browser/using_cdp.pyindex fe090bcef..773c6c3ff 100644--- a/examples/browser/using_cdp.py+++ b/examples/browser/using_cdp.py@@ -53,7 +53,7 @@ async def main():)await agent.run()- await browser_session.close()+ await browser_session.kill()input('Press Enter to close...')diff --git a/examples/browser/window_sizing.py b/examples/browser/window_sizing.pyindex 58a14c12c..d5acb2249 100644--- a/examples/browser/window_sizing.py+++ b/examples/browser/window_sizing.py@@ -77,7 +77,7 @@ async def example_custom_window_size():finally:# Close resourcesif browser_session:- await browser_session.stop()+ await browser_session.kill()async def example_no_viewport_option():@@ -120,7 +120,7 @@ async def example_no_viewport_option():finally:if browser_session:- await browser_session.stop()+ await browser_session.kill()def validate_window_size(configured: dict[str, Any], actual: dict[str, Any]) -> None:diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.pyindex f7a7ef41b..34a255035 100644--- a/examples/custom-functions/action_filters.py+++ b/examples/custom-functions/action_filters.py@@ -86,7 +86,7 @@ async def main():await agent.run(max_steps=10)# Cleanup- await browser_session.stop()+ await browser_session.kill()if __name__ == '__main__':diff --git a/examples/custom-functions/clipboard.py b/examples/custom-functions/clipboard.pyindex 33e1d615d..1fa9120b0 100644--- a/examples/custom-functions/clipboard.py+++ b/examples/custom-functions/clipboard.py@@ -50,7 +50,7 @@ async def main():)await agent.run()- await browser_session.stop()+ await browser_session.kill()input('Press Enter to close...')diff --git a/examples/custom-functions/cua.py b/examples/custom-functions/cua.pyindex 2a1f38011..09ab2a023 100644--- a/examples/custom-functions/cua.py+++ b/examples/custom-functions/cua.py@@ -253,7 +253,7 @@ async def main():finally:# Clean up browser session- await browser_session.close()+ await browser_session.kill()print('\nπ§Ή Browser session closed')diff --git a/examples/features/cross_origin_iframes.py b/examples/features/cross_origin_iframes.pyindex abdd9190c..bc03c4423 100644--- a/examples/features/cross_origin_iframes.py+++ b/examples/features/cross_origin_iframes.py@@ -38,7 +38,7 @@ async def main():)await agent.run()- await browser_session.close()+ await browser_session.kill()input('Press Enter to close...')diff --git a/examples/features/custom_user_agent.py b/examples/features/custom_user_agent.pyindex 82790a5e3..9182efc29 100644--- a/examples/features/custom_user_agent.py+++ b/examples/features/custom_user_agent.py@@ -67,7 +67,7 @@ async def main():await agent.run(max_steps=25)input('Press Enter to close the browser...')- await browser_session.close()+ await browser_session.kill()asyncio.run(main())diff --git a/examples/features/restrict_urls.py b/examples/features/restrict_urls.pyindex 9269cc38f..f995097f3 100644--- a/examples/features/restrict_urls.py+++ b/examples/features/restrict_urls.py@@ -38,7 +38,7 @@ async def main():await agent.run(max_steps=25)input('Press Enter to close the browser...')- await browser_session.close()+ await browser_session.kill()asyncio.run(main())diff --git a/examples/ui/command_line.py b/examples/ui/command_line.pyindex cc2efa33c..7e081832a 100644--- a/examples/ui/command_line.py+++ b/examples/ui/command_line.py@@ -91,7 +91,7 @@ async def main():await agent.run(max_steps=25)input('Press Enter to close the browser...')- await browser_session.close()+ await browser_session.kill()if __name__ == '__main__':diff --git a/examples/ui/streamlit_demo.py b/examples/ui/streamlit_demo.pyindex 4d85792b9..05bd073a8 100644--- a/examples/ui/streamlit_demo.py+++ b/examples/ui/streamlit_demo.py@@ -84,4 +84,4 @@ if st.button('Run Agent'):asyncio.run(run_agent())- st.button('Close Browser', on_click=lambda: asyncio.run(browser_session.close()))+ st.button('Close Browser', on_click=lambda: asyncio.run(browser_session.kill()))diff --git a/examples/use-cases/shopping.py b/examples/use-cases/shopping.pyindex fda19db13..a2c12fd3a 100644--- a/examples/use-cases/shopping.py+++ b/examples/use-cases/shopping.py@@ -121,7 +121,7 @@ agent = Agent(async def main():await agent.run()input('Press Enter to close the browser...')- await browser_session.close()+ await browser_session.kill()if __name__ == '__main__':diff --git a/pyproject.toml b/pyproject.tomlindex 60f2adc52..6bfe1305f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -124,7 +124,7 @@ skip-magic-trailing-comma = false[tool.pyright]typeCheckingMode = "basic"-exclude = [".venv/", ".git/", "__pycache__/", "./test_*.py", "./debug_*.py", "private_example/", "debug/*", "tests/scripts/*", "tests/old/*"]+exclude = [".venv/", ".git/", "__pycache__/", "./test_*.py", "./debug_*.py", "private_example/", "debug/*", "tests/scripts/*", "tests/old/*", "browser_use/dom/playground/*"]venvPath = "."venv = ".venv"diff --git a/tests/ci/test_aria_menu_dropdown.py b/tests/ci/test_aria_menu_dropdown.pyindex 7c222771c..f70944909 100644--- a/tests/ci/test_aria_menu_dropdown.py+++ b/tests/ci/test_aria_menu_dropdown.py@@ -272,8 +272,13 @@ class TestARIAMenuDropdown:assert 'selected option' in result.extracted_content.lower() or 'clicked' in result.extracted_content.lower()assert 'Filter' in result.extracted_content- # Verify the click actually had an effect on the page- result_text = await page.evaluate("document.getElementById('result').textContent")+ # Verify the click actually had an effect on the page using CDP+ cdp_session = await session.attach_cdp_session()+ result = await cdp_session.cdp_client.send.Runtime.evaluate(+ params={'expression': "document.getElementById('result').textContent", 'returnByValue': True},+ session_id=cdp_session.session_id+ )+ result_text = result.get('result', {}).get('value', '')assert 'Filter' in result_text, f"Expected 'Filter' in result text, got '{result_text}'"async def test_get_dropdown_options_with_nested_aria_menu(self, controller, browser_session: BrowserSession, base_url):diff --git a/tests/ci/test_browser_session_crashed_page_recovery.py b/tests/ci/test_browser_session_crashed_page_recovery.pyindex 528e6e9e3..576b49217 100644--- a/tests/ci/test_browser_session_crashed_page_recovery.py+++ b/tests/ci/test_browser_session_crashed_page_recovery.py@@ -488,8 +488,8 @@ class TestBrowserSessionRecovery:from browser_use.browser.events import NavigateToUrlEventevent = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=httpserver.url_for('/normal')))await event- page2 = await browser_session.get_current_page()- assert 'normal' in page2.url+ url2 = await browser_session.get_current_page_url()+ assert 'normal' in url2async def test_browser_crash_throws_hard_error_no_restart(self, browser_session: BrowserSession):"""Test that browser crashes throw hard errors instead of restarting the browser"""diff --git a/tests/ci/test_browser_session_downloads_simple.py b/tests/ci/test_browser_session_downloads_simple.pyindex c99c4040f..384baf26f 100644--- a/tests/ci/test_browser_session_downloads_simple.py+++ b/tests/ci/test_browser_session_downloads_simple.py@@ -101,7 +101,8 @@ async def test_browser_use_download_with_http_server(http_server):)await browser_session.start()- page = await browser_session.get_current_page()+ # Cannot get page directly - need to use events+ # page = await browser_session.get_current_page() - removed# Create HTML page with download link pointing to HTTP serverbase_url = f'http://{http_server.host}:{http_server.port}'@@ -114,14 +115,29 @@ async def test_browser_use_download_with_http_server(http_server):</body></html>"""-- await page.set_content(html_content)++ # Set content using CDP+ cdp_session = await session.attach_cdp_session()+ await cdp_session.cdp_client.send.Page.setDocumentContent(+ params={'frameId': cdp_session.cdp_client.page_frame_id, 'html': html_content},+ session_id=cdp_session.session_id+ )# Wait a moment for DOM to be readyawait asyncio.sleep(0.5)- # Click the download link and let the DownloadsWatchdog handle it completely- await page.click('#download-link')+ # Click the download link using events+ state = await session.get_browser_state_summary()+ download_link = None+ for idx, element in state.dom_state.selector_map.items():+ if element.attributes.get('id') == 'download-link':+ download_link = element+ break++ assert download_link is not None, "Download link not found"+ from browser_use.browser.events import ClickElementEvent+ click_event = session.event_bus.dispatch(ClickElementEvent(node=download_link))+ await click_event# Wait for the DownloadsWatchdog to process the download by expecting the FileDownloadedEventfrom browser_use.browser.events import FileDownloadedEventdiff --git a/tests/ci/test_browser_session_file_uploads.py b/tests/ci/test_browser_session_file_uploads.pyindex 1f3194a4d..d028ace87 100644--- a/tests/ci/test_browser_session_file_uploads.py+++ b/tests/ci/test_browser_session_file_uploads.py@@ -97,11 +97,12 @@ class TestBrowserSessionFileUploads:test_server.expect_request('/upload').respond_with_data(html, content_type='text/html')await browser_session.start()- page = await browser_session.get_current_page()- await page.goto(test_server.url_for('/upload'))-+ # Navigate to upload page using event+ from browser_use.browser.events import NavigateToUrlEvent, NavigationCompleteEvent+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/upload')))+ await event# Wait for page to load- await page.wait_for_load_state('networkidle')+ await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)# Get browser state to populate selector mapawait browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)@@ -204,9 +205,12 @@ class TestBrowserSessionFileUploads:test_server.expect_request('/traversal').respond_with_data(html, content_type='text/html')await browser_session.start()- page = await browser_session.get_current_page()- await page.goto(test_server.url_for('/traversal'))- await page.wait_for_load_state('networkidle')+ # Navigate to traversal page using event+ from browser_use.browser.events import NavigateToUrlEvent, NavigationCompleteEvent+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/traversal')))+ await event+ # Wait for page to load+ await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)# Get browser state to populate selector mapawait browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)@@ -268,9 +272,12 @@ class TestBrowserSessionFileUploads:test_server.expect_request('/limits').respond_with_data(html, content_type='text/html')await browser_session.start()- page = await browser_session.get_current_page()- await page.goto(test_server.url_for('/limits'))- await page.wait_for_load_state('networkidle')+ # Navigate to limits page using event+ from browser_use.browser.events import NavigateToUrlEvent, NavigationCompleteEvent+ event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url=test_server.url_for('/limits')))+ await event+ # Wait for page to load+ await browser_session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)# Get browser state to populate selector mapawait browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)diff --git a/tests/ci/test_browser_session_tab_management.py b/tests/ci/test_browser_session_tab_management.pyindex 56d36584b..6e20dc953 100644--- a/tests/ci/test_browser_session_tab_management.py+++ b/tests/ci/test_browser_session_tab_management.py@@ -263,8 +263,8 @@ class TestTabManagement:second_tab = await browser_session.create_new_tab(f'{base_url}/page2')# Verify the second tab is now active- current_page = await browser_session.get_current_page()- assert current_page.url == second_tab.url == f'{base_url}/page2'+ current_url = await browser_session.get_current_page_url()+ assert current_url == f'{base_url}/page2'# Close the second tab by closing the page directlyawait second_tab.close()@@ -302,10 +302,11 @@ class TestTabManagement:assert browser_session._browser_context is None# This should trigger reinitialization- page = await browser_session.get_current_page()+ # Verify by getting URL+ current_url = await browser_session.get_current_page_url()# Verify state is consistent with a new context- assert page is not None+ assert current_url is not Noneassert browser_session._browser_context is not Noneassert browser_session._browser_context != original_contextassert (await browser_session.is_connected()) is True@@ -380,16 +381,16 @@ class TestEventDrivenTabOperations:await switch_event# Verify the switch worked- current_page = await browser_session.get_current_page()- assert f'{base_url}/page1' in current_page.url+ current_url = await browser_session.get_current_page_url()+ assert f'{base_url}/page1' in current_url# Switch to tab 2 via direct eventswitch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=2))await switch_event# Verify the switch worked- current_page = await browser_session.get_current_page()- assert f'{base_url}/page3' in current_page.url+ current_url = await browser_session.get_current_page_url()+ assert f'{base_url}/page3' in current_urlasync def test_close_tab_event_dispatching(self, browser_session, base_url):"""Test direct CloseTabEvent dispatching."""@@ -429,8 +430,8 @@ class TestEventDrivenTabOperations:assert len(browser_session.tabs) == initial_tab_count + 1# Check that current page is the new tab- current_page = await browser_session.get_current_page()- assert f'{base_url}/page2' in current_page.url+ current_url = await browser_session.get_current_page_url()+ assert f'{base_url}/page2' in current_url# Check event history for TabCreatedEventevent_history = list(browser_session.event_bus.event_history.values())@@ -461,5 +462,5 @@ class TestEventDrivenTabOperations:await asyncio.gather(switch_event1, switch_event2)# Final state should be deterministic (last switch wins)- current_page = await browser_session.get_current_page()- assert current_page is not None+ current_url = await browser_session.get_current_page_url()+ assert current_url is not Nonediff --git a/tests/ci/test_browser_session_viewport_and_proxy.py b/tests/ci/test_browser_session_viewport_and_proxy.pyindex bdbfc9690..678929e81 100644--- a/tests/ci/test_browser_session_viewport_and_proxy.py+++ b/tests/ci/test_browser_session_viewport_and_proxy.py@@ -42,12 +42,13 @@ async def test_window_size_with_real_browser():))await browser_session.start()- page = await browser_session.get_current_page()- assert page is not None, 'Failed to get current page'+ # Use CDP to evaluate JavaScript+ cdp_session = await browser_session.get_or_create_cdp_session()# Get the context configuration used for browser window size- video_size = await page.evaluate("""- () => {+ result = await cdp_session.cdp_client.send.Runtime.evaluate(+ params={+ 'expression': """(() => {// This returns information about the context recording settings// which should match our configured video size (browser_window_size)try {@@ -63,18 +64,27 @@ async def test_window_size_with_real_browser():width: window.innerWidth,height: window.innerHeight};- }- """)+ })()""",+ 'returnByValue': True+ },+ session_id=cdp_session.session_id+ )+ video_size = result.get('result', {}).get('value', {})# Let's also check the viewport size- actual_size = await page.evaluate("""- () => {+ result2 = await cdp_session.cdp_client.send.Runtime.evaluate(+ params={+ 'expression': """(() => {return {width: window.innerWidth,height: window.innerHeight}- }- """)+ })()""",+ 'returnByValue': True+ },+ session_id=cdp_session.session_id+ )+ actual_size = result2.get('result', {}).get('value', {})print(f'Browser configured window_size={browser_session.browser_profile.window_size}')print(f'Browser configured viewport_size: {browser_session.browser_profile.viewport}')diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.pyindex 75dc99cdd..c18a5382c 100644--- a/tests/ci/test_controller.py+++ b/tests/ci/test_controller.py@@ -114,11 +114,37 @@ class TestControllerIntegration:assert result.extracted_content is not Noneassert f'Navigated to {base_url}' in result.extracted_content- async def test_scroll_actions(self, controller, browser_session, base_url):- """Test basic scroll action functionality without complex HTML."""+ async def test_scroll_actions(self, controller, browser_session, base_url, http_server):+ """Test basic scroll action functionality."""++ # Add a page with scrollable content+ http_server.expect_request('/scrollable').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head>+ <title>Scrollable Page</title>+ <style>+ body { margin: 0; padding: 20px; }+ .content { height: 3000px; background: linear-gradient(to bottom, #f0f0f0, #333); }+ .marker { padding: 20px; background: #007bff; color: white; margin: 500px 0; }+ </style>+ </head>+ <body>+ <h1>Scrollable Test Page</h1>+ <div class="content">+ <div class="marker" id="marker1">Marker 1</div>+ <div class="marker" id="marker2">Marker 2</div>+ <div class="marker" id="marker3">Marker 3</div>+ </div>+ </body>+ </html>+ """,+ content_type='text/html',+ )- # Navigate to any simple page- goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/page1', new_tab=False)}+ # Navigate to scrollable page+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/scrollable', new_tab=False)}class GoToUrlActionModel(ActionModel):go_to_url: GoToUrlAction | None = None@@ -133,30 +159,32 @@ class TestControllerIntegration:result = await controller.act(ScrollActionModel(**scroll_action), browser_session)- # Basic assertions that will always pass+ # Verify scroll down succeededassert isinstance(result, ActionResult)+ assert result.error is None, f"Scroll down failed: {result.error}"assert result.extracted_content is not None- assert 'Scrolled' in result.extracted_content+ assert 'Scrolled down' in result.extracted_content+ assert 'the page' in result.extracted_contentassert result.include_in_memory is True- assert result.error is None# Test 2: Basic page scroll upscroll_up_action = {'scroll': ScrollAction(down=False, num_pages=0.5)}result = await controller.act(ScrollActionModel(**scroll_up_action), browser_session)assert isinstance(result, ActionResult)+ assert result.error is None, f"Scroll up failed: {result.error}"assert result.extracted_content is not None- assert 'Scrolled' in result.extracted_content- assert result.error is None+ assert 'Scrolled up' in result.extracted_content+ assert '0.5 pages' in result.extracted_content- # Test 3: Invalid index should give an error+ # Test 3: Test with invalid element index (should error)invalid_scroll_action = {'scroll': ScrollAction(down=True, num_pages=1.0, index=999)}result = await controller.act(ScrollActionModel(**invalid_scroll_action), browser_session)# This should fail with error about element not foundassert isinstance(result, ActionResult)- assert result.error is not None- assert 'Element index 999 not found' in result.error+ assert result.error is not None, "Expected error for invalid element index"+ assert 'Element index 999 not found' in result.error or 'Failed to scroll' in result.error# Test 4: Model parameter validationscroll_with_index = ScrollAction(down=True, num_pages=1.0, index=5)diff --git a/tests/ci/test_navigation_events.py b/tests/ci/test_navigation_events.pyindex c1b407504..51b8c627b 100644--- a/tests/ci/test_navigation_events.py+++ b/tests/ci/test_navigation_events.py@@ -222,7 +222,8 @@ async def test_navigation_events_history_pushstate(httpserver):for idx, element in state.selector_map.items():if hasattr(element, 'attributes') and element.attributes.get('id') == 'push-btn':push_button_found = True- session.event_bus.dispatch(ClickElementEvent(index=idx))+ click_element = await session.get_dom_element_by_index(idx)+ session.event_bus.dispatch(ClickElementEvent(node=click_element))breakassert push_button_found, 'Should find push state button'@@ -240,7 +241,8 @@ async def test_navigation_events_history_pushstate(httpserver):for idx, element in state.selector_map.items():if hasattr(element, 'attributes') and element.attributes.get('id') == 'same-tab-link':same_tab_link_found = True- session.event_bus.dispatch(ClickElementEvent(index=idx))+ click_element = await session.get_dom_element_by_index(idx)+ session.event_bus.dispatch(ClickElementEvent(node=click_element))breakassert same_tab_link_found, 'Should find same tab link'@@ -269,7 +271,8 @@ async def test_navigation_events_history_pushstate(httpserver):if hasattr(element, 'attributes') and element.attributes.get('id') == 'new-tab-link':new_tab_link_found = True# Use new_tab=True parameter to properly trigger new tab behavior- session.event_bus.dispatch(ClickElementEvent(index=idx, new_tab=True))+ click_element = await session.get_dom_element_by_index(idx)+ session.event_bus.dispatch(ClickElementEvent(node=click_element, new_tab=True))breakif new_tab_link_found:@@ -364,7 +367,8 @@ async def test_navigation_events_link_clicks(httpserver):for idx, element in state.selector_map.items():if hasattr(element, 'attributes') and element.attributes.get('id') == 'same-tab-link':same_tab_link_found = True- session.event_bus.dispatch(ClickElementEvent(index=idx))+ click_element = await session.get_dom_element_by_index(idx)+ session.event_bus.dispatch(ClickElementEvent(node=click_element))breakassert same_tab_link_found, 'Should find same tab link'@@ -392,7 +396,8 @@ async def test_navigation_events_link_clicks(httpserver):for idx, element in state.selector_map.items():if hasattr(element, 'attributes') and element.attributes.get('id') == 'new-tab-link':new_tab_link_found = True- session.event_bus.dispatch(ClickElementEvent(index=idx, new_tab=True))+ click_element = await session.get_dom_element_by_index(idx)+ session.event_bus.dispatch(ClickElementEvent(node=click_element, new_tab=True))breakif new_tab_link_found:@@ -419,7 +424,8 @@ async def test_navigation_events_link_clicks(httpserver):for idx, element in state.selector_map.items():if hasattr(element, 'attributes') and element.attributes.get('id') == 'js-navigation':js_link_found = True- session.event_bus.dispatch(ClickElementEvent(index=idx))+ click_element = await session.get_dom_element_by_index(idx)+ session.event_bus.dispatch(ClickElementEvent(node=click_element))breakif js_link_found:diff --git a/tests/ci/test_storage_state_watchdog.py b/tests/ci/test_storage_state_watchdog.pyindex 8d17d22ec..a650e487f 100644--- a/tests/ci/test_storage_state_watchdog.py+++ b/tests/ci/test_storage_state_watchdog.py@@ -80,7 +80,9 @@ async def test_storage_state_watchdog_save_event():await session.event_bus.expect(BrowserConnectedEvent, timeout=5.0)# Navigate to create some context- await session.navigate('data:text/html,<h1>Test Page</h1>')+ from browser_use.browser.events import NavigateToUrlEvent+ nav_event = session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>Test Page</h1>'))+ await nav_event# Dispatch SaveStorageStateEventsave_event = session.event_bus.dispatch(SaveStorageStateEvent())@@ -159,7 +161,7 @@ async def test_storage_state_watchdog_load_event():# Get the current target to get cookies fromtarget_info = await session.get_current_target_info()if target_info:- cdp_session = await session.attach_cdp_session(target_info.target_id)+ cdp_session = await session.get_or_create_cdp_session(target_info['targetId'])result = await cdp_session.cdp_client.send.Storage.getCookies(session_id=cdp_session.session_id)cookies = result.get('cookies', [])# Should have at least the test cookie