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
add session.py cdp helpers
Nick Sweeting13ce936128f3
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.pyindex b75531b5b..c6e52bfb3 100644--- a/browser_use/browser/default_action_watchdog.py+++ b/browser_use/browser/default_action_watchdog.py@@ -81,10 +81,11 @@ class DefaultActionWatchdog(BaseWatchdog):msg += f' - {new_tab_msg}'logger.info(f'🔗 {new_tab_msg}')# Switch to the last tab (newly created tab)- 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-+ from browser_use.browser.events import SwitchTabEvent++ last_tab_index = len(current_target_ids) - 1+ await self.event_bus.dispatch(SwitchTabEvent(tab_index=last_tab_index))+# Return download_path if anyif download_path:return {'download_path': download_path}diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex ebc4fcdf1..f17fd764e 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -1,48 +1,28 @@"""DOM watchdog for browser DOM tree management using CDP."""-import asyncio-import loggingimport 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 typing import TYPE_CHECKINGfrom browser_use.browser.events import BrowserErrorEvent, BuildDOMTreeEventfrom 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.service import DomServicefrom browser_use.dom.views import (- CurrentPageTargets,- DOMRect,- EnhancedAXNode,- EnhancedAXProperty,EnhancedDOMTreeNode,- NodeType,SerializedDOMState,- TargetAllTrees,)from browser_use.utils import loggerif 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+ passclass DOMWatchdog(BaseWatchdog):- """Handles DOM tree building, serialization, and element access via CDP."""+ """Handles DOM tree building, serialization, and element access via CDP.++ This watchdog acts as a bridge between the event-driven browser session+ and the DomService implementation, maintaining cached state and providing+ helper methods for other watchdogs.+ """LISTENS_TO = [BuildDOMTreeEvent]EMITS = [BrowserErrorEvent]@@ -53,14 +33,13 @@ class DOMWatchdog(BaseWatchdog):current_dom_state: SerializedDOMState | None = Noneenhanced_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)+ # Internal DOM service+ _dom_service: DomService | None = Noneasync def attach_to_session(self) -> None:- """Attach watchdog to browser session and initialize CDP client."""+ """Attach watchdog to browser session."""await super().attach_to_session()- # CDP client will be initialized on first use+ # DomService will be created on first useasync def on_BuildDOMTreeEvent(self, event: BuildDOMTreeEvent) -> SerializedDOMState:"""Build and serialize DOM tree, returning ready-to-use LLM format.@@ -76,31 +55,42 @@ class DOMWatchdog(BaseWatchdog):"""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)+ # Create or reuse DOM service+ if self._dom_service is None:+ self._dom_service = DomService(browser=self.browser_session, page=page, logger=logger)- # Serialize for LLM+ # Get serialized DOM tree using the servicestart = time.time()- self.current_dom_state, serializer_timing = DOMTreeSerializer(- self.enhanced_dom_tree,- event.previous_state- ).serialize_accessible_elements()+ self.current_dom_state, timing_info = await self._dom_service.get_serialized_dom_tree(+ previous_cached_state=event.previous_state+ )end = time.time()logger.debug(f'Time taken to serialize dom tree: {end - start} seconds')# Update selector map for other watchdogsself.selector_map = self.current_dom_state.selector_map-+# Build UUID selector mapself.uuid_selector_map = {}if self.selector_map:for node in self.selector_map.values():- self.uuid_selector_map[node.uuid] = node+ if hasattr(node, 'uuid'):+ self.uuid_selector_map[node.uuid] = node++ # Store the enhanced DOM tree if available+ # Note: The service doesn't expose the raw enhanced tree,+ # but we can access it through the selector map if needed+ if self.selector_map:+ # The root node is typically at index 0 or we can traverse up from any node+ for node in self.selector_map.values():+ # Find root by traversing up+ root = node+ while root.parent_node:+ root = root.parent_node+ self.enhanced_dom_tree = root+ breakreturn self.current_dom_state@@ -152,482 +142,28 @@ class DOMWatchdog(BaseWatchdog):self.uuid_selector_map = Noneself.current_dom_state = Noneself.enhanced_dom_tree = None+ # Keep the DOM service instance to reuse its CDP client connectiondef 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'- )+ 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+ 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.+ Delegates to the DomService static method."""- 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+ return DomService.is_element_visible_according_to_all_parents(node, html_frames)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+ """Clean up DOM service on exit."""+ if self._dom_service:+ await self._dom_service.__aexit__(exc_type, exc_value, traceback)+ self._dom_service = Nonedef __del__(self):- """Clean up CDP client on deletion."""+ """Clean up DOM service on deletion."""super().__del__()- if self.cdp_client:- try:- asyncio.create_task(self.cdp_client.stop())- except Exception:- pass\ No newline at end of file+ # DOM service will clean up its own CDP client+ self._dom_service = Nonediff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 669f8c1b5..4d0de01fa 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -2,13 +2,8 @@import asyncioimport logging-import osfrom typing import Any, Self-from browser_use.observability import observe_debug-from browser_use.utils import _log_pretty_url--from bubus import EventBusfrom bubus.helpers import retryfrom pydantic import BaseModel, ConfigDict, Field, PrivateAttr@@ -21,27 +16,16 @@ from browser_use.browser.events import (BrowserStartEvent,BrowserStopEvent,BrowserStoppedEvent,- ClickElementEvent,- GoBackEvent,- GoForwardEvent,- NavigateToUrlEvent,- RefreshEvent,- SaveStorageStateEvent,- ScreenshotEvent,- ScrollEvent,- SendKeysEvent,- TypeTextEvent,- UploadFileEvent,- WaitEvent,)from browser_use.browser.profile import BrowserProfile-from browser_use.browser.views import (BrowserStateSummary,PageInfo,TabInfo,)+from browser_use.observability import observe_debugfrom browser_use.utils import (+ _log_pretty_url,is_new_tab_page,logger,time_execution_async,@@ -65,11 +49,9 @@ def _log_glob_warning(domain: str, glob: str, logger: logging.Logger):_GLOB_WARNING_SHOWN = True-DEFAULT_BROWSER_PROFILE = BrowserProfile()-class BrowserSession(BaseModel):"""Event-driven browser session with backwards compatibility.@@ -143,8 +125,6 @@ class BrowserSession(BaseModel):)return f'BrowserSession🆂 {self.id[-4:]}:{port_number_or_pid} #{str(id(self))[-2:]}' # ' 🅟 {str(id(self.current_target_id))[-2:]}'--async def on_BrowserStartEvent(self, event: BrowserStartEvent) -> None:"""Handle browser start request."""@@ -321,16 +301,16 @@ class BrowserSession(BaseModel):async def setup_browser_via_cdp_url(self) -> None:"""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)')-+# Import cdp-use clientimport httpxfrom cdp_use import CDPClient-+# Convert HTTP URL to WebSocket URL if neededws_url = self.cdp_urlif not ws_url.startswith('ws'):@@ -341,18 +321,18 @@ class BrowserSession(BaseModel):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 communicationif not hasattr(self, '_cdp_client'):self._cdp_client = CDPClient(ws_url)await self._cdp_client.start()-+# Get browser targets to find available contexts/pagestargets = 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 onenew_target = await self._cdp_client.send.Target.createTarget({'url': 'about:blank'})@@ -360,18 +340,15 @@ class BrowserSession(BaseModel):else:# Use the first available pagetarget_id = page_targets[0]['targetId']-+# Store the current page target IDself.current_target_id = target_id-+# Mark that we're connected via CDP (no playwright browser object)self._cdp_connected = Trueself.keep_alive = True-async def setup_domservice_init_scripts(self, retry_count: int = 0) -> None:--# self.logger.debug('Setting up init scripts in browser')init_script = """@@ -425,8 +402,6 @@ class BrowserSession(BaseModel):"""await self.browser_context.add_init_script(init_script)--@propertyasync def target_ids(self) -> list[str]:"""Get all open page target IDs using CDP."""@@ -453,15 +428,15 @@ class BrowserSession(BaseModel):async def get_tabs_info(self) -> list[TabInfo]:"""Get information about all open tabs using CDP for reliability."""tabs = []-+# Get all page targets using CDPpages = 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 pagesif is_new_tab_page(url) or url.startswith('chrome://'):# Use URL as title for chrome pages, or mark new tabs as unusable@@ -474,42 +449,34 @@ class BrowserSession(BaseModel):# Normal pages - try to get title with CDP for reliabilitytry:# Attach to target and get session ID- session = await cdp_client.send('Target.attachToTarget', {- 'targetId': target_id,- 'flatten': True- })+ 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',- {'expression': 'document.title'},- session_id=session_id- ),- timeout=2.0+ cdp_client.send('Runtime.evaluate', {'expression': 'document.title'}, session_id=session_id), timeout=2.0)title = title_result.get('result', {}).get('value', '')-+# Detach from targetawait cdp_client.send('Target.detachFromTarget', {'sessionId': session_id})-+# Special handling for PDF pagesif (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(url).path.split('/')[-1]if filename:title = filenameexcept Exception:pass-+except Exception as e:# Page might be crashed or unresponsive- self.logger.debug(- f'⚠️ Failed to get tab info for tab #{i}: {_log_pretty_url(url)} - {type(e).__name__}'- )-+ self.logger.debug(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 pageif is_new_tab_page(url):title = 'ignore this tab and do not use it'@@ -517,13 +484,11 @@ class BrowserSession(BaseModel):# For crashed pages, close them as they're not usefultry:await self._cdp_close_page(target_id)- self.logger.debug(- f'🪓 Force-closed page because it\'s unresponsive: {_log_pretty_url(url)}'- )+ self.logger.debug(f"🪓 Force-closed page because it's unresponsive: {_log_pretty_url(url)}")continueexcept Exception:title = '(Error)'-+tab_info = TabInfo(page_id=i,url=url,@@ -577,6 +542,7 @@ class BrowserSession(BaseModel):is_visible=True,absolute_position=None,frame_id=None,+ target_id=self.current_target_id,content_document=None,shadow_root_type=None,shadow_roots=None,@@ -604,7 +570,7 @@ class BrowserSession(BaseModel):pixels_below=0,browser_errors=[f'Page state retrieval failed, minimal recovery applied for {url}'],is_pdf_viewer=is_pdf_viewer,- loading_status=self._current_page_loading_status,+ recent_events='',)@observe_debug(ignore_input=True, ignore_output=True, name='get_updated_state')@@ -698,7 +664,7 @@ class BrowserSession(BaseModel):# Create minimal DOM state for basic navigationcontent = SerializedDOMState(- _root=None, # No simplified tree for minimal state+ _root=None, # No simplified tree for minimal stateselector_map={}, # Empty selector map)@@ -786,7 +752,6 @@ class BrowserSession(BaseModel):return self.browser_state_summaryraise-# ========== CDP Helper Methods ==========async def get_cdp_client(self) -> Any:@@ -794,11 +759,11 @@ class BrowserSession(BaseModel):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 clientimport httpxfrom cdp_use import CDPClient-+# Convert HTTP URL to WebSocket URL if neededws_url = self.cdp_urlif not ws_url.startswith('ws'):@@ -809,25 +774,186 @@ class BrowserSession(BaseModel):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_clientasync 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}- )+ session = await cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})return session['sessionId']+ async def _create_fresh_cdp_client(self) -> Any:+ """Create a new CDP client instance. Caller is responsible for cleanup."""+ if not self.cdp_url:+ raise ValueError('CDP URL is not set')++ import httpx+ from cdp_use import CDPClient++ # If the cdp_url is already a websocket URL, use it as-is.+ if self.cdp_url.startswith('ws'):+ ws_url = self.cdp_url+ else:+ # Otherwise, treat it as the DevTools HTTP root and fetch the websocket URL.+ url = self.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']++ cdp_client = CDPClient(ws_url)+ await cdp_client.start()+ return cdp_client++ async def create_cdp_session_for_target(self, target_id: str) -> Any:+ """Create a new CDP session attached to a specific target/frame.++ Args:+ target_id: The target ID to attach to++ Returns:+ CDPClient with session attached to target - caller is responsible for cleanup++ Note: The returned CDPClient should be stopped when done using:+ await cdp_client.stop()+ """+ cdp_client = await self._create_fresh_cdp_client()++ try:+ # Attach to the target+ session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})+ session_id = session['sessionId']++ # Store the session_id on the client for convenience+ cdp_client.target_session_id = session_id++ # Enable necessary domains+ 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),+ )++ return cdp_client++ except Exception:+ # Clean up on error+ await cdp_client.stop()+ raise++ async def create_cdp_session_for_frame(self, frame_id: str) -> Any:+ """Create a new CDP session for a specific frame by finding its parent target.++ Args:+ frame_id: The frame ID to find and attach to++ Returns:+ CDPClient with session attached to the target containing this frame++ Raises:+ ValueError: If frame_id is not found in any target+ """+ search_client = await self._create_fresh_cdp_client()++ try:+ # Get all targets+ targets = await search_client.send.Target.getTargets()++ # Search through page targets to find which one contains the frame+ for target in targets['targetInfos']:+ if target['type'] != 'page':+ continue++ # Attach to this target to check its frame tree+ session = await search_client.send.Target.attachToTarget(params={'targetId': target['targetId'], 'flatten': True})+ temp_session_id = session['sessionId']++ # Enable Page domain to get frame tree+ await search_client.send.Page.enable(session_id=temp_session_id)++ # Get frame tree for this target+ frame_tree = await search_client.send.Page.getFrameTree(session_id=temp_session_id)++ # Recursively search for the frame_id+ def search_frame_tree(node) -> bool:+ if node['frame']['id'] == frame_id:+ return True+ if 'childFrames' in node:+ for child in node['childFrames']:+ if search_frame_tree(child):+ return True+ return False++ if search_frame_tree(frame_tree['frameTree']):+ # Found the target containing this frame+ await search_client.stop()++ # Create a new session for this target+ return await self.create_cdp_session_for_target(target['targetId'])++ # Frame not found+ await search_client.stop()+ raise ValueError(f'Frame with ID {frame_id} not found in any target')++ except Exception:+ await search_client.stop()+ raise++ async def create_cdp_session_for_node(self, node: Any) -> Any:+ """Create a new CDP session for a specific DOM node's target.++ Args:+ node: The EnhancedDOMTreeNode to create a session for++ Returns:+ CDPClient with session attached to the node's target++ Raises:+ ValueError: If node doesn't have a target_id or node doesn't exist in target+ """+ if not hasattr(node, 'target_id') or not node.target_id:+ raise ValueError(f'Node does not have a target_id: {node}')++ # Create session for the node's target+ cdp_client = await self.create_cdp_session_for_target(node.target_id)++ try:+ # Verify the node exists in this target+ # Use the stored session_id from the client+ session_id = getattr(cdp_client, 'target_session_id', None)+ if not session_id:+ raise ValueError('CDP client does not have target_session_id set')++ result = await cdp_client.send.DOM.describeNode(params={'backendNodeId': node.backend_node_id}, session_id=session_id)++ # If we get here without exception, the node exists+ return cdp_client++ except Exception as e:+ # Node doesn't exist in this target, clean up+ await cdp_client.stop()+ raise ValueError(f'Node with backend_node_id {node.backend_node_id} not found in target {node.target_id}: {e}')+async def get_current_page(self) -> Any:"""Get the current active page."""if hasattr(self, '_browser_context') and self._browser_context:@@ -840,10 +966,10 @@ class BrowserSession(BaseModel):async def get_dom_element_by_index(self, index: int) -> Any | None:"""Get DOM element by index from the DOM watchdog.-+Args:index: The element index from the serialized DOM-+Returns:EnhancedDOMTreeNode or None if index not found"""@@ -853,10 +979,10 @@ class BrowserSession(BaseModel):def is_file_input(self, element: Any) -> bool:"""Check if element is a file input.-+Args:element: The DOM element to check-+Returns:True if element is a file input, False otherwise"""@@ -864,8 +990,10 @@ class BrowserSession(BaseModel):return self._dom_watchdog.is_file_input(element)# Fallback if watchdog not availablereturn (- hasattr(element, 'node_name') and element.node_name.upper() == 'INPUT'- and hasattr(element, 'attributes') and element.attributes.get('type', '').lower() == 'file'+ hasattr(element, 'node_name')+ and element.node_name.upper() == 'INPUT'+ and hasattr(element, 'attributes')+ and element.attributes.get('type', '').lower() == 'file')def clear_dom_cache(self) -> None:@@ -874,56 +1002,52 @@ class BrowserSession(BaseModel):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 onlyreturn [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- })+ 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()@@ -931,57 +1055,53 @@ class BrowserSession(BaseModel):if origin:params['origin'] = originawait 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- })-+ 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- })-+ 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 cookiescookies_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+ '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()diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex fb74fd598..d89a690b9 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -273,43 +273,46 @@ class Controller(Generic[Context]):# Content Actions- @self.registry.action(- """Extract structured, semantic data (e.g. product description, price, all information about XYZ) from the current webpage based on a textual query.-This tool takes the entire markdown of the page and extracts the query from it.-Set extract_links=True ONLY if your query requires extracting links/URLs from the page.-Only use this for specific queries for information retrieval from the page. Don't use this to get interactive elements - the tool does not see HTML elements, only the markdown.-""",- )- async def extract_structured_data(- query: str,- extract_links: bool,- page: Page,- page_extraction_llm: BaseChatModel,- file_system: FileSystem,- ):- from functools import partial+ # TODO: Refactor to use events instead of direct page access+ # This action is temporarily disabled as it needs refactoring to use events+ if False: # Disabled+ @self.registry.action(+ """Extract structured, semantic data (e.g. product description, price, all information about XYZ) from the current webpage based on a textual query.+ This tool takes the entire markdown of the page and extracts the query from it.+ Set extract_links=True ONLY if your query requires extracting links/URLs from the page.+ Only use this for specific queries for information retrieval from the page. Don't use this to get interactive elements - the tool does not see HTML elements, only the markdown.+ """,+ )+ async def extract_structured_data(+ query: str,+ extract_links: bool,+ page: Page,+ page_extraction_llm: BaseChatModel,+ file_system: FileSystem,+ ):+ from functools import partial- import markdownify+ import markdownify- strip = []+ strip = []- if not extract_links:- strip = ['a', 'img']+ if not extract_links:+ strip = ['a', 'img']- # Run markdownify in a thread pool to avoid blocking the event loop- loop = asyncio.get_event_loop()+ # Run markdownify in a thread pool to avoid blocking the event loop+ loop = asyncio.get_event_loop()- # Aggressive timeout for page content- try:- page_html_result = await asyncio.wait_for(page.content(), timeout=10.0) # 5 second aggressive timeout- except TimeoutError:- raise RuntimeError('Page content extraction timed out after 5 seconds')- except Exception as e:- raise RuntimeError(f"Couldn't extract page content: {e}")+ # Aggressive timeout for page content+ try:+ page_html_result = await asyncio.wait_for(page.content(), timeout=10.0) # 5 second aggressive timeout+ except TimeoutError:+ raise RuntimeError('Page content extraction timed out after 5 seconds')+ except Exception as e:+ raise RuntimeError(f"Couldn't extract page content: {e}")- page_html = page_html_result+ page_html = page_html_result- markdownify_func = partial(markdownify.markdownify, strip=strip)+ markdownify_func = partial(markdownify.markdownify, strip=strip)try:content = await asyncio.wait_for(@@ -533,10 +536,11 @@ Explain the content of the page and that the requested information is not availainclude_extracted_content_only_once=True,)- @self.registry.action(- description='Get all options from a native dropdown or ARIA menu',- )- async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult:+ # TODO: Refactor to use events instead of direct page/dom access+ # @self.registry.action(+ # description='Get all options from a native dropdown or ARIA menu',+ # )+ # async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult:"""Get all options from a native dropdown or ARIA menu"""page = await browser_session.get_current_page()dom_element = await browser_session.get_dom_element_by_index(index)@@ -646,10 +650,11 @@ Explain the content of the page and that the requested information is not availalogger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True)- @self.registry.action(- description='Select dropdown option or ARIA menu item for interactive element index by the text of the option you want to select',- )- async def select_dropdown_option(+ # TODO: Refactor to use events instead of direct page/dom access+ # @self.registry.action(+ # description='Select dropdown option or ARIA menu item for interactive element index by the text of the option you want to select',+ # )+ # async def select_dropdown_option(index: int,text: str,browser_session: BrowserSession,diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex b43a7a7f2..43f9e1ec0 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -453,6 +453,7 @@ class DomService:attributes=attributes or {},is_scrollable=node.get('isScrollable', None),frame_id=node.get('frameId', None),+ target_id=target['targetId'],content_document=None,shadow_root_type=shadow_root_type,shadow_roots=None,diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 6bc5054f1..04c831215 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -196,6 +196,7 @@ class EnhancedDOMTreeNode:"""# frames+ target_id: strframe_id: str | Nonecontent_document: 'EnhancedDOMTreeNode | None'"""@@ -307,6 +308,7 @@ class EnhancedDOMTreeNode:'node_value': self.node_value,'attributes': self.attributes,'is_scrollable': self.is_scrollable,+ 'target_id': self.target_id,'frame_id': self.frame_id,'content_document': self.content_document.__json__() if self.content_document else None,'shadow_root_type': self.shadow_root_type,