Skip to content

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

cleanup dead code

Nick Sweeting183d6b282947
diff --git a/browser_use/browser/__init__.py b/browser_use/browser/__init__.py
index 86283760e..eba05c4fb 100644
--- a/browser_use/browser/__init__.py
+++ b/browser_use/browser/__init__.py
@@ -4,9 +4,7 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .browser import Browser, BrowserConfig
from .context import BrowserContext, BrowserContextConfig
- from .local import LocalBrowserConnection
from .profile import BrowserProfile
- from .remote import RemoteBrowserConnection
from .session import BrowserSession
# Lazy imports mapping for heavy browser components
@@ -17,8 +15,6 @@ _LAZY_IMPORTS = {
'BrowserContextConfig': ('.context', 'BrowserContextConfig'),
'BrowserProfile': ('.profile', 'BrowserProfile'),
'BrowserSession': ('.session', 'BrowserSession'),
- 'LocalBrowserConnection': ('.local', 'LocalBrowserConnection'),
- 'RemoteBrowserConnection': ('.remote', 'RemoteBrowserConnection'),
}
@@ -49,6 +45,4 @@ __all__ = [
'BrowserContextConfig',
'BrowserSession',
'BrowserProfile',
- 'LocalBrowserConnection',
- 'RemoteBrowserConnection',
]
diff --git a/browser_use/browser/watchdog.py b/browser_use/browser/crash_watchdog.py
similarity index 99%
rename from browser_use/browser/watchdog.py
rename to browser_use/browser/crash_watchdog.py
index 2ddd8110f..59dbffdee 100644
--- a/browser_use/browser/watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -31,8 +31,8 @@ class NetworkRequestTracker:
self.resource_type = resource_type
-class BrowserWatchdog(BaseModel):
- """Monitors browser health and emits error events."""
+class CrashWatchdog(BaseModel):
+ """Monitors browser health for crashes and network timeouts."""
model_config = ConfigDict(
arbitrary_types_allowed=True,
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
new file mode 100644
index 000000000..568a91e50
--- /dev/null
+++ b/browser_use/browser/downloads_watchdog.py
@@ -0,0 +1,234 @@
+"""Downloads watchdog for monitoring and handling file downloads."""
+
+import asyncio
+from pathlib import Path
+from typing import TYPE_CHECKING
+from weakref import WeakSet
+
+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,
+)
+from browser_use.utils import logger
+
+if TYPE_CHECKING:
+ from browser_use.browser.session import BrowserSession
+
+
+class DownloadsWatchdog(BaseModel):
+ """Monitors downloads and handles file download events."""
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ validate_assignment=True,
+ extra='forbid',
+ )
+
+ 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)
+ _active_downloads: dict[str, Download] = PrivateAttr(default_factory=dict)
+
+ def __init__(self, event_bus: EventBus, browser_session: 'BrowserSession', **kwargs):
+ """Initialize watchdog with event bus and browser session."""
+ super().__init__(event_bus=event_bus, browser_session=browser_session, **kwargs)
+ self._register_handlers()
+
+ def _register_handlers(self) -> None:
+ """Register event handlers."""
+ self.event_bus.on(TabCreatedEvent, self._handle_tab_created)
+ self.event_bus.on(TabClosedEvent, self._handle_tab_closed)
+
+ async def _handle_tab_created(self, event: TabCreatedEvent) -> None:
+ """Monitor new tabs for downloads."""
+ # Tab will be added via add_page method from session
+ pass
+
+ async def _handle_tab_closed(self, event: TabClosedEvent) -> None:
+ """Stop monitoring closed tabs."""
+ # Tab will be removed automatically via WeakSet
+ pass
+
+ def add_page(self, page: Page) -> None:
+ """Add a page to monitor for downloads."""
+ self._pages.add(page)
+ self._setup_page_listeners(page)
+ logger.debug(f'[DownloadsWatchdog] Added page to monitoring: {page.url}')
+
+ def _setup_page_listeners(self, page: Page) -> None:
+ """Set up download listeners for a page."""
+ # Monitor download events
+ page.on('download', lambda download: asyncio.create_task(self._handle_download(download)))
+
+ async def _handle_download(self, download: Download) -> None:
+ """Handle a download event."""
+ 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 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]}...')
+
+ # 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(
+ url=url,
+ path=str(download_path),
+ file_name=suggested_filename,
+ file_size=file_size,
+ file_type=file_type,
+ mime_type=mime_type,
+ from_cache=False,
+ auto_download=auto_download,
+ )
+ )
+
+ logger.info(
+ f'[DownloadsWatchdog] Download completed: {suggested_filename} '
+ f'({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:
+ # Clean up tracking
+ if download_id in self._active_downloads:
+ del self._active_downloads[download_id]
+
+ 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) {
+ return {
+ isPdf: true,
+ url: embedElement.src,
+ isChromePdfViewer: true
+ };
+ }
+
+ // Check for direct PDF navigation
+ if (document.contentType === 'application/pdf') {
+ return {
+ isPdf: true,
+ url: window.location.href,
+ isDirectPdf: true
+ };
+ }
+
+ // Check for PDF in iframe
+ const iframes = document.querySelectorAll('iframe');
+ for (const iframe of iframes) {
+ try {
+ const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
+ if (iframeDoc.contentType === 'application/pdf') {
+ return {
+ isPdf: true,
+ url: iframe.src,
+ isIframePdf: true
+ };
+ }
+ } catch (e) {
+ // Cross-origin iframe, skip
+ }
+ }
+
+ 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."""
+ try:
+ # Try to get the PDF URL
+ pdf_info = await page.evaluate("""
+ () => {
+ const embedElement = 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();
+ }}
+ """)
+
+ except Exception as e:
+ logger.error(f'[DownloadsWatchdog] Error triggering PDF download: {e}')
\ No newline at end of file
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index 0a7383baa..8c57d71c9 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -84,8 +84,6 @@ class WaitEvent(BaseEvent):
# ============================================================================
-# BrowserSession -> RemoteBrowserConnection Events (Browser management)
-# ============================================================================
class StartBrowserEvent(BaseEvent):
@@ -142,8 +140,6 @@ class GetCookiesEvent(BaseEvent):
# ============================================================================
-# RemoteBrowserConnection -> BrowserSession Events (Status updates)
-# ============================================================================
class BrowserStartedEvent(BaseEvent):
@@ -274,3 +270,21 @@ class StorageStateLoadedEvent(BaseEvent):
path: str
cookies_count: int
origins_count: int
+
+
+# ============================================================================
+# File Download Events
+# ============================================================================
+
+
+class FileDownloadedEvent(BaseEvent):
+ """A file has been downloaded."""
+
+ url: str
+ path: str
+ file_name: str
+ file_size: int
+ file_type: str | None = None # e.g., 'pdf', 'zip', 'docx', etc.
+ mime_type: str | None = None # e.g., 'application/pdf'
+ from_cache: bool = False
+ auto_download: bool = False # Whether this was an automatic download (e.g., PDF auto-download)
diff --git a/browser_use/browser/local.py b/browser_use/browser/local.py
index 77d62ea97..e226e47a3 100644
--- a/browser_use/browser/local.py
+++ b/browser_use/browser/local.py
@@ -128,7 +128,7 @@ class LocalBrowserHelpers:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
- s.bind(('', 0))
+ s.bind(('127.0.0.1', 0))
s.listen(1)
port = s.getsockname()[1]
return port
diff --git a/browser_use/browser/remote.py b/browser_use/browser/remote.py
deleted file mode 100644
index 5847c6dd5..000000000
--- a/browser_use/browser/remote.py
+++ /dev/null
@@ -1,370 +0,0 @@
-"""Remote browser connection that connects via CDP."""
-
-from typing import Any
-
-from bubus import EventBus
-from playwright.async_api import Browser, BrowserContext, Page, Playwright, async_playwright
-from pydantic import BaseModel, ConfigDict, PrivateAttr
-
-from browser_use.browser.events import (
- BrowserErrorEvent,
- BrowserStartedEvent,
- BrowserStoppedEvent,
- NavigationCompleteEvent,
- PageCrashedEvent,
- StartBrowserEvent,
- StopBrowserEvent,
- TabCreatedEvent,
- TabsInfoRequestEvent,
- TabsInfoResponseEvent,
-)
-from browser_use.browser.profile import BrowserProfile
-
-
-class RemoteBrowserConnection(BaseModel):
- """Base connection for all browser connections via CDP.
-
- This class handles connections to existing browsers via Chrome DevTools Protocol (CDP).
- """
-
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- validate_assignment=True,
- extra='forbid',
- )
-
- # Configuration
- browser_profile: BrowserProfile
- event_bus: EventBus
-
- # Connection URL
- cdp_url: str
-
- # Runtime state (private)
- _playwright: Playwright | None = PrivateAttr(default=None)
- _browser: Browser | None = PrivateAttr(default=None)
- _context: BrowserContext | None = PrivateAttr(default=None)
- _current_page: Page | None = PrivateAttr(default=None)
- _pages: list[Page] = PrivateAttr(default_factory=list)
- _tab_id_map: dict[int, str] = PrivateAttr(default_factory=dict) # tab_index -> tab_id
-
- # State tracking
- _started: bool = PrivateAttr(default=False)
-
- def __init__(self, **data):
- """Initialize and register event handlers."""
- super().__init__(**data)
- self._register_handlers()
-
- def _register_handlers(self) -> None:
- """Register event handlers for browser control events."""
- self.event_bus.on(StartBrowserEvent, self._handle_start)
- self.event_bus.on(StopBrowserEvent, self._handle_stop)
- self.event_bus.on(TabsInfoRequestEvent, self._handle_tabs_info_request)
-
- async def _handle_start(self, event: StartBrowserEvent) -> None:
- """Handle browser start request."""
- if self._started:
- self.event_bus.dispatch(
- BrowserStartedEvent(
- cdp_url=self.cdp_url,
- browser_pid=None,
- )
- )
- return
-
- try:
- self._playwright = await async_playwright().start()
-
- # Connect via CDP
- await self._connect_via_cdp()
-
- # Set up the browser context
- await self._setup_browser_context()
-
- self._started = True
-
- # Notify that browser has started
- self.event_bus.dispatch(
- BrowserStartedEvent(
- cdp_url=self.cdp_url,
- browser_pid=None,
- )
- )
-
- except Exception as e:
- # Clean up on failure
- await self._cleanup_playwright()
-
- # Notify error
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='ConnectionFailed',
- message=f'Failed to connect to browser: {str(e)}',
- details={'cdp_url': self.cdp_url},
- )
- )
- raise
-
- async def _connect_via_cdp(self) -> None:
- """Connect to browser via Chrome DevTools Protocol."""
- # All channels (chrome, chromium, msedge, etc.) use chromium in playwright
- browser_type = self._playwright.chromium
-
- # CDP connection args from profile
- connection_args = {
- 'endpoint_url': self.cdp_url,
- **self.browser_profile.kwargs_for_cdp_connection(),
- }
-
- self._browser = await browser_type.connect_over_cdp(**connection_args)
-
- async def _setup_browser_context(self) -> None:
- """Set up the browser context with profile settings."""
- if not self._browser:
- raise RuntimeError('Browser not connected')
-
- # Get or create context
- contexts = self._browser.contexts
- if contexts:
- self._context = contexts[0]
- else:
- # Create new context with profile settings
- context_args = self.browser_profile.kwargs_for_new_context().model_dump(exclude_none=True)
- self._context = await self._browser.new_context(**context_args)
-
- # Track existing pages
- self._pages = list(self._context.pages)
- if self._pages:
- self._current_page = self._pages[0]
-
- async def _handle_stop(self, event: StopBrowserEvent) -> None:
- """Handle browser stop request."""
- if not self._started:
- self.event_bus.dispatch(
- BrowserStoppedEvent(
- reason='Browser was not started',
- )
- )
- return
-
- try:
- # Close context if we created it
- if self._context and not self._context.pages:
- await self._context.close()
-
- # CDP connections should be disconnected, not closed
- # The browser instance will be cleaned up when playwright stops
-
- # Clean up playwright
- await self._cleanup_playwright()
-
- # Reset state
- self._browser = None
- self._context = None
- self._current_page = None
- self._pages.clear()
- self._tab_id_map.clear()
- self._started = False
-
- # Notify that browser has stopped
- self.event_bus.dispatch(
- BrowserStoppedEvent(
- reason='Stopped by request',
- )
- )
-
- except Exception as e:
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='StopFailed',
- message=f'Failed to stop browser: {str(e)}',
- )
- )
-
- async def _cleanup_playwright(self) -> None:
- """Clean up playwright instance."""
- if self._playwright:
- await self._playwright.stop()
- self._playwright = None
-
- async def _handle_tabs_info_request(self, event: TabsInfoRequestEvent) -> None:
- """Handle request for tabs information."""
- if not self._started or not self._context:
- self.event_bus.dispatch(TabsInfoResponseEvent(tabs=[]))
- return
-
- tabs = []
- for i, page in enumerate(self._pages):
- if not page.is_closed():
- tab_id = self._tab_id_map.get(i, f'tab_{i}')
- tabs.append(
- {
- 'id': tab_id,
- 'index': i,
- 'url': page.url,
- 'title': await page.title(),
- }
- )
-
- self.event_bus.dispatch(TabsInfoResponseEvent(tabs=tabs))
-
- # Page management methods (used internally by session)
- async def navigate_page(self, tab_index: int, url: str, wait_until: str = 'load') -> None:
- """Navigate a specific tab to a URL."""
- page = await self._get_page_by_index(tab_index)
- if not page:
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='InvalidTab',
- message=f'Tab {tab_index} not found',
- )
- )
- return
-
- try:
- response = await page.goto(url, wait_until=wait_until)
- self.event_bus.dispatch(
- NavigationCompleteEvent(
- tab_index=tab_index,
- url=url,
- status=response.status if response else None,
- )
- )
- except Exception as e:
- if 'crash' in str(e).lower():
- self.event_bus.dispatch(
- PageCrashedEvent(
- tab_index=tab_index,
- error=str(e),
- )
- )
- else:
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='NavigationFailed',
- message=f'Failed to navigate: {str(e)}',
- details={'url': url, 'tab_index': tab_index},
- )
- )
-
- async def create_tab(self, url: str | None = None) -> None:
- """Create a new tab."""
- if not self._context:
- return
-
- page = await self._context.new_page()
- tab_index = len(self._pages)
- self._pages.append(page)
-
- # Generate tab ID
- tab_id = f'tab_{tab_index}_{id(page)}'
- self._tab_id_map[tab_index] = tab_id
-
- # Set up page event handlers
- page.on(
- 'crash',
- lambda: self.event_bus.dispatch(
- PageCrashedEvent(
- tab_index=tab_index,
- error='Page crashed',
- )
- ),
- )
-
- if url:
- await page.goto(url)
-
- self.event_bus.dispatch(
- TabCreatedEvent(
- tab_id=tab_id,
- tab_index=tab_index,
- url=url,
- )
- )
-
- async def _get_page_by_index(self, tab_index: int) -> Page | None:
- """Get page by tab index."""
- if 0 <= tab_index < len(self._pages):
- page = self._pages[tab_index]
- if not page.is_closed():
- return page
- return None
-
- async def click_element(self, tab_index: int, element_index: int, **kwargs) -> None:
- """Click an element on a page."""
- page = await self._get_page_by_index(tab_index)
- if not page:
- return
-
- # This would need DOM element tracking implementation
- # For now, just show the pattern
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='NotImplemented',
- message='Element clicking needs DOM tracking implementation',
- )
- )
-
- async def input_text(self, tab_index: int, element_index: int, text: str, **kwargs) -> None:
- """Input text into an element."""
- page = await self._get_page_by_index(tab_index)
- if not page:
- return
-
- # This would need DOM element tracking implementation
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='NotImplemented',
- message='Text input needs DOM tracking implementation',
- )
- )
-
- async def take_screenshot(self, tab_index: int, full_page: bool = False, clip: dict | None = None) -> str:
- """Take a screenshot of a page."""
- page = await self._get_page_by_index(tab_index)
- if not page:
- return ''
-
- screenshot_bytes = await page.screenshot(
- full_page=full_page,
- clip=clip,
- )
-
- # Convert to base64
- import base64
-
- return base64.b64encode(screenshot_bytes).decode('utf-8')
-
- async def get_browser_state(self, tab_index: int, include_dom: bool = True) -> dict[str, Any]:
- """Get the current state of a browser tab."""
- page = await self._get_page_by_index(tab_index)
- if not page:
- return {'error': 'Tab not found'}
-
- state = {
- 'url': page.url,
- 'title': await page.title(),
- 'viewport': page.viewport_size,
- }
-
- if include_dom:
- # This would need DOM extraction implementation
- state['dom'] = 'DOM extraction not implemented'
-
- return state
-
- @property
- def browser(self) -> Browser | None:
- """Get the connected browser instance."""
- return self._browser
-
- @property
- def context(self) -> BrowserContext | None:
- """Get the browser context."""
- return self._context
-
- @property
- def is_connected(self) -> bool:
- """Check if connected to a browser."""
- return self._browser is not None and self._browser.is_connected()
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 402ce9c6f..abb1bbd13 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -2,9 +2,12 @@
import asyncio
import base64
+import json
+import os
import warnings
from typing import TYPE_CHECKING, Any, Self
+import anyio
from bubus import EventBus
from playwright.async_api import Browser, BrowserContext, Page, Playwright, async_playwright
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
@@ -19,13 +22,18 @@ from browser_use.browser.events import (
CloseTabEvent,
CreateTabEvent,
InputTextEvent,
+ FileDownloadedEvent,
+ LoadStorageStateEvent,
NavigateToUrlEvent,
NavigationCompleteEvent,
+ SaveStorageStateEvent,
ScreenshotRequestEvent,
ScreenshotResponseEvent,
ScrollEvent,
StartBrowserEvent,
StopBrowserEvent,
+ StorageStateLoadedEvent,
+ StorageStateSavedEvent,
SwitchTabEvent,
TabCreatedEvent,
TabsInfoRequestEvent,
@@ -78,6 +86,14 @@ 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)
def __init__(
self,
@@ -192,6 +208,10 @@ 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)
# ========== Event Handlers ==========
@@ -243,6 +263,24 @@ 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)
+ # 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)
+ # Add initial pages to downloads watchdog
+ for page in pages:
+ self._downloads_watchdog.add_page(page)
# Notify success
self.event_bus.dispatch(
@@ -251,6 +289,9 @@ 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())
except Exception as e:
# Clean up on failure
@@ -287,6 +328,11 @@ class BrowserSession(BaseModel):
)
)
return
+
+ # Automatically save storage state before stopping
+ self.event_bus.dispatch(SaveStorageStateEvent())
+ # Give it a moment to save
+ await asyncio.sleep(0.1)
# Close context if we created it
if self._browser_context and not self._browser_context.pages:
@@ -369,13 +415,23 @@ 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=self.tabs.index(self._current_agent_page),
+ tab_index=tab_index,
url=event.url,
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}')
+
except Exception as e:
self.event_bus.dispatch(
BrowserErrorEvent(
@@ -387,13 +443,65 @@ class BrowserSession(BaseModel):
async def _handle_click(self, event: ClickElementEvent) -> None:
"""Handle click request."""
- # TODO: Implement DOM element tracking
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='NotImplemented',
- message='Click handling needs DOM element tracking implementation',
+ # TODO: This is a simplified implementation until DOM tracking is ported
+ if not self._current_agent_page:
+ self.event_bus.dispatch(
+ BrowserErrorEvent(
+ error_type='NoActivePage',
+ message='No active page for click',
+ )
+ )
+ 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(
+ BrowserErrorEvent(
+ error_type='NotImplemented',
+ 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)
+ else:
+ # TODO: Perform click without download handling
+ self.event_bus.dispatch(
+ BrowserErrorEvent(
+ error_type='NotImplemented',
+ message='Click handling needs full DOM element tracking implementation',
+ )
+ )
+
+ except Exception as e:
+ self.event_bus.dispatch(
+ BrowserErrorEvent(
+ error_type='ClickFailed',
+ message=str(e),
+ details={'index': event.index},
+ )
)
- )
async def _handle_input_text(self, event: InputTextEvent) -> None:
"""Handle text input request."""
@@ -427,6 +535,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)
@@ -491,6 +608,45 @@ class BrowserSession(BaseModel):
# Dispatch the response event
self.event_bus.dispatch(TabsInfoResponseEvent(tabs=tabs))
+ async def _handle_save_storage_state(self, event: SaveStorageStateEvent) -> None:
+ """Handle save storage state request."""
+ 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))
+ self.event_bus.dispatch(
+ StorageStateSavedEvent(
+ path=str(save_path),
+ cookies_count=len(storage.get('cookies', [])),
+ 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 "[]"
+
+ # Convert events to JSON
+ events_data = []
+ for event in recent_events:
+ # Exclude fields that might cause circular references
+ # 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 ==========
async def kill(self) -> None:
@@ -540,8 +696,7 @@ class BrowserSession(BaseModel):
@property
def downloaded_files(self) -> list[str]:
"""Get list of downloaded files."""
- # TODO: Implement download tracking
- return []
+ return self._downloaded_files.copy()
@property
def tabs(self) -> list[Page]:
@@ -651,21 +806,8 @@ class BrowserSession(BaseModel):
async def save_storage_state(self, path: str | None = None) -> None:
"""Save browser storage state."""
- if not self._browser_context:
- logger.warning('save_storage_state: No browser context available')
- return
-
- save_path = path or self.browser_profile.storage_state
- if save_path:
- logger.info(f'Saving storage state to: {save_path}')
- # Get current cookies to debug
- cookies = await self._browser_context.cookies()
- logger.info(f'Current cookies before save: {cookies}')
-
- storage = await self._browser_context.storage_state(path=str(save_path))
- logger.info(
- f'Storage state saved: cookies={len(storage.get("cookies", []))}, origins={len(storage.get("origins", []))}'
- )
+ # Use event-based approach
+ self.event_bus.dispatch(SaveStorageStateEvent(path=path))
async def get_tabs_info(self) -> list[dict[str, Any]]:
"""Get information about all open tabs."""
@@ -839,6 +981,13 @@ class BrowserSession(BaseModel):
pixels_right=0,
)
+ # 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}')
+
return BrowserStateSummary(
element_tree=content.element_tree,
selector_map=content.selector_map,
@@ -849,6 +998,8 @@ class BrowserSession(BaseModel):
page_info=page_info,
pixels_above=page_info.pixels_above,
pixels_below=page_info.pixels_below,
+ is_pdf_viewer=is_pdf_viewer,
+ recent_events=self._generate_recent_events_summary(),
)
async def _get_minimal_state_summary(self) -> Any:
@@ -881,6 +1032,13 @@ class BrowserSession(BaseModel):
parent=None,
)
+ # 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
+
return BrowserStateSummary(
element_tree=minimal_element_tree,
selector_map={},
@@ -889,6 +1047,8 @@ class BrowserSession(BaseModel):
tabs=tabs_info,
pixels_above=0,
pixels_below=0,
+ is_pdf_viewer=is_pdf_viewer,
+ recent_events=self._generate_recent_events_summary(),
)
async def get_selector_map(self) -> dict:
@@ -1001,6 +1161,315 @@ 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", []))
+ )
+ )
+
+ 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
+ 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:
+ storage = json.load(f)
+
+ self.event_bus.dispatch(
+ StorageStateLoadedEvent(
+ path=str(load_path),
+ 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}')
+
+ # ========== 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.
+ Returns True if PDF is detected, False otherwise.
+ """
+ try:
+ is_pdf_viewer = await page.evaluate("""
+ () => {
+ // Check for Chrome's built-in PDF viewer (updated selector)
+ const pdfEmbed = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||
+ document.querySelector('embed[type="application/pdf"]');
+ const isPdfViewer = !!pdfEmbed;
+
+ // Also check if the URL ends with .pdf or has PDF content-type
+ const url = window.location.href;
+ const isPdfUrl = url.toLowerCase().includes('.pdf') ||
+ document.contentType === 'application/pdf';
+
+ return isPdfViewer || isPdfUrl;
+ }
+ """)
+ return is_pdf_viewer
+ except Exception as e:
+ logger.debug(f'Error checking PDF viewer: {type(e).__name__}: {e}')
+ return False
+
+ async def _auto_download_pdf_if_needed(self, page: Page) -> str | None:
+ """
+ Check if the current page is a PDF viewer and automatically download the PDF if so.
+ Returns the download path if a PDF was downloaded, None otherwise.
+ """
+ if not self.browser_profile.downloads_path or not self._auto_download_pdfs:
+ return None
+
+ try:
+ # Check if we're in a PDF viewer
+ is_pdf_viewer = await self._is_pdf_viewer(page)
+ logger.debug(f'is_pdf_viewer: {is_pdf_viewer}')
+
+ if not is_pdf_viewer:
+ return None
+
+ # Get the PDF URL
+ pdf_url = page.url
+
+ # Check if we've already downloaded this PDF
+ pdf_filename = os.path.basename(pdf_url.split('?')[0]) # Remove query params
+ if not pdf_filename or not pdf_filename.endswith('.pdf'):
+ # Generate filename from URL
+ from urllib.parse import urlparse
+
+ 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
+ expected_path = os.path.join(self.browser_profile.downloads_path, pdf_filename)
+ if any(os.path.basename(downloaded) == pdf_filename for downloaded in self._downloaded_files):
+ logger.debug(f'๐Ÿ“„ PDF already downloaded: {pdf_filename}')
+ return None
+
+ logger.info(f'๐Ÿ“„ Auto-downloading PDF from: {pdf_url}')
+
+ # Download the actual PDF file using JavaScript fetch
+ # Note: This should hit the browser cache since Chrome already downloaded the PDF to display it
+ try:
+ logger.debug(f'Downloading PDF from URL: {pdf_url}')
+
+ # 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);
+
+ // Log whether this was 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
+ unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, pdf_filename)
+ download_path = os.path.join(self.browser_profile.downloads_path, 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
+ self._track_download(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'๐Ÿ“„ Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}')
+
+ # Emit file downloaded event
+ await self._emit_file_downloaded_event(
+ url=pdf_url,
+ path=download_path,
+ 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'โš ๏ธ No data received when downloading PDF from {pdf_url}')
+ return None
+
+ except Exception as e:
+ logger.warning(f'โš ๏ธ Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')
+ return None
+
+ 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."""
+ 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
+
+ # ========== 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
+ """
+ try:
+ # 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
+ )
+
+ # 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,
+ file_size: int | None = None,
+ file_type: str | None = None,
+ mime_type: str | None = None,
+ from_cache: 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,
+ path=str(path),
+ file_name=file_name,
+ file_size=file_size or 0,
+ file_type=file_type,
+ mime_type=mime_type,
+ from_cache=from_cache,
+ 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
+ """
+ self._auto_download_pdfs = enabled
+ logger.info(f'๐Ÿ“„ PDF auto-download {"enabled" if enabled else "disabled"}')
+
+ @property
+ def auto_download_pdfs(self) -> bool:
+ """Get current PDF auto-download setting."""
+ return self._auto_download_pdfs
# Import uuid7str for ID generation
diff --git a/tests/ci/test_browser_session_cookies.py b/tests/ci/test_browser_session_storage_state.py
similarity index 87%
rename from tests/ci/test_browser_session_cookies.py
rename to tests/ci/test_browser_session_storage_state.py
index dd79dc3d5..b121a27c5 100644
--- a/tests/ci/test_browser_session_cookies.py
+++ b/tests/ci/test_browser_session_storage_state.py
@@ -1,10 +1,10 @@
"""
-Test script for BrowserSession cookie functionality.
+Test script for BrowserSession storage state functionality.
Tests cover:
-- Loading cookies from cookies_file on browser start
-- Saving cookies to cookies_file
-- Verifying cookies are applied to browser context
+- Loading storage state on browser start
+- Saving storage state (including cookies and local storage)
+- Verifying storage state is applied to browser context
"""
import json
@@ -100,8 +100,11 @@ class TestBrowserSessionCookies:
# Start the browser session
await browser_session_with_cookies.start()
- # Verify cookies were loaded
- cookies = await browser_session_with_cookies.get_cookies()
+ # Verify cookies were loaded by accessing browser context directly
+ context = browser_session_with_cookies.browser_context
+ assert context is not None, 'Browser context should be available'
+
+ cookies = await context.cookies()
assert len(cookies) >= 2, 'Expected at least 2 cookies to be loaded'
# Check specific cookies
@@ -140,12 +143,13 @@ class TestBrowserSessionCookies:
await page.goto('about:blank')
await page.context.add_cookies([{'name': 'new_cookie', 'value': 'new_value', 'domain': 'localhost', 'path': '/'}])
- # Save cookies
- await session.save_cookies(save_path)
+ # Save storage state (which includes cookies)
+ await session.save_storage_state(save_path)
# Verify saved file exists and contains cookies
assert save_path.exists()
- saved_cookies = json.loads(save_path.read_text())
+ saved_storage = json.loads(save_path.read_text())
+ saved_cookies = saved_storage.get('cookies', [])
assert len(saved_cookies) >= 3 # Original 2 + 1 new
cookie_names = {cookie['name'] for cookie in saved_cookies}
@@ -166,7 +170,9 @@ class TestBrowserSessionCookies:
# Should have no cookies from localhost (our test domain)
# Note: Browser may have cookies from default pages like Google's new tab page
- cookies = await session.get_cookies()
+ context = session.browser_context
+ assert context is not None
+ cookies = await context.cookies()
localhost_cookies = [c for c in cookies if c['domain'] in ['localhost', '.localhost']]
assert len(localhost_cookies) == 0, f'Expected no localhost cookies, but found: {localhost_cookies}'
@@ -186,7 +192,9 @@ class TestBrowserSessionCookies:
# Should have no cookies from localhost (our test domain)
# Note: Browser may have cookies from default pages like Google's new tab page
- cookies = await session.get_cookies()
+ context = session.browser_context
+ assert context is not None
+ cookies = await context.cookies()
localhost_cookies = [c for c in cookies if c['domain'] in ['localhost', '.localhost']]
assert len(localhost_cookies) == 0, f'Expected no localhost cookies, but found: {localhost_cookies}'
@@ -212,7 +220,9 @@ class TestBrowserSessionCookies:
session = BrowserSession(browser_profile=profile)
await session.start()
- cookies = await session.get_cookies()
+ 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