Skip to content

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

cdp session caching updates

Nick Sweeting3b685e54d8c3
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.py
index 681b31ebe..aeb7beca7 100644
--- a/browser_use/browser/aboutblank_watchdog.py
+++ b/browser_use/browser/aboutblank_watchdog.py
@@ -155,16 +155,13 @@ class AboutBlankWatchdog(BaseWatchdog):
This is used to visually indicate that the browser is setting up or waiting.
"""
try:
- # Attach to target
- session = await self.browser_session.cdp_client.send.Target.attachToTarget(
- params={'targetId': target_id, 'flatten': True}
- )
- session_id = session['sessionId']
+ # Get cached session
+ client, session_id = await self.browser_session.get_cdp_session(target_id)
- # Inject the DVD screensaver script
+ # Inject the DVD screensaver script (from main branch with idempotency added)
script = f"""
(function(browser_session_label) {{
- // Check if animation is already running using window property
+ // Idempotency check
if (window.__dvdAnimationRunning) {{
return; // Already running, don't add another
}}
@@ -175,12 +172,15 @@ class AboutBlankWatchdog(BaseWatchdog):
// Try again after DOM is ready
window.__dvdAnimationRunning = false; // Reset flag to retry
if (document.readyState === 'loading') {{
- document.addEventListener('DOMContentLoaded', function() {{ arguments.callee(browser_session_label); }});
+ document.addEventListener('DOMContentLoaded', () => arguments.callee(browser_session_label));
}}
return;
}}
const animated_title = `Starting agent ${{browser_session_label}}...`;
+ if (document.title === animated_title) {{
+ return; // already run on this tab, dont run again
+ }}
document.title = animated_title;
// Create the main overlay
@@ -191,105 +191,86 @@ class AboutBlankWatchdog(BaseWatchdog):
loadingOverlay.style.left = '0';
loadingOverlay.style.width = '100vw';
loadingOverlay.style.height = '100vh';
- loadingOverlay.style.backgroundColor = '#1e1e1e';
- loadingOverlay.style.backgroundImage = 'radial-gradient(ellipse at top left, #2a2a3e 0%, #1e1e1e 50%, #0f0f0f 100%)';
- loadingOverlay.style.zIndex = '1000000';
- loadingOverlay.style.display = 'flex';
- loadingOverlay.style.justifyContent = 'center';
- loadingOverlay.style.alignItems = 'center';
+ loadingOverlay.style.background = '#000';
+ loadingOverlay.style.zIndex = '99999';
loadingOverlay.style.overflow = 'hidden';
- // Create the loading box (DVD logo)
- const loadingBox = document.createElement('div');
- loadingBox.id = 'dvd-logo';
- loadingBox.style.position = 'absolute';
- loadingBox.style.width = '160px';
- loadingBox.style.height = '80px';
- loadingBox.style.backgroundColor = '#007ACC';
- loadingBox.style.borderRadius = '15px';
- loadingBox.style.display = 'flex';
- loadingBox.style.flexDirection = 'column';
- loadingBox.style.justifyContent = 'center';
- loadingBox.style.alignItems = 'center';
- loadingBox.style.boxShadow = '0 0 30px rgba(0, 122, 204, 0.7), inset 0 0 20px rgba(255, 255, 255, 0.2)';
- loadingBox.style.transition = 'background-color 0.3s ease, box-shadow 0.3s ease';
-
- // Add logo emoji
- const logoEmoji = document.createElement('div');
- logoEmoji.innerHTML = '🅰';
- logoEmoji.style.fontSize = '32px';
- logoEmoji.style.marginBottom = '4px';
- logoEmoji.style.filter = 'drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3))';
- loadingBox.appendChild(logoEmoji);
-
- // Add text
- const loadingText = document.createElement('div');
- loadingText.style.color = 'white';
- loadingText.style.fontSize = '12px';
- loadingText.style.fontFamily = 'Consolas, Monaco, monospace';
- loadingText.style.fontWeight = '600';
- loadingText.style.letterSpacing = '1px';
- loadingText.style.textShadow = '0 1px 3px rgba(0, 0, 0, 0.5)';
- loadingText.innerText = `AGENT ${{browser_session_label}}`;
- loadingBox.appendChild(loadingText);
-
- loadingOverlay.appendChild(loadingBox);
+ // Create the image element
+ const img = document.createElement('img');
+ img.src = 'https://cf.browser-use.com/logo.svg';
+ img.alt = 'Browser-Use';
+ img.style.width = '200px';
+ img.style.height = 'auto';
+ img.style.position = 'absolute';
+ img.style.left = '0px';
+ img.style.top = '0px';
+ img.style.zIndex = '2';
+ img.style.opacity = '0.8';
+
+ loadingOverlay.appendChild(img);
document.body.appendChild(loadingOverlay);
- // DVD screensaver animation variables
- let x = Math.random() * (window.innerWidth - 160);
- let y = Math.random() * (window.innerHeight - 80);
- let xSpeed = (Math.random() > 0.5 ? 1 : -1) * (1 + Math.random() * 0.5);
- let ySpeed = (Math.random() > 0.5 ? 1 : -1) * (1 + Math.random() * 0.5);
- let hue = 0;
-
- // Color palette for the DVD logo
- const colors = [
- '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
- '#D63031', '#74B9FF', '#A29BFE', '#6C5CE7', '#FD79A8',
- '#FDCB6E', '#E17055', '#00B894', '#00CEC9', '#0984E3'
- ];
- let currentColorIndex = 0;
-
- function changeColor() {{
- currentColorIndex = (currentColorIndex + 1) % colors.length;
- const newColor = colors[currentColorIndex];
- loadingBox.style.backgroundColor = newColor;
- loadingBox.style.boxShadow = `0 0 30px ${{newColor}}88, inset 0 0 20px rgba(255, 255, 255, 0.2)`;
- }}
+ // DVD screensaver bounce logic
+ let x = Math.random() * (window.innerWidth - 300);
+ let y = Math.random() * (window.innerHeight - 300);
+ let dx = 1.2 + Math.random() * 0.4; // px per frame
+ let dy = 1.2 + Math.random() * 0.4;
+ // Randomize direction
+ if (Math.random() > 0.5) dx = -dx;
+ if (Math.random() > 0.5) dy = -dy;
function animate() {{
- // Update position
- x += xSpeed * 2;
- y += ySpeed * 2;
-
- // Bounce off walls
- if (x <= 0 || x >= window.innerWidth - 160) {{
- xSpeed = -xSpeed;
- changeColor();
- x = Math.max(0, Math.min(x, window.innerWidth - 160));
+ const imgWidth = img.offsetWidth || 300;
+ const imgHeight = img.offsetHeight || 300;
+ x += dx;
+ y += dy;
+
+ if (x <= 0) {{
+ x = 0;
+ dx = Math.abs(dx);
+ }} else if (x + imgWidth >= window.innerWidth) {{
+ x = window.innerWidth - imgWidth;
+ dx = -Math.abs(dx);
}}
- if (y <= 0 || y >= window.innerHeight - 80) {{
- ySpeed = -ySpeed;
- changeColor();
- y = Math.max(0, Math.min(y, window.innerHeight - 80));
+ if (y <= 0) {{
+ y = 0;
+ dy = Math.abs(dy);
+ }} else if (y + imgHeight >= window.innerHeight) {{
+ y = window.innerHeight - imgHeight;
+ dy = -Math.abs(dy);
}}
- // Apply position
- loadingBox.style.left = x + 'px';
- loadingBox.style.top = y + 'px';
+ img.style.left = `${{x}}px`;
+ img.style.top = `${{y}}px`;
requestAnimationFrame(animate);
}}
-
animate();
+
+ // Responsive: update bounds on resize
+ window.addEventListener('resize', () => {{
+ x = Math.min(x, window.innerWidth - img.offsetWidth);
+ y = Math.min(y, window.innerHeight - img.offsetHeight);
+ }});
+
+ // Add a little CSS for smoothness
+ const style = document.createElement('style');
+ style.textContent = `
+ #pretty-loading-animation {{
+ /*backdrop-filter: blur(2px) brightness(0.9);*/
+ }}
+ #pretty-loading-animation img {{
+ user-select: none;
+ pointer-events: none;
+ }}
+ `;
+ document.head.appendChild(style);
}})('{browser_session_label}');
"""
- await self.browser_session.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)
+ await client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)
- # Detach from target
- await self.browser_session.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+ # No need to detach - session is cached
# Dispatch event
tab_index = await self.browser_session.get_tab_index(target_id)
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index dfdf173f1..88b096624 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -51,9 +51,9 @@ class CrashWatchdog(BaseWatchdog):
# Private state
_active_requests: dict[str, NetworkRequestTracker] = PrivateAttr(default_factory=dict)
_monitoring_task: asyncio.Task | None = PrivateAttr(default=None)
- _cdp_sessions: dict[str, str] = PrivateAttr(default_factory=dict) # target_id -> session_id
_last_responsive_checks: dict[str, float] = PrivateAttr(default_factory=dict) # target_url -> timestamp
_cdp_event_tasks: set[asyncio.Task] = PrivateAttr(default_factory=set) # Track CDP event handler tasks
+ _sessions_with_listeners: set[str] = PrivateAttr(default_factory=set) # Track sessions that already have event listeners
async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:
"""Start monitoring when browser is connected."""
@@ -70,15 +70,13 @@ class CrashWatchdog(BaseWatchdog):
async def attach_to_target(self, target_id: str) -> None:
"""Set up crash monitoring for a specific target using CDP."""
try:
- cdp_client = self.browser_session.cdp_client
-
- # Attach to target and enable domains
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
- self._cdp_sessions[target_id] = session_id
-
- # Enable network domain for request tracking
- await cdp_client.send.Network.enable(session_id=session_id)
+ # Get cached session (domains already enabled by get_cdp_session)
+ cdp_client, session_id = await self.browser_session.get_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}')
+ return
# Set up network event handlers
def on_request_will_be_sent(event):
@@ -98,15 +96,13 @@ class CrashWatchdog(BaseWatchdog):
self._on_request_finished_cdp(event)
# Register event handlers
- cdp_client.on('Network.requestWillBeSent', on_request_will_be_sent, session_id=session_id)
- cdp_client.on('Network.responseReceived', on_response_received, session_id=session_id)
- cdp_client.on('Network.loadingFailed', on_loading_failed, session_id=session_id)
- cdp_client.on('Network.loadingFinished', on_loading_finished, session_id=session_id)
+ # TEMPORARILY DISABLED: Network events causing too much logging
+ # cdp_client.on('Network.requestWillBeSent', on_request_will_be_sent, session_id=session_id)
+ # cdp_client.on('Network.responseReceived', on_response_received, session_id=session_id)
+ # cdp_client.on('Network.loadingFailed', on_loading_failed, session_id=session_id)
+ # cdp_client.on('Network.loadingFinished', on_loading_finished, session_id=session_id)
- # Enable Inspector domain for crash detection
- await cdp_client.send.Inspector.enable(session_id=session_id)
-
- # Set up crash handler
+ # Set up crash handler (Inspector domain already enabled by get_cdp_session)
def on_target_crashed(event):
# Create and track the task
task = asyncio.create_task(self._on_target_crash_cdp(target_id))
@@ -115,6 +111,9 @@ class CrashWatchdog(BaseWatchdog):
task.add_done_callback(lambda t: self._cdp_event_tasks.discard(t))
cdp_client.on('Inspector.targetCrashed', on_target_crashed, session_id=session_id)
+
+ # Track that we've added listeners to this session
+ self._sessions_with_listeners.add(session_id)
# Get target info for logging
targets = await cdp_client.send.Target.getTargets()
@@ -250,18 +249,9 @@ class CrashWatchdog(BaseWatchdog):
await asyncio.gather(*self._cdp_event_tasks, return_exceptions=True)
self._cdp_event_tasks.clear()
- # Clean up CDP sessions
- if self._cdp_sessions:
- cdp_client = self.browser_session.cdp_client
- for target_id, session_id in self._cdp_sessions.items():
- try:
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
- except Exception:
- pass
- self._cdp_sessions.clear()
-
- # Clear tracking
+ # Clear tracking (CDP sessions are cached and managed by BrowserSession)
self._active_requests.clear()
+ self._sessions_with_listeners.clear()
async def _monitoring_loop(self) -> None:
"""Main monitoring loop."""
@@ -324,13 +314,32 @@ class CrashWatchdog(BaseWatchdog):
cdp_client = self.browser_session.cdp_client
# Try a simple CDP command to check connection
await asyncio.wait_for(cdp_client.send.Target.getTargets(), timeout=2.0)
- except (TimeoutError, Exception) as e:
+ except (asyncio.TimeoutError, Exception) as e:
self.logger.error(f'[CrashWatchdog] Browser connection check failed: {e}')
self.event_bus.dispatch(
BrowserErrorEvent(error_type='BrowserDisconnected', message='Browser disconnected unexpectedly', details={})
)
# Exit the monitoring loop
raise asyncio.CancelledError('Browser disconnected')
+
+ # Check all cached CDP sessions for health
+ if hasattr(self.browser_session, '_cdp_session_cache'):
+ dead_sessions = []
+ for target_id, cached_value in list(self.browser_session._cdp_session_cache.items()):
+ try:
+ client, session_id = cached_value
+ # 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
+ )
+ except:
+ dead_sessions.append(target_id)
+ self.logger.warning(f'[CrashWatchdog] Dead session detected for target {target_id}')
+
+ # Clean up dead sessions
+ for target_id in dead_sessions:
+ await self.browser_session.release_cdp_session(target_id)
# Check browser process if we have PID
if proc := self.browser_session._local_browser_watchdog._subprocess:
@@ -405,16 +414,9 @@ class CrashWatchdog(BaseWatchdog):
async def _is_target_responsive(self, target_id: str, timeout: float = 5.0) -> bool:
"""Check if a target is responsive by trying to evaluate simple JavaScript."""
eval_task = None
- session_id = None
try:
- cdp_client = self.browser_session.cdp_client
-
- # Attach to target if not already attached
- if target_id not in self._cdp_sessions:
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
- else:
- session_id = self._cdp_sessions[target_id]
+ # Get cached session
+ cdp_client, session_id = await self.browser_session.get_cdp_session(target_id)
# Try to evaluate simple JavaScript
eval_task = asyncio.create_task(cdp_client.send.Runtime.evaluate(params={'expression': '1'}, session_id=session_id))
@@ -442,12 +444,7 @@ class CrashWatchdog(BaseWatchdog):
except (asyncio.CancelledError, Exception):
pass
- # Detach if we attached just for this check
- if session_id and target_id not in self._cdp_sessions:
- try:
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
- except Exception:
- pass
+ # No need to detach - sessions are cached and managed by BrowserSession
@staticmethod
def _is_new_tab_page(url: str) -> bool:
@@ -484,14 +481,10 @@ class CrashWatchdog(BaseWatchdog):
self.logger.warning(f'[CrashWatchdog] Triggering target crash for testing on: {target_url}')
- # Attach to target
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
+ # Get cached session
+ cdp_client, session_id = await self.browser_session.get_cdp_session(target_id)
# Crash the target
await cdp_client.send.Page.crash(session_id=session_id)
-
- # Detach
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
except Exception as e:
self.logger.error(f'[CrashWatchdog] Failed to trigger target crash: {e}')
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.py
index cb3d45d7e..dc0fb5c1b 100644
--- a/browser_use/browser/default_action_watchdog.py
+++ b/browser_use/browser/default_action_watchdog.py
@@ -494,16 +494,10 @@ class DefaultActionWatchdog(BaseWatchdog):
# 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', '')):
- # Attach to this target
+ # Get cached session for this target
target_id = target['targetId']
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
-
- # Enable required domains on this session
- await cdp_client.send.DOM.enable(session_id=session_id)
- await cdp_client.send.Runtime.enable(session_id=session_id)
- # Note: Input domain doesn't have an enable method
-
+ client, session_id = await self.browser_session.get_cdp_session(target_id)
+ # Domains are already enabled by get_cdp_session
return session_id
# If frame not found in targets, use main target session
diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.py
index b3373c786..70784839e 100644
--- a/browser_use/browser/dom_watchdog.py
+++ b/browser_use/browser/dom_watchdog.py
@@ -139,9 +139,15 @@ class DOMWatchdog(BaseWatchdog):
if event.include_screenshot:
try:
screenshot_event = self.event_bus.dispatch(ScreenshotEvent(full_page=False))
- screenshot_result = await screenshot_event.event_result()
+ # Add timeout to prevent hanging if no handler exists
+ screenshot_result = await asyncio.wait_for(
+ screenshot_event.event_result(),
+ timeout=2.0
+ )
if screenshot_result:
screenshot_b64 = screenshot_result.get('screenshot')
+ except asyncio.TimeoutError:
+ self.logger.warning('Screenshot timed out after 2 seconds - no handler registered?')
except Exception as e:
self.logger.warning(f'Screenshot failed: {e}')
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 93b6f77df..1e8b19af2 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -43,7 +43,7 @@ class DownloadsWatchdog(BaseWatchdog):
]
# Private state
- _targets_with_listeners: set[str] = PrivateAttr(default_factory=set) # Track targets that already have download listeners
+ _sessions_with_listeners: set[str] = PrivateAttr(default_factory=set) # Track sessions that already have download listeners
_active_downloads: dict[str, Any] = PrivateAttr(default_factory=dict)
_pdf_viewer_cache: dict[str, bool] = PrivateAttr(default_factory=dict) # Cache PDF viewer status by target URL
_download_cdp_session_setup: bool = PrivateAttr(default=False) # Track if CDP session is set up
@@ -88,17 +88,12 @@ class DownloadsWatchdog(BaseWatchdog):
self._cdp_event_tasks.clear()
# Clean up CDP session
- if self._download_cdp_session:
- try:
- cdp_client = self.browser_session.cdp_client
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': self._download_cdp_session})
- except Exception:
- pass
- self._download_cdp_session = None
- self._download_cdp_session_setup = False
+ # CDP sessions are now cached and managed by BrowserSession
+ self._download_cdp_session = None
+ self._download_cdp_session_setup = False
# Clear other state
- self._targets_with_listeners.clear()
+ self._sessions_with_listeners.clear()
self._active_downloads.clear()
self._pdf_viewer_cache.clear()
@@ -129,10 +124,12 @@ class DownloadsWatchdog(BaseWatchdog):
# logger.info(f'[DownloadsWatchdog] No downloads path configured, skipping target: {target_id}')
return # No downloads path configured
- # Check if we already have a download listener on this target
+ # Check if we already have a download listener on this session
# to prevent duplicate listeners from being added
- if target_id in self._targets_with_listeners:
- self.logger.debug(f'[DownloadsWatchdog] Download listener already exists for target: {target_id}')
+ # 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')
return
# logger.debug(f'[DownloadsWatchdog] Setting up CDP download listener for target: {target_id}')
@@ -177,8 +174,7 @@ class DownloadsWatchdog(BaseWatchdog):
self._download_cdp_session_setup = True
self.logger.debug('[DownloadsWatchdog] Set up CDP download listeners')
- # Track that we've added a listener to prevent duplicates
- self._targets_with_listeners.add(target_id)
+ # No need to track individual targets since download listener is browser-level
# logger.debug(f'[DownloadsWatchdog] Successfully set up CDP download listener for target: {target_id}')
except Exception as e:
@@ -458,9 +454,8 @@ class DownloadsWatchdog(BaseWatchdog):
return self._pdf_viewer_cache[page_url]
try:
- # Attach to target for evaluation
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
+ # Get cached session
+ cdp_client, session_id = await self.browser_session.get_cdp_session(target_id)
# Add timeout to prevent hanging on unresponsive pages
import asyncio
@@ -528,9 +523,7 @@ class DownloadsWatchdog(BaseWatchdog):
timeout=5.0, # 5 second timeout to prevent hanging
)
- # Detach from target
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
-
+ # No need to detach - session is cached
is_pdf_viewer = result.get('result', {}).get('value', {})
if is_pdf_viewer.get('isPdf', False):
@@ -563,10 +556,8 @@ class DownloadsWatchdog(BaseWatchdog):
return None
try:
- # Get CDP client and attach to target
- cdp_client = self.browser_session.cdp_client
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
+ # Get cached session
+ cdp_client, session_id = await self.browser_session.get_cdp_session(target_id)
# Try to get the PDF URL with timeout
import asyncio
@@ -697,22 +688,14 @@ class DownloadsWatchdog(BaseWatchdog):
)
)
- # Detach from target before returning
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+ # No need to detach - session is cached
return download_path
else:
self.logger.warning(f'[DownloadsWatchdog] No data received when downloading PDF from {pdf_url}')
- # Detach from target
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
return None
except Exception as e:
self.logger.warning(f'[DownloadsWatchdog] Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')
- # Try to detach from target if possible
- try:
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
- except:
- pass
return None
except TimeoutError:
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index bcfb4e27e..66ad3d9f5 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -324,6 +324,9 @@ class AboutBlankDVDScreensaverShownEvent(BaseEvent):
error: str | None = None
+# Note: Model rebuilding for forward references is handled at the end of the module import chain
+# The events with 'EnhancedDOMTreeNode' forward references will be rebuilt after all imports are complete
+
# check that event names are valid and non-overlapping (naiively n^2 so it's pretty slow but ok for now, optimize when >20 events)
event_names = {
name
diff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.py
index 037a43587..2f4034f85 100644
--- a/browser_use/browser/local_browser_watchdog.py
+++ b/browser_use/browser/local_browser_watchdog.py
@@ -8,7 +8,6 @@ from typing import TYPE_CHECKING, Any, ClassVar
import psutil
from bubus import BaseEvent
-from playwright.async_api import async_playwright
from pydantic import PrivateAttr
from browser_use.browser.events import (
@@ -120,18 +119,9 @@ class LocalBrowserWatchdog(BaseWatchdog):
self.logger.debug(f'[LocalBrowserWatchdog] Using custom executable: {browser_path}')
else:
self.logger.debug('[LocalBrowserWatchdog] Getting browser path from playwright...')
- # Use async playwright properly with timeout
- playwright = await asyncio.wait_for(
- async_playwright().start(),
- timeout=5.0, # 5 second timeout
- )
- try:
- browser_path = playwright.chromium.executable_path
- self.logger.debug(f'[LocalBrowserWatchdog] Got browser path: {browser_path}')
- finally:
- # Always stop playwright after getting the path
- await playwright.stop()
- self.logger.debug('[LocalBrowserWatchdog] Playwright stopped')
+ # Get browser path from playwright in a subprocess to avoid thread issues
+ browser_path = await self._get_browser_path_via_subprocess()
+ self.logger.debug(f'[LocalBrowserWatchdog] Got browser path: {browser_path}')
# Launch browser subprocess directly
self.logger.debug(f'[LocalBrowserWatchdog] Launching browser subprocess with {len(launch_args)} args...')
@@ -197,6 +187,62 @@ class LocalBrowserWatchdog(BaseWatchdog):
profile.user_data_dir = self._original_user_data_dir
raise RuntimeError(f'Failed to launch browser after {max_retries} attempts')
+ @staticmethod
+ async def _get_browser_path_via_subprocess() -> str:
+ """Get browser executable path from playwright in a subprocess to avoid thread issues."""
+ import sys
+ import json
+
+ # Python code to run in subprocess
+ get_path_code = """
+import asyncio
+import json
+import sys
+
+async def get_path():
+ from playwright.async_api import async_playwright
+ playwright = await async_playwright().start()
+ try:
+ path = playwright.chromium.executable_path
+ print(json.dumps({"path": path}))
+ finally:
+ await playwright.stop()
+
+asyncio.run(get_path())
+"""
+
+ # Run in subprocess with timeout
+ process = await asyncio.create_subprocess_exec(
+ sys.executable, '-c', get_path_code,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+
+ try:
+ # Wait for result with timeout
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=10.0)
+
+ # Parse the result
+ if stdout:
+ result = json.loads(stdout.decode())
+ return result['path']
+ else:
+ # Fallback to default location if subprocess fails
+ error_msg = stderr.decode() if stderr else "Unknown error"
+ raise RuntimeError(f"Failed to get browser path from playwright: {error_msg}")
+
+ except asyncio.TimeoutError:
+ # Kill the subprocess if it times out
+ process.kill()
+ await process.wait()
+ raise RuntimeError("Timeout getting browser path from playwright")
+ except Exception as e:
+ # Make sure subprocess is terminated
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+ raise RuntimeError(f"Error getting browser path: {e}")
+
@staticmethod
def _find_free_port() -> int:
"""Find a free port for the debugging interface."""
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index cec5f4bf8..e00fdfac7 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -2,6 +2,7 @@
import asyncio
import logging
+import weakref
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -37,6 +38,18 @@ if TYPE_CHECKING:
from browser_use.dom.views import EnhancedDOMTreeNode
+
+class CachedSession:
+ """Container for cached CDP session to allow weak references."""
+ 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
+
+ def __hash__(self):
+ return hash(self.client)
+
_GLOB_WARNING_SHOWN = False # used inside _is_url_allowed to avoid spamming the logs with the same warning multiple times
MAX_SCREENSHOT_HEIGHT = 2000
@@ -107,6 +120,7 @@ class BrowserSession(BaseModel):
_local_browser_watchdog: Any = PrivateAttr(default=None)
_default_action_watchdog: Any = PrivateAttr(default=None)
_dom_watchdog: Any = PrivateAttr(default=None)
+ _screenshot_watchdog: Any = PrivateAttr(default=None)
# Navigation tracking now handled by watchdogs
@@ -118,6 +132,13 @@ class BrowserSession(BaseModel):
# CDP client
_cdp_client: 'CDPClient | None' = PrivateAttr(default=None)
"""Cached CDP client instance"""
+
+ # CDP session cache
+ _cdp_session_cache: weakref.WeakValueDictionary = PrivateAttr(default_factory=weakref.WeakValueDictionary)
+ """Cache of CDP sessions by target_id -> (client, session_id) tuple"""
+
+ _cdp_cache_enabled: bool = PrivateAttr(default=True)
+ """Flag to enable/disable CDP session caching"""
_logger: Any = PrivateAttr(default=None)
@@ -146,6 +167,95 @@ class BrowserSession(BaseModel):
raise RuntimeError('CDP client not initialized - browser may not be connected yet')
return self._cdp_client
+ async def get_cdp_session(self, target_id: str) -> tuple[Any, 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
+
+ Returns:
+ Tuple of (cdp_client, session_id)
+ """
+ # If caching is disabled, always create a new session
+ if not self._cdp_cache_enabled:
+ client = self.cdp_client
+ session = await client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
+ session_id = session['sessionId']
+ await self._enable_all_domains(client, session_id)
+ return client, session_id
+
+ # Check cache first
+ cached = self._cdp_session_cache.get(target_id)
+ if cached:
+ try:
+ # Quick ping to verify it's still alive (0.1s timeout)
+ await asyncio.wait_for(
+ cached.client.send.Runtime.evaluate(params={'expression': '1'}, session_id=cached.session_id),
+ timeout=0.1
+ )
+ return cached.client, cached.session_id
+ except:
+ # Dead session, remove from cache
+ self._cdp_session_cache.pop(target_id, None)
+
+ # Create new session
+ client = self.cdp_client
+ session = await client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
+ session_id = session['sessionId']
+
+ # Enable all necessary domains at creation time
+ await self._enable_all_domains(client, session_id)
+
+ # Cache it using CachedSession (which supports weak references)
+ cache_value = CachedSession(client, session_id, target_id)
+ self._cdp_session_cache[target_id] = cache_value
+
+ return client, session_id
+
+ async def _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
+ )
+
+ # Enable all commonly used domains in parallel
+ await asyncio.gather(
+ client.send.Page.enable(session_id=session_id),
+ # TEMPORARILY DISABLED: Network.enable causes excessive event logging
+ # client.send.Network.enable(session_id=session_id),
+ client.send.Runtime.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.Inspector.enable(session_id=session_id),
+ return_exceptions=True # Don't fail if some domains aren't available
+ )
+
+ async def release_cdp_session(self, target_id: str) -> None:
+ """Explicitly release a CDP session (detach and remove from cache).
+
+ Args:
+ target_id: The target ID to release the session for
+ """
+ # If caching is disabled, nothing to release from cache
+ if not self._cdp_cache_enabled:
+ return
+
+ cached = self._cdp_session_cache.pop(target_id, None)
+ if cached:
+ try:
+ client, session_id = cached
+ await client.send.Target.detachFromTarget(params={'sessionId': session_id})
+ except:
+ pass # Session might already be dead
+
+ async def clear_cdp_cache(self) -> None:
+ """Clear all cached CDP sessions with proper cleanup."""
+ for target_id in list(self._cdp_session_cache.keys()):
+ await self.release_cdp_session(target_id)
+
def __repr__(self) -> str:
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:]} (cdp_url={self.cdp_url}, profile={self.browser_profile})'
@@ -214,12 +324,8 @@ class BrowserSession(BaseModel):
self.event_bus.dispatch(BrowserStoppedEvent(reason='Kept alive due to keep_alive=True'))
return
- # TODO: We may want to gracefully tell the browser to shut down via CDP here
- # so it can properly save traces, recordings, user_data_dir changes, etc.
- # For example:
- # - Browser.close() to trigger graceful browser shutdown
- # - Target.closeTarget() for each page
- # - Give browser time to flush data before process kill
+ # Clear CDP session cache before stopping
+ await self.clear_cdp_cache()
# Reset state
if self.is_local:
@@ -285,6 +391,7 @@ class BrowserSession(BaseModel):
from browser_use.browser.downloads_watchdog import DownloadsWatchdog
from browser_use.browser.local_browser_watchdog import LocalBrowserWatchdog
from browser_use.browser.navigation_watchdog import NavigationWatchdog
+ from browser_use.browser.screenshot_watchdog import ScreenshotWatchdog
from browser_use.browser.storage_state_watchdog import StorageStateWatchdog
watchdog_configs = [
@@ -296,6 +403,7 @@ class BrowserSession(BaseModel):
('_aboutblank_watchdog', AboutBlankWatchdog),
('_default_action_watchdog', DefaultActionWatchdog),
('_dom_watchdog', DOMWatchdog),
+ ('_screenshot_watchdog', ScreenshotWatchdog),
]
for attr_name, watchdog_class in watchdog_configs:
@@ -370,13 +478,9 @@ class BrowserSession(BaseModel):
target_id = target['targetId']
self.logger.info(f'🔄 Redirecting {target_url} to about:blank for target {target_id}')
try:
- # Attach to target and navigate to about:blank
- session = await self._cdp_client.send.Target.attachToTarget(
- params={'targetId': target_id, 'flatten': True}
- )
- session_id = session['sessionId']
- await self._cdp_client.send.Page.navigate(params={'url': 'about:blank'}, session_id=session_id)
- await self._cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+ # 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)
except Exception as e:
self.logger.warning(f'Failed to redirect {target_url} to about:blank: {e}')
@@ -393,17 +497,12 @@ class BrowserSession(BaseModel):
# Store the current page target ID
self.current_target_id = target_id
- # Enable Network domain on the target session for cookie access
+ # Pre-create cached session for the current target (enables all domains)
try:
- # Attach to the target to enable Network domain
- session = await self._cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
- await self._cdp_client.send.Network.enable(session_id=session_id)
- self.logger.info(f'🌐 Network domain enabled for cookie access on target {target_id[:8]}...')
- # Detach from target after enabling
- await self._cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+ await self.get_cdp_session(target_id)
+ self.logger.info(f'🌐 CDP session cached and domains enabled for target {target_id[:8]}...')
except Exception as e:
- self.logger.warning(f'Failed to enable Network domain: {e}')
+ self.logger.warning(f'Failed to create CDP session: {e}')
except Exception as e:
# Fatal error - browser is not usable without CDP connection
@@ -494,7 +593,7 @@ class BrowserSession(BaseModel):
return -1
async def get_tabs_info(self) -> list[TabInfo]:
- """Get information about all open tabs using CDP for reliability."""
+ """Get information about all open tabs using CDP Target.getTargetInfo for speed."""
tabs = []
# Get all page targets using CDP
@@ -503,40 +602,43 @@ class BrowserSession(BaseModel):
for i, page_target in enumerate(pages):
target_id = page_target['targetId']
url = page_target['url']
-
- # Skip JS execution for chrome:// pages and new tab pages
- if is_new_tab_page(url) or url.startswith('chrome://'):
- # Use URL as title for chrome pages, or mark new tabs as unusable
+
+ # Try to get the title directly from Target.getTargetInfo - much faster!
+ # The initial getTargets() doesn't include title, but getTargetInfo does
+ try:
+ target_info = await self.cdp_client.send.Target.getTargetInfo(params={'targetId': target_id})
+ # The title is directly available in targetInfo
+ title = target_info.get('targetInfo', {}).get('title', '')
+
+ # Skip JS execution for chrome:// pages and new tab pages
+ if is_new_tab_page(url) or url.startswith('chrome://'):
+ # Use URL as title for chrome pages, or mark new tabs as unusable
+ if is_new_tab_page(url):
+ title = 'ignore this tab and do not use it'
+ elif not title:
+ # For chrome:// pages without a title, use the URL itself
+ title = url
+
+ # Special handling for PDF pages without titles
+ if (not title or title == '') and (url.endswith('.pdf') or 'pdf' in url):
+ # PDF pages might not have a title, use URL filename
+ try:
+ from urllib.parse import urlparse
+ filename = urlparse(url).path.split('/')[-1]
+ if filename:
+ title = filename
+ except Exception:
+ pass
+
+ except Exception as e:
+ # Fallback to basic title handling
+ self.logger.debug(f'⚠️ Failed to get target info for tab #{i}: {_log_pretty_url(url)} - {type(e).__name__}')
+
if is_new_tab_page(url):
title = 'ignore this tab and do not use it'
- else:
- # For chrome:// pages, use the URL itself as the title
+ elif url.startswith('chrome://'):
title = url
- else:
- # Normal pages - try to get title with CDP for reliability
- try:
- # Use helper to get document title with very short timeout
- title_result = await asyncio.wait_for(
- self._cdp_execute_on_target(target_id, commands=[('Runtime.evaluate', {'expression': 'document.title'})]),
- timeout=0.2, # Very short timeout to prevent hanging
- )
- title = title_result.get('result', {}).get('value', '') if title_result else ''
-
- # Special handling for PDF pages
- if (not title or title == '') and (url.endswith('.pdf') or 'pdf' in url):
- # PDF pages might not have a title, use URL filename
- try:
- from urllib.parse import urlparse
-
- filename = urlparse(url).path.split('/')[-1]
- if filename:
- title = filename
- except Exception:
- pass
-
- except Exception as e:
- # Page might be crashed or unresponsive - just use empty title
- self.logger.debug(f'⚠️ Failed to get tab title for tab #{i}: {_log_pretty_url(url)} - {type(e).__name__}')
+ else:
title = ''
tab_info = TabInfo(
@@ -814,13 +916,12 @@ class BrowserSession(BaseModel):
clients = []
- # Attach to main target
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
-
+ # 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(self.cdp_client) # Root client with session attached
+ clients.append(client)
return clients
@@ -873,9 +974,9 @@ class BrowserSession(BaseModel):
if not hasattr(self, 'current_target_id') or not self.current_target_id:
return None
- # Attach to the current target and get session ID
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})
- return session['sessionId']
+ # 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."""
@@ -908,39 +1009,10 @@ class BrowserSession(BaseModel):
target_id: The target ID to attach to
Returns:
- CDPClient with session attached to target - caller is responsible for cleanup
-
- Note: The returned CDPClient should be stopped when done using:
- await cdp_client.stop()
+ Tuple of (CDPClient, session_id) - uses cached session when available
"""
- cdp_client = await self._create_fresh_cdp_client()
-
- try:
- # Attach to the target
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
-
- # Store the session_id on the client for convenience
- cdp_client.target_session_id = session_id
-
- # Enable necessary domains
- await cdp_client.send.Target.setAutoAttach(
- params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}, session_id=session_id
- )
-
- await asyncio.gather(
- cdp_client.send.DOM.enable(session_id=session_id),
- cdp_client.send.Accessibility.enable(session_id=session_id),
- cdp_client.send.DOMSnapshot.enable(session_id=session_id),
- cdp_client.send.Page.enable(session_id=session_id),
- )
-
- return cdp_client
-
- except Exception:
- # Clean up on error
- await cdp_client.stop()
- raise
+ # 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.
@@ -949,19 +1021,16 @@ class BrowserSession(BaseModel):
frame_id: The frame ID to find and attach to
Returns:
- CDPClient with session attached to the target containing this frame
+ Tuple of (CDPClient, session_id) for the target containing this frame
Raises:
ValueError: If frame_id is not found in any target
"""
- search_client = await self._create_fresh_cdp_client()
-
- try:
- # Get all targets
- targets = await search_client.send.Target.getTargets()
+ # 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']:
+ # 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
@@ -969,15 +1038,11 @@ class BrowserSession(BaseModel):
if target['type'] != 'page':
continue
- # Attach to this target to check its frame tree
- session = await search_client.send.Target.attachToTarget(params={'targetId': target['targetId'], 'flatten': True})
- temp_session_id = session['sessionId']
-
- # Enable Page domain to get frame tree
- await search_client.send.Page.enable(session_id=temp_session_id)
+ # 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 search_client.send.Page.getFrameTree(session_id=temp_session_id)
+ frame_tree = await client.send.Page.getFrameTree(session_id=temp_session_id)
# Recursively search for the frame_id
def search_frame_tree(node) -> bool:
@@ -990,19 +1055,11 @@ class BrowserSession(BaseModel):
return False
if search_frame_tree(frame_tree['frameTree']):
- # Found the target containing this frame
- await search_client.stop()
+ # Found the target containing this frame - return cached session
+ return await self.get_cdp_session(target['targetId'])
- # Create a new session for this target
- return await self.create_cdp_session_for_target(target['targetId'])
-
- # Frame not found
- await search_client.stop()
- raise ValueError(f'Frame with ID {frame_id} not found in any target')
-
- except Exception:
- await search_client.stop()
- raise
+ # 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.
@@ -1011,7 +1068,7 @@ class BrowserSession(BaseModel):
node: The EnhancedDOMTreeNode to create a session for
Returns:
- CDPClient with session attached to the node's target
+ 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
@@ -1019,24 +1076,15 @@ class BrowserSession(BaseModel):
if not hasattr(node, 'target_id') or not node.target_id:
raise ValueError(f'Node does not have a target_id: {node}')
- # Create session for the node's target
- cdp_client = await self.create_cdp_session_for_target(node.target_id)
+ # 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:
- # Verify the node exists in this target
- # Use the stored session_id from the client
- session_id = getattr(cdp_client, 'target_session_id', None)
- if not session_id:
- raise ValueError('CDP client does not have target_session_id set')
-
- result = await cdp_client.send.DOM.describeNode(params={'backendNodeId': node.backend_node_id}, session_id=session_id)
-
+ 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 cdp_client
-
+ return client, session_id
except Exception as e:
- # Node doesn't exist in this target, clean up
- await cdp_client.stop()
raise ValueError(f'Node with backend_node_id {node.backend_node_id} not found in target {node.target_id}: {e}')
async def get_current_target_info(self) -> dict | None:
@@ -1164,27 +1212,19 @@ class BrowserSession(BaseModel):
async def remove_highlights(self) -> None:
"""Remove highlights from the page using CDP."""
try:
- # Check if we have a CDP client and target
if not self.current_target_id:
return
- # This will raise RuntimeError if CDP client not initialized
- cdp_client = self.cdp_client
-
- # Attach to current target
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})
- session_id = session['sessionId']
+ # Get cached session
+ client, session_id = await self.get_cdp_session(self.current_target_id)
- # Remove highlights via JavaScript - matches the highlighting system from debug/highlights.py
+ # Remove highlights via JavaScript
script = """
// Remove all browser-use highlight elements
const highlights = document.querySelectorAll('[data-browser-use-highlight]');
highlights.forEach(el => el.remove());
"""
- await cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)
-
- # Detach from target
- await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+ await client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)
except Exception as e:
self.logger.debug(f'Failed to remove highlights: {e}')
@@ -1207,45 +1247,31 @@ class BrowserSession(BaseModel):
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 with automatic attach/detach.
+ """Execute CDP commands on a specific target using cached session.
Args:
- target_id: The target ID to attach to
+ 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
"""
- # Attach to target
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
-
- try:
- if callable_fn:
- # Execute the provided async function
- return await callable_fn(self.cdp_client, session_id)
- elif commands:
- # Execute the list of commands
- result = None
- for method, params in commands:
- # Parse the method name to get domain and command
- domain, command = method.split('.')
- # Get the domain object dynamically
- domain_obj = getattr(self.cdp_client.send, domain)
- # Call the command with params and session_id
- # CDP library expects params as first arg (can be None), session_id as second
- cmd_func = getattr(domain_obj, command)
- if params:
- result = await cmd_func(params=params, session_id=session_id)
- else:
- result = await cmd_func(session_id=session_id)
- return result
- else:
- return session_id # Just return session_id if no commands
- finally:
- # Always detach from target
- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+ # 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) -> list[dict]:
"""Get all browser pages/tabs using CDP Target.getTargets."""
@@ -1267,85 +1293,38 @@ class BrowserSession(BaseModel):
await self.cdp_client.send.Target.activateTarget(params={'targetId': target_id})
async def _cdp_get_cookies(self, urls: list[str] | None = None) -> list[dict]:
- """Get cookies using CDP Network.getCookies.
-
- Note: Network domain must be enabled on a target before calling this.
- """
+ """Get cookies using CDP Network.getCookies."""
if not self.current_target_id:
return []
-
- # Attach to current target to get cookies
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})
- session_id = session['sessionId']
-
- try:
- # Enable Network domain if not already enabled
- await self.cdp_client.send.Network.enable(session_id=session_id)
-
- # Get cookies
- params = {'urls': urls} if urls else {}
- result = await self.cdp_client.send.Network.getCookies(params=params, session_id=session_id)
- return result.get('cookies', [])
- finally:
- # Always detach from target
- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+
+ 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)
+ return result.get('cookies', [])
async def _cdp_set_cookies(self, cookies: list[dict]) -> None:
"""Set cookies using CDP Network.setCookies."""
if not self.current_target_id or not cookies:
return
-
- # Attach to current target to set cookies
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})
- session_id = session['sessionId']
-
- try:
- # Enable Network domain if not already enabled
- await self.cdp_client.send.Network.enable(session_id=session_id)
-
- # Set cookies
- await self.cdp_client.send.Network.setCookies(params={'cookies': cookies}, session_id=session_id)
- finally:
- # Always detach from target
- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+
+ client, session_id = await self.get_cdp_session(self.current_target_id)
+ await client.send.Network.setCookies(params={'cookies': cookies}, session_id=session_id)
async def _cdp_clear_cookies(self) -> None:
"""Clear all cookies using CDP Network.clearBrowserCookies."""
if not self.current_target_id:
return
-
- # Attach to current target to clear cookies
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})
- session_id = session['sessionId']
-
- try:
- # Enable Network domain if not already enabled
- await self.cdp_client.send.Network.enable(session_id=session_id)
-
- # Clear cookies
- await self.cdp_client.send.Network.clearBrowserCookies(session_id=session_id)
- finally:
- # Always detach from target
- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+
+ client, session_id = await self.get_cdp_session(self.current_target_id)
+ await client.send.Network.clearBrowserCookies(session_id=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:
return
-
- # Attach to current target to set headers
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': self.current_target_id, 'flatten': True})
- session_id = session['sessionId']
-
- try:
- # Enable Network domain if not already enabled
- await self.cdp_client.send.Network.enable(session_id=session_id)
-
- # Set extra headers
- await self.cdp_client.send.Network.setExtraHTTPHeaders(params={'headers': headers}, session_id=session_id)
- finally:
- # Always detach from target
- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
+
+ client, session_id = await self.get_cdp_session(self.current_target_id)
+ await client.send.Network.setExtraHTTPHeaders(params={'headers': headers}, session_id=session_id)
async def _cdp_grant_permissions(self, permissions: list[str], origin: str | None = None) -> None:
"""Grant permissions using CDP Browser.grantPermissions."""
@@ -1488,21 +1467,14 @@ class BrowserSession(BaseModel):
):
continue
- # Attach to target
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
+ # Get cached session for this target
+ client, session_id = await self.get_cdp_session(target_id)
target_sessions[target_id] = session_id
try:
- # Set auto-attach to get related targets
- await self.cdp_client.send.Target.setAutoAttach(
- params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}, session_id=session_id
- )
-
# Try to get frame tree (not all target types support this)
try:
- await self.cdp_client.send.Page.enable(session_id=session_id)
- frame_tree_result = await self.cdp_client.send.Page.getFrameTree(session_id=session_id)
+ frame_tree_result = await client.send.Page.getFrameTree(session_id=session_id)
# Process the frame tree recursively
def process_frame_tree(node, parent_frame_id=None):
@@ -1625,19 +1597,6 @@ class BrowserSession(BaseModel):
return all_frames.get(frame_id)
- async def cleanup_target_sessions(self, target_sessions: dict[str, str], keep_target_id: str | None = None) -> None:
- """Clean up CDP sessions by detaching from targets.
-
- Args:
- target_sessions: Dict of target_id -> session_id to clean up
- keep_target_id: Optional target ID to keep attached (won't detach this one)
- """
- for target_id, session_id in target_sessions.items():
- if target_id != keep_target_id:
- try:
- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
- except Exception:
- pass
async def cdp_client_for_frame(self, frame_id: str) -> Any:
"""Get a CDP client attached to the target containing the specified frame.
@@ -1666,36 +1625,24 @@ class BrowserSession(BaseModel):
if target_id in target_sessions:
# Use existing session
session_id = target_sessions[target_id]
-
- # Clean up other sessions before returning
- await self.cleanup_target_sessions(target_sessions, keep_target_id=target_id)
-
- # Return the client with session attached (caller must detach)
+ # Return the client with session attached
return self.cdp_client, session_id, target_id
- # Clean up all sessions before raising error
- await self.cleanup_target_sessions(target_sessions)
-
# 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 attaches to a specific target ID.
+ 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 attached target
+ Tuple of (cdp_client, session_id) for the target
"""
- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
- session_id = session['sessionId']
-
- # Return the client and session_id
- # Caller is responsible for detaching when done
- return self.cdp_client, session_id
+ return await self.get_cdp_session(target_id)
# Import uuid7str for ID generation
@@ -1719,6 +1666,7 @@ _watchdog_modules = [
'browser_use.browser.aboutblank_watchdog.AboutBlankWatchdog',
'browser_use.browser.default_action_watchdog.DefaultActionWatchdog',
'browser_use.browser.dom_watchdog.DOMWatchdog',
+ 'browser_use.browser.screenshot_watchdog.ScreenshotWatchdog',
]
for module_path in _watchdog_modules:
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index babca906c..119f42909 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -130,8 +130,12 @@ class Controller(Generic[Context]):
@self.registry.action('Go back', param_model=NoParamsAction)
async def go_back(_: NoParamsAction, browser_session: BrowserSession):
- event = browser_session.event_bus.dispatch(GoBackEvent())
- await event
+ try:
+ event = browser_session.event_bus.dispatch(GoBackEvent())
+ await event
+ except Exception as e:
+ logger.error(f'Failed to dispatch GoBackEvent: {type(e).__name__}: {e}')
+ raise ValueError(f'Failed to go back: {e}') from e
msg = '🔙 Navigated back'
logger.info(msg)
return ActionResult(extracted_content=msg)
@@ -162,10 +166,14 @@ class Controller(Generic[Context]):
raise ValueError(f'Element index {params.index} not found in DOM')
# Dispatch click event with node
- event = browser_session.event_bus.dispatch(
- ClickElementEvent(node=node, expect_download=params.expect_download, new_tab=params.new_tab)
- )
- await event
+ try:
+ event = browser_session.event_bus.dispatch(
+ ClickElementEvent(node=node, expect_download=params.expect_download, new_tab=params.new_tab)
+ )
+ await event
+ except Exception as e:
+ logger.error(f'Failed to dispatch ClickElementEvent: {type(e).__name__}: {e}')
+ raise ValueError(f'Failed to click element {params.index}: {e}') from e
# Get the result if any (e.g., download path)
result = await event.event_result()
@@ -192,8 +200,14 @@ class Controller(Generic[Context]):
raise ValueError(f'Element index {params.index} not found in DOM')
# Dispatch type text event with node
- event = browser_session.event_bus.dispatch(TypeTextEvent(node=node, text=params.text))
- await event
+ try:
+ event = browser_session.event_bus.dispatch(TypeTextEvent(node=node, text=params.text))
+ await event
+ except Exception as e:
+ # Log the full error for debugging
+ logger.error(f'Failed to dispatch TypeTextEvent: {type(e).__name__}: {e}')
+ # Re-raise with more context
+ raise ValueError(f'Failed to input text into element {params.index}: {e}') from e
if not has_sensitive_data:
msg = f'⌨️ Input {params.text} into index {params.index}'
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 206074016..d02a05ae7 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -107,31 +107,15 @@ class DomService:
target_id = str(target['targetId'])
- # if target_id in self.target_to_session_id_cache:
- # return self.target_to_session_id_cache[target_id]
-
- try:
- session = await self.browser_session.cdp_client.send.Target.attachToTarget(
- params={'targetId': target_id, 'flatten': True}
- )
- session_id = session['sessionId']
- except Exception as e:
- raise
-
- # Track this session for cleanup
- self._attached_sessions.add(session_id)
-
- await self._enable_all_domains_on_session(session_id)
-
+ # Use cached session from BrowserSession
+ client, session_id = await self.browser_session.get_cdp_session(target_id)
+
+ # Domains are already enabled by get_cdp_session, no need to track for cleanup
return session_id
async def _cleanup_sessions(self) -> None:
- """Detach from all attached sessions."""
- for session_id in self._attached_sessions:
- try:
- await self.browser_session.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})
- except Exception:
- pass # Session might already be detached
+ """Clear cached session data. Sessions are now managed by BrowserSession."""
+ # Sessions are now cached and managed by BrowserSession, no need to detach
self._attached_sessions.clear()
self.session_id_domains_enabled_cache.clear()