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
Merge commit '9b882faa10c54be5a870cc5d8abd6ddb19d0682f' into feature/new-dom-extraction-layer
Gregor Žunič0aa3d5423312
diff --cc browser_use/agent/service.pyindex 7db2f468f,6b0194bde..cc58916cb--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -178,15 -184,15 +180,20 @@@ class Agent(Generic[Context, AgentStruccalculate_cost: bool = False,display_files_in_done_text: bool = True,include_tool_call_examples: bool = False,+ vision_detail_level: Literal['auto', 'low', 'high'] = 'auto',+ llm_timeout: int = 60,+ step_timeout: int = 180,**kwargs,):+ if not isinstance(llm, BaseChatModel):+ raise ValueError('invalid llm, must be from browser_use.llm')# Check for deprecated planner parameters- planner_params = [planner_llm, use_vision_for_planner, is_planner_reasoning, extend_planner_system_message]+ planner_params = [+ planner_llm,+ use_vision_for_planner,+ is_planner_reasoning,+ extend_planner_system_message,+ ]if any(param is not None and param is not False for param in planner_params) or planner_interval != 1:logger.warning('⚠️ Planner functionality has been removed in browser-use v0.3.3+. '@@@ -1394,54 -1387,64 +1407,58 @@@results: list[ActionResult] = []assert self.browser_session is not None, 'BrowserSession is not set up'- cached_selector_map = {}- cached_path_hashes = set()- # check all actions if any has index, if so, get the selector map- for action in actions:- if action.get_index() is not None:- cached_selector_map = await self.browser_session.get_selector_map()- cached_path_hashes = {e.hash.branch_path_hash for e in cached_selector_map.values()}- break-- # loop over actions and execute them+ cached_selector_map = await self.browser_session.get_selector_map()+ cached_element_hashes = {hash(e) for e in cached_selector_map.values()}++ # await self.browser_session.remove_highlights()+for i, action in enumerate(actions):- # DO NOT ALLOW TO CALL `done` AS A SINGLE ACTION- if i > 0 and action.model_dump(exclude_unset=True).get('done') is not None:- msg = f'Done action is allowed only as a single action - stopped after action {i} / {len(actions)}.'- logger.info(msg)- break+ if i > 0:+ # ONLY ALLOW TO CALL `done` IF IT IS A SINGLE ACTION+ if action.model_dump(exclude_unset=True).get('done') is not None:+ msg = f'Done action is allowed only as a single action - stopped after action {i} / {len(actions)}.'+ logger.info(msg)+ break- if action.get_index() is not None:- new_browser_state_summary = await self.browser_session.get_browser_state_with_recovery(- cache_clickable_elements_hashes=False, include_screenshot=False- )- new_selector_map = new_browser_state_summary.selector_map-- # Detect index change after previous action- orig_target = cached_selector_map.get(action.get_index()) # type: ignore- orig_target_hash = orig_target.hash.branch_path_hash if orig_target else None- new_target = new_selector_map.get(action.get_index()) # type: ignore- new_target_hash = new_target.hash.branch_path_hash if new_target else None- if orig_target_hash != new_target_hash:- msg = f'Element index changed after action {i} / {len(actions)}, because page changed.'- logger.info(msg)- results.append(- ActionResult(- extracted_content=msg,- include_in_memory=True,- long_term_memory=msg,- )+ if action.get_index() is not None and i != 0:+ new_browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)+ new_selector_map = new_browser_state_summary.dom_state.selector_map++ # Detect index change after previous action+ orig_target = cached_selector_map.get(action.get_index()) # type: ignore+ orig_target_hash = hash(orig_target) if orig_target else None+ new_target = new_selector_map.get(action.get_index()) # type: ignore+ new_target_hash = hash(new_target) if new_target else None++ if orig_target_hash != new_target_hash:+ msg = f'Element index changed after action {i} / {len(actions)}, because page changed.'+ logger.info(msg)+ results.append(+ ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ long_term_memory=msg,)- break+ )+ break- new_path_hashes = {e.hash.branch_path_hash for e in new_selector_map.values()}- if check_for_new_elements and not new_path_hashes.issubset(cached_path_hashes):- # next action requires index but there are new elements on the page- msg = f'Something new appeared after action {i} / {len(actions)}, following actions are NOT executed and should be retried.'- logger.info(msg)- results.append(- ActionResult(- extracted_content=msg,- include_in_memory=True,- long_term_memory=msg,- )+ new_element_hashes = {hash(e) for e in new_selector_map.values()}+ if check_for_new_elements and not new_element_hashes.issubset(cached_element_hashes):+ # next action requires index but there are new elements on the page+ msg = f'Something new appeared after action {i} / {len(actions)}, following actions are NOT executed and should be retried.'+ logger.info(msg)+ results.append(+ ActionResult(+ extracted_content=msg,+ include_in_memory=True,+ long_term_memory=msg,)- break+ )+ break+ # wait between actions+ await asyncio.sleep(self.browser_profile.wait_between_actions)+try:await self._raise_if_stopped_or_paused()diff --cc browser_use/browser/session.pyindex bb23a3767,a5acb5a76..40a14e9ab--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@@ -74,9 -54,10 +76,9 @@@ from browser_use.browser.views importURLNotAllowedError,)+ # 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 DOMElementNode, SelectorMap-from browser_use.dom.views import DOMElementNode, SelectorMapfrom browser_use.utils import (is_new_tab_page,match_url_with_domain_pattern,@@@ -181,15 -165,16 +186,17 @@@ def require_healthy_browser(usable_pageelse:try:await self._recover_unresponsive_page(- func.__name__, timeout_ms=int(self.browser_profile.default_navigation_timeout or 5000) + 5_000+ 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(self.agent_current_page.url)}...'+ f'🤕 Crashed page recovery finished, attempting to continue with {func.__name__}() on {_log_pretty_url(page_url)}...')- except Exception:+ 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(self.agent_current_page.url)}...'+ 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@@@ -779,32 -767,31 +808,38 @@@ class BrowserSession(BaseModel)finally:self.browser_pid = None- @retry(wait=0.5, retries=2, timeout=30, semaphore_limit=1, semaphore_scope='self', semaphore_lax=True)+ @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."""- 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))+ # 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) -> None:- """Try all connection methods in order of precedence."""+ 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 firstawait self.setup_browser_via_passed_objects()if self.browser_context:@@@ -2088,21 -2080,11 +2145,20 @@@page = await self.get_current_page()await page.wait_for_selector(selector, state='visible', timeout=timeout)+ @observe_debug(name='inject_highlights', ignore_output=True, ignore_input=True)+ @time_execution_async('--inject_highlights')+ @retry(timeout=10, retries=0)+ async def inject_highlights(self, dom_service: DomService, selector_map: DOMSelectorMap):+ """Inject highlights into the page."""+ await inject_highlighting_script(dom_service, selector_map)+@observe_debug(name='remove_highlights', ignore_output=True, ignore_input=True)- @require_healthy_browser(usable_page=True, reopen_page=True)@time_execution_async('--remove_highlights')- @retry(timeout=2, retries=0)- async def remove_highlights(self):+ @retry(timeout=10, retries=0)+ async def remove_highlights(self, dom_service: DomService):"""+ DEPRECATED+Removes all highlight overlays and labels created by the highlightElement function.Handles cases where the page might be closed or inaccessible."""@@@ -2113,9 -2120,10 +2169,8 @@@selector_map = await self.get_selector_map()return selector_map.get(index)- @require_healthy_browser(usable_page=True, reopen_page=True)@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) -> str | None:+ async def _click_element_node(self, element_node: EnhancedDOMTreeNode) -> str | None:"""Optimized method to click an element using xpath."""@@@ -2244,13 -2263,9 +2312,13 @@@f'⚠️ Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (using fallback title)')- # Only mark as unusable if it's actually about:blank, otherwise preserve the real URL- if page.url == 'about:blank':+ # Only mark as unusable if it's actually a new tab page, otherwise preserve the real URL+ if is_new_tab_page(page.url):- tab_info = TabInfo(page_id=page_id, url=page.url, title='ignore this tab and do not use it')+ tab_info = TabInfo(+ page_id=page_id,- url='about:blank',++ url=page.url,+ title='ignore this tab and do not use it',+ )else:# Preserve the real URL and use a descriptive fallback title# fallback_title = '(title unavailable, page possibly crashed / unresponsive)'@@@ -2321,12 -2323,15 +2389,15 @@@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+ url: URL to navigate to (defaults to 'about:blank')+ new_tab: If True, creates a new tab for navigationReturns:- Page: The page that was navigated+ Page: The page that was navigated"""+ # Clear loading status from previous page+ self._current_page_loading_status = None+# Normalize the URLnormalized_url = normalize_url(url)@@@ -3149,10 -3172,36 +3241,13 @@@If True, cache the clickable elements hashes for the current state.This is used to calculate which elements are new to the LLM since the last message,which helps reduce token usage.+ 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)."""- await self._wait_for_page_and_frames_load()- updated_state = await self._get_updated_state()++ 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_stateself._cached_browser_state_summary = updated_statereturn self._cached_browser_state_summary@@@ -3183,8 -3233,22 +3278,11 @@@except Exception:tabs_info = []- # Create minimal DOM element for error state- minimal_element_tree = DOMElementNode(- tag_name='body',- xpath='/body',- attributes={},- children=[],- is_visible=True,- parent=None,- )-+ # Check if current page is a PDF viewer+ is_pdf_viewer = await self._is_pdf_viewer(page)+return BrowserStateSummary(- element_tree=minimal_element_tree, # Minimal DOM tree- selector_map={}, # Empty selector map+ dom_state=SerializedDOMState(_root=None, selector_map={}),url=url,title=title,tabs=tabs_info,@@@ -3200,16 -3266,72 +3300,53 @@@# Check if current page is still valid, if not switch to another available pagepage = await self.get_current_page()- try:- # Test if page is still accessible- # NOTE: This also happens on invalid urls like www.sadfdsafdssdafd.com- await asyncio.wait_for(page.evaluate('1'), timeout=2.5)- except Exception as e:- self.logger.debug(f'👋 Current page is not accessible: {type(e).__name__}: {e}')- raise BrowserError('Page is not accessible')+ # Check if this is a new tab or chrome:// page early for optimization+ is_empty_page = is_new_tab_page(page.url) or page.url.startswith('chrome://')try:- self.logger.debug('🧹 Removing highlights...')+ # Fast path for empty pages - skip all expensive operations+ if is_empty_page:+ self.logger.debug(f'⚡ Fast path for empty page: {page.url}')+- # Create minimal DOM state immediately- from browser_use.dom.views import DOMElementNode, DOMState-- minimal_element_tree = DOMElementNode(- tag_name='body',- xpath='',- attributes={},- children=[],- is_visible=False,- parent=None,- )- content = DOMState(element_tree=minimal_element_tree, selector_map={})-+ # Get minimal tab info+ tabs_info = await self.get_tabs_info()++ # Skip screenshot for empty pages+ screenshot_b64 = None++ # Use default viewport dimensions from browser profile+ viewport = self.browser_profile.viewport or {'width': 1280, 'height': 720}+ page_info = PageInfo(+ viewport_width=viewport['width'],+ viewport_height=viewport['height'],+ page_width=viewport['width'],+ page_height=viewport['height'],+ scroll_x=0,+ scroll_y=0,+ pixels_above=0,+ pixels_below=0,+ pixels_left=0,+ pixels_right=0,+ )+++ from browser_use.dom.views import SerializedDOMState+++ # Return minimal state immediately+ self.browser_state_summary = BrowserStateSummary(- element_tree=content.element_tree,- selector_map=content.selector_map,++ dom_state=SerializedDOMState(_root=None, selector_map={}),+ url=page.url,+ title='New Tab' if is_new_tab_page(page.url) else 'Chrome Page',+ tabs=tabs_info,+ screenshot=screenshot_b64,+ page_info=page_info,+ pixels_above=0,+ pixels_below=0,+ browser_errors=[],+ is_pdf_viewer=False,+ loading_status=self._current_page_loading_status,+ )+ return self.browser_state_summary+- # Normal path for regular pages- self.logger.debug('🧹 Removing highlights...')- try:- await self.remove_highlights()- except TimeoutError:- self.logger.debug('Timeout to remove highlights')-# Check for PDF and auto-download if neededtry:pdf_path = await self._auto_download_pdf_if_needed(page)@@@ -3219,30 -3341,38 +3356,36 @@@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+ async with DomService(self, page) as dom_service:- await self.remove_highlights(dom_service)++ # Normal path for regular pages++ self.logger.debug('🧹 Removing highlights...')++ try:++ await self.remove_highlights(dom_service)++ except TimeoutError:++ self.logger.debug('Timeout to remove highlights')+- dom_service = DomService(page, logger=self.logger)- try:- content = await asyncio.wait_for(- dom_service.get_clickable_elements(- focus_element=focus_element,- viewport_expansion=self.browser_profile.viewport_expansion,- highlight_elements=self.browser_profile.highlight_elements,- ),- timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages- )- self.logger.debug('✅ DOM processing completed')- except TimeoutError:- self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')- 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 DOMElementNode-- minimal_element_tree = DOMElementNode(- tag_name='body',- xpath='/body',- attributes={},- children=[],- is_visible=True,- parent=None,- )+ try:+ dom_state, timing_info = await asyncio.wait_for(+ dom_service.get_serialized_dom_tree(+ previous_cached_state=self._cached_browser_state_summary.dom_state+ if self._cached_browser_state_summary+ else None,+ ),+ timeout=120.0, # 45 second timeout for DOM processing - generous for complex pages+ )++ await self.inject_highlights(dom_service, dom_state.selector_map)- from browser_use.dom.views import DOMState+ self.logger.debug('✅ DOM processing completed')+ except TimeoutError:+ self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')+ self.logger.warning('🔄 Falling back to minimal DOM state to allow basic navigation...')- content = DOMState(element_tree=minimal_element_tree, selector_map={})+ # Create minimal DOM state for basic navigation++ from browser_use.dom.views import SerializedDOMState++ dom_state = SerializedDOMState(_root=None, selector_map={})self.logger.debug('📋 Getting tabs info...')tabs_info = await self.get_tabs_info()@@@ -3300,8 -3433,12 +3446,11 @@@f'DOM processing timed out for {page.url} - using minimal state. Basic navigation still available via go_to_url, scroll, and search actions.')+ # Check if current page is a PDF viewer+ is_pdf_viewer = await self._is_pdf_viewer(page)+self.browser_state_summary = BrowserStateSummary(- element_tree=content.element_tree,- selector_map=content.selector_map,+ dom_state=dom_state,url=page.url,title=title,tabs=tabs_info,@@@ -3523,10 -3658,25 +3675,43 @@@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),- )+ 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')+++ # 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-entranceself._in_recovery = True@@@ -3875,7 -4027,8 +4061,8 @@@@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:+ async def get_locate_element(self, element: EnhancedDOMTreeNode) -> ElementHandle | None:page = await self.get_current_page()current_frame = page@@@ -4047,7 -4199,8 +4234,8 @@@@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):+ async def _input_text_element_node(self, element_node: EnhancedDOMTreeNode, 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.@@@ -4528,20 -4700,20 +4732,20 @@@Parameters:-----------cache_clickable_elements_hashes: bool- If True, cache the clickable elements hashes for the current state.+ If True, cache the clickable elements hashes for the current state.-- Returns:- --------- BrowserStateSummary: Either full state or minimal fallback 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)++ # Try 1: Full state summary (current implementation) - like main branchtry:- return await self.get_state_summary(cache_clickable_elements_hashes)+ await self._wait_for_page_and_frames_load()+ return await self.get_state_summary(cache_clickable_elements_hashes, 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')- # Try 2: Minimal state summary as fallback+ 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:diff --cc browser_use/browser/views.pyindex b67725f81,03dffe6e3..9af5c894f--- a/browser_use/browser/views.py+++ b/browser_use/browser/views.py@@@ -3,8 -3,14 +3,13 @@@ from typing import Anfrom pydantic import BaseModel-from browser_use.dom.history_tree_processor.service import DOMHistoryElement-from browser_use.dom.views import DOMState+from browser_use.dom.views import DOMInteractedElement, SerializedDOMState+ # Known placeholder image data for about:blank pages - a 4x4 white PNG+ PLACEHOLDER_4PX_SCREENSHOT = (+ 'iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAFElEQVR4nGP8//8/AwwwMSAB3BwAlm4DBfIlvvkAAAAASUVORK5CYII='+ )+# Pydanticclass TabInfo(BaseModel):diff --cc browser_use/dom/service.pyindex 689056358,1c7173746..f6c5c111e--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@@ -1,559 -1,227 +1,562 @@@+import asyncio+ import logging-from importlib import resources+import timefrom typing import TYPE_CHECKING-from urllib.parse import urlparse--if TYPE_CHECKING:- from browser_use.browser.types import Page+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 browser_use.dom.enhanced_snapshot import (+ REQUIRED_COMPUTED_STYLES,+ build_snapshot_lookup,+)+from browser_use.dom.serializer.serializer import DOMTreeSerializerfrom browser_use.dom.views import (- DOMBaseNode,- DOMElementNode,- DOMState,- DOMTextNode,- SelectorMap,- ViewportInfo,+ CurrentPageTargets,+ DOMRect,+ EnhancedAXNode,+ EnhancedAXProperty,+ EnhancedDOMTreeNode,+ NodeType,+ SerializedDOMState,+ TargetAllTrees,)-from browser_use.observability import observe_debug-from browser_use.utils import is_new_tab_page, time_execution_async-# @dataclass-# class ViewportInfo:-# width: int-# height: int+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 = Falseclass DomService:+ """+ Service for getting the DOM tree and other DOM-related information.++ Either browser or page must be provided.++ TODO: currently we start a new websocket connection PER STEP, we should definitely keep this persistent+ """+- def __init__(self, browser: 'BrowserSession', page: 'Page'):+ logger: logging.Logger+- def __init__(self, page: 'Page', logger: logging.Logger | None = None):++ def __init__(self, browser: 'BrowserSession', page: 'Page', logger: logging.Logger | None = None):+ self.browser = browserself.page = page- self.xpath_cache = {}- self.logger = logger or logging.getLogger(__name__)- self.js_code = resources.files('browser_use.dom.dom_tree').joinpath('index.js').read_text()+ self.cdp_client: CDPClient | None = None+ # self.playwright_page_to_session_id_store: dict[str, str] = {}- # region - Clickable elements- @observe_debug(ignore_input=True, ignore_output=True, name='get_clickable_elements')- @time_execution_async('--get_clickable_elements')- async def get_clickable_elements(- self,- highlight_elements: bool = True,- focus_element: int = -1,- viewport_expansion: int = 0,- ) -> DOMState:- element_tree, selector_map = await self._build_dom_tree(highlight_elements, focus_element, viewport_expansion)- return DOMState(element_tree=element_tree, selector_map=selector_map)-- @time_execution_async('--get_cross_origin_iframes')- async def get_cross_origin_iframes(self) -> list[str]:- # invisible cross-origin iframes are used for ads and tracking, dont open those- hidden_frame_urls = await self.page.locator('iframe').filter(visible=False).evaluate_all('e => e.map(e => e.src)')-- is_ad_url = lambda url: any(- domain in urlparse(url).netloc for domain in ('doubleclick.net', 'adroll.com', 'googletagmanager.com')+ self.target_to_session_id_cache: dict[str, str] = {}++ async def _get_cdp_client(self) -> CDPClient:+ if not self.browser.cdp_url:+ raise ValueError('CDP URL is not set')++ # TODO: MOVE THIS TO BROWSER SESSION (or sth idk)+ # If the cdp_url is already a websocket URL, use it as-is.+ if self.browser.cdp_url.startswith('ws'):+ ws_url = self.browser.cdp_url+ else:+ # Otherwise, treat it as the DevTools HTTP root and fetch the websocket URL.+ url = self.browser.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']++ if self.cdp_client is None:+ self.cdp_client = CDPClient(ws_url)+ await self.cdp_client.start()++ return self.cdp_client++ async def __aenter__(self):+ await self._get_cdp_client()+ return self++ # on self destroy -> stop the cdp client+ async def __aexit__(self, exc_type, exc_value, traceback):+ if self.cdp_client:+ await self.cdp_client.stop()+ self.cdp_client = None++ async def _get_targets_for_current_page(self) -> CurrentPageTargets:+ """Get the target ID for a playwright page.++ TODO: this is a REALLY hacky way -> if multiple same urls are open then this will break+ """+ # page_guid = self.page._impl_obj._guid+ # TODO: add cache for page to sessionId++ # if page_guid in self.page_to_session_id_store:+ # return self.page_to_session_id_store[page_guid]++ 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'] == self.page.url), None)++ if not main_target:+ raise ValueError(f'No main page target found for URL: {self.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,)- return [- frame.url- for frame in self.page.frames- if urlparse(frame.url).netloc # exclude data:urls and new tab pages- and urlparse(frame.url).netloc != urlparse(self.page.url).netloc # exclude same-origin iframes- and frame.url not in hidden_frame_urls # exclude hidden frames- and not is_ad_url(frame.url) # exclude most common ad network tracker frame URLs- ]-- @time_execution_async('--build_dom_tree')- async def _build_dom_tree(- self,- highlight_elements: bool,- focus_element: int,- viewport_expansion: int,- ) -> tuple[DOMElementNode, SelectorMap]:- if await self.page.evaluate('1+1') != 2:- raise ValueError('The page cannot evaluate javascript code properly')-- if is_new_tab_page(self.page.url) or self.page.url.startswith('chrome://'):- # short-circuit if the page is a new empty tab or chrome:// page for speed, no need to inject buildDomTree.js- return (- DOMElementNode(- tag_name='body',- xpath='',- attributes={},- children=[],- is_visible=False,- parent=None,- ),- {},- )+ async def _attach_target_activate_domains_get_session_id(self, target: TargetInfo) -> str:+ """This function is cached, so go crazy"""- # NOTE: We execute JS code in the browser to extract important DOM information.- # The returned hash map contains information about the DOM tree and the- # relationship between the DOM elements.- debug_mode = self.logger.getEffectiveLevel() == logging.DEBUG- args = {- 'doHighlightElements': highlight_elements,- 'focusHighlightIndex': focus_element,- 'viewportExpansion': viewport_expansion,- 'debugMode': debug_mode,- }+ cdp_client = await self._get_cdp_client()++ target_id = str(target['targetId'])++ if target_id in self.target_to_session_id_cache:+ return self.target_to_session_id_cache[target_id]++ session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})+ session_id = session['sessionId']++ 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.target_to_session_id_cache[target_id] = session_id++ return session_id++ def _build_enhanced_ax_node(self, ax_node: AXNode) -> EnhancedAXNode:+ 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),+ # related_nodes=[], # TODO: add related nodes+ )+ )+ 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:- self.logger.debug(f'🔧 Starting JavaScript DOM analysis for {self.page.url[:50]}...')- eval_page: dict = await self.page.evaluate(self.js_code, args)- self.logger.debug('✅ JavaScript DOM analysis completed')- except Exception as e:- self.logger.error('Error evaluating JavaScript: %s', e)- raise-- # Only log performance metrics in debug mode- if debug_mode and 'perfMetrics' in eval_page:- perf = eval_page['perfMetrics']-- # Get key metrics for summary- total_nodes = perf.get('nodeMetrics', {}).get('totalNodes', 0)- # processed_nodes = perf.get('nodeMetrics', {}).get('processedNodes', 0)-- # Count interactive elements from the DOM map- interactive_count = 0- if 'map' in eval_page:- for node_data in eval_page['map'].values():- if isinstance(node_data, dict) and node_data.get('isInteractive'):- interactive_count += 1-- # Create concise summary- url_short = self.page.url[:50] + '...' if len(self.page.url) > 50 else self.page.url- self.logger.debug(- '🔎 Ran buildDOMTree.js interactive element detection on: %s interactive=%d/%d\n',- url_short,- interactive_count,- total_nodes,- # processed_nodes,- )+ cdp_client = await self._get_cdp_client()- self.logger.debug('🔄 Starting Python DOM tree construction...')- result = await self._construct_dom_tree(eval_page)- self.logger.debug('✅ Python DOM tree construction completed')- return result+ # Get the layout metrics which includes the visual viewport+ metrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)- @time_execution_async('--construct_dom_tree')- async def _construct_dom_tree(- self,- eval_page: dict,- ) -> tuple[DOMElementNode, SelectorMap]:- js_node_map = eval_page['map']- js_root_id = eval_page['rootId']+ visual_viewport = metrics.get('visualViewport', {})- selector_map = {}- node_map = {}+ # 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', {})- for id, node_data in js_node_map.items():- node, children_ids = self._parse_node(node_data)- if node is None:- continue+ # Use CSS pixels (what JavaScript sees) instead of device pixels+ width = css_visual_viewport.get('clientWidth', css_layout_viewport.get('clientWidth', 1920.0))- node_map[id] = node+ # 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- if isinstance(node, DOMElementNode) and node.highlight_index is not None:- selector_map[node.highlight_index] = node+ return float(device_pixel_ratio)+ except Exception as e:+ print(f'⚠️ Viewport size detection failed: {e}')+ # Fallback to default viewport size+ return 1.0++ @classmethod+ def is_element_visible_according_to_all_parents(+ cls, node: EnhancedDOMTreeNode, html_frames: list[EnhancedDOMTreeNode]+ ) -> bool:+ """Check if the element is visible according to all its parent HTML frames."""- # NOTE: We know that we are building the tree bottom up- # and all children are already processed.- if isinstance(node, DOMElementNode):- for child_id in children_ids:- if child_id not in node_map:- continue+ if not node.snapshot_node:+ return False- child_node = node_map[child_id]+ computed_styles = node.snapshot_node.computed_styles or {}- child_node.parent = node- node.children.append(child_node)+ display = computed_styles.get('display', '').lower()+ visibility = computed_styles.get('visibility', '').lower()+ opacity = computed_styles.get('opacity', '1')- html_to_dict = node_map[str(js_root_id)]+ if display == 'none' or visibility == 'hidden':+ return False- del node_map- del js_node_map- del js_root_id+ 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++ 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:+ if not self.browser.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,+ )- if html_to_dict is None or not isinstance(html_to_dict, DOMElementNode):- raise ValueError('Failed to parse HTML to dictionary')+ dom_tree_request = cdp_client.send.DOM.getDocument(params={'depth': -1, 'pierce': True}, session_id=session_id)- return html_to_dict, selector_map+ ax_tree_request = self._get_ax_tree_for_all_frames(session_id)- def _parse_node(+ 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}+ print(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,- node_data: dict,- ) -> tuple[DOMBaseNode | None, list[int]]:- if not node_data:- return None, []-- # Process text nodes immediately- if node_data.get('type') == 'TEXT_NODE':- text_node = DOMTextNode(- text=node_data['text'],- is_visible=node_data['isVisible'],- parent=None,- )- return text_node, []+ target: TargetInfo,+ initial_html_frames: list[EnhancedDOMTreeNode] | None = None,+ initial_total_frame_offset: DOMRect | None = None,+ ) -> EnhancedDOMTreeNode:+ # Get viewport dimensions first for visibility calculation- # Process coordinates if they exist for element nodes+ session_id = await self._attach_target_activate_domains_get_session_id(target)- viewport_info = None+ trees = await self._get_all_trees_for_session_id(session_id)- if 'viewport' in node_data:- viewport_info = ViewportInfo(- width=node_data['viewport']['width'],- height=node_data['viewport']['height'],- )+ dom_tree = trees.dom_tree+ ax_tree = trees.ax_tree+ snapshot = trees.snapshot+ device_pixel_ratio = trees.device_pixel_ratio- element_node = DOMElementNode(- tag_name=node_data['tagName'],- xpath=node_data['xpath'],- attributes=node_data.get('attributes', {}),- children=[],- is_visible=node_data.get('isVisible', False),- is_interactive=node_data.get('isInteractive', False),- is_top_element=node_data.get('isTopElement', False),- is_in_viewport=node_data.get('isInViewport', False),- highlight_index=node_data.get('highlightIndex'),- shadow_root=node_data.get('shadowRoot', False),- parent=None,- viewport_info=viewport_info,- )+ ax_tree_lookup: dict[int, AXNode] = {+ ax_node['backendDOMNodeId']: ax_node for ax_node in ax_tree['nodes'] if 'backendDOMNodeId' in ax_node+ }- children_ids = node_data.get('children', [])+ enhanced_dom_tree_node_lookup: dict[int, EnhancedDOMTreeNode] = {}+ """ NodeId (NOT backend node id) -> enhanced dom tree node""" # way to get the parent/content 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+ accumulated_iframe_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 the mf (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,+ )- return element_node, children_ids+ 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+ # forcefully set the parent node to the content document node (helps traverse the tree)++ 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)+ # forcefully set the parent node to the shadow root node (helps traverse the tree)+ 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)+ # only do this if the iframe is visible (otherwise it's not worth it)++ if (+ # TODO: hacky way to disable cross origin iframes for now+ ENABLE_CROSS_ORIGIN_IFRAMES and node['nodeName'].upper() == 'IFRAME' and node.get('contentDocument', None) is None+ ): # None meaning there is no content+ 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 target actually exists in one of the frames, just recursively build the dom tree for it+ if iframe_document_target:+ print(f'🔍 Getting content document for iframe {node.get("frameId", None)}')+ content_document = await self.get_dom_tree(+ iframe_document_target,+ # TODO: experiment with this values -> not sure whether the whole cross origin iframe should be ALWAYS included as soon as some part of it is visible or not.+ # Current config: if the cross origin iframe is AT ALL visible, then just include everything inside of it!+ # initial_html_frames=updated_html_frames,+ 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 get_serialized_dom_tree(+ self, previous_cached_state: SerializedDOMState | None = None+ ) -> tuple[SerializedDOMState, dict[str, float]]:+ """Get the serialized DOM tree representation for LLM consumption.++ TODO: this is a bit of a hack, we should probably have a better way to do this+ """++ page_session_info = await self._get_targets_for_current_page()+ enhanced_dom_tree = await self.get_dom_tree(page_session_info.page_session)++ start = time.time()+ serialized_dom_state, serializer_timing = DOMTreeSerializer(+ enhanced_dom_tree, previous_cached_state+ ).serialize_accessible_elements()++ end = time.time()+ serialize_total_timing = {'serialize_dom_tree_total': end - start}+ print(f'Time taken to serialize dom tree: {end - start} seconds')++ # Combine all timing info+ all_timing = {**serializer_timing, **serialize_total_timing}++ return serialized_dom_state, all_timingdiff --cc pyproject.tomlindex 8fa9553f9,d23fb5b81..bf14830dd--- a/pyproject.toml+++ b/pyproject.toml@@@ -41,8 -41,7 +41,8 @@@ dependencies ="google-auth-oauthlib>=1.2.2","mcp>=1.10.1","pypdf>=5.7.0",+ "cdp-use>=1.3.2",- "markdown-pdf>=1.7",+ "markdown-pdf==1.5",]# google-api-core: only used for Google LLM APIs# pyperclip: only used for examples that use copy/paste