Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

new cdp_session singleton for current page

Nick Sweeting482604115423
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 9121d4d70..b2371fcbb 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -482,26 +482,10 @@ class Agent(Generic[Context, AgentStructuredOutput]):
_browser_session_id = self.browser_session.id if self.browser_session else self.id
_current_page_id = (
- self.browser_session.current_target_id[-2:]
- if self.browser_session and self.browser_session.current_target_id
- else '--'
+ self.browser_session.cdp_session.target_id[-2:] if self.browser_session and self.browser_session.cdp_session else '--'
)
return logging.getLogger(f'browser_use.Agent🅰 {self.task_id[-4:]} on 🆂 {_browser_session_id[-4:]} 🅟 {_current_page_id}')
- @property
- def browser(self) -> Browser:
- assert self.browser_session is not None, 'BrowserSession is not set up'
- assert self.browser_session.browser is not None, 'Browser is not set up'
- return self.browser_session.browser
-
- @property
- def browser_context(self) -> BrowserContext:
- # Deprecated - browser_context no longer exists with CDP-only approach
- assert self.browser_session is not None, 'BrowserSession is not set up'
- assert self.browser_session.cdp_client is not None, 'CDP client is not set up'
- # Return None or raise since we don't have browser_context anymore
- raise NotImplementedError('browser_context is deprecated - use browser_session.cdp_client instead')
-
@property
def browser_profile(self) -> BrowserProfile:
assert self.browser_session is not None, 'BrowserSession is not set up'
@@ -1449,7 +1433,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):
break
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_browser_state_summary = await self.browser_session.get_browser_state_summary(
+ cache_clickable_elements_hashes=False
+ )
new_selector_map = new_browser_state_summary.dom_state.selector_map
# Detect index change after previous action
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.py
index aeb7beca7..031793314 100644
--- a/browser_use/browser/aboutblank_watchdog.py
+++ b/browser_use/browser/aboutblank_watchdog.py
@@ -156,7 +156,7 @@ class AboutBlankWatchdog(BaseWatchdog):
"""
try:
# Get cached session
- client, session_id = await self.browser_session.get_cdp_session(target_id)
+ cdp_session = await self.browser_session.attach_cdp_session(target_id)
# Inject the DVD screensaver script (from main branch with idempotency added)
script = f"""
@@ -268,7 +268,7 @@ class AboutBlankWatchdog(BaseWatchdog):
}})('{browser_session_label}');
"""
- await client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)
+ await cdp_session.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=cdp_session.session_id)
# No need to detach - session is cached
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index 16a109ff5..94b1b0ec7 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -68,18 +68,18 @@ class CrashWatchdog(BaseWatchdog):
async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Attach to new tab."""
- assert self.browser_session.current_target_id is not None, 'No current target ID'
- await self.attach_to_target(self.browser_session.current_target_id)
+ assert self.browser_session.cdp_session is not None, 'No current target ID'
+ await self.attach_to_target(self.browser_session.cdp_session.target_id)
async def attach_to_target(self, target_id: str) -> None:
"""Set up crash monitoring for a specific target using CDP."""
try:
- # Get cached session (domains already enabled by get_cdp_session)
- cdp_client, session_id = await self.browser_session.get_cdp_session(target_id)
+ # Get cached session (domains already enabled by attach_cdp_session)
+ cdp_session = await self.browser_session.attach_cdp_session(target_id)
# Check if we already have listeners for this session
- if session_id in self._sessions_with_listeners:
- self.logger.debug(f'[CrashWatchdog] Event listeners already exist for session: {session_id}')
+ if cdp_session.session_id in self._sessions_with_listeners:
+ self.logger.debug(f'[CrashWatchdog] Event listeners already exist for session: {cdp_session.session_id}')
return
# Set up network event handlers
@@ -106,7 +106,6 @@ class CrashWatchdog(BaseWatchdog):
# cdp_client.on('Network.loadingFailed', on_loading_failed, session_id=session_id)
# cdp_client.on('Network.loadingFinished', on_loading_finished, session_id=session_id)
- # Set up crash handler (Inspector domain already enabled by get_cdp_session)
def on_target_crashed(event: TargetCrashedEvent, session_id: str | None = None):
# Create and track the task
task = asyncio.create_task(self._on_target_crash_cdp(target_id))
@@ -114,13 +113,13 @@ class CrashWatchdog(BaseWatchdog):
# Remove from set when done
task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))
- cdp_client.register.Target.targetCrashed(on_target_crashed)
+ cdp_session.cdp_client.register.Target.targetCrashed(on_target_crashed)
# Track that we've added listeners to this session
- self._sessions_with_listeners.add(session_id)
+ self._sessions_with_listeners.add(cdp_session.session_id)
# Get target info for logging
- targets = await cdp_client.send.Target.getTargets()
+ targets = await cdp_session.cdp_client.send.Target.getTargets()
target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)
if target_info:
self.logger.debug(f'[CrashWatchdog] Added target to monitoring: {target_info.get("url", "unknown")}')
@@ -172,8 +171,9 @@ class CrashWatchdog(BaseWatchdog):
cdp_client = self.browser_session.cdp_client
targets = await cdp_client.send.Target.getTargets()
target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)
- if target_info and target_info['targetId'] == self.browser_session.current_target_id:
- self.browser_session.current_target_id = None
+ if target_info and target_info['targetId'] == self.browser_session.cdp_session.target_id:
+ self.browser_session.cdp_session.target_id = None # type: ignore
+ self.browser_session.cdp_session.session_id = None # type: ignore
self.logger.error(
f'[CrashWatchdog] 💥 Target crashed, navigating Agent to a new tab: {target_info.get("url", "unknown")}'
)
@@ -205,7 +205,6 @@ class CrashWatchdog(BaseWatchdog):
self._monitoring_task = asyncio.create_task(self._monitoring_loop())
# logger.debug('[CrashWatchdog] Monitoring loop created and started')
-
async def _stop_monitoring(self) -> None:
"""Stop the monitoring loop."""
if self._monitoring_task and not self._monitoring_task.done():
@@ -287,12 +286,15 @@ class CrashWatchdog(BaseWatchdog):
"""Check if browser and targets are still responsive."""
try:
- client, session_id = await self.browser_session.get_cdp_session()
+ cdp_session = await self.browser_session.attach_cdp_session()
# Quick ping to check if session is alive
- await asyncio.wait_for(client.send.Runtime.evaluate(params={'expression': '1'}, session_id=session_id), timeout=1.0)
+ await asyncio.wait_for(
+ cdp_session.cdp_client.send.Runtime.evaluate(params={'expression': '1'}, session_id=cdp_session.session_id),
+ timeout=1.0,
+ )
except Exception as e:
- self.logger.error(f'[CrashWatchdog] ❌ Crashed session detected for target {self.browser_session.current_target_id}')
- self.browser_session.current_target_id = None
+ self.logger.error(f'[CrashWatchdog] ❌ Crashed session detected for target {self.browser_session.cdp_session}')
+ self.browser_session.cdp_session.target_id = None # type: ignore
# Check browser process if we have PID
if self.browser_session._local_browser_watchdog and (proc := self.browser_session._local_browser_watchdog._subprocess):
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.py
index 5eaeb1203..49e92770c 100644
--- a/browser_use/browser/default_action_watchdog.py
+++ b/browser_use/browser/default_action_watchdog.py
@@ -3,8 +3,6 @@
import asyncio
from typing import TYPE_CHECKING
-from cdp_use import CDPClient
-
from browser_use.browser.events import (
BrowserErrorEvent,
ClickElementEvent,
@@ -20,6 +18,7 @@ from browser_use.browser.events import (
)
from browser_use.browser.views import BrowserError, URLNotAllowedError
from browser_use.browser.watchdog_base import BaseWatchdog
+from browser_use.dom.service import EnhancedDOMTreeNode
if TYPE_CHECKING:
pass
@@ -75,15 +74,15 @@ class DefaultActionWatchdog(BaseWatchdog):
self.logger.debug(f'Element xpath: {element_node.xpath}')
# Check if a new tab was opened
- current_target_ids = await self.browser_session._cdp_get_all_pages()
- if len(current_target_ids) > len(initial_target_ids):
+ after_target_ids = await self.browser_session._cdp_get_all_pages()
+ if len(after_target_ids) > len(initial_target_ids):
new_tab_msg = 'New tab opened - switching to it'
msg += f' - {new_tab_msg}'
self.logger.info(f'🔗 {new_tab_msg}')
# Switch to the last tab (newly created tab)
from browser_use.browser.events import SwitchTabEvent
- last_tab_index = len(current_target_ids) - 1
+ last_tab_index = len(after_target_ids) - 1
await self.event_bus.dispatch(SwitchTabEvent(tab_index=last_tab_index))
# Return download_path if any
@@ -126,7 +125,7 @@ class DefaultActionWatchdog(BaseWatchdog):
"""Handle scroll request with CDP."""
try:
# Check if we have a current target for scrolling
- if not self.browser_session.current_target_id:
+ if not self.browser_session.cdp_session:
raise ValueError('No active target for scrolling')
except ValueError as e:
self.event_bus.dispatch(
@@ -187,16 +186,18 @@ class DefaultActionWatchdog(BaseWatchdog):
try:
# Get CDP client
- cdp_client = self.browser_session.cdp_client
+ cdp_session = await self.browser_session.attach_cdp_session()
# Get the correct session ID for the element's frame
- session_id = await self._get_session_id_for_element(cdp_client, element_node)
+ session_id = await self._get_session_id_for_element(element_node)
# Get element bounds
backend_node_id = element_node.backend_node_id
# Get bounds from CDP
- box_model = await cdp_client.send.DOM.getBoxModel(params={'backendNodeId': backend_node_id}, session_id=session_id)
+ box_model = await cdp_session.cdp_client.send.DOM.getBoxModel(
+ params={'backendNodeId': backend_node_id}, session_id=session_id
+ )
content_quad = box_model['model']['content']
if len(content_quad) < 8:
raise Exception('Invalid content quad')
@@ -207,7 +208,9 @@ class DefaultActionWatchdog(BaseWatchdog):
# Scroll element into view
try:
- await cdp_client.send.DOM.scrollIntoViewIfNeeded(params={'backendNodeId': backend_node_id}, session_id=session_id)
+ await cdp_session.cdp_client.send.DOM.scrollIntoViewIfNeeded(
+ params={'backendNodeId': backend_node_id}, session_id=session_id
+ )
await asyncio.sleep(0.1) # Wait for scroll to complete
except Exception as e:
self.logger.debug(f'Failed to scroll element into view: {e}')
@@ -219,7 +222,7 @@ class DefaultActionWatchdog(BaseWatchdog):
if self.browser_session.browser_profile.downloads_path:
# Enable download events
- await cdp_client.send.Page.setDownloadBehavior(
+ await cdp_session.cdp_client.send.Page.setDownloadBehavior(
params={'behavior': 'allow', 'downloadPath': str(self.browser_session.browser_profile.downloads_path)},
session_id=session_id,
)
@@ -236,7 +239,7 @@ class DefaultActionWatchdog(BaseWatchdog):
# Perform the click using CDP
try:
# Move mouse to element
- await cdp_client.send.Input.dispatchMouseEvent(
+ await cdp_session.cdp_client.send.Input.dispatchMouseEvent(
params={
'type': 'mouseMoved',
'x': center_x,
@@ -246,7 +249,7 @@ class DefaultActionWatchdog(BaseWatchdog):
)
# Mouse down
- await cdp_client.send.Input.dispatchMouseEvent(
+ await cdp_session.cdp_client.send.Input.dispatchMouseEvent(
params={
'type': 'mousePressed',
'x': center_x,
@@ -258,7 +261,7 @@ class DefaultActionWatchdog(BaseWatchdog):
)
# Mouse up
- await cdp_client.send.Input.dispatchMouseEvent(
+ await cdp_session.cdp_client.send.Input.dispatchMouseEvent(
params={
'type': 'mouseReleased',
'x': center_x,
@@ -268,7 +271,7 @@ class DefaultActionWatchdog(BaseWatchdog):
},
session_id=session_id,
)
-
+
# TODO: do occlusion detection, if element is not on the top, fire JS-based click event instead of x,y coordinate clicking
# Handle download if expected: should be handled by downloads_watchdog.py now using browser-level download event listeners
@@ -313,13 +316,16 @@ class DefaultActionWatchdog(BaseWatchdog):
self.logger.warning(f'CDP click failed: {type(e).__name__}: {e}')
# Fall back to JavaScript click via CDP
try:
- result = await cdp_client.send.DOM.resolveNode(
+ result = await cdp_session.cdp_client.send.DOM.resolveNode(
params={'backendNodeId': backend_node_id},
session_id=session_id,
)
+ assert 'object' in result and 'objectId' in result['object'], (
+ 'Failed to find DOM element based on backendNodeId, maybe page content changed?'
+ )
object_id = result['object']['objectId']
- await cdp_client.send.Runtime.callFunctionOn(
+ await cdp_session.cdp_client.send.Runtime.callFunctionOn(
params={
'functionDeclaration': 'function() { this.click(); }',
'objectId': object_id,
@@ -348,7 +354,7 @@ class DefaultActionWatchdog(BaseWatchdog):
cdp_client = self.browser_session.cdp_client
# Get the correct session ID for the element's frame
- session_id = await self._get_session_id_for_element(cdp_client, element_node)
+ session_id = await self._get_session_id_for_element(element_node)
# Get element info
backend_node_id = element_node.backend_node_id
@@ -365,6 +371,9 @@ class DefaultActionWatchdog(BaseWatchdog):
params={'backendNodeId': backend_node_id},
session_id=session_id,
)
+ assert 'object' in result and 'objectId' in result['object'], (
+ 'Failed to find DOM element based on backendNodeId, maybe page content changed?'
+ )
object_id = result['object']['objectId']
# Clear existing text if requested
@@ -431,8 +440,9 @@ class DefaultActionWatchdog(BaseWatchdog):
"""
try:
# Get CDP client and session
- cdp_client = self.browser_session.cdp_client
- session_id = await self.browser_session.get_current_page_cdp_session_id()
+ assert self.browser_session.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'
+ cdp_client = self.browser_session.cdp_session.cdp_client
+ session_id = self.browser_session.cdp_session.session_id
# Get viewport dimensions
layout_metrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)
@@ -468,15 +478,13 @@ class DefaultActionWatchdog(BaseWatchdog):
async def _scroll_element_container(self, element_node, pixels: int) -> bool:
"""Try to scroll an element's container using CDP."""
try:
- # Get CDP client
- cdp_client = self.browser_session.cdp_client
-
- # Get the correct session ID for the element's frame
- session_id = await self._get_session_id_for_element(cdp_client, element_node)
+ cdp_session = await self.browser_session.cdp_client_for_node(element_node)
# Get element bounds to know where to scroll
backend_node_id = element_node.backend_node_id
- box_model = await cdp_client.send.DOM.getBoxModel(params={'backendNodeId': backend_node_id}, session_id=session_id)
+ box_model = await cdp_session.cdp_client.send.DOM.getBoxModel(
+ params={'backendNodeId': backend_node_id}, session_id=cdp_session.session_id
+ )
content_quad = box_model['model']['content']
# Calculate center point
@@ -484,7 +492,7 @@ class DefaultActionWatchdog(BaseWatchdog):
center_y = (content_quad[1] + content_quad[3] + content_quad[5] + content_quad[7]) / 4
# Dispatch mouse wheel event at element location
- await cdp_client.send.Input.dispatchMouseEvent(
+ await cdp_session.cdp_client.send.Input.dispatchMouseEvent(
params={
'type': 'mouseWheel',
'x': center_x,
@@ -492,7 +500,7 @@ class DefaultActionWatchdog(BaseWatchdog):
'deltaX': 0,
'deltaY': pixels,
},
- session_id=session_id,
+ session_id=cdp_session.session_id,
)
return True
@@ -500,22 +508,21 @@ class DefaultActionWatchdog(BaseWatchdog):
self.logger.debug(f'Failed to scroll element container via CDP: {e}')
return False
- async def _get_session_id_for_element(self, cdp_client: CDPClient, element_node) -> str | None:
+ async def _get_session_id_for_element(self, element_node: EnhancedDOMTreeNode) -> str | None:
"""Get the appropriate CDP session ID for an element based on its frame."""
if element_node.frame_id:
# Element is in an iframe, need to get session for that frame
try:
# Get all targets
- targets = await cdp_client.send.Target.getTargets()
+ targets = await self.browser_session.cdp_client.send.Target.getTargets()
# Find the target for this frame
for target in targets['targetInfos']:
if target['type'] == 'iframe' and element_node.frame_id in str(target.get('targetId', '')):
# Get cached session for this target
target_id = target['targetId']
- client, session_id = await self.browser_session.get_cdp_session(target_id)
- # Domains are already enabled by get_cdp_session
- return session_id
+ cdp_session = await self.browser_session.attach_cdp_session(target_id)
+ return cdp_session.session_id
# If frame not found in targets, use main target session
self.logger.debug(f'Frame {element_node.frame_id} not found in targets, using main session')
@@ -523,17 +530,17 @@ class DefaultActionWatchdog(BaseWatchdog):
self.logger.debug(f'Error getting frame session: {e}, using main session')
# Use main target session
- return await self.browser_session.get_current_page_cdp_session_id()
+ assert self.browser_session.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'
+ return self.browser_session.cdp_session.session_id
async def on_GoBackEvent(self, event: GoBackEvent) -> None:
"""Handle navigate back request with CDP."""
+ cdp_session = await self.browser_session.attach_cdp_session()
try:
# Get CDP client and session
- cdp_client = self.browser_session.cdp_client
- session_id = await self.browser_session.get_current_page_cdp_session_id()
# Get navigation history
- history = await cdp_client.send.Page.getNavigationHistory(session_id=session_id)
+ history = await cdp_session.cdp_client.send.Page.getNavigationHistory(session_id=cdp_session.session_id)
current_index = history['currentIndex']
entries = history['entries']
@@ -544,7 +551,9 @@ class DefaultActionWatchdog(BaseWatchdog):
# Navigate to the previous entry
previous_entry_id = entries[current_index - 1]['id']
- await cdp_client.send.Page.navigateToHistoryEntry(params={'entryId': previous_entry_id}, session_id=session_id)
+ await cdp_session.cdp_client.send.Page.navigateToHistoryEntry(
+ params={'entryId': previous_entry_id}, session_id=cdp_session.session_id
+ )
# Wait for navigation
await asyncio.sleep(0.5)
@@ -561,13 +570,10 @@ class DefaultActionWatchdog(BaseWatchdog):
async def on_GoForwardEvent(self, event: GoForwardEvent) -> None:
"""Handle navigate forward request with CDP."""
+ cdp_session = await self.browser_session.attach_cdp_session()
try:
- # Get CDP client and session
- cdp_client = self.browser_session.cdp_client
- session_id = await self.browser_session.get_current_page_cdp_session_id()
-
# Get navigation history
- history = await cdp_client.send.Page.getNavigationHistory(session_id=session_id)
+ history = await cdp_session.cdp_client.send.Page.getNavigationHistory(session_id=cdp_session.session_id)
current_index = history['currentIndex']
entries = history['entries']
@@ -578,7 +584,9 @@ class DefaultActionWatchdog(BaseWatchdog):
# Navigate to the next entry
next_entry_id = entries[current_index + 1]['id']
- await cdp_client.send.Page.navigateToHistoryEntry(params={'entryId': next_entry_id}, session_id=session_id)
+ await cdp_session.cdp_client.send.Page.navigateToHistoryEntry(
+ params={'entryId': next_entry_id}, session_id=cdp_session.session_id
+ )
# Wait for navigation
await asyncio.sleep(0.5)
@@ -595,13 +603,10 @@ class DefaultActionWatchdog(BaseWatchdog):
async def on_RefreshEvent(self, event: RefreshEvent) -> None:
"""Handle target refresh request with CDP."""
+ cdp_session = await self.browser_session.attach_cdp_session()
try:
- # Get CDP client and session
- cdp_client = self.browser_session.cdp_client
- session_id = await self.browser_session.get_current_page_cdp_session_id()
-
# Reload the target
- await cdp_client.send.Page.reload(session_id=session_id)
+ await cdp_session.cdp_client.send.Page.reload(session_id=cdp_session.session_id)
# Wait for reload
await asyncio.sleep(1.0)
@@ -637,11 +642,8 @@ class DefaultActionWatchdog(BaseWatchdog):
async def on_SendKeysEvent(self, event: SendKeysEvent) -> None:
"""Handle send keys request with CDP."""
+ cdp_session = await self.browser_session.attach_cdp_session()
try:
- # Get CDP client and session
- cdp_client = self.browser_session.cdp_client
- session_id = await self.browser_session.get_current_page_cdp_session_id()
-
# Parse key combination
keys = event.keys.lower()
@@ -663,21 +665,21 @@ class DefaultActionWatchdog(BaseWatchdog):
modifiers |= 4 # Meta/Command
# Send key with modifiers
- await cdp_client.send.Input.dispatchKeyEvent(
+ await cdp_session.cdp_client.send.Input.dispatchKeyEvent(
params={
'type': 'keyDown',
'key': key.capitalize() if len(key) == 1 else key,
'modifiers': modifiers,
},
- session_id=session_id,
+ session_id=cdp_session.session_id,
)
- await cdp_client.send.Input.dispatchKeyEvent(
+ await cdp_session.cdp_client.send.Input.dispatchKeyEvent(
params={
'type': 'keyUp',
'key': key.capitalize() if len(key) == 1 else key,
'modifiers': modifiers,
},
- session_id=session_id,
+ session_id=cdp_session.session_id,
)
else:
# Single key
@@ -702,13 +704,13 @@ class DefaultActionWatchdog(BaseWatchdog):
key = key_map.get(keys, keys)
- await cdp_client.send.Input.dispatchKeyEvent(
+ await cdp_session.cdp_client.send.Input.dispatchKeyEvent(
params={'type': 'keyDown', 'key': key},
- session_id=session_id,
+ session_id=cdp_session.session_id,
)
- await cdp_client.send.Input.dispatchKeyEvent(
+ await cdp_session.cdp_client.send.Input.dispatchKeyEvent(
params={'type': 'keyUp', 'key': key},
- session_id=session_id,
+ session_id=cdp_session.session_id,
)
self.logger.info(f'⌨️ Sent keys: {event.keys}')
@@ -734,7 +736,7 @@ class DefaultActionWatchdog(BaseWatchdog):
# Get CDP client and session
cdp_client = self.browser_session.cdp_client
- session_id = await self._get_session_id_for_element(cdp_client, element_node)
+ session_id = await self._get_session_id_for_element(element_node)
# Set file(s) to upload
backend_node_id = element_node.backend_node_id
@@ -761,7 +763,8 @@ class DefaultActionWatchdog(BaseWatchdog):
try:
# Get CDP client and session
cdp_client = self.browser_session.cdp_client
- session_id = await self.browser_session.get_current_page_cdp_session_id()
+ assert self.browser_session.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'
+ session_id = self.browser_session.cdp_session.session_id
# Enable DOM
await cdp_client.send.DOM.enable(session_id=session_id)
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 296133b0f..aa4f1ef09 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -128,7 +128,7 @@ class DownloadsWatchdog(BaseWatchdog):
# Note: Since download listeners are set up once per browser session, not per target,
# we just track if we've set up the browser-level listener
if self._download_cdp_session_setup:
- self.logger.debug(f'[DownloadsWatchdog] Download listener already set up for browser session')
+ self.logger.debug('[DownloadsWatchdog] Download listener already set up for browser session')
return
# logger.debug(f'[DownloadsWatchdog] Setting up CDP download listener for target: {target_id}')
@@ -454,13 +454,13 @@ class DownloadsWatchdog(BaseWatchdog):
try:
# Get cached session
- cdp_client, session_id = await self.browser_session.get_cdp_session(target_id)
+ cdp_session = await self.browser_session.attach_cdp_session(target_id)
# Add timeout to prevent hanging on unresponsive pages
import asyncio
result = await asyncio.wait_for(
- cdp_client.send.Runtime.evaluate(
+ cdp_session.cdp_client.send.Runtime.evaluate(
params={
'expression': """
(() => {
@@ -517,7 +517,7 @@ class DownloadsWatchdog(BaseWatchdog):
""",
'returnByValue': True,
},
- session_id=session_id,
+ session_id=cdp_session.session_id,
),
timeout=5.0, # 5 second timeout to prevent hanging
)
@@ -556,13 +556,13 @@ class DownloadsWatchdog(BaseWatchdog):
try:
# Get cached session
- cdp_client, session_id = await self.browser_session.get_cdp_session(target_id)
+ cdp_session = await self.browser_session.attach_cdp_session(target_id)
# Try to get the PDF URL with timeout
import asyncio
result = await asyncio.wait_for(
- cdp_client.send.Runtime.evaluate(
+ cdp_session.cdp_client.send.Runtime.evaluate(
params={
'expression': """
(() => {
@@ -576,7 +576,7 @@ class DownloadsWatchdog(BaseWatchdog):
""",
'returnByValue': True,
},
- session_id=session_id,
+ session_id=cdp_session.session_id,
),
timeout=5.0, # 5 second timeout to prevent hanging
)
@@ -611,7 +611,7 @@ class DownloadsWatchdog(BaseWatchdog):
escaped_pdf_url = json.dumps(pdf_url)
result = await asyncio.wait_for(
- cdp_client.send.Runtime.evaluate(
+ cdp_session.cdp_client.send.Runtime.evaluate(
params={
'expression': f"""
(async () => {{
@@ -648,7 +648,7 @@ class DownloadsWatchdog(BaseWatchdog):
'awaitPromise': True,
'returnByValue': True,
},
- session_id=session_id,
+ session_id=cdp_session.session_id,
),
timeout=10.0, # 10 second timeout for download operation
)
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index 4c945ecfd..e1057623c 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -1,13 +1,13 @@
"""Event definitions for browser communication."""
-from typing import Any, Generic, Literal
+from typing import Any, Literal
from bubus import BaseEvent
from bubus.models import T_EventResultType
from pydantic import Field, field_validator
+from browser_use.browser.views import BrowserStateSummary
from browser_use.dom.views import EnhancedDOMTreeNode
-from typing_extensions import TypeVar
# ============================================================================
# Agent/Controller -> BrowserSession Events (High-level browser actions)
@@ -35,7 +35,7 @@ class ElementSelectedEvent(BaseEvent[T_EventResultType]):
is_scrollable=data.is_scrollable,
is_visible=data.is_visible,
absolute_position=data.absolute_position,
- # override the circular reference fields in EnhancedDOMTreeNode as they cant be serialized and arent needed by event handlers
+ # override the circular reference fields in EnhancedDOMTreeNode as they cant be serialized and aren't needed by event handlers
content_document=None,
shadow_root_type=None,
shadow_roots=[],
@@ -100,7 +100,7 @@ class ScreenshotEvent(BaseEvent):
clip: dict[str, float] | None = None # {x, y, width, height}
-class BrowserStateRequestEvent(BaseEvent):
+class BrowserStateRequestEvent(BaseEvent[BrowserStateSummary]):
"""Request current browser state."""
include_dom: bool = True
diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.py
index 49672c0dd..6a4a73676 100644
--- a/browser_use/browser/navigation_watchdog.py
+++ b/browser_use/browser/navigation_watchdog.py
@@ -4,7 +4,7 @@ import asyncio
from typing import TYPE_CHECKING, Any, ClassVar
from bubus import BaseEvent
-from pydantic import Field, PrivateAttr
+from pydantic import PrivateAttr
from browser_use.browser.events import (
AgentFocusChangedEvent,
@@ -45,9 +45,6 @@ class NavigationWatchdog(BaseWatchdog):
NavigationCompleteEvent,
]
- # Agent focus tracking - using target IDs
- current_target_id: str | None = Field(default=None, exclude=True)
-
# Track target close handlers
_target_close_handlers: dict[str, Any] = PrivateAttr(default_factory=dict)
@@ -67,7 +64,8 @@ class NavigationWatchdog(BaseWatchdog):
"""Clear agent focus when browser stops."""
# Clear target handlers
self._target_close_handlers.clear()
- self.browser_session.current_target_id = None
+ assert self.browser_session.cdp_session is not None, 'No current target ID'
+ self.browser_session.cdp_session.target_id = None
# ========== Tab Lifecycle Events ==========
@@ -194,7 +192,8 @@ class NavigationWatchdog(BaseWatchdog):
)
# Update agent focus to the new tab immediately
- self.browser_session.current_target_id = target_id
+ assert self.browser_session.cdp_session is not None, 'No current target ID'
+ self.browser_session.cdp_session.target_id = target_id
await self._dispatch_focus_changed()
# ONLY dispatch TabCreatedEvent for NEW tabs (not existing tab navigation)
@@ -454,7 +453,7 @@ class NavigationWatchdog(BaseWatchdog):
@property
def current_agent_target(self) -> str | None:
"""Get the current target ID the agent is focused on."""
- return self.browser_session.current_target_id if self.browser_session else None
+ return self.browser_session.cdp_session.target_id if self.browser_session.cdp_session else None
@property
def current_agent_tab_index(self) -> int:
@@ -468,9 +467,9 @@ class NavigationWatchdog(BaseWatchdog):
async def _get_current_tab_index(self) -> int:
"""Get the current tab index from target position."""
- if self.browser_session.current_target_id is None:
+ if self.browser_session.cdp_session is None or self.browser_session.cdp_session.target_id is None:
return 0
- return await self._get_tab_index_for_target(self.browser_session.current_target_id)
+ return await self._get_tab_index_for_target(self.browser_session.cdp_session.target_id)
async def _get_tab_index_for_target(self, target_id: str) -> int:
"""Get tab index for a specific target ID."""
@@ -506,7 +505,7 @@ class NavigationWatchdog(BaseWatchdog):
if targets:
# Set initial focus to first target BEFORE dispatching events
- self.browser_session.current_target_id = targets[0]['targetId']
+ await self.browser_session.attach_cdp_session(targets[0]['targetId'])
# Dispatch TabCreatedEvent for all initial pages so watchdogs can process them
from browser_use.browser.events import TabCreatedEvent
@@ -518,7 +517,7 @@ class NavigationWatchdog(BaseWatchdog):
# Dispatch focus changed event
await self._dispatch_focus_changed()
- target_url = await self._get_target_url(self.browser_session.current_target_id)
+ target_url = self.browser_session.cdp_session.url if self.browser_session.cdp_session else ''
self.logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {target_url}')
async def _update_agent_focus_to_latest_tab(self) -> None:
@@ -526,9 +525,9 @@ class NavigationWatchdog(BaseWatchdog):
targets = await self.browser_session._cdp_get_all_pages()
if targets:
# Focus on the last target (most recently created)
- self.browser_session.current_target_id = targets[-1]['targetId']
+ self.browser_session.cdp_session.target_id = targets[-1]['targetId']
await self._dispatch_focus_changed()
- target_url = await self._get_target_url(self.browser_session.current_target_id)
+ target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)
tab_index = await self._get_current_tab_index()
self.logger.info(f'[NavigationWatchdog] 👀 Agent focus moved to new tab {tab_index}: {target_url}')
@@ -536,9 +535,9 @@ class NavigationWatchdog(BaseWatchdog):
"""Switch agent focus to a specific tab index."""
targets = await self.browser_session._cdp_get_all_pages()
if 0 <= tab_index < len(targets):
- self.browser_session.current_target_id = targets[tab_index]['targetId']
+ self.browser_session.cdp_session.target_id = targets[tab_index]['targetId']
await self._dispatch_focus_changed()
- target_url = await self._get_target_url(self.browser_session.current_target_id)
+ target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)
self.logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {target_url}')
async def _find_new_agent_target(self) -> None:
@@ -548,20 +547,20 @@ class NavigationWatchdog(BaseWatchdog):
# Try to stay at the same index, or go to the previous one
current_index = await self._get_current_tab_index()
new_index = min(current_index, len(targets) - 1)
- self.browser_session.current_target_id = targets[new_index]['targetId']
+ self.browser_session.cdp_session.target_id = targets[new_index]['targetId']
await self._dispatch_focus_changed()
- target_url = await self._get_target_url(self.browser_session.current_target_id)
+ target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)
self.logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {target_url}')
else:
if self.browser_session:
- self.browser_session.current_target_id = None
+ self.browser_session.cdp_session.target_id = None
async def _dispatch_focus_changed(self) -> None:
"""Dispatch event when agent focus changes."""
- if self.browser_session.current_target_id:
+ if self.browser_session.cdp_session.target_id:
try:
# Get URL asynchronously
- target_url = await self._get_target_url(self.browser_session.current_target_id)
+ target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)
tab_index = await self._get_current_tab_index()
self.event_bus.dispatch(
AgentFocusChangedEvent(
@@ -574,28 +573,28 @@ class NavigationWatchdog(BaseWatchdog):
async def get_or_create_target(self) -> str:
"""Get current agent target or create a new one if none exists."""
- if self.browser_session.current_target_id:
+ if self.browser_session.cdp_session.target_id:
# Check if current target URL is still allowed
- target_url = await self._get_target_url(self.browser_session.current_target_id)
+ target_url = await self._get_target_url(self.browser_session.cdp_session.target_id)
if target_url and not self._is_url_allowed(target_url):
self.logger.warning(f'⛔️ Current target URL no longer allowed: {target_url}')
# Close the current target and find/create a new one
try:
- await self.browser_session._cdp_close_page(self.browser_session.current_target_id)
+ await self.browser_session._cdp_close_page(self.browser_session.cdp_session.target_id)
except Exception:
pass
- self.browser_session.current_target_id = None
+ self.browser_session.cdp_session.target_id = None
else:
- return self.browser_session.current_target_id
+ return self.browser_session.cdp_session.target_id
try:
targets = await self.browser_session._cdp_get_all_pages()
for target in targets:
target_url = target.get('url', '')
if self._is_url_allowed(target_url):
- self.browser_session.current_target_id = target['targetId']
+ self.browser_session.cdp_session.target_id = target['targetId']
await self._dispatch_focus_changed()
- return self.browser_session.current_target_id
+ return self.browser_session.cdp_session.target_id
except Exception as e:
self.logger.warning(f'[NavigationWatchdog] Failed to get targets: {e}')
# Don't pass TimeoutError, re-raise other exceptions
@@ -611,8 +610,8 @@ class NavigationWatchdog(BaseWatchdog):
# Try to get the new target
targets = await self.browser_session._cdp_get_all_pages()
if targets:
- self.browser_session.current_target_id = targets[-1]['targetId']
+ self.browser_session.cdp_session.target_id = targets[-1]['targetId']
await self._dispatch_focus_changed()
- return self.browser_session.current_target_id
+ return self.browser_session.cdp_session.target_id
raise ValueError('Failed to create or find an active target')
diff --git a/browser_use/browser/screenshot_watchdog.py b/browser_use/browser/screenshot_watchdog.py
index a1b4714aa..ff5c3795a 100644
--- a/browser_use/browser/screenshot_watchdog.py
+++ b/browser_use/browser/screenshot_watchdog.py
@@ -4,9 +4,7 @@ from typing import TYPE_CHECKING, Any, ClassVar
from bubus import BaseEvent
-from browser_use.browser.events import (
- ScreenshotEvent,
-)
+from browser_use.browser.events import ScreenshotEvent
from browser_use.browser.watchdog_base import BaseWatchdog
if TYPE_CHECKING:
@@ -17,50 +15,40 @@ class ScreenshotWatchdog(BaseWatchdog):
"""Handles screenshot requests using CDP."""
# Events this watchdog listens to
- LISTENS_TO: ClassVar[list[type[BaseEvent[Any]]]] = [
- ScreenshotEvent,
- ]
+ LISTENS_TO: ClassVar[list[type[BaseEvent[Any]]]] = [ScreenshotEvent]
# Events this watchdog emits
EMITS: ClassVar[list[type[BaseEvent[Any]]]] = []
-
async def on_ScreenshotEvent(self, event: ScreenshotEvent) -> dict[str, str | None]:
"""Handle screenshot request using CDP.
-
+
Args:
event: ScreenshotEvent with optional full_page and clip parameters
-
+
Returns:
Dict with 'screenshot' key containing base64-encoded screenshot or None
"""
try:
- # Check if we have a current target
- if not self.browser_session.current_target_id:
- self.logger.warning('[ScreenshotWatchdog] No current target for screenshot')
- return {'screenshot': None}
-
# Get CDP client and session for current target
- client, session_id = await self.browser_session.get_cdp_session(
- self.browser_session.current_target_id
- )
-
+ cdp_session = await self.browser_session.attach_cdp_session()
+
# Prepare screenshot parameters
params = {'format': 'png'}
-
- if event.full_page:
- params['captureBeyondViewport'] = True
-
- if event.clip:
- params['clip'] = event.clip
-
+
+ # if event.full_page:
+ # params['captureBeyondViewport'] = True
+
+ # if event.clip:
+ # params['clip'] = event.clip
+
# Take screenshot using CDP
self.logger.debug(f'[ScreenshotWatchdog] Taking screenshot with params: {params}')
- result = await client.send.Page.captureScreenshot(
- params=params,
- session_id=session_id
+ result = await cdp_session.cdp_client.send.Page.captureScreenshot(
+ # params=params,
+ session_id=cdp_session.session_id
)
-
+
# Return base64-encoded screenshot data
if result and 'data' in result:
self.logger.debug('[ScreenshotWatchdog] Screenshot captured successfully')
@@ -68,11 +56,7 @@ class ScreenshotWatchdog(BaseWatchdog):
else:
self.logger.warning('[ScreenshotWatchdog] Screenshot result missing data')
return {'screenshot': None}
-
+
except Exception as e:
self.logger.error(f'[ScreenshotWatchdog] Screenshot failed: {e}')
return {'screenshot': None}
-
- async def attach_to_target(self, target_id: str) -> None:
- """ScreenshotWatchdog doesn't need to attach to individual targets."""
- pass
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 7175aba01..f4eb13913 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -3,11 +3,12 @@
import asyncio
import logging
from pathlib import Path
-from typing import Any, Self
+from typing import Any, Self, cast
import httpx
from bubus import EventBus
from cdp_use import CDPClient
+from cdp_use.cdp.network import Cookie
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
from uuid_extensions import uuid7str
@@ -45,17 +46,59 @@ def _log_glob_warning(domain: str, glob: str, logger: logging.Logger):
_GLOB_WARNING_SHOWN = True
-class CachedSession:
- """Container for cached CDP session to allow weak references."""
+class CDPSession(BaseModel):
+ """Info about a single CDP session bound to a specific target."""
- def __init__(self, client: Any, session_id: str, target_id: str, frame_id: str | None = None):
- self.client = client
- self.session_id = session_id
- self.target_id = target_id
- self.frame_id = frame_id
+ model_config = ConfigDict(arbitrary_types_allowed=True, revalidate_instances='never')
- def __hash__(self):
- return hash(self.client)
+ cdp_client: CDPClient
+
+ target_id: str
+ session_id: str
+ title: str = 'Unknown title'
+ url: str = 'about:blank'
+
+ @classmethod
+ async def for_target(cls, cdp_client: CDPClient, target_id: str):
+ cdp_session = cls(
+ cdp_client=cdp_client,
+ target_id=target_id,
+ session_id='connecting',
+ )
+ return await cdp_session.attach()
+
+ async def attach(self) -> Self:
+ result = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.target_id, 'flatten': True})
+ self.session_id = result['sessionId']
+
+ # Enable all domains in parallel
+ await asyncio.gather(
+ self.cdp_client.send.Page.enable(session_id=self.session_id),
+ self.cdp_client.send.DOM.enable(session_id=self.session_id),
+ self.cdp_client.send.DOMSnapshot.enable(session_id=self.session_id),
+ self.cdp_client.send.Accessibility.enable(session_id=self.session_id),
+ self.cdp_client.send.Runtime.enable(session_id=self.session_id),
+ self.cdp_client.send.Inspector.enable(session_id=self.session_id),
+ # TEMPORARILY DISABLED: Network.enable causes excessive event logging
+ # self.cdp_client.send.Network.enable(session_id=self.session_id),
+ return_exceptions=True, # Don't fail if some domains aren't available
+ )
+ target_info = await self.get_target_info()
+ self.title = target_info['title']
+ self.url = target_info['url']
+ return self
+
+ async def get_tab_info(self) -> TabInfo:
+ target_info = await self.get_target_info()
+ return TabInfo(
+ page_id=-1, # TODO: get tab order efficiently somehow
+ url=target_info['url'],
+ title=target_info['title'],
+ )
+
+ async def get_target_info(self) -> TargetInfo:
+ result = await self.cdp_client.send.Target.getTargetInfo(params={'targetId': self.target_id})
+ return result['targetInfo']
class BrowserSession(BaseModel):
@@ -80,10 +123,6 @@ class BrowserSession(BaseModel):
cdp_url: str | None = None
is_local: bool = Field(default=True)
- cdp_session_cache_enabled: bool = Field(
- default=True,
- description='Cache CDP sessions based on target_id, set False to create a fresh CDP session for every single CDP call',
- )
browser_profile: BrowserProfile = Field(
default_factory=lambda: DEFAULT_BROWSER_PROFILE,
description='BrowserProfile() options to use for the session, otherwise a default profile will be used',
@@ -93,12 +132,12 @@ class BrowserSession(BaseModel):
event_bus: EventBus = Field(default_factory=EventBus)
# Mutable public state
- current_target_id: str | None = None
+ cdp_session: CDPSession | None = None
# Mutable private state shared between watchdogs
_cdp_client_root: CDPClient | None = PrivateAttr(default=None)
_cached_browser_state_summary: Any = PrivateAttr(default=None)
- _cached_selector_map: dict[int, 'EnhancedDOMTreeNode'] = PrivateAttr(default_factory=dict)
+ _cached_selector_map: dict[int, EnhancedDOMTreeNode] = PrivateAttr(default_factory=dict)
# Watchdogs
_crash_watchdog: Any | None = PrivateAttr(default=None)
@@ -116,7 +155,8 @@ class BrowserSession(BaseModel):
@property
def logger(self) -> Any:
"""Get instance-specific logger with session ID in the name"""
- # if self._logger is None or not self._cdp_client_root: # keep updating the name pre-init because our id and str(self) can change until we are connected
+ # **regenerate it every time** because our id and str(self) can change as browser connection state changes
+ # if self._logger is None or not self._cdp_client_root:
# self._logger = logging.getLogger(f'browser_use.{self}')
return logging.getLogger(f'browser_use.{self}')
@@ -127,9 +167,7 @@ class BrowserSession(BaseModel):
def __str__(self) -> str:
# Note: _original_browser_session tracking moved to Agent class
port_number = (self.cdp_url or 'no-cdp').rsplit(':', 1)[-1].split('/', 1)[0]
- return (
- f'BrowserSession🆂 {self.id[-4:]}:{port_number} #{str(id(self))[-2:]}' # ' 🅟 {str(id(self.current_target_id))[-2:]}'
- )
+ return f'BrowserSession🆂 {self.id[-4:]}:{port_number} #{str(id(self))[-2:]}' # ' 🅟 {str(id(self.cdp_session.target_id))[-2:]}'
async def reset(self) -> None:
"""Clear all cached CDP sessions with proper cleanup."""
@@ -142,7 +180,7 @@ class BrowserSession(BaseModel):
self._cached_browser_state_summary = None
self._cached_selector_map.clear()
- self.current_target_id = None
+ self.cdp_session = None
if self.is_local:
self.cdp_url = None
@@ -156,12 +194,6 @@ class BrowserSession(BaseModel):
self._dom_watchdog = None
self._screenshot_watchdog = None
- @property
- def cdp_client(self) -> CDPClient:
- """Get the cached root CDP client. The client is created and started in self.connect()."""
- assert self._cdp_client_root is not None, 'CDP client not initialized - browser may not be connected yet'
- return self._cdp_client_root
-
def model_post_init(self, __context) -> None:
"""Register event handlers after model initialization."""
# Register BrowserSession's event handlers manually since it's not a BaseWatchdog
@@ -173,7 +205,7 @@ class BrowserSession(BaseModel):
async def start(self) -> None:
"""Start the browser session."""
await self.event_bus.dispatch(BrowserStartEvent())
-
+
async def kill(self) -> None:
"""Kill the browser session."""
await self.event_bus.dispatch(BrowserStopEvent(force=True))
@@ -263,92 +295,53 @@ class BrowserSession(BaseModel):
)
)
- async def get_cdp_session(self, target_id: str | None = None) -> tuple[CDPClient, str]:
- """Get or create a CDP session for a target, using cache when enabled.
-
- Args:
- target_id: The target ID to get a session for
+ @property
+ def cdp_client(self) -> CDPClient:
+ """Get the cached root CDP cdp_session.cdp_client. The client is created and started in self.connect()."""
+ assert self._cdp_client_root is not None, 'CDP client not initialized - browser may not be connected yet'
+ return self._cdp_client_root
- Returns:
- Tuple of (cdp_client, session_id)
- """
+ async def attach_cdp_session(self, target_id: str | None = None) -> CDPSession:
assert self.cdp_url is not None, 'CDP URL not set - browser may not be configured or launched yet'
assert self._cdp_client_root is not None, 'Root CDP client not initialized - browser may not be connected yet'
- assert self.cdp_session_cache_enabled, (
- 'cdp_session_cache_enabled should be always enabled to force us to make sure it works properly'
- )
+ assert self.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'
- if not target_id:
- target_id = self.current_target_id
- if not target_id:
- raise ValueError('No target ID provided and no current target ID set')
+ if self.cdp_session.target_id == target_id:
+ return self.cdp_session
- await self._cdp_client_root.send.Target.setAutoAttach(
- params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}
- )
+ self.cdp_session = await CDPSession.for_target(self._cdp_client_root, target_id or self.cdp_session.target_id)
+ return self.cdp_session
- session = await self._cdp_client_root.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
- await self._cdp_enable_all_domains(self._cdp_client_root, session_id)
- return self._cdp_client_root, session_id
-
- async def _cdp_enable_all_domains(self, client: Any, session_id: str) -> None:
- """Enable all necessary CDP domains for a session."""
- # Enable auto-attach for related targets (iframes, etc)
- await client.send.Target.setAutoAttach(
- params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}, session_id=session_id
- )
+ @property
+ def current_target_id(self) -> str | None:
+ return self.cdp_session.target_id if self.cdp_session else None
- # Enable all commonly used domains in parallel
- await asyncio.gather(
- client.send.Page.enable(session_id=session_id),
- client.send.DOM.enable(session_id=session_id),
- client.send.DOMSnapshot.enable(session_id=session_id),
- client.send.Accessibility.enable(session_id=session_id),
- client.send.Runtime.enable(session_id=session_id),
- client.send.Inspector.enable(session_id=session_id),
- # TEMPORARILY DISABLED: Network.enable causes excessive event logging
- # client.send.Network.enable(session_id=session_id),
- return_exceptions=True, # Don't fail if some domains aren't available
- )
+ @property
+ def current_session_id(self) -> str | None:
+ return self.cdp_session.session_id if self.cdp_session else None
# ========== Helper Methods ==========
async def get_browser_state_summary(
self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = False
- ) -> 'BrowserStateSummary':
- """Get browser state using event system.
-
- This is a compatibility wrapper that dispatches BrowserStateRequestEvent.
-
- Args:
- cache_clickable_elements_hashes: Whether to cache element hashes (for compatibility)
- include_screenshot: Whether to include screenshot in state
-
- Returns:
- BrowserStateSummary from the event handler
- """
-
+ ) -> BrowserStateSummary:
# Dispatch the event and wait for result
- event = self.event_bus.dispatch(
- BrowserStateRequestEvent(
- include_dom=True,
- include_screenshot=include_screenshot,
- cache_clickable_elements_hashes=cache_clickable_elements_hashes,
- )
+ event = cast(
+ BrowserStateRequestEvent,
+ self.event_bus.dispatch(
+ BrowserStateRequestEvent(
+ include_dom=True,
+ include_screenshot=include_screenshot,
+ cache_clickable_elements_hashes=cache_clickable_elements_hashes,
+ )
+ ),
)
# The handler returns the BrowserStateSummary directly
result = await event.event_result(raise_if_none=True, raise_if_any=True)
- assert isinstance(result, BrowserStateSummary)
+ assert result is not None
return result
- async def get_state_summary(self, cache_clickable_elements_hashes: bool = True) -> 'BrowserStateSummary':
- """Alias for get_browser_state_with_recovery for backwards compatibility."""
- return await self.get_browser_state_summary(
- cache_clickable_elements_hashes=cache_clickable_elements_hashes, include_screenshot=False
- )
-
async def attach_all_watchdogs(self) -> None:
"""Initialize and attach all watchdogs with explicit handler registration."""
from browser_use.browser.aboutblank_watchdog import AboutBlankWatchdog
@@ -479,6 +472,9 @@ class BrowserSession(BaseModel):
self._cdp_client_root = CDPClient(self.cdp_url)
assert self._cdp_client_root is not None
await self._cdp_client_root.start()
+ await self._cdp_client_root.send.Target.setAutoAttach(
+ params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}
+ )
self.logger.info('✅ CDP client connected successfully')
# Get browser targets to find available contexts/pages
@@ -504,9 +500,11 @@ class BrowserSession(BaseModel):
target_id = target['targetId']
self.logger.info(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')
try:
- # Use cached session to navigate to about:blank
- client, session_id = await self.get_cdp_session(target_id)
- await client.send.Page.navigate(params={'url': 'about:blank'}, session_id=session_id)
+ # navigate to about:blank
+ cdp_session = await self.attach_cdp_session(target_id)
+ await cdp_session.cdp_client.send.Page.navigate(
+ params={'url': 'about:blank'}, session_id=cdp_session.session_id
+ )
except Exception as e:
self.logger.warning(f'Failed to redirect {target_url} to about:blank: {e}')
@@ -521,12 +519,12 @@ class BrowserSession(BaseModel):
self.logger.info(f'📄 Using existing page with target ID: {target_id}')
# Store the current page target ID
- self.current_target_id = target_id
+ self.cdp_session = await CDPSession.for_target(self._cdp_client_root, target_id)
# Pre-create cached session for the current target (enables all domains)
try:
- await self.get_cdp_session(target_id)
- assert self.cdp_client is not None
+ cdp_session = await self.attach_cdp_session(target_id)
+ assert self.cdp_session.title != 'Unknown title'
except Exception as e:
self.logger.warning(f'Failed to create CDP session: {e}')
raise
@@ -537,26 +535,12 @@ class BrowserSession(BaseModel):
self.logger.error('❌ Browser cannot continue without CDP connection')
# Clean up any partial state
self._cdp_client_root = None
- self.current_target_id = None
+ self.cdp_session = None
# Re-raise as a fatal error
raise RuntimeError(f'Failed to establish CDP connection to browser: {e}') from e
return self
- async def get_target_id_by_tab_index(self, tab_index: int) -> str | None:
- """Get target ID by tab index."""
- target_ids = await self._cdp_get_all_pages()
- if 0 <= tab_index < len(target_ids):
- return target_ids[tab_index]['targetId']
- return None
-
- async def get_tab_index(self, target_id: str) -> int:
- """Get tab index for a target ID."""
- target_ids = await self._cdp_get_all_pages()
- if target_id in target_ids:
- return target_ids.index(target_id)
- return -1
-
async def get_tabs(self) -> list[TabInfo]:
"""Get information about all open tabs using CDP Target.getTargetInfo for speed."""
tabs = []
@@ -619,200 +603,30 @@ class BrowserSession(BaseModel):
return tabs
- # DOM element methods
- # Removed duplicate get_browser_state_with_recovery - using the decorated version below
-
- # ========== CDP Helper Methods ==========
-
- async def cdp_clients_for_target(self, target_id: str) -> list['CDPClient']:
- """Get CDP clients for a target, including main and iframe sessions.
-
- Returns list with root target session first, then iframe sessions.
- """
- if not self._cdp_client_root:
- raise ValueError('CDP client not initialized')
-
- clients = []
-
- # Get cached session for main target
- client, session_id = await self.get_cdp_session(target_id)
-
- # For now, return just the main client with session
- # In future, we'd enumerate iframes and attach to them too
- clients.append(client)
+ # ========== ID Lookup Methods ==========
- return clients
-
- async def cdp_client_for_node(self, node: 'EnhancedDOMTreeNode') -> 'CDPClient':
- """Get CDP client for a specific DOM node based on its frame."""
- if node.frame_id:
- return await self.cdp_client_for_frame(node.frame_id)
- return self.cdp_client
-
- async def frames_by_target(self, target_id: str) -> list[str]:
- """Get all frame IDs for a target."""
- # Get frame tree using helper
- frame_tree = await self._cdp_execute_on_target(target_id, commands=[('Page.getFrameTree', {})])
-
- # Extract frame IDs recursively
- frame_ids = []
-
- def extract_frames(tree_node):
- frame_ids.append(tree_node['frame']['id'])
- for child in tree_node.get('childFrames', []):
- extract_frames(child)
-
- extract_frames(frame_tree['frameTree'])
-
- return frame_ids
-
- async def target_id_by_frame_id(self, frame_id: str) -> str | None:
- """Get target ID for a given frame ID.
-
- Note: This requires iterating through all targets to find the frame.
- """
- targets = await self.cdp_client.send.Target.getTargets()
-
- for target in targets['targetInfos']:
- # Skip invalid targets
- if not self._is_valid_target(
- target, include_http=True, include_about=True, include_pages=True, include_iframes=True, include_workers=False
- ):
- continue
-
- # Check if this target contains the frame
- frames = await self.frames_by_target(target['targetId'])
- if frame_id in frames:
- return target['targetId']
+ async def get_tab_index(self, target_id: str) -> int:
+ """Get tab index for a target ID."""
+ target_ids = await self._cdp_get_all_pages()
+ if target_id in target_ids:
+ return target_ids.index(target_id)
+ return -1
+ async def get_target_id_by_tab_index(self, tab_index: int) -> str | None:
+ """Get target ID by tab index."""
+ target_ids = await self._cdp_get_all_pages()
+ if 0 <= tab_index < len(target_ids):
+ return target_ids[tab_index]['targetId']
return None
- async def get_current_page_cdp_session_id(self) -> str | None:
- """Get the CDP session ID for the current page."""
- if not hasattr(self, 'current_target_id') or not self.current_target_id:
- return None
-
- # Get cached session ID
- client, session_id = await self.get_cdp_session(self.current_target_id)
- return session_id
-
- 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:
- Tuple of (CDPClient, session_id) - uses cached session when available
- """
- # Just use the cached session
- return await self.get_cdp_session(target_id)
-
- 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:
- Tuple of (CDPClient, session_id) for the target containing this frame
-
- Raises:
- ValueError: If frame_id is not found in any target
- """
- # Get all targets using main client
- targets = await self.cdp_client.send.Target.getTargets()
-
- # Search through page targets to find which one contains the frame
- for target in targets['targetInfos']:
- # Skip invalid targets
- if not self._is_valid_target(target):
- continue
-
- if target['type'] != 'page':
- continue
-
- # Use cached session to check frame tree
- client, temp_session_id = await self.get_cdp_session(target['targetId'])
-
- # Get frame tree for this target
- frame_tree = await 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 - return cached session
- return await self.get_cdp_session(target['targetId'])
-
- # Frame not found
- raise ValueError(f'Frame with ID {frame_id} not found in any target')
-
- 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:
- Tuple of (CDPClient, session_id) for 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}')
-
- # Get cached session for the node's target
- client, session_id = await self.get_cdp_session(node.target_id)
-
- # Verify the node exists in this target
- try:
- await client.send.DOM.describeNode(params={'backendNodeId': node.backend_node_id}, session_id=session_id)
- # If we get here without exception, the node exists
- return client, session_id
- except Exception as e:
- raise ValueError(f'Node with backend_node_id {node.backend_node_id} not found in target {node.target_id}: {e}')
-
- async def get_current_target_info(self) -> dict | None:
+ async def get_current_target_info(self) -> TargetInfo | None:
"""Get info about the current active target using CDP."""
- if not self.current_target_id:
+ if not self.cdp_session or not self.cdp_session.target_id:
return None
targets = await self.cdp_client.send.Target.getTargets()
for target in targets.get('targetInfos', []):
- if target.get('targetId') == self.current_target_id:
+ if target.get('targetId') == self.cdp_session.target_id:
# Still return even if it's not a "valid" target since we're looking for a specific ID
return target
return None
@@ -822,40 +636,18 @@ class BrowserSession(BaseModel):
target = await self.get_current_target_info()
if target:
return target.get('url', '')
- return ''
+ return 'about:blank'
async def get_current_page_title(self) -> str:
"""Get the title of the current page using CDP."""
- if not self.current_target_id:
- return ''
-
- try:
- session = await self.cdp_client.send.Target.attachToTarget(
- params={'targetId': self.current_target_id, 'flatten': True}
- )
- session_id = session['sessionId']
- title_result = await self.cdp_client.send.Runtime.evaluate(
- params={'expression': 'document.title'}, session_id=session_id
- )
- title = title_result.get('result', {}).get('value', '')
- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
- return title
- except Exception:
- return ''
+ target_info = await self.get_current_target_info()
+ if target_info:
+ return target_info.get('title', 'Unknown page title')
+ return 'Unknown page title'
# ========== DOM Helper Methods ==========
- def update_cached_selector_map(self, selector_map: dict[int, 'EnhancedDOMTreeNode']) -> None:
- """Update the cached selector map with new DOM state.
-
- This should be called by the DOM watchdog after rebuilding the DOM.
-
- Args:
- selector_map: The new selector map from DOM serialization
- """
- self._cached_selector_map = selector_map
-
- async def get_dom_element_by_index(self, index: int) -> 'EnhancedDOMTreeNode | None':
+ async def get_dom_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:
"""Get DOM element by index.
First checks cached selector map, then falls back to DOM watchdog
@@ -881,8 +673,18 @@ class BrowserSession(BaseModel):
return None
+ def update_cached_selector_map(self, selector_map: dict[int, EnhancedDOMTreeNode]) -> None:
+ """Update the cached selector map with new DOM state.
+
+ This should be called by the DOM watchdog after rebuilding the DOM.
+
+ Args:
+ selector_map: The new selector map from DOM serialization
+ """
+ self._cached_selector_map = selector_map
+
# Alias for backwards compatibility
- async def get_element_by_index(self, index: int) -> 'EnhancedDOMTreeNode | None':
+ async def get_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:
"""Alias for get_dom_element_by_index for backwards compatibility."""
return await self.get_dom_element_by_index(index)
@@ -910,7 +712,7 @@ class BrowserSession(BaseModel):
if self._dom_watchdog:
self._dom_watchdog.clear_cache()
- async def get_selector_map(self) -> dict[int, 'EnhancedDOMTreeNode']:
+ async def get_selector_map(self) -> dict[int, EnhancedDOMTreeNode]:
"""Get the current selector map from cached state or DOM watchdog.
Returns:
@@ -930,11 +732,11 @@ class BrowserSession(BaseModel):
async def remove_highlights(self) -> None:
"""Remove highlights from the page using CDP."""
try:
- if not self.current_target_id:
+ if not self.cdp_session or not self.cdp_session.target_id:
return
# Get cached session
- client, session_id = await self.get_cdp_session(self.current_target_id)
+ cdp_session = await self.attach_cdp_session()
# Remove highlights via JavaScript
script = """
@@ -942,7 +744,7 @@ class BrowserSession(BaseModel):
const highlights = document.querySelectorAll('[data-browser-use-highlight]');
highlights.forEach(el => el.remove());
"""
- await client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)
+ await cdp_session.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=cdp_session.session_id)
except Exception as e:
self.logger.debug(f'Failed to remove highlights: {e}')
@@ -962,35 +764,6 @@ class BrowserSession(BaseModel):
# ========== CDP-based replacements for browser_context operations ==========
- async def _cdp_execute_on_target(
- self, target_id: str, commands: list[tuple[str, dict]] | None = None, callable_fn: Any | None = None
- ) -> Any:
- """Execute CDP commands on a specific target using cached session.
-
- Args:
- target_id: The target ID to execute commands on
- commands: List of (method, params) tuples to execute, e.g. [('Runtime.evaluate', {'expression': '...'})]
- callable_fn: Alternative - async function that receives (cdp_client, session_id) and returns result
-
- Returns:
- Result of the last command or callable_fn return value
- """
- # Get cached session or create new one
- client, session_id = await self.get_cdp_session(target_id)
-
- if callable_fn:
- return await callable_fn(client, session_id)
- elif commands:
- result = None
- for method, params in commands:
- domain, command = method.split('.')
- domain_obj = getattr(client.send, domain)
- cmd_func = getattr(domain_obj, command)
- result = await cmd_func(params=params, session_id=session_id) if params else await cmd_func(session_id=session_id)
- return result
- else:
- return session_id
-
async def _cdp_get_all_pages(
self,
include_http: bool = True,
@@ -1030,51 +803,42 @@ class BrowserSession(BaseModel):
"""Close a page/tab using CDP Target.closeTarget."""
await self.cdp_client.send.Target.closeTarget(params={'targetId': target_id})
- async def _cdp_activate_page(self, target_id: str) -> None:
- """Activate/focus a page using CDP Target.activateTarget."""
- await self.cdp_client.send.Target.activateTarget(params={'targetId': target_id})
-
- async def _cdp_get_cookies(self, urls: list[str] | None = None) -> list[dict]:
+ async def _cdp_get_cookies(self) -> list[Cookie]:
"""Get cookies using CDP Network.getCookies."""
- if not self.current_target_id:
- return []
-
- client, session_id = await self.get_cdp_session(self.current_target_id)
- params = {'urls': urls} if urls else {}
- result = await client.send.Network.getCookies(params=params, session_id=session_id)
+ cdp_session = await self.attach_cdp_session()
+ result = await cdp_session.cdp_client.send.Storage.getCookies(session_id=cdp_session.session_id)
return result.get('cookies', [])
- async def _cdp_set_cookies(self, cookies: list[dict]) -> None:
+ async def _cdp_set_cookies(self, cookies: list[Cookie]) -> None:
"""Set cookies using CDP Network.setCookies."""
- if not self.current_target_id or not cookies:
+ if not self.cdp_session or not cookies:
return
- client, session_id = await self.get_cdp_session(self.current_target_id)
- await client.send.Network.setCookies(params={'cookies': cookies}, session_id=session_id)
+ cdp_session = await self.attach_cdp_session()
+ await cdp_session.cdp_client.send.Storage.setCookies(params={'cookies': cookies}, session_id=cdp_session.session_id)
async def _cdp_clear_cookies(self) -> None:
"""Clear all cookies using CDP Network.clearBrowserCookies."""
- if not self.current_target_id:
- return
-
- client, session_id = await self.get_cdp_session(self.current_target_id)
- await client.send.Network.clearBrowserCookies(session_id=session_id)
+ cdp_session = await self.attach_cdp_session()
+ await cdp_session.cdp_client.send.Storage.clearCookies(session_id=cdp_session.session_id)
async def _cdp_set_extra_headers(self, headers: dict[str, str]) -> None:
"""Set extra HTTP headers using CDP Network.setExtraHTTPHeaders."""
- if not self.current_target_id:
+ if not self.cdp_session:
return
- client, session_id = await self.get_cdp_session(self.current_target_id)
- await client.send.Network.setExtraHTTPHeaders(params={'headers': headers}, session_id=session_id)
+ cdp_session = await self.attach_cdp_session()
+ # await cdp_session.cdp_client.send.Network.setExtraHTTPHeaders(params={'headers': headers}, session_id=cdp_session.session_id)
+ raise NotImplementedError('Not implemented yet')
async def _cdp_grant_permissions(self, permissions: list[str], origin: str | None = None) -> None:
"""Grant permissions using CDP Browser.grantPermissions."""
params = {'permissions': permissions}
- if origin:
- params['origin'] = origin
- client, session_id = await self.get_cdp_session()
- await client.send.Browser.grantPermissions(params=params, session_id=session_id)
+ # if origin:
+ # params['origin'] = origin
+ cdp_session = await self.attach_cdp_session()
+ # await cdp_session.cdp_client.send.Browser.grantPermissions(params=params, session_id=cdp_session.session_id)
+ raise NotImplementedError('Not implemented yet')
async def _cdp_set_geolocation(self, latitude: float, longitude: float, accuracy: float = 100) -> None:
"""Set geolocation using CDP Emulation.setGeolocationOverride."""
@@ -1089,15 +853,19 @@ class BrowserSession(BaseModel):
async def _cdp_add_init_script(self, script: str) -> str:
"""Add script to evaluate on new document using CDP Page.addScriptToEvaluateOnNewDocument."""
assert self._cdp_client_root is not None
- client, session_id = await self.get_cdp_session()
+ cdp_session = await self.attach_cdp_session()
- result = await client.send.Page.addScriptToEvaluateOnNewDocument(params={'source': script, 'runImmediately': True})
+ result = await cdp_session.cdp_client.send.Page.addScriptToEvaluateOnNewDocument(
+ params={'source': script, 'runImmediately': True}
+ )
return result['identifier']
async def _cdp_remove_init_script(self, identifier: str) -> None:
"""Remove script added with addScriptToEvaluateOnNewDocument."""
- client, session_id = await self.get_cdp_session(target_id='main')
- await client.send.Page.removeScriptToEvaluateOnNewDocument(params={'identifier': identifier}, session_id=session_id)
+ cdp_session = await self.attach_cdp_session(target_id='main')
+ await cdp_session.cdp_client.send.Page.removeScriptToEvaluateOnNewDocument(
+ params={'identifier': identifier}, session_id=cdp_session.session_id
+ )
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."""
@@ -1120,19 +888,14 @@ class BrowserSession(BaseModel):
async def _cdp_navigate(self, url: str, target_id: str | None = None) -> None:
"""Navigate to URL using CDP Page.navigate."""
# Use provided target_id or fall back to current_target_id
- target_to_use = target_id or self.current_target_id
-
- if not target_to_use:
- # If no target available, get the first page target
- targets = await self._cdp_get_all_pages()
- if targets:
- target_to_use = targets[0]['targetId']
- self.current_target_id = target_to_use
- else:
- raise ValueError('No target available for navigation')
+
+ assert self._cdp_client_root is not None, 'CDP client not initialized - browser may not be connected yet'
+ assert self.cdp_session is not None, 'CDP session not initialized - browser may not be connected yet'
+
+ self.cdp_session = await CDPSession.for_target(self._cdp_client_root, target_id or self.cdp_session.target_id)
# Use helper to navigate on the target
- await self._cdp_execute_on_target(target_to_use, commands=[('Page.enable', {}), ('Page.navigate', {'url': url})])
+ await self.cdp_session.cdp_client.send.Page.navigate(params={'url': url}, session_id=self.cdp_session.session_id)
@staticmethod
def _is_valid_target(
@@ -1215,13 +978,13 @@ class BrowserSession(BaseModel):
target_id = target['targetId']
# Get cached session for this target
- client, session_id = await self.get_cdp_session(target_id)
- target_sessions[target_id] = session_id
+ cdp_session = await self.attach_cdp_session(target_id)
+ target_sessions[target_id] = cdp_session.session_id
try:
# Try to get frame tree (not all target types support this)
try:
- frame_tree_result = await client.send.Page.getFrameTree(session_id=session_id)
+ frame_tree_result = await cdp_session.cdp_client.send.Page.getFrameTree(session_id=cdp_session.session_id)
# Process the frame tree recursively
def process_frame_tree(node, parent_frame_id=None):
@@ -1355,7 +1118,10 @@ class BrowserSession(BaseModel):
return all_frames.get(frame_id)
- async def cdp_client_for_frame(self, frame_id: str) -> Any:
+ async def cdp_client_for_target(self, target_id: str) -> CDPSession:
+ return await self.attach_cdp_session(target_id)
+
+ async def cdp_client_for_frame(self, frame_id: str) -> CDPSession:
"""Get a CDP client attached to the target containing the specified frame.
Builds a unified frame hierarchy from all targets to find the correct target
@@ -1365,7 +1131,7 @@ class BrowserSession(BaseModel):
frame_id: The frame ID to search for
Returns:
- Tuple of (cdp_client, session_id, target_id) for the target containing the frame
+ Tuple of (cdp_cdp_session, target_id) for the target containing the frame
Raises:
ValueError: If the frame is not found in any target
@@ -1384,23 +1150,16 @@ class BrowserSession(BaseModel):
# Use existing session
session_id = target_sessions[target_id]
# Return the client with session attached
- return self.cdp_client, session_id, target_id
+ return await self.attach_cdp_session(target_id)
# Frame not found
raise ValueError(f"Frame with ID '{frame_id}' not found in any target")
- async def cdp_client_for_target(self, target_id: str) -> Any:
- """Get a CDP client attached to a specific target.
-
- This is a simpler helper that just gets a cached session for a target.
-
- Args:
- target_id: The target ID to attach to
-
- Returns:
- Tuple of (cdp_client, session_id) for the target
- """
- return await self.get_cdp_session(target_id)
+ async def cdp_client_for_node(self, node: EnhancedDOMTreeNode) -> CDPSession:
+ """Get CDP client for a specific DOM node based on its frame."""
+ if node.frame_id:
+ return await self.cdp_client_for_frame(node.frame_id)
+ return await self.attach_cdp_session()
# Fix Pydantic circular dependency for all watchdogs
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index a5148ed6d..fc050f61d 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -314,14 +314,14 @@ class Controller(Generic[Context]):
# Run markdownify in a thread pool to avoid blocking the event loop
loop = asyncio.get_event_loop()
- client, session_id = await browser_session.get_cdp_session()
+ cdp_session = await browser_session.attach_cdp_session()
try:
# result = await client.send.DOM.getDocument(params={'pierce': True}, session_id=session_id)
# root_node_id = result['root']['nodeId']
# page_html_result = await client.send.DOM.getOuterHTML(params={'nodeId': 1}, session_id=session_id)
- page_html_result = await client.send.Page.captureSnapshot(
- params={'format': 'mhtml'}, session_id=session_id
+ page_html_result = await cdp_session.cdp_client.send.Page.captureSnapshot(
+ params={'format': 'mhtml'}, session_id=cdp_session.session_id
) # included OOPIF content automatically
except TimeoutError:
raise RuntimeError('Page content extraction timed out after 5 seconds')
@@ -365,12 +365,8 @@ Explain the content of the page and that the requested information is not availa
page_extraction_llm.ainvoke([UserMessage(content=formatted_prompt)]),
timeout=120.0, # 120 second aggressive timeout for LLM call
)
- target_info = await client.send.Target.getTargetInfo(
- session_id=session_id
- ) # TODO: make a helper method on browser_session for this
- url = target_info['targetInfo']['url']
- extracted_content = f'Page Link: {url}\nQuery: {query}\nExtracted Content:\n{response.completion}'
+ extracted_content = f'Page Link: {cdp_session.url}\nQuery: {query}\nExtracted Content:\n{response.completion}'
# if content is small include it to memory
MAX_MEMORY_SIZE = 600
@@ -389,7 +385,7 @@ Explain the content of the page and that the requested information is not availa
else:
break
save_result = await file_system.save_extracted_content(extracted_content)
- memory = f'Extracted content from {url}\n<query>{query}\n</query>\n<extracted_content>\n{display}{len(lines) - display_lines_count} more lines...\n</extracted_content>\n<file_system>{save_result}</file_system>'
+ memory = f'Extracted content from {cdp_session.url}\n<query>{query}\n</query>\n<extracted_content>\n{display}{len(lines) - display_lines_count} more lines...\n</extracted_content>\n<file_system>{save_result}</file_system>'
include_extracted_content_only_once = True
logger.info(f'📄 {memory}')
return ActionResult(
diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.py
index dba7780aa..188777ff7 100644
--- a/browser_use/dom/debug/highlights.py
+++ b/browser_use/dom/debug/highlights.py
@@ -53,7 +53,7 @@ async def remove_highlighting_script(dom_service: DomService) -> None:
"""Remove all browser-use highlighting elements from the page."""
try:
# Get CDP client and session ID
- client, session_id = await dom_service.browser_session.get_cdp_session(target_id=dom_service.browser_session.current_target_id)
+ cdp_session = await dom_service.browser_session.attach_cdp_session()
print('🧹 Removing browser-use highlighting elements')
@@ -68,8 +68,8 @@ async def remove_highlighting_script(dom_service: DomService) -> None:
"""
# Execute the removal script via CDP
- await client.send.Runtime.evaluate(
- params={'expression': script, 'returnByValue': True}, session_id=session_id
+ await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={'expression': script, 'returnByValue': True}, session_id=cdp_session.session_id
)
print('✅ All browser-use highlighting elements removed')
@@ -84,13 +84,10 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
print('⚠️ No interactive elements to highlight')
return
-
-
try:
# Convert DOMSelectorMap to the format expected by the JavaScript
converted_elements = convert_dom_selector_map_to_highlight_format(interactive_elements)
-
print(f'📍 Creating CSP-safe highlighting for {len(converted_elements)} elements')
# Remove any existing highlights first
@@ -363,12 +360,12 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
console.log('✅ Browser-use highlighting complete');
}})();
"""
-
- client, session_id = await dom_service.browser_session.get_cdp_session(target_id=dom_service.browser_session.current_target_id)
+
+ cdp_session = await dom_service.browser_session.attach_cdp_session()
# Inject the enhanced CSP-safe script via CDP
- await client.send.Runtime.evaluate(
- params={'expression': script, 'returnByValue': True}, session_id=session_id
+ await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={'expression': script, 'returnByValue': True}, session_id=cdp_session.session_id
)
print(f'✅ Enhanced CSP-safe highlighting injected for {len(converted_elements)} elements')
diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.py
index 363b9b841..041701d97 100644
--- a/browser_use/dom/playground/extraction.py
+++ b/browser_use/dom/playground/extraction.py
@@ -133,7 +133,7 @@ async def test_focus_vs_all_elements():
print('\nGetting page state...')
start_time = time.time()
- all_elements_state = await browser_session.get_state_summary(True)
+ all_elements_state = await browser_session.get_browser_state_summary(True)
end_time = time.time()
get_state_time = end_time - start_time
print(f'get_state_summary took {get_state_time:.2f} seconds')
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 900c4b009..0abb516f1 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -3,11 +3,9 @@ import logging
import time
from typing import TYPE_CHECKING
-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,
@@ -52,7 +50,7 @@ class DomService:
return self
async def __aexit__(self, exc_type, exc_value, traceback):
- pass # no need to cleanup anything, browser_session auto handles cleaning up session cache
+ pass # no need to cleanup anything, browser_session auto handles cleaning up session cache
async def _get_targets_for_page(self, target_id: str | None = None) -> CurrentPageTargets:
"""Get the target info for a specific page.
@@ -97,7 +95,6 @@ class DomService:
iframe_sessions=iframe_targets,
)
-
def _build_enhanced_ax_node(self, ax_node: AXNode) -> EnhancedAXNode:
properties: list[EnhancedAXProperty] | None = None
if 'properties' in ax_node and ax_node['properties']:
@@ -127,11 +124,11 @@ class DomService:
async def _get_viewport_ratio(self, target_id: str) -> float:
"""Get viewport dimensions, device pixel ratio, and scroll position using CDP."""
- client, session_id = await self.browser_session.get_cdp_session(target_id=target_id)
+ cdp_session = await self.browser_session.attach_cdp_session(target_id=target_id)
try:
# Get the layout metrics which includes the visual viewport
- metrics = await client.send.Page.getLayoutMetrics(session_id=session_id)
+ metrics = await cdp_session.cdp_client.send.Page.getLayoutMetrics(session_id=cdp_session.session_id)
visual_viewport = metrics.get('visualViewport', {})
@@ -227,8 +224,8 @@ class DomService:
async def _get_ax_tree_for_all_frames(self, target_id: str) -> GetFullAXTreeReturns:
"""Recursively collect all frames and merge their accessibility trees into a single array."""
- client, session_id = await self.browser_session.get_cdp_session(target_id=target_id)
- frame_tree = await client.send.Page.getFrameTree(session_id=session_id)
+ cdp_session = await self.browser_session.attach_cdp_session(target_id=target_id)
+ frame_tree = await cdp_session.cdp_client.send.Page.getFrameTree(session_id=cdp_session.session_id)
def collect_all_frame_ids(frame_tree_node) -> list[str]:
"""Recursively collect all frame IDs from the frame tree."""
@@ -246,8 +243,8 @@ class DomService:
# Get accessibility tree for each frame
ax_tree_requests = []
for frame_id in all_frame_ids:
- ax_tree_request = client.send.Accessibility.getFullAXTree(
- params={'frameId': frame_id}, session_id=session_id
+ ax_tree_request = cdp_session.cdp_client.send.Accessibility.getFullAXTree(
+ params={'frameId': frame_id}, session_id=cdp_session.session_id
)
ax_tree_requests.append(ax_tree_request)
@@ -262,16 +259,16 @@ class DomService:
return {'nodes': merged_nodes}
async def _get_all_trees(self, target_id: str) -> TargetAllTrees:
- client, session_id = await self.browser_session.get_cdp_session(target_id=target_id)
+ cdp_session = await self.browser_session.attach_cdp_session(target_id=target_id)
# Wait for the page to be ready first
try:
- ready_state = await client.send.Runtime.evaluate(
- params={'expression': 'document.readyState'}, session_id=session_id
+ ready_state = await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={'expression': 'document.readyState'}, session_id=cdp_session.session_id
)
except Exception as e:
pass # Page might not be ready yet
- snapshot_request = client.send.DOMSnapshot.captureSnapshot(
+ snapshot_request = cdp_session.cdp_client.send.DOMSnapshot.captureSnapshot(
params={
'computedStyles': REQUIRED_COMPUTED_STYLES,
'includePaintOrder': True,
@@ -279,11 +276,11 @@ class DomService:
'includeBlendedBackgroundColors': False,
'includeTextColorOpacities': False,
},
- session_id=session_id,
+ session_id=cdp_session.session_id,
)
- dom_tree_request = client.send.DOM.getDocument(
- params={'depth': -1, 'pierce': True}, session_id=session_id
+ dom_tree_request = cdp_session.cdp_client.send.DOM.getDocument(
+ params={'depth': -1, 'pierce': True}, session_id=cdp_session.session_id
)
ax_tree_request = self._get_ax_tree_for_all_frames(target_id)
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index dd1776364..e96a1ed4b 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -338,19 +338,6 @@ class EnhancedDOMTreeNode:
'children_nodes': [c.__json__() for c in self.children_nodes] if self.children_nodes else [],
}
- async def create_cdp_session(self, browser_session):
- """Create a CDP session for this node's target.
-
- Args:
- browser_session: The BrowserSession to use for creating the CDP client
-
- Returns:
- CDPClient attached to this node's target
-
- Note: Caller is responsible for cleanup using await cdp_client.stop()
- """
- return await browser_session.create_cdp_session_for_node(self)
-
def get_all_children_text(self, max_depth: int = -1) -> str:
text_parts = []
diff --git a/docs/customize/browser-settings.mdx b/docs/customize/browser-settings.mdx
index 84dc7d601..1a6bb7518 100644
--- a/docs/customize/browser-settings.mdx
+++ b/docs/customize/browser-settings.mdx
@@ -79,57 +79,7 @@ browser_profile: BrowserProfile = BrowserProfile()
Optional `BrowserProfile` template containing default config to use for the `BrowserSession`. (see below for more info)
-#### `playwright`
-```python
-playwright: Playwright | None = None
-```
-
-Optional playwright or patchright API client handle to use, the result of `(await async_playwright().start())` or `(await async_patchright().start())`, which spawns a node.js child subprocess that relays commands to the browser over CDP.
-
-See here for [more detailed usage instructions](https://docs.browser-use.com/customize/real-browser#method-b%3A-connect-using-existing-playwright-objects).
-
-#### `browser`
-
-```python
-browser: Browser | None = None
-```
-
-Playwright Browser object to use (optional). See here for [more detailed usage instructions](https://docs.browser-use.com/customize/real-browser#method-b%3A-connect-using-existing-playwright-objects).
-
-#### `browser_context`
-
-```python
-browser_context: BrowserContext | None = None
-```
-
-Playwright BrowserContext object to use (optional). See here for [more detailed usage instructions](https://docs.browser-use.com/customize/real-browser#method-b%3A-connect-using-existing-playwright-objects).
-
-#### `page` *aka* `current_target_id`
-
-<a name="page"></a><a name="agent-current-page"></a>
-
-```python
-page: Page | None = None
-```
-
-Foreground Page that the agent is focused on, can also be passed as `page=...` as a shortcut. See here for [more detailed usage instructions](https://docs.browser-use.com/customize/real-browser#method-b%3A-connect-using-existing-playwright-objects).
-
-#### `page`
-
-```python
-page: Page | None = None
-```
-
-Foreground Page that the human is focused on to start, not necessary to set manually.
-
-#### `initialized`
-
-```python
-initialized: bool = False
-```
-
-Mark BrowserSession as already initialized, skips launch/connection (not recommended)
#### `**kwargs`
diff --git a/tests/ci/test_aria_menu_dropdown.py b/tests/ci/test_aria_menu_dropdown.py
index 3855f5820..c5b3fded6 100644
--- a/tests/ci/test_aria_menu_dropdown.py
+++ b/tests/ci/test_aria_menu_dropdown.py
@@ -163,7 +163,7 @@ class TestARIAMenuDropdown:
await page.wait_for_load_state()
# Initialize the DOM state to populate the selector map
- await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=True)
# Get the selector map
selector_map = await browser_session.get_selector_map()
@@ -228,7 +228,7 @@ class TestARIAMenuDropdown:
await page.wait_for_load_state()
# Initialize the DOM state to populate the selector map
- await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=True)
# Get the selector map
selector_map = await browser_session.get_selector_map()
@@ -291,7 +291,7 @@ class TestARIAMenuDropdown:
await page.wait_for_load_state()
# Initialize the DOM state to populate the selector map
- await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=True)
# Get the selector map
selector_map = await browser_session.get_selector_map()
diff --git a/tests/ci/test_browser_session_file_uploads.py b/tests/ci/test_browser_session_file_uploads.py
index 1befa29e3..1f3194a4d 100644
--- a/tests/ci/test_browser_session_file_uploads.py
+++ b/tests/ci/test_browser_session_file_uploads.py
@@ -104,7 +104,7 @@ class TestBrowserSessionFileUploads:
await page.wait_for_load_state('networkidle')
# Get browser state to populate selector map
- await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)
# Get the selector map after page load
selector_map = await browser_session.get_selector_map()
@@ -209,7 +209,7 @@ class TestBrowserSessionFileUploads:
await page.wait_for_load_state('networkidle')
# Get browser state to populate selector map
- await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)
selector_map = await browser_session.get_selector_map()
@@ -273,7 +273,7 @@ class TestBrowserSessionFileUploads:
await page.wait_for_load_state('networkidle')
# Get browser state to populate selector map
- await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)
selector_map = await browser_session.get_selector_map()
diff --git a/tests/ci/test_browser_session_screenshots.py b/tests/ci/test_browser_session_screenshots.py
index 4e9567424..6c71f68f5 100644
--- a/tests/ci/test_browser_session_screenshots.py
+++ b/tests/ci/test_browser_session_screenshots.py
@@ -91,7 +91,7 @@ class TestHeadlessScreenshots:
await browser_session.navigate(httpserver.url_for('/'))
# Get state summary
- state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ state = await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)
# Verify screenshot is included
assert state.screenshot is not None
@@ -132,7 +132,7 @@ class TestHeadlessScreenshots:
# Browser should auto-create a new page on about:blank with animation
# With AboutBlankWatchdog, about:blank pages now have animated content, so they should have screenshots
- state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ state = await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)
assert state.screenshot is not None, 'Screenshot should not be None for animated about:blank pages'
assert state.url == 'about:blank' or state.url.startswith('chrome://'), f'Expected empty page but got {state.url}'
@@ -140,7 +140,7 @@ class TestHeadlessScreenshots:
await browser_session.navigate(httpserver.url_for('/test'))
# Get state with screenshot
- state = await browser_session.get_state_summary(cache_clickable_elements_hashes=False)
+ state = await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=False)
# Should have a screenshot now
assert state.screenshot is not None, 'Screenshot should not be None for real pages'
assert isinstance(state.screenshot, str)
diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.py
index edc0bb603..39de76265 100644
--- a/tests/ci/test_controller.py
+++ b/tests/ci/test_controller.py
@@ -1195,7 +1195,7 @@ class TestControllerIntegration:
# Test that get_state_summary works
try:
- await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+ await browser_session.get_browser_state_summary(cache_clickable_elements_hashes=True)
assert False, 'Expected throw error when navigating to non-existent page'
except Exception as e:
pass