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
wip
Nick Sweeting46dd9bd584ab
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.pyindex 8ab77d81a..b75531b5b 100644--- a/browser_use/browser/default_action_watchdog.py+++ b/browser_use/browser/default_action_watchdog.py@@ -29,7 +29,7 @@ if TYPE_CHECKING:class DefaultActionWatchdog(BaseWatchdog):"""Handles default browser actions like click, type, and scroll using CDP."""- async def on_ClickElementEvent(self, event: ClickElementEvent) -> None:+ async def on_ClickElementEvent(self, event: ClickElementEvent) -> dict[str, str] | None:"""Handle click request with CDP."""page = await self.browser_session.get_current_page()try:@@ -45,7 +45,7 @@ class DefaultActionWatchdog(BaseWatchdog):index_for_logging = event.index# Track initial number of tabs to detect new tab opening- initial_pages = len(self.browser_session.pages)+ initial_target_ids = await self.browser_session.target_ids# Check if element is a file input (should not be clicked)if self.browser_session.is_file_input(element_node):@@ -75,13 +75,19 @@ class DefaultActionWatchdog(BaseWatchdog):logger.debug(f'Element xpath: {element_node.xpath}')# Check if a new tab was opened- if len(self.browser_session.pages) > initial_pages:+ current_target_ids = await self.browser_session.target_ids+ if len(current_target_ids) > len(initial_target_ids):new_tab_msg = 'New tab opened - switching to it'msg += f' - {new_tab_msg}'logger.info(f'π {new_tab_msg}')# Switch to the last tab (newly created tab)- last_tab_index = len(self.browser_session.pages) - 1- await self.browser_session.switch_to_tab(last_tab_index)+ new_target_id = current_target_ids[-1]+ await self.browser_session._cdp_activate_page(new_target_id)+ self.browser_session.current_target_id = new_target_id++ # Return download_path if any+ if download_path:+ return {'download_path': download_path}except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pynew file mode 100644index 000000000..ebc4fcdf1--- /dev/null+++ b/browser_use/browser/dom_watchdog.py@@ -0,0 +1,633 @@+"""DOM watchdog for browser DOM tree management using CDP."""++import asyncio+import logging+import time+from typing import TYPE_CHECKING, Any++import httpx+from cdp_use import CDPClient+from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns+from cdp_use.cdp.accessibility.types import AXNode+from cdp_use.cdp.dom.types import Node+from cdp_use.cdp.target.types import TargetInfo+from pydantic import Field++from browser_use.browser.events import BrowserErrorEvent, BuildDOMTreeEvent+from browser_use.browser.watchdog_base import BaseWatchdog+from browser_use.dom.enhanced_snapshot import (+ REQUIRED_COMPUTED_STYLES,+ build_snapshot_lookup,+)+from browser_use.dom.serializer.serializer import DOMTreeSerializer+from browser_use.dom.views import (+ CurrentPageTargets,+ DOMRect,+ EnhancedAXNode,+ EnhancedAXProperty,+ EnhancedDOMTreeNode,+ NodeType,+ SerializedDOMState,+ TargetAllTrees,+)+from browser_use.utils import logger++if TYPE_CHECKING:+ from browser_use.browser.session import BrowserSession+ from browser_use.browser.types import Page+++# TODO: enable cross origin iframes -> experimental for now+ENABLE_CROSS_ORIGIN_IFRAMES = False+++class DOMWatchdog(BaseWatchdog):+ """Handles DOM tree building, serialization, and element access via CDP."""++ LISTENS_TO = [BuildDOMTreeEvent]+ EMITS = [BrowserErrorEvent]++ # Public properties for other watchdogs+ selector_map: dict[int, EnhancedDOMTreeNode] | None = None+ uuid_selector_map: dict[str, EnhancedDOMTreeNode] | None = None+ current_dom_state: SerializedDOMState | None = None+ enhanced_dom_tree: EnhancedDOMTreeNode | None = None++ # Internal CDP management+ cdp_client: CDPClient | None = None+ session_id_domains_enabled_cache: dict[str, bool] = Field(default_factory=dict)++ async def attach_to_session(self) -> None:+ """Attach watchdog to browser session and initialize CDP client."""+ await super().attach_to_session()+ # CDP client will be initialized on first use++ async def on_BuildDOMTreeEvent(self, event: BuildDOMTreeEvent) -> SerializedDOMState:+ """Build and serialize DOM tree, returning ready-to-use LLM format.++ Updates public properties:+ - self.selector_map: Index to node mapping for element access+ - self.uuid_selector_map: UUID to node mapping for element access+ - self.current_dom_state: Cached serialized state+ - self.enhanced_dom_tree: Full enhanced DOM tree++ Returns:+ SerializedDOMState with serialized DOM and selector map+ """+ try:+ page = await self.browser_session.get_current_page()++ # Get current page targets+ targets = await self._get_targets_for_current_page()++ # Build enhanced DOM tree+ self.enhanced_dom_tree = await self._get_dom_tree(targets.page_session)++ # Serialize for LLM+ start = time.time()+ self.current_dom_state, serializer_timing = DOMTreeSerializer(+ self.enhanced_dom_tree,+ event.previous_state+ ).serialize_accessible_elements()+ end = time.time()++ logger.debug(f'Time taken to serialize dom tree: {end - start} seconds')++ # Update selector map for other watchdogs+ self.selector_map = self.current_dom_state.selector_map++ # Build UUID selector map+ self.uuid_selector_map = {}+ if self.selector_map:+ for node in self.selector_map.values():+ self.uuid_selector_map[node.uuid] = node++ return self.current_dom_state++ except Exception as e:+ logger.error(f'Failed to build DOM tree: {e}')+ self.event_bus.dispatch(+ BrowserErrorEvent(+ error_type='DOMBuildFailed',+ message=str(e),+ )+ )+ raise++ # ========== Public Helper Methods ==========++ async def get_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:+ """Get DOM element by index from cached selector map.++ Builds DOM if not cached.++ Returns:+ EnhancedDOMTreeNode or None if index not found+ """+ if not self.selector_map:+ # Build DOM if not cached+ result = await self.event_bus.dispatch(BuildDOMTreeEvent())+ await result++ return self.selector_map.get(index) if self.selector_map else None++ async def get_element_by_uuid(self, uuid: str) -> EnhancedDOMTreeNode | None:+ """Get DOM element by UUID from cached selector map.++ Builds DOM if not cached.++ Returns:+ EnhancedDOMTreeNode or None if UUID not found+ """+ if not self.uuid_selector_map:+ # Build DOM if not cached+ result = await self.event_bus.dispatch(BuildDOMTreeEvent())+ await result++ return self.uuid_selector_map.get(uuid) if self.uuid_selector_map else None++ def clear_cache(self) -> None:+ """Clear cached DOM state to force rebuild on next access."""+ self.selector_map = None+ self.uuid_selector_map = None+ self.current_dom_state = None+ self.enhanced_dom_tree = None++ def is_file_input(self, element: EnhancedDOMTreeNode) -> bool:+ """Check if element is a file input."""+ return (+ element.node_name.upper() == 'INPUT'+ and element.attributes.get('type', '').lower() == 'file'+ )++ @staticmethod+ def is_element_visible_according_to_all_parents(+ node: EnhancedDOMTreeNode, html_frames: list[EnhancedDOMTreeNode]+ ) -> bool:+ """Check if the element is visible according to all its parent HTML frames."""++ if not node.snapshot_node:+ return False++ computed_styles = node.snapshot_node.computed_styles or {}++ display = computed_styles.get('display', '').lower()+ visibility = computed_styles.get('visibility', '').lower()+ opacity = computed_styles.get('opacity', '1')++ if display == 'none' or visibility == 'hidden':+ return False++ try:+ if float(opacity) <= 0:+ return False+ except (ValueError, TypeError):+ pass++ # Start with the element's local bounds (in its own frame's coordinate system)+ current_bounds = node.snapshot_node.bounds++ if not current_bounds:+ return False # If there are no bounds, the element is not visible++ """+ Reverse iterate through the html frames (that can be either iframe or document -> if it's a document frame compare if the current bounds interest with it (taking scroll into account) otherwise move the current bounds by the iframe offset)+ """+ for frame in reversed(html_frames):+ if (+ frame.node_type == NodeType.ELEMENT_NODE+ and frame.node_name.upper() == 'IFRAME'+ and frame.snapshot_node+ and frame.snapshot_node.bounds+ ):+ iframe_bounds = frame.snapshot_node.bounds++ current_bounds.x += iframe_bounds.x+ current_bounds.y += iframe_bounds.y++ if (+ frame.node_type == NodeType.ELEMENT_NODE+ and frame.node_name == 'HTML'+ and frame.snapshot_node+ and frame.snapshot_node.scrollRects+ and frame.snapshot_node.clientRects+ ):+ frame_left = frame.snapshot_node.scrollRects.x+ frame_top = frame.snapshot_node.scrollRects.y+ frame_right = frame.snapshot_node.scrollRects.x + frame.snapshot_node.clientRects.width+ frame_bottom = frame.snapshot_node.scrollRects.y + frame.snapshot_node.clientRects.height++ frame_intersects = (+ current_bounds.x < frame_right+ and current_bounds.x + current_bounds.width > frame_left+ and current_bounds.y < frame_bottom+ and current_bounds.y + current_bounds.height > frame_top+ )++ if not frame_intersects:+ return False++ # If we reach here, element is visible in main viewport and all containing iframes+ return True++ # ========== Private CDP Methods ==========++ async def _get_cdp_client(self) -> CDPClient:+ """Get or create CDP client."""+ if self.cdp_client is not None:+ return self.cdp_client++ if not self.browser_session.cdp_url:+ raise ValueError('CDP URL is not set')++ # If the cdp_url is already a websocket URL, use it as-is.+ if self.browser_session.cdp_url.startswith('ws'):+ ws_url = self.browser_session.cdp_url+ else:+ # Otherwise, treat it as the DevTools HTTP root and fetch the websocket URL.+ url = self.browser_session.cdp_url.rstrip('/')+ if not url.endswith('/json/version'):+ url = url + '/json/version'+ async with httpx.AsyncClient() as client:+ version_info = await client.get(url)+ ws_url = version_info.json()['webSocketDebuggerUrl']++ self.cdp_client = CDPClient(ws_url)+ await self.cdp_client.start()++ return self.cdp_client++ async def _get_targets_for_current_page(self) -> CurrentPageTargets:+ """Get the target ID for a playwright page."""+ page = await self.browser_session.get_current_page()+ cdp_client = await self._get_cdp_client()+ targets = await cdp_client.send.Target.getTargets()++ # Find main page target+ main_target = next((t for t in targets['targetInfos'] if t['type'] == 'page' and t['url'] == page.url), None)++ if not main_target:+ raise ValueError(f'No main page target found for URL: {page.url}')++ # Separate iframe targets for attachment+ iframe_targets = [t for t in targets['targetInfos'] if t['type'] == 'iframe']++ return CurrentPageTargets(+ page_session=main_target,+ iframe_sessions=iframe_targets,+ )++ async def _attach_target_activate_domains_get_session_id(self, target: TargetInfo) -> str:+ """Attach to target and activate required CDP domains."""+ cdp_client = await self._get_cdp_client()+ target_id = str(target['targetId'])++ session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})+ session_id = session['sessionId']++ await self._enable_all_domains_on_session(session_id)++ return session_id++ async def _enable_all_domains_on_session(self, session_id: str) -> None:+ """Enable required CDP domains on session."""+ if session_id in self.session_id_domains_enabled_cache:+ return++ cdp_client = await self._get_cdp_client()++ await cdp_client.send.Target.setAutoAttach(+ params={+ 'autoAttach': True,+ 'waitForDebuggerOnStart': False,+ 'flatten': True,+ },+ session_id=session_id,+ )++ await asyncio.gather(+ cdp_client.send.DOM.enable(session_id=session_id),+ cdp_client.send.Accessibility.enable(session_id=session_id),+ cdp_client.send.DOMSnapshot.enable(session_id=session_id),+ cdp_client.send.Page.enable(session_id=session_id),+ )++ self.session_id_domains_enabled_cache[session_id] = True++ def _build_enhanced_ax_node(self, ax_node: AXNode) -> EnhancedAXNode:+ """Build enhanced accessibility node from CDP AX node."""+ properties: list[EnhancedAXProperty] | None = None+ if 'properties' in ax_node and ax_node['properties']:+ properties = []+ for property in ax_node['properties']:+ try:+ # test whether property name can go into the enum (sometimes Chrome returns some random properties)+ properties.append(+ EnhancedAXProperty(+ name=property['name'],+ value=property.get('value', {}).get('value', None),+ )+ )+ except ValueError:+ pass++ enhanced_ax_node = EnhancedAXNode(+ ax_node_id=ax_node['nodeId'],+ ignored=ax_node['ignored'],+ role=ax_node.get('role', {}).get('value', None),+ name=ax_node.get('name', {}).get('value', None),+ description=ax_node.get('description', {}).get('value', None),+ properties=properties,+ )+ return enhanced_ax_node++ async def _get_viewport_ratio(self, session_id: str) -> float:+ """Get viewport dimensions, device pixel ratio, and scroll position using CDP."""+ try:+ cdp_client = await self._get_cdp_client()++ # Get the layout metrics which includes the visual viewport+ metrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)++ visual_viewport = metrics.get('visualViewport', {})++ # IMPORTANT: Use CSS viewport instead of device pixel viewport+ # This fixes the coordinate mismatch on high-DPI displays+ css_visual_viewport = metrics.get('cssVisualViewport', {})+ css_layout_viewport = metrics.get('cssLayoutViewport', {})++ # Use CSS pixels (what JavaScript sees) instead of device pixels+ width = css_visual_viewport.get('clientWidth', css_layout_viewport.get('clientWidth', 1920.0))++ # Calculate device pixel ratio+ device_width = visual_viewport.get('clientWidth', width)+ css_width = css_visual_viewport.get('clientWidth', width)+ device_pixel_ratio = device_width / css_width if css_width > 0 else 1.0++ return float(device_pixel_ratio)+ except Exception as e:+ logger.warning(f'Viewport size detection failed: {e}')+ # Fallback to default viewport size+ return 1.0++ async def _get_ax_tree_for_all_frames(self, session_id: str) -> GetFullAXTreeReturns:+ """Recursively collect all frames and merge their accessibility trees into a single array."""+ cdp_client = await self._get_cdp_client()+ frame_tree = await cdp_client.send.Page.getFrameTree(session_id=session_id)++ def collect_all_frame_ids(frame_tree_node) -> list[str]:+ """Recursively collect all frame IDs from the frame tree."""+ frame_ids = [frame_tree_node['frame']['id']]++ if 'childFrames' in frame_tree_node and frame_tree_node['childFrames']:+ for child_frame in frame_tree_node['childFrames']:+ frame_ids.extend(collect_all_frame_ids(child_frame))++ return frame_ids++ # Collect all frame IDs recursively+ all_frame_ids = collect_all_frame_ids(frame_tree['frameTree'])++ # Get accessibility tree for each frame+ ax_tree_requests = []+ for frame_id in all_frame_ids:+ ax_tree_request = cdp_client.send.Accessibility.getFullAXTree(params={'frameId': frame_id}, session_id=session_id)+ ax_tree_requests.append(ax_tree_request)++ # Wait for all requests to complete+ ax_trees = await asyncio.gather(*ax_tree_requests)++ # Merge all AX nodes into a single array+ merged_nodes: list[AXNode] = []+ for ax_tree in ax_trees:+ merged_nodes.extend(ax_tree['nodes'])++ return {'nodes': merged_nodes}++ async def _get_all_trees_for_session_id(self, session_id: str) -> TargetAllTrees:+ """Get all tree data for a session."""+ if not self.browser_session.cdp_url:+ raise ValueError('CDP URL is not set')++ cdp_client = await self._get_cdp_client()++ snapshot_request = cdp_client.send.DOMSnapshot.captureSnapshot(+ params={+ 'computedStyles': REQUIRED_COMPUTED_STYLES,+ 'includePaintOrder': True,+ 'includeDOMRects': True,+ 'includeBlendedBackgroundColors': False,+ 'includeTextColorOpacities': False,+ },+ session_id=session_id,+ )++ dom_tree_request = cdp_client.send.DOM.getDocument(params={'depth': -1, 'pierce': True}, session_id=session_id)+ ax_tree_request = self._get_ax_tree_for_all_frames(session_id)+ device_pixel_ratio_request = self._get_viewport_ratio(session_id)++ start = time.time()+ snapshot, dom_tree, ax_tree, device_pixel_ratio = await asyncio.gather(+ snapshot_request, dom_tree_request, ax_tree_request, device_pixel_ratio_request+ )+ end = time.time()+ cdp_timing = {'cdp_calls_total': end - start}+ logger.debug(f'Time taken to get dom tree: {end - start} seconds')++ return TargetAllTrees(+ snapshot=snapshot,+ dom_tree=dom_tree,+ ax_tree=ax_tree,+ device_pixel_ratio=device_pixel_ratio,+ cdp_timing=cdp_timing,+ )++ async def _get_dom_tree(+ self,+ target: TargetInfo,+ initial_html_frames: list[EnhancedDOMTreeNode] | None = None,+ initial_total_frame_offset: DOMRect | None = None,+ ) -> EnhancedDOMTreeNode:+ """Build enhanced DOM tree from target."""+ session_id = await self._attach_target_activate_domains_get_session_id(target)+ trees = await self._get_all_trees_for_session_id(session_id)++ dom_tree = trees.dom_tree+ ax_tree = trees.ax_tree+ snapshot = trees.snapshot+ device_pixel_ratio = trees.device_pixel_ratio++ ax_tree_lookup: dict[int, AXNode] = {+ ax_node['backendDOMNodeId']: ax_node for ax_node in ax_tree['nodes'] if 'backendDOMNodeId' in ax_node+ }++ enhanced_dom_tree_node_lookup: dict[int, EnhancedDOMTreeNode] = {}+ """ NodeId (NOT backend node id) -> enhanced dom tree node"""++ # Parse snapshot data with everything calculated upfront+ snapshot_lookup = build_snapshot_lookup(snapshot, device_pixel_ratio)++ async def _construct_enhanced_node(+ node: Node, html_frames: list[EnhancedDOMTreeNode] | None, total_frame_offset: DOMRect | None+ ) -> EnhancedDOMTreeNode:+ """+ Recursively construct enhanced DOM tree nodes.++ Args:+ node: The DOM node to construct+ html_frames: List of HTML frame nodes encountered so far+ total_frame_offset: Accumulated coordinate translation from parent iframes (includes scroll corrections)+ """+ # Initialize lists if not provided+ if html_frames is None:+ html_frames = []++ # to get rid of the pointer references+ if total_frame_offset is None:+ total_frame_offset = DOMRect(x=0.0, y=0.0, width=0.0, height=0.0)+ else:+ total_frame_offset = DOMRect(+ total_frame_offset.x, total_frame_offset.y, total_frame_offset.width, total_frame_offset.height+ )++ # memoize (I don't know if some nodes are duplicated)+ if node['nodeId'] in enhanced_dom_tree_node_lookup:+ return enhanced_dom_tree_node_lookup[node['nodeId']]++ ax_node = ax_tree_lookup.get(node['backendNodeId'])+ if ax_node:+ enhanced_ax_node = self._build_enhanced_ax_node(ax_node)+ else:+ enhanced_ax_node = None++ # To make attributes more readable+ attributes: dict[str, str] | None = None+ if 'attributes' in node and node['attributes']:+ attributes = {}+ for i in range(0, len(node['attributes']), 2):+ attributes[node['attributes'][i]] = node['attributes'][i + 1]++ shadow_root_type = None+ if 'shadowRootType' in node and node['shadowRootType']:+ try:+ shadow_root_type = node['shadowRootType']+ except ValueError:+ pass++ # Get snapshot data and calculate absolute position+ snapshot_data = snapshot_lookup.get(node['backendNodeId'], None)+ absolute_position = None+ if snapshot_data and snapshot_data.bounds:+ absolute_position = DOMRect(+ x=snapshot_data.bounds.x + total_frame_offset.x,+ y=snapshot_data.bounds.y + total_frame_offset.y,+ width=snapshot_data.bounds.width,+ height=snapshot_data.bounds.height,+ )++ dom_tree_node = EnhancedDOMTreeNode(+ node_id=node['nodeId'],+ backend_node_id=node['backendNodeId'],+ node_type=NodeType(node['nodeType']),+ node_name=node['nodeName'],+ node_value=node['nodeValue'],+ attributes=attributes or {},+ is_scrollable=node.get('isScrollable', None),+ frame_id=node.get('frameId', None),+ content_document=None,+ shadow_root_type=shadow_root_type,+ shadow_roots=None,+ parent_node=None,+ children_nodes=None,+ ax_node=enhanced_ax_node,+ snapshot_node=snapshot_data,+ is_visible=None,+ absolute_position=absolute_position,+ )++ enhanced_dom_tree_node_lookup[node['nodeId']] = dom_tree_node++ if 'parentId' in node and node['parentId']:+ dom_tree_node.parent_node = enhanced_dom_tree_node_lookup[+ node['parentId']+ ] # parents should always be in the lookup++ # Check if this is an HTML frame node and add it to the list+ updated_html_frames = html_frames.copy()+ if node['nodeType'] == NodeType.ELEMENT_NODE.value and node['nodeName'] == 'HTML' and node.get('frameId') is not None:+ updated_html_frames.append(dom_tree_node)++ # and adjust the total frame offset by scroll+ if snapshot_data and snapshot_data.scrollRects:+ total_frame_offset.x -= snapshot_data.scrollRects.x+ total_frame_offset.y -= snapshot_data.scrollRects.y++ # Calculate new iframe offset for content documents, accounting for iframe scroll+ if node['nodeName'].upper() == 'IFRAME' and snapshot_data and snapshot_data.bounds:+ if snapshot_data.bounds:+ updated_html_frames.append(dom_tree_node)++ total_frame_offset.x += snapshot_data.bounds.x+ total_frame_offset.y += snapshot_data.bounds.y++ if 'contentDocument' in node and node['contentDocument']:+ dom_tree_node.content_document = await _construct_enhanced_node(+ node['contentDocument'], updated_html_frames, total_frame_offset+ )+ dom_tree_node.content_document.parent_node = dom_tree_node++ if 'shadowRoots' in node and node['shadowRoots']:+ dom_tree_node.shadow_roots = []+ for shadow_root in node['shadowRoots']:+ shadow_root_node = await _construct_enhanced_node(shadow_root, updated_html_frames, total_frame_offset)+ shadow_root_node.parent_node = dom_tree_node+ dom_tree_node.shadow_roots.append(shadow_root_node)++ if 'children' in node and node['children']:+ dom_tree_node.children_nodes = []+ for child in node['children']:+ dom_tree_node.children_nodes.append(+ await _construct_enhanced_node(child, updated_html_frames, total_frame_offset)+ )++ # Set visibility using the collected HTML frames+ dom_tree_node.is_visible = self.is_element_visible_according_to_all_parents(dom_tree_node, updated_html_frames)++ # handle cross origin iframe (just recursively call the main function with the proper target if it exists in iframes)+ if (+ ENABLE_CROSS_ORIGIN_IFRAMES and node['nodeName'].upper() == 'IFRAME' and node.get('contentDocument', None) is None+ ):+ targets = await self._get_targets_for_current_page()+ iframe_document_target = next(+ (iframe for iframe in targets.iframe_sessions if iframe.get('targetId') == node.get('frameId', None)), None+ )+ if iframe_document_target:+ logger.debug(f'Getting content document for iframe {node.get("frameId", None)}')+ content_document = await self._get_dom_tree(+ iframe_document_target,+ initial_total_frame_offset=total_frame_offset,+ )++ dom_tree_node.content_document = content_document+ dom_tree_node.content_document.parent_node = dom_tree_node++ return dom_tree_node++ enhanced_dom_tree_node = await _construct_enhanced_node(dom_tree['root'], initial_html_frames, initial_total_frame_offset)++ return enhanced_dom_tree_node++ async def __aexit__(self, exc_type, exc_value, traceback):+ """Clean up CDP client on exit."""+ if self.cdp_client:+ await self.cdp_client.stop()+ self.cdp_client = None++ def __del__(self):+ """Clean up CDP client on deletion."""+ super().__del__()+ if self.cdp_client:+ try:+ asyncio.create_task(self.cdp_client.stop())+ except Exception:+ pass\ No newline at end of filediff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 40870d701..0fb425ee6 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -192,6 +192,20 @@ class GetCookiesEvent(BaseEvent):urls: list[str] | None = None+# ============================================================================+# DOM-related Events+# ============================================================================+++class BuildDOMTreeEvent(BaseEvent):+ """Build and serialize the DOM tree for the current page.++ Returns SerializedDOMState with the DOM tree ready for LLM consumption.+ """++ previous_state: Any | None = None # SerializedDOMState, but avoid circular import++# ============================================================================diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.pyindex dfe6279e9..a307dbe51 100644--- a/browser_use/browser/navigation_watchdog.py+++ b/browser_use/browser/navigation_watchdog.py@@ -4,7 +4,6 @@ import asynciofrom typing import TYPE_CHECKING, Any, ClassVarfrom bubus import BaseEvent-from playwright.async_api import Pagefrom pydantic import Field, PrivateAttrfrom browser_use.browser.events import (@@ -45,42 +44,39 @@ class NavigationWatchdog(BaseWatchdog):NavigationCompleteEvent,]- # Agent focus tracking - using regular fields so they can be accessed as properties- page: Page | None = Field(default=None, exclude=True)+ # Agent focus tracking - using target IDs instead of Page objects+ current_target_id: str | None = Field(default=None, exclude=True)- # Track page close handlers so we can remove them on shutdown- _page_close_handlers: dict[Page, Any] = PrivateAttr(default_factory=dict)+ # Track target close handlers+ _target_close_handlers: dict[str, Any] = PrivateAttr(default_factory=dict)- async def attach_to_page(self, page: Page) -> None:- """Set up monitoring for a page - tracks page lifecycle."""- page.on('close', self._handle_page_close)+ async def attach_to_target(self, target_id: str) -> None:+ """Set up monitoring for a target - tracks target lifecycle."""+ # CDP doesn't have direct page close events, we'll handle via Target.targetDestroyed+ self._target_close_handlers[target_id] = True# ========== Browser Lifecycle Events ==========async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:"""Clear agent focus when browser stops."""- # Remove close handlers from all pages to prevent TabClosedEvent during shutdown- for page, handler in list(self._page_close_handlers.items()):- try:- page.remove_listener('close', handler)- except Exception:- pass # Page might already be closed- self._page_close_handlers.clear()- self.page = None+ # Clear target handlers+ self._target_close_handlers.clear()+ self.current_target_id = None# ========== Tab Lifecycle Events ==========async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:- """Handle new tab creation - track page and possibly move agent focus."""+ """Handle new tab creation - track target and possibly move agent focus."""# logger.debug(f'[NavigationWatchdog] Tab created: {event.url}')- # Get the page from browser context and track it+ # Get all targets and track the new onetry:- page = self.browser_session.get_page_by_tab_index(event.tab_index)- if page:- self._track_page(page)+ targets = await self.browser_session._cdp_get_all_pages()+ if event.tab_index < len(targets):+ target_id = targets[event.tab_index]['targetId']+ self._track_target(target_id)except Exception as e:- logger.error(f'[NavigationWatchdog] Error tracking new page: {e}')+ logger.error(f'[NavigationWatchdog] Error tracking new target: {e}')# When a new tab is created, agent typically focuses on it immediatelyawait self._update_agent_focus_to_latest_tab()@@ -89,10 +85,11 @@ class NavigationWatchdog(BaseWatchdog):"""Handle tab closure."""logger.debug(f'[NavigationWatchdog] Tab closed at index {event.tab_index}')- # If the closed tab was the agent's current page, find a new one- if self.tab_index == event.tab_index:- await self._find_new_agent_page()- # No need to adjust tab_index since it's computed from page position+ # If the closed tab was the agent's current target, find a new one+ current_tab_index = await self._get_current_tab_index()+ if current_tab_index == event.tab_index:+ await self._find_new_agent_target()+ # No need to adjust tab_index since it's computed from target positionasync def on_SwitchTabEvent(self, event: SwitchTabEvent) -> None:"""Handle explicit tab switches by the agent."""@@ -102,9 +99,9 @@ class NavigationWatchdog(BaseWatchdog):async def on_NavigateToUrlEvent(self, event: NavigateToUrlEvent) -> None:"""Handle all navigation requests with security enforcement and complete logic."""- # Check if browser context is still available- if not self.browser_session or not self.browser_session._browser_context:- logger.debug('[NavigationWatchdog] No browser context available, ignoring navigation')+ # Check if browser session is still available+ if not self.browser_session:+ logger.debug('[NavigationWatchdog] No browser session available, ignoring navigation')return# SECURITY CHECK: Block disallowed URLs before navigation starts@@ -122,16 +119,15 @@ class NavigationWatchdog(BaseWatchdog):try:# Handle new tab navigationif event.new_tab:- if not self.browser_session._browser_context:- return-- # Create new page- page = await self.browser_session._browser_context.new_page()+ # 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 page)- tab_index = len(self.browser_session.tabs) - 1+ # Get tab index for events (after adding the target)+ targets = await self.browser_session._cdp_get_all_pages()+ tab_index = len(targets) - 1- # Navigate to URL if provided+ # Navigate to URL if provided (already done in create_new_page if URL was provided)if event.url:# Dispatch navigation started eventfrom browser_use.browser.events import NavigationStartedEvent@@ -144,18 +140,16 @@ class NavigationWatchdog(BaseWatchdog):)try:- # Perform navigation with timeout protection- response = await asyncio.wait_for(- page.goto(event.url, wait_until=event.wait_until),- timeout=30.0, # 30 second timeout to prevent hanging- )+ # Navigation already happened in _cdp_create_new_page+ # Just dispatch completion+ response_status = None # CDP doesn't return response status directly# Dispatch completion eventself.event_bus.dispatch(NavigationCompleteEvent(tab_index=tab_index,url=event.url,- status=response.status if response else None,+ status=response_status,))@@ -194,16 +188,18 @@ class NavigationWatchdog(BaseWatchdog):)# Update agent focus to the new tab immediately- self.page = page+ self.current_target_id = target_idself._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+ target_url = await self._get_target_url(target_id)self.event_bus.dispatch(TabCreatedEvent(tab_index=tab_index,- url=page.url, # Use actual page URL+ url=target_url or event.url,))return@@ -229,20 +225,21 @@ class NavigationWatchdog(BaseWatchdog):return# Handle standard navigation- # Get the page to navigate - use current agent page or create one- page = None+ # Get the target to navigate - use current agent target or create one+ target_id = Nonetry:- page = await self.get_or_create_page()+ target_id = await self.get_or_create_target()except Exception:- # Fallback to first page- if self.browser_session.pages:- page = self.browser_session.pages[0]+ # Fallback to first target+ targets = await self.browser_session._cdp_get_all_pages()+ if targets:+ target_id = targets[0]['targetId']- if not page:- raise ValueError('Failed to get or create a page for navigation')+ if not target_id:+ raise ValueError('Failed to get or create a target for navigation')# Get tab index- tab_index = self.browser_session.get_tab_index(page)+ tab_index = await self._get_tab_index_for_target(target_id)# Dispatch navigation started eventfrom browser_use.browser.events import NavigationStartedEvent@@ -254,21 +251,19 @@ class NavigationWatchdog(BaseWatchdog):))- # Perform navigation with timeout protection- response = await asyncio.wait_for(- page.goto(- event.url,- wait_until=event.wait_until,- ),+ # Perform navigation with timeout protection using CDP+ await asyncio.wait_for(+ self.browser_session._cdp_navigate(event.url, target_id),timeout=30.0, # 30 second timeout to prevent hanging)+ response_status = None # CDP doesn't return response status directly# Dispatch completion eventself.event_bus.dispatch(NavigationCompleteEvent(tab_index=tab_index,url=event.url,- status=response.status if response else None,+ status=response_status,))@@ -281,7 +276,7 @@ class NavigationWatchdog(BaseWatchdog):logger.warning(f'[NavigationWatchdog] Navigation to {event.url} timed out in standard navigation')# Get tab index for timeout error reporting- tab_index = self.browser_session.get_tab_index(page) if page else 0+ tab_index = await self._get_tab_index_for_target(target_id) if target_id else 0# Dispatch NavigationCompleteEvent with timeout error detailsself.event_bus.dispatch(@@ -329,52 +324,46 @@ class NavigationWatchdog(BaseWatchdog):details={'url': event.url, 'tab_index': event.tab_index},))- # Close the page that navigated to the disallowed URL+ # Close the target that navigated to the disallowed URLtry:- if self.browser_session._browser_context:- pages = self.browser_session._browser_context.pages- if 0 <= event.tab_index < len(pages):- page = pages[event.tab_index]- await page.close()- logger.info(f'βοΈ Closed page with non-allowed URL: {event.url}')+ targets = await self.browser_session._cdp_get_all_pages()+ if 0 <= event.tab_index < len(targets):+ target_id = targets[event.tab_index]['targetId']+ await self.browser_session._cdp_close_page(target_id)+ logger.info(f'βοΈ Closed page with non-allowed URL: {event.url}')except Exception as e:logger.error(f'βοΈ Failed to close page with non-allowed URL: {str(e)}')return# Agent focus stays on the tab that navigated- if event.tab_index != self.tab_index:+ 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)# ========== Tab Tracking Methods ==========- def _track_page(self, page: Page) -> None:- """Track a page for lifecycle events."""- # logger.debug(f'[NavigationWatchdog] Started tracking page: {page.url}')-- # Set up page close handler and store it so we can remove it later- def close_handler(*args, **kwargs):- self._handle_page_close(page)-- self._page_close_handlers[page] = close_handler- page.on('close', close_handler)+ def _track_target(self, target_id: str) -> None:+ """Track a target for lifecycle events."""+ # logger.debug(f'[NavigationWatchdog] Started tracking target: {target_id}')+ self._target_close_handlers[target_id] = True- def _handle_page_close(self, page: Page) -> None:- """Handle page close event."""+ def _handle_target_close(self, target_id: str) -> None:+ """Handle target close event."""try:- # Try to get tab index before page is fully closed- tab_index = self.browser_session.get_tab_index(page)+ # Try to get tab index before target is fully closed+ tab_index = asyncio.run(self._get_tab_index_for_target(target_id))if tab_index == -1:- tab_index = 0 # Fallback if page already removed+ tab_index = 0 # Fallback if target already removed# Emit TabClosedEventself.event_bus.dispatch(TabClosedEvent(tab_index=tab_index))- logger.info(f'[NavigationWatchdog] Page closed, emitted TabClosedEvent for tab {tab_index}')+ logger.info(f'[NavigationWatchdog] Target closed, emitted TabClosedEvent for tab {tab_index}')# Clean up the handler from our tracking dict- self._page_close_handlers.pop(page, None)+ self._target_close_handlers.pop(target_id, None)except Exception as e:- logger.error(f'[NavigationWatchdog] Error handling page close: {e}')+ logger.error(f'[NavigationWatchdog] Error handling target close: {e}')# ========== Security Methods ==========@@ -452,128 +441,145 @@ class NavigationWatchdog(BaseWatchdog):# ========== Agent Focus Tracking Methods ==========@property- def current_agent_page(self) -> Page | None:- """Get the current page the agent is focused on."""- return self.page+ def current_agent_target(self) -> str | None:+ """Get the current target ID the agent is focused on."""+ return self.current_target_id@propertydef current_agent_tab_index(self) -> int:"""Get the current tab index the agent is focused on."""- return self.tab_index+ return asyncio.run(self._get_current_tab_index())@propertydef tab_index(self) -> int:- """Get the current tab index derived from page position in browser_session.pages."""- if self.page is None:+ """Get the current tab index derived from target position."""+ return asyncio.run(self._get_current_tab_index())++ async def _get_current_tab_index(self) -> int:+ """Get the current tab index from target position."""+ if self.current_target_id is None:return 0- return self.browser_session.get_tab_index(self.page)+ return await self._get_tab_index_for_target(self.current_target_id)- async def _initialize_agent_focus(self) -> None:- """Initialize agent focus to first available page."""- if not self.browser_session._browser_context:- return+ async def _get_tab_index_for_target(self, target_id: str) -> int:+ """Get tab index for a specific target ID."""+ try:+ targets = await self.browser_session._cdp_get_all_pages()+ for i, target in enumerate(targets):+ if target['targetId'] == target_id:+ return i+ except Exception:+ pass+ return -1- pages = self.browser_session._browser_context.pages- if pages:- self.page = pages[0]+ async def _get_target_url(self, target_id: str) -> str | None:+ """Get the URL for a specific target ID."""+ try:+ targets = await self.browser_session._cdp_get_all_pages()+ for target in targets:+ if target['targetId'] == target_id:+ return target.get('url', '')+ except Exception:+ pass+ return None++ async def _initialize_agent_focus(self) -> None:+ """Initialize agent focus to first available target."""+ targets = await self.browser_session._cdp_get_all_pages()+ if targets:+ self.current_target_id = targets[0]['targetId']self._dispatch_focus_changed()- try:- current_page = await self.browser_session.get_current_page()- logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {current_page.url}')- except ValueError:- logger.info('[NavigationWatchdog] Initial agent focus set to tab 0')+ target_url = await self._get_target_url(self.current_target_id)+ logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {target_url}')async def _update_agent_focus_to_latest_tab(self) -> None:"""Update agent focus to the latest (most recently created) tab."""- if self.browser_session.pages:- # Focus on the last tab (most recently created)- self.page = self.browser_session.pages[-1]+ targets = await self.browser_session._cdp_get_all_pages()+ if targets:+ # Focus on the last target (most recently created)+ self.current_target_id = targets[-1]['targetId']self._dispatch_focus_changed()- try:- current_page = await self.browser_session.get_current_page()- logger.info(f'[NavigationWatchdog] π Agent focus moved to new tab {self.tab_index}: {current_page.url}')- except ValueError:- logger.info(f'[NavigationWatchdog] π Agent focus moved to new tab {self.tab_index}')+ target_url = await self._get_target_url(self.current_target_id)+ tab_index = await self._get_current_tab_index()+ logger.info(f'[NavigationWatchdog] π Agent focus moved to new tab {tab_index}: {target_url}')async def _switch_agent_focus_to_tab(self, tab_index: int) -> None:"""Switch agent focus to a specific tab index."""- page = self.browser_session.get_page_by_tab_index(tab_index)- if page:- self.page = page+ targets = await self.browser_session._cdp_get_all_pages()+ if 0 <= tab_index < len(targets):+ self.current_target_id = targets[tab_index]['targetId']self._dispatch_focus_changed()- try:- current_page = await self.browser_session.get_current_page()- logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {current_page.url}')- except ValueError:- logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}')-- async def _find_new_agent_page(self) -> None:- """Find a new page for agent focus when current one is closed."""- if self.browser_session.pages:+ target_url = await self._get_target_url(self.current_target_id)+ logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {target_url}')++ async def _find_new_agent_target(self) -> None:+ """Find a new target for agent focus when current one is closed."""+ targets = await self.browser_session._cdp_get_all_pages()+ if targets:# Try to stay at the same index, or go to the previous one- new_index = min(self.tab_index, len(self.browser_session.pages) - 1)- self.page = self.browser_session.pages[new_index]+ current_index = await self._get_current_tab_index()+ new_index = min(current_index, len(targets) - 1)+ self.current_target_id = targets[new_index]['targetId']self._dispatch_focus_changed()- try:- current_page = await self.browser_session.get_current_page()- logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {current_page.url}')- except ValueError:- logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}')+ target_url = await self._get_target_url(self.current_target_id)+ logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {target_url}')else:- self.page = None+ self.current_target_id = Nonedef _dispatch_focus_changed(self) -> None:"""Dispatch event when agent focus changes."""- if self.page:+ if self.current_target_id:try:+ # Get URL asynchronously+ target_url = asyncio.run(self._get_target_url(self.current_target_id))+ tab_index = asyncio.run(self._get_current_tab_index())self.event_bus.dispatch(AgentFocusChangedEvent(- tab_index=self.tab_index,- url=self.page.url,+ tab_index=tab_index,+ url=target_url or '',))except Exception as e:logger.error(f'[NavigationWatchdog] Error dispatching focus change: {e}')- async def get_or_create_page(self) -> Page:- """Get current agent page or create a new one if none exists."""- if self.page and not self.page.is_closed():- # Check if current page URL is still allowed- if not self._is_url_allowed(self.page.url):- logger.warning(f'βοΈ Current page URL no longer allowed: {self.page.url}')- # Close the current page and find/create a new one+ async def get_or_create_target(self) -> str:+ """Get current agent target or create a new one if none exists."""+ if self.current_target_id:+ # Check if current target URL is still allowed+ target_url = await self._get_target_url(self.current_target_id)+ if target_url and not self._is_url_allowed(target_url):+ logger.warning(f'βοΈ Current target URL no longer allowed: {target_url}')+ # Close the current target and find/create a new onetry:- await self.page.close()+ await self.browser_session._cdp_close_page(self.current_target_id)except Exception:pass- self.page = None+ self.current_target_id = Noneelse:- return self.page+ return self.current_target_idtry:- for i, tab in enumerate(self.browser_session.pages):- if self._is_url_allowed(tab.url):- await self._switch_agent_focus_to_tab(i)- if self.page:- return self.page+ 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.current_target_id = target['targetId']+ self._dispatch_focus_changed()+ return self.current_target_idexcept TimeoutError:pass# No tabs available or no allowed tabs, create a new one with about:blank- logger.info('[NavigationWatchdog] No active page, creating new tab')-- # Check if browser is still connected before trying to create a new tab- if not self.browser_session._browser_context:- raise ValueError('Browser context is not available - browser may have disconnected')+ logger.info('[NavigationWatchdog] No active target, creating new tab')nav_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))await nav_event # Wait for navigation to complete- # Try to get the new page- if self.browser_session.pages:- self.page = self.browser_session.pages[-1]+ # Try to get the new target+ targets = await self.browser_session._cdp_get_all_pages()+ if targets:+ self.current_target_id = targets[-1]['targetId']self._dispatch_focus_changed()- if self.page:- return self.page+ return self.current_target_id- raise ValueError('Failed to create or find an active page')+ raise ValueError('Failed to create or find an active target')\ No newline at end of filediff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex a8c1e0678..669f8c1b5 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1,33 +1,26 @@"""Event-driven browser session with backwards compatibility."""import asyncio-import atexitimport loggingimport os-import shutil-import tempfile-import time-from functools import wraps-from pathlib import Path-from typing import Any, Literal, Self--from browser_use.config import CONFIG-from browser_use.observability import observe_debug-from browser_use.utils import _log_pretty_path, _log_pretty_url--from .utils import normalize_url+from typing import Any, Self-os.environ['PW_TEST_SCREENSHOT_NO_FONTS_READY'] = '1' # https://github.com/microsoft/playwright/issues/35972+from browser_use.observability import observe_debug+from browser_use.utils import _log_pretty_url-import psutilfrom bubus import EventBusfrom bubus.helpers import retry-from playwright._impl._api_structures import ViewportSizefrom pydantic import BaseModel, ConfigDict, Field, PrivateAttrfrom uuid_extensions import uuid7strfrom browser_use.browser.events import (+ BrowserConnectedEvent,+ BrowserErrorEvent,+ BrowserLaunchEvent,+ BrowserStartEvent,+ BrowserStopEvent,+ BrowserStoppedEvent,ClickElementEvent,GoBackEvent,GoForwardEvent,@@ -41,46 +34,21 @@ from browser_use.browser.events import (UploadFileEvent,WaitEvent,)-from browser_use.browser.profile import BROWSERUSE_DEFAULT_CHANNEL, BrowserChannel, BrowserProfile-from browser_use.browser.types import (- Browser,- BrowserContext,- ElementHandle,- FrameLocator,- Page,- Patchright,- PlaywrightOrPatchright,- async_patchright,- async_playwright,-)+from browser_use.browser.profile import BrowserProfile+from browser_use.browser.views import (- PLACEHOLDER_4PX_SCREENSHOT,- BrowserError,BrowserStateSummary,PageInfo,TabInfo,- URLNotAllowedError,)-from browser_use.dom.views import DOMSelectorMap as SelectorMap--# Lazy imports for heavy DOM services to improve startup time-# from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor-# from browser_use.dom.service import DomService-from browser_use.dom.views import EnhancedDOMTreeNode as DOMElementNodefrom browser_use.utils import (is_new_tab_page,logger,time_execution_async,- time_execution_sync,)_GLOB_WARNING_SHOWN = False # used inside _is_url_allowed to avoid spamming the logs with the same warning multiple times-GLOBAL_PLAYWRIGHT_API_OBJECT = None # never instantiate the playwright API object more than once per thread-GLOBAL_PATCHRIGHT_API_OBJECT = None # never instantiate the patchright API object more than once per thread-GLOBAL_PLAYWRIGHT_EVENT_LOOP = None # track which event loop the global objects belong to-GLOBAL_PATCHRIGHT_EVENT_LOOP = None # track which event loop the global objects belong to-MAX_SCREENSHOT_HEIGHT = 2000MAX_SCREENSHOT_WIDTH = 1920@@ -97,116 +65,9 @@ def _log_glob_warning(domain: str, glob: str, logger: logging.Logger):_GLOB_WARNING_SHOWN = True-def require_healthy_browser(usable_page=True, reopen_page=True):- """Decorator for BrowserSession methods to ensure browser/page is healthy before execution.-- This ridiculous overengineered logic is necessary to work around playwright's completely broken handling of crashed pages.- - When a page is loading, playwright calls will hang indefinitely.- - When a page is blocked by a JS while(true){}, playwright calls will hang indefinitely.- - When a page is unresponsive because the system is out of CPU or Memory, playwright calls will hang indefinitely.- asyncio.wait(...) is the most extreme method available to try and terminate asyncio tasks in python, but even this does not work- because it's likely the underlying playwright node.js process that's crashing and synchronously blocking the python side.- This is why we must use CDP directly and skip playwright eventually.-- Args:- usable_page: If True, check that the agent_current_page is valid and responsive before executing the method, if invalid log it but continue anyway- reopen_page: If True, attempt to reopen the page if it's crashed, invalid, or unresponsive (only applies if usable_page=True)- """-- def decorator(func):- assert asyncio.iscoroutinefunction(func), '@require_healthy_browser only supports async methods'-- @wraps(func)- async def wrapper(self: BrowserSession, *args, **kwargs):- try:- if not self.initialized or not self.browser_context:- # raise RuntimeError('BrowserSession(...).start() must be called first to launch or connect to the browser')- await self.start() # just start it automatically if not already started-- if not self.agent_current_page or self.agent_current_page.is_closed():- self.agent_current_page = (- self.browser_context.pages[0] if (self.browser_context and len(self.browser_context.pages) > 0) else None- )-- # always require at least one tab to be open for the context to be considered usable, dont check responsiveness unless usable_page=True- if not self.agent_current_page or self.agent_current_page.is_closed():- # Create new page directly to avoid circular dependency- assert self.browser_context is not None, 'Browser context is not set'- self.logger.debug(- f'@require_healthy_browser: Creating new page in {func.__name__} because agent_current_page is closed/missing'- )- new_page = await self.browser_context.new_page()- self.agent_current_page = new_page- if (not self.human_current_page) or self.human_current_page.is_closed():- self.human_current_page = new_page- if self.browser_profile.viewport:- await new_page.set_viewport_size(self.browser_profile.viewport)-- assert self.agent_current_page and not self.agent_current_page.is_closed()-- if not hasattr(self, '_cached_browser_state_summary'):- raise RuntimeError('BrowserSession(...).start() must be called first to initialize the browser session')-- # Check page responsiveness if usable_page=True- if usable_page:- # Skip if already in recovery to prevent infinite recursion- if hasattr(self, '_in_recovery') and self._in_recovery:- # self.logger.debug('Already in recovery, skipping responsiveness check')- return await func(self, *args, **kwargs)-- # Skip responsiveness check for about:blank pages - they're always responsive (I hope, otherwise something is very wrong)- if self.agent_current_page and is_new_tab_page(self.agent_current_page.url):- # self.logger.debug('Skipping responsiveness check for about:blank page')- return await func(self, *args, **kwargs)-- # Check if page is responsive- # self.logger.debug(f'Checking page responsiveness for {func.__name__}...')- if await self._is_page_responsive(self.agent_current_page):- # self.logger.debug('β Confirmed page is responsive')- pass- else:- # Page is unresponsive - handle recovery- if not reopen_page:- self.logger.warning(- 'β οΈ Page unresponsive but @require_healthy_browser(reopen_page=False), attempting to continue anyway...'- )- else:- try:- await self._recover_unresponsive_page(- func.__name__, timeout_ms=int(self.browser_profile.default_navigation_timeout or 5000) + 5_000- )- page_url = self.agent_current_page.url if self.agent_current_page else 'unknown page'- self.logger.debug(- f'π€ Crashed page recovery finished, attempting to continue with {func.__name__}() on {_log_pretty_url(page_url)}...'- )- except Exception as e:- page_url = self.agent_current_page.url if self.agent_current_page else 'unknown page'- self.logger.warning(- f'β Crashed page recovery failed, could not run {func.__name__}(), page is stuck unresponsive on {_log_pretty_url(page_url)}...'- )- raise # Re-raise to let retry decorator / callsite handle it-- return await func(self, *args, **kwargs)-- except Exception as e:- # Check if this is a TargetClosedError or similar connection error- if 'TargetClosedError' in str(type(e)) or 'browser has been closed' in str(e):- self.logger.warning(- f'βοΈ Browser {self._connection_str} disconnected before BrowserSession.{func.__name__}() could run... (error: {type(e).__name__}: {e})'- )- self._reset_connection_state()- # Re-raise all hard errors so the caller can handle them appropriately- raise-- return wrapper-- return decorator-DEFAULT_BROWSER_PROFILE = BrowserProfile()-# Common new tab page URLs-NEW_TAB_URLS = ['about:blank', 'chrome://new-tab-page/', 'chrome://newtab/']class BrowserSession(BaseModel):@@ -252,6 +113,7 @@ class BrowserSession(BaseModel):_storage_state_watchdog: Any = PrivateAttr(default=None)_local_browser_watchdog: Any = PrivateAttr(default=None)_default_action_watchdog: Any = PrivateAttr(default=None)+ _dom_watchdog: Any = PrivateAttr(default=None)# Navigation tracking now handled by watchdogs@@ -279,228 +141,156 @@ class BrowserSession(BaseModel):port_number_or_pid = ((self.cdp_url or self.wss_url or str(self.browser_pid) or 'playwright').rsplit(':', 1)[-1].split('/', 1)[0])- return f'BrowserSessionπ {self.id[-4:]}:{port_number_or_pid} #{str(id(self))[-2:]}' # ' π {str(id(self.agent_current_page))[-2:]}'-- # better to force people to get it from the right object, "only one way to do it" is better python- # def __getattr__(self, key: str) -> Any:- # """- # fall back to getting any attrs from the underlying self.browser_profile when not defined on self.- # (extra kwargs passed e.g. BrowserSession(extra_kwarg=124) on init get saved into self.browser_profile on validation,- # so this also allows you to read those: browser_session.extra_kwarg => browser_session.browser_profile.extra_kwarg)- # """- # return getattr(self.browser_profile, key)-- @observe_debug(ignore_input=True, ignore_output=True, name='browser.session.start')- async def start(self) -> Self:- """- Starts the browser session by either connecting to an existing browser or launching a new one.- Precedence order for launching/connecting:- 1. page=Page playwright object, will use its page.context as browser_context- 2. browser_context=PlaywrightBrowserContext object, will use its browser- 3. browser=PlaywrightBrowser object, will use its first available context- 4. browser_pid=int, will connect to a local chromium-based browser via pid- 5. wss_url=str, will connect to a remote playwright browser server via WSS- 6. cdp_url=str, will connect to a remote chromium-based browser via CDP- 7. playwright=Playwright object, will use its chromium instance to launch a new browser- """+ return f'BrowserSessionπ {self.id[-4:]}:{port_number_or_pid} #{str(id(self))[-2:]}' # ' π {str(id(self.current_target_id))[-2:]}'- # if we're already initialized and the connection is still valid, return the existing session state and start from scratch- # Use timeout to prevent indefinite waiting on lock acquisition- # Quick return if already connected- if self.initialized and await self.is_connected():- return self+ async def on_BrowserStartEvent(self, event: BrowserStartEvent) -> None:+ """Handle browser start request."""- # Reset if we were initialized but lost connection- if self.initialized:- self.logger.warning(f'π Browser {self._connection_str} has gone away, attempting to reconnect...')- self._reset_connection_state()+ # Initialize and attach all watchdogs FIRST so LocalBrowserWatchdog can handle BrowserLaunchEvent+ await self.attach_all_watchdogs()++ if self.cdp_url and self._browser_context:+ self.event_bus.dispatch(BrowserConnectedEvent(cdp_url=self.cdp_url))+ returntry:- # Setup- self.browser_profile.detect_display_configuration()- # Note: prepare_user_data_dir() is called later in _unsafe_setup_new_browser_context()- # after the temp directory is created. Calling it here is premature.-- # Get playwright object (has its own retry/semaphore)- await self.setup_playwright()-- # Try to connect/launch browser (each has appropriate retry logic)- await self._connect_or_launch_browser()-- # Ensure we have a context- assert self.browser_context, f'Failed to create BrowserContext for browser={self.browser}'-- # Configure browser - run some setup tasks in parallel for speed- setup_results = await asyncio.gather(- self._setup_viewports(),- self._setup_current_page_change_listeners(),- self._start_context_tracing(),- return_exceptions=True,- )+ if self.is_local and not self.cdp_url:+ # Launch local browser using event-driven approach+ launch_event = self.event_bus.dispatch(BrowserLaunchEvent())+ await launch_event- # Check for exceptions in setup results- for i, result in enumerate(setup_results):- if isinstance(result, Exception):- setup_task_names = ['_setup_viewports', '_setup_current_page_change_listeners', '_start_context_tracing']- raise Exception(f'Browser setup failed in {setup_task_names[i]}: {result}') from result+ # Get the CDP URL from LocalBrowserWatchdog handler result+ results = await launch_event.event_results_flat_dict()+ self.cdp_url = results.get('cdp_url')- self.initialized = True- return self+ if not self.cdp_url:+ raise Exception('No CDP URL returned from LocalBrowserWatchdog')- except BaseException:- self.initialized = False- raise-- @property- def _connection_str(self) -> str:- """Get a logging-ready string describing the connection method e.g. browser=playwright+google-chrome-canary (local)"""- binary_name = (- Path(self.browser_profile.executable_path).name.lower().replace(' ', '-').replace('.exe', '')- if self.browser_profile.executable_path- else (self.browser_profile.channel or BROWSERUSE_DEFAULT_CHANNEL).name.lower().replace('_', '-').replace(' ', '-')- ) # Google Chrome Canary.exe -> google-chrome-canary- driver_name = 'playwright'- if self.browser_profile.stealth:- driver_name = 'patchright'- return (- f'cdp_url={self.cdp_url}'- if self.cdp_url- else f'wss_url={self.wss_url}'- if self.wss_url- else f'browser_pid={self.browser_pid}'- if self.browser_pid- else f'browser={driver_name}:{binary_name}'- )+ assert self.cdp_url and '://' in self.cdp_url- async def stop(self, _hint: str = '') -> None:- """Shuts down the BrowserSession, killing the browser process (only works if keep_alive=False)"""+ # Connect via CDP+ self._playwright = await async_playwright().start()- # Save cookies to disk if configured- if self.browser_context:- try:- await self.save_storage_state()- except Exception as e:- self.logger.warning(f'β οΈ Failed to save auth storage state before stopping: {type(e).__name__}: {e}')+ # Get connection kwargs and exclude accept_downloads when using CDP download behavior+ connect_kwargs = self.browser_profile.kwargs_for_connect().model_dump(exclude={'accept_downloads'})- if self.browser_profile.keep_alive:- self.logger.info(- 'ποΈ BrowserSession.stop() called but keep_alive=True, leaving the browser running. Use .kill() to force close.'+ self._browser = await self._playwright.chromium.connect_over_cdp(+ self.cdp_url,+ **connect_kwargs,)- return # nothing to do if keep_alive=True, leave the browser running- # Only the owner can actually stop the browser- if not self._owns_browser_resources:- self.logger.debug(f'π BrowserSession.stop() called on a copy, not closing shared browser resources {_hint}')- # Still reset our references though- self._reset_connection_state()- return-- if self.browser_context or self.browser:- self.logger.info(f'π Closing {self._connection_str} browser context {_hint} {self.browser or self.browser_context}')-- # Save trace recording if configured- if self.browser_profile.traces_dir and self.browser_context:+ # Enable downloads via CDP Browser.setDownloadBehavior+ if self.browser_profile.downloads_path:try:- await self._save_trace_recording()+ cdp_session = await self._browser.new_browser_cdp_session()+ await cdp_session.send(+ 'Browser.setDownloadBehavior',+ {'behavior': 'allow', 'downloadPath': str(self.browser_profile.downloads_path)},+ )+ logger.debug(+ f'[Session] Enabled downloads via Browser.setDownloadBehavior to: {self.browser_profile.downloads_path}'+ )except Exception as e:- # TargetClosedError is expected when browser has already been closed- from browser_use.browser.types import TargetClosedError-- if isinstance(e, TargetClosedError):- self.logger.debug('Browser context already closed, trace may have been saved automatically')- else:- self.logger.error(f'β Error saving browser context trace: {type(e).__name__}: {e}')-- # Log video/HAR save operations (saved automatically on close)- if self.browser_profile.record_video_dir:- self.logger.info(f'π₯ Saving video recording to record_video_dir= {self.browser_profile.record_video_dir}...')- if self.browser_profile.record_har_path:- self.logger.info(f'π₯ Saving HAR file to record_har_path= {self.browser_profile.record_har_path}...')+ logger.error(f'[Session] Failed to set browser download behavior via CDP: {e}')- # Close browser context and browser using retry-decorated methods- try:- # IMPORTANT: Close context first to ensure HAR/video files are saved- await self._close_browser_context()- await self._close_browser()- except Exception as e:- if 'browser has been closed' not in str(e):- self.logger.warning(f'β Error closing browser: {type(e).__name__}: {e}')- finally:- # Always clear references to ensure a fresh start next time- self.browser_context = None- self.browser = None-- # Kill the chrome subprocess if we started it- if self.browser_pid:- try:- await self._terminate_browser_process(_hint='(stop() called)')- except psutil.NoSuchProcess:- self.browser_pid = None- except (TimeoutError, psutil.TimeoutExpired):- # If graceful termination failed, force kill- try:- proc = psutil.Process(pid=self.browser_pid)- self.logger.warning(f'β±οΈ Process did not terminate gracefully, force killing browser_pid={self.browser_pid}')- proc.kill()- except psutil.NoSuchProcess:- pass- self.browser_pid = None- except Exception as e:- if 'NoSuchProcess' not in type(e).__name__:- self.logger.debug(f'β Error terminating subprocess: {type(e).__name__}: {e}')- self.browser_pid = None-- # Clean up temporary user data directory- if self.browser_profile.user_data_dir and Path(self.browser_profile.user_data_dir).name.startswith('browseruse-tmp'):- shutil.rmtree(self.browser_profile.user_data_dir, ignore_errors=True)-- # Clear CDP/WSS URLs when stopping the browser- self.cdp_url = None- self.wss_url = None+ # Get or create browser context+ if self._browser.contexts:+ self._browser_context = self._browser.contexts[0]+ else:+ self._browser_context = await self._browser.new_context(+ **self.browser_profile.kwargs_for_new_context().model_dump(mode='json', exclude_unset=True)+ )- self._reset_connection_state()+ # Notify that browser is connected+ self.event_bus.dispatch(BrowserConnectedEvent(cdp_url=self.cdp_url))- async def close(self) -> None:- """Deprecated: Provides backwards-compatibility with old method Browser().close() and playwright BrowserContext.close()"""- await self.stop(_hint='(close() called)')+ except Exception as e:+ self.event_bus.dispatch(+ BrowserErrorEvent(+ error_type='BrowserStartEventError',+ message=f'Failed to start browser: {type(e).__name__} {e}',+ details={'cdp_url': self.cdp_url, 'is_local': self.is_local},+ )+ )+ raise- async def kill(self) -> None:- """Stop the BrowserSession even if keep_alive=True"""- # self.logger.debug(- # f'βΉοΈ Browser browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (close() called)'- # )- self.browser_profile.keep_alive = False- await self.stop(_hint='(kill() called)')+ async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:+ """Handle browser stop request."""- # do not stop self.playwright here as its likely used by other parallel browser_sessions- # let it be cleaned up by the garbage collector when no refs use it anymore+ try:+ # Check if we should keep the browser alive+ if self.browser_profile.keep_alive and not event.force:+ self.event_bus.dispatch(BrowserStoppedEvent(reason='Kept alive due to keep_alive=True'))+ return- async def new_context(self, **kwargs):- """Deprecated: Provides backwards-compatibility with old class method Browser().new_context()."""- # TODO: remove this after >=0.3.0- return self+ # Close context if we created it+ if self._browser_context:+ await self._browser_context.close()+ self._browser_context = None- async def __aenter__(self) -> Self:- await self.start()- return self+ # Clean up playwright+ if self._playwright:+ await self._playwright.stop()+ self._playwright = None- def __eq__(self, other: object) -> bool:- """Check if two BrowserSession instances are using the same browser."""+ # Reset state+ self._browser = None+ self._browser_context = None+ if self.is_local:+ self.cdp_url = None- if not isinstance(other, BrowserSession):- return False+ # Notify stop and wait for all handlers to complete+ # LocalBrowserWatchdog listens for BrowserStopEvent and dispatches BrowserKillEvent+ stop_event = self.event_bus.dispatch(BrowserStoppedEvent(reason='Stopped by request'))+ await stop_event- # Two sessions are considered equal if they're connected to the same browser- # All three connection identifiers must match- return self.browser_pid == other.browser_pid and self.cdp_url == other.cdp_url and self.wss_url == other.wss_url+ except Exception as e:+ self.event_bus.dispatch(+ BrowserErrorEvent(+ error_type='BrowserStopEventError',+ message=f'Failed to stop browser: {type(e).__name__} {e}',+ details={'cdp_url': self.cdp_url, 'is_local': self.is_local},+ )+ )- async def __aexit__(self, exc_type, exc_val, exc_tb):- # self.logger.debug(- # f'βΉοΈ Stopping gracefully browser_pid={self.browser_pid} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} keep_alive={self.browser_profile.keep_alive} (context manager exit)'- # )- await self.stop(_hint='(context manager exit)')+ # ========== Helper Methods ==========++ async def attach_all_watchdogs(self) -> None:+ """Initialize and attach all watchdogs in one go."""+ from browser_use.browser.aboutblank_watchdog import AboutBlankWatchdog+ from browser_use.browser.crash_watchdog import CrashWatchdog+ from browser_use.browser.default_action_watchdog import DefaultActionWatchdog+ from browser_use.browser.dom_watchdog import DOMWatchdog+ from browser_use.browser.downloads_watchdog import DownloadsWatchdog+ from browser_use.browser.local_browser_watchdog import LocalBrowserWatchdog+ from browser_use.browser.navigation_watchdog import NavigationWatchdog+ from browser_use.browser.storage_state_watchdog import StorageStateWatchdog++ watchdog_configs = [+ ('_crash_watchdog', CrashWatchdog),+ ('_downloads_watchdog', DownloadsWatchdog),+ ('_storage_state_watchdog', StorageStateWatchdog),+ ('_local_browser_watchdog', LocalBrowserWatchdog),+ ('_navigation_watchdog', NavigationWatchdog),+ ('_aboutblank_watchdog', AboutBlankWatchdog),+ ('_default_action_watchdog', DefaultActionWatchdog),+ ('_dom_watchdog', DOMWatchdog),+ ]++ for attr_name, watchdog_class in watchdog_configs:+ if not hasattr(self, attr_name) or getattr(self, attr_name) is None:+ try:+ watchdog = watchdog_class(event_bus=self.event_bus, browser_session=self)+ await watchdog.attach_to_session()+ setattr(self, attr_name, watchdog)+ # logger.debug(f'[Session] Initialized and attached {watchdog_class.__name__}')+ except Exception as e:+ logger.warning(f'[Session] Failed to initialize {watchdog_class.__name__}: {e}')+ else:+ # Watchdog already exists, don't re-initialize to avoid duplicate handlers+ logger.debug(f'[Session] {watchdog_class.__name__} already initialized, skipping')def model_copy(self, **kwargs) -> Self:"""Create a copy of this BrowserSession that shares the browser resources but doesn't own them.@@ -521,812 +311,66 @@ class BrowserSession(BaseModel):# Manually copy over the excluded fields that are needed for browser connection# These fields are excluded in the model config but need to be shared- copy.playwright = self.playwright- copy.browser = self.browser- copy.browser_context = self.browser_context- copy.agent_current_page = self.agent_current_page- copy.human_current_page = self.human_current_page+ copy._playwright = self._playwright+ copy._browser = self._browser+ copy._browser_context = self._browser_context+ copy.current_target_id = self.current_target_idcopy.browser_pid = self.browser_pidreturn copy- def __del__(self):- profile = getattr(self, 'browser_profile', None)- keep_alive = getattr(profile, 'keep_alive', None)- user_data_dir = getattr(profile, 'user_data_dir', None)- owns_browser = getattr(self, '_owns_browser_resources', True)- status = f'πͺ killing pid={self.browser_pid}...' if (self.browser_pid and owns_browser) else 'β οΈ'- self.logger.debug(- f'ποΈ Garbage collected BrowserSession π {self.id[-4:]}.{str(id(self.agent_current_page))[-2:]} ref #{str(id(self))[-4:]} keep_alive={keep_alive} owns_browser={owns_browser} {status}'- )- # Only kill browser processes if this instance owns them- if owns_browser:- # Avoid keeping references in __del__ that might prevent garbage collection- try:- self._kill_child_processes(_hint='(garbage collected)')- except TimeoutError:- # Never let __del__ raise Timeout exceptions- pass-- def _kill_child_processes(self, _hint: str = '') -> None:- """Kill any child processes that might be related to the browser"""-- if not self.browser_profile.keep_alive and self.browser_pid:- try:- browser_proc = psutil.Process(self.browser_pid)- try:- browser_proc.terminate()- browser_proc.wait(- timeout=5- ) # wait up to 5 seconds for the process to exit cleanly and commit its user_data_dir changes- self.logger.debug(f'π Killed browser subprocess gracefully browser_pid={self.browser_pid} {_hint}')- except (psutil.NoSuchProcess, psutil.AccessDenied, TimeoutError):- pass-- # Kill all child processes first (recursive)- for child in browser_proc.children(recursive=True):- try:- # self.logger.debug(f'Force killing child process: {child.pid} ({child.name()})')- child.kill()- self.logger.debug(f'β οΈ Force-killed hung browser helper subprocess pid={child.pid} {_hint}')- except (psutil.NoSuchProcess, psutil.AccessDenied):- pass-- # Kill the main browser process- # self.logger.debug(f'Force killing browser process: {self.browser_pid}')- browser_proc.kill()- self.logger.debug(f'β οΈ Force-killed hung browser subprocess browser_pid={self.browser_pid} {_hint}')- except psutil.NoSuchProcess:- pass- except Exception as e:- self.logger.warning(f'β οΈ Error force-killing browser in BrowserSession.__del__: {type(e).__name__}: {e}')-- @staticmethod- async def _start_global_playwright_subprocess(is_stealth: bool) -> PlaywrightOrPatchright:- """Create and return a new playwright or patchright node.js subprocess / API connector"""- global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT- global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP-- try:- current_loop = asyncio.get_running_loop()- except RuntimeError:- current_loop = None-- if is_stealth:- GLOBAL_PATCHRIGHT_API_OBJECT = await async_patchright().start()- GLOBAL_PATCHRIGHT_EVENT_LOOP = current_loop- return GLOBAL_PATCHRIGHT_API_OBJECT- else:- GLOBAL_PLAYWRIGHT_API_OBJECT = await async_playwright().start()- GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loop- return GLOBAL_PLAYWRIGHT_API_OBJECT-- async def _unsafe_get_or_start_playwright_object(self) -> PlaywrightOrPatchright:- """Get existing or create new global playwright object with proper locking."""- global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT- global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP-- # Get current event loop- try:- current_loop = asyncio.get_running_loop()- except RuntimeError:- current_loop = None-- is_stealth = self.browser_profile.stealth- driver_name = 'patchright' if is_stealth else 'playwright'- global_api_object = GLOBAL_PATCHRIGHT_API_OBJECT if is_stealth else GLOBAL_PLAYWRIGHT_API_OBJECT- global_event_loop = GLOBAL_PATCHRIGHT_EVENT_LOOP if is_stealth else GLOBAL_PLAYWRIGHT_EVENT_LOOP-- # Check if we need to create or recreate the global object- should_recreate = False-- if global_api_object and global_event_loop != current_loop:- self.logger.debug(- f'Detected event loop change. Previous {driver_name} instance was created in a different event loop. '- 'Creating new instance to avoid disconnection when the previous loop closes.'- )- should_recreate = True-- # Also check if the object exists but is no longer functional- if global_api_object and not should_recreate:- try:- # Try to access the chromium property to verify the object is still valid- _ = global_api_object.chromium.executable_path- except Exception as e:- self.logger.debug(f'Detected invalid {driver_name} instance: {type(e).__name__}. Creating new instance.')- should_recreate = True-- # If we already have a valid object, use it- if global_api_object and not should_recreate:- return global_api_object-- # Create new playwright object- return await self._start_global_playwright_subprocess(is_stealth=is_stealth)-- @retry(wait=1, retries=2, timeout=45, semaphore_limit=1, semaphore_scope='self', semaphore_lax=False)- async def _close_browser_context(self) -> None:- """Close browser context with retry logic."""- await self._unsafe_close_browser_context()-- async def _unsafe_close_browser_context(self) -> None:- """Unsafe browser context close logic without retry protection."""- if self.browser_context:- await self.browser_context.close()- self.browser_context = None-- @retry(wait=1, retries=2, timeout=10, semaphore_limit=1, semaphore_scope='self', semaphore_lax=False)- async def _close_browser(self) -> None:- """Close browser instance with retry logic."""- await self._unsafe_close_browser()-- async def _unsafe_close_browser(self) -> None:- """Unsafe browser close logic without retry protection."""- if self.browser and self.browser.is_connected():- await self.browser.close()- self.browser = None-- @retry(- wait=0.5,- retries=3,- timeout=5,- semaphore_limit=1,- semaphore_scope='self',- semaphore_lax=True,- retry_on=(TimeoutError, psutil.TimeoutExpired), # Only retry on timeouts, not NoSuchProcess- )- async def _terminate_browser_process(self, _hint: str = '') -> None:- """Terminate browser process with retry logic."""- await self._unsafe_terminate_browser_process(_hint='(terminate() called)')-- async def _unsafe_terminate_browser_process(self, _hint: str = '') -> None:- """Unsafe browser process termination without retry protection."""- if self.browser_pid:- try:- proc = psutil.Process(pid=self.browser_pid)- cmdline = proc.cmdline()- executable_path = cmdline[0] if cmdline else 'unknown'- self.logger.info(f' β³ Killing browser_pid={self.browser_pid} {_log_pretty_path(executable_path)} {_hint}')-- # Try graceful termination first- proc.terminate()- self._kill_child_processes(_hint=_hint)- await asyncio.to_thread(proc.wait, timeout=4)- except psutil.NoSuchProcess:- # Process already gone, that's fine- pass- finally:- self.browser_pid = None-- @retry(wait=0.5, retries=2, timeout=30, semaphore_limit=1, semaphore_scope='self', semaphore_lax=True)- async def _save_trace_recording(self) -> None:- """Save browser trace recording."""- # TEMPORARILY DISABLED: Trace recording causing test timeouts- return- # if self.browser_profile.traces_dir and self.browser_context is not None:- # traces_path = Path(self.browser_profile.traces_dir)- # if traces_path.suffix:- # # Path has extension, use as-is (user specified exact file path)- # final_trace_path = traces_path- # else:- # # Path has no extension, treat as directory and create filename- # trace_filename = f'BrowserSession_{self.id}.zip'- # final_trace_path = traces_path / trace_filename-- # self.logger.info(f'π₯ Saving browser_context trace to {final_trace_path}...')- # await self.browser_context.tracing.stop(path=str(final_trace_path))-- @observe_debug(ignore_input=True, ignore_output=True, name='connect_or_launch_browser')- async def _connect_or_launch_browser(self, retry_count: int = 0) -> None:- """Try all connection methods in order of precedence.-- Args:- retry_count: Number of retries already attempted (max 2)- """- # Try connecting via passed objects first- await self.setup_browser_via_passed_objects()- if self.browser_context:- return-- # Try connecting via browser PID- await self.setup_browser_via_browser_pid()- if self.browser_context:- return-- # Try connecting via WSS URL- await self.setup_browser_via_wss_url()- if self.browser_context:- return-- # Try connecting via CDP URL- await self.setup_browser_via_cdp_url()- if self.browser_context:- return-- # Launch new browser as last resort- await self.setup_new_browser_context(retry_count)-- # Removed _take_screenshot_hybrid - merged into take_screenshot-- @observe_debug(ignore_input=True, ignore_output=True, name='setup_playwright')- @retry(- wait=1,- retries=3,- timeout=10,- semaphore_limit=1,- semaphore_name='playwright_global_object',- semaphore_scope='global',- semaphore_lax=False,- semaphore_timeout=5, # 5s to wait for global playwright object- )- async def setup_playwright(self) -> None:- """- Set up playwright library client object: usually the result of (await async_playwright().start())- Override to customize the set up of the playwright or patchright library object- """- is_stealth = self.browser_profile.stealth-- # Configure browser channel based on stealth mode- if is_stealth:- # use patchright + chrome when stealth=True- self.browser_profile.channel = self.browser_profile.channel or BrowserChannel.CHROME- self.logger.info(f'πΆοΈ Activated stealth mode using patchright {self.browser_profile.channel.name.lower()} browser...')- else:- # use playwright + chromium by default- self.browser_profile.channel = self.browser_profile.channel or BrowserChannel.CHROMIUM-- # Get or create the global playwright object- self.playwright = self.playwright or await self._unsafe_get_or_start_playwright_object()-- # Log stealth best-practices warnings if applicable- if is_stealth:- if self.browser_profile.channel and self.browser_profile.channel != BrowserChannel.CHROME:- self.logger.info(- ' πͺ For maximum stealth, BrowserSession(...) should be passed channel=None or BrowserChannel.CHROME'- )- if not self.browser_profile.user_data_dir:- self.logger.info(' πͺ For maximum stealth, BrowserSession(...) should be passed a persistent user_data_dir=...')- if self.browser_profile.headless or not self.browser_profile.no_viewport:- self.logger.info(' πͺ For maximum stealth, BrowserSession(...) should be passed headless=False & viewport=None')-- # register a shutdown hook to stop the shared global playwright node.js client when the program exits (if an event loop is still running)- def shudown_playwright():- if not self.playwright:- return- try:- loop = asyncio.get_running_loop()- self.logger.debug('π Shutting down shared global playwright node.js client')- task = loop.create_task(self.playwright.stop())- if hasattr(task, '_log_destroy_pending'):- task._log_destroy_pending = False # type: ignore- except Exception:- pass- self.playwright = None-- atexit.register(shudown_playwright)-- @observe_debug(ignore_input=True, ignore_output=True, name='setup_browser_via_passed_objects')- async def setup_browser_via_passed_objects(self) -> None:- """Override to customize the set up of the connection to an existing browser"""-- # 1. check for a passed Page object, if present, it always takes priority, set browser_context = page.context- if self.agent_current_page:- try:- # Test if the page is still usable by evaluating simple JS- await self.agent_current_page.evaluate('() => true')- self.browser_context = self.agent_current_page.context- except Exception:- # Page is closed or unusable, clear it- self.agent_current_page = None- self.browser_context = None-- # 2. Check if the current browser connection is valid, if not clear the invalid objects- if self.browser_context:- try:- # Try to access a property that would fail if the context is closed- _ = self.browser_context.pages- # Additional check: verify the browser is still connected- if self.browser_context.browser and not self.browser_context.browser.is_connected():- self.browser_context = None- except Exception:- # Context is closed, clear it- self.browser_context = None-- # 3. if we have a browser object but it's disconnected, clear it and the context because we cant use either- if self.browser and not self.browser.is_connected():- if self.browser_context and (self.browser_context.browser is self.browser):- self.browser_context = None- self.browser = None-- # 4. if we have a context now, it always takes precedence, set browser = context.browser, otherwise use the passed browser- browser_from_context = self.browser_context and self.browser_context.browser- if browser_from_context and browser_from_context.is_connected():- self.browser = browser_from_context-- if self.browser or self.browser_context:- self.logger.info(f'π Connected to existing user-provided browser: {self.browser_context}')- self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end-- @observe_debug(ignore_input=True, ignore_output=True, name='setup_browser_via_browser_pid')- async def setup_browser_via_browser_pid(self) -> None:- """if browser_pid is provided, calcuclate its CDP URL by looking for --remote-debugging-port=... in its CLI args, then connect to it"""-- if self.browser or self.browser_context:- return # already connected to a browser- if not self.browser_pid:- return # no browser_pid provided, nothing to do-- # check that browser_pid process is running, otherwise we cannot connect to it- try:- chrome_process = psutil.Process(pid=self.browser_pid)- if not chrome_process.is_running():- self.logger.warning(f'β οΈ Expected Chrome process with pid={self.browser_pid} is not running')- return- args = chrome_process.cmdline()- except psutil.NoSuchProcess:- self.logger.warning(f'β οΈ Expected Chrome process with pid={self.browser_pid} not found, unable to (re-)connect')- return- except Exception as e:- self.browser_pid = None- self.logger.warning(f'β οΈ Error accessing chrome process with pid={self.browser_pid}: {type(e).__name__}: {e}')- return-- # check that browser_pid process is exposing a debug port we can connect to, otherwise we cannot connect to it- debug_port = next((arg for arg in args if arg.startswith('--remote-debugging-port=')), '').split('=')[-1].strip()- # self.logger.debug(f'πΎ Found Chrome subprocess browser_pid={self.browser_pid} open CDP port: --remote-debugging-port={debug_port}')- if not debug_port:- # provided pid is unusable, it's either not running or doesnt have an open debug port we can connect to- if '--remote-debugging-pipe' in args:- self.logger.error(- f'β Found --remote-debugging-pipe in browser launch args for browser_pid={self.browser_pid} but it was started by a different BrowserSession, cannot connect to it'- )- else:- self.logger.error(- f'β Could not find --remote-debugging-port=... to connect to in browser launch args for browser_pid={self.browser_pid}: {" ".join(args)}'- )- self.browser_pid = None- return-- self.cdp_url = self.cdp_url or f'http://127.0.0.1:{debug_port}/'-- # Wait for CDP port to become available (Chrome might still be starting)- import httpx-- # No initial sleep needed - the polling loop below handles waiting if Chrome isn't ready yet-- async with httpx.AsyncClient() as client:- for i in range(30): # timeout- # First check if the Chrome process has exited- try:- chrome_process = psutil.Process(pid=self.browser_pid)- if not chrome_process.is_running():- # If we have a subprocess reference, try to get stderr- if hasattr(self, '_subprocess') and self._subprocess:- stderr_output = ''- if self._subprocess.stderr:- try:- stderr_bytes = await self._subprocess.stderr.read()- stderr_output = stderr_bytes.decode('utf-8', errors='replace')- except Exception:- pass- if 'Failed parsing extensions' in stderr_output:- self.logger.error(f'β Chrome process {self.browser_pid} exited: Failed parsing extensions')- raise RuntimeError('Failed parsing extensions: Chrome profile incompatibility detected')- elif 'SingletonLock' in stderr_output or 'ProcessSingleton' in stderr_output:- # Chrome exited due to singleton lock- self.logger.error(- f'β Chrome process {self.browser_pid} crashed due to SingletonLock error: {stderr_output[:500]}'- )- # Kill the subprocess- try:- self._subprocess.terminate()- await self._subprocess.wait()- except Exception:- pass- self.browser_pid = None- # Throw hard error instead of restarting- raise RuntimeError(f'Chrome process crashed due to SingletonLock error: {stderr_output[:500]}')- else:- # Chrome exited for unknown reason- self.logger.error(- f'β Chrome process {self.browser_pid} crashed unexpectedly. Error: {stderr_output[:500] if stderr_output else "No error output"}'- )- # Kill the subprocess- try:- self._subprocess.terminate()- await self._subprocess.wait()- except Exception:- pass- self.browser_pid = None- # Throw hard error instead of restarting- raise RuntimeError(- f'Chrome process crashed unexpectedly: {stderr_output[:500] if stderr_output else "No error output"}'- )- self.logger.error(f'β Chrome process {self.browser_pid} exited unexpectedly')- self.browser_pid = None- return- except psutil.NoSuchProcess:- self.logger.error(f'β Chrome process {self.browser_pid} no longer exists')- self.browser_pid = None- return-- try:- response = await client.get(f'{self.cdp_url}json/version', timeout=1.0)- if response.status_code == 200:- # self.logger.debug(f'β Chrome CDP port {debug_port} is ready')- break- except (httpx.ConnectError, httpx.TimeoutException):- if i == 0:- self.logger.debug(f'β³ Waiting for Chrome CDP port {debug_port} to become available...')- await asyncio.sleep(0.5)- else:- self.logger.error(f'β Chrome CDP port {debug_port} did not become available after 30 seconds')- self.browser_pid = None- raise RuntimeError(f'Chrome CDP port {debug_port} did not become available - browser process may have crashed')-- # Determine if this is a newly spawned subprocess or an existing process- if hasattr(self, '_subprocess') and self._subprocess and self._subprocess.pid == self.browser_pid:- self.logger.info(- f'π Connecting to newly spawned browser via CDP {self.cdp_url} -> browser_pid={self.browser_pid} (local)'- )- else:- self.logger.info(- f'π Connecting to existing browser via CDP {self.cdp_url} -> browser_pid={self.browser_pid} (local)'- )- assert self.playwright is not None, 'playwright instance is None'- self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(- self.cdp_url,- **self.browser_profile.kwargs_for_connect().model_dump(),- )- self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end-- @observe_debug(ignore_input=True, ignore_output=True, name='setup_browser_via_wss_url')- async def setup_browser_via_wss_url(self) -> None:- """check for a passed wss_url, connect to a remote playwright browser server via WSS"""-- if self.browser or self.browser_context:- return # already connected to a browser- if not self.wss_url:- return # no wss_url provided, nothing to do-- self.logger.info(- f'π Connecting to existing playwright node.js browser server over WSS: {self.wss_url} -> (remote playwright)'- )- assert self.playwright is not None, 'playwright instance is None'- self.browser = self.browser or await self.playwright.chromium.connect(- self.wss_url,- **self.browser_profile.kwargs_for_connect().model_dump(),- )- self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end-async def setup_browser_via_cdp_url(self) -> None:- """check for a passed cdp_url, connect to a remote chromium-based browser via CDP"""-- if self.browser or self.browser_context:- return # already connected to a browser+ """Connect to a remote chromium-based browser via CDP using cdp-use."""+if not self.cdp_url:return # no cdp_url provided, nothing to do-+self.logger.info(f'π Connecting to existing chromium-based browser via CDP: {self.cdp_url} -> (remote browser)')- assert self.playwright is not None, 'playwright instance is None'- self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(- self.cdp_url,- **self.browser_profile.kwargs_for_connect().model_dump(),- )- self._set_browser_keep_alive(True) # we connected to an existing browser, dont kill it at the end-- @observe_debug(ignore_input=True, ignore_output=True, name='setup_new_browser_context')- @retry(wait=0.1, retries=5, timeout=45, semaphore_limit=1, semaphore_scope='self', semaphore_lax=False)- async def setup_new_browser_context(self, retry_count: int = 0) -> None:- """Launch a new browser and browser_context-- Args:- retry_count: Number of retries already attempted (max 2)- """- # Double-check after semaphore acquisition to prevent duplicate browser launches- if self.browser_context:- try:- # Check if context is still valid and has pages- if self.browser_context.pages and not all(page.is_closed() for page in self.browser_context.pages):- # self.logger.debug('Browser context already exists after semaphore acquisition, skipping launch')- return- except Exception:- # If we can't check pages, assume context is invalid and continue with launch- pass- await self._unsafe_setup_new_browser_context(retry_count)-- @observe_debug(ignore_input=True, ignore_output=True, name='_unsafe_setup_new_browser_context')- async def _unsafe_setup_new_browser_context(self, retry_count: int = 0) -> None:- """Unsafe browser context setup without retry protection.-- Args:- retry_count: Number of retries already attempted (max 2)- """-- # Note: cdp_url might be set from a previous attempt that failed and is being retried- # Only assert if we don't own browser resources (meaning cdp_url was user-provided for external browser)- # AND we don't already have a browser (which means we need to get/create a context)- if self.cdp_url and not self._owns_browser_resources and not self.browser:- raise AssertionError(- 'Should never try to set up a new local browser when connecting to an external browser via cdp_url'- )-- # if we have a browser object but no browser_context, use the first context discovered or make a new one- if self.browser and not self.browser_context:- # If HAR recording or video recording is requested, we need to create a new context with recording enabled- # Cannot reuse existing context as recording must be configured at context creation- if (self.browser_profile.record_har_path or self.browser_profile.record_video_dir) and self.browser.contexts:- recording_types = []- if self.browser_profile.record_har_path:- recording_types.append('HAR')- if self.browser_profile.record_video_dir:- recording_types.append('video')- self.logger.info(- f'π₯ Creating new browser_context with {" and ".join(recording_types)} recording enabled (cannot reuse existing context)'- )- self.browser_context = await self.browser.new_context(- **self.browser_profile.kwargs_for_new_context().model_dump(mode='json')- )- elif self.browser.contexts:- self.browser_context = self.browser.contexts[0]- # Check if this is a newly spawned subprocess- if hasattr(self, '_subprocess') and self._subprocess and self._subprocess.pid == self.browser_pid:- self.logger.debug(f'π€ Using default browser_context opened in newly spawned browser: {self.browser_context}')- else:- self.logger.info(f'π€ Using first browser_context found in existing browser: {self.browser_context}')- else:- self.browser_context = await self.browser.new_context(- **self.browser_profile.kwargs_for_new_context().model_dump(mode='json')- )- storage_info = (- f' + loaded storage_state={len(self.browser_profile.storage_state) if self.browser_profile.storage_state else 0} cookies'- if self.browser_profile.storage_state and isinstance(self.browser_profile.storage_state, dict)- else ''- )- self.logger.info(- f'π Created new empty browser_context in existing browser{storage_info}: {self.browser_context}'- )-- # if we still have no browser_context by now, launch a new local one using launch_persistent_context()- if not self.browser_context:- assert self.browser_profile.channel is not None, 'browser_profile.channel is None'- self.logger.info(- f'π Launching new local browser '- f'{str(type(self.playwright).__module__).split(".")[0]}:{self.browser_profile.channel.name.lower()} keep_alive={self.browser_profile.keep_alive or False} '- f'user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"}'- )-- # if no user_data_dir is provided, generate a unique one for this temporary browser_context (will be used to uniquely identify the browser_pid later)- if not self.browser_profile.user_data_dir:- # self.logger.debug('π Launching local browser in incognito mode')- # if no user_data_dir is provided, generate a unique one for this temporary browser_context (will be used to uniquely identify the browser_pid later)- self.browser_profile.user_data_dir = self.browser_profile.user_data_dir or Path(- tempfile.mkdtemp(prefix='browseruse-tmp-')- )- # If we're reconnecting and using a temp directory, create a new one- # This avoids conflicts with the previous browser process that might still be shutting down- elif self.browser_profile.user_data_dir and Path(self.browser_profile.user_data_dir).name.startswith(- 'browseruse-tmp-'- ):- old_dir = self.browser_profile.user_data_dir- self.browser_profile.user_data_dir = Path(tempfile.mkdtemp(prefix='browseruse-tmp-'))- self.logger.debug(- f'ποΈ Cleaning up old tmp user_data_dir= {_log_pretty_path(old_dir)} and using fresh one:{_log_pretty_path(self.browser_profile.user_data_dir)}'- )- try:- shutil.rmtree(old_dir)- except Exception:- self.logger.warning(f'ποΈ Failed to cleanup old tmp user_data_dir= {_log_pretty_path(old_dir)}')-- # user data dir was provided, prepare it for use (handles conflicts automatically)- self.prepare_user_data_dir()++ # Import cdp-use client+ import httpx+ from cdp_use import CDPClient++ # Convert HTTP URL to WebSocket URL if needed+ ws_url = self.cdp_url+ if not ws_url.startswith('ws'):+ # If it's an HTTP URL, fetch the WebSocket URL from /json/version endpoint+ url = ws_url.rstrip('/')+ if not url.endswith('/json/version'):+ url = url + '/json/version'+ async with httpx.AsyncClient() as client:+ version_info = await client.get(url)+ ws_url = version_info.json()['webSocketDebuggerUrl']++ # Create and store the CDP client for direct CDP communication+ if not hasattr(self, '_cdp_client'):+ self._cdp_client = CDPClient(ws_url)+ await self._cdp_client.start()++ # Get browser targets to find available contexts/pages+ targets = await self._cdp_client.send.Target.getTargets()++ # Find main browser pages (not iframes or workers)+ page_targets = [t for t in targets['targetInfos'] if t['type'] == 'page']++ if not page_targets:+ # No pages found, create a new one+ new_target = await self._cdp_client.send.Target.createTarget({'url': 'about:blank'})+ target_id = new_target['targetId']+ else:+ # Use the first available page+ target_id = page_targets[0]['targetId']++ # Store the current page target ID+ self.current_target_id = target_id++ # Mark that we're connected via CDP (no playwright browser object)+ self._cdp_connected = True+ self.keep_alive = True- # if a user_data_dir is provided, launch Chrome as subprocess then connect via CDP- try:- async with asyncio.timeout(self.browser_profile.timeout / 1000):- try:- assert self.playwright is not None, 'playwright instance is None'-- # Find an available port for remote debugging- import socket-- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:- s.bind(('127.0.0.1', 0))- s.listen(1)- debug_port = s.getsockname()[1]-- # Get chromium executable path from browser profile or fall back to to playwright default- chromium_path = self.browser_profile.executable_path or self.playwright.chromium.executable_path-- # Build chrome launch command with all args- chrome_args = self.browser_profile.get_args()-- # Add/replace remote-debugging-port with our chosen port- final_args = []- for arg in chrome_args:- if not arg.startswith('--remote-debugging-port='):- final_args.append(arg)- final_args.extend(- [- f'--remote-debugging-port={debug_port}',- f'--user-data-dir={self.browser_profile.user_data_dir}',- ]- )-- # Build final command- chrome_launch_cmd = [chromium_path] + final_args-- # Launch chrome as subprocess- self.logger.info(- f' β³ Spawning Chrome subprocess listening on CDP http://127.0.0.1:{debug_port}/ with user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)}'- )- process = await asyncio.create_subprocess_exec(- *chrome_launch_cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )-- # Store the subprocess reference for error handling- self._subprocess = process-- # Store the browser PID- self.browser_pid = process.pid- self._set_browser_keep_alive(False) # We launched it, so we should close it- self._owns_browser_resources = True # We launched it, so we own it- # self.logger.debug(f'πΆ Chrome subprocess launched with browser_pid={process.pid}')-- # Use the existing setup_browser_via_browser_pid method to connect- # It will wait for the CDP port to become available- await self.setup_browser_via_browser_pid()-- # If connection failed, browser will be None- if not self.browser:- # Try to get error info from the process- if process.returncode is not None:- # Chrome exited, try to read stderr for error message- stderr_output = ''- if process.stderr:- try:- stderr_bytes = await process.stderr.read()- stderr_output = stderr_bytes.decode('utf-8', errors='replace')- except Exception:- pass-- # Check for common Chrome errors- if 'Failed parsing extensions' in stderr_output:- raise RuntimeError(- f'Failed parsing extensions: Chrome profile incompatibility detected. Chrome exited with code {process.returncode}'- )- elif 'SingletonLock' in stderr_output or 'ProcessSingleton' in stderr_output:- raise RuntimeError(f'SingletonLock error: {stderr_output[:500]}')- else:- # For any other error, raise hard error- self.logger.error(- f'β Chrome subprocess crashed with code {process.returncode}. Error: {stderr_output[:500] if stderr_output else "No error output"}'- )- raise RuntimeError(- f'Chrome subprocess crashed with code {process.returncode}. Error output: {stderr_output[:500] if stderr_output else "No error output"}'- )- else:- # Kill the subprocess if it's still running but we couldn't connect- try:- process.terminate()- await process.wait()- except Exception:- pass- raise RuntimeError(f'Failed to connect to Chrome subprocess on port {debug_port}')-- except Exception as e:- # Check if it's a SingletonLock error or Chrome subprocess exit error- if (- 'SingletonLock' in str(e)- or 'ProcessSingleton' in str(e)- or 'Chrome subprocess exited' in str(e)- or isinstance(e, RuntimeError)- ):- # Chrome has crashed - throw hard error instead of restarting- self.logger.error(f'β Chrome process crashed and cannot be recovered: {str(e)}')- # Kill the failed subprocess if it exists- if hasattr(self, '_subprocess') and self._subprocess:- try:- self._subprocess.terminate()- await self._subprocess.wait()- except Exception:- pass- # Re-raise to be caught by outer exception handler for fallback- raise- # Re-raise if not a timeout- elif not isinstance(e, asyncio.TimeoutError):- raise- except TimeoutError:- self.logger.error(- 'β Browser operation timed out. This may indicate the playwright instance is invalid or the browser has crashed.'- )- # Try fallback to temp profile in case it's a profile lock issue- # But only if we're trying to launch a local browser (not connecting to external)- if retry_count < 2 and self._owns_browser_resources:- self.logger.warning(- f'β οΈ Chrome subprocess failed to start (timeout). Profile at {_log_pretty_path(self.browser_profile.user_data_dir)} may be locked. Using temporary profile instead.'- )- self._fallback_to_temp_profile('Chrome subprocess timeout')- # Retry with temp profile- return await self.setup_new_browser_context(retry_count + 1)- else:- # Max retries reached or external browser - throw hard error- raise RuntimeError('Browser operation timed out - browser may have crashed or become unresponsive')- except Exception as e:- # Check if it's a SingletonLock error or any Chrome subprocess failure- if 'SingletonLock' in str(e) or 'ProcessSingleton' in str(e) or isinstance(e, RuntimeError):- # Chrome crashed - fallback to temp profile- # But only if we're trying to launch a local browser (not connecting to external)- if retry_count < 2 and self._owns_browser_resources:- self.logger.warning(- f'β οΈ Chrome subprocess failed to start detected. Profile at {_log_pretty_path(self.browser_profile.user_data_dir)} is locked. Using temporary profile instead.'- )- self._fallback_to_temp_profile()- # Retry with temp profile- return await self._connect_or_launch_browser(retry_count + 1)- else:- # Max retries reached or external browser - throw error- self.logger.error(f'β Chrome launch failed after {retry_count} retries: {str(e)}')- raise RuntimeError(f'Chrome launch failed: {str(e)}')-- # show a nice logger hint explaining what went wrong with the user_data_dir- # calculate the version of the browser that the user_data_dir is for, and the version of the browser we are running with- user_data_dir_chrome_version = '???'- test_browser_version = '???'- try:- # user_data_dir is corrupted or unreadable because it was migrated to a newer version of chrome than we are running with- user_data_dir_chrome_version = (Path(self.browser_profile.user_data_dir) / 'Last Version').read_text().strip()- except Exception:- pass # let the logger below handle it- try:- assert self.playwright is not None, 'playwright instance is None'- test_browser = await self.playwright.chromium.launch(headless=True)- test_browser_version = test_browser.version- await test_browser.close()- except Exception:- pass-- # failed to parse extensions == most common error text when user_data_dir is corrupted / has an unusable schema- reason = 'due to bad' if 'Failed parsing extensions' in str(e) else 'for unknown reason with'- driver = str(type(self.playwright).__module__).split('.')[0].lower()- browser_channel = (- Path(self.browser_profile.executable_path).name.replace(' ', '-').replace('.exe', '').lower()- if self.browser_profile.executable_path- else (self.browser_profile.channel or BROWSERUSE_DEFAULT_CHANNEL).name.lower()- )- self.logger.error(- f'β Launching new local browser {driver}:{browser_channel} (v{test_browser_version}) failed!'- f'\n\tFailed {reason} user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)} (created with v{user_data_dir_chrome_version})'- '\n\tTry using a different browser version/channel or delete the user_data_dir to start over with a fresh profile.'- '\n\t(can happen if different versions of Chrome/Chromium/Brave/etc. tried to share one dir)'- f'\n\n{type(e).__name__} {e}'- )- raise- # Only restore browser from context if it's connected, otherwise keep it None to force new launch- browser_from_context = self.browser_context and self.browser_context.browser- if browser_from_context and browser_from_context.is_connected():- self.browser = browser_from_context- # ^ self.browser can unfortunately still be None at the end ^- # playwright does not give us a browser object at all when we use launch_persistent_context()!+ async def setup_domservice_init_scripts(self, retry_count: int = 0) -> None:- # PID detection is no longer needed since we get PIDs directly from subprocesses or passed objects-- if self.browser:- assert self.browser.is_connected(), (- f'Browser is not connected, did the browser process crash or get killed? (connection method: {self._connection_str})'- )- # Only log final connection if we didn't already log it via setup_browser_via_browser_pid- if not (hasattr(self, '_subprocess') and self._subprocess and self._subprocess.pid == self.browser_pid):- self.logger.debug(f'πͺ’ Browser {self._connection_str} connected {self.browser or self.browser_context}')- elif self.browser_context and not self.browser:- # For launch_persistent_context case where we don't get a browser object- self.logger.debug(f'πͺ’ Browser context {self._connection_str} connected {self.browser_context}')-- assert self.browser_context, (- f'{self} Failed to create a playwright BrowserContext {self.browser_context} for browser={self.browser}'- )# self.logger.debug('Setting up init scripts in browser')@@ -1346,1323 +390,115 @@ class BrowserSession(BaseModel):if (window._eventListenerTrackerInitialized) return;window._eventListenerTrackerInitialized = true;- const originalAddEventListener = EventTarget.prototype.addEventListener;- const eventListenersMap = new WeakMap();-- EventTarget.prototype.addEventListener = function(type, listener, options) {- if (typeof listener === "function") {- let listeners = eventListenersMap.get(this);- if (!listeners) {- listeners = [];- eventListenersMap.set(this, listeners);- }-- listeners.push({- type,- listener,- listenerPreview: listener.toString().slice(0, 100),- options- });- }-- return originalAddEventListener.call(this, type, listener, options);- };-- window.getEventListenersForNode = (node) => {- const listeners = eventListenersMap.get(node) || [];- return listeners.map(({ type, listenerPreview, options }) => ({- type,- listenerPreview,- options- }));- };- })();- }- """-- # Expose anti-detection scripts- try:- await self.browser_context.add_init_script(init_script)- except Exception as e:- if 'Target page, context or browser has been closed' in str(e):- self.logger.warning('β οΈ Browser context was closed before init script could be added')- # Reset connection state since browser is no longer valid- self._reset_connection_state()- else:- raise-- if self.browser_profile.stealth and not isinstance(self.playwright, Patchright):- self.logger.warning('β οΈ Failed to set up stealth mode. (...) got normal playwright objects as input.')-- # async def _fork_locked_user_data_dir(self) -> None:- # """Fork an in-use user_data_dir by cloning it to a new location to allow a second browser to use it"""- # # TODO: implement copy-on-write using overlayfs or zfs or something- # suffix_num = str(self.browser_profile.user_data_dir).rsplit('.', 1)[-1] or '1'- # suffix_num = int(suffix_num) if suffix_num.isdigit() else 1- # dir_name = self.browser_profile.user_data_dir.name- # incremented_name = dir_name.replace(f'.{suffix_num}', f'.{suffix_num + 1}')- # fork_path = self.browser_profile.user_data_dir.parent / incremented_name-- # # keep incrementing the suffix_num until we find a path that doesn't exist- # while fork_path.exists():- # suffix_num += 1- # fork_path = self.browser_profile.user_data_dir.parent / (dir_name.rsplit('.', 1)[0] + f'.{suffix_num}')-- # # use shutil to recursively copy the user_data_dir to a new location- # shutil.copytree(- # str(self.browser_profile.user_data_dir),- # str(fork_path),- # symlinks=True,- # ignore_dangling_symlinks=True,- # dirs_exist_ok=False,- # )- # self.browser_profile.user_data_dir = fork_path- # self.browser_profile.prepare_user_data_dir()-- @observe_debug(ignore_input=True, ignore_output=True, name='setup_current_page_change_listeners')- async def _setup_current_page_change_listeners(self) -> None:- # Uses a combination of:- # - visibilitychange events- # - window focus/blur events- # - pointermove events-- # This annoying multi-method approach is needed for more reliable detection across browsers because playwright provides no API for this.-- # TODO: pester the playwright team to add a new event that fires when a headful tab is focused.- # OR implement a browser-use chrome extension that acts as a bridge to the chrome.tabs API.-- # - https://github.com/microsoft/playwright/issues/1290- # - https://github.com/microsoft/playwright/issues/2286- # - https://github.com/microsoft/playwright/issues/3570- # - https://github.com/microsoft/playwright/issues/13989-- # set up / detect foreground page- assert self.browser_context is not None, 'BrowserContext object is not set'- pages = self.browser_context.pages- foreground_page = None- if pages:- foreground_page = pages[0]- self.logger.debug(- f'ποΈβπ¨οΈ Found {len(pages)} existing tabs in browser, Agent π ° {self.id[-4:]} is on Page π {str(id(foreground_page))[-2:]}: {_log_pretty_url(foreground_page.url)}' # type: ignore- )- else:- foreground_page = await self.browser_context.new_page()- pages = [foreground_page]- self.logger.debug('β Opened new tab in empty browser context...')-- self.agent_current_page = self.agent_current_page or foreground_page- self.human_current_page = self.human_current_page or foreground_page- # Note: JavaScript focus tracking has been removed as it's now handled by NavigationWatchdog-- @observe_debug(- ignore_input=True, ignore_output=True, name='setup_viewports', metadata={'browser_profile': '{{browser_profile}}'}- )- async def _setup_viewports(self) -> None:- """Resize any existing page viewports to match the configured size, set up storage_state, permissions, geolocation, etc."""-- assert self.browser_context, 'BrowserSession.browser_context must already be set up before calling _setup_viewports()'-- # log the viewport settings to terminal- viewport = self.browser_profile.viewport- self.logger.debug(- 'π Setting up viewport: '- + f'headless={self.browser_profile.headless} '- + (- f'window={self.browser_profile.window_size["width"]}x{self.browser_profile.window_size["height"]}px '- if self.browser_profile.window_size- else '(no window) '- )- + (- f'screen={self.browser_profile.screen["width"]}x{self.browser_profile.screen["height"]}px '- if self.browser_profile.screen- else ''- )- + (f'viewport={viewport["width"]}x{viewport["height"]}px ' if viewport else '(no viewport) ')- + f'device_scale_factor={self.browser_profile.device_scale_factor or 1.0} '- + f'is_mobile={self.browser_profile.is_mobile} '- + (f'color_scheme={self.browser_profile.color_scheme.value} ' if self.browser_profile.color_scheme else '')- + (f'locale={self.browser_profile.locale} ' if self.browser_profile.locale else '')- + (f'timezone_id={self.browser_profile.timezone_id} ' if self.browser_profile.timezone_id else '')- + (f'geolocation={self.browser_profile.geolocation} ' if self.browser_profile.geolocation else '')- + (f'permissions={",".join(self.browser_profile.permissions or ["<none>"])} ')- + f'storage_state={_log_pretty_path(str(self.browser_profile.storage_state or self.browser_profile.cookies_file or "<none>"))} '- )-- # if we have any viewport settings in the profile, make sure to apply them to the entire browser_context as defaults- if self.browser_profile.permissions:- try:- await self.browser_context.grant_permissions(self.browser_profile.permissions)- except Exception as e:- self.logger.warning(- f'β οΈ Failed to grant browser permissions {self.browser_profile.permissions}: {type(e).__name__}: {e}'- )- try:- if self.browser_profile.default_timeout:- self.browser_context.set_default_timeout(self.browser_profile.default_timeout)- if self.browser_profile.default_navigation_timeout:- self.browser_context.set_default_navigation_timeout(self.browser_profile.default_navigation_timeout)- except Exception as e:- self.logger.warning(- f'β οΈ Failed to set playwright timeout settings '- f'cdp_api={self.browser_profile.default_timeout} '- f'navigation={self.browser_profile.default_navigation_timeout}: {type(e).__name__}: {e}'- )- try:- if self.browser_profile.extra_http_headers:- await self.browser_context.set_extra_http_headers(self.browser_profile.extra_http_headers)- except Exception as e:- self.logger.warning(- f'β οΈ Failed to setup playwright extra_http_headers: {type(e).__name__}: {e}'- ) # dont print the secret header contents in the logs!-- try:- if self.browser_profile.geolocation:- await self.browser_context.set_geolocation(self.browser_profile.geolocation)- except Exception as e:- self.logger.warning(- f'β οΈ Failed to update browser geolocation {self.browser_profile.geolocation}: {type(e).__name__}: {e}'- )-- # Storage state is automatically loaded by StorageStateWatchdog on browser connection-- page = None-- for page in self.browser_context.pages:- # apply viewport size settings to any existing pages- if viewport:- await page.set_viewport_size(viewport)-- # show browser-use dvd screensaver-style bouncing loading animation on any new tab pages- if is_new_tab_page(page.url):- # Navigate to about:blank if we're on chrome://new-tab-page to avoid security restrictions- if page.url.startswith('chrome://new-tab-page'):- try:- # can raise exception if nav is interrupted by another agent nav or human, harmless but annoying- await page.goto('about:blank', wait_until='load', timeout=5000)- except Exception:- pass- await self._show_dvd_screensaver_loading_animation(page)-- page = page or (await self.browser_context.new_page())-- if (not viewport) and (self.browser_profile.window_size is not None) and not self.browser_profile.headless:- # attempt to resize the actual browser window-- # cdp api: https://chromedevtools.github.io/devtools-protocol/tot/Browser/#method-setWindowBounds- try:- cdp_session = await page.context.new_cdp_session(page) # type: ignore- window_id_result = await cdp_session.send('Browser.getWindowForTarget')- await cdp_session.send(- 'Browser.setWindowBounds',- {- 'windowId': window_id_result['windowId'],- 'bounds': {- **self.browser_profile.window_size,- 'windowState': 'normal', # Ensure window is not minimized/maximized- },- },- )- try:- await asyncio.wait_for(cdp_session.detach(), timeout=1.0)- except (TimeoutError, Exception):- pass- except Exception as e:- _log_size = lambda size: f'{size["width"]}x{size["height"]}px'- try:- # fallback to javascript resize if cdp setWindowBounds fails- await page.evaluate(- """(width, height) => {window.resizeTo(width, height)}""",- [self.browser_profile.window_size['width'], self.browser_profile.window_size['height']],- )- return- except Exception:- pass-- self.logger.warning(- f'β οΈ Failed to resize browser window to {_log_size(self.browser_profile.window_size)} via CDP setWindowBounds: {type(e).__name__}: {e}'- )-- def _set_browser_keep_alive(self, keep_alive: bool | None) -> None:- """set the keep_alive flag on the browser_profile, defaulting to True if keep_alive is None"""- if self.browser_profile.keep_alive is None:- self.browser_profile.keep_alive = keep_alive-- @observe_debug(ignore_input=True, ignore_output=True, name='is_connected')- async def is_connected(self, restart: bool = True) -> bool:- """- Check if the browser session has valid, connected browser and context objects.- Returns False if any of the following conditions are met:- - No browser_context exists- - Browser exists but is disconnected- - Browser_context's browser exists but is disconnected- - Browser_context itself is closed/unusable-- Args:- restart: If True, will attempt to create a new tab if no pages exist (valid contexts must always have at least one page open).- If False, will only check connection status without side effects.- """- if not self.browser_context:- return False-- if self.browser_context.browser and not self.browser_context.browser.is_connected():- return False-- # Check if the browser_context itself is closed/unusable- try:- # The only reliable way to check if a browser context is still valid- # is to try to use it. We'll try a simple page.evaluate() call.- if self.browser_context.pages:- # Use the first available page to test the connection- test_page = self.browser_context.pages[0]- # Try a simple evaluate to check if the connection is alive- result = await test_page.evaluate('() => true')- return result is True- elif restart:- # Create new page directly to avoid using decorated methods- new_page = await self.browser_context.new_page()- self.agent_current_page = new_page- if (not self.human_current_page) or self.human_current_page.is_closed():- self.human_current_page = new_page- # Test the new tab- if self.browser_context.pages:- test_page = self.browser_context.pages[0]- result = await test_page.evaluate('() => true')- return result is True- return False- else:- return False- except Exception:- # Any exception means the context is closed or invalid- return False-- def _reset_connection_state(self) -> None:- """Reset the browser connection state when disconnection is detected"""-- already_disconnected = not any(- (- self.initialized,- self.browser,- self.browser_context,- self.agent_current_page,- self.human_current_page,- self._cached_clickable_element_hashes,- self._cached_browser_state_summary,- )- )-- self.initialized = False- self.browser = None- self.browser_context = None- self.agent_current_page = None- self.human_current_page = None- self._cached_clickable_element_hashes = None- # Reset CDP connection info when browser is stopped- self.browser_pid = None- self._cached_browser_state_summary = None- # Don't clear self.playwright here - it should be cleared explicitly in kill()-- if self.browser_pid:- try:- # browser_pid is different from all the other state objects, it's closer to cdp_url or wss_url- # because we might still be able to reconnect to the same browser even if self.browser_context died- # if we have a self.browser_pid, check if it's still alive and serving a remote debugging port- # if so, don't clear it because there's a chance we can re-use it by just reconnecting to the same pid's port- proc = psutil.Process(self.browser_pid)- proc_is_alive = proc.status() not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD)- assert proc_is_alive and '--remote-debugging-port' in ' '.join(proc.cmdline())- except Exception:- self.logger.info(f' β³ Browser browser_pid={self.browser_pid} process is no longer running')- # process has gone away or crashed, pid is no longer valid so we clear it- self.browser_pid = None-- if not already_disconnected:- self.logger.debug(f'β°οΈ Browser {self._connection_str} disconnected')-- def _check_for_singleton_lock_conflict(self) -> bool:- """Check if the user data directory has a conflicting browser process.-- Returns:- True if there's a conflict (active process using this profile), False otherwise- """- if not self.browser_profile.user_data_dir:- return False-- # Normalize the path for comparison- target_dir = str(Path(self.browser_profile.user_data_dir).expanduser().resolve())-- # Check for running processes using this user data dir- for proc in psutil.process_iter(['pid', 'cmdline']):- # Skip our own browser process- if hasattr(self, 'browser_pid') and self.browser_pid and proc.info['pid'] == self.browser_pid:- continue-- cmdline = proc.info['cmdline'] or []-- # Check both formats: --user-data-dir=/path and --user-data-dir /path- for i, arg in enumerate(cmdline):- # Combined format: --user-data-dir=/path- if arg.startswith('--user-data-dir='):- try:- cmd_path = str(Path(arg.split('=', 1)[1]).expanduser().resolve())- if cmd_path == target_dir:- self.logger.debug(- f'π Found conflicting Chrome process PID {proc.info["pid"]} using profile {_log_pretty_path(self.browser_profile.user_data_dir)}'- )- return True- except Exception:- # Fallback to string comparison if path resolution fails- if arg.split('=', 1)[1] == str(self.browser_profile.user_data_dir):- self.logger.debug(- f'π Found conflicting Chrome process PID {proc.info["pid"]} using profile {_log_pretty_path(self.browser_profile.user_data_dir)}'- )- return True- # Separate format: --user-data-dir /path- elif arg == '--user-data-dir' and i + 1 < len(cmdline):- try:- cmd_path = str(Path(cmdline[i + 1]).expanduser().resolve())- if cmd_path == target_dir:- self.logger.debug(- f'π Found conflicting Chrome process PID {proc.info["pid"]} using profile {_log_pretty_path(self.browser_profile.user_data_dir)}'- )- return True- except Exception:- # Fallback to string comparison if path resolution fails- if cmdline[i + 1] == str(self.browser_profile.user_data_dir):- self.logger.debug(- f'π Found conflicting Chrome process PID {proc.info["pid"]} using profile {_log_pretty_path(self.browser_profile.user_data_dir)}'- )- return True-- # Note: We don't consider a SingletonLock file alone as a conflict- # because it might be stale. Only actual running processes count as conflicts.- return False-- def _fallback_to_temp_profile(self, reason: str = 'SingletonLock conflict') -> None:- """Fallback to a temporary profile directory when the current one is locked.-- Args:- reason: Human-readable reason for the fallback- """- old_dir = self.browser_profile.user_data_dir- self.browser_profile.user_data_dir = Path(tempfile.mkdtemp(prefix='browseruse-tmp-singleton-'))- self.logger.warning(- f'β οΈ {reason} detected. Profile at {_log_pretty_path(old_dir)} is locked. '- f'Using temporary profile instead: {_log_pretty_path(self.browser_profile.user_data_dir)}'- )-- @observe_debug(ignore_input=True, ignore_output=True, name='prepare_user_data_dir')- def prepare_user_data_dir(self, check_conflicts: bool = True) -> None:- """Create and prepare the user data dir, handling conflicts if needed.-- Args:- check_conflicts: Whether to check for and handle singleton lock conflicts- """- if self.browser_profile.user_data_dir:- try:- self.browser_profile.user_data_dir = Path(self.browser_profile.user_data_dir).expanduser().resolve()- self.browser_profile.user_data_dir.mkdir(parents=True, exist_ok=True)- (self.browser_profile.user_data_dir / '.browseruse_profile_id').write_text(self.browser_profile.id)- except Exception as e:- raise ValueError(- f'Unusable path provided for user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)} (check for typos/permissions issues)'- ) from e-- # Remove stale singleton lock file ONLY if no process is using this profile- # This must happen BEFORE checking for conflicts to avoid false positives- singleton_lock = self.browser_profile.user_data_dir / 'SingletonLock'- if singleton_lock.exists():- # Check if any process is actually using this user_data_dir- has_active_process = False- target_dir = str(self.browser_profile.user_data_dir)- for proc in psutil.process_iter(['pid', 'cmdline']):- # Skip our own browser process- if hasattr(self, 'browser_pid') and self.browser_pid and proc.info['pid'] == self.browser_pid:- continue-- cmdline = proc.info['cmdline'] or []- # Check both formats: --user-data-dir=/path and --user-data-dir /path- for i, arg in enumerate(cmdline):- if arg.startswith('--user-data-dir='):- try:- if str(Path(arg.split('=', 1)[1]).expanduser().resolve()) == target_dir:- has_active_process = True- break- except Exception:- if arg.split('=', 1)[1] == str(self.browser_profile.user_data_dir):- has_active_process = True- break- elif arg == '--user-data-dir' and i + 1 < len(cmdline):- try:- if str(Path(cmdline[i + 1]).expanduser().resolve()) == target_dir:- has_active_process = True- break- except Exception:- if cmdline[i + 1] == str(self.browser_profile.user_data_dir):- has_active_process = True- break- if has_active_process:- break-- if not has_active_process:- # No active process, safe to remove stale lock- try:- # Handle both regular files and symlinks- if singleton_lock.is_symlink() or singleton_lock.exists():- singleton_lock.unlink()- self.logger.debug(- f'π§Ή Removed stale SingletonLock file from {_log_pretty_path(self.browser_profile.user_data_dir)} (no active Chrome process found)'- )- except Exception:- pass # Ignore errors removing lock file-- # Check for conflicts and fallback if needed (AFTER cleaning stale locks)- if check_conflicts and self._check_for_singleton_lock_conflict():- self._fallback_to_temp_profile()- # Recursive call without conflict checking to prepare the new temp dir- return self.prepare_user_data_dir(check_conflicts=False)-- # Create directories for all paths that need them- dir_paths = {- 'downloads_path': self.browser_profile.downloads_path,- 'record_video_dir': self.browser_profile.record_video_dir,- 'traces_dir': self.browser_profile.traces_dir,- }-- file_paths = {- 'record_har_path': self.browser_profile.record_har_path,- }-- # Handle directory creation- for path_name, path_value in dir_paths.items():- if path_value:- try:- path_obj = Path(path_value).expanduser().resolve()- path_obj.mkdir(parents=True, exist_ok=True)- setattr(self.browser_profile, path_name, str(path_obj) if path_name == 'traces_dir' else path_obj)- except Exception as e:- self.logger.error(f'β Failed to create {path_name} directory {path_value}: {e}')-- # Handle file path parent directory creation- for path_name, path_value in file_paths.items():- if path_value:- try:- path_obj = Path(path_value).expanduser().resolve()- path_obj.parent.mkdir(parents=True, exist_ok=True)- except Exception as e:- self.logger.error(f'β Failed to create parent directory for {path_name} {path_value}: {e}')-- # --- Tab management ---- @observe_debug(ignore_input=True, ignore_output=True, name='get_current_page')- async def get_current_page(self) -> Page:- """Get the current page + ensure it's not None / closed"""-- if not self.initialized:- await self.start()-- # get-or-create the browser_context if it's not already set up- if not self.browser_context:- await self.start()- assert self.browser_context, 'BrowserContext is not set up'-- # if either focused page is closed, clear it so we dont use a dead object- if (not self.human_current_page) or self.human_current_page.is_closed():- self.human_current_page = None- if (not self.agent_current_page) or self.agent_current_page.is_closed():- self.agent_current_page = None-- # if either one is None, fallback to using the other one for both- self.agent_current_page = self.agent_current_page or self.human_current_page or None- self.human_current_page = self.human_current_page or self.agent_current_page or None-- # if both are still None, fallback to using the first open tab we can find- if self.agent_current_page is None:- if self.browser_context.pages:- first_available_tab = self.browser_context.pages[0]- self.agent_current_page = first_available_tab- self.human_current_page = first_available_tab- else:- # if all tabs are closed, open a new one, never allow a context with 0 tabs- new_page = await self.browser_context.new_page()- self.agent_current_page = new_page- self.human_current_page = new_page- if self.browser_profile.viewport:- await new_page.set_viewport_size(self.browser_profile.viewport)-- assert self.agent_current_page is not None, f'{self} Failed to find or create a new page for the agent'- assert self.human_current_page is not None, f'{self} Failed to find or create a new page for the human'-- return self.agent_current_page-- @property- def tabs(self) -> list[Page]:- if not self.browser_context:- return []- return list(self.browser_context.pages)-- @require_healthy_browser(usable_page=False, reopen_page=False)- async def switch_tab(self, tab_index: int) -> Page:- assert self.browser_context is not None, 'BrowserContext is not set up'- pages = self.browser_context.pages- if not pages or tab_index >= len(pages):- raise IndexError('Tab index out of range')- page = pages[tab_index]- self.agent_current_page = page-- # Invalidate cached state since we've switched to a different tab- # The cached state contains DOM elements and selector map from the previous tab- self._cached_browser_state_summary = None- self._cached_clickable_element_hashes = None-- return page-- @require_healthy_browser(usable_page=True, reopen_page=True)- async def wait_for_element(self, selector: str, timeout: int = 10000) -> None:- page = await self.get_current_page()- await page.wait_for_selector(selector, state='visible', timeout=timeout)-- @observe_debug(name='remove_highlights', ignore_output=True, ignore_input=True)- @time_execution_async('--remove_highlights')- @retry(timeout=2, retries=0)- async def remove_highlights(self):- """- Removes all highlight overlays and labels created by the highlightElement function.- Handles cases where the page might be closed or inaccessible.- """- page = await self.get_current_page()- try:- await page.evaluate(- """- try {- // Remove the highlight container and all its contents- const container = document.getElementById('playwright-highlight-container');- if (container) {- container.remove();- }-- // Remove highlight attributes from elements- const highlightedElements = document.querySelectorAll('[browser-user-highlight-id^="playwright-highlight-"]');- highlightedElements.forEach(el => {- el.removeAttribute('browser-user-highlight-id');- });- } catch (e) {- console.error('Failed to remove highlights:', e);- }- """- )- except Exception as e:- self.logger.debug(f'β οΈ Failed to remove highlights (this is usually ok): {type(e).__name__}: {e}')- # Don't raise the error since this is not critical functionality-- @observe_debug(ignore_output=True, name='get_dom_element_by_index')- @require_healthy_browser(usable_page=True, reopen_page=True)- async def get_dom_element_by_index(self, index: int) -> DOMElementNode | None:- """Get DOM element by index."""- selector_map = await self.get_selector_map()- return selector_map.get(index)-- @time_execution_async('--click_element_node')- @observe_debug(ignore_input=True, name='click_element_node')- @require_healthy_browser(usable_page=True, reopen_page=True)- async def _click_element_node(- self, element_node: DOMElementNode, expect_download: bool = False, new_tab: bool = False- ) -> str | None:- """- Optimized method to click an element using xpath with CDP fallbacks.-- Args:- element_node: The DOM element to click- expect_download: If True, wait for download and handle it inline- new_tab: If True, open any resulting navigation in a new tab-- Returns:- The download path if a download was triggered, None otherwise- """- page = await self.get_current_page()- try:- # Highlight before clicking- # if element_node.highlight_index is not None:- # await self._update_state(focus_element=element_node.highlight_index)-- element_handle = await self.get_locate_element(element_node)-- if element_handle is None:- self.logger.debug(f'Element: {repr(element_node)} not found')- raise Exception('Element not found')-- async def perform_click(click_func):- """Performs the actual click, handling both download and navigation scenarios."""-- # only wait the 5s extra for potential downloads if they are enabled- # TODO: instead of blocking for 5s, we should register a non-block page.on('download') event- # and then check if the download has been triggered within the event handler- if self.browser_profile.downloads_path:- try:- # Try short-timeout expect_download to detect a file download has been been triggered- async with page.expect_download(timeout=5_000) as download_info:- await click_func()- download = await download_info.value- # Determine file path- suggested_filename = download.suggested_filename- unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, suggested_filename)- download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)- await download.save_as(download_path)- self.logger.info(f'β¬οΈ Downloaded file to: {download_path}')-- # Downloads are tracked via the filesystem in the session's unique downloads directory- self.logger.info(f'π Download completed: {download_path}')-- return download_path- except Exception:- # If no download is triggered, treat as normal click- self.logger.debug('No download triggered within timeout. Checking navigation...')- try:- await page.wait_for_load_state()- except Exception as e:- self.logger.warning(- f'β οΈ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}'- )- # Navigation is handled by NavigationWatchdog via events- else:- # If downloads are disabled, just perform the click- await click_func()- try:- await page.wait_for_load_state()- except Exception as e:- self.logger.warning(- f'β οΈ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}'- )- # Navigation is handled by NavigationWatchdog via events-- try:- return await perform_click(lambda: element_handle and element_handle.click(timeout=1_500))- except URLNotAllowedError as e:- raise e- except Exception as e:- # Check if it's a context error and provide more info- if 'Cannot find context with specified id' in str(e) or 'Protocol error' in str(e):- self.logger.warning(f'β οΈ Element context lost, attempting to re-locate element: {type(e).__name__}')- # Try to re-locate the element- element_handle = await self.get_locate_element(element_node)- if element_handle is None:- raise Exception(f'Element no longer exists in DOM after context loss: {repr(element_node)}')- # Try click again with fresh element- try:- return await perform_click(lambda: element_handle.click(timeout=1_500))- except Exception:- # Fall back to JavaScript click- return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))- else:- # Original fallback for other errors- try:- return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))- except URLNotAllowedError as e:- raise e- except Exception as e:- # Final fallback - try clicking by coordinates if available- if element_node.absolute_position:- try:- center_x = element_node.absolute_position.x + element_node.absolute_position.width / 2- center_y = element_node.absolute_position.y + element_node.absolute_position.height / 2- self.logger.warning(- f'β οΈ Element click failed, falling back to coordinate click at ({center_x}, {center_y})'- )- await page.mouse.click(center_x, center_y)- try:- await page.wait_for_load_state()- except Exception:- pass- # Navigation is handled by NavigationWatchdog via events- return None # Success- except Exception as coord_e:- self.logger.error(f'Coordinate click also failed: {type(coord_e).__name__}: {coord_e}')- raise Exception(f'Failed to click element: {type(e).__name__}: {e}')-- except URLNotAllowedError as e:- raise e- except Exception as e:- raise Exception(f'Failed to click element. Error: {str(e)}')--- @retry(timeout=20, retries=1, semaphore_limit=1, semaphore_scope='self')- async def _set_viewport_size(self, page: Page, viewport: dict[str, int] | ViewportSize) -> None:- """Set viewport size with timeout protection."""- if isinstance(viewport, dict):- await page.set_viewport_size(ViewportSize(width=viewport['width'], height=viewport['height']))- else:- await page.set_viewport_size(viewport)-- @require_healthy_browser(usable_page=False, reopen_page=False)- async def get_cdp_client(self) -> Any:- """Get or create a CDP client for the current browser session."""- if not self.cdp_url:- raise ValueError('No CDP URL available for this browser session')-- # Import here to avoid circular imports- from browser_use.dom.service import DomService-- # Create a temporary DOM service to get CDP client- page = await self.get_current_page()- dom_service = DomService(self, page, logger=self.logger)- return await dom_service._get_cdp_client()-- async def get_current_page_cdp_session_id(self) -> str | None:- """Get the CDP session ID for the current page."""- # For now, return None to use the default session- # This can be enhanced later to handle frames- return None-- async def close_tab(self, tab_index: int | None = None) -> None:- assert self.browser_context is not None, 'BrowserContext is not set up'- pages = self.browser_context.pages- if not pages:- return-- if tab_index is None:- # to tab_index passed, just close the current agent page- page = await self.get_current_page()- else:- # otherwise close the tab at the given index- if tab_index >= len(pages) or tab_index < 0:- raise IndexError(f'Tab index {tab_index} out of range. Available tabs: {len(pages)}')- page = pages[tab_index]-- await page.close()-- # reset the self.agent_current_page and self.human_current_page references to first available tab- await self.get_current_page()-- # --- Page navigation ---- @observe_debug(ignore_input=True, ignore_output=True)- @retry(retries=0, timeout=30, wait=1, semaphore_timeout=10, semaphore_limit=1, semaphore_scope='self', semaphore_lax=True)- @require_healthy_browser(usable_page=False, reopen_page=False)- async def navigate(self, url: str = 'about:blank', new_tab: bool = False, timeout_ms: int | None = None) -> Page:- """- Universal navigation method that handles all navigation scenarios.-- Args:- url: URL to navigate to (defaults to 'about:blank')- new_tab: If True, creates a new tab for navigation-- Returns:- Page: The page that was navigated- """- # Clear loading status from previous page- self._current_page_loading_status = None-- # Normalize the URL- normalized_url = normalize_url(url)-- # URL checking is handled by NavigationWatchdog when processing NavigateToUrlEvent- # If timeout_ms is not None, use it (even if 0); else try profile.default_navigation_timeout (even if 0); else 12000- if timeout_ms is not None:- user_timeout_ms = int(timeout_ms)- elif self.browser_profile.default_navigation_timeout is not None:- user_timeout_ms = int(self.browser_profile.default_navigation_timeout)- else:- user_timeout_ms = 12000- timeout_ms = min(3000, user_timeout_ms)-- # Handle new tab creation- if new_tab:- # Create new tab- assert self.browser_context is not None, 'Browser context is not set'- self.agent_current_page = await self.browser_context.new_page()-- # Update human tab reference if there is no human tab yet- if (not self.human_current_page) or self.human_current_page.is_closed():- self.human_current_page = self.agent_current_page-- # Set viewport for new tab- if self.browser_profile.viewport:- await self.agent_current_page.set_viewport_size(self.browser_profile.viewport)-- page = self.agent_current_page- else:- # Use existing page- page = await self.get_current_page()-- # Navigate to URL- try:- # Use asyncio.wait to prevent hanging on a slow page loads- # Don't cap the timeout - respect what was requested- self.logger.debug(f'π§ Starting navigation to {_log_pretty_url(normalized_url)} with timeout {timeout_ms}ms')- nav_task = asyncio.create_task(page.goto(normalized_url, wait_until='load', timeout=timeout_ms))- done, pending = await asyncio.wait([nav_task], timeout=(timeout_ms + 500) / 1000)-- if nav_task in pending:- # Navigation timed out- self.logger.warning(- f"β οΈ Loading {_log_pretty_url(normalized_url)} didn't finish after {timeout_ms / 1000}s, continuing anyway..."- )- nav_task.cancel()- try:- await nav_task- except asyncio.CancelledError:- pass-- # Check if page is still usable after timeout- if page and not page.is_closed():- current_url = page.url- # self.logger.debug(f'π€ Checking responsiveness after navigation timeout (current URL: {current_url})')- is_responsive = await self._is_page_responsive(page, timeout=3.0)- if is_responsive:- self.logger.debug(- f'β Page is responsive and usable despite navigation loading timeout on: {_log_pretty_url(current_url)})'- )- else:- self.logger.error(- f'β Page is unresponsive after navigation stalled on: {_log_pretty_url(current_url)} WARNING! Subsequent operations will likely fail on this page, it must be reset...'- )- # Don't try complex recovery during navigate - just raise the error- # The retry decorator will handle retries, and other methods with- # @require_healthy_browser(reopen_page=True) will trigger proper recovery- raise RuntimeError(- f'Page JS engine is unresponsive after navigation / loading issue on: {_log_pretty_url(current_url)}). Agent cannot proceed with this page because its JS event loop is unresponsive.'- )- elif nav_task in done:- # Navigation completed, check if it succeeded- await nav_task # This will raise if navigation failed- except Exception as e:- if 'timeout' in str(e).lower():- # self.logger.warning(- # f"β οΈ Loading {_log_pretty_url(normalized_url)} didn't finish and further operations may fail on this page..."- # )- pass # allow agent to attempt to continue without raising hard error, it can use tools to work around it- else:- raise-- # Show DVD animation on new tab pages if no URL specified- if new_tab and is_new_tab_page(page.url):- # Navigate to about:blank if we're on chrome://new-tab-page to avoid security restrictions- if page.url.startswith('chrome://new-tab-page'):- try:- await page.goto('about:blank', wait_until='load', timeout=timeout_ms)- except Exception:- pass- await self._show_dvd_screensaver_loading_animation(page)-- return page-- # Fallback: return the first available page if browser context is ready- if self._browser_context and self._browser_context.pages:- return self._browser_context.pages[0]-- return None-- @property- def downloaded_files(self) -> list[str]:- """Get list of downloaded files from the downloads directory, sorted by date (newest first)."""- if not self.browser_profile.downloads_path:- return []-- downloads_dir = self.browser_profile.downloads_path- if not os.path.exists(downloads_dir):- return []-- # List all files in the downloads directory with their modification times- try:- files_with_time = []- for filename in os.listdir(downloads_dir):- filepath = os.path.join(downloads_dir, filename)- if os.path.isfile(filepath):- # Get modification time- mtime = os.path.getmtime(filepath)- files_with_time.append((filepath, mtime))-- # Sort by modification time (newest first)- files_with_time.sort(key=lambda x: x[1], reverse=True)-- # Return just the file paths- return [filepath for filepath, _ in files_with_time]- except Exception as e:- logger.warning(f'Failed to list downloaded files: {e}')- return []-- @property- def pages(self) -> list[Page]:- """Get all open pages."""- if self._browser_context:- return self._browser_context.pages- return []-- def get_page_by_tab_index(self, tab_index: int) -> Page | None:- """Get page by tab index."""- if 0 <= tab_index < len(self.pages):- return self.pages[tab_index]- return None-- def get_tab_index(self, page: Page) -> int:- """Get tab index for a page."""- if page in self.pages:- return self.pages.index(page)- return -1-- @property- def auto_download_pdfs(self) -> bool:- """Get current PDF auto-download setting."""- return self._auto_download_pdfs-- # @property- # def browser_extension_pages(self) -> list[Page]:- # if not self.browser_context:- # return []- # return [p for p in self.browser_context.pages if p.url.startswith('chrome-extension://')]-- # @property- # def saved_downloads(self) -> list[Path]:- # """- # Return a list of files in the downloads_path.- # """- # return list(Path(self.browser_profile.downloads_path).glob('*'))-- async def _wait_for_stable_network(self):- pending_requests = set()- last_activity = asyncio.get_event_loop().time()-- page = await self.get_current_page()-- # Define relevant resource types and content types- RELEVANT_RESOURCE_TYPES = {- 'document',- 'stylesheet',- 'image',- 'font',- 'script',- 'iframe',- }-- RELEVANT_CONTENT_TYPES = {- 'text/html',- 'text/css',- 'application/javascript',- 'image/',- 'font/',- 'application/json',- }-- # Additional patterns to filter out- IGNORED_URL_PATTERNS = {- # Analytics and tracking- 'analytics',- 'tracking',- 'telemetry',- 'beacon',- 'metrics',- # Ad-related- 'doubleclick',- 'adsystem',- 'adserver',- 'advertising',- # Social media widgets- 'facebook.com/plugins',- 'platform.twitter',- 'linkedin.com/embed',- # Live chat and support- 'livechat',- 'zendesk',- 'intercom',- 'crisp.chat',- 'hotjar',- # Push notifications- 'push-notifications',- 'onesignal',- 'pushwoosh',- # Background sync/heartbeat- 'heartbeat',- 'ping',- 'alive',- # WebRTC and streaming- 'webrtc',- 'rtmp://',- 'wss://',- # Common CDNs for dynamic content- 'cloudfront.net',- 'fastly.net',- }-- async def on_request(request):- # Filter by resource type- if request.resource_type not in RELEVANT_RESOURCE_TYPES:- return-- # Filter out streaming, websocket, and other real-time requests- if request.resource_type in {- 'websocket',- 'media',- 'eventsource',- 'manifest',- 'other',- }:- return-- # Filter out by URL patterns- url = request.url.lower()- if any(pattern in url for pattern in IGNORED_URL_PATTERNS):- return-- # Filter out data URLs and blob URLs- if url.startswith(('data:', 'blob:')):- return-- # Filter out requests with certain headers- headers = request.headers- if headers.get('purpose') == 'prefetch' or headers.get('sec-fetch-dest') in [- 'video',- 'audio',- ]:- return-- nonlocal last_activity- pending_requests.add(request)- last_activity = asyncio.get_event_loop().time()- # self.logger.debug(f'Request started: {request.url} ({request.resource_type})')-- async def on_response(response):- request = response.request- if request not in pending_requests:- return-- # Filter by content type if available- content_type = response.headers.get('content-type', '').lower()-- # Skip if content type indicates streaming or real-time data- if any(- t in content_type- for t in [- 'streaming',- 'video',- 'audio',- 'webm',- 'mp4',- 'event-stream',- 'websocket',- 'protobuf',- ]- ):- pending_requests.remove(request)- return-- # Only process relevant content types- if not any(ct in content_type for ct in RELEVANT_CONTENT_TYPES):- pending_requests.remove(request)- return-- # Skip if response is too large (likely not essential for page load)- content_length = response.headers.get('content-length')- if content_length and int(content_length) > 5 * 1024 * 1024: # 5MB- pending_requests.remove(request)- return-- nonlocal last_activity- pending_requests.remove(request)- last_activity = asyncio.get_event_loop().time()- # self.logger.debug(f'Request resolved: {request.url} ({content_type})')-- # Attach event listeners- page.on('request', on_request)- page.on('response', on_response)+ const originalAddEventListener = EventTarget.prototype.addEventListener;+ const eventListenersMap = new WeakMap();- now = asyncio.get_event_loop().time()- try:- # Wait for idle time- start_time = asyncio.get_event_loop().time()- while True:- await asyncio.sleep(0.1)- now = asyncio.get_event_loop().time()- if (- len(pending_requests) == 0- and (now - last_activity) >= self.browser_profile.wait_for_network_idle_page_load_time- ):- # Clear loading status when page loads successfully- self._current_page_loading_status = None- break- if now - start_time > self.browser_profile.maximum_wait_page_load_time:- self.logger.debug(- f'{self} Network timeout after {self.browser_profile.maximum_wait_page_load_time}s with {len(pending_requests)} '- f'pending requests: {[r.url for r in pending_requests]}'- )- # Set loading status for LLM to see- self._current_page_loading_status = f'Page loading was aborted after {self.browser_profile.maximum_wait_page_load_time}s with {len(pending_requests)} pending network requests. You may want to use the wait action to allow more time for the page to fully load.'- break+ EventTarget.prototype.addEventListener = function(type, listener, options) {+ if (typeof listener === "function") {+ let listeners = eventListenersMap.get(this);+ if (!listeners) {+ listeners = [];+ eventListenersMap.set(this, listeners);+ }- finally:- # Clean up event listeners- page.remove_listener('request', on_request)- page.remove_listener('response', on_response)+ listeners.push({+ type,+ listener,+ listenerPreview: listener.toString().slice(0, 100),+ options+ });+ }- elapsed = now - start_time- if elapsed > 1:- self.logger.debug(f'π€ Page network traffic calmed down after {now - start_time:.2f} seconds')+ return originalAddEventListener.call(this, type, listener, options);+ };- @observe_debug(ignore_input=True, ignore_output=True, name='wait_for_page_and_frames_load')- async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):- """- Ensures page is fully loaded and stable before continuing.- Waits for network idle, DOM stability, and minimum WAIT_TIME.- Also checks if the loaded URL is allowed.-- Parameters:- ------------ timeout_overwrite: float | None- Override the minimum wait time+ window.getEventListenersForNode = (node) => {+ const listeners = eventListenersMap.get(node) || [];+ return listeners.map(({ type, listenerPreview, options }) => ({+ type,+ listenerPreview,+ options+ }));+ };+ })();+ }"""- # Start timing- start_time = time.time()+ await self.browser_context.add_init_script(init_script)- # Wait for page load- page = await self.get_current_page()-- # Skip network waiting for new tab pages (about:blank, chrome://new-tab-page, etc.)- # These pages load instantly and don't need network idle time- if is_new_tab_page(page.url):- self.logger.debug(f'β‘ Skipping page load wait for new tab page: {page.url}')- return-- try:- await self._wait_for_stable_network()-- # URL checking is handled by NavigationWatchdog via events- except URLNotAllowedError as e:- raise e- except Exception as e:- self.logger.warning(- f'β οΈ Page load for {_log_pretty_url(page.url)} failed due to {type(e).__name__}, continuing anyway...'- )- # Calculate remaining time to meet minimum WAIT_TIME- elapsed = time.time() - start_time- remaining = max((timeout_overwrite or self.browser_profile.minimum_wait_page_load_time) - elapsed, 0)-- # Skip expensive performance API logging - can cause significant delays on complex pages- bytes_used = None+ @property+ async def target_ids(self) -> list[str]:+ """Get all open page target IDs using CDP."""try:- tab_idx = self.tabs.index(page)- except ValueError:- tab_idx = '??'-- extra_delay = ''- if remaining > 0:- extra_delay = f', waiting +{remaining:.2f}s for all frames to finish'+ pages = await self._cdp_get_all_pages()+ return [page['targetId'] for page in pages]+ except Exception:+ return []- if bytes_used is not None:- self.logger.info(- f'β‘οΈ Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} used {bytes_used / 1024:.1f} KB in {elapsed:.2f}s{extra_delay}'- )- else:- self.logger.info(- f'β‘οΈ Page navigation [{tab_idx}]{_log_pretty_url(page.url, 40)} completed in {elapsed:.2f}s{extra_delay}'- )+ async def get_target_id_by_tab_index(self, tab_index: int) -> str | None:+ """Get target ID by tab index."""+ target_ids = await self.target_ids+ if 0 <= tab_index < len(target_ids):+ return target_ids[tab_index]+ return None- async def navigate_to(self, url: str) -> Page:- """Navigate the current page to a URL."""- event = self.event_bus.dispatch(NavigateToUrlEvent(url=url))- await event- return await self.get_current_page()-- async def go_to_url(self, url: str) -> None:- """Alias for navigate_to."""- event = self.event_bus.dispatch(NavigateToUrlEvent(url=url))- await event-- async def go_back(self) -> None:- """Go back in the browser history."""- event = self.event_bus.dispatch(GoBackEvent())- await event-- async def go_forward(self) -> None:- """Go forward in the browser history."""- event = self.event_bus.dispatch(GoForwardEvent())- await event-- async def refresh(self) -> None:- """Refresh the current page."""- event = self.event_bus.dispatch(RefreshEvent())- await event-- async def take_screenshot(self, full_page: bool = False, clip: dict | None = None) -> str | None:- """Take a screenshot."""- return (- await self.event_bus.dispatch(ScreenshotEvent(full_page=full_page, clip=clip)).event_result() or {'screenshot': None}- )['screenshot'] or None-- async def click_element(self, index: int, expect_download: bool = False, new_tab: bool = False) -> None:- """Click element by index."""- event = self.event_bus.dispatch(ClickElementEvent(index=index, expect_download=expect_download, new_tab=new_tab))- await event-- async def input_text(self, index: int, text: str) -> None:- """Input text into element."""- event = self.event_bus.dispatch(TypeTextEvent(index=index, text=text))- await event-- async def scroll(- self, direction: Literal['up', 'down', 'left', 'right'], amount: int, element_index: int | None = None- ) -> None:- """Scroll the page or element."""- event = self.event_bus.dispatch(ScrollEvent(direction=direction, amount=amount, element_index=element_index))- await event-- async def wait(self, seconds: float = 3.0) -> None:- """Wait for specified seconds."""- event = self.event_bus.dispatch(WaitEvent(seconds=seconds))- await event-- async def send_keys(self, keys: str) -> None:- """Send keyboard keys/shortcuts."""- event = self.event_bus.dispatch(SendKeysEvent(keys=keys))- await event-- async def upload_file(self, element_index: int, file_path: str) -> None:- """Upload file to element."""- event = self.event_bus.dispatch(UploadFileEvent(element_index=element_index, file_path=file_path))- await event-- # Additional compatibility methods-- async def save_storage_state(self, path: str | None = None) -> None:- """Save browser storage state."""- # Use event-based approach- self.event_bus.dispatch(SaveStorageStateEvent(path=path))+ async def get_tab_index(self, target_id: str) -> int:+ """Get tab index for a target ID."""+ target_ids = await self.target_ids+ if target_id in target_ids:+ return target_ids.index(target_id)+ return -1async def get_tabs_info(self) -> list[TabInfo]:"""Get information about all open tabs using CDP for reliability."""tabs = []- for i, page in enumerate(self.pages):- if page.is_closed():- continue-++ # Get all page targets using CDP+ pages = await self._cdp_get_all_pages()+ cdp_client = await self.get_cdp_client()++ for i, page_target in enumerate(pages):+ target_id = page_target['targetId']+ url = page_target['url']+# Skip JS execution for chrome:// pages and new tab pages- if is_new_tab_page(page.url) or page.url.startswith('chrome://'):+ if is_new_tab_page(url) or url.startswith('chrome://'):# Use URL as title for chrome pages, or mark new tabs as unusable- if is_new_tab_page(page.url):+ if is_new_tab_page(url):title = 'ignore this tab and do not use it'else:# For chrome:// pages, use the URL itself as the title- title = page.url+ title = urlelse:# Normal pages - try to get title with CDP for reliabilitytry:- # Use CDP to get title with timeout- cdp_client = await self.get_cdp_client()- session_id = await self.get_current_page_cdp_session_id()+ # Attach to target and get session ID+ session = await cdp_client.send('Target.attachToTarget', {+ 'targetId': target_id,+ 'flatten': True+ })+ session_id = session['sessionId']# Use CDP to evaluate document.titletitle_result = await asyncio.wait_for(- cdp_client.send.Runtime.evaluate(- params={'expression': 'document.title'},+ cdp_client.send('Runtime.evaluate',+ {'expression': 'document.title'},session_id=session_id),timeout=2.0)title = title_result.get('result', {}).get('value', '')+ # Detach from target+ await cdp_client.send('Target.detachFromTarget', {'sessionId': session_id})+# Special handling for PDF pages- if (not title or title == '') and (page.url.endswith('.pdf') or 'pdf' in page.url):+ if (not title or title == '') and (url.endswith('.pdf') or 'pdf' in url):# PDF pages might not have a title, use URL filenametry:from urllib.parse import urlparse- filename = urlparse(page.url).path.split('/')[-1]+ filename = urlparse(url).path.split('/')[-1]if filename:title = filenameexcept Exception:@@ -2671,18 +507,18 @@ class BrowserSession(BaseModel):except Exception as e:# Page might be crashed or unresponsiveself.logger.debug(- f'β οΈ Failed to get tab info for tab #{i}: {_log_pretty_url(page.url)} - {type(e).__name__}'+ f'β οΈ Failed to get tab info for tab #{i}: {_log_pretty_url(url)} - {type(e).__name__}')# Only mark as unusable if it's actually a new tab page- if is_new_tab_page(page.url):+ if is_new_tab_page(url):title = 'ignore this tab and do not use it'else:# For crashed pages, close them as they're not usefultry:- await page.close()+ await self._cdp_close_page(target_id)self.logger.debug(- f'πͺ Force-closed page because it\'s unresponsive: {_log_pretty_url(page.url)}'+ f'πͺ Force-closed page because it\'s unresponsive: {_log_pretty_url(url)}')continueexcept Exception:@@ -2690,61 +526,19 @@ class BrowserSession(BaseModel):tab_info = TabInfo(page_id=i,- url=page.url,+ url=url,title=title,parent_page_id=None,- id=f'tab_{i}',+ id=target_id, # Use target ID as the unique identifierindex=i,)tabs.append(tab_info)return tabs# DOM element methods- async def get_browser_state_with_recovery(- self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = True- ) -> Any:- """Get browser state with multiple fallback strategies for error recovery-- Parameters:- ------------ cache_clickable_elements_hashes: bool- If True, cache the clickable elements hashes for the current state.- include_screenshot: bool- If True, include screenshot in the state summary. Set to False to improve performance- when screenshots are not needed (e.g., in multi_act element validation).- """-- updated_state = await self._get_updated_state(include_screenshot=include_screenshot)-- # Find out which elements are new- # Do this only if url has not changed- if cache_clickable_elements_hashes:- # Lazy import heavy DOM service- from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor-- # if we are on the same url as the last state, we can use the cached hashes- if self._cached_clickable_element_hashes and self._cached_clickable_element_hashes.url == updated_state.url:- # Pointers, feel free to edit in place- updated_state_clickable_elements = ClickableElementProcessor.get_clickable_elements(updated_state.element_tree)-- for dom_element in updated_state_clickable_elements:- dom_element.is_new = (- ClickableElementProcessor.hash_dom_element(dom_element)- not in self._cached_clickable_element_hashes.hashes # see which elements are new from the last state where we cached the hashes- )- # in any case, we need to cache the new hashes- self._cached_clickable_element_hashes = CachedClickableElementHashes(- url=updated_state.url,- hashes=ClickableElementProcessor.get_clickable_elements_hashes(updated_state.element_tree),- )-- assert updated_state- self._cached_browser_state_summary = updated_state-- return self._cached_browser_state_summary+ # Removed duplicate get_browser_state_with_recovery - using the decorated version below@observe_debug(ignore_input=True, ignore_output=True, name='get_minimal_state_summary')- @require_healthy_browser(usable_page=True, reopen_page=True)@time_execution_async('--get_minimal_state_summary')async def get_minimal_state_summary(self) -> BrowserStateSummary:"""Get basic page info without DOM processing, but try to capture screenshot"""@@ -2884,22 +678,25 @@ class BrowserSession(BaseModel):self.logger.debug(f'PDF auto-download check failed: {type(e).__name__}: {e}')self.logger.debug('π³ Starting DOM processing...')- from browser_use.dom.service import DomService+ from browser_use.browser.events import BuildDOMTreeEvent+ from browser_use.dom.views import SerializedDOMState- dom_service = DomService(self, page, logger=self.logger)try:- content, _ = await asyncio.wait_for(- dom_service.get_serialized_dom_tree(),+ # Use the DOMWatchdog via event bus+ result = await asyncio.wait_for(+ self.event_bus.dispatch(BuildDOMTreeEvent(previous_state=None)),timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages)+ content = await result.event_result()self.logger.debug('β DOM processing completed')- except TimeoutError:- self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')+ except (TimeoutError, Exception) as e:+ if isinstance(e, TimeoutError):+ self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')+ else:+ self.logger.warning(f'DOM processing failed: {e}')self.logger.warning('π Falling back to minimal DOM state to allow basic navigation...')# Create minimal DOM state for basic navigation- from browser_use.dom.views import SerializedDOMState-content = SerializedDOMState(_root=None, # No simplified tree for minimal stateselector_map={}, # Empty selector map@@ -2914,7 +711,7 @@ class BrowserSession(BaseModel):# unfortunately too buggy for now, too many sites use invisible cross-origin iframes for ads, tracking, youtube videos, social media, etc.# and it distracts the bot by opening a lot of new tabs# iframe_urls = await dom_service.get_cross_origin_iframes()- # outer_page = self.agent_current_page+ # outer_page = self.current_target_id# for url in iframe_urls:# if url in [tab.url for tab in tabs_info]:# continue # skip if the iframe if we already have it open in a tab@@ -2989,1107 +786,208 @@ class BrowserSession(BaseModel):return self.browser_state_summaryraise- # region - Page Health Check Helpers- @observe_debug(ignore_input=True)- async def _is_page_responsive(self, page: Page, timeout: float = 5.0) -> bool:- """Check if a page is responsive by trying to evaluate simple JavaScript."""- eval_task = None- try:- eval_task = asyncio.create_task(page.evaluate('1'))- done, pending = await asyncio.wait([eval_task], timeout=timeout)-- if eval_task in done:- try:- await eval_task # This will raise if the evaluation failed- return True- except Exception:- return False- else:- # Timeout - the page is unresponsive- return False- except Exception:- return False- finally:- # Always clean up the eval task- if eval_task and not eval_task.done():- eval_task.cancel()- try:- await eval_task- except (asyncio.CancelledError, Exception):- pass-- async def _force_close_page_via_cdp(self, page_url: str) -> bool:- """Force close a crashed page using CDP from a clean temporary page."""- try:- # self.logger.info('π¨ Creating temporary page for CDP force-close...')-- # Create a clean page for CDP operations- assert self.browser_context, 'Browser context is not set up yet'- temp_page = await asyncio.wait_for(self.browser_context.new_page(), timeout=5.0)- await asyncio.wait_for(temp_page.goto('about:blank'), timeout=2.0)-- # Create CDP session from the clean page- cdp_session = await asyncio.wait_for(self.browser_context.new_cdp_session(temp_page), timeout=5.0) # type: ignore-- try:- # Get all browser targets- targets = await asyncio.wait_for(cdp_session.send('Target.getTargets'), timeout=2.0)-- # Find the crashed page target- blocked_target_id = None- for target in targets.get('targetInfos', []):- if target.get('type') == 'page' and target.get('url') == page_url:- blocked_target_id = target.get('targetId')- # self.logger.debug(f'Found target to close: {page_url}')- break-- if blocked_target_id:- # Force close the target- self.logger.warning(- f'πͺ Force-closing crashed page target_id={blocked_target_id} via CDP: {_log_pretty_url(page_url)}...'- )- await asyncio.wait_for(cdp_session.send('Target.closeTarget', {'targetId': blocked_target_id}), timeout=2.0)- # self.logger.debug(f'β οΈ Successfully force-closed crashed page target_id={blocked_target_id} via CDP: {_log_pretty_url(page_url)}')- return True- else:- self.logger.debug(- f'β Could not find CDP page target_id to force-close: {_log_pretty_url(page_url)} (concurrency issues?)'- )- return False-- finally:- # Clean up- try:- await asyncio.wait_for(cdp_session.detach(), timeout=1.0)- except Exception:- pass- await temp_page.close()-- except Exception as e:- self.logger.error(f'β Using raw CDP to force-close crashed page failed: {type(e).__name__}: {e}')- return False-- # Removed duplicate get_locate_element - using the properly typed version below-- @observe_debug(ignore_input=True, name='recover_unresponsive_page')- async def _recover_unresponsive_page(self, calling_method: str, timeout_ms: int | None = None) -> None:- """Recover from an unresponsive page by closing and reopening it."""- self.logger.warning(f'β οΈ Page JS engine became unresponsive in {calling_method}(), attempting recovery...')- timeout_ms = min(3000, int(timeout_ms or self.browser_profile.default_navigation_timeout or 5000))-- # Check if browser process is still alive before attempting recovery- if self.browser_pid:- try:- import psutil-- proc = psutil.Process(self.browser_pid)- if proc.status() in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD):- self.logger.error(f'β Browser process {self.browser_pid} has crashed and cannot be recovered')- raise RuntimeError('Browser process has crashed - cannot recover unresponsive page')- except psutil.NoSuchProcess:- self.logger.error(f'β Browser process {self.browser_pid} no longer exists')- raise RuntimeError('Browser process has crashed - cannot recover unresponsive page')-- # Check if browser connection is still alive- if self.browser and not self.browser.is_connected():- self.logger.error('β Browser connection lost - browser process may have crashed')- raise RuntimeError('Browser connection lost - cannot recover unresponsive page')-- # Prevent re-entrance- self._in_recovery = True- try:- # Get current URL before recovery- assert self.agent_current_page, 'Agent current page is not set'- current_url = self.agent_current_page.url- # self.logger.debug(f'Current URL: {current_url}')-- # Clear page references- blocked_page = self.agent_current_page- self.agent_current_page = None- if blocked_page == self.human_current_page:- self.human_current_page = None-- # Force-close the crashed page via CDP- self.logger.debug('πͺ Page Recovery Step 1/3: Force-closing crashed page via CDP...')- await self._force_close_page_via_cdp(current_url)-- # Remove the closed page from browser_context.pages by forcing a refresh- # This prevents TargetClosedError when iterating through pages later- if self.browser_context and self.browser_context.pages:- # Additional cleanup: close any page objects that have the same url as the crashed page- # (could close too many pages by accident if we have a few different tabs on the same URL)- # Sometimes playwright doesn't immediately remove force-closed pages from the list- for page in self.browser_context.pages[:]: # Use slice to avoid modifying list during iteration- if page.url == current_url and not page.is_closed() and not is_new_tab_page(page.url):- try:- # Try to close it via playwright as well- await page.close()- self.logger.debug(- f'πͺ Closed π {str(id(page))[-2:]} because it has a known crash-causing URL: {_log_pretty_url(page.url)}'- )- except Exception:- pass # Page might already be closed via CDP-- # Try to reopen the URL (in case blocking was transient)- self.logger.debug('πΌ Page Recovery Step 2/3: Trying to reopen the URL again...')- if await self._try_reopen_url(current_url, timeout_ms=timeout_ms):- self.logger.debug('β Page Recovery Step 3/3: Page loading succeeded after 2nd attempt!')- return # Success!- # If that failed, fall back to blank page- self.logger.debug(- 'β Page Recovery Step 3/3: Loading the page a 2nd time failed as well, browser seems unable to load this URL without getting stuck, retreating to a safe page...'- )- await self._create_blank_fallback_page(current_url)-- finally:- # Always clear recovery flag- self._in_recovery = False-- # region - Browser Actions- @observe_debug(name='take_screenshot', ignore_output=True)- @retry(- retries=1, # try up to 1 time to take the screenshot (2 total attempts)- timeout=30, # allow up to 30s for each attempt (includes recovery time)- wait=1, # wait 1s between each attempt- # semaphore_limit=2, # Allow 2 screenshots at a time to better utilize resources- # semaphore_name='screenshot_global',- # semaphore_scope='multiprocess',- # semaphore_lax=True, # Continue without semaphore if it can't be acquired- # semaphore_timeout=15, # Wait up to 15s for semaphore acquisition- )- @require_healthy_browser(usable_page=True, reopen_page=True)- @time_execution_async('--take_screenshot')- async def take_screenshot(self, full_page: bool = False) -> str | None:- """- Returns a base64 encoded screenshot of the current page using CDP.-- The decorator order ensures:- 1. @retry runs first (outer decorator)- 2. @require_healthy_browser runs on each retry attempt- 3. Page responsiveness is checked before each screenshot attempt- 4. If page is unresponsive, it's recovered and the method is retried- """- assert self.agent_current_page is not None, 'Agent current page is not set'- assert self.browser_context, 'Browser context is not set'-- page = self.agent_current_page-- if is_new_tab_page(page.url):- self.logger.warning(- f'β«οΈ Sending LLM 4px placeholder instead of real screenshot of: {_log_pretty_url(page.url)} (page empty)'- )- # not an exception because there's no point in retrying if we hit this, its always pointless to screenshot about:blank- # raise ValueError('Refusing to take unneeded screenshot of empty new tab page')- # return a 4px*4px white png to avoid wasting tokens - instead of 1px*1px white png that was- return PLACEHOLDER_4PX_SCREENSHOT-- # Always bring page to front before rendering, otherwise it crashes in some cases, not sure why- try:- await page.bring_to_front()- except Exception:- pass-- # Take screenshot using CDP to get around playwright's unnecessary slowness and weird behavior- cdp_session = None- try:- # Create CDP session for the screenshot- self.logger.debug(- f'πΈ Taking viewport-only PNG screenshot of page via fresh CDP session: {_log_pretty_url(page.url)}'- )- cdp_session = await self.browser_context.new_cdp_session(page) # type: ignore-- # Capture screenshot via CDP- screenshot_response = await cdp_session.send(- 'Page.captureScreenshot',- {- 'captureBeyondViewport': False,- 'fromSurface': True,- 'format': 'png',- },- )-- screenshot_b64 = screenshot_response.get('data')- if not screenshot_b64:- raise Exception(- f'CDP returned empty screenshot data for page {_log_pretty_url(page.url)}? (expected png base64)'- ) # have never seen this happen in practice+ # ========== CDP Helper Methods ==========- return screenshot_b64+ async def get_cdp_client(self) -> Any:+ """Get the CDP client, creating it if necessary."""+ if not hasattr(self, '_cdp_client') or self._cdp_client is None:+ if not self.cdp_url:+ raise ValueError('CDP URL is not set')++ # Import cdp-use client+ import httpx+ from cdp_use import CDPClient++ # Convert HTTP URL to WebSocket URL if needed+ ws_url = self.cdp_url+ if not ws_url.startswith('ws'):+ # If it's an HTTP URL, fetch the WebSocket URL from /json/version endpoint+ url = ws_url.rstrip('/')+ if not url.endswith('/json/version'):+ url = url + '/json/version'+ async with httpx.AsyncClient() as client:+ version_info = await client.get(url)+ ws_url = version_info.json()['webSocketDebuggerUrl']++ self._cdp_client = CDPClient(ws_url)+ await self._cdp_client.start()++ return self._cdp_client- except Exception as err:- error_str = f'{type(err).__name__}: {err}'- if 'timeout' in error_str.lower():- self.logger.warning(f'β±οΈ Screenshot timed out on page {_log_pretty_url(page.url)} (possibly crashed): {error_str}')- else:- self.logger.error(f'β Screenshot failed on page {_log_pretty_url(page.url)} (possibly crashed): {error_str}')- raise- finally:- if cdp_session:- try:- await asyncio.wait_for(cdp_session.detach(), timeout=1.0)- except Exception:- pass-- # region - User Actions-- @staticmethod- async def _get_unique_filename(directory: str | Path, filename: str) -> str:- """Generate a unique filename for downloads by appending (1), (2), etc., if a file already exists."""- base, ext = os.path.splitext(filename)- counter = 1- new_filename = filename- while os.path.exists(os.path.join(directory, new_filename)):- new_filename = f'{base} ({counter}){ext}'- counter += 1- return new_filename-- async def _start_context_tracing(self):- """Start tracing on browser context if trace_path is configured."""- # TEMPORARILY DISABLED: Trace recording causing test timeouts- # if self.browser_profile.traces_dir and self.browser_context:- # try:- # self.logger.debug(f'π½οΈ Starting tracing (will save to: {self.browser_profile.traces_dir})')- # # Don't pass any path to start() - let Playwright handle internal temp files- # await self.browser_context.tracing.start(- # screenshots=True,- # snapshots=True,- # sources=False, # Reduce trace size- # )- # except Exception as e:- # self.logger.warning(f'Failed to start tracing: {e}')-- @staticmethod- def _convert_simple_xpath_to_css_selector(xpath: str) -> str:- """Converts simple XPath expressions to CSS selectors."""- if not xpath:- return ''-- # Remove leading slash if present- xpath = xpath.lstrip('/')-- # Split into parts- parts = xpath.split('/')- css_parts = []-- for part in parts:- if not part:- continue-- # Handle custom elements with colons by escaping them- if ':' in part and '[' not in part:- base_part = part.replace(':', r'\:')- css_parts.append(base_part)- continue-- # Handle index notation [n]- if '[' in part:- base_part = part[: part.find('[')]- # Handle custom elements with colons in the base part- if ':' in base_part:- base_part = base_part.replace(':', r'\:')- index_part = part[part.find('[') :]-- # Handle multiple indices- indices = [i.strip('[]') for i in index_part.split(']')[:-1]]-- for idx in indices:- try:- # Handle numeric indices- if idx.isdigit():- index = int(idx) - 1- base_part += f':nth-of-type({index + 1})'- # Handle last() function- elif idx == 'last()':- base_part += ':last-of-type'- # Handle position() functions- elif 'position()' in idx:- if '>1' in idx:- base_part += ':nth-of-type(n+2)'- except ValueError:- continue-- css_parts.append(base_part)- else:- css_parts.append(part)+ async def get_current_page_cdp_session_id(self) -> str | None:+ """Get the CDP session ID for the current page."""+ if not hasattr(self, 'current_target_id') or not self.current_target_id:+ return None++ cdp_client = await self.get_cdp_client()++ # Attach to the current target and get session ID+ session = await cdp_client.send.Target.attachToTarget(+ params={'targetId': self.current_target_id, 'flatten': True}+ )+ return session['sessionId']- base_selector = ' > '.join(css_parts)- return base_selector+ async def get_current_page(self) -> Any:+ """Get the current active page."""+ if hasattr(self, '_browser_context') and self._browser_context:+ pages = self._browser_context.pages+ if pages:+ return pages[-1] # Return the last (most recent) page+ raise ValueError('No active page available')- @classmethod- @time_execution_sync('--enhanced_css_selector_for_element')- def _enhanced_css_selector_for_element(cls, element: DOMElementNode, include_dynamic_attributes: bool = True) -> str:- """- Creates a CSS selector for a DOM element, handling various edge cases and special characters.+ # ========== DOM Helper Methods ==========+ async def get_dom_element_by_index(self, index: int) -> Any | None:+ """Get DOM element by index from the DOM watchdog.+Args:- element: The DOM element to create a selector for-+ index: The element index from the serialized DOM+Returns:- A valid CSS selector string- """- try:- import re-- # Get base selector from XPath- css_selector = cls._convert_simple_xpath_to_css_selector(element.xpath)-- # Handle class attributes- if 'class' in element.attributes and element.attributes['class'] and include_dynamic_attributes:- # Define a regex pattern for valid class names in CSS- valid_class_name_pattern = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_-]*$')-- # Iterate through the class attribute values- classes = element.attributes['class'].split()- for class_name in classes:- # Skip empty class names- if not class_name.strip():- continue-- # Check if the class name is valid- if valid_class_name_pattern.match(class_name):- # Append the valid class name to the CSS selector- css_selector += f'.{class_name}'- else:- # Skip invalid class names- continue-- # Expanded set of safe attributes that are stable and useful for selection- SAFE_ATTRIBUTES = {- # Data attributes (if they're stable in your application)- 'id',- # Standard HTML attributes- 'name',- 'type',- 'placeholder',- # Accessibility attributes- 'aria-label',- 'aria-labelledby',- 'aria-describedby',- 'role',- # Common form attributes- 'for',- 'autocomplete',- 'required',- 'readonly',- # Media attributes- 'alt',- 'title',- 'src',- # Custom stable attributes (add any application-specific ones)- 'href',- 'target',- }-- if include_dynamic_attributes:- dynamic_attributes = {- 'data-id',- 'data-qa',- 'data-cy',- 'data-testid',- }- SAFE_ATTRIBUTES.update(dynamic_attributes)-- # Handle other attributes- for attribute, value in element.attributes.items():- if attribute == 'class':- continue-- # Skip invalid attribute names- if not attribute.strip():- continue-- if attribute not in SAFE_ATTRIBUTES:- continue-- # Escape special characters in attribute names- safe_attribute = attribute.replace(':', r'\:')-- # Handle different value cases- if value == '':- css_selector += f'[{safe_attribute}]'- elif any(char in value for char in '"\'<>`\n\r\t'):- # Use contains for values with special characters- # For newline-containing text, only use the part before the newline- if '\n' in value:- value = value.split('\n')[0]- # Regex-substitute *any* whitespace with a single space, then strip.- collapsed_value = re.sub(r'\s+', ' ', value).strip()- # Escape embedded double-quotes.- safe_value = collapsed_value.replace('"', '\\"')-- # if safe_value is empty, don't add it to the selector (could be empty after the filters)- if safe_value:- css_selector += f'[{safe_attribute}*="{safe_value}"]'- else:- css_selector += f'[{safe_attribute}="{value}"]'-- return css_selector- except Exception:- # Fallback to a more basic selector if something goes wrong- tag_name = element.tag_name or '*'- return f'{tag_name}'-- @require_healthy_browser(usable_page=True, reopen_page=True)- @time_execution_async('--is_visible')- async def _is_visible(self, element: ElementHandle) -> bool:+ EnhancedDOMTreeNode or None if index not found"""- Checks if an element is visible on the page.- We use our own implementation instead of relying solely on Playwright's is_visible() because- of edge cases with CSS frameworks like Tailwind. When elements use Tailwind's 'hidden' class,- the computed style may return display as '' (empty string) instead of 'none', causing Playwright- to incorrectly consider hidden elements as visible. By additionally checking the bounding box- dimensions, we catch elements that have zero width/height regardless of how they were hidden.- """- is_hidden = await element.is_hidden()- bbox = await element.bounding_box()-- return not is_hidden and bbox is not None and bbox['width'] > 0 and bbox['height'] > 0-- @require_healthy_browser(usable_page=True, reopen_page=True)- @time_execution_async('--get_locate_element')- @observe_debug(ignore_input=True, name='get_locate_element')- async def get_locate_element(self, element: DOMElementNode) -> ElementHandle | None:- page = await self.get_current_page()- current_frame = page-- # Start with the target element and collect all parents- parents: list[DOMElementNode] = []- current = element- while current.parent is not None:- parent = current.parent- parents.append(parent)- current = parent-- # Reverse the parents list to process from top to bottom- parents.reverse()-- # Process all iframe parents in sequence- iframes = [item for item in parents if item.tag_name == 'iframe']- for parent in iframes:- css_selector = self._enhanced_css_selector_for_element(- parent,- include_dynamic_attributes=self.browser_profile.include_dynamic_attributes,- )- # Use CSS selector if available, otherwise fall back to XPath- if css_selector:- current_frame = current_frame.frame_locator(css_selector)- else:- self.logger.debug(f'Using XPath for iframe: {parent.xpath}')- current_frame = current_frame.frame_locator(f'xpath={parent.xpath}')-- css_selector = self._enhanced_css_selector_for_element(- element, include_dynamic_attributes=self.browser_profile.include_dynamic_attributes- )-- try:- if isinstance(current_frame, FrameLocator):- if css_selector:- element_handle = await current_frame.locator(css_selector).element_handle()- else:- # Fall back to XPath when CSS selector is empty- self.logger.debug(f'CSS selector empty, falling back to XPath: {element.xpath}')- element_handle = await current_frame.locator(f'xpath={element.xpath}').element_handle()- return element_handle- else:- # Try CSS selector first if available- if css_selector:- element_handle = await current_frame.query_selector(css_selector)- else:- # Fall back to XPath- self.logger.debug(f'CSS selector empty, falling back to XPath: {element.xpath}')- element_handle = await current_frame.locator(f'xpath={element.xpath}').element_handle()- if element_handle:- is_visible = await self._is_visible(element_handle)- if is_visible:- await element_handle.scroll_into_view_if_needed(timeout=1_000)- return element_handle- return None- except Exception as e:- # If CSS selector failed, try XPath as fallback- if css_selector and 'CSS.escape' not in str(e):- try:- self.logger.debug(f'CSS selector failed, trying XPath fallback: {element.xpath}')- if isinstance(current_frame, FrameLocator):- element_handle = await current_frame.locator(f'xpath={element.xpath}').element_handle()- else:- element_handle = await current_frame.locator(f'xpath={element.xpath}').element_handle()-- if element_handle:- is_visible = await self._is_visible(element_handle)- if is_visible:- await element_handle.scroll_into_view_if_needed(timeout=1_000)- return element_handle- except Exception as xpath_e:- self.logger.error(- f'β Failed to locate element with both CSS ({css_selector}) and XPath ({element.xpath}): {type(xpath_e).__name__}: {xpath_e}'- )- return None- else:- self.logger.error(f'Failed to locate element: {type(e).__name__}: {e}')- return None-- async def _click_element_node_compat(self, element: Any, expect_download: bool = False, new_tab: bool = False) -> str | None:- """Click an element node and handle potential downloads.-- DEPRECATED: This is a compatibility method. Use the event-based approach instead.+ if self._dom_watchdog:+ return await self._dom_watchdog.get_element_by_index(index)+ return None+ def is_file_input(self, element: Any) -> bool:+ """Check if element is a file input.+Args:- element: The DOM element to click- expect_download: If True, wait for download and handle it inline. If False, let page-level handler catch it.- new_tab: If True, open any resulting navigation in a new tab.-- Returns the download path if a download was triggered, None otherwise.- """- if not element:- raise ValueError('No element provided to click')-- # This method is deprecated - clicking is now handled by DefaultActionWatchdog- raise NotImplementedError(- '_click_element_node is deprecated. Use click_element() which dispatches ClickElementEvent instead.'- )-- @require_healthy_browser(usable_page=True, reopen_page=True)- @time_execution_async('--input_text_element_node')- @observe_debug(ignore_input=True, name='input_text_element_node')- async def _input_text_element_node(self, element_node: DOMElementNode, text: str):- """- Input text into an element with proper error handling and state management.- Handles different types of input fields and ensures proper element state before input.+ element: The DOM element to check++ Returns:+ True if element is a file input, False otherwise"""- try:- element_handle = await self.get_locate_element(element_node)-- if element_handle is None:- raise BrowserError(f'Element: {repr(element_node)} not found')-- # Ensure element is ready for input- try:- await element_handle.wait_for_element_state('stable', timeout=1_000)- is_visible = await self._is_visible(element_handle)- if is_visible:- await element_handle.scroll_into_view_if_needed(timeout=1_000)- except Exception:- pass-- # let's first try to click and type- try:- await element_handle.evaluate('el => {el.textContent = ""; el.value = "";}')- await element_handle.click(timeout=2_000) # Add 2 second timeout- await asyncio.sleep(0.1) # Increased sleep time- page = await self.get_current_page()- await page.keyboard.type(text)- return- except Exception as e:- self.logger.debug(f'Input text with click and type failed, trying element handle method: {e}')- pass-- # Get element properties to determine input method- tag_handle = await element_handle.get_property('tagName')- tag_name = (await tag_handle.json_value()).lower()- is_contenteditable = await element_handle.get_property('isContentEditable')- readonly_handle = await element_handle.get_property('readOnly')- disabled_handle = await element_handle.get_property('disabled')-- readonly = await readonly_handle.json_value() if readonly_handle else False- disabled = await disabled_handle.json_value() if disabled_handle else False-- try:- if (await is_contenteditable.json_value() or tag_name == 'input') and not (readonly or disabled):- await element_handle.evaluate('el => {el.textContent = ""; el.value = "";}')- await element_handle.type(text, delay=5, timeout=5_000) # Add 5 second timeout- else:- # Try fill() first for supported elements- try:- await element_handle.fill(text, timeout=3_000) # Add 3 second timeout- except Exception as fill_error:- # If fill() fails because element doesn't support it, try type() instead- if 'not an <input>, <textarea>, <select>' in str(fill_error):- self.logger.debug(f'Element does not support fill(), using type() instead: {fill_error}')- await element_handle.evaluate('el => {el.textContent = ""; el.value = "";}')- await element_handle.type(text, delay=5, timeout=5_000)- else:- raise- except Exception as e:- self.logger.error(f'Error during input text into element: {type(e).__name__}: {e}')- raise BrowserError(f'Failed to input text into element: {repr(element_node)}')-- except Exception as e:- # Get current page URL safely for error message- try:- page = await self.get_current_page()- page_url = _log_pretty_url(page.url)- except Exception:- page_url = 'unknown page'-- self.logger.debug(- f'β Failed to input text into element: {repr(element_node)} on page {page_url}: {type(e).__name__}: {e}'- )- raise BrowserError(f'Failed to input text into element: {element_node.tag_name}')-- @require_healthy_browser(usable_page=True, reopen_page=True)- @time_execution_async('--switch_to_tab')- async def switch_to_tab(self, page_id: int) -> Page:- """Switch to a specific tab by its page_id (aka tab index exposed to LLM)"""- assert self.browser_context is not None, 'Browser context is not set'- pages = self.browser_context.pages-- if page_id >= len(pages):- raise BrowserError(f'No tab found with page_id: {page_id}')-- page = pages[page_id]-- # Check if the tab's URL is allowed before switching- if self._navigation_watchdog and not self._navigation_watchdog._is_url_allowed(page.url):- raise BrowserError(f'Cannot switch to tab with non-allowed URL: {page.url}')-- # Update both tab references - agent wants this tab, and it's now in the foreground- self.agent_current_page = page- await self.agent_current_page.bring_to_front() # crucial for screenshot to work-- # in order for a human watching to be able to follow along with what the agent is doing- # update the human's active tab to match the agent's- if self.human_current_page != page:- # TODO: figure out how to do this without bringing the entire window to the foreground and stealing foreground app focus- # might require browser-use extension loaded into the browser so we can use chrome.tabs extension APIs- # await page.bring_to_front()- pass-- self.human_current_page = page-- # Invalidate cached state since we've switched to a different tab- # The cached state contains DOM elements and selector map from the previous tab- self._cached_browser_state_summary = None- self._cached_clickable_element_hashes = None-- try:- await page.wait_for_load_state()- except Exception as e:- self.logger.warning(f'β οΈ New page failed to fully load: {type(e).__name__}: {e}')-- # Set the viewport size for the tab- if self.browser_profile.viewport:- await page.set_viewport_size(self.browser_profile.viewport)-- return page-- # region - Helper methods for easier access to the DOM- @observe_debug(name='get_selector_map', ignore_output=True, ignore_input=True)- @require_healthy_browser(usable_page=True, reopen_page=True)- async def get_selector_map(self) -> SelectorMap:- if self._cached_browser_state_summary is None:- return {}- return self._cached_browser_state_summary.selector_map-- @observe_debug(ignore_input=True, ignore_output=True, name='get_element_by_index')- @require_healthy_browser(usable_page=True, reopen_page=True)- async def get_element_by_index(self, index: int) -> ElementHandle | None:- selector_map = await self.get_selector_map()- element_handle = await self.get_locate_element(selector_map[index])- return element_handle-- @observe_debug(ignore_input=True, ignore_output=True, name='is_file_input_by_index')- async def is_file_input_by_index(self, index: int) -> bool:- try:- selector_map = await self.get_selector_map()- node = selector_map[index]- return self.is_file_input(node)- except Exception as e:- self.logger.debug(f'β Error in is_file_input(index={index}): {type(e).__name__}: {e}')- return False-- @staticmethod- def is_file_input(node: DOMElementNode) -> bool:+ if self._dom_watchdog:+ return self._dom_watchdog.is_file_input(element)+ # Fallback if watchdog not availablereturn (- isinstance(node, DOMElementNode)- and getattr(node, 'tag_name', '').lower() == 'input'- and node.attributes.get('type', '').lower() == 'file'- )-- @require_healthy_browser(usable_page=True, reopen_page=True)- async def find_file_upload_element_by_index(- self, index: int, max_height: int = 3, max_descendant_depth: int = 3- ) -> DOMElementNode | None:- """- Find the closest file input to the selected element by traversing the DOM bottom-up.- At each level (up to max_height ancestors):- - Check the current node itself- - Check all its children/descendants up to max_descendant_depth- - Check all siblings (and their descendants up to max_descendant_depth)- Returns the first file input found, or None if not found.- """- try:- selector_map = await self.get_selector_map()- if index not in selector_map:- return None-- candidate_element = selector_map[index]-- def find_file_input_in_descendants(node: DOMElementNode, depth: int) -> DOMElementNode | None:- if depth < 0 or not isinstance(node, DOMElementNode):- return None- if self.is_file_input(node):- return node- for child in getattr(node, 'children', []):- result = find_file_input_in_descendants(child, depth - 1)- if result:- return result- return None-- current = candidate_element- for _ in range(max_height + 1): # include the candidate itself- # 1. Check the current node itself- if self.is_file_input(current):- return current- # 2. Check all descendants of the current node- result = find_file_input_in_descendants(current, max_descendant_depth)- if result:- return result- # 3. Check all siblings and their descendants- parent = getattr(current, 'parent', None)- if parent:- for sibling in getattr(parent, 'children', []):- if sibling is current:- continue- if self.is_file_input(sibling):- return sibling- result = find_file_input_in_descendants(sibling, max_descendant_depth)- if result:- return result- current = parent- if not current:- break- return None- except Exception as e:- page = await self.get_current_page()- self.logger.debug(- f'β Error in find_file_upload_element_by_index(index={index}) on page {_log_pretty_url(page.url)}: {type(e).__name__}: {e}'- )- return None-- @require_healthy_browser(usable_page=True, reopen_page=True)- async def get_scroll_info(self, page: Page) -> tuple[int, int]:- """Get scroll position information for the current page."""- scroll_y = await page.evaluate('window.scrollY')- viewport_height = await page.evaluate('window.innerHeight')- total_height = await page.evaluate('document.documentElement.scrollHeight')- # Convert to int to handle fractional pixels- pixels_above = int(scroll_y)- pixels_below = int(max(0, total_height - (scroll_y + viewport_height)))- return pixels_above, pixels_below-- @require_healthy_browser(usable_page=True, reopen_page=True)- async def get_page_info(self, page: Page) -> PageInfo:- """Get comprehensive page size and scroll information."""- # Get all page dimensions and scroll info in one JavaScript call for efficiency- page_data = await page.evaluate("""() => {- return {- // Current viewport dimensions- viewport_width: window.innerWidth,- viewport_height: window.innerHeight,-- // Total page dimensions- page_width: Math.max(- document.documentElement.scrollWidth,- document.body.scrollWidth || 0- ),- page_height: Math.max(- document.documentElement.scrollHeight,- document.body.scrollHeight || 0- ),-- // Current scroll position- scroll_x: window.scrollX || window.pageXOffset || document.documentElement.scrollLeft || 0,- scroll_y: window.scrollY || window.pageYOffset || document.documentElement.scrollTop || 0- };- }""")-- # Calculate derived values (convert to int to handle fractional pixels)- viewport_width = int(page_data['viewport_width'])- viewport_height = int(page_data['viewport_height'])- page_width = int(page_data['page_width'])- page_height = int(page_data['page_height'])- scroll_x = int(page_data['scroll_x'])- scroll_y = int(page_data['scroll_y'])-- # Calculate pixels above/below/left/right current viewport- pixels_above = scroll_y- pixels_below = max(0, page_height - (scroll_y + viewport_height))- pixels_left = scroll_x- pixels_right = max(0, page_width - (scroll_x + viewport_width))-- return PageInfo(- viewport_width=viewport_width,- viewport_height=viewport_height,- page_width=page_width,- page_height=page_height,- scroll_x=scroll_x,- scroll_y=scroll_y,- pixels_above=pixels_above,- pixels_below=pixels_below,- pixels_left=pixels_left,- pixels_right=pixels_right,+ hasattr(element, 'node_name') and element.node_name.upper() == 'INPUT'+ and hasattr(element, 'attributes') and element.attributes.get('type', '').lower() == 'file')- async def _scroll_with_cdp_gesture(self, page: Page, pixels: int) -> bool:- """- Scroll using CDP Input.synthesizeScrollGesture for universal compatibility.-- Args:- page: The page to scroll- pixels: Number of pixels to scroll (positive = up, negative = down)-- Returns:- True if successful, False if failed- """- try:- # Use CDP to synthesize scroll gesture - works in all contexts including PDFs- cdp_session = await page.context.new_cdp_session(page) # type: ignore-- # Get viewport center for scroll origin- viewport = await page.evaluate("""- () => ({- width: window.innerWidth,- height: window.innerHeight- })- """)-- center_x = viewport['width'] // 2- center_y = viewport['height'] // 2-- await cdp_session.send(- 'Input.synthesizeScrollGesture',- {- 'x': center_x,- 'y': center_y,- 'xDistance': 0,- 'yDistance': -pixels, # Negative = scroll down, Positive = scroll up- 'gestureSourceType': 'mouse', # Use mouse gestures for better compatibility- 'speed': 3000, # Pixels per second- },- )-- try:- await asyncio.wait_for(cdp_session.detach(), timeout=1.0)- except (TimeoutError, Exception):- # Detach may timeout on some CDP implementations- pass-- return True- except Exception as e:- logger.debug(f'CDP scroll gesture failed: {e}')- return False-- async def _scroll_container(self, pixels: int) -> None:- """Scroll using CDP gesture synthesis with JavaScript fallback."""-- page = await self.get_current_page()-- # Try CDP scroll gesture first (works universally including PDFs)- if await self._scroll_with_cdp_gesture(page, pixels):- return-- # Fallback to JavaScript for older browsers or when CDP fails- logger.debug('Falling back to JavaScript scrolling')- SMART_SCROLL_JS = """(dy) => {- const bigEnough = el => el.clientHeight >= window.innerHeight * 0.5;- const canScroll = el =>- el &&- /(auto|scroll|overlay)/.test(getComputedStyle(el).overflowY) &&- el.scrollHeight > el.clientHeight &&- bigEnough(el);-- let el = document.activeElement;- while (el && !canScroll(el) && el !== document.body) el = el.parentElement;-- el = canScroll(el)- ? el- : [...document.querySelectorAll('*')].find(canScroll)- || document.scrollingElement- || document.documentElement;-- if (el === document.scrollingElement ||- el === document.documentElement ||- el === document.body) {- window.scrollBy(0, dy);- } else {- el.scrollBy({ top: dy, behavior: 'auto' });- }- }"""- await page.evaluate(SMART_SCROLL_JS, pixels)-- # --- DVD Screensaver Loading Animation Helper ---- async def _show_dvd_screensaver_loading_animation(self, page: Page) -> None:- """- Injects a DVD screensaver-style bouncing logo loading animation overlay into the given Playwright Page.- This is used to visually indicate that the browser is setting up or waiting.- """- if CONFIG.IS_IN_EVALS:- # dont bother wasting CPU showing animations during evals- return-- # we could enforce this, but maybe it's useful to be able to show it on other tabs?- # assert is_new_tab_page(page.url), 'DVD screensaver loading animation should only be shown on new tab pages'-- # all in one JS function for speed, we want as few roundtrip CDP calls as possible- # between opening the tab and showing the animation- try:- await page.evaluate(- """(browser_session_label) => {- // Ensure document.body exists before proceeding- if (!document.body) {- // Try again after DOM is ready- if (document.readyState === 'loading') {- document.addEventListener('DOMContentLoaded', () => arguments.callee(browser_session_label));- }- return;- }-- const animated_title = `Starting agent ${browser_session_label}...`;- if (document.title === animated_title) {- return; // already run on this tab, dont run again- }- document.title = animated_title;-- // Create the main overlay- const loadingOverlay = document.createElement('div');- loadingOverlay.id = 'pretty-loading-animation';- loadingOverlay.style.position = 'fixed';- loadingOverlay.style.top = '0';- loadingOverlay.style.left = '0';- loadingOverlay.style.width = '100vw';- loadingOverlay.style.height = '100vh';- loadingOverlay.style.background = '#000';- loadingOverlay.style.zIndex = '99999';- loadingOverlay.style.overflow = 'hidden';-- // Create the image element- const img = document.createElement('img');- img.src = 'https://cf.browser-use.com/logo.svg';- img.alt = 'Browser-Use';- img.style.width = '200px';- img.style.height = 'auto';- img.style.position = 'absolute';- img.style.left = '0px';- img.style.top = '0px';- img.style.zIndex = '2';- img.style.opacity = '0.8';-- loadingOverlay.appendChild(img);- document.body.appendChild(loadingOverlay);-- // DVD screensaver bounce logic- let x = Math.random() * (window.innerWidth - 300);- let y = Math.random() * (window.innerHeight - 300);- let dx = 1.2 + Math.random() * 0.4; // px per frame- let dy = 1.2 + Math.random() * 0.4;- // Randomize direction- if (Math.random() > 0.5) dx = -dx;- if (Math.random() > 0.5) dy = -dy;-- function animate() {- const imgWidth = img.offsetWidth || 300;- const imgHeight = img.offsetHeight || 300;- x += dx;- y += dy;-- if (x <= 0) {- x = 0;- dx = Math.abs(dx);- } else if (x + imgWidth >= window.innerWidth) {- x = window.innerWidth - imgWidth;- dx = -Math.abs(dx);- }- if (y <= 0) {- y = 0;- dy = Math.abs(dy);- } else if (y + imgHeight >= window.innerHeight) {- y = window.innerHeight - imgHeight;- dy = -Math.abs(dy);- }-- img.style.left = `${x}px`;- img.style.top = `${y}px`;-- requestAnimationFrame(animate);- }- animate();-- // Responsive: update bounds on resize- window.addEventListener('resize', () => {- x = Math.min(x, window.innerWidth - img.offsetWidth);- y = Math.min(y, window.innerHeight - img.offsetHeight);- });-- // Add a little CSS for smoothness- const style = document.createElement('style');- style.textContent = `- #pretty-loading-animation {- /*backdrop-filter: blur(2px) brightness(0.9);*/- }- #pretty-loading-animation img {- user-select: none;- pointer-events: none;- }- `;- document.head.appendChild(style);- }""",- str(self.id)[-4:],- )- except Exception as e:- self.logger.debug(f'β Failed to show π DVD loading animation: {type(e).__name__}: {e}')-- @observe_debug(ignore_input=True, ignore_output=True, name='get_browser_state_with_recovery')- async def get_browser_state_with_recovery(- self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = True- ) -> BrowserStateSummary:- """Get browser state with multiple fallback strategies for error recovery-- Parameters:- ------------ cache_clickable_elements_hashes: bool- If True, cache the clickable elements hashes for the current state.- include_screenshot: bool- If True, include screenshot in the state summary. Set to False to improve performance- when screenshots are not needed (e.g., in multi_act element validation).- """-- # Try 1: Full state summary (current implementation) - like main branch- try:- await self._wait_for_page_and_frames_load()- return await self._get_updated_state(include_screenshot=include_screenshot)- except Exception as e:- self.logger.warning(f'Full state retrieval failed: {type(e).__name__}: {e}')-- self.logger.warning('π Falling back to minimal state summary')- return await self.get_minimal_state_summary()-- async def _is_pdf_viewer(self, page: Page) -> bool:- """- Check if the current page is a PDF viewer.- """- try:- is_pdf = await page.evaluate('window.isPdfViewer || false')- return bool(is_pdf)- except Exception:- return False-- # ========== PDF API Methods ==========-- def set_auto_download_pdfs(self, enabled: bool) -> None:- """- Enable or disable automatic PDF downloading when PDFs are encountered.-- Args:- enabled: Whether to automatically download PDFs- """- self._auto_download_pdfs = enabled- logger.info(f'π PDF auto-download {"enabled" if enabled else "disabled"}')-- @property- def auto_download_pdfs(self) -> bool:- """Get current PDF auto-download setting."""- return self._auto_download_pdfs+ def clear_dom_cache(self) -> None:+ """Clear cached DOM state to force rebuild on next access."""+ if self._dom_watchdog:+ self._dom_watchdog.clear_cache()++ # ========== CDP-based replacements for browser_context operations ==========++ async def _cdp_get_all_pages(self) -> list[dict]:+ """Get all browser pages/tabs using CDP Target.getTargets."""+ cdp_client = await self.get_cdp_client()+ targets = await cdp_client.send('Target.getTargets')+ # Filter for page targets only+ return [t for t in targets.get('targetInfos', []) if t.get('type') == 'page']++ async def _cdp_create_new_page(self, url: str = 'about:blank') -> str:+ """Create a new page/tab using CDP Target.createTarget. Returns target ID."""+ cdp_client = await self.get_cdp_client()+ result = await cdp_client.send('Target.createTarget', {+ 'url': url,+ 'newWindow': False,+ 'background': False+ })+ return result['targetId']++ async def _cdp_close_page(self, target_id: str) -> None:+ """Close a page/tab using CDP Target.closeTarget."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Target.closeTarget', {'targetId': target_id})++ async def _cdp_activate_page(self, target_id: str) -> None:+ """Activate/focus a page using CDP Target.activateTarget."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Target.activateTarget', {'targetId': target_id})++ async def _cdp_get_cookies(self, urls: list[str] | None = None) -> list[dict]:+ """Get cookies using CDP Network.getCookies."""+ cdp_client = await self.get_cdp_client()+ params = {'urls': urls} if urls else {}+ result = await cdp_client.send('Network.getCookies', params)+ return result.get('cookies', [])++ async def _cdp_set_cookies(self, cookies: list[dict]) -> None:+ """Set cookies using CDP Network.setCookies."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Network.setCookies', {'cookies': cookies})++ async def _cdp_clear_cookies(self) -> None:+ """Clear all cookies using CDP Network.clearBrowserCookies."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Network.clearBrowserCookies')++ async def _cdp_set_extra_headers(self, headers: dict[str, str]) -> None:+ """Set extra HTTP headers using CDP Network.setExtraHTTPHeaders."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Network.setExtraHTTPHeaders', {'headers': headers})++ async def _cdp_grant_permissions(self, permissions: list[str], origin: str | None = None) -> None:+ """Grant permissions using CDP Browser.grantPermissions."""+ cdp_client = await self.get_cdp_client()+ params = {'permissions': permissions}+ if origin:+ params['origin'] = origin+ await cdp_client.send('Browser.grantPermissions', params)++ async def _cdp_set_geolocation(self, latitude: float, longitude: float, accuracy: float = 100) -> None:+ """Set geolocation using CDP Emulation.setGeolocationOverride."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Emulation.setGeolocationOverride', {+ 'latitude': latitude,+ 'longitude': longitude,+ 'accuracy': accuracy+ })++ async def _cdp_clear_geolocation(self) -> None:+ """Clear geolocation override using CDP."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Emulation.clearGeolocationOverride')++ async def _cdp_add_init_script(self, script: str) -> str:+ """Add script to evaluate on new document using CDP Page.addScriptToEvaluateOnNewDocument."""+ cdp_client = await self.get_cdp_client()+ result = await cdp_client.send('Page.addScriptToEvaluateOnNewDocument', {'source': script})+ return result['identifier']++ async def _cdp_remove_init_script(self, identifier: str) -> None:+ """Remove script added with addScriptToEvaluateOnNewDocument."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Page.removeScriptToEvaluateOnNewDocument', {'identifier': identifier})++ async def _cdp_set_viewport(self, width: int, height: int, device_scale_factor: float = 1.0, mobile: bool = False) -> None:+ """Set viewport using CDP Emulation.setDeviceMetricsOverride."""+ cdp_client = await self.get_cdp_client()+ await cdp_client.send('Emulation.setDeviceMetricsOverride', {+ 'width': width,+ 'height': height,+ 'deviceScaleFactor': device_scale_factor,+ 'mobile': mobile+ })++ async def _cdp_get_storage_state(self) -> dict:+ """Get storage state (cookies, localStorage, sessionStorage) using CDP."""+ cdp_client = await self.get_cdp_client()++ # Get cookies+ cookies_result = await cdp_client.send('Network.getCookies')+ cookies = cookies_result.get('cookies', [])++ # Get localStorage and sessionStorage would require evaluating JavaScript+ # on each origin, which is more complex. For now, return cookies only.+ return {+ 'cookies': cookies,+ 'origins': [] # Would need to iterate through origins for localStorage/sessionStorage+ }++ async def _cdp_navigate(self, url: str, target_id: str | None = None) -> None:+ """Navigate to URL using CDP Page.navigate."""+ cdp_client = await self.get_cdp_client()+ # If target_id provided, we'd need to attach to that session first+ # For now, navigate on the current page+ await cdp_client.send('Page.navigate', {'url': url})# Import uuid7str for ID generation@@ -4112,6 +1010,7 @@ _watchdog_modules = ['browser_use.browser.navigation_watchdog.NavigationWatchdog','browser_use.browser.aboutblank_watchdog.AboutBlankWatchdog','browser_use.browser.default_action_watchdog.DefaultActionWatchdog',+ 'browser_use.browser.dom_watchdog.DOMWatchdog',]for module_path in _watchdog_modules:diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 26c27bcca..fb74fd598 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -15,8 +15,18 @@ from pydantic import BaseModelfrom browser_use.agent.views import ActionModel, ActionResultfrom browser_use.browser import BrowserSession-from browser_use.browser.events import ClickElementEvent-from browser_use.browser.types import Page+from browser_use.browser.events import (+ ClickElementEvent,+ NavigateToUrlEvent,+ GoBackEvent,+ SwitchTabEvent,+ CloseTabEvent,+ TypeTextEvent,+ UploadFileEvent,+ ScrollEvent,+ SendKeysEvent,+ ScrollToTextEvent,+)from browser_use.browser.views import BrowserErrorfrom browser_use.controller.registry.service import Registryfrom browser_use.controller.views import (@@ -69,14 +79,14 @@ 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'- page = await browser_session.get_current_page()- if page.url.strip('/') == 'https://www.google.com':- # SECURITY FIX: Use browser_session.navigate_to() instead of direct page.goto()- # This ensures URL validation against allowed_domains is performed- await browser_session.navigate_to(search_url)- else:- # create_new_tab already includes proper URL validation- page = await browser_session.create_new_tab(search_url)+ # Dispatch navigation event+ event = browser_session.event_bus.dispatch(+ NavigateToUrlEvent(+ url=search_url,+ new_tab=True # Always use new tab for Google searches+ )+ )+ await eventmsg = f'π Searched for "{params.query}" in Google'logger.info(msg)@@ -89,23 +99,24 @@ class Controller(Generic[Context]):)async def go_to_url(params: GoToUrlAction, browser_session: BrowserSession):try:+ # Dispatch navigation event+ event = browser_session.event_bus.dispatch(+ NavigateToUrlEvent(+ url=params.url,+ new_tab=params.new_tab+ )+ )+ await event+if params.new_tab:- # Open in new tab (logic from open_tab function)- page = await browser_session.create_new_tab(params.url)- tab_index = browser_session.tabs.index(page)memory = f'Opened new tab with URL {params.url}'- msg = f'π Opened new tab #{tab_index} with url {params.url}'- logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=memory)+ msg = f'π Opened new tab with url {params.url}'else:- # Navigate in current tab (original logic)- # SECURITY FIX: Use browser_session.navigate_to() instead of direct page.goto()- # This ensures URL validation against allowed_domains is performed- await browser_session.navigate_to(params.url)memory = f'Navigated to {params.url}'msg = f'π {memory}'- logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=memory)++ logger.info(msg)+ return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=memory)except Exception as e:error_msg = str(e)# Check for network-related errors@@ -128,7 +139,8 @@ class Controller(Generic[Context]):@self.registry.action('Go back', param_model=NoParamsAction)async def go_back(_: NoParamsAction, browser_session: BrowserSession):- await browser_session.go_back()+ event = browser_session.event_bus.dispatch(GoBackEvent())+ await eventmsg = 'π Navigated back'logger.info(msg)return ActionResult(extracted_content=msg)@@ -153,73 +165,49 @@ class Controller(Generic[Context]):param_model=ClickElementAction,)async def click_element_by_index(params: ClickElementAction, browser_session: BrowserSession):- element_node = await browser_session.get_dom_element_by_index(params.index)- if element_node is None:- raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')-- initial_pages = len(browser_session.tabs)-- # if element has file uploader then dont click- # Check if element is actually a file input (not just contains file-related keywords)- if browser_session.is_file_input(element_node):- msg = f'Index {params.index} - has an element which opens file upload dialog. To upload files please use a specific function to upload files '- logger.info(msg)- return ActionResult(extracted_content=msg, include_in_memory=True, success=False, long_term_memory=msg)-- msg = None-- try:- download_path = await browser_session._click_element_node(- element_node, expect_download=params.expect_download, new_tab=params.new_tab+ # Dispatch click event with index+ event = browser_session.event_bus.dispatch(+ ClickElementEvent(+ index=params.index,+ expect_download=params.expect_download,+ new_tab=params.new_tab)+ )+ await event++ # Get the result if any (e.g., download path)+ result = await event.event_result()+ if result:+ download_path = result.get('download_path')if download_path:- emoji = 'πΎ'- msg = f'Downloaded file to {download_path}' + (' (new tab)' if params.new_tab else '')+ msg = f'πΎ Downloaded file to {download_path}' + (' (new tab)' if params.new_tab else '')else:- emoji = 'π±οΈ'- msg = f'Clicked button with index {params.index}: {element_node.llm_representation()}'-- # Check for new tab opening (existing behavior for normal clicks, expected for new tab clicks)- if len(browser_session.tabs) > initial_pages:- new_tab_msg = 'New tab opened - switching to it'- if params.new_tab:- msg = f'Clicked element {params.index} and opened in new tab'- else:- msg += f' - {new_tab_msg}'- emoji = 'π'- logger.info(f'{emoji} {new_tab_msg}')- # Switch to the last tab (newly created tab)- last_tab_index = len(browser_session.tabs) - 1- await browser_session.switch_to_tab(last_tab_index)-- logger.info(f'{emoji} {msg}')- logger.debug(f'Element xpath: {element_node.xpath}')- return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)- except Exception as e:- error_msg = str(e)- raise BrowserError(error_msg)+ msg = f'π±οΈ Clicked element with index {params.index}'+ else:+ msg = f'π±οΈ Clicked element with index {params.index}'++ logger.info(msg)+ return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)@self.registry.action('Click and input text into a input interactive element',param_model=InputTextAction,)async def input_text(params: InputTextAction, browser_session: BrowserSession, has_sensitive_data: bool = False):- element_node = await browser_session.get_dom_element_by_index(params.index)- if element_node is None:- raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')-- try:- await browser_session._input_text_element_node(element_node, params.text)- except Exception:- msg = f'Failed to input text into element {params.index}.'- raise BrowserError(msg)+ # Dispatch type text event+ event = browser_session.event_bus.dispatch(+ TypeTextEvent(+ index=params.index,+ text=params.text+ )+ )+ await eventif not has_sensitive_data:msg = f'β¨οΈ Input {params.text} into index {params.index}'else:msg = f'β¨οΈ Input sensitive data into index {params.index}'logger.info(msg)- logger.debug(f'Element xpath: {element_node.xpath}')return ActionResult(extracted_content=msg,include_in_memory=True,@@ -234,46 +222,34 @@ class Controller(Generic[Context]):if not os.path.exists(params.path):raise BrowserError(f'File {params.path} does not exist')- file_upload_dom_el = await browser_session.find_file_upload_element_by_index(params.index)-- if file_upload_dom_el is None:- msg = f'No file upload element found at index {params.index}'- logger.info(msg)- raise BrowserError(msg)-- file_upload_el = await browser_session.get_locate_element(file_upload_dom_el)-- if file_upload_el is None:- msg = f'No file upload element found at index {params.index}'- logger.info(msg)- raise BrowserError(msg)-- try:- await file_upload_el.set_input_files(params.path)- msg = f'π Successfully uploaded file to index {params.index}'- logger.info(msg)- return ActionResult(- extracted_content=msg,- include_in_memory=True,- long_term_memory=f'Uploaded file {params.path} to element {params.index}',+ # Dispatch upload file event+ event = browser_session.event_bus.dispatch(+ UploadFileEvent(+ element_index=params.index,+ file_path=params.path)- except Exception as e:- msg = f'Failed to upload file to index {params.index}: {str(e)}'- logger.info(msg)- raise BrowserError(msg)+ )+ await event++ msg = f'π Successfully uploaded file to index {params.index}'+ logger.info(msg)+ return ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ long_term_memory=f'Uploaded file {params.path} to element {params.index}',+ )# Tab Management Actions@self.registry.action('Switch tab', param_model=SwitchTabAction)async def switch_tab(params: SwitchTabAction, browser_session: BrowserSession):- await browser_session.switch_to_tab(params.page_id)- page = await browser_session.get_current_page()- try:- await page.wait_for_load_state(state='domcontentloaded', timeout=5_000)- # page was already loaded when we first navigated, this is additional to wait for onfocus/onblur animations/ajax to settle- except Exception as e:- pass- msg = f'π Switched to tab #{params.page_id} with url {page.url}'+ # Dispatch switch tab event+ event = browser_session.event_bus.dispatch(+ SwitchTabEvent(tab_index=params.page_id)+ )+ await event++ msg = f'π Switched to tab #{params.page_id}'logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Switched to tab {params.page_id}'@@ -281,18 +257,18 @@ class Controller(Generic[Context]):@self.registry.action('Close an existing tab', param_model=CloseTabAction)async def close_tab(params: CloseTabAction, browser_session: BrowserSession):- await browser_session.switch_to_tab(params.page_id)- page = await browser_session.get_current_page()- url = page.url- await page.close()- new_page = await browser_session.get_current_page()- new_page_idx = browser_session.tabs.index(new_page)- msg = f'β Closed tab #{params.page_id} with {url}, now focused on tab #{new_page_idx} with url {new_page.url}'+ # Dispatch close tab event+ event = browser_session.event_bus.dispatch(+ CloseTabEvent(tab_index=params.page_id)+ )+ await event++ msg = f'β Closed tab #{params.page_id}'logger.info(msg)return ActionResult(extracted_content=msg,include_in_memory=True,- long_term_memory=f'Closed tab {params.page_id} with url {url}, now focused on tab {new_page_idx} with url {new_page.url}.',+ long_term_memory=f'Closed tab {params.page_id}',)# Content Actions@@ -432,187 +408,25 @@ Explain the content of the page and that the requested information is not availaparam_model=ScrollAction,)async def scroll(params: ScrollAction, browser_session: BrowserSession):- """- (a) If index is provided, find scrollable containers in the element hierarchy and scroll directly.- (b) If no index or no container found, use browser._scroll_container for container-aware scrolling.- (c) If that JavaScript throws, fall back to window.scrollBy().- """- page = await browser_session.get_current_page()-- # Helper function to get window height with retry decorator- @retry(wait=1, retries=3, timeout=5)- async def get_window_height():- return await page.evaluate('() => window.innerHeight')-- # Get window height with retries- try:- window_height = await get_window_height()- except Exception as e:- raise RuntimeError(f'Scroll failed due to an error: {e}')- window_height = window_height or 0-- # Determine scroll amount based on num_pages- scroll_amount = int(window_height * params.num_pages)- pages_scrolled = params.num_pages-- # Set direction based on down parameter- dy = scroll_amount if params.down else -scroll_amount-- # Initialize result message components+ # Dispatch scroll event - the complex logic is handled in the event handler+ event = browser_session.event_bus.dispatch(+ ScrollEvent(+ direction='down' if params.down else 'up',+ amount=params.num_pages, # Pass num_pages, handler will convert to pixels+ element_index=params.index+ )+ )+ await event+direction = 'down' if params.down else 'up'- scroll_target = 'the page'-- # Element-specific scrolling if index is provided- if params.index is not None:- try:- element_node = await browser_session.get_dom_element_by_index(params.index)- if element_node is None:- raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')-- # Try direct container scrolling (no events that might close dropdowns)- container_scroll_js = """- (params) => {- const { dy, elementXPath } = params;-- // Get the target element by XPath- const targetElement = document.evaluate(elementXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;- if (!targetElement) {- return { success: false, reason: 'Element not found by XPath' };- }-- console.log('[SCROLL DEBUG] Starting direct container scroll for element:', targetElement.tagName);-- // Try to find scrollable containers in the hierarchy (starting from element itself)- let currentElement = targetElement;- let scrollSuccess = false;- let scrolledElement = null;- let scrollDelta = 0;- let attempts = 0;-- // Check up to 10 elements in hierarchy (including the target element itself)- while (currentElement && attempts < 10) {- const computedStyle = window.getComputedStyle(currentElement);- const hasScrollableY = /(auto|scroll|overlay)/.test(computedStyle.overflowY);- const canScrollVertically = currentElement.scrollHeight > currentElement.clientHeight;-- console.log('[SCROLL DEBUG] Checking element:', currentElement.tagName,- 'hasScrollableY:', hasScrollableY,- 'canScrollVertically:', canScrollVertically,- 'scrollHeight:', currentElement.scrollHeight,- 'clientHeight:', currentElement.clientHeight);-- if (hasScrollableY && canScrollVertically) {- const beforeScroll = currentElement.scrollTop;- const maxScroll = currentElement.scrollHeight - currentElement.clientHeight;-- // Calculate scroll amount (1/3 of provided dy for gentler scrolling)- let scrollAmount = dy / 3;-- // Ensure we don't scroll beyond bounds- if (scrollAmount > 0) {- scrollAmount = Math.min(scrollAmount, maxScroll - beforeScroll);- } else {- scrollAmount = Math.max(scrollAmount, -beforeScroll);- }-- // Try direct scrollTop manipulation (most reliable)- currentElement.scrollTop = beforeScroll + scrollAmount;-- const afterScroll = currentElement.scrollTop;- const actualScrollDelta = afterScroll - beforeScroll;-- console.log('[SCROLL DEBUG] Scroll attempt:', currentElement.tagName,- 'before:', beforeScroll, 'after:', afterScroll, 'delta:', actualScrollDelta);-- if (Math.abs(actualScrollDelta) > 0.5) {- scrollSuccess = true;- scrolledElement = currentElement;- scrollDelta = actualScrollDelta;- console.log('[SCROLL DEBUG] Successfully scrolled container:', currentElement.tagName, 'delta:', actualScrollDelta);- break;- }- }-- // Move to parent (but don't go beyond body for dropdown case)- if (currentElement === document.body || currentElement === document.documentElement) {- break;- }- currentElement = currentElement.parentElement;- attempts++;- }-- if (scrollSuccess) {- // Successfully scrolled a container- return {- success: true,- method: 'direct_container_scroll',- containerType: 'element',- containerTag: scrolledElement.tagName.toLowerCase(),- containerClass: scrolledElement.className || '',- containerId: scrolledElement.id || '',- scrollDelta: scrollDelta- };- } else {- // No container found or could scroll- console.log('[SCROLL DEBUG] No scrollable container found for element');- return {- success: false,- reason: 'No scrollable container found',- needsPageScroll: true- };- }- }- """-- # Pass parameters as a single object- scroll_params = {'dy': dy, 'elementXPath': element_node.xpath}- result = await page.evaluate(container_scroll_js, scroll_params)-- if result['success']:- if result['containerType'] == 'element':- container_info = f'{result["containerTag"]}'- if result['containerId']:- container_info += f'#{result["containerId"]}'- elif result['containerClass']:- container_info += f'.{result["containerClass"].split()[0]}'- scroll_target = f"element {params.index}'s scroll container ({container_info})"- # Don't do additional page scrolling since we successfully scrolled the container- else:- scroll_target = f'the page (fallback from element {params.index})'- else:- # Container scroll failed, need page-level scrolling- logger.debug(f'Container scroll failed for element {params.index}: {result.get("reason", "Unknown")}')- scroll_target = f'the page (no container found for element {params.index})'- # This will trigger page-level scrolling below-- except Exception as e:- logger.debug(f'Element-specific scrolling failed for index {params.index}: {e}')- scroll_target = f'the page (fallback from element {params.index})'- # Fall through to page-level scrolling-- # Page-level scrolling (default or fallback)- if (- scroll_target == 'the page'- or 'fallback' in scroll_target- or 'no container found' in scroll_target- or 'mouse wheel failed' in scroll_target- ):- logger.debug(f'π Performing page-level scrolling. Reason: {scroll_target}')- try:- await browser_session._scroll_container(cast(int, dy))- except Exception as e:- # Hard fallback: always works on root scroller- await page.evaluate('(y) => window.scrollBy(0, y)', dy)- logger.debug('Smart scroll failed; used window.scrollBy fallback', exc_info=e)-- # Create descriptive message- if pages_scrolled == 1.0:- long_term_memory = f'Scrolled {direction} {scroll_target} by one page'+ target = f'element {params.index}' if params.index is not None else 'the page'++ if params.num_pages == 1.0:+ long_term_memory = f'Scrolled {direction} {target} by one page'else:- long_term_memory = f'Scrolled {direction} {scroll_target} by {pages_scrolled} pages'+ long_term_memory = f'Scrolled {direction} {target} by {params.num_pages} pages'msg = f'π {long_term_memory}'-logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=long_term_memory)@@ -620,20 +434,13 @@ Explain the content of the page and that the requested information is not availa'Send strings of special keys to use Playwright page.keyboard.press - examples include Escape, Backspace, Insert, PageDown, Delete, Enter, or Shortcuts such as `Control+o`, `Control+Shift+T`',param_model=SendKeysAction,)- async def send_keys(params: SendKeysAction, page: Page):- try:- await page.keyboard.press(params.keys)- except Exception as e:- if 'Unknown key' in str(e):- # loop over the keys and try to send each one- for key in params.keys:- try:- await page.keyboard.press(key)- except Exception as e:- logger.debug(f'Error sending key {key}: {str(e)}')- raise e- else:- raise e+ async def send_keys(params: SendKeysAction, browser_session: BrowserSession):+ # Dispatch send keys event+ event = browser_session.event_bus.dispatch(+ SendKeysEvent(keys=params.keys)+ )+ await event+msg = f'β¨οΈ Sent keys: {params.keys}'logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Sent keys: {params.keys}')@@ -641,37 +448,22 @@ Explain the content of the page and that the requested information is not availa@self.registry.action(description='Scroll to a text in the current page',)- async def scroll_to_text(text: str, page: Page): # type: ignore- try:- # Try different locator strategies- locators = [- page.get_by_text(text, exact=False),- page.locator(f'text={text}'),- page.locator(f"//*[contains(text(), '{text}')]"),- ]-- for locator in locators:- try:- if await locator.count() == 0:- continue-- element = locator.first- is_visible = await element.is_visible()- bbox = await element.bounding_box()-- if is_visible and bbox is not None and bbox['width'] > 0 and bbox['height'] > 0:- await element.scroll_into_view_if_needed()- await asyncio.sleep(0.5) # Wait for scroll to complete- 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}'- )-- except Exception as e:- logger.debug(f'Locator attempt failed: {str(e)}')- continue-+ 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(@@ -680,11 +472,6 @@ Explain the content of the page and that the requested information is not availalong_term_memory=f"Tried scrolling to text '{text}' but it was not found",)- except Exception as e:- msg = f"Failed to scroll to text '{text}': {str(e)}"- logger.error(msg)- raise BrowserError(msg)-# File System Actions@self.registry.action('Write or append content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv, .pdf. For .pdf files, write the content in markdown format and it will automatically be converted to a properly formatted PDF document.'@@ -1036,13 +823,14 @@ Explain the content of the page and that the requested information is not availaraise BrowserError(msg)@self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['https://docs.google.com'])- async def read_sheet_contents(page: Page):- # select all cells- await page.keyboard.press('Enter')- await page.keyboard.press('Escape')- await page.keyboard.press('ControlOrMeta+A')- await page.keyboard.press('ControlOrMeta+C')+ async def read_sheet_contents(browser_session: BrowserSession):+ # Use send keys events to select and copy all cells+ for key in ['Enter', 'Escape', 'ControlOrMeta+A', 'ControlOrMeta+C']:+ event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ await event+ # Get page to evaluate clipboard+ page = await browser_session.get_current_page()extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')return ActionResult(extracted_content=extracted_tsv,@@ -1102,20 +890,27 @@ Explain the content of the page and that the requested information is not availa)@self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['https://docs.google.com'])- async def select_cell_or_range(cell_or_range: str, page: Page):- await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editing- await page.keyboard.press('Escape') # to clear current focus (otherwise select range popup is additive)+ async def select_cell_or_range(cell_or_range: str, browser_session: BrowserSession):+ # Use send keys events for navigation+ for key in ['Enter', 'Escape']:+ event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ await eventawait asyncio.sleep(0.1)- await page.keyboard.press('Home') # move cursor to the top left of the sheet first- await page.keyboard.press('ArrowUp')+ for key in ['Home', 'ArrowUp']:+ event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ await eventawait asyncio.sleep(0.1)- await page.keyboard.press('Control+G') # open the goto range popup+ event = browser_session.event_bus.dispatch(SendKeysEvent(keys='Control+G'))+ await eventawait asyncio.sleep(0.2)+ # Get page to type the cell range+ page = await browser_session.get_current_page()await page.keyboard.type(cell_or_range, delay=0.05)await asyncio.sleep(0.2)- await page.keyboard.press('Enter')- await asyncio.sleep(0.2)- await page.keyboard.press('Escape') # to make sure the popup still closes in the case where the jump failed+ for key in ['Enter', 'Escape']:+ event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ await event+ await asyncio.sleep(0.2)return ActionResult(extracted_content=f'Selected cells: {cell_or_range}',include_in_memory=False,@@ -1126,10 +921,14 @@ Explain the content of the page and that the requested information is not availa'Google Sheets: Fallback method to type text into (only one) currently selected cell',domains=['https://docs.google.com'],)- async def fallback_input_into_single_selected_cell(text: str, page: Page):+ async def fallback_input_into_single_selected_cell(text: str, browser_session: BrowserSession):+ # Get page to type text+ page = await browser_session.get_current_page()await page.keyboard.type(text, delay=0.1)- await page.keyboard.press('Enter') # make sure to commit the input so it doesn't get overwritten by the next action- await page.keyboard.press('ArrowUp')+ # Use send keys for Enter and ArrowUp+ for key in ['Enter', 'ArrowUp']:+ event = browser_session.event_bus.dispatch(SendKeysEvent(keys=key))+ await eventreturn ActionResult(extracted_content=f'Inputted text {text}',include_in_memory=False,diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.pyindex 928e8232c..079212963 100644--- a/browser_use/dom/playground/extraction.py+++ b/browser_use/dom/playground/extraction.py@@ -9,6 +9,7 @@ import tiktokenfrom browser_use.agent.prompts import AgentMessagePromptfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.browser.events import ClickElementEventfrom browser_use.browser.types import ViewportSizefrom browser_use.dom.debug.highlights import inject_highlighting_script, remove_highlighting_scriptfrom browser_use.dom.service import DomService@@ -251,7 +252,10 @@ async def test_focus_vs_all_elements():if clicked_index in selector_map:element_node = selector_map[clicked_index]print(f'Clicking element {clicked_index}: {element_node.tag_name}')- await browser_session._click_element_node(element_node)+ event = browser_session.event_bus.dispatch(+ ClickElementEvent(element_node=element_node)+ )+ await eventprint('Click successful.')except ValueError:print(f"Invalid input: '{answer}'. Enter an index, 'index,text', 'c,index', or 'q'.")diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 54b96f021..6bc5054f1 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -1,5 +1,5 @@import hashlib-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom enum import Enumfrom typing import Any@@ -9,6 +9,7 @@ from cdp_use.cdp.dom.commands import GetDocumentReturnsfrom cdp_use.cdp.dom.types import ShadowRootTypefrom cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturnsfrom cdp_use.cdp.target.types import TargetInfo+from uuid_extensions import uuid7strfrom browser_use.dom.utils import cap_text_length@@ -168,6 +169,7 @@ class EnhancedDOMTreeNode:"""# region - DOM Node data+node_id: intbackend_node_id: int@@ -222,6 +224,8 @@ class EnhancedDOMTreeNode:# endregion - Snapshot Node data+ uuid: str = field(default_factory=uuid7str)+@propertydef parent(self) -> 'EnhancedDOMTreeNode | None':return self.parent_nodediff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.pyindex 208f361d5..9d484adc7 100644--- a/browser_use/mcp/server.py+++ b/browser_use/mcp/server.py@@ -77,6 +77,7 @@ _configure_mcp_server_logging()# Import browser_use modulesfrom browser_use import ActionModel, Agentfrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.browser.events import ClickElementEventfrom browser_use.config import get_default_llm, get_default_profile, load_browser_use_configfrom browser_use.controller.service import Controllerfrom browser_use.filesystem.file_system import FileSystem@@ -639,7 +640,10 @@ class BrowserUseServer:return f'Could not locate element {index} for modified click'else:# Normal click- await self.browser_session._click_element_node(element)+ event = self.browser_session.event_bus.dispatch(+ ClickElementEvent(element_node=element)+ )+ await eventreturn f'Clicked element {index}'async def _type_text(self, index: int, text: str) -> str:diff --git a/docs/customize/browser-settings.mdx b/docs/customize/browser-settings.mdxindex 557627bae..84dc7d601 100644--- a/docs/customize/browser-settings.mdx+++ b/docs/customize/browser-settings.mdx@@ -105,7 +105,7 @@ browser_context: BrowserContext | None = NonePlaywright BrowserContext object to use (optional). See here for [more detailed usage instructions](https://docs.browser-use.com/customize/real-browser#method-b%3A-connect-using-existing-playwright-objects).-#### `page` *aka* `agent_current_page`+#### `page` *aka* `current_target_id`<a name="page"></a><a name="agent-current-page"></a>diff --git a/tests/ci/test_downloads_watchdog.py b/tests/ci/test_downloads_watchdog.pyindex 63773476d..4fbd3b3d8 100644--- a/tests/ci/test_downloads_watchdog.py+++ b/tests/ci/test_downloads_watchdog.py@@ -13,6 +13,7 @@ from browser_use.browser.events import (BrowserStartEvent,BrowserStopEvent,BrowserStoppedEvent,+ ClickElementEvent,FileDownloadedEvent,)from browser_use.browser.profile import BrowserProfile@@ -348,7 +349,12 @@ async def test_downloads_watchdog_detection_timing(comprehensive_download_test_selse:# Time the click using browser session methodstart_time = time.time()- result = await browser_with_downloads._click_element_node(button_node)+ event = browser_with_downloads.event_bus.dispatch(+ ClickElementEvent(element_node=button_node)+ )+ await event+ result = await event.event_result()+ result = result.get('download_path') if result else Noneduration_with_downloads = time.time() - start_time# Verify click worked@@ -394,7 +400,12 @@ async def test_downloads_watchdog_detection_timing(comprehensive_download_test_selse:# Time the click using browser session methodstart_time = time.time()- result = await browser_no_downloads._click_element_node(button_node)+ event = browser_no_downloads.event_bus.dispatch(+ ClickElementEvent(element_node=button_node)+ )+ await event+ result = await event.event_result()+ result = result.get('download_path') if result else Noneduration_no_downloads = time.time() - start_time# Verify click worked@@ -458,7 +469,10 @@ async def test_downloads_watchdog_actual_download_detection(comprehensive_downlo# We don't need our own download handler - let the downloads watchdog handle it# Click the download link with expect_download=True- await browser_session._click_element_node(download_node, expect_download=True)+ event = browser_session.event_bus.dispatch(+ ClickElementEvent(element_node=download_node, expect_download=True)+ )+ await eventduration = time.time() - start_timeprint(f'Click completed in {duration:.2f}s')diff --git a/tests/old/test_clicks.py b/tests/old/test_clicks.pyindex 74788f9eb..79466d637 100644--- a/tests/old/test_clicks.py+++ b/tests/old/test_clicks.py@@ -4,6 +4,7 @@ import jsonimport anyiofrom browser_use.browser import BrowserProfile, BrowserSession+from browser_use.browser.events import ClickElementEventfrom browser_use.dom.views import DOMBaseNode, DOMElementNode, DOMTextNodefrom browser_use.utils import time_execution_sync@@ -88,7 +89,10 @@ async def test_highlight_elements():# check if index of selector map are the same as index of items in dom_items- await browser_session._click_element_node(node_element)+ event = browser_session.event_bus.dispatch(+ ClickElementEvent(element_node=node_element)+ )+ await eventexcept Exception as e:print(e)