Skip to content

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

fixes

Nick Sweeting0919ab6d494e
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index 59dbffdee..3db28ca3f 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -2,7 +2,7 @@
import asyncio
import time
-from typing import Any, Dict, Set
+from typing import Any
from weakref import WeakSet
from bubus import EventBus
@@ -14,15 +14,15 @@ from browser_use.browser.events import (
BrowserStartedEvent,
BrowserStoppedEvent,
PageCrashedEvent,
- TabCreatedEvent,
TabClosedEvent,
+ TabCreatedEvent,
)
from browser_use.utils import logger
class NetworkRequestTracker:
"""Tracks ongoing network requests."""
-
+
def __init__(self, request: Request, start_time: float, url: str, method: str, resource_type: str | None = None):
self.request = request
self.start_time = start_time
@@ -49,7 +49,7 @@ class CrashWatchdog(BaseModel):
_browser_context: BrowserContext | None = PrivateAttr(default=None)
_browser_pid: int | None = PrivateAttr(default=None)
_pages: WeakSet[Page] = PrivateAttr(default_factory=WeakSet)
- _active_requests: Dict[str, NetworkRequestTracker] = PrivateAttr(default_factory=dict)
+ _active_requests: dict[str, NetworkRequestTracker] = PrivateAttr(default_factory=dict)
_monitoring_task: asyncio.Task | None = PrivateAttr(default=None)
_cdp_session: Any = PrivateAttr(default=None)
@@ -112,7 +112,7 @@ class CrashWatchdog(BaseModel):
async def _on_request(self, request: Request) -> None:
"""Track new network request."""
- request_id = f"{id(request)}"
+ request_id = f'{id(request)}'
self._active_requests[request_id] = NetworkRequestTracker(
request=request,
start_time=time.time(),
@@ -124,7 +124,7 @@ class CrashWatchdog(BaseModel):
def _on_response(self, response: Response) -> None:
"""Remove request from tracking on response."""
- request_id = f"{id(response.request)}"
+ request_id = f'{id(response.request)}'
if request_id in self._active_requests:
elapsed = time.time() - self._active_requests[request_id].start_time
logger.debug(f'[Watchdog] Request completed in {elapsed:.2f}s: {response.url[:50]}...')
@@ -132,7 +132,7 @@ class CrashWatchdog(BaseModel):
def _on_request_failed(self, request: Request) -> None:
"""Remove request from tracking on failure."""
- request_id = f"{id(request)}"
+ request_id = f'{id(request)}'
if request_id in self._active_requests:
elapsed = time.time() - self._active_requests[request_id].start_time
logger.debug(f'[Watchdog] Request failed after {elapsed:.2f}s: {request.url[:50]}...')
@@ -140,14 +140,14 @@ class CrashWatchdog(BaseModel):
def _on_request_finished(self, request: Request) -> None:
"""Remove request from tracking on finish."""
- request_id = f"{id(request)}"
+ request_id = f'{id(request)}'
if request_id in self._active_requests:
del self._active_requests[request_id]
async def _on_page_crash(self, page: Page) -> None:
"""Handle page crash."""
logger.error(f'[Watchdog] Page crashed: {page.url}')
-
+
# Find tab index
tab_index = -1
if self._browser_context:
@@ -171,7 +171,7 @@ class CrashWatchdog(BaseModel):
details={
'url': page.url,
'tab_index': tab_index,
- }
+ },
)
)
@@ -189,14 +189,14 @@ class CrashWatchdog(BaseModel):
# Get CDP session from browser
cdp_contexts = await self._browser.contexts[0].new_cdp_session(self._browser.contexts[0].pages[0])
self._cdp_session = cdp_contexts
-
+
# Enable crash detection domains
await self._cdp_session.send('Inspector.enable')
await self._cdp_session.send('Page.enable')
-
+
# Set up crash handlers
self._cdp_session.on('Inspector.targetCrashed', self._on_browser_crash)
-
+
logger.info('[Watchdog] CDP crash detection enabled')
except Exception as e:
logger.warning(f'[Watchdog] Failed to set up CDP crash detection: {e}')
@@ -251,7 +251,7 @@ class CrashWatchdog(BaseModel):
f'[Watchdog] Network request timeout after {self.network_timeout_seconds}s: '
f'{tracker.method} {tracker.url[:100]}...'
)
-
+
self.event_bus.dispatch(
BrowserErrorEvent(
error_type='NetworkTimeout',
@@ -261,10 +261,10 @@ class CrashWatchdog(BaseModel):
'method': tracker.method,
'resource_type': tracker.resource_type,
'elapsed_seconds': current_time - tracker.start_time,
- }
+ },
)
)
-
+
# Remove from tracking
del self._active_requests[request_id]
@@ -274,11 +274,7 @@ class CrashWatchdog(BaseModel):
if self._browser and not self._browser.is_connected():
logger.error('[Watchdog] Browser disconnected unexpectedly')
self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='BrowserDisconnected',
- message='Browser disconnected unexpectedly',
- details={}
- )
+ BrowserErrorEvent(error_type='BrowserDisconnected', message='Browser disconnected unexpectedly', details={})
)
await self._stop_monitoring()
return
@@ -287,6 +283,7 @@ class CrashWatchdog(BaseModel):
if hasattr(self, '_browser_pid') and self._browser_pid:
try:
import psutil
+
proc = psutil.Process(self._browser_pid)
if proc.status() in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD):
logger.error(f'[Watchdog] Browser process {self._browser_pid} has crashed')
@@ -294,7 +291,7 @@ class CrashWatchdog(BaseModel):
BrowserErrorEvent(
error_type='BrowserProcessCrashed',
message=f'Browser process {self._browser_pid} has crashed',
- details={'pid': self._browser_pid, 'status': proc.status()}
+ details={'pid': self._browser_pid, 'status': proc.status()},
)
)
await self._stop_monitoring()
@@ -305,7 +302,7 @@ class CrashWatchdog(BaseModel):
# Check each page
dead_pages = []
unresponsive_pages = []
-
+
for page in list(self._pages): # Copy to avoid modification during iteration
try:
if page.is_closed():
@@ -324,18 +321,18 @@ class CrashWatchdog(BaseModel):
# Remove dead pages
for page in dead_pages:
self._pages.discard(page)
-
+
# Report unresponsive pages
for page in unresponsive_pages:
logger.warning(f'[Watchdog] Page unresponsive: {page.url}')
-
+
# Find tab index
tab_index = -1
if self._browser_context:
pages = self._browser_context.pages
if page in pages:
tab_index = pages.index(page)
-
+
self.event_bus.dispatch(
BrowserErrorEvent(
error_type='PageUnresponsive',
@@ -343,13 +340,13 @@ class CrashWatchdog(BaseModel):
details={
'url': page.url,
'tab_index': tab_index,
- }
+ },
)
)
-
+
async def _is_page_responsive(self, page: Page, timeout: float = 5.0) -> bool:
"""Check if a page is responsive by trying to evaluate simple JavaScript.
-
+
Reused from main branch BrowserSession._is_page_responsive
"""
eval_task = None
@@ -376,21 +373,15 @@ class CrashWatchdog(BaseModel):
await eval_task
except (asyncio.CancelledError, Exception):
pass
-
+
def _is_new_tab_page(self, url: str) -> bool:
"""Check if URL is a new tab page."""
return url in ['about:blank', 'chrome://new-tab-page/', 'chrome://newtab/']
- def _on_browser_crash(self, params: Dict[str, Any]) -> None:
+ def _on_browser_crash(self, params: dict[str, Any]) -> None:
"""Handle browser crash event from CDP."""
logger.error('[Watchdog] Browser crash detected via CDP')
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='BrowserCrash',
- message='Browser process crashed',
- details=params
- )
- )
+ self.event_bus.dispatch(BrowserErrorEvent(error_type='BrowserCrash', message='Browser process crashed', details=params))
async def trigger_browser_crash(self) -> None:
"""Trigger a browser crash for testing (requires CDP session)."""
@@ -424,4 +415,4 @@ class CrashWatchdog(BaseModel):
await cdp.send('Page.crash')
await cdp.detach()
except Exception as e:
- logger.error(f'[Watchdog] Failed to trigger page crash: {e}')
\ No newline at end of file
+ logger.error(f'[Watchdog] Failed to trigger page crash: {e}')
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 568a91e50..1232fc82d 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -1,18 +1,22 @@
"""Downloads watchdog for monitoring and handling file downloads."""
import asyncio
+import json
+import os
from pathlib import Path
from typing import TYPE_CHECKING
+from urllib.parse import urlparse
from weakref import WeakSet
+import anyio
from bubus import EventBus
from playwright.async_api import Download, Page
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
from browser_use.browser.events import (
FileDownloadedEvent,
- TabCreatedEvent,
TabClosedEvent,
+ TabCreatedEvent,
)
from browser_use.utils import logger
@@ -31,7 +35,6 @@ class DownloadsWatchdog(BaseModel):
event_bus: EventBus
browser_session: 'BrowserSession' # Dependency injection instead of private attrs
- downloads_dir: Path | None = Field(default=None)
# Private state
_pages: WeakSet[Page] = PrivateAttr(default_factory=WeakSet)
@@ -70,42 +73,44 @@ class DownloadsWatchdog(BaseModel):
async def _handle_download(self, download: Download) -> None:
"""Handle a download event."""
- download_id = f"{id(download)}"
+ download_id = f'{id(download)}'
self._active_downloads[download_id] = download
-
+
try:
# Get download info
url = download.url
suggested_filename = download.suggested_filename
+
+ # Determine download directory from browser profile
+ downloads_dir = self.browser_session.browser_profile.downloads_path
+ if not downloads_dir:
+ downloads_dir = str(Path.home() / 'Downloads')
- # Determine download path
- if self.downloads_dir:
- download_path = self.downloads_dir / suggested_filename
- else:
- # Use default downloads directory
- download_path = Path.home() / "Downloads" / suggested_filename
-
- logger.info(f'[DownloadsWatchdog] Download started: {suggested_filename} from {url[:100]}...')
-
+ # Ensure unique filename
+ unique_filename = await self._get_unique_filename(downloads_dir, suggested_filename)
+ download_path = Path(downloads_dir) / unique_filename
+
+ logger.info(f'[DownloadsWatchdog] Download started: {unique_filename} from {url[:100]}...')
+
# Save the download
await download.save_as(str(download_path))
-
+
# Get file info
file_size = download_path.stat().st_size if download_path.exists() else 0
-
+
# Determine file type from extension
file_ext = download_path.suffix.lower().lstrip('.')
file_type = file_ext if file_ext else None
-
+
# Try to get MIME type from response headers if available
mime_type = None
# Note: Playwright doesn't expose response headers directly from Download object
-
+
# Check if this was a PDF auto-download
auto_download = False
if file_type == 'pdf' and hasattr(self.browser_session, '_auto_download_pdfs'):
auto_download = self.browser_session._auto_download_pdfs
-
+
# Emit download event
self.event_bus.dispatch(
FileDownloadedEvent(
@@ -119,16 +124,15 @@ class DownloadsWatchdog(BaseModel):
auto_download=auto_download,
)
)
-
+
logger.info(
- f'[DownloadsWatchdog] Download completed: {suggested_filename} '
- f'({file_size} bytes) saved to {download_path}'
+ f'[DownloadsWatchdog] Download completed: {suggested_filename} ({file_size} bytes) saved to {download_path}'
)
-
+
# Track downloaded file in browser session
if hasattr(self.browser_session, '_downloaded_files'):
self.browser_session._downloaded_files.append(str(download_path))
-
+
except Exception as e:
logger.error(f'[DownloadsWatchdog] Error handling download: {e}')
finally:
@@ -138,19 +142,20 @@ class DownloadsWatchdog(BaseModel):
async def check_for_pdf_viewer(self, page: Page) -> bool:
"""Check if the current page is Chrome's built-in PDF viewer.
-
+
Returns True if a PDF is detected and should be downloaded.
"""
try:
# Check if we're in Chrome's PDF viewer
is_pdf_viewer = await page.evaluate("""
() => {
- // Check for Chrome PDF viewer
- const embedElement = document.querySelector('embed[type="application/pdf"]');
- if (embedElement && embedElement.src) {
+ // 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"]');
+ if (pdfEmbed && pdfEmbed.src) {
return {
isPdf: true,
- url: embedElement.src,
+ url: pdfEmbed.src,
isChromePdfViewer: true
};
}
@@ -164,6 +169,17 @@ class DownloadsWatchdog(BaseModel):
};
}
+ // Also check if the URL ends with .pdf or has PDF in it
+ const url = window.location.href;
+ const isPdfUrl = url.toLowerCase().includes('.pdf');
+ if (isPdfUrl) {
+ return {
+ isPdf: true,
+ url: url,
+ isPdfUrl: true
+ };
+ }
+
// Check for PDF in iframe
const iframes = document.querySelectorAll('iframe');
for (const iframe of iframes) {
@@ -184,51 +200,154 @@ class DownloadsWatchdog(BaseModel):
return { isPdf: false };
}
""")
-
+
if is_pdf_viewer.get('isPdf', False):
logger.info(
f'[DownloadsWatchdog] PDF detected: {is_pdf_viewer.get("url", "unknown")} '
f'(type: {"Chrome viewer" if is_pdf_viewer.get("isChromePdfViewer") else "direct PDF"})'
)
return True
-
+
return False
-
+
except Exception as e:
logger.debug(f'[DownloadsWatchdog] Error checking for PDF viewer: {e}')
return False
- async def trigger_pdf_download(self, page: Page) -> None:
- """Trigger download of a PDF from Chrome's PDF viewer."""
+ async def trigger_pdf_download(self, page: Page) -> str | None:
+ """Trigger download of a PDF from Chrome's PDF viewer.
+
+ Returns the download path if successful, None otherwise.
+ """
+ if not self.browser_session.browser_profile.downloads_path:
+ logger.warning('[DownloadsWatchdog] No downloads path configured')
+ return None
+
try:
# Try to get the PDF URL
pdf_info = await page.evaluate("""
() => {
- const embedElement = document.querySelector('embed[type="application/pdf"]');
+ const embedElement = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||
+ document.querySelector('embed[type="application/pdf"]');
if (embedElement && embedElement.src) {
return { url: embedElement.src };
}
return { url: window.location.href };
}
""")
-
+
pdf_url = pdf_info.get('url', '')
if not pdf_url:
logger.warning('[DownloadsWatchdog] Could not determine PDF URL for download')
- return
-
- logger.info(f'[DownloadsWatchdog] Triggering PDF download from: {pdf_url[:100]}...')
-
- # Navigate to the PDF URL with a download-triggering approach
- # This should trigger the browser's download mechanism
- await page.evaluate(f"""
- () => {{
- const link = document.createElement('a');
- link.href = '{pdf_url}';
- link.download = ''; // Force download
- link.click();
- }}
- """)
-
+ return None
+
+ # Generate filename from URL
+ pdf_filename = os.path.basename(pdf_url.split('?')[0]) # Remove query params
+ if not pdf_filename or not pdf_filename.endswith('.pdf'):
+ parsed = urlparse(pdf_url)
+ pdf_filename = os.path.basename(parsed.path) or 'document.pdf'
+ if not pdf_filename.endswith('.pdf'):
+ pdf_filename += '.pdf'
+
+ # Check if already downloaded
+ if hasattr(self.browser_session, '_downloaded_files'):
+ if any(os.path.basename(downloaded) == pdf_filename for downloaded in self.browser_session._downloaded_files):
+ logger.debug(f'[DownloadsWatchdog] PDF already downloaded: {pdf_filename}')
+ return None
+
+ logger.info(f'[DownloadsWatchdog] Auto-downloading PDF from: {pdf_url[:100]}...')
+
+ # Download using JavaScript fetch to leverage browser cache
+ try:
+ # Properly escape the URL to prevent JavaScript injection
+ escaped_pdf_url = json.dumps(pdf_url)
+
+ download_result = await page.evaluate(f"""
+ async () => {{
+ try {{
+ // Use fetch with cache: 'force-cache' to prioritize cached version
+ const response = await fetch({escaped_pdf_url}, {{
+ cache: 'force-cache'
+ }});
+ 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);
+
+ // Check if served from cache
+ const fromCache = response.headers.has('age') ||
+ !response.headers.has('date') ||
+ performance.getEntriesByName({escaped_pdf_url}).some(entry =>
+ entry.transferSize === 0 || entry.transferSize < entry.encodedBodySize
+ );
+
+ return {{
+ data: Array.from(uint8Array),
+ fromCache: fromCache,
+ responseSize: uint8Array.length,
+ transferSize: response.headers.get('content-length') || 'unknown'
+ }};
+ }} catch (error) {{
+ throw new Error(`Fetch failed: ${{error.message}}`);
+ }}
+ }}
+ """)
+
+ if download_result and download_result.get('data') and len(download_result['data']) > 0:
+ # Ensure unique filename
+ downloads_dir = self.browser_session.browser_profile.downloads_path
+ unique_filename = await self._get_unique_filename(downloads_dir, pdf_filename)
+ download_path = os.path.join(downloads_dir, unique_filename)
+
+ # Save the PDF asynchronously
+ async with await anyio.open_file(download_path, 'wb') as f:
+ await f.write(bytes(download_result['data']))
+
+ # Track the downloaded file
+ if hasattr(self.browser_session, '_downloaded_files'):
+ self.browser_session._downloaded_files.append(download_path)
+
+ # Log cache information
+ 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}')
+
+ # Emit file downloaded event
+ self.event_bus.dispatch(
+ FileDownloadedEvent(
+ url=pdf_url,
+ path=download_path,
+ file_name=unique_filename,
+ file_size=response_size,
+ file_type='pdf',
+ mime_type='application/pdf',
+ from_cache=download_result.get('fromCache', False),
+ auto_download=True,
+ )
+ )
+
+ return download_path
+ else:
+ logger.warning(f'[DownloadsWatchdog] No data received when downloading PDF from {pdf_url}')
+ return None
+
+ except Exception as e:
+ logger.warning(f'[DownloadsWatchdog] Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')
+ return None
+
except Exception as e:
- logger.error(f'[DownloadsWatchdog] Error triggering PDF download: {e}')
\ No newline at end of file
+ logger.error(f'[DownloadsWatchdog] Error in PDF download: {type(e).__name__}: {e}')
+ return None
+
+ @staticmethod
+ async def _get_unique_filename(directory: str, filename: str) -> str:
+ """Generate a unique filename for downloads by appending (1), (2), etc., if a file already exists."""
+ base, ext = os.path.splitext(filename)
+ counter = 1
+ new_filename = filename
+ while os.path.exists(os.path.join(directory, new_filename)):
+ new_filename = f'{base} ({counter}){ext}'
+ counter += 1
+ return new_filename
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index abb1bbd13..20600b81e 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -21,8 +21,8 @@ from browser_use.browser.events import (
ClickElementEvent,
CloseTabEvent,
CreateTabEvent,
- InputTextEvent,
FileDownloadedEvent,
+ InputTextEvent,
LoadStorageStateEvent,
NavigateToUrlEvent,
NavigationCompleteEvent,
@@ -86,11 +86,11 @@ class BrowserSession(BaseModel):
# Local browser state (only used when cdp_url is None)
_subprocess: Any = PrivateAttr(default=None) # psutil.Process
_owns_browser_resources: bool = PrivateAttr(default=True)
-
+
# PDF handling
_auto_download_pdfs: bool = PrivateAttr(default=True)
_downloaded_files: list[str] = PrivateAttr(default_factory=list)
-
+
# Watchdogs
_crash_watchdog: Any = PrivateAttr(default=None)
_downloads_watchdog: Any = PrivateAttr(default=None)
@@ -208,7 +208,7 @@ class BrowserSession(BaseModel):
self.event_bus.on(BrowserStateRequestEvent, self._handle_browser_state_request)
self.event_bus.on(ScreenshotRequestEvent, self._handle_screenshot_request)
self.event_bus.on(TabsInfoRequestEvent, self._handle_tabs_info_request)
-
+
# Storage state
self.event_bus.on(SaveStorageStateEvent, self._handle_save_storage_state)
self.event_bus.on(LoadStorageStateEvent, self._handle_load_storage_state)
@@ -263,21 +263,28 @@ class BrowserSession(BaseModel):
if pages:
self._current_agent_page = pages[0]
self._current_human_page = pages[0]
-
+
# Initialize crash watchdog if not already initialized
if not hasattr(self, '_crash_watchdog'):
from browser_use.browser.crash_watchdog import CrashWatchdog
+
self._crash_watchdog = CrashWatchdog(event_bus=self.event_bus)
# Set browser context for crash watchdog
- self._crash_watchdog.set_browser_context(self._browser, self._browser_context, self._subprocess.pid if self._subprocess else None)
+ self._crash_watchdog.set_browser_context(
+ self._browser, self._browser_context, self._subprocess.pid if self._subprocess else None
+ )
# Add initial pages to crash watchdog
for page in pages:
self._crash_watchdog.add_page(page)
-
+
# Initialize downloads watchdog if not already initialized
if not hasattr(self, '_downloads_watchdog'):
from browser_use.browser.downloads_watchdog import DownloadsWatchdog
- self._downloads_watchdog = DownloadsWatchdog(event_bus=self.event_bus)
+
+ self._downloads_watchdog = DownloadsWatchdog(
+ event_bus=self.event_bus,
+ browser_session=self
+ )
# Add initial pages to downloads watchdog
for page in pages:
self._downloads_watchdog.add_page(page)
@@ -289,7 +296,7 @@ class BrowserSession(BaseModel):
browser_pid=self._subprocess.pid if self._subprocess else None,
)
)
-
+
# Automatically load storage state after browser start
self.event_bus.dispatch(LoadStorageStateEvent())
@@ -328,7 +335,7 @@ class BrowserSession(BaseModel):
)
)
return
-
+
# Automatically save storage state before stopping
self.event_bus.dispatch(SaveStorageStateEvent())
# Give it a moment to save
@@ -415,9 +422,9 @@ class BrowserSession(BaseModel):
event.url,
wait_until=event.wait_until,
)
-
+
tab_index = self.tabs.index(self._current_agent_page)
-
+
self.event_bus.dispatch(
NavigationCompleteEvent(
tab_index=tab_index,
@@ -425,13 +432,12 @@ class BrowserSession(BaseModel):
status=response.status if response else None,
)
)
-
+
# Check for PDF after navigation and auto-download if enabled
- if self._auto_download_pdfs and await self._is_pdf_viewer(self._current_agent_page):
- pdf_path = await self._auto_download_pdf_if_needed(self._current_agent_page)
- if pdf_path:
- logger.info(f'📄 PDF auto-downloaded: {pdf_path}')
-
+ if self._auto_download_pdfs and self._downloads_watchdog:
+ if await self._downloads_watchdog.check_for_pdf_viewer(self._current_agent_page):
+ await self._downloads_watchdog.trigger_pdf_download(self._current_agent_page)
+
except Exception as e:
self.event_bus.dispatch(
BrowserErrorEvent(
@@ -452,24 +458,24 @@ class BrowserSession(BaseModel):
)
)
return
-
+
try:
# For now, we'll implement basic download detection
# Full implementation will need DOM element tracking from old session
page = self._current_agent_page
-
+
# Set up download handling if downloads are enabled
if self.browser_profile.downloads_path:
# Register download listener
download_promise = None
-
+
async def handle_download(download):
nonlocal download_promise
download_promise = download
-
+
# Temporarily attach download listener
page.on('download', handle_download)
-
+
# TODO: Perform actual click when DOM tracking is implemented
# For now this is a placeholder
self.event_bus.dispatch(
@@ -478,10 +484,10 @@ class BrowserSession(BaseModel):
message='Click handling needs full DOM element tracking implementation',
)
)
-
+
# Clean up listener
page.remove_listener('download', handle_download)
-
+
# If a download was triggered, handle it
if download_promise:
await self._handle_download(download_promise)
@@ -493,7 +499,7 @@ class BrowserSession(BaseModel):
message='Click handling needs full DOM element tracking implementation',
)
)
-
+
except Exception as e:
self.event_bus.dispatch(
BrowserErrorEvent(
@@ -535,15 +541,15 @@ class BrowserSession(BaseModel):
return
page = await self._browser_context.new_page()
-
+
# Add page to crash watchdog
if hasattr(self, '_crash_watchdog') and self._crash_watchdog:
self._crash_watchdog.add_page(page)
-
+
# Add page to downloads watchdog
if hasattr(self, '_downloads_watchdog') and self._downloads_watchdog:
self._downloads_watchdog.add_page(page)
-
+
if event.url:
await page.goto(event.url)
@@ -613,7 +619,7 @@ class BrowserSession(BaseModel):
if not self._browser_context:
logger.warning('_handle_save_storage_state: No browser context available')
return
-
+
save_path = event.path or self.browser_profile.storage_state
if save_path:
storage = await self._browser_context.storage_state(path=str(save_path))
@@ -621,22 +627,21 @@ class BrowserSession(BaseModel):
StorageStateSavedEvent(
path=str(save_path),
cookies_count=len(storage.get('cookies', [])),
- origins_count=len(storage.get('origins', []))
+ origins_count=len(storage.get('origins', [])),
)
)
-
def _generate_recent_events_summary(self, max_events: int = 10) -> str:
"""Generate a JSON summary of recent browser events."""
import json
-
+
# Get recent events from the event bus history (it's a dict of UUID -> Event)
all_events = list(self.event_bus.event_history.values())
recent_events = all_events[-max_events:] if all_events else []
-
+
if not recent_events:
- return "[]"
-
+ return '[]'
+
# Convert events to JSON
events_data = []
for event in recent_events:
@@ -644,7 +649,7 @@ class BrowserSession(BaseModel):
# BrowserStateResponseEvent has 'state' which can be circular
event_dict = event.model_dump(mode='json', exclude={'state'})
events_data.append(event_dict)
-
+
return json.dumps(events_data, indent=2)
# ========== Backwards Compatibility Methods ==========
@@ -982,11 +987,11 @@ class BrowserSession(BaseModel):
)
# Check for PDF and auto-download if needed
- is_pdf_viewer = await self._is_pdf_viewer(page)
- if is_pdf_viewer and self._auto_download_pdfs:
- pdf_path = await self._auto_download_pdf_if_needed(page)
- if pdf_path:
- logger.info(f'📄 PDF auto-downloaded: {pdf_path}')
+ is_pdf_viewer = False
+ if self._downloads_watchdog:
+ is_pdf_viewer = await self._downloads_watchdog.check_for_pdf_viewer(page)
+ if is_pdf_viewer and self._auto_download_pdfs:
+ await self._downloads_watchdog.trigger_pdf_download(page)
return BrowserStateSummary(
element_tree=content.element_tree,
@@ -1034,10 +1039,11 @@ class BrowserSession(BaseModel):
# Check if current page is a PDF viewer
is_pdf_viewer = False
- try:
- is_pdf_viewer = await self._is_pdf_viewer(page)
- except Exception:
- pass
+ if self._downloads_watchdog:
+ try:
+ is_pdf_viewer = await self._downloads_watchdog.check_for_pdf_viewer(page)
+ except Exception:
+ pass
return BrowserStateSummary(
element_tree=minimal_element_tree,
@@ -1161,53 +1167,76 @@ class BrowserSession(BaseModel):
return True
return False
-
+
# ========== Storage State Handlers ==========
-
+
async def _handle_save_storage_state(self, event: SaveStorageStateEvent) -> None:
"""Handle storage state save request."""
if not self._browser_context:
logger.warning('save_storage_state: No browser context available')
return
-
+
save_path = event.path or self.browser_profile.storage_state
if save_path:
logger.info(f'Saving storage state to: {save_path}')
storage = await self._browser_context.storage_state(path=str(save_path))
-
+
# Dispatch success event
self.event_bus.dispatch(
StorageStateSavedEvent(
path=str(save_path),
- cookies_count=len(storage.get("cookies", [])),
- origins_count=len(storage.get("origins", []))
+ cookies_count=len(storage.get('cookies', [])),
+ origins_count=len(storage.get('origins', [])),
)
)
-
+
async def _handle_load_storage_state(self, event: LoadStorageStateEvent) -> None:
"""Handle storage state load request."""
- # Storage state is loaded during browser context creation
- # This handler is mainly for notification purposes
+ if not self._browser_context:
+ logger.warning('_handle_load_storage_state: No browser context available')
+ return
+
+ # Load from storage_state file if available
load_path = event.path or self.browser_profile.storage_state
if load_path and os.path.exists(str(load_path)):
- # Read the file to get counts
try:
- with open(str(load_path), 'r') as f:
+ # Read the storage state file
+ with open(str(load_path)) as f:
storage = json.load(f)
-
+
+ # Apply cookies if present
+ if 'cookies' in storage and storage['cookies']:
+ await self._browser_context.add_cookies(storage['cookies'])
+ logger.info(f'Added {len(storage["cookies"])} cookies from storage state')
+
+ # Apply origins (localStorage/sessionStorage) if present
+ if 'origins' in storage and storage['origins']:
+ for origin in storage['origins']:
+ if 'localStorage' in origin:
+ for item in origin['localStorage']:
+ await self._browser_context.add_init_script(f"""
+ window.localStorage.setItem({json.dumps(item['name'])}, {json.dumps(item['value'])});
+ """)
+ if 'sessionStorage' in origin:
+ for item in origin['sessionStorage']:
+ await self._browser_context.add_init_script(f"""
+ window.sessionStorage.setItem({json.dumps(item['name'])}, {json.dumps(item['value'])});
+ """)
+ logger.info(f'Applied localStorage/sessionStorage from {len(storage["origins"])} origins')
+
self.event_bus.dispatch(
StorageStateLoadedEvent(
path=str(load_path),
- cookies_count=len(storage.get("cookies", [])),
- origins_count=len(storage.get("origins", []))
+ cookies_count=len(storage.get('cookies', [])),
+ origins_count=len(storage.get('origins', [])),
)
)
logger.info(f'Loaded storage state from: {load_path}')
except Exception as e:
- logger.warning(f'Failed to read storage state for notification: {e}')
-
+ logger.warning(f'Failed to load storage state: {e}')
+
# ========== PDF Methods ==========
-
+
async def _is_pdf_viewer(self, page: Page) -> bool:
"""
Check if the current page is displaying a PDF in Chrome's PDF viewer.
@@ -1329,7 +1358,7 @@ class BrowserSession(BaseModel):
cache_status = 'from cache' if download_result.get('fromCache') else 'from network'
response_size = download_result.get('responseSize', 0)
logger.info(f'📄 Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}')
-
+
# Emit file downloaded event
await self._emit_file_downloaded_event(
url=pdf_url,
@@ -1353,7 +1382,7 @@ class BrowserSession(BaseModel):
except Exception as e:
logger.warning(f'⚠️ Error in PDF auto-download check: {type(e).__name__}: {e}')
return None
-
+
@staticmethod
async def _get_unique_filename(directory: str, filename: str) -> str:
"""Generate a unique filename for downloads by appending (1), (2), etc., if a file already exists."""
@@ -1364,15 +1393,15 @@ class BrowserSession(BaseModel):
new_filename = f'{base} ({counter}){ext}'
counter += 1
return new_filename
-
+
# ========== Download Tracking Methods ==========
-
+
async def _handle_download(self, download) -> str:
"""Handle a Playwright download object and emit appropriate events.
-
+
Args:
download: Playwright Download object
-
+
Returns:
Path where the file was saved
"""
@@ -1380,67 +1409,60 @@ class BrowserSession(BaseModel):
# Get download info
suggested_filename = download.suggested_filename
download_url = download.url
-
+
# Ensure unique filename
- unique_filename = await self._get_unique_filename(
- self.browser_profile.downloads_path,
- suggested_filename
- )
- download_path = os.path.join(
- self.browser_profile.downloads_path,
- unique_filename
- )
-
+ unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, suggested_filename)
+ download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)
+
# Save the download
await download.save_as(download_path)
logger.info(f'⬇️ Downloaded file to: {download_path}')
-
+
# Track the download
self._track_download(download_path)
-
+
# Emit download event
await self._emit_file_downloaded_event(
url=download_url,
path=download_path,
auto_download=False, # This is a user-initiated download
)
-
+
return download_path
-
+
except Exception as e:
logger.error(f'Failed to handle download: {e}')
raise
-
+
def _track_download(self, download_path: str) -> None:
"""Track a downloaded file internally."""
self._downloaded_files.append(download_path)
logger.debug(f'📁 Added download to session tracking: {download_path} (total: {len(self._downloaded_files)} files)')
-
+
async def _emit_file_downloaded_event(
- self,
- url: str,
- path: str,
+ self,
+ url: str,
+ path: str,
file_size: int | None = None,
file_type: str | None = None,
mime_type: str | None = None,
from_cache: bool = False,
- auto_download: bool = False
+ auto_download: bool = False,
) -> None:
"""Emit a FileDownloadedEvent with file information."""
- import os
from pathlib import Path
-
+
file_path = Path(path)
file_name = file_path.name
-
+
# Try to determine file type from extension if not provided
if not file_type and file_path.suffix:
file_type = file_path.suffix.lstrip('.')
-
+
# Get file size if not provided
if file_size is None and file_path.exists():
file_size = file_path.stat().st_size
-
+
self.event_bus.dispatch(
FileDownloadedEvent(
url=url,
@@ -1453,13 +1475,13 @@ class BrowserSession(BaseModel):
auto_download=auto_download,
)
)
-
+
# ========== PDF API Methods ==========
-
+
def set_auto_download_pdfs(self, enabled: bool) -> None:
"""
Enable or disable automatic PDF downloading when PDFs are encountered.
-
+
Args:
enabled: Whether to automatically download PDFs
"""
diff --git a/tests/ci/test_browser_session_storage_state.py b/tests/ci/test_browser_session_storage_state.py
index b121a27c5..0a27b181a 100644
--- a/tests/ci/test_browser_session_storage_state.py
+++ b/tests/ci/test_browser_session_storage_state.py
@@ -22,36 +22,39 @@ from browser_use.browser.session import BrowserSession
logger = logging.getLogger('browser_session_cookie_tests')
-class TestBrowserSessionCookies:
- """Tests for BrowserSession cookie loading and saving functionality."""
+class TestBrowserSessionStorageState:
+ """Tests for BrowserSession storage state loading and saving functionality."""
@pytest.fixture
- async def temp_cookies_file(self):
- """Create a temporary cookies file with test cookies."""
+ async def temp_storage_state_file(self):
+ """Create a temporary storage state file with test cookies and local storage."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
- test_cookies = [
- {
- 'name': 'test_cookie',
- 'value': 'test_value',
- 'domain': 'localhost',
- 'path': '/',
- 'expires': -1,
- 'httpOnly': False,
- 'secure': False,
- 'sameSite': 'Lax',
- },
- {
- 'name': 'session_cookie',
- 'value': 'session_12345',
- 'domain': 'localhost',
- 'path': '/',
- 'expires': -1,
- 'httpOnly': True,
- 'secure': False,
- 'sameSite': 'Lax',
- },
- ]
- json.dump(test_cookies, f)
+ storage_state = {
+ "cookies": [
+ {
+ 'name': 'test_cookie',
+ 'value': 'test_value',
+ 'domain': '127.0.0.1',
+ 'path': '/',
+ 'expires': -1,
+ 'httpOnly': False,
+ 'secure': False,
+ 'sameSite': 'Lax',
+ },
+ {
+ 'name': 'session_cookie',
+ 'value': 'session_12345',
+ 'domain': '127.0.0.1',
+ 'path': '/',
+ 'expires': -1,
+ 'httpOnly': True,
+ 'secure': False,
+ 'sameSite': 'Lax',
+ },
+ ],
+ "origins": [] # Could add localStorage/sessionStorage data here
+ }
+ json.dump(storage_state, f)
temp_path = Path(f.name)
yield temp_path
@@ -60,15 +63,15 @@ class TestBrowserSessionCookies:
temp_path.unlink(missing_ok=True)
@pytest.fixture
- async def browser_profile_with_cookies(self, temp_cookies_file):
- """Create a BrowserProfile with cookies_file set."""
- profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=temp_cookies_file)
+ async def browser_profile_with_storage_state(self, temp_storage_state_file):
+ """Create a BrowserProfile with storage_state set."""
+ profile = BrowserProfile(headless=True, user_data_dir=None, storage_state=temp_storage_state_file)
yield profile
@pytest.fixture
- async def browser_session_with_cookies(self, browser_profile_with_cookies):
- """Create a BrowserSession with cookie file configured."""
- session = BrowserSession(browser_profile=browser_profile_with_cookies)
+ async def browser_session_with_storage_state(self, browser_profile_with_storage_state):
+ """Create a BrowserSession with storage state configured."""
+ session = BrowserSession(browser_profile=browser_profile_with_storage_state)
yield session
# Cleanup
try:
@@ -95,17 +98,20 @@ class TestBrowserSessionCookies:
)
return httpserver
- async def test_cookies_loaded_on_start(self, browser_session_with_cookies, http_server):
- """Test that cookies are loaded from cookies_file when browser starts."""
+ async def test_storage_state_loaded_on_start(self, browser_session_with_storage_state, http_server):
+ """Test that storage state is loaded when browser starts."""
# Start the browser session
- await browser_session_with_cookies.start()
+ await browser_session_with_storage_state.start()
# Verify cookies were loaded by accessing browser context directly
- context = browser_session_with_cookies.browser_context
+ context = browser_session_with_storage_state.browser_context
assert context is not None, 'Browser context should be available'
+
+ import asyncio
+ await asyncio.sleep(0.1) # Give time for async operations
cookies = await context.cookies()
- assert len(cookies) >= 2, 'Expected at least 2 cookies to be loaded'
+ assert len(cookies) >= 2, f'Expected at least 2 cookies to be loaded from storage state, but got {len(cookies)}: {cookies}'
# Check specific cookies
cookie_names = {cookie['name'] for cookie in cookies}
@@ -117,25 +123,39 @@ class TestBrowserSessionCookies:
assert test_cookie['value'] == 'test_value'
assert test_cookie['domain'] == 'localhost'
- async def test_cookies_available_in_page(self, browser_session_with_cookies, http_server):
- """Test that loaded cookies are available to web pages."""
+ async def test_storage_state_cookies_available_in_page(self, browser_session_with_storage_state, http_server):
+ """Test that cookies from storage state are available to web pages."""
# Start the browser session
- await browser_session_with_cookies.start()
+ await browser_session_with_storage_state.start()
# Navigate to test page
- page = await browser_session_with_cookies.get_current_page()
- await page.goto(http_server.url_for('/cookies'))
+ page = await browser_session_with_storage_state.get_current_page()
+ test_url = http_server.url_for('/cookies')
+ await page.goto(test_url)
+
+ # Wait a bit for cookies to be available
+ import asyncio
+ await asyncio.sleep(0.1)
# Check that cookies are available to the page
page_cookies = await page.evaluate('document.cookie')
+
+ # The test_cookie should be visible in document.cookie (httpOnly=False)
+ # but session_cookie won't be visible (httpOnly=True)
assert 'test_cookie=test_value' in page_cookies
+
+ # Verify all cookies are in the context
+ all_cookies = await browser_session_with_storage_state.browser_context.cookies()
+ cookie_names = {c['name'] for c in all_cookies}
+ assert 'test_cookie' in cookie_names
+ assert 'session_cookie' in cookie_names # This one is httpOnly
- async def test_save_cookies(self, browser_profile_with_cookies, temp_cookies_file):
- """Test saving cookies to file."""
+ async def test_save_storage_state(self, browser_profile_with_storage_state, temp_storage_state_file):
+ """Test saving storage state to file."""
# Create a new temp file for saving
- save_path = temp_cookies_file.parent / 'saved_cookies.json'
+ save_path = temp_storage_state_file.parent / 'saved_storage_state.json'
- session = BrowserSession(browser_profile=browser_profile_with_cookies)
+ session = BrowserSession(browser_profile=browser_profile_with_storage_state)
await session.start()
# Navigate to a page and set a new cookie
@@ -159,10 +179,10 @@ class TestBrowserSessionCookies:
save_path.unlink(missing_ok=True)
await session.kill()
- async def test_nonexistent_cookies_file(self):
- """Test that browser starts normally when cookies_file doesn't exist."""
+ async def test_nonexistent_storage_state_file(self):
+ """Test that browser starts normally when storage_state file doesn't exist."""
# Use a non-existent file path
- profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=Path('/tmp/nonexistent_cookies.json'))
+ profile = BrowserProfile(headless=True, user_data_dir=None, storage_state=Path('/tmp/nonexistent_storage_state.json'))
session = BrowserSession(browser_profile=profile)
# Should start without errors
@@ -178,13 +198,13 @@ class TestBrowserSessionCookies:
await session.kill()
- async def test_invalid_cookies_file(self, tmp_path):
- """Test that browser handles invalid cookie file gracefully."""
+ async def test_invalid_storage_state_file(self, tmp_path):
+ """Test that browser handles invalid storage state file gracefully."""
# Create a file with invalid JSON
- invalid_file = tmp_path / 'invalid_cookies.json'
+ invalid_file = tmp_path / 'invalid_storage_state.json'
invalid_file.write_text('not valid json')
- profile = BrowserProfile(headless=True, user_data_dir=None, cookies_file=invalid_file)
+ profile = BrowserProfile(headless=True, user_data_dir=None, storage_state=invalid_file)
session = BrowserSession(browser_profile=profile)
# Should start without errors (warning logged)
@@ -199,33 +219,3 @@ class TestBrowserSessionCookies:
assert len(localhost_cookies) == 0, f'Expected no localhost cookies, but found: {localhost_cookies}'
await session.kill()
-
- async def test_relative_cookies_file_path(self, browser_profile_with_cookies):
- """Test that relative cookies_file paths work correctly."""
- # Create profile with relative path
- profile = BrowserProfile(
- headless=True,
- user_data_dir=None,
- cookies_file=Path('./test_cookies.json'), # Relative path
- downloads_path=browser_profile_with_cookies.downloads_path,
- )
-
- # Copy test cookies to expected location
- expected_path = Path('.').resolve() / 'test_cookies.json'
- expected_path.parent.mkdir(parents=True, exist_ok=True)
- expected_path.write_text(
- json.dumps([{'name': 'relative_cookie', 'value': 'relative_value', 'domain': 'localhost', 'path': '/'}])
- )
-
- session = BrowserSession(browser_profile=profile)
- await session.start()
-
- context = session.browser_context
- assert context is not None
- cookies = await context.cookies()
- cookie_names = {cookie['name'] for cookie in cookies}
- assert 'relative_cookie' in cookie_names
-
- # Cleanup
- expected_path.unlink(missing_ok=True)
- await session.kill()