Skip to content

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

remove expect_download param from click action

Nick Sweeting557067b8e977
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.py
index 8b4cd71ce..fe4a30005 100644
--- a/browser_use/browser/aboutblank_watchdog.py
+++ b/browser_use/browser/aboutblank_watchdog.py
@@ -136,7 +136,7 @@ class AboutBlankWatchdog(BaseWatchdog):
try:
# Get just the page targets without expensive title fetching
page_targets = await self.browser_session._cdp_get_all_pages()
- browser_session_id = str(self.browser_session.id)[-4:]
+ browser_session_label = str(self.browser_session.id)[-4:]
for page_target in page_targets:
target_id = page_target['targetId']
@@ -144,7 +144,7 @@ class AboutBlankWatchdog(BaseWatchdog):
# Only target about:blank pages specifically
if url == 'about:blank':
- await self._show_dvd_screensaver_loading_animation_cdp(target_id, browser_session_id)
+ await self._show_dvd_screensaver_loading_animation_cdp(target_id, browser_session_label)
except Exception as e:
self.logger.error(f'[AboutBlankWatchdog] Error showing DVD screensaver: {e}')
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.py
index b6c6e1a9a..913f814a3 100644
--- a/browser_use/browser/default_action_watchdog.py
+++ b/browser_use/browser/default_action_watchdog.py
@@ -2,7 +2,6 @@
import asyncio
import platform
-from typing import TYPE_CHECKING
from browser_use.browser.events import (
BrowserErrorEvent,
@@ -21,9 +20,6 @@ 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
-
# Import EnhancedDOMTreeNode and rebuild event models that have forward references to it
# This must be done after all imports are complete
ClickElementEvent.model_rebuild()
@@ -61,9 +57,8 @@ class DefaultActionWatchdog(BaseWatchdog):
)
# Perform the actual click using internal implementation
- download_path = await self._click_element_node_impl(
- element_node, expect_download=event.expect_download, new_tab=event.new_tab
- )
+ await self._click_element_node_impl(element_node, new_tab=event.new_tab)
+ download_path = None # moved to downloads_watchdog.py
# Build success message
if download_path:
@@ -77,7 +72,7 @@ class DefaultActionWatchdog(BaseWatchdog):
# Wait a bit for potential new tab to be created
# This is necessary because tab creation is async and might not be immediate
await asyncio.sleep(0.5)
-
+
# Clear cached state after click action since DOM might have changed
self.logger.debug('πŸ”„ Click action completed, clearing cached browser state')
self.browser_session._cached_browser_state_summary = None
@@ -123,14 +118,14 @@ class DefaultActionWatchdog(BaseWatchdog):
# Log success
self.logger.info(f'⌨️ Typed "{event.text}" into element with index {index_for_logging}')
self.logger.debug(f'Element xpath: {element_node.xpath}')
-
+
# Clear cached state after type action since DOM might have changed
self.logger.debug('πŸ”„ Type action completed, clearing cached browser state')
self.browser_session._cached_browser_state_summary = None
self.browser_session._cached_selector_map.clear()
if self.browser_session._dom_watchdog:
self.browser_session._dom_watchdog.clear_cache()
-
+
return {'success': True}
except Exception as e:
self.event_bus.dispatch(
@@ -192,17 +187,13 @@ class DefaultActionWatchdog(BaseWatchdog):
# ========== Implementation Methods ==========
- async def _click_element_node_impl(self, element_node, expect_download: bool = False, new_tab: bool = False) -> str | None:
+ async def _click_element_node_impl(self, element_node, new_tab: bool = False) -> str | None:
"""
Click an element using pure CDP.
Args:
element_node: The DOM element to click
- expect_download: If True, wait for download and handle it inline
new_tab: If True, open any resulting navigation in a new tab
-
- Returns:
- The download path if a download was triggered, None otherwise
"""
try:
@@ -237,27 +228,6 @@ class DefaultActionWatchdog(BaseWatchdog):
except Exception as e:
self.logger.debug(f'Failed to scroll element into view: {e}')
- # Set up download detection if downloads are enabled
- # download_path = None
- # download_event = asyncio.Event()
- # download_guid = None
-
- if self.browser_session.browser_profile.downloads_path and expect_download:
- # Enable download events
- await cdp_session.cdp_client.send.Page.setDownloadBehavior(
- params={'behavior': 'allow', 'downloadPath': str(self.browser_session.browser_profile.downloads_path)},
- session_id=session_id,
- )
-
- # # Set up download listener
- # async def on_download_will_begin(event):
- # nonlocal download_guid
- # download_guid = event['guid']
- # download_event.set()
-
- # TODO: fix this with download_watchdog.py
- # cdp_client.on('Page.downloadWillBegin', on_download_will_begin, session_id=session_id) # type: ignore[attr-defined]
-
# Perform the click using CDP
# TODO: do occlusion detection first, if element is not on the top, fire JS-based
# click event instead using xpath of x,y coordinate clicking, because we wont be able to click *through* occluding elements using x,y clicks
@@ -316,44 +286,6 @@ class DefaultActionWatchdog(BaseWatchdog):
self.logger.debug('πŸ–±οΈ Clicked successfully using x,y coordinates')
- # Handle download if expected: should be handled by downloads_watchdog.py now using browser-level download event listeners
- # if self.browser_session.browser_profile.downloads_path:
- # try:
- # # Wait for download to start (with timeout)
- # await asyncio.wait_for(download_event.wait(), timeout=5.0)
-
- # # Wait for download to complete
- # download_complete = False
- # for _ in range(60): # Wait up to 60 seconds
- # try:
- # # Check download progress
- # response = await cdp_client.send.Page.getDownloadProgress(
- # params={'guid': download_guid}, session_id=session_id
- # )
- # if response['state'] == 'completed':
- # download_complete = True
- # break
- # elif response['state'] == 'canceled':
- # self.logger.warning('Download was canceled')
- # break
- # except Exception:
- # pass
- # await asyncio.sleep(1)
-
- # if download_complete and download_guid:
- # self.logger.info('⬇️ Download completed via CDP')
- # # Note: DownloadsWatchdog handles download tracking via events
- # return f'download_{download_guid}' # Return guid as placeholder
- # except TimeoutError:
- # # No download triggered, normal click
- # self.logger.debug('No download triggered within timeout.')
-
- # # Wait for navigation/changes
- # await asyncio.sleep(0.5)
- # # Navigation is handled by NavigationWatchdog via events
-
- # return download_path
-
except Exception as e:
self.logger.warning(f'CDP click failed: {type(e).__name__}: {e}')
# Fall back to JavaScript click via CDP
@@ -650,14 +582,14 @@ class DefaultActionWatchdog(BaseWatchdog):
# Wait for reload
await asyncio.sleep(1.0)
-
+
# Clear cached state after refresh since DOM has been reloaded
self.logger.debug('πŸ”„ Page refreshed, clearing cached browser state')
self.browser_session._cached_browser_state_summary = None
self.browser_session._cached_selector_map.clear()
if self.browser_session._dom_watchdog:
self.browser_session._dom_watchdog.clear_cache()
-
+
# Navigation is handled by NavigationWatchdog via events
self.logger.info('πŸ”„ Target refreshed')
@@ -770,7 +702,7 @@ class DefaultActionWatchdog(BaseWatchdog):
)
self.logger.info(f'⌨️ Sent keys: {event.keys}')
-
+
# Clear cached state if Enter key was pressed (might submit form and change DOM)
if 'enter' in event.keys.lower() or 'return' in event.keys.lower():
self.logger.debug('πŸ”„ Enter key pressed, clearing cached browser state')
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index fd8ce8fbf..f162810d1 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -63,9 +63,9 @@ class ClickElementEvent(ElementSelectedEvent[dict[str, str] | None]):
node: 'EnhancedDOMTreeNode'
button: Literal['left', 'right', 'middle'] = 'left'
- click_count: int = 1
- expect_download: bool = False
new_tab: bool = False
+ # click_count: int = 1 # TODO
+ # expect_download: bool = False # moved to downloads_watchdog.py
class TypeTextEvent(ElementSelectedEvent):
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 9ce0171f0..e64289a52 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -5,6 +5,9 @@ import logging
from pathlib import Path
from typing import Any, Self, cast
+# Silence cdp_use logging - it's too verbose at DEBUG level
+# We need to patch the logger in the cdp_use.client module directly
+import cdp_use.client
import httpx
from bubus import EventBus
from cdp_use import CDPClient
@@ -12,9 +15,6 @@ from cdp_use.cdp.network import Cookie
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
from uuid_extensions import uuid7str
-# Silence cdp_use logging - it's too verbose at DEBUG level
-# We need to patch the logger in the cdp_use.client module directly
-import cdp_use.client
cdp_use.client.logger.setLevel(logging.ERROR)
# Also configure all cdp_use loggers
@@ -220,14 +220,14 @@ class BrowserSession(BaseModel):
# Check if handlers are already registered to prevent duplicates
start_handlers = self.event_bus.handlers.get('BrowserStartEvent', [])
start_handler_names = [getattr(h, '__name__', str(h)) for h in start_handlers]
-
+
if any('on_BrowserStartEvent' in name for name in start_handler_names):
raise RuntimeError(
- f'[BrowserSession] Duplicate handler registration attempted! '
- f'on_BrowserStartEvent is already registered. '
- f'This likely means BrowserSession was initialized multiple times with the same EventBus.'
+ '[BrowserSession] Duplicate handler registration attempted! '
+ 'on_BrowserStartEvent is already registered. '
+ 'This likely means BrowserSession was initialized multiple times with the same EventBus.'
)
-
+
# Register BrowserSession's event handlers
self.event_bus.on(BrowserStartEvent, self.on_BrowserStartEvent)
self.event_bus.on(BrowserStopEvent, self.on_BrowserStopEvent)
@@ -333,11 +333,11 @@ class BrowserSession(BaseModel):
async def get_or_create_cdp_session(self, target_id: str | None = None, focus: bool = True) -> CDPSession:
"""Get or create a CDP session for a target.
-
+
Args:
target_id: Target ID to get session for. If None, uses current agent focus.
focus: If True, switches agent focus to this target. If False, just returns session without changing focus.
-
+
Returns:
CDPSession for the specified target.
"""
@@ -348,17 +348,19 @@ class BrowserSession(BaseModel):
# If no target_id specified, use the current target_id
if target_id is None:
target_id = self.agent_focus.target_id
-
+
# Check if we already have a session for this target in the pool
if target_id in self._cdp_session_pool:
session = self._cdp_session_pool[target_id]
if focus and self.agent_focus.target_id != target_id:
- self.logger.debug(f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}')
+ self.logger.debug(
+ f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}'
+ )
self.agent_focus = session
else:
self.logger.debug(f'[get_or_create_cdp_session] Reusing existing session for {target_id} (focus={focus})')
return session
-
+
# If it's the current focus target, return that session
if self.agent_focus.target_id == target_id:
self._cdp_session_pool[target_id] = self.agent_focus
@@ -368,14 +370,18 @@ class BrowserSession(BaseModel):
self.logger.debug(f'[get_or_create_cdp_session] Creating new CDP session for target {target_id}')
session = await CDPSession.for_target(self._cdp_client_root, target_id)
self._cdp_session_pool[target_id] = session
-
+
# Only change agent focus if requested
if focus:
- self.logger.debug(f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}')
+ self.logger.debug(
+ f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}'
+ )
self.agent_focus = session
else:
- self.logger.debug(f'[get_or_create_cdp_session] Created session for {target_id} without changing focus (still on {self.agent_focus.target_id})')
-
+ self.logger.debug(
+ f'[get_or_create_cdp_session] Created session for {target_id} without changing focus (still on {self.agent_focus.target_id})'
+ )
+
return session
@property
@@ -394,7 +400,7 @@ class BrowserSession(BaseModel):
if cached and self._cached_browser_state_summary is not None and self._cached_browser_state_summary.dom_state:
# Don't use cached state if it has 0 interactive elements
selector_map = self._cached_browser_state_summary.dom_state.selector_map
-
+
# Don't use cached state if we need a screenshot but the cached state doesn't have one
if include_screenshot and not self._cached_browser_state_summary.screenshot:
self.logger.debug('⚠️ Cached browser state has no screenshot, fetching fresh state with screenshot')
@@ -427,7 +433,7 @@ class BrowserSession(BaseModel):
if hasattr(self, '_watchdogs_attached') and self._watchdogs_attached:
self.logger.debug('Watchdogs already attached, skipping duplicate attachment')
return
-
+
from browser_use.browser.aboutblank_watchdog import AboutBlankWatchdog
from browser_use.browser.crash_watchdog import CrashWatchdog
from browser_use.browser.default_action_watchdog import DefaultActionWatchdog
@@ -521,7 +527,7 @@ class BrowserSession(BaseModel):
# self.event_bus.on(TabCreatedEvent, self._dom_watchdog.on_TabCreatedEvent)
# self.event_bus.on(BrowserStateRequestEvent, self._dom_watchdog.on_BrowserStateRequestEvent)
await self._dom_watchdog.attach_to_session()
-
+
# Mark watchdogs as attached to prevent duplicate attachment
self._watchdogs_attached = True
@@ -540,6 +546,8 @@ class BrowserSession(BaseModel):
url = self.cdp_url.rstrip('/')
if not url.endswith('/json/version'):
url = url + '/json/version'
+
+ # Run a tiny HTTP client to query for the WebSocket URL from the /json/version endpoint
async with httpx.AsyncClient() as client:
version_info = await client.get(url)
self.cdp_url = version_info.json()['webSocketDebuggerUrl']
@@ -601,7 +609,7 @@ class BrowserSession(BaseModel):
await asyncio.sleep(0.1)
except Exception as e:
self.logger.warning(f'Failed to redirect {target_url} to about:blank: {e}')
-
+
# Log summary of redirections
if redirected_targets:
self.logger.info(f'βœ… Redirected {len(redirected_targets)} chrome://newtab pages to about:blank')
diff --git a/browser_use/cli.py b/browser_use/cli.py
index c2de399c3..454d9f230 100644
--- a/browser_use/cli.py
+++ b/browser_use/cli.py
@@ -258,53 +258,58 @@ class BrowserUseApp(App):
layout: vertical;
}
- #logo-panel, #links-panel, #paths-panel, #info-panels {
+ #logo-panel, #links-panel, #paths-panel {
border: solid $primary;
margin: 0 0 0 0;
padding: 0;
}
- #info-panels {
+ #three-column-container {
+ height: 1fr;
+ layout: horizontal;
+ width: 100%;
display: none;
- layout: vertical;
- height: auto;
- min-height: 5;
}
- #top-panels {
- layout: horizontal;
- height: auto;
- width: 100%;
- min-height: 5;
+ #main-output-column {
+ width: 1fr;
+ height: 100%;
+ border: solid $primary;
+ padding: 0;
+ margin: 0 1 0 0;
}
- #browser-panel, #model-panel {
+ #events-column {
width: 1fr;
- height: auto;
- border: solid $primary-darken-2;
- padding: 1;
- overflow: auto;
+ height: 100%;
+ border: solid $warning;
+ padding: 0;
margin: 0 1 0 0;
- padding: 1;
}
- #tasks-panel {
+ #cdp-column {
+ width: 1fr;
+ height: 100%;
+ border: solid $accent;
+ padding: 0;
+ margin: 0;
+ }
+
+ #main-output-log, #events-log, #cdp-log {
+ height: 100%;
+ overflow-y: scroll;
+ background: $surface;
+ color: $text;
width: 100%;
- height: 1fr;
- min-height: 20;
- max-height: 60vh;
- border: solid $primary-darken-2;
padding: 1;
- overflow-y: scroll;
- margin: 1 0 0 0;
}
- #browser-panel {
- border-left: solid $primary-darken-2;
+ #events-log {
+ color: $warning;
}
- #results-container {
- display: none;
+ #cdp-log {
+ color: $accent-lighten-2;
}
#logo-panel {
@@ -374,46 +379,6 @@ class BrowserUseApp(App):
#task-input {
width: 100%;
}
-
- #working-panel {
- border: solid $warning;
- padding: 1;
- margin: 1 0;
- }
-
- #completion-panel {
- border: solid $success;
- padding: 1;
- margin: 1 0;
- }
-
- #results-container {
- height: 1fr;
- overflow: auto;
- border: none;
- }
-
- #results-log {
- height: auto;
- overflow-y: scroll;
- background: $surface;
- color: $text;
- width: 100%;
- }
-
- .log-entry {
- margin: 0;
- padding: 0;
- }
-
- #browser-info, #model-info, #tasks-info {
- height: auto;
- margin: 0;
- padding: 0;
- background: transparent;
- overflow-y: auto;
- min-height: 5;
- }
"""
BINDINGS = [
@@ -436,6 +401,8 @@ class BrowserUseApp(App):
self.history_index = len(self.task_history)
# Initialize telemetry
self._telemetry = ProductTelemetry()
+ # Store for event bus handler
+ self._event_bus_handler_id = None
def setup_richlog_logging(self) -> None:
"""Set up logging to redirect to RichLog widget instead of stdout."""
@@ -445,8 +412,8 @@ class BrowserUseApp(App):
except AttributeError:
pass # Level already exists, which is fine
- # Get the RichLog widget
- rich_log = self.query_one('#results-log', RichLog)
+ # Get the main output RichLog widget
+ rich_log = self.query_one('#main-output-log', RichLog)
# Create and set up the custom handler
log_handler = RichLogHandler(rich_log)
@@ -545,13 +512,13 @@ class BrowserUseApp(App):
logger.error(f'Error focusing input field: {str(e)}', exc_info=True)
# Non-critical, continue
- # Step 5: Start continuous info panel updates
- logger.debug('Starting info panel updates...')
+ # Step 5: Setup CDP logger early (event bus listener will be set up when browser session is available)
+ logger.debug('Setting up CDP logging...')
try:
- self.update_info_panels()
- logger.debug('Info panel updates started')
+ self.setup_cdp_logger()
+ logger.debug('CDP logging setup complete')
except Exception as e:
- logger.error(f'Error starting info panel updates: {str(e)}', exc_info=True)
+ logger.error(f'Error setting up CDP logging: {str(e)}', exc_info=True)
# Non-critical, continue
# Capture telemetry for CLI start
@@ -651,328 +618,102 @@ class BrowserUseApp(App):
event.input.value = ''
def hide_intro_panels(self) -> None:
- """Hide the intro panels, show info panels, and expand the log view."""
+ """Hide the intro panels and show the three-column view."""
try:
# Get the panels
logo_panel = self.query_one('#logo-panel')
links_panel = self.query_one('#links-panel')
paths_panel = self.query_one('#paths-panel')
- info_panels = self.query_one('#info-panels')
- tasks_panel = self.query_one('#tasks-panel')
- # Hide intro panels if they're visible and show info panels
+ three_column = self.query_one('#three-column-container')
+
+ # Hide intro panels if they're visible and show three-column view
if logo_panel.display:
- # Log for debugging
- logging.info('Hiding intro panels and showing info panels')
+ logging.info('Hiding intro panels and showing three-column view')
logo_panel.display = False
links_panel.display = False
paths_panel.display = False
- # Show info panels
- info_panels.display = True
- tasks_panel.display = True
-
- # Make results container take full height
- results_container = self.query_one('#results-container')
- results_container.styles.height = '1fr'
-
- # Configure the log
- results_log = self.query_one('#results-log')
- results_log.styles.height = 'auto'
+ # Show three-column container
+ three_column.display = True
- logging.info('Panels should now be visible')
+ logging.info('Three-column view should now be visible')
except Exception as e:
logging.error(f'Error in hide_intro_panels: {str(e)}')
- def update_info_panels(self) -> None:
- """Update all information panels with current state."""
- try:
- # Update actual content
- self.update_browser_panel()
- self.update_model_panel()
- self.update_tasks_panel()
- except Exception as e:
- logging.error(f'Error in update_info_panels: {str(e)}')
- finally:
- # Always schedule the next update - will update at 1-second intervals
- # This ensures continuous updates even if agent state changes
- self.set_timer(1.0, self.update_info_panels)
-
- def update_browser_panel(self) -> None:
- """Update browser information panel with details about the browser."""
- browser_info = self.query_one('#browser-info', RichLog)
- browser_info.clear()
-
- # Try to use the agent's browser session if available
- browser_session = self.browser_session
- if hasattr(self, 'agent') and self.agent and hasattr(self.agent, 'browser_session'):
- browser_session = self.agent.browser_session
-
- if browser_session:
+ def setup_event_bus_listener(self) -> None:
+ """Setup listener for browser session event bus."""
+ if not self.browser_session or not self.browser_session.event_bus:
+ return
+
+ # Get the events log widget
+ events_log = self.query_one('#events-log', RichLog)
+
+ # Create handler to log all events
+ def log_event(event):
+ event_name = event.__class__.__name__
+ # Format event data nicely
try:
- # Check if browser session is connected
- if not browser_session.cdp_url:
- browser_info.write('[yellow]Browser session created, waiting for browser to launch...[/]')
- return
-
- # Update our reference if we're using the agent's session
- if browser_session != self.browser_session:
- self.browser_session = browser_session
-
- # Get basic browser info from browser_profile
- browser_type = 'Chromium'
- headless = browser_session.browser_profile.headless
-
- # Determine connection type based on config
- connection_type = 'playwright' # Default
- if browser_session.cdp_url:
- connection_type = 'CDP'
- elif browser_session.browser_profile.executable_path:
- connection_type = 'user-provided'
-
- # Get window size details from browser_profile
- window_width = None
- window_height = None
- if browser_session.browser_profile.viewport:
- window_width = browser_session.browser_profile.viewport.get('width')
- window_height = browser_session.browser_profile.viewport.get('height')
-
- # Try to get browser PID
- browser_pid = 'Unknown'
- connected = False
- browser_status = '[red]Disconnected[/]'
+ if hasattr(event, 'model_dump'):
+ event_data = event.model_dump(exclude_unset=True)
+ # Remove large fields
+ if 'screenshot' in event_data:
+ event_data['screenshot'] = '<bytes>'
+ if 'dom_state' in event_data:
+ event_data['dom_state'] = '<truncated>'
+ event_str = str(event_data) if event_data else ''
+ else:
+ event_str = str(event)
+
+ # Truncate long strings
+ if len(event_str) > 200:
+ event_str = event_str[:200] + '...'
+
+ events_log.write(f'[yellow]β†’ {event_name}[/] {event_str}')
+ except Exception as e:
+ events_log.write(f'[red]β†’ {event_name}[/] (error formatting: {e})')
+
+ # Register wildcard handler for all events
+ self._event_bus_handler_id = self.browser_session.event_bus.on('*', log_event)
+
+ def setup_cdp_logger(self) -> None:
+ """Setup CDP message logger."""
+ # Get the CDP log widget
+ cdp_log = self.query_one('#cdp-log', RichLog)
+ # Create custom handler for CDP logging
+ class CDPLogHandler(logging.Handler):
+ def __init__(self, rich_log: RichLog):
+ super().__init__()
+ self.rich_log = rich_log
+
+ def emit(self, record):
try:
- # Check if browser PID is available through LocalBrowserWatchdog
- if hasattr(browser_session, '_local_browser_watchdog') and browser_session._local_browser_watchdog:
- local_watchdog = browser_session._local_browser_watchdog
- if hasattr(local_watchdog, 'browser_pid') and local_watchdog.browser_pid:
- browser_pid = str(local_watchdog.browser_pid)
- connected = True
- browser_status = '[green]Connected[/]'
- # Otherwise just check if we have a CDP URL
- elif browser_session.cdp_url:
- connected = True
- browser_status = '[green]Connected[/]'
- browser_pid = 'N/A'
- except Exception as e:
- browser_pid = f'Error: {str(e)}'
-
- # Display browser information
- browser_info.write(f'[bold cyan]Chromium[/] Browser ({browser_status})')
- browser_info.write(
- f'Type: [yellow]{connection_type}[/] [{"green" if not headless else "red"}]{" (headless)" if headless else ""}[/]'
- )
- browser_info.write(f'PID: [dim]{browser_pid}[/]')
- browser_info.write(f'CDP Port: {browser_session.cdp_url}')
-
- if window_width and window_height:
- browser_info.write(f'Window: [blue]{window_width}[/] Γ— [blue]{window_height}[/]')
-
- # Include additional information about the browser if needed
- if connected and hasattr(self, 'agent') and self.agent:
- try:
- # Show when the browser was connected
- timestamp = int(time.time())
- current_time = time.strftime('%H:%M:%S', time.localtime(timestamp))
- browser_info.write(f'Last updated: [dim]{current_time}[/]')
- except Exception:
- pass
-
- # Show the agent's current page URL if available
- if browser_session._cached_browser_state_summary:
- try:
- # Use cached browser state to get URL
- current_url = browser_session._cached_browser_state_summary.url
- if current_url:
- current_url = current_url.replace('https://', '').replace('http://', '').replace('www.', '')[:36]
- if len(current_url) > 36:
- current_url += '…'
- browser_info.write(f'πŸ‘οΈ [green]{current_url}[/]')
- except Exception:
- pass
- except Exception as e:
- browser_info.write(f'[red]Error updating browser info: {str(e)}[/]')
- else:
- browser_info.write('[red]Browser not initialized[/]')
-
- def update_model_panel(self) -> None:
- """Update model information panel with details about the LLM."""
- model_info = self.query_one('#model-info', RichLog)
- model_info.clear()
-
- if self.llm:
- # Get model details
- model_name = 'Unknown'
- if hasattr(self.llm, 'model_name'):
- model_name = self.llm.model_name
- elif hasattr(self.llm, 'model'):
- model_name = self.llm.model
-
- # Show model name
- if self.agent:
- temp_str = f'{self.llm.temperature}ΒΊC ' if self.llm.temperature else ''
- vision_str = '+ vision ' if self.agent.settings.use_vision else ''
- planner_str = '+ planner' if self.agent.settings.planner_llm else ''
- model_info.write(
- f'[white]LLM:[/] [blue]{self.llm.__class__.__name__} [yellow]{model_name}[/] {temp_str}{vision_str}{planner_str}'
- )
- else:
- model_info.write(f'[white]LLM:[/] [blue]{self.llm.__class__.__name__} [yellow]{model_name}[/]')
-
- # Show token usage statistics if agent exists and has history
- if self.agent and hasattr(self.agent, 'state') and hasattr(self.agent.state, 'history'):
- # Get total tokens used
- # total_tokens = self.agent.history.total_input_tokens()
- # model_info.write(f'[white]Input tokens:[/] [green]{total_tokens:,}[/]')
-
- # Calculate tokens per step
- num_steps = len(self.agent.history.history)
- # if num_steps > 0:
- # avg_tokens_per_step = total_tokens / num_steps
- # model_info.write(f'[white]Avg tokens/step:[/] [green]{avg_tokens_per_step:,.1f}[/]')
-
- # Get the last step metadata to show the most recent LLM response time
- if num_steps > 0 and self.agent.history.history[-1].metadata:
- last_step = self.agent.history.history[-1]
- if last_step.metadata:
- step_duration = last_step.metadata.duration_seconds
+ msg = self.format(record)
+ # Truncate very long messages
+ if len(msg) > 300:
+ msg = msg[:300] + '...'
+ # Color code by level
+ if record.levelno >= logging.ERROR:
+ self.rich_log.write(f'[red]{msg}[/]')
+ elif record.levelno >= logging.WARNING:
+ self.rich_log.write(f'[yellow]{msg}[/]')
else:
- step_duration = 0
- # step_tokens = last_step.metadata.input_tokens
-
- # if step_tokens > 0:
- # tokens_per_second = step_tokens / step_duration if step_duration > 0 else 0
- # model_info.write(f'[white]Avg tokens/sec:[/] [magenta]{tokens_per_second:.1f}[/]')
-
- # Show total duration
- total_duration = self.agent.history.total_duration_seconds()
- if total_duration > 0:
- model_info.write(f'[white]Total Duration:[/] [magenta]{total_duration:.2f}s[/]')
-
- # Calculate response time metrics
- model_info.write(f'[white]Last Step Duration:[/] [magenta]{step_duration:.2f}s[/]')
-
- # Add current state information
- if hasattr(self.agent, 'running'):
- if getattr(self.agent, 'running', False):
- model_info.write('[yellow]LLM is thinking[blink]...[/][/]')
- elif hasattr(self.agent, 'state') and hasattr(self.agent.state, 'paused') and self.agent.state.paused:
- model_info.write('[orange]LLM paused[/]')
- else:
- model_info.write('[red]Model not initialized[/]')
-
- def update_tasks_panel(self) -> None:
- """Update tasks information panel with details about the tasks and steps hierarchy."""
- tasks_info = self.query_one('#tasks-info', RichLog)
- tasks_info.clear()
-
- if self.agent:
- # Check if agent has tasks
- task_history = []
- message_history = []
-
- # Try to extract tasks by looking at message history
- if hasattr(self.agent, '_message_manager') and self.agent._message_manager:
- message_history = self.agent._message_manager.state.history.get_messages()
-
- # Extract original task(s)
- original_tasks = []
- for msg in message_history:
- if hasattr(msg, 'content'):
- content = msg.content
- if isinstance(content, str) and 'Your ultimate task is:' in content:
- task_text = content.split('"""')[1].strip()
- original_tasks.append(task_text)
-
- if original_tasks:
- tasks_info.write('[bold green]TASK:[/]')
- for i, task in enumerate(original_tasks, 1):
- # Only show latest task if multiple task changes occurred
- if i == len(original_tasks):
- tasks_info.write(f'[white]{task}[/]')
- tasks_info.write('')
-
- # Get current state information
- current_step = self.agent.state.n_steps if hasattr(self.agent, 'state') else 0
-
- # Get all agent history items
- history_items = []
- if hasattr(self.agent, 'state') and hasattr(self.agent.state, 'history'):
- history_items = self.agent.history.history
-
- if history_items:
- tasks_info.write('[bold yellow]STEPS:[/]')
-
- for idx, item in enumerate(history_items, 1):
- # Determine step status
- step_style = '[green]βœ“[/]'
-
- # For the current step, show it as in progress
- if idx == current_step:
- step_style = '[yellow]⟳[/]'
-
- # Check if this step had an error
- if item.result and any(result.error for result in item.result):
- step_style = '[red]βœ—[/]'
-
- # Show step number
- tasks_info.write(f'{step_style} Step {idx}/{current_step}')
-
- # Show goal if available
- if item.model_output and hasattr(item.model_output, 'current_state'):
- # Show goal for this step
- goal = item.model_output.current_state.next_goal
- if goal:
- # Take just the first line for display
- goal_lines = goal.strip().split('\n')
- goal_summary = goal_lines[0]
- tasks_info.write(f' [cyan]Goal:[/] {goal_summary}')
-
- # Show evaluation of previous goal (feedback)
- eval_prev = item.model_output.current_state.evaluation_previous_goal
- if eval_prev and idx > 1: # Only show for steps after the first
- eval_lines = eval_prev.strip().split('\n')
- eval_summary = eval_lines[0]
- eval_summary = eval_summary.replace('Success', 'βœ… ').replace('Failed', '❌ ').strip()
- tasks_info.write(f' [tan]Evaluation:[/] {eval_summary}')
-
- # Show actions taken in this step
- if item.model_output and item.model_output.action:
- tasks_info.write(' [purple]Actions:[/]')
- for action_idx, action in enumerate(item.model_output.action, 1):
- action_type = action.__class__.__name__
- if hasattr(action, 'model_dump'):
- # For proper actions, show the action type
- action_dict = action.model_dump(exclude_unset=True)
- if action_dict:
- action_name = list(action_dict.keys())[0]
- tasks_info.write(f' {action_idx}. [blue]{action_name}[/]')
-
- # Show results or errors from this step
- if item.result:
- for result in item.result:
- if result.error:
- error_text = result.error
- tasks_info.write(f' [red]Error:[/] {error_text}')
- elif result.extracted_content:
- content = result.extracted_content
- tasks_info.write(f' [green]Result:[/] {content}')
-
- # Add a space between steps for readability
- tasks_info.write('')
-
- # If agent is actively running, show a status indicator
- if hasattr(self.agent, 'running') and getattr(self.agent, 'running', False):
- tasks_info.write('[yellow]Agent is actively working[blink]...[/][/]')
- elif hasattr(self.agent, 'state') and hasattr(self.agent.state, 'paused') and self.agent.state.paused:
- tasks_info.write('[orange]Agent is paused (press Enter to resume)[/]')
- else:
- tasks_info.write('[dim]Agent not initialized[/]')
-
- # Force scroll to bottom
- tasks_panel = self.query_one('#tasks-panel')
- tasks_panel.scroll_end(animate=False)
+ self.rich_log.write(f'[cyan]{msg}[/]')
+ except Exception:
+ self.handleError(record)
+
+ # Setup handler for cdp_use loggers
+ cdp_handler = CDPLogHandler(cdp_log)
+ cdp_handler.setFormatter(logging.Formatter('%(name)s: %(message)s'))
+ cdp_handler.setLevel(logging.DEBUG)
+
+ # Configure cdp_use loggers to use our handler
+ for logger_name in ['cdp_use', 'cdp_use.client', 'cdp_use.cdp']:
+ cdp_logger = logging.getLogger(logger_name)
+ cdp_logger.setLevel(logging.DEBUG)
+ cdp_logger.handlers = [cdp_handler] # Replace existing handlers
+ cdp_logger.propagate = False
def scroll_to_input(self) -> None:
"""Scroll to the input field to ensure it's visible."""
@@ -990,11 +731,8 @@ class BrowserUseApp(App):
# Make sure intro is hidden and log is ready
self.hide_intro_panels()
- # Start continuous updates of all info panels
- self.update_info_panels()
-
- # Clear the log to start fresh
- rich_log = self.query_one('#results-log', RichLog)
+ # Clear the main output log to start fresh
+ rich_log = self.query_one('#main-output-log', RichLog)
rich_log.clear()
if self.agent is None:
@@ -1011,6 +749,9 @@ class BrowserUseApp(App):
# Update our browser_session reference to point to the agent's
if hasattr(self.agent, 'browser_session'):
self.browser_session = self.agent.browser_session
+ # Set up event bus listener and CDP logger now that we have the browser session
+ self.setup_event_bus_listener()
+ self.setup_cdp_logger()
else:
self.agent.add_new_task(task)
@@ -1051,8 +792,6 @@ class BrowserUseApp(App):
if self.agent:
self.agent.running = False # type: ignore
- # No need to call update_info_panels() here as it's already updating via timer
-
# Capture telemetry for task completion
duration = time.time() - task_start_time
self._telemetry.capture(
@@ -1138,22 +877,6 @@ class BrowserUseApp(App):
# Logo panel
yield Static(BROWSER_LOGO, id='logo-panel', markup=True)
- # Information panels (hidden by default)
- with Container(id='info-panels'):
- # Top row with browser and model panels side by side
- with Container(id='top-panels'):
- # Browser panel
- with Container(id='browser-panel'):
- yield RichLog(id='browser-info', markup=True, highlight=True, wrap=True)
-
- # Model panel
- with Container(id='model-panel'):
- yield RichLog(id='model-info', markup=True, highlight=True, wrap=True)
-
- # Tasks panel (full width, below browser and model)
- with VerticalScroll(id='tasks-panel'):
- yield RichLog(id='tasks-info', markup=True, highlight=True, wrap=True, auto_scroll=True)
-
# Links panel with URLs
with Container(id='links-panel'):
with HorizontalGroup(classes='link-row'):
@@ -1192,9 +915,28 @@ class BrowserUseApp(App):
markup=True,
)
- # Results view with scrolling (place this before input to make input sticky at bottom)
- with VerticalScroll(id='results-container'):
- yield RichLog(highlight=True, markup=True, id='results-log', wrap=True, auto_scroll=True)
+ # Three-column container (hidden by default)
+ with Container(id='three-column-container'):
+ # Column 1: Main output
+ with VerticalScroll(id='main-output-column'):
+ rich_log = RichLog(highlight=True, markup=True, id='main-output-log', wrap=True, auto_scroll=True)
+ rich_log.write('[bold blue]Agent Output[/]')
+ rich_log.write('-' * 20)
+ yield rich_log
+
+ # Column 2: Event bus events
+ with VerticalScroll(id='events-column'):
+ events_log = RichLog(highlight=True, markup=True, id='events-log', wrap=True, auto_scroll=True)
+ events_log.write('[bold yellow]Browser Events[/]')
+ events_log.write('-' * 20)
+ yield events_log
+
+ # Column 3: CDP messages
+ with VerticalScroll(id='cdp-column'):
+ cdp_log = RichLog(highlight=True, markup=True, id='cdp-log', wrap=True, auto_scroll=True)
+ cdp_log.write('[bold cyan]CDP Messages[/]')
+ cdp_log.write('-' * 20)
+ yield cdp_log
# Task input container (now at the bottom)
with Container(id='task-input-container'):
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index fe204a259..c6044267b 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -87,32 +87,35 @@ class Controller(Generic[Context]):
tabs = await browser_session.get_tabs()
# Get last 4 chars of browser session ID to identify agent's tabs
browser_session_label = str(browser_session.id)[-4:]
-
+
for i, tab in enumerate(tabs):
# Check if tab is on Google domain
- if tab.url and 'google.com' in tab.url:
+ if tab.url and tab.url.strip('/').lower() in ('https://www.google.com', 'https://google.com'):
# Found existing Google tab, navigate in it
logger.debug(f'Found existing Google tab at index {i}: {tab.url}, reusing it')
-
+
# Switch to this tab first if it's not the current one
from browser_use.browser.events import SwitchTabEvent
+
if browser_session.agent_focus and tab.id != browser_session.agent_focus.target_id:
switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=i))
await switch_event
-
+
use_new_tab = False
break
# Check if it's an agent-owned about:blank page (has "Starting agent XXXX..." title)
+ # IMPORTANT: about:blank is also used briefly for new tabs the agent is trying to open, dont take over those!
elif tab.url == 'about:blank' and tab.title and browser_session_label in tab.title:
# This is our agent's about:blank page with DVD animation
logger.debug(f'Found agent-owned about:blank tab at index {i} with title: {tab.title}, reusing it')
-
+
# Switch to this tab first
from browser_use.browser.events import SwitchTabEvent
+
if browser_session.agent_focus and tab.id != browser_session.agent_focus.target_id:
switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=i))
await switch_event
-
+
use_new_tab = False
break
except Exception as e:
@@ -217,25 +220,12 @@ class Controller(Generic[Context]):
# Dispatch click event with node
try:
- event = browser_session.event_bus.dispatch(
- ClickElementEvent(node=node, expect_download=params.expect_download, new_tab=params.new_tab)
- )
- await event
+ await browser_session.event_bus.dispatch(ClickElementEvent(node=node, new_tab=params.new_tab))
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(raise_if_none=False, raise_if_any=True)
- if result:
- download_path = result.get('download_path')
- if download_path:
- msg = f'πŸ’Ύ Downloaded file to {download_path}' + (' (new tab)' if params.new_tab else '')
- else:
- msg = f'πŸ–±οΈ Clicked element with index {params.index}'
- else:
- msg = f'πŸ–±οΈ Clicked element with index {params.index}'
-
+ msg = f'πŸ–±οΈ Clicked element with index {params.index}'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)
@@ -475,11 +465,7 @@ Explain the content of the page and that the requested information is not availa
pixels = int(params.num_pages * 800)
try:
event = browser_session.event_bus.dispatch(
- ScrollEvent(
- direction='down' if params.down else 'up',
- amount=pixels,
- node=node
- )
+ ScrollEvent(direction='down' if params.down else 'up', amount=pixels, node=node)
)
await event
except Exception as e:
@@ -505,9 +491,7 @@ Explain the content of the page and that the requested information is not availa
async def send_keys(params: SendKeysAction, browser_session: BrowserSession):
# Dispatch send keys event
try:
- event = browser_session.event_bus.dispatch(
- SendKeysEvent(keys=params.keys)
- )
+ event = browser_session.event_bus.dispatch(SendKeysEvent(keys=params.keys))
await event
except Exception as e:
logger.error(f'Failed to dispatch SendKeysEvent: {type(e).__name__}: {e}')
@@ -522,9 +506,7 @@ Explain the content of the page and that the requested information is not availa
)
async def scroll_to_text(text: str, browser_session: BrowserSession): # type: ignore
# Dispatch scroll to text event
- event = browser_session.event_bus.dispatch(
- ScrollToTextEvent(text=text)
- )
+ event = browser_session.event_bus.dispatch(ScrollToTextEvent(text=text))
await event
# Check result to see if text was found
@@ -532,9 +514,7 @@ Explain the content of the page and that the requested information is not availa
if result and result.get('found'):
msg = f'πŸ” Scrolled to text: {text}'
logger.info(msg)
- return ActionResult(
- extracted_content=msg, include_in_memory=True, long_term_memory=f'Scrolled to text: {text}'
- )
+ return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Scrolled to text: {text}')
else:
msg = f"Text '{text}' not found or not visible on page"
logger.info(msg)
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 06edc7e53..5513d99a7 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -16,7 +16,8 @@ class GoToUrlAction(BaseModel):
class ClickElementAction(BaseModel):
index: int
new_tab: bool = Field(default=False, description='set True to open any resulting navigation in a new tab, False otherwise')
- expect_download: bool = Field(default=False, description='set True if expecting a download, False otherwise')
+ # expect_download: bool = Field(default=False, description='set True if expecting a download, False otherwise') # moved to downloads_watchdog.py
+ # click_count: int = 1 # TODO
class InputTextAction(BaseModel):
diff --git a/examples/browser/stealth.py b/examples/browser/stealth.py
index e7afd8bc6..d131aba36 100644
--- a/examples/browser/stealth.py
+++ b/examples/browser/stealth.py
@@ -14,8 +14,8 @@ load_dotenv()
from imgcat import imgcat
from browser_use.browser import BrowserSession
+from browser_use.browser.events import NavigateToUrlEvent
from browser_use.browser.profile import BrowserProfile
-from browser_use.browser.types import async_patchright
from browser_use.llm import ChatOpenAI
llm = ChatOpenAI(model='gpt-4.1')
@@ -23,8 +23,23 @@ llm = ChatOpenAI(model='gpt-4.1')
terminal_width, terminal_height = shutil.get_terminal_size((80, 20))
+async def take_screenshot_cdp(browser_session: BrowserSession, filename: str):
+ """Take a screenshot using CDP."""
+ # Get current CDP session
+ cdp_session = await browser_session.get_or_create_cdp_session()
+
+ # Take screenshot using CDP
+ result = await cdp_session.cdp_client.send.Page.captureScreenshot(params={'format': 'png'}, session_id=cdp_session.session_id)
+
+ # Save the screenshot
+ import base64
+
+ screenshot_data = base64.b64decode(result['data'])
+ Path(filename).write_bytes(screenshot_data)
+
+
async def main():
- patchright = await async_patchright().start()
+ # Note: Patchright is deprecated, using standard stealth mode
print('\n\nNORMAL BROWSER:')
# Default Playwright Chromium Browser
@@ -39,14 +54,21 @@ async def main():
)
)
await normal_browser_session.start()
- await normal_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
+
+ # Navigate using events
+ nav_event = normal_browser_session.event_bus.dispatch(
+ NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
+ )
+ await nav_event
await asyncio.sleep(5)
- await (await normal_browser_session.get_current_page()).screenshot(path='normal_browser.png')
+
+ # Take screenshot using CDP
+ await take_screenshot_cdp(normal_browser_session, 'normal_browser.png')
imgcat(Path('normal_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
await normal_browser_session.kill()
- print('\n\nPATCHRIGHT STEALTH BROWSER:')
- patchright_browser_session = BrowserSession(
+ print('\n\nSTEALTH BROWSER:')
+ stealth_browser_session = BrowserSession(
# cdp_url='wss://browser.zenrows.com?apikey=your-api-key-here&proxy_region=na',
# or try anchor browser, browserless, steel.dev, browserbase, oxylabs, brightdata, etc.
browser_profile=BrowserProfile(
@@ -57,12 +79,19 @@ async def main():
deterministic_rendering=False,
)
)
- await patchright_browser_session.start()
- await patchright_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
+ await stealth_browser_session.start()
+
+ # Navigate using events
+ nav_event = stealth_browser_session.event_bus.dispatch(
+ NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
+ )
+ await nav_event
await asyncio.sleep(5)
- await (await patchright_browser_session.get_current_page()).screenshot(path='patchright_browser.png')
- imgcat(Path('patchright_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
- await patchright_browser_session.kill()
+
+ # Take screenshot using CDP
+ await take_screenshot_cdp(stealth_browser_session, 'stealth_browser.png')
+ imgcat(Path('stealth_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
+ await stealth_browser_session.kill()
# Brave Browser
if Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():
@@ -77,33 +106,47 @@ async def main():
)
)
await brave_browser_session.start()
- await brave_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
+
+ # Navigate using events
+ nav_event = brave_browser_session.event_bus.dispatch(
+ NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
+ )
+ await nav_event
await asyncio.sleep(5)
- await (await brave_browser_session.get_current_page()).screenshot(path='brave_browser.png')
+
+ # Take screenshot using CDP
+ await take_screenshot_cdp(brave_browser_session, 'brave_browser.png')
imgcat(Path('brave_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
await brave_browser_session.kill()
if Path('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser').is_file():
- print('\n\nBRAVE + PATCHRIGHT STEALTH BROWSER:')
- brave_patchright_browser_session = BrowserSession(
- playwright=patchright,
+ print('\n\nBRAVE + STEALTH BROWSER:')
+ brave_stealth_browser_session = BrowserSession(
browser_profile=BrowserProfile(
executable_path='/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
headless=False,
+ stealth=True, # Enable stealth mode
disable_security=False,
user_data_dir=None,
deterministic_rendering=False,
),
- # **patchright.devices['iPhone 13'], # emulate other devices: https://playwright.dev/python/docs/emulation
+ # Device emulation can be done via viewport/user_agent settings
+ )
+ await brave_stealth_browser_session.start()
+
+ # Navigate using events
+ nav_event = brave_stealth_browser_session.event_bus.dispatch(
+ NavigateToUrlEvent(url='https://abrahamjuliot.github.io/creepjs/', new_tab=True)
)
- await brave_patchright_browser_session.start()
- await brave_patchright_browser_session.create_new_tab('https://abrahamjuliot.github.io/creepjs/')
+ await nav_event
await asyncio.sleep(5)
- await (await brave_patchright_browser_session.get_current_page()).screenshot(path='brave_patchright_browser.png')
- imgcat(Path('brave_patchright_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
+
+ # Take screenshot using CDP
+ await take_screenshot_cdp(brave_stealth_browser_session, 'brave_stealth_browser.png')
+ imgcat(Path('brave_stealth_browser.png').read_bytes(), height=max(terminal_height - 15, 40))
input('Press [Enter] to close the browser...')
- await brave_patchright_browser_session.kill()
+ await brave_stealth_browser_session.kill()
# print()
# agent = Agent(
diff --git a/examples/browser/window_sizing.py b/examples/browser/window_sizing.py
index d5acb2249..077c0e67a 100644
--- a/examples/browser/window_sizing.py
+++ b/examples/browser/window_sizing.py
@@ -15,6 +15,27 @@ from dotenv import load_dotenv
load_dotenv()
from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser.events import NavigateToUrlEvent
+
+
+async def get_viewport_size_cdp(browser_session: BrowserSession) -> dict[str, int]:
+ """Get viewport size using CDP."""
+ cdp_session = await browser_session.get_or_create_cdp_session()
+ result = await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={'expression': '({width: window.innerWidth, height: window.innerHeight})', 'returnByValue': True},
+ session_id=cdp_session.session_id,
+ )
+ return result.get('result', {}).get('value', {})
+
+
+async def get_window_size_cdp(browser_session: BrowserSession) -> dict[str, int]:
+ """Get window outer size using CDP."""
+ cdp_session = await browser_session.get_or_create_cdp_session()
+ result = await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={'expression': '({width: window.outerWidth, height: window.outerHeight})', 'returnByValue': True},
+ session_id=cdp_session.session_id,
+ )
+ return result.get('result', {}).get('value', {})
async def example_custom_window_size():
@@ -40,17 +61,15 @@ async def example_custom_window_size():
)
await browser_session.start()
- # Get the current page
- page = await browser_session.get_current_page()
-
- # Navigate to a test page
- await page.goto('https://example.com', wait_until='load')
+ # Navigate to a test page using events
+ nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url='https://example.com'))
+ await nav_event
# Wait a bit to see the window
await asyncio.sleep(1)
- # Get the actual viewport size using JavaScript
- actual_content_size = await page.evaluate("""() => ({width: window.innerWidth, height: window.innerHeight})""")
+ # Get the actual viewport size using CDP
+ actual_content_size = await get_viewport_size_cdp(browser_session)
if profile.viewport:
expected_page_size = dict(profile.viewport)
@@ -92,25 +111,21 @@ async def example_no_viewport_option():
browser_session = BrowserSession(browser_profile=profile)
await browser_session.start()
- page = await browser_session.get_current_page()
- await page.goto('https://example.com')
+ # Navigate using events
+ nav_event = browser_session.event_bus.dispatch(NavigateToUrlEvent(url='https://example.com'))
+ await nav_event
await asyncio.sleep(1)
- # Get viewport size (inner dimensions)
- viewport = await page.evaluate('() => ({width: window.innerWidth, height: window.innerHeight})')
+ # Get viewport size (inner dimensions) using CDP
+ viewport = await get_viewport_size_cdp(browser_session)
if profile.window_size:
print(f'Configured size: width={profile.window_size["width"]}, height={profile.window_size["height"]}')
else:
print('No window size configured')
print(f'Actual viewport size: {viewport}')
- # Get the actual window size (outer dimensions)
- window_size = await page.evaluate("""
- () => ({
- width: window.outerWidth,
- height: window.outerHeight
- })
- """)
+ # Get the actual window size (outer dimensions) using CDP
+ window_size = await get_window_size_cdp(browser_session)
print(f'Actual window size (outer): {window_size}')
await asyncio.sleep(2)
diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.py
index 34a255035..37d0aa54f 100644
--- a/examples/custom-functions/action_filters.py
+++ b/examples/custom-functions/action_filters.py
@@ -29,7 +29,6 @@ load_dotenv()
from browser_use.agent.service import Agent, Controller
from browser_use.browser import BrowserSession
-from browser_use.browser.types import Page
from browser_use.llm import ChatOpenAI
# Initialize controller and registry
diff --git a/examples/custom-functions/solve_amazon_captcha.py b/examples/custom-functions/solve_amazon_captcha.py
index 27ab02e0f..cf73e1919 100644
--- a/examples/custom-functions/solve_amazon_captcha.py
+++ b/examples/custom-functions/solve_amazon_captcha.py
@@ -77,7 +77,7 @@ async def main():
agent = Agent(task=task, llm=model, controller=controller, browser_session=browser_session)
await agent.run()
- await browser_session.stop()
+ await browser_session.kill()
input('Press Enter to close...')
diff --git a/tests/ci/test_downloads_watchdog.py b/tests/ci/test_downloads_watchdog.py
index a914ef583..8ec529540 100644
--- a/tests/ci/test_downloads_watchdog.py
+++ b/tests/ci/test_downloads_watchdog.py
@@ -456,7 +456,6 @@ async def test_downloads_watchdog_actual_download_detection(comprehensive_downlo
# Debug: Log what we're about to click
print(f'Clicking download link with href: {download_node.attributes.get("href")}')
print(f'Download link has download attribute: {"download" in download_node.attributes}')
- print(f'Auto download PDFs enabled: {browser_session._auto_download_pdfs}')
# Since the link has a download attribute, it will trigger a download, not navigation
# The downloads watchdog will handle the download automatically
@@ -465,7 +464,7 @@ async def test_downloads_watchdog_actual_download_detection(comprehensive_downlo
# We don't need our own download handler - let the downloads watchdog handle it
# Click the download link with expect_download=True
- event = browser_session.event_bus.dispatch(ClickElementEvent(element_node=download_node, expect_download=True))
+ event = browser_session.event_bus.dispatch(ClickElementEvent(element_node=download_node))
await event
duration = time.time() - start_time