Skip to content

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

tweak logging

Nick Sweeting0512c42448cb
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.py
index 37b3e4a7d..5ba8a6714 100644
--- a/browser_use/browser/aboutblank_watchdog.py
+++ b/browser_use/browser/aboutblank_watchdog.py
@@ -43,17 +43,17 @@ class AboutBlankWatchdog(BaseWatchdog):
async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:
"""Handle browser stop request - stop creating new tabs."""
- logger.info('[AboutBlankWatchdog] Browser stop requested, stopping tab creation')
+ # logger.info('[AboutBlankWatchdog] Browser stop requested, stopping tab creation')
self._stopping = True
async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:
"""Handle browser stopped event."""
- logger.info('[AboutBlankWatchdog] Browser stopped')
+ # logger.info('[AboutBlankWatchdog] Browser stopped')
self._stopping = True
async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Check tabs when a new tab is created."""
- logger.debug(f'[AboutBlankWatchdog] Tab created: {event.url}')
+ # logger.debug(f'[AboutBlankWatchdog] ➕ New tab created: {event.url}')
# If a new tab page was created, show DVD screensaver on it
if CrashWatchdog._is_new_tab_page(event.url):
@@ -63,17 +63,17 @@ class AboutBlankWatchdog(BaseWatchdog):
async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
"""Check tabs when a tab is closed and proactively create about:blank if needed."""
- logger.debug('[AboutBlankWatchdog] Tab closing, checking if we need to create about:blank tab')
+ # logger.debug('[AboutBlankWatchdog] Tab closing, checking if we need to create about:blank tab')
# Don't create new tabs if browser is shutting down
if self._stopping:
- logger.debug('[AboutBlankWatchdog] Browser is stopping, not creating new tabs')
+ # logger.debug('[AboutBlankWatchdog] Browser is stopping, not creating new tabs')
return
# Check if we're about to close the last page (event happens BEFORE tab closes)
pages = self.browser_session.pages
if len(pages) <= 1:
- logger.info('[AboutBlankWatchdog] Last tab closing, will create animation tab')
+ logger.info('[AboutBlankWatchdog] Last tab closing, creating new about:blank tab to avoid closing entire browser')
# Create the animation tab since no tabs should remain
navigate_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
await navigate_event
@@ -106,25 +106,27 @@ class AboutBlankWatchdog(BaseWatchdog):
except Exception:
pass # Skip pages that can't be checked
- logger.debug(f'[AboutBlankWatchdog] Found {len(animation_pages)} animation tabs out of {len(pages)} total tabs')
+ # logger.debug(f'[AboutBlankWatchdog] Found {len(animation_pages)} animation tabs out of {len(pages)} total tabs')
# If no animation tabs exist, create one only if there are no tabs at all
if not animation_pages:
if len(pages) == 0:
# Only create a new tab if there are no tabs at all
- logger.info('[AboutBlankWatchdog] No tabs exist, creating animation tab')
+ # logger.info('[AboutBlankWatchdog] No tabs exist, creating new about:blank DVD screensaver tab')
navigate_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
await navigate_event
# Show DVD screensaver on the new tab
await self._show_dvd_screensaver_on_about_blank_tabs()
else:
# There are other tabs - don't create new about:blank tabs during scripting
- logger.debug(
- f'[AboutBlankWatchdog] {len(pages)} tabs exist, not creating animation tab to avoid interfering with scripting'
- )
+ # logger.debug(
+ # f'[AboutBlankWatchdog] {len(pages)} tabs exist, not creating animation tab to avoid interfering with scripting'
+ # )
+ pass
# If more than one animation tab exists, just log it - don't close anything
elif len(animation_pages) > 1:
- logger.debug(f'[AboutBlankWatchdog] Found {len(animation_pages)} animation tabs, allowing them to exist')
+ # logger.debug(f'[AboutBlankWatchdog] Found {len(animation_pages)} animation tabs, allowing them to exist')
+ pass
except Exception as e:
logger.error(f'[AboutBlankWatchdog] Error ensuring about:blank tab: {e}')
@@ -137,6 +139,9 @@ class AboutBlankWatchdog(BaseWatchdog):
for page in pages:
if CrashWatchdog._is_new_tab_page(page.url):
+ # If it's a chrome:// new tab page, redirect to about:blank to avoid CSP issues
+ if page.url.startswith('chrome://'):
+ await page.goto('about:blank')
await self._show_dvd_screensaver_loading_animation(page, browser_session_id)
except Exception as e:
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index d7a6074db..df669774e 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -58,14 +58,14 @@ class CrashWatchdog(BaseWatchdog):
async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:
"""Start monitoring when browser is connected."""
- logger.info('[CrashWatchdog] Browser connected event received, beginning monitoring')
+ # logger.debug('[CrashWatchdog] Browser connected event received, beginning monitoring')
await self._start_monitoring()
- logger.info(f'[CrashWatchdog] Monitoring task started: {self._monitoring_task and not self._monitoring_task.done()}')
+ # logger.debug(f'[CrashWatchdog] Monitoring task started: {self._monitoring_task and not self._monitoring_task.done()}')
async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:
"""Stop monitoring when browser stops."""
- logger.info('[CrashWatchdog] Browser stopped, ending monitoring')
+ # logger.debug('[CrashWatchdog] Browser stopped, ending monitoring')
await self._stop_monitoring()
async def attach_to_page(self, page: Page) -> None:
@@ -95,7 +95,7 @@ class CrashWatchdog(BaseWatchdog):
method=request.method,
resource_type=request.resource_type,
)
- logger.debug(f'[CrashWatchdog] Tracking request: {request.method} {request.url[:50]}...')
+ # logger.debug(f'[CrashWatchdog] Tracking request: {request.method} {request.url[:50]}...')
def _on_response(self, response: Response) -> None:
"""Remove request from tracking on response."""
@@ -142,11 +142,11 @@ class CrashWatchdog(BaseWatchdog):
async def _start_monitoring(self) -> None:
"""Start the monitoring loop."""
if self._monitoring_task and not self._monitoring_task.done():
- logger.info('[CrashWatchdog] Monitoring already running')
+ # logger.info('[CrashWatchdog] Monitoring already running')
return
self._monitoring_task = asyncio.create_task(self._monitoring_loop())
- logger.info('[CrashWatchdog] Monitoring loop created and started')
+ # logger.debug('[CrashWatchdog] Monitoring loop created and started')
# Set up CDP session for browser crash detection
if self.browser_session._browser:
@@ -175,7 +175,7 @@ class CrashWatchdog(BaseWatchdog):
),
)
- logger.info('[CrashWatchdog] CDP crash detection enabled')
+ logger.debug('[CrashWatchdog] 💥 CDP crash detection enabled')
except Exception as e:
logger.warning(f'[CrashWatchdog] Failed to set up CDP crash detection: {e}')
@@ -187,7 +187,7 @@ class CrashWatchdog(BaseWatchdog):
await self._monitoring_task
except asyncio.CancelledError:
pass
- logger.info('[CrashWatchdog] Monitoring loop stopped')
+ logger.debug('[CrashWatchdog] Monitoring loop stopped')
# Clean up CDP session
if self._cdp_session:
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 95ed33504..2a8e81413 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -60,14 +60,14 @@ class DownloadsWatchdog(BaseWatchdog):
async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Monitor new tabs for downloads."""
- logger.info(f'[DownloadsWatchdog] TabCreatedEvent received for tab {event.tab_index}: {event.url}')
+ # logger.info(f'[DownloadsWatchdog] TabCreatedEvent received for tab {event.tab_index}: {event.url}')
# Assert downloads path is configured (should always be set by BrowserProfile default)
assert self.browser_session.browser_profile.downloads_path is not None, 'Downloads path must be configured'
page = self.browser_session.get_page_by_tab_index(event.tab_index)
if page:
- logger.info(f'[DownloadsWatchdog] Found page for tab {event.tab_index}, calling attach_to_page')
+ # logger.info(f'[DownloadsWatchdog] Found page for tab {event.tab_index}, calling attach_to_page')
await self.attach_to_page(page)
else:
logger.warning(f'[DownloadsWatchdog] No page found for tab {event.tab_index}')
@@ -100,7 +100,7 @@ class DownloadsWatchdog(BaseWatchdog):
try:
downloads_path_raw = self.browser_session.browser_profile.downloads_path
if not downloads_path_raw:
- logger.info(f'[DownloadsWatchdog] No downloads path configured, skipping page: {page.url}')
+ # logger.info(f'[DownloadsWatchdog] No downloads path configured, skipping page: {page.url}')
return # No downloads path configured
# Check if we already have a download listener on this page
@@ -109,35 +109,42 @@ class DownloadsWatchdog(BaseWatchdog):
logger.debug(f'[DownloadsWatchdog] Download listener already exists for page: {page.url}')
return
- logger.info(f'[DownloadsWatchdog] Setting up CDP download listener for page: {page.url}')
+ # logger.debug(f'[DownloadsWatchdog] Setting up CDP download listener for page: {page.url}')
- # Use raw CDP Page.downloadWillBegin events instead of Playwright's download events
- # This is required when connected via CDP as Playwright download events don't work reliably
- cdp_session = await page.context.new_cdp_session(page)
+ # Use page-level CDP session for download events but store reference in watchdog
+ if not self._download_cdp_session_setup:
+ # Set up page-level CDP session for downloads (only once per browser session)
+ cdp_session = await page.context.new_cdp_session(page)
+ await cdp_session.send('Page.enable')
- # Enable Page domain events
- await cdp_session.send('Page.enable')
+ # Set up download event listener
+ def download_handler(event):
+ logger.info(f'[DownloadsWatchdog] Download event triggered: {event}')
+ # Find the correct page for this download
+ current_page = page # Default to current page
+ asyncio.create_task(self._handle_cdp_download(event, current_page))
- # Set up CDP download listener
- cdp_session.on(
- 'Page.downloadWillBegin', lambda event: asyncio.create_task(self._handle_cdp_download(event, page, cdp_session))
- )
+ cdp_session.on('Page.downloadWillBegin', download_handler)
+ self._download_cdp_session_setup = True
+ self._download_cdp_session = cdp_session
+ logger.debug('[DownloadsWatchdog] Set up page-level CDP download listener')
# Track that we've added a listener to prevent duplicates
self._pages_with_listeners.add(page)
- logger.info(f'[DownloadsWatchdog] Successfully set up CDP download listener for page: {page.url}')
+ # logger.debug(f'[DownloadsWatchdog] Successfully set up CDP download listener for page: {page.url}')
except Exception as e:
logger.warning(f'[DownloadsWatchdog] Failed to set up CDP download listener for page {page.url}: {e}')
- async def _handle_cdp_download(self, event: dict, page: Page, cdp_session) -> None:
+ async def _handle_cdp_download(self, event: dict, page: Page, cdp_session=None) -> None:
"""Handle a CDP Page.downloadWillBegin event."""
try:
download_url = event.get('url', '')
suggested_filename = event.get('suggestedFilename', 'download')
guid = event.get('guid', '')
- logger.info(f'[DownloadsWatchdog] CDP download will begin: {suggested_filename} from {download_url[:100]}...')
+ logger.info(f'[DownloadsWatchdog] ⬇️ File download starting: {suggested_filename} from {download_url[:100]}...')
+ logger.debug(f'[DownloadsWatchdog] Full CDP event: {event}')
# Get download directory
downloads_dir = self.browser_session.browser_profile.downloads_path
@@ -146,85 +153,109 @@ class DownloadsWatchdog(BaseWatchdog):
else:
downloads_dir = str(downloads_dir)
- # Generate unique filename
- unique_filename = await self._get_unique_filename(downloads_dir, suggested_filename)
- download_path = Path(downloads_dir) / unique_filename
-
- # Use CDP Browser.downloadProgress to get the actual download data
- # We need to wait for the download to complete and then get its data
- logger.info(f'[DownloadsWatchdog] Waiting for CDP download to complete: {guid}')
-
- # Wait for download completion via CDP events
- download_complete = False
- download_data = b''
-
- def on_download_progress(progress_event):
- nonlocal download_complete, download_data
- if progress_event.get('guid') == guid:
- state = progress_event.get('state', '')
- if state == 'completed':
- download_complete = True
- logger.info(f'[DownloadsWatchdog] CDP download completed: {guid}')
-
- # Listen for download progress
- cdp_session.on('Browser.downloadProgress', on_download_progress)
-
- # Wait for download to complete (up to 30 seconds)
- for _ in range(150): # 150 * 0.2s = 30s timeout
- if download_complete:
- break
- await asyncio.sleep(0.2)
-
- if not download_complete:
- logger.error(f'[DownloadsWatchdog] CDP download timed out: {guid}')
- return
-
- # The download should now be in the downloads directory set by Browser.setDownloadBehavior
- # Check if the file exists at the expected location
+ # Since Browser.setDownloadBehavior is already configured, the browser will download the file
+ # We just need to wait for it to appear in the downloads directory
expected_path = Path(downloads_dir) / suggested_filename
- if expected_path.exists() and expected_path.stat().st_size > 0:
- download_path = expected_path
- file_size = expected_path.stat().st_size
- logger.info(f'[DownloadsWatchdog] Found completed download: {download_path} ({file_size} bytes)')
- else:
- logger.warning(f'[DownloadsWatchdog] CDP download completed but file not found: {expected_path}')
+
+ # Debug: List current directory contents
+ logger.info(f'[DownloadsWatchdog] Downloads directory: {downloads_dir}')
+ if Path(downloads_dir).exists():
+ files_before = list(Path(downloads_dir).iterdir())
+ logger.info(f'[DownloadsWatchdog] Files before download: {[f.name for f in files_before]}')
+
+ # Browser.setDownloadBehavior doesn't work reliably with CDP connections
+ # So we'll download the file manually using JavaScript fetch
+ logger.info(f'[DownloadsWatchdog] Downloading file manually via fetch: {download_url}')
+
+ try:
+ # Escape the URL for JavaScript
+ import json
+
+ escaped_url = json.dumps(download_url)
+
+ download_result = await page.evaluate(f"""
+ async () => {{
+ try {{
+ const response = await fetch({escaped_url});
+ if (!response.ok) {{
+ throw new Error(`HTTP error! status: ${{response.status}}`);
+ }}
+ const blob = await response.blob();
+ const arrayBuffer = await blob.arrayBuffer();
+ const uint8Array = new Uint8Array(arrayBuffer);
+ return {{
+ data: Array.from(uint8Array),
+ size: uint8Array.length,
+ contentType: response.headers.get('content-type') || 'application/octet-stream'
+ }};
+ }} catch (error) {{
+ throw new Error(`Fetch failed: ${{error.message}}`);
+ }}
+ }}
+ """)
+
+ if download_result and download_result.get('data'):
+ # Save the file
+ file_data = bytes(download_result['data'])
+ file_size = len(file_data)
+
+ # Ensure unique filename
+ unique_filename = await self._get_unique_filename(downloads_dir, suggested_filename)
+ final_path = Path(downloads_dir) / unique_filename
+
+ # Write the file
+ import anyio
+
+ async with await anyio.open_file(final_path, 'wb') as f:
+ await f.write(file_data)
+
+ logger.info(f'[DownloadsWatchdog] ✅ Downloaded and saved file: {final_path} ({file_size} bytes)')
+ expected_path = final_path
+ else:
+ logger.error('[DownloadsWatchdog] ❌ No data received from fetch')
+ return
+
+ except Exception as fetch_error:
+ logger.error(f'[DownloadsWatchdog] ❌ Failed to download file via fetch: {fetch_error}')
return
# Determine file type from extension
- file_ext = download_path.suffix.lower().lstrip('.')
+ file_ext = expected_path.suffix.lower().lstrip('.')
file_type = file_ext if file_ext else None
# Emit download event
self.event_bus.dispatch(
FileDownloadedEvent(
url=download_url,
- path=str(download_path),
- file_name=suggested_filename,
+ path=str(expected_path),
+ file_name=unique_filename,
file_size=file_size,
file_type=file_type,
- mime_type=None,
+ mime_type=download_result.get('contentType'),
from_cache=False,
auto_download=False,
)
)
logger.info(
- f'[DownloadsWatchdog] CDP download completed: {suggested_filename} ({file_size} bytes) saved to {download_path}'
+ f'[DownloadsWatchdog] ✅ File download completed via CDP: {suggested_filename} ({file_size} bytes) saved to {expected_path}'
)
except Exception as e:
- logger.error(f'[DownloadsWatchdog] Error handling CDP download: {e}')
+ logger.error(f'[DownloadsWatchdog] ❌ Error handling CDP download: {e}')
async def _handle_download(self, download: Download) -> None:
"""Handle a download event."""
download_id = f'{id(download)}'
self._active_downloads[download_id] = download
- logger.info(f'[DownloadsWatchdog] Handling download: {download.suggested_filename} from {download.url[:100]}...')
+ logger.info(f'[DownloadsWatchdog] ⬇️ Handling download: {download.suggested_filename} from {download.url[:100]}...')
# Debug: Check if download is already being handled elsewhere
- failure = await download.failure()
- logger.info(f'[DownloadsWatchdog] Download state - canceled: {failure}, url: {download.url}')
- logger.info(f'[DownloadsWatchdog] Active downloads count: {len(self._active_downloads)}')
+ failure = (
+ await download.failure()
+ ) # TODO: it always fails for some reason, figure out why connect_over_cdp makes accept_downloads not work
+ logger.warning(f'[DownloadsWatchdog] ❌ Download state - canceled: {failure}, url: {download.url}')
+ # logger.info(f'[DownloadsWatchdog] Active downloads count: {len(self._active_downloads)}')
try:
current_step = 'getting_download_info'
@@ -345,7 +376,7 @@ class DownloadsWatchdog(BaseWatchdog):
() => {
// Check for Chrome's built-in PDF viewer (both old and new selectors)
const pdfEmbed = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||
- document.querySelector('embed[type="application/pdf"]');
+ document.querySelector('embed[type="application/pdf"]');
if (pdfEmbed && pdfEmbed.src) {
return {
isPdf: true,
@@ -399,7 +430,7 @@ class DownloadsWatchdog(BaseWatchdog):
if is_pdf_viewer.get('isPdf', False):
logger.info(
- f'[DownloadsWatchdog] PDF detected: {is_pdf_viewer.get("url", "unknown")} '
+ f'[DownloadsWatchdog] 📄 PDF detected: {is_pdf_viewer.get("url", "unknown")} '
f'(type: {"Chrome viewer" if is_pdf_viewer.get("isChromePdfViewer") else "direct PDF"})'
)
self._pdf_viewer_cache[page_url] = True
@@ -409,11 +440,11 @@ class DownloadsWatchdog(BaseWatchdog):
return False
except TimeoutError:
- logger.debug(f'[DownloadsWatchdog] PDF check timed out for page: {page_url}')
+ logger.warning(f'[DownloadsWatchdog] ❌ PDF check timed out for page: {page_url}')
self._pdf_viewer_cache[page_url] = False
return False
except Exception as e:
- logger.debug(f'[DownloadsWatchdog] Error checking for PDF viewer: {e}')
+ logger.warning(f'[DownloadsWatchdog] ❌ Error checking for PDF viewer: {e}')
self._pdf_viewer_cache[page_url] = False
return False
@@ -423,13 +454,13 @@ class DownloadsWatchdog(BaseWatchdog):
Returns the download path if successful, None otherwise.
"""
if not self.browser_session.browser_profile.downloads_path:
- logger.warning('[DownloadsWatchdog] No downloads path configured')
+ logger.warning(f'[DownloadsWatchdog] ❌ No downloads path configured, cannot save PDF download for {page.url[:100]}')
return None
try:
# Check if page is still valid before evaluation
if page.is_closed():
- logger.debug('[DownloadsWatchdog] Page is closed, cannot trigger PDF download')
+ logger.error(f'[DownloadsWatchdog] ❌ Page is closed, cannot trigger PDF download for {page.url[:100]}')
return None
# Try to get the PDF URL with timeout
@@ -439,7 +470,7 @@ class DownloadsWatchdog(BaseWatchdog):
page.evaluate("""
() => {
const embedElement = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||
- document.querySelector('embed[type="application/pdf"]');
+ document.querySelector('embed[type="application/pdf"]');
if (embedElement && embedElement.src) {
return { url: embedElement.src };
}
@@ -451,7 +482,7 @@ class DownloadsWatchdog(BaseWatchdog):
pdf_url = pdf_info.get('url', '')
if not pdf_url:
- logger.warning('[DownloadsWatchdog] Could not determine PDF URL for download')
+ logger.warning(f'[DownloadsWatchdog] ❌ Could not determine PDF URL for download {pdf_info}')
return None
# Generate filename from URL
@@ -467,10 +498,10 @@ class DownloadsWatchdog(BaseWatchdog):
if os.path.exists(downloads_dir):
existing_files = os.listdir(downloads_dir)
if pdf_filename in existing_files:
- logger.debug(f'[DownloadsWatchdog] PDF already downloaded: {pdf_filename}')
+ logger.debug(f'[DownloadsWatchdog] ✅ PDF already downloaded: {pdf_filename}')
return None
- logger.info(f'[DownloadsWatchdog] Auto-downloading PDF from: {pdf_url[:100]}...')
+ logger.info(f'[DownloadsWatchdog] ⬇️ Downloading PDF file from: {pdf_url[:100]}...')
# Download using JavaScript fetch to leverage browser cache
try:
@@ -529,7 +560,7 @@ class DownloadsWatchdog(BaseWatchdog):
cache_status = 'from cache' if download_result.get('fromCache') else 'from network'
response_size = download_result.get('responseSize', 0)
logger.info(
- f'[DownloadsWatchdog] Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}'
+ f'[DownloadsWatchdog] ✅ Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}'
)
# Emit file downloaded event
diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.py
index 4f26df020..3f45a0d02 100644
--- a/browser_use/browser/navigation_watchdog.py
+++ b/browser_use/browser/navigation_watchdog.py
@@ -72,7 +72,7 @@ class NavigationWatchdog(BaseWatchdog):
async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Handle new tab creation - track page and possibly move agent focus."""
- logger.debug(f'[NavigationWatchdog] Tab created: {event.url}')
+ # logger.debug(f'[NavigationWatchdog] Tab created: {event.url}')
# Get the page from browser context and track it
try:
@@ -349,7 +349,7 @@ class NavigationWatchdog(BaseWatchdog):
def _track_page(self, page: Page) -> None:
"""Track a page for lifecycle events."""
- logger.debug(f'[NavigationWatchdog] Started tracking page: {page.url}')
+ # logger.debug(f'[NavigationWatchdog] Started tracking page: {page.url}')
# Set up page close handler and store it so we can remove it later
def close_handler(*args, **kwargs):
@@ -491,9 +491,9 @@ class NavigationWatchdog(BaseWatchdog):
self._dispatch_focus_changed()
try:
current_page = await self.browser_session.get_current_page()
- logger.info(f'[NavigationWatchdog] Agent focus moved to new tab {self.tab_index}: {current_page.url}')
+ logger.info(f'[NavigationWatchdog] 👀 Agent focus moved to new tab {self.tab_index}: {current_page.url}')
except ValueError:
- logger.info(f'[NavigationWatchdog] Agent focus moved to new tab {self.tab_index}')
+ logger.info(f'[NavigationWatchdog] 👀 Agent focus moved to new tab {self.tab_index}')
async def _switch_agent_focus_to_tab(self, tab_index: int) -> None:
"""Switch agent focus to a specific tab index."""
diff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.py
index a90d52ce3..b5b254aef 100644
--- a/browser_use/browser/profile.py
+++ b/browser_use/browser/profile.py
@@ -819,9 +819,9 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro
continue
if extension_paths:
- logger.debug(f'🧩 Extensions loaded ({len(extension_paths)}): [{", ".join(loaded_extension_names)}]')
+ logger.debug(f'[BrowserProfile] 🧩 Extensions loaded ({len(extension_paths)}): [{", ".join(loaded_extension_names)}]')
else:
- logger.warning('⚠️ No default extensions could be loaded')
+ logger.warning('[BrowserProfile] ⚠️ No default extensions could be loaded')
return extension_paths
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 006a258fd..99c056b82 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -108,6 +108,14 @@ class BrowserSession(BaseModel):
self._logger = logging.getLogger(f'browser_use.{self}')
return self._logger
+ def __repr__(self) -> str:
+ port_number_or_pid = (self.cdp_url or str(self.browser_pid) or 'playwright').rsplit(':', 1)[-1].split('/', 1)[0]
+ return f'BrowserSession🆂 {self.id[-4:]}:{port_number_or_pid} #{str(id(self))[-2:]} (cdp_url={self.cdp_url}, profile={self.browser_profile})'
+
+ def __str__(self) -> str:
+ port_number_or_pid = (self.cdp_url or str(self.browser_pid) or 'playwright').rsplit(':', 1)[-1].split('/', 1)[0]
+ return f'BrowserSession🆂 {self.id[-4:]}:{port_number_or_pid} #{str(id(self))[-2:]}'
+
def __init__(
self,
browser_profile: BrowserProfile | None = None,
@@ -198,30 +206,30 @@ class BrowserSession(BaseModel):
try:
if self.is_local and not self.cdp_url:
# Launch local browser using event-driven approach
- logger.info('[Session] Dispatching BrowserLaunchEvent')
- logger.info(
+ # logger.info('[Session] Dispatching BrowserLaunchEvent')
+ logger.debug(
f'[Session] EventBus ID: {id(self.event_bus)}, has {len(self.event_bus.handlers)} handlers registered'
)
# Debug: Check what handlers are registered for BrowserLaunchEvent
from browser_use.browser.events import BrowserLaunchEvent
- logger.info(
- f'[Session] BrowserLaunchEvent class ID: {id(BrowserLaunchEvent)}, module: {BrowserLaunchEvent.__module__}'
- )
+ # logger.debug(
+ # f'[Session] BrowserLaunchEvent class ID: {id(BrowserLaunchEvent)}, module: {BrowserLaunchEvent.__module__}'
+ # )
# Debug: Check all registered event types
- logger.info(f'[Session] All registered event types: {list(self.event_bus.handlers.keys())}')
+ logger.debug(f'[Session] All registered event types: {", ".join(self.event_bus.handlers.keys())}')
# Debug: Check handlers dictionary structure
for event_type, handlers_list in self.event_bus.handlers.items():
if str(event_type) == "<class 'browser_use.browser.events.BrowserLaunchEvent'>":
- logger.info(
+ logger.debug(
f'[Session] Found BrowserLaunchEvent in handlers: {event_type} (ID: {id(event_type)}) has {len(handlers_list)} handlers'
)
- logger.info(f'[Session] Handler names: {[h for h in handlers_list]}')
+ logger.debug(f'[Session] Handler names: {[h for h in handlers_list]}')
elif hasattr(event_type, '__name__') and 'BrowserLaunchEvent' in str(event_type):
- logger.info(
+ logger.debug(
f'[Session] Found BrowserLaunchEvent by name: {event_type} (ID: {id(event_type)}) has {len(handlers_list)} handlers'
)
@@ -251,16 +259,16 @@ class BrowserSession(BaseModel):
# Enable downloads via CDP Browser.setDownloadBehavior
if self.browser_profile.downloads_path:
try:
- logger.info('[Session] Attempting to set Browser.setDownloadBehavior...')
+ # logger.debug('[Session] Attempting to set Browser.setDownloadBehavior...')
# Get CDP session for the browser (not a specific page)
cdp_session = await self._browser.new_browser_cdp_session()
- logger.info(f'[Session] Got CDP session: {cdp_session}')
+ # logger.debug(f'[Session] Got CDP session: {cdp_session}')
result = await cdp_session.send(
'Browser.setDownloadBehavior',
{'behavior': 'allow', 'downloadPath': str(self.browser_profile.downloads_path)},
)
- logger.info(f'[Session] Browser.setDownloadBehavior result: {result}')
- logger.info(
+ # logger.debug(f'[Session] Browser.setDownloadBehavior result: {result}')
+ logger.debug(
f'[Session] Enabled downloads via Browser.setDownloadBehavior to: {self.browser_profile.downloads_path}'
)
except Exception as e:
@@ -1683,7 +1691,7 @@ class BrowserSession(BaseModel):
watchdog = watchdog_class(event_bus=self.event_bus, browser_session=self)
await watchdog.attach_to_session()
setattr(self, attr_name, watchdog)
- logger.info(f'[Session] Initialized and attached {watchdog_class.__name__}')
+ # logger.debug(f'[Session] Initialized and attached {watchdog_class.__name__}')
except Exception as e:
logger.warning(f'[Session] Failed to initialize {watchdog_class.__name__}: {e}')
else:
diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.py
index b9aafad90..01f195360 100644
--- a/browser_use/browser/storage_state_watchdog.py
+++ b/browser_use/browser/storage_state_watchdog.py
@@ -48,7 +48,7 @@ class StorageStateWatchdog(BaseWatchdog):
async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:
"""Start monitoring when browser starts."""
- logger.info('[StorageStateWatchdog] Browser started, initializing storage monitoring')
+ logger.info('[StorageStateWatchdog] 🍪 Initializing auth/cookies sync <-> with storage_state.json file')
# Start monitoring
await self._start_monitoring()
@@ -58,18 +58,18 @@ class StorageStateWatchdog(BaseWatchdog):
async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:
"""Stop monitoring and save state when browser stop is requested."""
- logger.info('[StorageStateWatchdog] Browser stop requested, saving final storage state')
+ logger.info('[StorageStateWatchdog] Browser stop requested, saving final storage_state.json')
# Save storage state before stopping and wait for completion
- logger.info('[StorageStateWatchdog] Dispatching SaveStorageStateEvent...')
+ # logger.info('[StorageStateWatchdog] Dispatching SaveStorageStateEvent...')
save_event = self.event_bus.dispatch(SaveStorageStateEvent())
- logger.info('[StorageStateWatchdog] Waiting for save event to complete...')
+ # logger.info('[StorageStateWatchdog] Waiting for save event to complete...')
await save_event
- logger.info('[StorageStateWatchdog] Save event completed, stopping monitoring...')
+ # logger.info('[StorageStateWatchdog] Save event completed, stopping monitoring...')
# Stop monitoring
await self._stop_monitoring()
- logger.info('[StorageStateWatchdog] Browser stop handling complete')
+ # logger.info('[StorageStateWatchdog] Browser stop handling complete')
# No cleanup needed - browser context is managed by session
async def on_SaveStorageStateEvent(self, event: SaveStorageStateEvent) -> None:
@@ -102,7 +102,7 @@ class StorageStateWatchdog(BaseWatchdog):
return
self._monitoring_task = asyncio.create_task(self._monitor_storage_changes())
- logger.info('[StorageStateWatchdog] Started storage monitoring task')
+ # logger.info('[StorageStateWatchdog] Started storage monitoring task')
# Set up page monitoring for existing pages
if self.browser_session._browser_context:
@@ -117,14 +117,14 @@ class StorageStateWatchdog(BaseWatchdog):
await self._monitoring_task
except asyncio.CancelledError:
pass
- logger.info('[StorageStateWatchdog] Stopped storage monitoring task')
+ # logger.debug('[StorageStateWatchdog] Stopped storage monitoring task')
def _setup_page_monitoring(self, page: Page) -> None:
"""Set up storage change monitoring for a page."""
# Monitor for cookie changes via response headers
page.on('response', lambda response: asyncio.create_task(self._check_for_cookie_changes(response)))
- logger.debug(f'[StorageStateWatchdog] Set up monitoring for page: {page.url}')
+ # logger.debug(f'[StorageStateWatchdog] Set up monitoring for page: {page.url}')
async def _check_for_cookie_changes(self, response) -> None:
"""Check if a response set any cookies."""
@@ -138,7 +138,7 @@ class StorageStateWatchdog(BaseWatchdog):
if self.save_on_change:
await self._save_storage_state()
except Exception as e:
- logger.debug(f'[StorageStateWatchdog] Error checking for cookie changes: {e}')
+ logger.warning(f'[StorageStateWatchdog] Error checking for cookie changes: {e}')
async def _monitor_storage_changes(self) -> None:
"""Periodically check for storage changes and auto-save."""
@@ -148,7 +148,7 @@ class StorageStateWatchdog(BaseWatchdog):
# Check if cookies have changed
if await self._have_cookies_changed():
- logger.info('[StorageStateWatchdog] Detected cookie changes during periodic check')
+ logger.info('[StorageStateWatchdog] Detected changes to sync with storage_state.json')
await self._save_storage_state()
except asyncio.CancelledError:
diff --git a/browser_use/browser/watchdog_base.py b/browser_use/browser/watchdog_base.py
index 8b251cb82..4e0562333 100644
--- a/browser_use/browser/watchdog_base.py
+++ b/browser_use/browser/watchdog_base.py
@@ -86,15 +86,15 @@ class BaseWatchdog(BaseModel):
self.event_bus.on(event_class, unique_handler)
registered_events.add(event_class)
- logger.debug(
- f'[{self.__class__.__name__}] Registered handler {method_name} for {event_name}, event_class ID: {id(event_class)}, module: {event_class.__module__}'
- )
+ # logger.debug(
+ # f'[{self.__class__.__name__}] Registered handler {method_name} for {event_name}, event_class ID: {id(event_class)}, module: {event_class.__module__}'
+ # )
# Debug: Verify handler was actually stored
- stored_handlers = self.event_bus.handlers.get(event_class, [])
- logger.debug(
- f'[{self.__class__.__name__}] After registration, {event_name} has {len(stored_handlers)} handlers in EventBus'
- )
+ # stored_handlers = self.event_bus.handlers.get(event_class, [])
+ # logger.debug(
+ # f'[{self.__class__.__name__}] After registration, {event_name} has {len(stored_handlers)} handlers in EventBus'
+ # )
# ASSERTION: If LISTENS_TO is defined, ensure all declared events have handlers
if self.LISTENS_TO: