Skip to content

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

wip cleanup flow]

Nick Sweetingebc3a3846f74
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index fe55a7969..be646b576 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -194,12 +194,12 @@ class AgentMessagePrompt:
# If we have exactly one match, mark it as current
# Otherwise, don't mark any tab as current to avoid confusion
- current_tab_id = current_tab_candidates[0] if len(current_tab_candidates) == 1 else None
+ current_tab_index = current_tab_candidates[0] if len(current_tab_candidates) == 1 else None
for tab in self.browser_state.tabs:
tabs_text += f'Tab {tab.page_id}: {tab.url} - {tab.title[:30]}\n'
- current_tab_text = f'Current tab: {current_tab_id}' if current_tab_id is not None else ''
+ current_tab_text = f'Current tab: {current_tab_index}' if current_tab_index is not None else ''
# Check if current page is a PDF viewer and add appropriate message
pdf_message = ''
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 4998ebe07..597cf8ea1 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -360,9 +360,10 @@ class Agent(Generic[Context, AgentStructuredOutput]):
if browser_session._owns_browser_resources:
self.browser_session = browser_session
else:
- self.logger.warning(
- '⚠️ Attempting to use multiple Agents with the same BrowserSession! This is not supported yet and will likely lead to strange behavior, use separate BrowserSessions for each Agent.'
- )
+ # TODO: Only warn when multiple agents are running in parallel, not sequentially
+ # self.logger.warning(
+ # '⚠️ Attempting to use multiple Agents with the same BrowserSession! This is not supported yet and will likely lead to strange behavior, use separate BrowserSessions for each Agent.'
+ # )
self.browser_session = browser_session.model_copy()
else:
if browser is not None:
@@ -1208,6 +1209,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Emit CreateAgentTaskEvent at the START of run()
self.eventbus.dispatch(CreateAgentTaskEvent.from_agent(self))
+ # Start browser session and attach watchdogs
+ assert self.browser_session is not None, "Browser session must be initialized before starting"
+ self.logger.debug('🌐 Starting browser session...')
+ await self.browser_session.start()
+
+ self.logger.debug('🔧 Browser session started with watchdogs attached')
+
# Execute initial actions if provided
if self.initial_actions:
self.logger.debug(f'⚡ Executing {len(self.initial_actions)} initial actions...')
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.py
index 6678584e6..148a89a1b 100644
--- a/browser_use/browser/aboutblank_watchdog.py
+++ b/browser_use/browser/aboutblank_watchdog.py
@@ -1,156 +1,123 @@
"""About:blank watchdog for managing about:blank tabs with DVD screensaver."""
import asyncio
-from typing import Any
+from typing import TYPE_CHECKING, Any, ClassVar
-from bubus import EventBus
-from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
+from bubus import BaseEvent
+from playwright.async_api import Page
from browser_use.browser.events import (
- BrowserStartedEvent,
BrowserStoppedEvent,
CloseTabEvent,
- CreateTabEvent,
+ NavigateToUrlEvent,
TabClosedEvent,
TabCreatedEvent,
TabsInfoRequestEvent,
- TabsInfoResponseEvent,
)
+from browser_use.browser.watchdog_base import BaseWatchdog
from browser_use.utils import logger
+if TYPE_CHECKING:
+ pass
-class AboutBlankWatchdog(BaseModel):
- """Ensures there's always exactly one about:blank tab with DVD screensaver."""
-
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- validate_assignment=True,
- extra='forbid',
- )
-
- event_bus: EventBus
- browser_session: Any # Avoid circular import
- check_interval_seconds: float = Field(default=2.0)
-
- # Only keep the monitoring task as private state
- _monitoring_task: asyncio.Task | None = PrivateAttr(default=None)
-
- def __init__(self, event_bus: EventBus, browser_session: Any, **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(BrowserStartedEvent, self._handle_browser_started)
- self.event_bus.on(BrowserStoppedEvent, self._handle_browser_stopped)
- self.event_bus.on(TabCreatedEvent, self._handle_tab_created)
- self.event_bus.on(TabClosedEvent, self._handle_tab_closed)
-
- async def _handle_browser_started(self, event: BrowserStartedEvent) -> None:
- """Start monitoring when browser starts."""
- logger.info('[AboutBlankWatchdog] Browser started, beginning monitoring')
- await self._start_monitoring()
- # Check tabs immediately
- await self._check_and_ensure_about_blank_tab()
- async def _handle_browser_stopped(self, event: BrowserStoppedEvent) -> None:
- """Stop monitoring when browser stops."""
- logger.info('[AboutBlankWatchdog] Browser stopped, ending monitoring')
- await self._stop_monitoring()
+class AboutBlankWatchdog(BaseWatchdog):
+ """Ensures there's always exactly one about:blank tab with DVD screensaver."""
- async def _handle_tab_created(self, event: TabCreatedEvent) -> None:
+ # Event contracts
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
+ BrowserStoppedEvent,
+ TabCreatedEvent,
+ TabClosedEvent,
+ ]
+ EMITS: ClassVar[list[type[BaseEvent]]] = [
+ NavigateToUrlEvent,
+ CloseTabEvent,
+ TabsInfoRequestEvent,
+ ]
+
+ async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:
+ """Handle browser stopped event."""
+ logger.info('[AboutBlankWatchdog] Browser stopped')
+
+ async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Check tabs when a new tab is created."""
logger.debug(f'[AboutBlankWatchdog] Tab created: {event.url}')
# Small delay to let tab finish loading
- await asyncio.sleep(0.5)
+ await asyncio.sleep(0.1)
await self._check_and_ensure_about_blank_tab()
- async def _handle_tab_closed(self, event: TabClosedEvent) -> None:
- """Check tabs when a tab is closed."""
- logger.debug('[AboutBlankWatchdog] Tab closed')
- # Small delay to let tab finish closing
- await asyncio.sleep(0.5)
- await self._check_and_ensure_about_blank_tab()
-
- async def _start_monitoring(self) -> None:
- """Start the monitoring task."""
- if self._monitoring_task and not self._monitoring_task.done():
- return
- self._monitoring_task = asyncio.create_task(self._monitor_tabs())
- logger.info('[AboutBlankWatchdog] Started monitoring task')
-
- async def _stop_monitoring(self) -> None:
- """Stop the monitoring task."""
- if self._monitoring_task and not self._monitoring_task.done():
- self._monitoring_task.cancel()
- try:
- await self._monitoring_task
- except asyncio.CancelledError:
- pass
- logger.info('[AboutBlankWatchdog] Stopped monitoring task')
-
- async def _monitor_tabs(self) -> None:
- """Periodically check and ensure about:blank tab."""
- while True:
- try:
- await asyncio.sleep(self.check_interval_seconds)
- await self._check_and_ensure_about_blank_tab()
- except asyncio.CancelledError:
- break
- except Exception as e:
- logger.error(f'[AboutBlankWatchdog] Error in monitoring loop: {e}')
-
- async def _get_current_tabs(self) -> list[dict[str, Any]]:
- """Get current tabs info using event system."""
- # Request tabs info
- self.event_bus.dispatch(TabsInfoRequestEvent())
-
- # Wait for response
- try:
- event_result = await self.event_bus.expect(TabsInfoResponseEvent, timeout=5.0)
- response: TabsInfoResponseEvent = event_result # type: ignore
- return response.tabs
- except TimeoutError:
- logger.warning('[AboutBlankWatchdog] Timeout waiting for tabs info')
- return []
+ 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 closed, checking if we need to create about:blank tab')
+
+ # Check if we're about to close the last page
+ pages = self.browser_session.pages
+ if len(pages) <= 1:
+ logger.info('[AboutBlankWatchdog] Last page closing, proactively creating about:blank tab')
+ navigate_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
+ await navigate_event
+ # Wait a bit for navigation to complete
+ await asyncio.sleep(0.1)
+ # Show DVD screensaver on the new tab
+ await self._show_dvd_screensaver_on_about_blank_tabs()
+ else:
+ # Normal check after tab closes
+ await asyncio.sleep(0.1)
+ await self._check_and_ensure_about_blank_tab()
+
+ async def attach_to_page(self, page: Page) -> None:
+ """AboutBlankWatchdog doesn't monitor individual pages."""
+ pass
async def _check_and_ensure_about_blank_tab(self) -> None:
- """Check current tabs and ensure exactly one about:blank tab exists."""
+ """Check current tabs and ensure exactly one about:blank tab with animation exists."""
try:
- tabs = await self._get_current_tabs()
- if not tabs:
- return
+ pages = self.browser_session.pages
- # Count about:blank tabs
- about_blank_tabs = [tab for tab in tabs if tab['url'] == 'about:blank']
- other_tabs = [tab for tab in tabs if tab['url'] != 'about:blank']
-
- logger.debug(f'[AboutBlankWatchdog] Found {len(about_blank_tabs)} about:blank tabs and {len(other_tabs)} other tabs')
+ # Only look for tabs that have our animation (check by title)
+ animation_pages = []
+ browser_session_id = str(self.browser_session.id)[-4:]
+ expected_title = f'Starting agent {browser_session_id}...'
- # If no about:blank tabs, create one
- if not about_blank_tabs:
- logger.info('[AboutBlankWatchdog] No about:blank tab found, creating one')
- event = self.event_bus.dispatch(CreateTabEvent(url='about:blank'))
+ for page in pages:
+ if page.url == 'about:blank':
+ try:
+ page_title = await page.title()
+ if page_title == expected_title:
+ animation_pages.append(page)
+ 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')
+
+ # If no animation tabs exist, create one
+ if not animation_pages:
+ logger.info('[AboutBlankWatchdog] Creating animation tab')
+ event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
await event
# Wait a bit for navigation to complete
- await asyncio.sleep(1.0)
+ await asyncio.sleep(0.1)
# Show DVD screensaver on the new tab
await self._show_dvd_screensaver_on_about_blank_tabs()
-
- # If more than one about:blank tab, close extras
- elif len(about_blank_tabs) > 1:
- logger.info(f'[AboutBlankWatchdog] Found {len(about_blank_tabs)} about:blank tabs, closing extras')
- # Keep the first one, close the rest
- for i in range(1, len(about_blank_tabs)):
- tab = about_blank_tabs[i]
- event = self.event_bus.dispatch(CloseTabEvent(tab_index=tab['index']))
- await event
- await asyncio.sleep(0.2) # Small delay between closes
-
- # Ensure the about:blank tab has the screensaver
- else:
- await self._show_dvd_screensaver_on_about_blank_tabs()
+ # If more than one animation tab exists, close the extras (only the ones with animation)
+ elif len(animation_pages) > 1:
+ logger.info(
+ f'[AboutBlankWatchdog] Found {len(animation_pages)} animation tabs, closing {len(animation_pages) - 1} extras'
+ )
+ # Keep the first animation tab, close the rest
+ for i in range(1, len(animation_pages)):
+ page = animation_pages[i]
+ # Find the tab index for this page
+ tab_index = None
+ for idx, p in enumerate(pages):
+ if p == page:
+ tab_index = idx
+ break
+ if tab_index is not None:
+ event = self.event_bus.dispatch(CloseTabEvent(tab_index=tab_index))
+ await event
+ await asyncio.sleep(0.1) # Small delay between closes
except Exception as e:
logger.error(f'[AboutBlankWatchdog] Error ensuring about:blank tab: {e}')
@@ -158,11 +125,7 @@ class AboutBlankWatchdog(BaseModel):
async def _show_dvd_screensaver_on_about_blank_tabs(self) -> None:
"""Show DVD screensaver on all about:blank tabs."""
try:
- # Get current page from browser session
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- return
-
- pages = self.browser_session._browser_context.pages
+ pages = self.browser_session.pages
browser_session_id = str(self.browser_session.id)[-4:]
for page in pages:
diff --git a/browser_use/browser/agent_focus_watchdog.py b/browser_use/browser/agent_focus_watchdog.py
deleted file mode 100644
index 462d2d813..000000000
--- a/browser_use/browser/agent_focus_watchdog.py
+++ /dev/null
@@ -1,226 +0,0 @@
-"""Agent focus watchdog for tracking which tab the agent is currently working on."""
-
-import asyncio
-from typing import Any
-
-from bubus import EventBus
-from playwright.async_api import Page
-from pydantic import BaseModel, ConfigDict, PrivateAttr
-
-from browser_use.browser.events import (
- AgentFocusChangedEvent,
- BrowserStartedEvent,
- BrowserStoppedEvent,
- CreateTabEvent,
- NavigationCompleteEvent,
- SwitchTabEvent,
- TabClosedEvent,
- TabCreatedEvent,
- TabsInfoRequestEvent,
- TabsInfoResponseEvent,
-)
-from browser_use.utils import logger
-
-
-class AgentFocusWatchdog(BaseModel):
- """Tracks which tab the agent is currently focused on."""
-
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- validate_assignment=True,
- extra='forbid',
- )
-
- event_bus: EventBus
- browser_session: Any # Avoid circular import
-
- # Private state
- _current_agent_page: Page | None = PrivateAttr(default=None)
- _current_agent_tab_index: int = PrivateAttr(default=0)
-
- def __init__(self, event_bus: EventBus, browser_session: Any, **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(BrowserStartedEvent, self._handle_browser_started)
- self.event_bus.on(BrowserStoppedEvent, self._handle_browser_stopped)
- self.event_bus.on(TabCreatedEvent, self._handle_tab_created)
- self.event_bus.on(TabClosedEvent, self._handle_tab_closed)
- self.event_bus.on(SwitchTabEvent, self._handle_switch_tab)
- self.event_bus.on(NavigationCompleteEvent, self._handle_navigation_complete)
-
- async def _handle_browser_started(self, event: BrowserStartedEvent) -> None:
- """Initialize agent focus when browser starts."""
- logger.info('[AgentFocusWatchdog] Browser started')
- await self._initialize_agent_focus()
-
- async def _handle_browser_stopped(self, event: BrowserStoppedEvent) -> None:
- """Clear agent focus when browser stops."""
- logger.info('[AgentFocusWatchdog] Browser stopped')
- self._current_agent_page = None
- self._current_agent_tab_index = 0
-
- async def _handle_tab_created(self, event: TabCreatedEvent) -> None:
- """Handle new tab creation - agent focus moves to new tab."""
- logger.debug(f'[AgentFocusWatchdog] Tab created: {event.url}')
- # When a new tab is created, agent typically focuses on it
- # Small delay to let tab finish loading
- await asyncio.sleep(0.5)
- await self._update_agent_focus_to_latest_tab()
-
- async def _handle_tab_closed(self, event: TabClosedEvent) -> None:
- """Handle tab closure."""
- logger.debug(f'[AgentFocusWatchdog] Tab closed at index {event.tab_index}')
-
- # If the closed tab was the agent's current page, find a new one
- if self._current_agent_tab_index == event.tab_index:
- await self._find_new_agent_page()
- elif event.tab_index < self._current_agent_tab_index:
- # Adjust index if a tab before current was closed
- self._current_agent_tab_index -= 1
-
- async def _handle_switch_tab(self, event: SwitchTabEvent) -> None:
- """Handle explicit tab switches by the agent."""
- logger.debug(f'[AgentFocusWatchdog] Agent switching to tab {event.tab_index}')
- await self._switch_agent_focus_to_tab(event.tab_index)
-
- async def _handle_navigation_complete(self, event: NavigationCompleteEvent) -> None:
- """Update agent focus when navigation completes."""
- # Agent focus stays on the tab that navigated
- if event.tab_index != self._current_agent_tab_index:
- await self._switch_agent_focus_to_tab(event.tab_index)
-
- @property
- def current_agent_page(self) -> Page | None:
- """Get the current page the agent is focused on."""
- return self._current_agent_page
-
- @property
- def current_agent_tab_index(self) -> int:
- """Get the current tab index the agent is focused on."""
- return self._current_agent_tab_index
-
- async def _initialize_agent_focus(self) -> None:
- """Initialize agent focus to first available page."""
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- return
-
- pages = self.browser_session._browser_context.pages
- if pages:
- self._current_agent_page = pages[0]
- self._current_agent_tab_index = 0
- self._dispatch_focus_changed()
- try:
- current_page = await self.browser_session.get_current_page()
- logger.info(f'[AgentFocusWatchdog] Initial agent focus set to tab 0: {current_page.url}')
- except ValueError:
- logger.info('[AgentFocusWatchdog] Initial agent focus set to tab 0')
-
- async def _update_agent_focus_to_latest_tab(self) -> None:
- """Update agent focus to the latest (most recently created) tab."""
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- return
-
- pages = self.browser_session._browser_context.pages
- if pages:
- # Focus on the last tab (most recently created)
- self._current_agent_page = pages[-1]
- self._current_agent_tab_index = len(pages) - 1
- self._dispatch_focus_changed()
- try:
- current_page = await self.browser_session.get_current_page()
- logger.info(
- f'[AgentFocusWatchdog] Agent focus moved to new tab {self._current_agent_tab_index}: {current_page.url}'
- )
- except ValueError:
- logger.info(f'[AgentFocusWatchdog] Agent focus moved to new tab {self._current_agent_tab_index}')
-
- async def _switch_agent_focus_to_tab(self, tab_index: int) -> None:
- """Switch agent focus to a specific tab index."""
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- return
-
- pages = self.browser_session._browser_context.pages
- if 0 <= tab_index < len(pages):
- self._current_agent_page = pages[tab_index]
- self._current_agent_tab_index = tab_index
- self._dispatch_focus_changed()
- try:
- current_page = await self.browser_session.get_current_page()
- logger.info(f'[AgentFocusWatchdog] Agent focus switched to tab {tab_index}: {current_page.url}')
- except ValueError:
- logger.info(f'[AgentFocusWatchdog] Agent focus switched to tab {tab_index}')
-
- async def _find_new_agent_page(self) -> None:
- """Find a new page for agent focus when current one is closed."""
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- self._current_agent_page = None
- self._current_agent_tab_index = 0
- return
-
- pages = self.browser_session._browser_context.pages
- if pages:
- # Try to stay at the same index, or go to the previous one
- new_index = min(self._current_agent_tab_index, len(pages) - 1)
- self._current_agent_page = pages[new_index]
- self._current_agent_tab_index = new_index
- self._dispatch_focus_changed()
- try:
- current_page = await self.browser_session.get_current_page()
- logger.info(f'[AgentFocusWatchdog] Agent focus moved to tab {new_index}: {current_page.url}')
- except ValueError:
- logger.info(f'[AgentFocusWatchdog] Agent focus moved to tab {new_index}')
- else:
- self._current_agent_page = None
- self._current_agent_tab_index = 0
-
- def _dispatch_focus_changed(self) -> None:
- """Dispatch event when agent focus changes."""
- if self._current_agent_page:
- try:
- self.event_bus.dispatch(
- AgentFocusChangedEvent(
- tab_index=self._current_agent_tab_index,
- url=self._current_agent_page.url,
- )
- )
- except Exception as e:
- logger.error(f'[AgentFocusWatchdog] Error dispatching focus change: {e}')
-
- async def get_or_create_page(self) -> Page:
- """Get current agent page or create a new one if none exists."""
- if self._current_agent_page and not self._current_agent_page.is_closed():
- return self._current_agent_page
-
- # No current page, request tabs info to find one
- self.event_bus.dispatch(TabsInfoRequestEvent())
- try:
- event_result = await self.event_bus.expect(TabsInfoResponseEvent, timeout=5.0)
- response: TabsInfoResponseEvent = event_result # type: ignore
- if response.tabs:
- # Use the first available tab
- await self._switch_agent_focus_to_tab(0)
- if self._current_agent_page:
- return self._current_agent_page
- except TimeoutError:
- pass
-
- # No tabs available, create a new one
- logger.info('[AgentFocusWatchdog] No active page, creating new tab')
- self.event_bus.dispatch(CreateTabEvent(url='about:blank'))
- await asyncio.sleep(0.5) # Wait for tab creation
-
- # Try to get the new page
- if hasattr(self.browser_session, '_browser_context') and self.browser_session._browser_context:
- pages = self.browser_session._browser_context.pages
- if pages:
- self._current_agent_page = pages[-1]
- self._current_agent_tab_index = len(pages) - 1
- self._dispatch_focus_changed()
- if self._current_agent_page:
- return self._current_agent_page
-
- raise ValueError('Failed to create or find an active page')
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.py
index d1d74540c..076c5c3a7 100644
--- a/browser_use/browser/crash_watchdog.py
+++ b/browser_use/browser/crash_watchdog.py
@@ -2,12 +2,11 @@
import asyncio
import time
-from typing import Any
-from weakref import WeakSet
+from typing import TYPE_CHECKING, Any, ClassVar
-from bubus import EventBus
-from playwright.async_api import Browser, BrowserContext, Page, Request, Response
-from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
+from bubus import BaseEvent
+from playwright.async_api import Browser, Page, Request, Response
+from pydantic import Field, PrivateAttr
from browser_use.browser.events import (
BrowserErrorEvent,
@@ -17,8 +16,12 @@ from browser_use.browser.events import (
TabClosedEvent,
TabCreatedEvent,
)
+from browser_use.browser.watchdog_base import BaseWatchdog
from browser_use.utils import logger
+if TYPE_CHECKING:
+ pass
+
class NetworkRequestTracker:
"""Tracks ongoing network requests."""
@@ -31,86 +34,70 @@ class NetworkRequestTracker:
self.resource_type = resource_type
-class CrashWatchdog(BaseModel):
+class CrashWatchdog(BaseWatchdog):
"""Monitors browser health for crashes and network timeouts."""
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- validate_assignment=True,
- extra='forbid',
- )
-
- event_bus: EventBus
+ # Event contracts
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
+ BrowserStartedEvent,
+ BrowserStoppedEvent,
+ TabCreatedEvent,
+ TabClosedEvent,
+ ]
+ EMITS: ClassVar[list[type[BaseEvent]]] = [
+ BrowserErrorEvent,
+ PageCrashedEvent,
+ ]
+
+ # Configuration
network_timeout_seconds: float = Field(default=10.0)
check_interval_seconds: float = Field(default=1.0)
# Private state
- _browser: Browser | None = PrivateAttr(default=None)
- _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)
_monitoring_task: asyncio.Task | None = PrivateAttr(default=None)
_cdp_session: Any = PrivateAttr(default=None)
_last_responsive_checks: dict[str, float] = PrivateAttr(default_factory=dict) # page_url -> timestamp
- def __init__(self, event_bus: EventBus, **kwargs):
- """Initialize watchdog with event bus."""
- super().__init__(event_bus=event_bus, **kwargs)
- self._register_handlers()
+ async def on_BrowserStartedEvent(self, event: BrowserStartedEvent) -> None:
+ """Start monitoring when browser starts."""
+ logger.info('[CrashWatchdog] Browser started event received, beginning monitoring')
- def _register_handlers(self) -> None:
- """Register event handlers."""
- self.event_bus.on(BrowserStartedEvent, self._handle_browser_started)
- self.event_bus.on(BrowserStoppedEvent, self._handle_browser_stopped)
- self.event_bus.on(TabCreatedEvent, self._handle_tab_created)
- self.event_bus.on(TabClosedEvent, self._handle_tab_closed)
+ # Get browser pid for process monitoring
+ self._browser_pid = self.browser_session.browser_pid
- async def _handle_browser_started(self, event: BrowserStartedEvent) -> None:
- """Start monitoring when browser starts."""
- logger.info('[Watchdog] Browser started, beginning monitoring')
- # Note: Browser and context will be set by session via set_browser_context
await self._start_monitoring()
+ logger.info(f'[CrashWatchdog] Monitoring task started: {self._monitoring_task and not self._monitoring_task.done()}')
- async def _handle_browser_stopped(self, event: BrowserStoppedEvent) -> None:
+ async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:
"""Stop monitoring when browser stops."""
logger.info('[Watchdog] Browser stopped, ending monitoring')
await self._stop_monitoring()
- async def _handle_tab_created(self, event: TabCreatedEvent) -> None:
+ async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Monitor new tabs."""
# Tab will be added via add_page method from session
pass
- async def _handle_tab_closed(self, event: TabClosedEvent) -> None:
+ async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
"""Stop monitoring closed tabs."""
# Tab will be removed automatically via WeakSet
pass
- def set_browser_context(self, browser: Browser, context: BrowserContext, browser_pid: int | None = None) -> None:
- """Set browser and context references."""
- self._browser = browser
- self._browser_context = context
- self._browser_pid = browser_pid
- logger.info(f'[Watchdog] Browser and context references set (pid: {browser_pid})')
-
- def add_page(self, page: Page) -> None:
- """Add a page to monitor."""
- self._pages.add(page)
- self._setup_page_listeners(page)
- logger.debug(f'[Watchdog] Added page to monitoring: {page.url}')
-
- def _setup_page_listeners(self, page: Page) -> None:
- """Set up network and crash listeners for a page."""
+ async def attach_to_page(self, page: Page) -> None:
+ """Set up crash monitoring for a specific page."""
# Network request tracking
page.on('request', lambda req: asyncio.create_task(self._on_request(req)))
page.on('response', lambda resp: self._on_response(resp))
page.on('requestfailed', lambda req: self._on_request_failed(req))
- page.on('requestfinished', lambda req: self._on_request_finished(req))
+ page.on('requestfinished', lambda req: (self._active_requests.pop(f'{id(req)}', None), None)[1])
# Page crash detection
page.on('crash', lambda _: asyncio.create_task(self._on_page_crash(page)))
+ logger.debug(f'[CrashWatchdog] Added page to monitoring: {page.url}')
+
async def _on_request(self, request: Request) -> None:
"""Track new network request."""
request_id = f'{id(request)}'
@@ -139,22 +126,11 @@ class CrashWatchdog(BaseModel):
logger.debug(f'[Watchdog] Request failed after {elapsed:.2f}s: {request.url[:50]}...')
del self._active_requests[request_id]
- def _on_request_finished(self, request: Request) -> None:
- """Remove request from tracking on finish."""
- 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:
- pages = self._browser_context.pages
- if page in pages:
- tab_index = pages.index(page)
+ tab_index = self.browser_session.get_tab_index(page)
# Emit crash event
self.event_bus.dispatch(
@@ -179,10 +155,11 @@ class CrashWatchdog(BaseModel):
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')
return
self._monitoring_task = asyncio.create_task(self._monitoring_loop())
- logger.info('[Watchdog] Monitoring loop started')
+ logger.info('[CrashWatchdog] Monitoring loop created and started')
# Set up CDP session for browser crash detection
if self._browser:
@@ -196,7 +173,15 @@ class CrashWatchdog(BaseModel):
await self._cdp_session.send('Page.enable')
# Set up crash handlers
- self._cdp_session.on('Inspector.targetCrashed', self._on_browser_crash)
+ self._cdp_session.on(
+ 'Inspector.targetCrashed',
+ lambda params: (
+ logger.error('[Watchdog] Browser crash detected via CDP'),
+ self.event_bus.dispatch(
+ BrowserErrorEvent(error_type='BrowserCrash', message='Browser process crashed', details=params)
+ ),
+ ),
+ )
logger.info('[Watchdog] CDP crash detection enabled')
except Exception as e:
@@ -222,7 +207,7 @@ class CrashWatchdog(BaseModel):
# Clear tracking
self._active_requests.clear()
- self._pages.clear()
+ # No _pages attribute in this watchdog
async def _monitoring_loop(self) -> None:
"""Main monitoring loop."""
@@ -241,9 +226,18 @@ class CrashWatchdog(BaseModel):
current_time = time.time()
timed_out_requests = []
+ # Debug logging
+ if self._active_requests:
+ logger.debug(
+ f'[Watchdog] Checking {len(self._active_requests)} active requests for timeouts (threshold: {self.network_timeout_seconds}s)'
+ )
+
for request_id, tracker in self._active_requests.items():
elapsed = current_time - tracker.start_time
- if elapsed > self.network_timeout_seconds:
+ logger.debug(
+ f'[Watchdog] Request {tracker.url[:30]}... elapsed: {elapsed:.1f}s, timeout: {self.network_timeout_seconds}s'
+ )
+ if elapsed >= self.network_timeout_seconds:
timed_out_requests.append((request_id, tracker))
# Emit events for timed out requests
@@ -281,7 +275,7 @@ class CrashWatchdog(BaseModel):
return
# Check browser process if we have PID
- if hasattr(self, '_browser_pid') and self._browser_pid:
+ if self._browser_pid:
try:
import psutil
@@ -304,7 +298,10 @@ class CrashWatchdog(BaseModel):
dead_pages = []
unresponsive_pages = []
- for page in list(self._pages): # Copy to avoid modification during iteration
+ if not self.browser_session._browser_context:
+ return
+
+ for page in list(self.browser_session._browser_context.pages): # Copy to avoid modification during iteration
try:
if page.is_closed():
dead_pages.append(page)
@@ -323,19 +320,14 @@ class CrashWatchdog(BaseModel):
# Remove dead pages
for page in dead_pages:
- self._pages.discard(page)
+ # Pages are managed by browser context, no need to remove manually
+ pass
# 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)
-
+ tab_index = self.browser_session.get_tab_index(page)
self.event_bus.dispatch(
BrowserErrorEvent(
error_type='PageUnresponsive',
@@ -381,11 +373,6 @@ class CrashWatchdog(BaseModel):
"""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:
- """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))
-
async def trigger_browser_crash(self) -> None:
"""Trigger a browser crash for testing (requires CDP session)."""
if not self._cdp_session:
@@ -419,3 +406,6 @@ class CrashWatchdog(BaseModel):
await cdp.detach()
except Exception as e:
logger.error(f'[Watchdog] Failed to trigger page crash: {e}')
+
+
+# Fix Pydantic circular dependency - this will be called from session.py after BrowserSession is defined
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 0a50b34b3..00959d36a 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -1,17 +1,16 @@
"""Downloads watchdog for monitoring and handling file downloads."""
-import asyncio
import json
import os
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, ClassVar
from urllib.parse import urlparse
from weakref import WeakSet
import anyio
-from bubus import EventBus
+from bubus import BaseEvent
from playwright.async_api import Download, Page
-from pydantic import BaseModel, ConfigDict, PrivateAttr
+from pydantic import PrivateAttr
from browser_use.browser.events import (
FileDownloadedEvent,
@@ -19,51 +18,54 @@ from browser_use.browser.events import (
TabClosedEvent,
TabCreatedEvent,
)
+from browser_use.browser.watchdog_base import BaseWatchdog
from browser_use.utils import logger
if TYPE_CHECKING:
- from browser_use.browser.session import BrowserSession
+ pass
-class DownloadsWatchdog(BaseModel):
+class DownloadsWatchdog(BaseWatchdog):
"""Monitors downloads and handles file download events."""
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- validate_assignment=True,
- extra='forbid',
- )
+ # Events this watchdog listens to (for documentation)
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
+ TabCreatedEvent,
+ TabClosedEvent,
+ NavigationCompleteEvent,
+ ]
- event_bus: EventBus
- browser_session: 'BrowserSession' # Dependency injection instead of private attrs
+ # Events this watchdog emits
+ EMITS: ClassVar[list[type[BaseEvent]]] = [
+ FileDownloadedEvent,
+ ]
# Private state
- _pages: WeakSet[Page] = PrivateAttr(default_factory=WeakSet)
+ _pages_with_listeners: WeakSet[Page] = PrivateAttr(
+ default_factory=WeakSet
+ ) # Track pages that already have download listeners
_active_downloads: dict[str, Download] = PrivateAttr(default_factory=dict)
_pdf_viewer_cache: dict[str, bool] = PrivateAttr(default_factory=dict) # Cache PDF viewer status by page URL
- 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()
+ 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}')
- 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)
- self.event_bus.on(NavigationCompleteEvent, self._handle_navigation_complete)
+ # 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'
- 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
+ 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')
+ await self.attach_to_page(page)
+ else:
+ logger.warning(f'[DownloadsWatchdog] No page found for tab {event.tab_index}')
- async def _handle_tab_closed(self, event: TabClosedEvent) -> None:
+ async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
"""Stop monitoring closed tabs."""
- # Tab will be removed automatically via WeakSet
- pass
+ pass # No cleanup needed, browser context handles page lifecycle
- async def _handle_navigation_complete(self, event: NavigationCompleteEvent) -> None:
+ async def on_NavigationCompleteEvent(self, event: NavigationCompleteEvent) -> None:
"""Check for PDFs after navigation completes."""
# Clear PDF cache for the navigated URL since content may have changed
if event.url in self._pdf_viewer_cache:
@@ -73,37 +75,38 @@ class DownloadsWatchdog(BaseModel):
if not self._is_auto_download_enabled():
return
- # Get the page that navigated
- try:
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- return
-
- pages = self.browser_session._browser_context.pages
- if 0 <= event.tab_index < len(pages):
- page = pages[event.tab_index]
-
- # Check if it's a PDF and auto-download if needed
- if await self.check_for_pdf_viewer(page):
- logger.info(f'[DownloadsWatchdog] PDF detected after navigation to {event.url}')
- await self.trigger_pdf_download(page)
- except Exception as e:
- logger.error(f'[DownloadsWatchdog] Error checking for PDF after navigation: {e}')
+ page = self.browser_session.get_page_by_tab_index(event.tab_index)
+ if page and await self.check_for_pdf_viewer(page):
+ logger.info(f'[DownloadsWatchdog] PDF detected after navigation to {event.url}')
+ await self.trigger_pdf_download(page)
def _is_auto_download_enabled(self) -> bool:
"""Check if PDF auto-download is enabled."""
return getattr(self.browser_session, '_auto_download_pdfs', True)
- 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}')
+ async def attach_to_page(self, page: Page) -> None:
+ """Set up download monitoring for a specific page."""
+ 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}')
+ return # No downloads path configured
+
+ # Check if we already have a download listener on this page
+ # to prevent duplicate listeners from being added
+ if page in self._pages_with_listeners:
+ logger.debug(f'[DownloadsWatchdog] Download listener already exists for page: {page.url}')
+ return
- def _setup_page_listeners(self, page: Page) -> None:
- """Set up download listeners for a page."""
- # Monitor download events
- logger.info(f'[DownloadsWatchdog] Setting up download listener for page: {page.url}')
- page.on('download', lambda download: asyncio.create_task(self._handle_download(download)))
+ logger.info(f'[DownloadsWatchdog] Setting up download listener for page: {page.url}')
+ # Set up Playwright download event listener
+ page.on('download', self._handle_download)
+ # Track that we've added a listener to prevent duplicates
+ self._pages_with_listeners.add(page)
+ logger.info(f'[DownloadsWatchdog] Successfully set up download listener for page: {page.url}')
+
+ except Exception as e:
+ logger.warning(f'[DownloadsWatchdog] Failed to set up download listener for page {page.url}: {e}')
async def _handle_download(self, download: Download) -> None:
"""Handle a download event."""
@@ -112,10 +115,12 @@ class DownloadsWatchdog(BaseModel):
logger.info(f'[DownloadsWatchdog] Handling download: {download.suggested_filename} from {download.url[:100]}...')
try:
- # Get download info
+ current_step = 'getting_download_info'
+ # Get download info immediately
url = download.url
suggested_filename = download.suggested_filename
+ current_step = 'determining_download_directory'
# Determine download directory from browser profile
downloads_dir = self.browser_session.browser_profile.downloads_path
if not downloads_dir:
@@ -123,14 +128,48 @@ class DownloadsWatchdog(BaseModel):
else:
downloads_dir = str(downloads_dir) # Ensure it's a string
+ current_step = 'generating_unique_filename'
# 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))
+ current_step = 'calling_save_as'
+ # Save the download using Playwright's save_as method
+ logger.info(f'[DownloadsWatchdog] Saving download to: {download_path}')
+ logger.info(f'[DownloadsWatchdog] Download path exists: {download_path.parent.exists()}')
+ logger.info(f'[DownloadsWatchdog] Download path writable: {os.access(download_path.parent, os.W_OK)}')
+
+ try:
+ logger.info('[DownloadsWatchdog] About to call download.save_as()...')
+ await download.save_as(str(download_path))
+ logger.info(f'[DownloadsWatchdog] Successfully saved download to: {download_path}')
+ current_step = 'save_as_completed'
+ except Exception as save_error:
+ logger.error(f'[DownloadsWatchdog] save_as() failed with error: {save_error}')
+ if 'canceled' in str(save_error).lower():
+ # Download was canceled - try using the path method as fallback
+ logger.warning(f'[DownloadsWatchdog] save_as() was canceled, trying path() method: {save_error}')
+ current_step = 'using_path_fallback'
+ try:
+ # Use download.path() to access the file that was already downloaded
+ source_path = await download.path()
+ if source_path and Path(source_path).exists():
+ # Move the file from the temporary location to our desired location
+ import shutil
+
+ shutil.move(str(source_path), str(download_path))
+ logger.info(f'[DownloadsWatchdog] Successfully moved download from {source_path} to: {download_path}')
+ current_step = 'path_fallback_completed'
+ else:
+ raise Exception(f'Downloaded file not found at path: {source_path}')
+ except Exception as path_error:
+ logger.error(f'[DownloadsWatchdog] Path fallback also failed: {path_error}')
+ raise save_error # Re-raise the original error
+ else:
+ # Some other save error
+ raise save_error
# Get file info
file_size = download_path.stat().st_size if download_path.exists() else 0
@@ -169,7 +208,10 @@ class DownloadsWatchdog(BaseModel):
# File is now tracked on filesystem, no need to track in memory
except Exception as e:
- logger.error(f'[DownloadsWatchdog] Error handling download: {e}')
+ logger.error(
+ f'[DownloadsWatchdog] Error handling download at step "{locals().get("current_step", "unknown")}", error: {e}'
+ )
+ logger.error(f'[DownloadsWatchdog] Download state - URL: {download.url}, filename: {download.suggested_filename}')
finally:
# Clean up tracking
if download_id in self._active_downloads:
@@ -395,3 +437,6 @@ class DownloadsWatchdog(BaseModel):
new_filename = f'{base} ({counter}){ext}'
counter += 1
return new_filename
+
+
+# Fix Pydantic circular dependency - this will be called from session.py after BrowserSession is defined
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index c8f458da8..e2b0a4c33 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -15,6 +15,8 @@ class NavigateToUrlEvent(BaseEvent):
url: str
wait_until: Literal['load', 'domcontentloaded', 'networkidle', 'commit'] = 'load'
+ new_tab: bool = False
+ timeout_ms: int | None = None
class ClickElementEvent(BaseEvent):
@@ -23,10 +25,12 @@ class ClickElementEvent(BaseEvent):
index: int
button: Literal['left', 'right', 'middle'] = 'left'
click_count: int = 1
+ expect_download: bool = False
+ new_tab: bool = False
-class InputTextEvent(BaseEvent):
- """Input text into an element."""
+class TypeTextEvent(BaseEvent):
+ """Type text into an element."""
index: int
text: str
@@ -47,12 +51,6 @@ class SwitchTabEvent(BaseEvent):
tab_index: int
-class CreateTabEvent(BaseEvent):
- """Create a new tab."""
-
- url: str | None = None
-
-
class CloseTabEvent(BaseEvent):
"""Close a tab."""
@@ -74,7 +72,7 @@ class BrowserStateRequestEvent(BaseEvent):
cache_clickable_elements_hashes: bool = True
-class WaitEvent(BaseEvent):
+class WaitForConditionEvent(BaseEvent):
"""Wait for a condition."""
condition: Literal['navigation', 'selector', 'timeout', 'load_state']
@@ -158,22 +156,21 @@ class BrowserStoppedEvent(BaseEvent):
class TabCreatedEvent(BaseEvent):
"""A new tab was created."""
- tab_id: str
tab_index: int
- url: str | None = None
+ url: str
class TabClosedEvent(BaseEvent):
"""A tab was closed."""
- tab_id: str | None = None # Made optional for compatibility
tab_index: int
class TabUpdatedEvent(BaseEvent):
"""Tab information updated (URL changed, etc.)."""
- tab_id: str
+ tab_index: int
+ url: str
class HumanFocusChangedEvent(BaseEvent):
@@ -250,7 +247,7 @@ class TabsInfoResponseEvent(BaseEvent):
tabs: list[dict[str, Any]]
-class EvaluateResponse(BaseEvent):
+class EvaluateJavaScriptResponseEvent(BaseEvent):
"""Response to EvaluateJavaScriptEvent."""
result: Any
diff --git a/browser_use/browser/human_focus_watchdog.py b/browser_use/browser/human_focus_watchdog.py
index af412ac41..7b9587288 100644
--- a/browser_use/browser/human_focus_watchdog.py
+++ b/browser_use/browser/human_focus_watchdog.py
@@ -1,66 +1,54 @@
"""Human focus watchdog for tracking which tab the human is viewing."""
import asyncio
-from typing import Any
+from typing import Any, ClassVar
from weakref import WeakKeyDictionary
-from bubus import EventBus
+from bubus import BaseEvent
from playwright.async_api import Page
-from pydantic import BaseModel, ConfigDict, PrivateAttr
+from pydantic import PrivateAttr
from browser_use.browser.events import (
- BrowserStartedEvent,
BrowserStoppedEvent,
HumanFocusChangedEvent,
SwitchTabEvent,
TabClosedEvent,
TabCreatedEvent,
)
+from browser_use.browser.watchdog_base import BaseWatchdog
from browser_use.utils import logger
-class HumanFocusWatchdog(BaseModel):
+class HumanFocusWatchdog(BaseWatchdog):
"""Tracks which tab the human is currently viewing/focused on."""
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- validate_assignment=True,
- extra='forbid',
- )
-
- event_bus: EventBus
- browser_session: Any # Avoid circular import
+ # Event contracts
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
+ BrowserStoppedEvent,
+ TabCreatedEvent,
+ TabClosedEvent,
+ SwitchTabEvent,
+ ]
+ EMITS: ClassVar[list[type[BaseEvent]]] = [
+ HumanFocusChangedEvent,
+ ]
# Use WeakKeyDictionary to avoid holding references to closed pages
_page_visibility_handlers: WeakKeyDictionary[Page, Any] = PrivateAttr(default_factory=WeakKeyDictionary)
_current_human_page: Page | None = PrivateAttr(default=None)
_monitoring_task: asyncio.Task | None = PrivateAttr(default=None)
- def __init__(self, event_bus: EventBus, browser_session: Any, **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(BrowserStartedEvent, self._handle_browser_started)
- self.event_bus.on(BrowserStoppedEvent, self._handle_browser_stopped)
- self.event_bus.on(TabCreatedEvent, self._handle_tab_created)
- self.event_bus.on(TabClosedEvent, self._handle_tab_closed)
- self.event_bus.on(SwitchTabEvent, self._handle_switch_tab)
-
- async def _handle_browser_started(self, event: BrowserStartedEvent) -> None:
- """Start monitoring when browser starts."""
- logger.info('[HumanFocusWatchdog] Browser started')
- await self._setup_initial_pages()
-
- async def _handle_browser_stopped(self, event: BrowserStoppedEvent) -> None:
+ async def attach_to_page(self, page: Page) -> None:
+ """Set up visibility tracking for a page."""
+ await self._setup_page_visibility_tracking(page)
+
+ async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:
"""Clean up when browser stops."""
logger.info('[HumanFocusWatchdog] Browser stopped')
self._current_human_page = None
self._page_visibility_handlers.clear()
- async def _handle_tab_created(self, event: TabCreatedEvent) -> None:
+ async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Monitor new tabs for visibility changes."""
# The actual page will be set up when we detect it via browser context
logger.debug(f'[HumanFocusWatchdog] Tab created: {event.url}')
@@ -68,14 +56,14 @@ class HumanFocusWatchdog(BaseModel):
await asyncio.sleep(0.5)
await self._setup_new_pages()
- async def _handle_tab_closed(self, event: TabClosedEvent) -> None:
+ async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
"""Handle tab closure."""
logger.debug(f'[HumanFocusWatchdog] Tab closed at index {event.tab_index}')
# If the closed tab was the human's current page, find a new one
if self._current_human_page and self._current_human_page.is_closed():
await self._find_new_human_page()
- async def _handle_switch_tab(self, event: SwitchTabEvent) -> None:
+ async def on_SwitchTabEvent(self, event: SwitchTabEvent) -> None:
"""Handle programmatic tab switches."""
# This could be the agent switching tabs, not necessarily the human
# We rely on visibility API to track actual human focus
@@ -86,24 +74,9 @@ class HumanFocusWatchdog(BaseModel):
"""Get the current page the human is viewing."""
return self._current_human_page
- async def _setup_initial_pages(self) -> None:
- """Set up visibility tracking for initial pages."""
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- return
-
- pages = self.browser_session._browser_context.pages
- for page in pages:
- await self._setup_page_visibility_tracking(page)
-
- # Set initial human page to first page if not set
- if not self._current_human_page and pages:
- self._current_human_page = pages[0]
- self._dispatch_focus_changed()
-
async def _setup_new_pages(self) -> None:
"""Check for new pages and set up visibility tracking."""
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
- return
+ assert self.browser_session._browser_context is not None, 'Browser context must be initialized before watchdog operations'
pages = self.browser_session._browser_context.pages
for page in pages:
@@ -185,7 +158,7 @@ class HumanFocusWatchdog(BaseModel):
async def _find_new_human_page(self) -> None:
"""Find a new page for human focus when current one is closed."""
- if not hasattr(self.browser_session, '_browser_context') or not self.browser_session._browser_context:
+ if not self.browser_session._browser_context:
self._current_human_page = None
return
diff --git a/browser_use/browser/navigation_watchdog.py b/browser_use/browser/navigation_watchdog.py
new file mode 100644
index 000000000..d74ae3c80
--- /dev/null
+++ b/browser_use/browser/navigation_watchdog.py
@@ -0,0 +1,516 @@
+"""Navigation watchdog for monitoring tab lifecycle and agent focus tracking."""
+
+import asyncio
+from typing import TYPE_CHECKING, ClassVar
+
+from bubus import BaseEvent
+from playwright.async_api import Page
+from pydantic import PrivateAttr
+
+from browser_use.browser.events import (
+ AgentFocusChangedEvent,
+ BrowserErrorEvent,
+ BrowserStoppedEvent,
+ NavigateToUrlEvent,
+ NavigationCompleteEvent,
+ NavigationStartedEvent,
+ SwitchTabEvent,
+ TabClosedEvent,
+ TabCreatedEvent,
+ TabsInfoRequestEvent,
+ TabsInfoResponseEvent,
+)
+from browser_use.browser.watchdog_base import BaseWatchdog
+from browser_use.utils import logger
+
+if TYPE_CHECKING:
+ pass
+
+
+class NavigationWatchdog(BaseWatchdog):
+ """Monitors tab creation, lifecycle events, and tracks agent focus."""
+
+ # Event contracts
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
+ BrowserStoppedEvent,
+ TabCreatedEvent,
+ TabClosedEvent,
+ SwitchTabEvent,
+ NavigateToUrlEvent,
+ NavigationCompleteEvent,
+ ]
+ EMITS: ClassVar[list[type[BaseEvent]]] = [
+ AgentFocusChangedEvent,
+ BrowserErrorEvent,
+ TabClosedEvent,
+ NavigationStartedEvent,
+ NavigationCompleteEvent,
+ ]
+
+ # Private state for agent focus tracking
+ _current_agent_page: Page | None = PrivateAttr(default=None)
+ _current_agent_tab_index: int = PrivateAttr(default=0)
+
+ async def attach_to_page(self, page: Page) -> None:
+ """Set up monitoring for a page - tracks page lifecycle."""
+ logger.debug(f'[NavigationWatchdog] Started tracking page: {page.url}')
+ page.on('close', lambda: self._handle_page_close(page))
+
+ # ========== Browser Lifecycle Events ==========
+
+ async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:
+ """Clear agent focus when browser stops."""
+ logger.info('[NavigationWatchdog] Browser stopped')
+ self._current_agent_page = None
+ self._current_agent_tab_index = 0
+
+ # ========== Tab Lifecycle Events ==========
+
+ 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}')
+
+ # Get the page from browser context and track it
+ try:
+ page = self.browser_session.get_page_by_tab_index(event.tab_index)
+ if page:
+ self._track_page(page)
+ except Exception as e:
+ logger.error(f'[NavigationWatchdog] Error tracking new page: {e}')
+
+ # When a new tab is created, agent typically focuses on it
+ # Small delay to let tab finish loading
+ await asyncio.sleep(0.5)
+ await self._update_agent_focus_to_latest_tab()
+
+ async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
+ """Handle tab closure."""
+ logger.debug(f'[NavigationWatchdog] Tab closed at index {event.tab_index}')
+
+ # If the closed tab was the agent's current page, find a new one
+ if self._current_agent_tab_index == event.tab_index:
+ await self._find_new_agent_page()
+ elif event.tab_index < self._current_agent_tab_index:
+ # Adjust index if a tab before current was closed
+ self._current_agent_tab_index -= 1
+
+ async def on_SwitchTabEvent(self, event: SwitchTabEvent) -> None:
+ """Handle explicit tab switches by the agent."""
+ logger.debug(f'[NavigationWatchdog] Agent switching to tab {event.tab_index}')
+ await self._switch_agent_focus_to_tab(event.tab_index)
+
+ async def on_NavigateToUrlEvent(self, event: NavigateToUrlEvent) -> None:
+ """Handle all navigation requests with security enforcement and complete logic."""
+ # SECURITY CHECK: Block disallowed URLs before navigation starts
+ if not self._is_url_allowed(event.url):
+ logger.warning(f'⛔️ Blocking navigation to disallowed URL: {event.url}')
+ self.event_bus.dispatch(
+ BrowserErrorEvent(
+ error_type='NavigationBlocked',
+ message=f'Navigation blocked to disallowed URL: {event.url}',
+ details={'url': event.url, 'reason': 'not_in_allowed_domains'},
+ )
+ )
+ return
+
+ try:
+ # Handle new tab navigation
+ if event.new_tab:
+ if not self.browser_session._browser_context:
+ return
+
+ # Create new page
+ page = await self.browser_session._browser_context.new_page()
+
+ # Page will be automatically attached to watchdogs via TabCreatedEvent
+
+ # Navigate to URL if provided
+ if event.url:
+ # Get tab index for events (after adding the page)
+ tab_index = len(self.browser_session.tabs) - 1
+
+ # Dispatch navigation started event
+ from browser_use.browser.events import NavigationStartedEvent
+
+ self.event_bus.dispatch(
+ NavigationStartedEvent(
+ tab_index=tab_index,
+ url=event.url,
+ )
+ )
+
+ try:
+ # Perform navigation
+ response = await page.goto(event.url, wait_until=event.wait_until)
+
+ # Dispatch completion event
+ self.event_bus.dispatch(
+ NavigationCompleteEvent(
+ tab_index=tab_index,
+ url=event.url,
+ status=response.status if response else None,
+ )
+ )
+
+ # Network monitoring is handled by CrashWatchdog
+
+ except Exception as e:
+ # Handle navigation error for new tab
+ error_message = str(e)
+ loading_status = None
+ if 'timeout' in error_message.lower() or 'timed out' in error_message.lower():
+ loading_status = f'Navigation timeout: {error_message}'
+
+ self.event_bus.dispatch(
+ NavigationCompleteEvent(
+ tab_index=tab_index,
+ url=event.url,
+ status=None,
+ error_message=error_message,
+ loading_status=loading_status,
+ )
+ )
+ return
+
+ # Handle timeout navigation
+ if event.timeout_ms is not None:
+ # Create a new navigation event without timeout for the actual navigation
+ nav_event = self.event_bus.dispatch(NavigateToUrlEvent(url=event.url, wait_until=event.wait_until))
+ try:
+ await asyncio.wait_for(nav_event, timeout=event.timeout_ms / 1000.0)
+ except TimeoutError:
+ logger.warning(f'Navigation to {event.url} timed out after {event.timeout_ms}ms')
+ # Dispatch NavigationCompleteEvent for timeout error
+ self.event_bus.dispatch(
+ NavigationCompleteEvent(
+ tab_index=0, # Default tab index since we don't have access to the actual page
+ url=event.url,
+ status=None,
+ error_message=f'Navigation timed out after {event.timeout_ms}ms',
+ loading_status=f'Navigation timeout after {event.timeout_ms}ms',
+ )
+ )
+ return
+
+ # Handle standard navigation
+ # Get the page to navigate - use current agent page or create one
+ page = None
+ try:
+ page = await self.get_or_create_page()
+ except Exception:
+ # Fallback to first page
+ if self.browser_session.pages:
+ page = self.browser_session.pages[0]
+
+ if not page:
+ raise ValueError('Failed to get or create a page for navigation')
+
+ # Get tab index
+ tab_index = self.browser_session.get_tab_index(page)
+
+ # Dispatch navigation started event
+ from browser_use.browser.events import NavigationStartedEvent
+
+ self.event_bus.dispatch(
+ NavigationStartedEvent(
+ tab_index=tab_index,
+ url=event.url,
+ )
+ )
+
+ # Perform navigation
+ response = await page.goto(
+ event.url,
+ wait_until=event.wait_until,
+ )
+
+ # Dispatch completion event
+ self.event_bus.dispatch(
+ NavigationCompleteEvent(
+ tab_index=tab_index,
+ url=event.url,
+ status=response.status if response else None,
+ )
+ )
+
+ # Network monitoring is handled by CrashWatchdog
+
+ except Exception as e:
+ # Handle navigation errors
+ error_message = str(e)
+ loading_status = None
+
+ # Check for timeout errors
+ if 'timeout' in error_message.lower() or 'timed out' in error_message.lower():
+ loading_status = f'Navigation timeout: {error_message}'
+
+ # Get tab index for error reporting
+ tab_index = 0 # Default to first tab for errors
+
+ # Dispatch NavigationCompleteEvent with error details
+ self.event_bus.dispatch(
+ NavigationCompleteEvent(
+ tab_index=tab_index,
+ url=event.url,
+ status=None,
+ error_message=error_message,
+ loading_status=loading_status,
+ )
+ )
+
+ async def on_NavigationCompleteEvent(self, event: NavigationCompleteEvent) -> None:
+ """Update agent focus when navigation completes and enforce security."""
+ # Check if the navigated URL is allowed
+ if not self._is_url_allowed(event.url):
+ logger.warning(f'⛔️ Navigation to non-allowed URL detected: {event.url}')
+ # Dispatch browser error
+ self.event_bus.dispatch(
+ BrowserErrorEvent(
+ error_type='NavigationBlocked',
+ message=f'Navigation to non-allowed URL: {event.url}',
+ details={'url': event.url, 'tab_index': event.tab_index},
+ )
+ )
+ # Close the page that navigated to the disallowed URL
+ try:
+ if self.browser_session._browser_context:
+ pages = self.browser_session._browser_context.pages
+ if 0 <= event.tab_index < len(pages):
+ page = pages[event.tab_index]
+ await page.close()
+ logger.info(f'⛔️ Closed page with non-allowed URL: {event.url}')
+ except Exception as e:
+ logger.error(f'⛔️ Failed to close page with non-allowed URL: {str(e)}')
+ return
+
+ # Agent focus stays on the tab that navigated
+ if event.tab_index != self._current_agent_tab_index:
+ await self._switch_agent_focus_to_tab(event.tab_index)
+
+ # ========== Tab Tracking Methods ==========
+
+ def _track_page(self, page: Page) -> None:
+ """Track a page for lifecycle events."""
+ logger.debug(f'[NavigationWatchdog] Started tracking page: {page.url}')
+
+ # Set up page close handler
+ page.on('close', lambda: self._handle_page_close(page))
+
+ def _handle_page_close(self, page: Page) -> None:
+ """Handle page close event."""
+ try:
+ # Try to get tab index before page is fully closed
+ tab_index = self.browser_session.get_tab_index(page)
+ if tab_index == -1:
+ tab_index = 0 # Fallback if page already removed
+
+ # Emit TabClosedEvent
+ self.event_bus.dispatch(TabClosedEvent(tab_index=tab_index))
+ logger.info(f'[NavigationWatchdog] Page closed, emitted TabClosedEvent for tab {tab_index}')
+
+ except Exception as e:
+ logger.error(f'[NavigationWatchdog] Error handling page close: {e}')
+
+ # ========== Security Methods ==========
+
+ def _is_url_allowed(self, url: str) -> bool:
+ """Check if a URL is allowed based on the allowed_domains configuration.
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ True if the URL is allowed, False otherwise
+ """
+ # If no allowed_domains specified, allow all URLs
+ if not self.browser_session.browser_profile.allowed_domains:
+ return True
+
+ # Always allow internal browser pages
+ if url in ['about:blank', 'chrome://new-tab-page/', 'chrome://new-tab-page', 'chrome://newtab/']:
+ return True
+
+ # Parse the URL to extract components
+ from urllib.parse import urlparse
+
+ try:
+ parsed = urlparse(url)
+ except Exception:
+ # Invalid URL
+ return False
+
+ # Get the actual host (domain)
+ host = parsed.hostname
+ if not host:
+ return False
+
+ # Full URL for matching (scheme + host)
+ full_url_pattern = f'{parsed.scheme}://{host}'
+
+ # Check each allowed domain pattern
+ for pattern in self.browser_session.browser_profile.allowed_domains:
+ # Handle glob patterns
+ if '*' in pattern:
+ import fnmatch
+
+ # Check if pattern matches the host
+ if pattern.startswith('*.'):
+ # Pattern like *.example.com should match subdomains and main domain
+ # But only for http/https URLs unless scheme is specified
+ domain_part = pattern[2:] # Remove *.
+ if host == domain_part or host.endswith('.' + domain_part):
+ # Only match http/https URLs for domain-only patterns
+ if parsed.scheme in ['http', 'https']:
+ return True
+ elif pattern.endswith('/*'):
+ # Pattern like brave://* should match any brave:// URL
+ prefix = pattern[:-1] # Remove the * at the end
+ if url.startswith(prefix):
+ return True
+ else:
+ # Use fnmatch for other glob patterns
+ if fnmatch.fnmatch(host, pattern):
+ return True
+ else:
+ # Exact match
+ if pattern.startswith(('http://', 'https://', 'chrome://', 'brave://', 'file://')):
+ # Full URL pattern
+ if url.startswith(pattern):
+ return True
+ else:
+ # Domain-only pattern
+ if host == pattern:
+ return True
+
+ return False
+
+ # ========== Agent Focus Tracking Methods ==========
+
+ @property
+ def current_agent_page(self) -> Page | None:
+ """Get the current page the agent is focused on."""
+ return self._current_agent_page
+
+ @property
+ def current_agent_tab_index(self) -> int:
+ """Get the current tab index the agent is focused on."""
+ return self._current_agent_tab_index
+
+ async def _initialize_agent_focus(self) -> None:
+ """Initialize agent focus to first available page."""
+ if not self.browser_session._browser_context:
+ return
+
+ pages = self.browser_session._browser_context.pages
+ if pages:
+ self._current_agent_page = pages[0]
+ self._current_agent_tab_index = 0
+ self._dispatch_focus_changed()
+ try:
+ current_page = await self.browser_session.get_current_page()
+ logger.info(f'[NavigationWatchdog] Initial agent focus set to tab 0: {current_page.url}')
+ except ValueError:
+ logger.info('[NavigationWatchdog] Initial agent focus set to tab 0')
+
+ async def _update_agent_focus_to_latest_tab(self) -> None:
+ """Update agent focus to the latest (most recently created) tab."""
+ if self.browser_session.pages:
+ # Focus on the last tab (most recently created)
+ self._current_agent_page = self.browser_session.pages[-1]
+ self._current_agent_tab_index = len(self.browser_session.pages) - 1
+ 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._current_agent_tab_index}: {current_page.url}'
+ )
+ except ValueError:
+ logger.info(f'[NavigationWatchdog] Agent focus moved to new tab {self._current_agent_tab_index}')
+
+ async def _switch_agent_focus_to_tab(self, tab_index: int) -> None:
+ """Switch agent focus to a specific tab index."""
+ page = self.browser_session.get_page_by_tab_index(tab_index)
+ if page:
+ self._current_agent_page = page
+ self._current_agent_tab_index = tab_index
+ self._dispatch_focus_changed()
+ try:
+ current_page = await self.browser_session.get_current_page()
+ logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}: {current_page.url}')
+ except ValueError:
+ logger.info(f'[NavigationWatchdog] Agent focus switched to tab {tab_index}')
+
+ async def _find_new_agent_page(self) -> None:
+ """Find a new page for agent focus when current one is closed."""
+ if self.browser_session.pages:
+ # Try to stay at the same index, or go to the previous one
+ new_index = min(self._current_agent_tab_index, len(self.browser_session.pages) - 1)
+ self._current_agent_page = self.browser_session.pages[new_index]
+ self._current_agent_tab_index = new_index
+ self._dispatch_focus_changed()
+ try:
+ current_page = await self.browser_session.get_current_page()
+ logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}: {current_page.url}')
+ except ValueError:
+ logger.info(f'[NavigationWatchdog] Agent focus moved to tab {new_index}')
+ else:
+ self._current_agent_page = None
+ self._current_agent_tab_index = 0
+
+ def _dispatch_focus_changed(self) -> None:
+ """Dispatch event when agent focus changes."""
+ if self._current_agent_page:
+ try:
+ self.event_bus.dispatch(
+ AgentFocusChangedEvent(
+ tab_index=self._current_agent_tab_index,
+ url=self._current_agent_page.url,
+ )
+ )
+ except Exception as e:
+ logger.error(f'[NavigationWatchdog] Error dispatching focus change: {e}')
+
+ async def get_or_create_page(self) -> Page:
+ """Get current agent page or create a new one if none exists."""
+ if self._current_agent_page and not self._current_agent_page.is_closed():
+ # Check if current page URL is still allowed
+ if not self._is_url_allowed(self._current_agent_page.url):
+ logger.warning(f'⛔️ Current page URL no longer allowed: {self._current_agent_page.url}')
+ # Close the current page and find/create a new one
+ try:
+ await self._current_agent_page.close()
+ except Exception:
+ pass
+ self._current_agent_page = None
+ else:
+ return self._current_agent_page
+
+ # No current page, request tabs info to find one
+ self.event_bus.dispatch(TabsInfoRequestEvent())
+ try:
+ event_result = await self.event_bus.expect(TabsInfoResponseEvent, timeout=5.0)
+ response: TabsInfoResponseEvent = event_result # type: ignore
+ if response.tabs:
+ # Find the first tab with an allowed URL
+ for i, tab in enumerate(response.tabs):
+ if self._is_url_allowed(tab.get('url', 'about:blank')):
+ await self._switch_agent_focus_to_tab(i)
+ if self._current_agent_page:
+ return self._current_agent_page
+ except TimeoutError:
+ pass
+
+ # No tabs available or no allowed tabs, create a new one with about:blank
+ logger.info('[NavigationWatchdog] No active page, creating new tab')
+ self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
+ await asyncio.sleep(0.5) # Wait for tab creation
+
+ # Try to get the new page
+ if self.browser_session.pages:
+ self._current_agent_page = self.browser_session.pages[-1]
+ self._current_agent_tab_index = len(self.browser_session.pages) - 1
+ self._dispatch_focus_changed()
+ if self._current_agent_page:
+ return self._current_agent_page
+
+ raise ValueError('Failed to create or find an active page')
diff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.py
index 06c72f9e8..551f2a5d6 100644
--- a/browser_use/browser/profile.py
+++ b/browser_use/browser/profile.py
@@ -459,6 +459,15 @@ class BrowserLaunchArgs(BaseModel):
assert not (self.headless and self.devtools), 'headless=True and devtools=True cannot both be set at the same time'
return self
+ @model_validator(mode='after')
+ def set_default_downloads_path(self) -> Self:
+ """Set a default downloads path if none is provided."""
+ if self.downloads_path is None:
+ import tempfile
+
+ self.downloads_path = Path(tempfile.gettempdir()) / 'browser-use-downloads'
+ return self
+
@staticmethod
def args_as_dict(args: list[str]) -> dict[str, str]:
"""Return the extra launch CLI args as a dictionary."""
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 2b7c60686..491fb8728 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -6,11 +6,10 @@ import json
import os
import warnings
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Literal, Self
-from weakref import WeakKeyDictionary, WeakSet
+from typing import TYPE_CHECKING, Any, Literal, Self, cast
from bubus import EventBus
-from playwright.async_api import Browser, BrowserContext, FloatRect, Page, Playwright, Request, Response, async_playwright
+from playwright.async_api import Browser, BrowserContext, FloatRect, Page, Playwright, async_playwright
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
from browser_use.browser.events import (
@@ -21,13 +20,10 @@ from browser_use.browser.events import (
BrowserStoppedEvent,
ClickElementEvent,
CloseTabEvent,
- CreateTabEvent,
FileDownloadedEvent,
- InputTextEvent,
LoadStorageStateEvent,
NavigateToUrlEvent,
NavigationCompleteEvent,
- NavigationStartedEvent,
SaveStorageStateEvent,
ScreenshotRequestEvent,
ScreenshotResponseEvent,
@@ -39,6 +35,7 @@ from browser_use.browser.events import (
TabCreatedEvent,
TabsInfoRequestEvent,
TabsInfoResponseEvent,
+ TypeTextEvent,
)
from browser_use.browser.profile import BrowserProfile
from browser_use.browser.views import TabInfo
@@ -71,7 +68,7 @@ class BrowserSession(BaseModel):
)
# Core configuration
- browser_profile: BrowserProfile
+ browser_profile: BrowserProfile = Field(default_factory=lambda: DEFAULT_BROWSER_PROFILE)
id: str = Field(default_factory=lambda: uuid7str())
# Connection info (for backwards compatibility)
@@ -98,18 +95,29 @@ class BrowserSession(BaseModel):
_downloads_watchdog: Any = PrivateAttr(default=None)
_aboutblank_watchdog: Any = PrivateAttr(default=None)
_human_focus_watchdog: Any = PrivateAttr(default=None)
- _agent_focus_watchdog: Any = PrivateAttr(default=None)
+ _navigation_watchdog: Any = PrivateAttr(default=None)
_storage_state_watchdog: Any = PrivateAttr(default=None)
- # Navigation tracking state (merged from NavigationWatchdog)
- _tracked_pages: WeakSet[Page] = PrivateAttr(default_factory=WeakSet)
- _page_requests: WeakKeyDictionary[Page, set[Request]] = PrivateAttr(default_factory=WeakKeyDictionary)
- _page_last_activity: WeakKeyDictionary[Page, float] = PrivateAttr(default_factory=WeakKeyDictionary)
- _monitoring_tasks: WeakKeyDictionary[Page, asyncio.Task] = PrivateAttr(default_factory=WeakKeyDictionary)
+ # Navigation tracking now handled by watchdogs
+
+ # Cached browser state for synchronous access
+ _cached_browser_state_summary: Any = PrivateAttr(default=None)
+ _logger: Any = PrivateAttr(default=None)
+
+ @property
+ def logger(self) -> Any:
+ """Get instance-specific logger with session ID in the name"""
+ if (
+ self._logger is None or self._browser_context is None
+ ): # keep updating the name pre-init because our id and str(self) can change
+ import logging
+
+ self._logger = logging.getLogger(f'browser_use.{self}')
+ return self._logger
def __init__(
self,
- browser_profile: BrowserProfile,
+ browser_profile: BrowserProfile | None = None,
cdp_url: str | None = None,
browser_pid: int | None = None,
**kwargs: Any,
@@ -117,12 +125,16 @@ class BrowserSession(BaseModel):
"""Initialize a browser session.
Args:
- browser_profile: Browser configuration profile
+ browser_profile: Browser configuration profile (defaults to DEFAULT_BROWSER_PROFILE)
cdp_url: CDP URL for connecting to existing browser
browser_pid: Process ID of existing browser (DEPRECATED)
**kwargs: Additional arguments
"""
+ # Use default profile if none provided
+ if browser_profile is None:
+ browser_profile = DEFAULT_BROWSER_PROFILE
+
# Initialize base model
super().__init__(
browser_profile=browser_profile,
@@ -198,15 +210,13 @@ class BrowserSession(BaseModel):
self.event_bus.on(StartBrowserEvent, self._handle_start)
self.event_bus.on(StopBrowserEvent, self._handle_stop)
- # Navigation and interaction
- self.event_bus.on(NavigateToUrlEvent, self._handle_navigate)
+ # Navigation is handled by NavigationWatchdog
+ # Interaction
self.event_bus.on(ClickElementEvent, self._handle_click)
- self.event_bus.on(InputTextEvent, self._handle_input_text)
+ self.event_bus.on(TypeTextEvent, self._handle_input_text)
self.event_bus.on(ScrollEvent, self._handle_scroll)
- # Tab management
- self.event_bus.on(SwitchTabEvent, self._handle_switch_tab)
- self.event_bus.on(CreateTabEvent, self._handle_create_tab)
+ # Tab management - handled by watchdogs
self.event_bus.on(CloseTabEvent, self._handle_close_tab)
# Browser state
@@ -259,14 +269,15 @@ class BrowserSession(BaseModel):
new_context_args = self.browser_profile.kwargs_for_new_context()
context_kwargs = new_context_args.model_dump(exclude_none=True)
- # Map downloads_path to downloads_path for new_context and ensure accept_downloads is True
+ # Ensure accept_downloads is True when downloads are enabled
if self.browser_profile.downloads_path:
# Ensure downloads directory exists
downloads_dir = Path(self.browser_profile.downloads_path)
downloads_dir.mkdir(parents=True, exist_ok=True)
context_kwargs['accept_downloads'] = True
- context_kwargs['downloads_path'] = str(downloads_dir.absolute())
- logger.info(f'Setting downloads_path to: {context_kwargs["downloads_path"]}')
+ # Note: downloads_path is NOT a valid parameter for new_context()
+ # Downloads will be handled by the downloads watchdog using download.save_as()
+ logger.info(f'Downloads enabled, target directory: {downloads_dir.absolute()}')
logger.info(f'Accept downloads: {context_kwargs["accept_downloads"]}')
# Log storage state info
@@ -274,7 +285,6 @@ class BrowserSession(BaseModel):
logger.info(f'NewContextArgs storage_state: {new_context_args.storage_state}')
logger.info(f'Context kwargs keys: {list(context_kwargs.keys())}')
logger.info(f'Context kwargs storage_state: {context_kwargs.get("storage_state")}')
- logger.info(f'Context kwargs downloads_path: {context_kwargs.get("downloads_path")}')
logger.info(f'Context kwargs accept_downloads: {context_kwargs.get("accept_downloads")}')
self._browser_context = await self._browser.new_context(**context_kwargs)
@@ -283,57 +293,42 @@ class BrowserSession(BaseModel):
pages = self._browser_context.pages
# Agent focus will be initialized by the watchdog
- # 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
- )
-
- # 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, browser_session=self)
-
- # Add initial pages to all watchdogs
- for page in pages:
- self._add_page_to_watchdogs(page)
-
- # Initialize aboutblank watchdog if not already initialized
- if not hasattr(self, '_aboutblank_watchdog'):
- from browser_use.browser.aboutblank_watchdog import AboutBlankWatchdog
-
- self._aboutblank_watchdog = AboutBlankWatchdog(event_bus=self.event_bus, browser_session=self)
-
- # Initialize human focus watchdog if not already initialized
- if not hasattr(self, '_human_focus_watchdog'):
- from browser_use.browser.human_focus_watchdog import HumanFocusWatchdog
-
- self._human_focus_watchdog = HumanFocusWatchdog(event_bus=self.event_bus, browser_session=self)
-
- # Initialize agent focus watchdog if not already initialized
- if not hasattr(self, '_agent_focus_watchdog'):
- from browser_use.browser.agent_focus_watchdog import AgentFocusWatchdog
-
- self._agent_focus_watchdog = AgentFocusWatchdog(event_bus=self.event_bus, browser_session=self)
-
- # Initialize storage state watchdog if not already initialized
- if not hasattr(self, '_storage_state_watchdog'):
- from browser_use.browser.storage_state_watchdog import StorageStateWatchdog
-
- self._storage_state_watchdog = StorageStateWatchdog(event_bus=self.event_bus, browser_session=self)
+ # Initialize and attach all watchdogs
+ await self.attach_all_watchdogs()
# Notify success
+ logger.info('[Session] !!!! DISPATCHING BrowserStartedEvent !!!!')
self.event_bus.dispatch(
BrowserStartedEvent(
cdp_url=self.cdp_url,
browser_pid=self._subprocess.pid if self._subprocess else None,
)
)
+ logger.info('[Session] !!!! BrowserStartedEvent dispatched !!!!')
+
+ # Emit TabCreatedEvent and NavigationCompleteEvent for all existing pages
+ if self._browser_context:
+ for idx, page in enumerate(self._browser_context.pages):
+ # Emit TabCreatedEvent
+ self.event_bus.dispatch(
+ TabCreatedEvent(
+ tab_index=idx,
+ url=page.url,
+ )
+ )
+ logger.info(f'[Session] Emitted TabCreatedEvent for existing tab {idx}: {page.url}')
+
+ # Emit NavigationCompleteEvent for the current page state
+ self.event_bus.dispatch(
+ NavigationCompleteEvent(
+ tab_index=idx,
+ url=page.url,
+ status=200, # Assume existing pages loaded successfully
+ error_message=None,
+ loading_status='Existing page, found already open',
+ )
+ )
+ logger.info(f'[Session] Emitted NavigationCompleteEvent for existing tab {idx}: {page.url}')
# Automatically load storage state after browser start
self.event_bus.dispatch(LoadStorageStateEvent())
@@ -374,16 +369,7 @@ class BrowserSession(BaseModel):
)
return
- # Cancel all navigation monitoring tasks
- for task in list(self._monitoring_tasks.values()):
- if not task.done():
- task.cancel()
-
- # Clear navigation tracking state
- self._tracked_pages.clear()
- self._page_requests.clear()
- self._page_last_activity.clear()
- self._monitoring_tasks.clear()
+ # Network monitoring now handled by watchdogs
# Automatically save storage state before stopping
self.event_bus.dispatch(SaveStorageStateEvent())
@@ -453,91 +439,12 @@ class BrowserSession(BaseModel):
event = self.event_bus.dispatch(StopBrowserEvent())
await event
- async def _handle_navigate(self, event: NavigateToUrlEvent) -> None:
- """Handle navigation request with network monitoring (merged from NavigationWatchdog)."""
- try:
- # Get the page to navigate
- page = await self._get_page_for_navigation(event)
- if not page:
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='NoActivePage',
- message='No active page to navigate',
- )
- )
- return
-
- # Dispatch navigation started event
- tab_index = await self._get_tab_index(page)
- self.event_bus.dispatch(
- NavigationStartedEvent(
- tab_index=tab_index,
- url=event.url,
- )
- )
-
- # Perform navigation
- response = await page.goto(
- event.url,
- wait_until=event.wait_until,
- )
-
- # Dispatch completion event
- self.event_bus.dispatch(
- NavigationCompleteEvent(
- tab_index=tab_index,
- url=event.url,
- status=response.status if response else None,
- )
- )
-
- # Start monitoring network activity for the page
- await self._monitor_page_network(page)
-
- except Exception as e:
- # Handle navigation errors
- error_message = str(e)
- loading_status = None
-
- # Check for timeout errors
- if 'timeout' in error_message.lower():
- loading_status = f'Timed out waiting for network idle after {event.wait_until}'
- if 'exceeded while waiting for event "load"' in error_message:
- loading_status = 'Network timeout - page load incomplete'
-
- # Get tab index for error reporting
- try:
- page = await self._get_page_for_navigation(event)
- tab_index = await self._get_tab_index(page) if page else 0
- except Exception:
- tab_index = 0
-
- # Dispatch NavigationCompleteEvent with error details
- self.event_bus.dispatch(
- NavigationCompleteEvent(
- tab_index=tab_index,
- url=event.url,
- status=None,
- error_message=error_message,
- loading_status=loading_status,
- )
- )
-
- # Also dispatch error event for backwards compatibility
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type='NavigationFailed',
- message=str(e),
- details={'url': event.url},
- )
- )
-
async def _handle_click(self, event: ClickElementEvent) -> None:
"""Handle click request."""
try:
page = await self.get_current_page()
except ValueError:
- self._dispatch_no_page_error('NoActivePage', 'No active page for click')
+ self.event_bus.dispatch(BrowserErrorEvent(error_type='NoActivePage', message='No active page for click', details={}))
return
try:
@@ -547,7 +454,7 @@ class BrowserSession(BaseModel):
raise Exception(f'Element index {event.index} does not exist - retry or use alternative actions')
# Track initial number of tabs to detect new tab opening
- initial_pages = len(self.tabs)
+ initial_pages = len(self.pages)
# Check if element is a file input (should not be clicked)
if self.is_file_input(element_node):
@@ -563,7 +470,9 @@ class BrowserSession(BaseModel):
return
# Perform the actual click
- download_path = await self._click_element_node(element_node)
+ download_path = await self._click_element_node(
+ element_node, expect_download=event.expect_download, new_tab=event.new_tab
+ )
# Build success message
if download_path:
@@ -576,7 +485,7 @@ class BrowserSession(BaseModel):
logger.debug(f'Element xpath: {element_node.xpath}')
# Check if a new tab was opened
- if len(self.tabs) > initial_pages:
+ if len(self.pages) > initial_pages:
new_tab_msg = 'New tab opened - switching to it'
msg += f' - {new_tab_msg}'
logger.info(f'🔗 {new_tab_msg}')
@@ -591,7 +500,7 @@ class BrowserSession(BaseModel):
)
)
- async def _handle_input_text(self, event: InputTextEvent) -> None:
+ async def _handle_input_text(self, event: TypeTextEvent) -> None:
"""Handle text input request."""
try:
page = await self.get_current_page()
@@ -659,54 +568,26 @@ class BrowserSession(BaseModel):
)
)
- async def _handle_switch_tab(self, event: SwitchTabEvent) -> None:
- """Handle tab switch request."""
- # Agent focus watchdog will handle the actual switch via event listener
- pass
-
- async def _handle_create_tab(self, event: CreateTabEvent) -> None:
- """Handle new tab creation."""
- if not self._browser_context:
- return
-
- page = await self._browser_context.new_page()
-
- # Note: Download behavior is set at browser level during startup
-
- # Add page to all watchdogs
- self._add_page_to_watchdogs(page)
-
- if event.url:
- await page.goto(event.url)
-
- tab_index = len(self.tabs) - 1
- self.event_bus.dispatch(
- TabCreatedEvent(
- tab_id=f'tab_{tab_index}_{id(page)}',
- tab_index=tab_index,
- url=event.url,
- )
- )
-
async def _handle_close_tab(self, event: CloseTabEvent) -> None:
"""Handle tab close request."""
- pages = self.tabs
- if 0 <= event.tab_index < len(pages):
- await pages[event.tab_index].close()
+ if 0 <= event.tab_index < len(self.pages):
+ await self.pages[event.tab_index].close()
# Dispatch tab closed event for watchdogs
self.event_bus.dispatch(TabClosedEvent(tab_index=event.tab_index))
async def _handle_browser_state_request(self, event: BrowserStateRequestEvent) -> None:
"""Handle browser state request."""
try:
- # Get the full browser state with recovery
+ # Use the internal method directly to avoid infinite loop
state = await self._get_browser_state_with_recovery(
cache_clickable_elements_hashes=event.cache_clickable_elements_hashes, include_screenshot=event.include_screenshot
)
+ # Cache the state for the property
+ self._cached_browser_state_summary = state
self.event_bus.dispatch(BrowserStateResponseEvent(state=state))
except Exception as e:
# Fall back to minimal state on error
- minimal_state = await self._get_minimal_state_summary()
+ minimal_state = await self.get_minimal_state_summary()
self.event_bus.dispatch(BrowserStateResponseEvent(state=minimal_state))
async def _handle_screenshot_request(self, event: ScreenshotRequestEvent) -> None:
@@ -743,7 +624,7 @@ class BrowserSession(BaseModel):
await start_event
tabs = []
- for i, page in enumerate(self.tabs):
+ for i, page in enumerate(self.pages):
if not page.is_closed():
tab_info = TabInfo(
page_id=i,
@@ -821,8 +702,8 @@ class BrowserSession(BaseModel):
@property
def agent_current_page(self) -> Page | None:
"""Get the agent's current page."""
- if self._agent_focus_watchdog:
- return self._agent_focus_watchdog.current_agent_page
+ if self._navigation_watchdog:
+ return self._navigation_watchdog.current_agent_page
return None
@property
@@ -868,21 +749,50 @@ class BrowserSession(BaseModel):
return self._browser_context.pages
return []
+ @property
+ def pages(self) -> list[Page]:
+ """Get all open pages."""
+ if self._browser_context:
+ return self._browser_context.pages
+ return []
+
+ def get_page_by_tab_index(self, tab_index: int) -> Page | None:
+ """Get page by tab index."""
+ if 0 <= tab_index < len(self.pages):
+ return self.pages[tab_index]
+ return None
+
+ def get_tab_index(self, page: Page) -> int:
+ """Get tab index for a page."""
+ if page in self.pages:
+ return self.pages.index(page)
+ return -1
+
+ @property
+ def browser_state_summary(self) -> Any:
+ """Get the cached browser state summary (synchronous access)."""
+ # This is a compatibility property for code that expects synchronous access
+ # For new code, use get_browser_state_with_recovery() instead
+ return getattr(self, '_cached_browser_state_summary', None)
+
# Page management
async def get_current_page(self) -> Page:
"""Get the current active page."""
- if self._agent_focus_watchdog:
- return await self._agent_focus_watchdog.get_or_create_page()
+ if self._navigation_watchdog:
+ return await self._navigation_watchdog.get_or_create_page()
# Fallback if watchdog not initialized
- if self.tabs:
- return self.tabs[0]
+ if self.pages:
+ return self.pages[0]
raise ValueError('No active page available')
async def new_page(self, url: str | None = None) -> Page:
"""Create a new page."""
- event = self.event_bus.dispatch(CreateTabEvent(url=url))
+ if url:
+ event = self.event_bus.dispatch(NavigateToUrlEvent(url=url, new_tab=True))
+ else:
+ event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
await event
- return self.tabs[-1] # Return the newly created page
+ return self.pages[-1] # Return the newly created page
async def create_new_tab(self, url: str | None = None) -> Page:
"""Create a new tab."""
@@ -897,18 +807,22 @@ class BrowserSession(BaseModel):
event = self.event_bus.dispatch(SwitchTabEvent(tab_index=tab_index))
await event
- async def navigate_to(self, url: str) -> None:
+ async def navigate_to(self, url: str) -> Page:
"""Navigate the current page to a URL."""
event = self.event_bus.dispatch(NavigateToUrlEvent(url=url))
await event
+ return await self.get_current_page()
- async def navigate(self, url: str) -> None:
- """Alias for navigate_to for backwards compatibility."""
- await self.navigate_to(url)
+ async def navigate(self, url: str, timeout_ms: int | None = None, new_tab: bool = False) -> Page:
+ """Navigate with optional timeout and new tab support."""
+ event = self.event_bus.dispatch(NavigateToUrlEvent(url=url, timeout_ms=timeout_ms, new_tab=new_tab))
+ await event
+ return await self.get_current_page()
async def go_to_url(self, url: str) -> None:
"""Alias for navigate_to."""
- await self.navigate_to(url)
+ event = self.event_bus.dispatch(NavigateToUrlEvent(url=url))
+ await event
async def go_back(self) -> None:
"""Go back in the browser history."""
@@ -941,14 +855,14 @@ class BrowserSession(BaseModel):
# No screenshot received
return b''
- async def click_element(self, index: int) -> None:
+ async def click_element(self, index: int, expect_download: bool = False, new_tab: bool = False) -> None:
"""Click element by index."""
- event = self.event_bus.dispatch(ClickElementEvent(index=index))
+ event = self.event_bus.dispatch(ClickElementEvent(index=index, expect_download=expect_download, new_tab=new_tab))
await event
async def input_text(self, index: int, text: str) -> None:
"""Input text into element."""
- event = self.event_bus.dispatch(InputTextEvent(index=index, text=text))
+ event = self.event_bus.dispatch(TypeTextEvent(index=index, text=text))
await event
async def scroll(self, direction: Literal['up', 'down', 'left', 'right'], amount: int) -> None:
@@ -974,8 +888,10 @@ class BrowserSession(BaseModel):
return copy
# Additional compatibility methods
- async def is_connected(self) -> bool:
+ async def is_connected(self, restart: bool = True) -> bool:
"""Check if connected to browser."""
+ # The restart parameter is for backward compatibility but is ignored
+ # in the current implementation since restart behavior is now handled automatically
return self._browser is not None and self._browser.is_connected()
async def save_storage_state(self, path: str | None = None) -> None:
@@ -1038,7 +954,7 @@ class BrowserSession(BaseModel):
return response.state
except TimeoutError:
# Fall back to minimal state
- return await self._get_minimal_state_summary()
+ return await self.get_minimal_state_summary()
async def _get_browser_state_with_recovery(
self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = True
@@ -1046,44 +962,15 @@ class BrowserSession(BaseModel):
"""Internal method to get browser state with recovery logic."""
# Try 1: Full state summary
try:
- await self._wait_for_page_and_frames_load()
- return await self._get_state_summary(cache_clickable_elements_hashes, include_screenshot=include_screenshot)
+ await self.get_current_page() # Ensure we have a page
+ return await self.get_state_summary(cache_clickable_elements_hashes, include_screenshot=include_screenshot)
except Exception as e:
logger.warning(f'Full state retrieval failed: {type(e).__name__}: {e}')
logger.warning('🔄 Falling back to minimal state summary')
- return await self._get_minimal_state_summary()
-
- async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):
- """
- Ensures page is fully loaded and stable before continuing.
- Waits for network idle, DOM stability, and minimum WAIT_TIME.
- """
- # For now, just ensure we have a page
- page = await self.get_current_page()
- if not page:
- raise ValueError('No current page available')
-
- # Skip wait for new tab pages
- if page.url in NEW_TAB_URLS:
- return
-
- # Wait for page load (previously handled by NavigationWatchdog)
- await self._wait_for_page_load(page, timeout_overwrite)
+ return await self.get_minimal_state_summary()
- async def _wait_for_page_load(self, page: Page, timeout_overwrite: float | None = None) -> None:
- """Wait for page to load completely with network idle."""
- timeout = timeout_overwrite or 30.0
- try:
- await page.wait_for_load_state('networkidle', timeout=timeout * 1000)
- except Exception:
- # If networkidle times out, at least wait for domcontentloaded
- try:
- await page.wait_for_load_state('domcontentloaded', timeout=10 * 1000)
- except Exception:
- pass # Continue anyway
-
- async def _get_state_summary(self, cache_clickable_elements_hashes: bool, include_screenshot: bool = True) -> Any:
+ async def get_state_summary(self, cache_clickable_elements_hashes: bool, include_screenshot: bool = True) -> Any:
"""Get a summary of the current browser state"""
from browser_use.browser.views import BrowserStateSummary, PageInfo
from browser_use.dom.service import DomService
@@ -1196,7 +1083,7 @@ class BrowserSession(BaseModel):
recent_events=self._generate_recent_events_summary(),
)
- async def _get_minimal_state_summary(self) -> Any:
+ async def get_minimal_state_summary(self) -> Any:
"""Get basic page info without DOM processing"""
from browser_use.browser.views import BrowserStateSummary
from browser_use.dom.views import DOMElementNode
@@ -1263,6 +1150,28 @@ class BrowserSession(BaseModel):
return element
return None
+ async def get_locate_element_by_xpath(self, xpath: str) -> Any:
+ """Get playwright ElementHandle for an element by XPath."""
+ page = await self.get_current_page()
+ if not page:
+ return None
+
+ try:
+ return await page.locator(f'xpath={xpath}').element_handle()
+ except Exception:
+ return None
+
+ async def get_locate_element_by_css_selector(self, selector: str) -> Any:
+ """Get playwright ElementHandle for an element by CSS selector."""
+ page = await self.get_current_page()
+ if not page:
+ return None
+
+ try:
+ return await page.locator(selector).element_handle()
+ except Exception:
+ return None
+
async def get_locate_element(self, element: Any) -> Any:
"""Get playwright ElementHandle for a DOM element."""
if not element or not hasattr(element, 'xpath'):
@@ -1501,9 +1410,14 @@ class BrowserSession(BaseModel):
counter += 1
return new_filename
- async def _click_element_node(self, element: Any) -> str | None:
+ async def _click_element_node(self, element: Any, expect_download: bool = False, new_tab: bool = False) -> str | None:
"""Click an element node and handle potential downloads.
+ Args:
+ element: The DOM element to click
+ expect_download: If True, wait for download and handle it inline. If False, let page-level handler catch it.
+ new_tab: If True, open any resulting navigation in a new tab.
+
Returns the download path if a download was triggered, None otherwise.
"""
if not element:
@@ -1520,41 +1434,38 @@ class BrowserSession(BaseModel):
download_path = None
- # Handle potential downloads if downloads are enabled
- if self.browser_profile.downloads_path:
+ if expect_download and self.browser_profile.downloads_path:
+ # When expecting a download, click and wait for FileDownloadedEvent from downloads watchdog
+ # The downloads watchdog page-level listener will handle the actual download
try:
- # Try short-timeout expect_download to detect a file download
- async with page.expect_download(timeout=5_000) as download_info:
+ # Click the element (with new tab modifier if requested)
+ if new_tab:
+ import sys
+
+ modifier = 'Meta' if sys.platform == 'darwin' else 'Control'
+ await locator.click(modifiers=[modifier])
+ else:
await locator.click()
- download = await download_info.value
- # Determine file path
- suggested_filename = download.suggested_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)
- await download.save_as(download_path)
- logger.info(f'⬇️ Downloaded file to: {download_path}')
+ # Wait for download event from downloads watchdog with timeout
+ # The watchdog's page.on('download') handler will save_as() and dispatch FileDownloadedEvent
+ download_event = cast(FileDownloadedEvent, await self.event_bus.expect(FileDownloadedEvent, timeout=10.0))
+ download_path = download_event.path
+ logger.info(f'⬇️ Downloaded file via watchdog: {download_path}')
- # Emit download event for the watchdog
- self.event_bus.dispatch(
- FileDownloadedEvent(
- url=download.url,
- path=download_path,
- file_name=suggested_filename,
- file_size=os.path.getsize(download_path) if os.path.exists(download_path) else 0,
- file_type=os.path.splitext(suggested_filename)[1].lstrip('.'),
- mime_type=None,
- from_cache=False,
- auto_download=False,
- )
- )
+ except TimeoutError:
+ logger.warning('Expected download but no FileDownloadedEvent received within timeout')
+ except Exception as e:
+ logger.warning(f'Error while waiting for download: {e}')
+ else:
+ # Normal click or new tab click - let downloads watchdog handle any downloads in background
+ if new_tab:
+ import sys
- except Exception:
- # If no download is triggered, just perform normal click
+ modifier = 'Meta' if sys.platform == 'darwin' else 'Control'
+ await locator.click(modifiers=[modifier])
+ else:
await locator.click()
- else:
- # If downloads are disabled, just perform the click
- await locator.click()
return download_path
@@ -1735,188 +1646,36 @@ class BrowserSession(BaseModel):
# ========== Helper Methods ==========
- def _add_page_to_watchdogs(self, page: Page) -> None:
- """Add a page to all active watchdogs."""
- # 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)
-
- # Add page to navigation tracking
- self._add_page_tracking(page)
+ async def attach_all_watchdogs(self) -> None:
+ """Initialize and attach all watchdogs in one go."""
+ from browser_use.browser.aboutblank_watchdog import AboutBlankWatchdog
+ from browser_use.browser.crash_watchdog import CrashWatchdog
+ from browser_use.browser.downloads_watchdog import DownloadsWatchdog
+ from browser_use.browser.human_focus_watchdog import HumanFocusWatchdog
+ from browser_use.browser.navigation_watchdog import NavigationWatchdog
+ from browser_use.browser.storage_state_watchdog import StorageStateWatchdog
+
+ watchdog_configs = [
+ ('_crash_watchdog', CrashWatchdog),
+ ('_downloads_watchdog', DownloadsWatchdog),
+ ('_navigation_watchdog', NavigationWatchdog),
+ ('_storage_state_watchdog', StorageStateWatchdog),
+ ('_aboutblank_watchdog', AboutBlankWatchdog),
+ ('_human_focus_watchdog', HumanFocusWatchdog),
+ ]
+
+ for attr_name, watchdog_class in watchdog_configs:
+ if not hasattr(self, attr_name) or getattr(self, attr_name) is None:
+ try:
+ 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__}')
+ except Exception as e:
+ logger.warning(f'[Session] Failed to initialize {watchdog_class.__name__}: {e}')
# ========== Navigation Helper Methods (merged from NavigationWatchdog) ==========
- def _add_page_tracking(self, page: Page) -> None:
- """Add a page to track for navigation."""
- self._tracked_pages.add(page)
- self._setup_page_listeners(page)
- logger.debug(f'[Session] Added page to navigation tracking: {page.url}')
-
- def _setup_page_listeners(self, page: Page) -> None:
- """Set up network request listeners for a page."""
- # Initialize tracking structures
- self._page_requests[page] = set()
- self._page_last_activity[page] = asyncio.get_event_loop().time()
-
- # Set up request/response tracking
- page.on('request', lambda request: self._on_request(page, request))
- page.on('response', lambda response: self._on_response(page, response))
- page.on('requestfailed', lambda request: self._on_request_failed(page, request))
- page.on('requestfinished', lambda request: self._on_request_finished(page, request))
-
- def _on_request(self, page: Page, request: Request) -> None:
- """Track new network request."""
- if page in self._page_requests:
- self._page_requests[page].add(request)
- self._page_last_activity[page] = asyncio.get_event_loop().time()
- logger.debug(f'[Session] Request started: {request.method} {request.url}')
-
- def _on_response(self, page: Page, response: Response) -> None:
- """Track network response."""
- if page in self._page_requests and response.request in self._page_requests[page]:
- self._page_requests[page].discard(response.request)
- self._page_last_activity[page] = asyncio.get_event_loop().time()
- logger.debug(f'[Session] Request completed: {response.request.method} {response.url}')
-
- def _on_request_failed(self, page: Page, request: Request) -> None:
- """Handle failed network request."""
- if page in self._page_requests:
- self._page_requests[page].discard(request)
- logger.debug(f'[Session] Request failed: {request.method} {request.url}')
-
- def _on_request_finished(self, page: Page, request: Request) -> None:
- """Handle finished network request."""
- if page in self._page_requests:
- self._page_requests[page].discard(request)
- logger.debug(f'[Session] Request finished: {request.method} {request.url}')
-
- async def _monitor_page_network(self, page: Page) -> None:
- """Monitor network activity for a page after navigation."""
- # Cancel any existing monitoring task for this page
- if page in self._monitoring_tasks:
- old_task = self._monitoring_tasks[page]
- if not old_task.done():
- old_task.cancel()
-
- # Skip monitoring for new tab pages
- if page.url in NEW_TAB_URLS:
- return
-
- # Ensure page is tracked
- if page not in self._tracked_pages:
- self._add_page_tracking(page)
-
- # Create new monitoring task
- task = asyncio.create_task(self._wait_for_stable_network(page))
- self._monitoring_tasks[page] = task
-
- async def _wait_for_stable_network(self, page: Page) -> None:
- """Wait for network to be stable with no pending requests for a specific page."""
- logger.info(f'[Session] Monitoring network stability for {page.url}')
-
- start_time = asyncio.get_event_loop().time()
-
- try:
- while True:
- await asyncio.sleep(0.1)
- now = asyncio.get_event_loop().time()
-
- # Get pending requests for this page
- pending_requests = self._page_requests.get(page, set())
- last_activity = self._page_last_activity.get(page, start_time)
-
- # Check if network is idle
- idle_time = self.browser_profile.wait_for_network_idle_page_load_time
- if len(pending_requests) == 0 and (now - last_activity) >= idle_time:
- # Page loaded successfully
- logger.info(f'[Session] Network stable for {page.url}')
- break
-
- # Check for timeout
- max_wait = self.browser_profile.maximum_wait_page_load_time
- if now - start_time > max_wait:
- logger.info(
- f'[Session] Network timeout after {max_wait}s with {len(pending_requests)} '
- f'pending requests for {page.url}'
- )
-
- # Dispatch NavigationCompleteEvent with loading status
- loading_status = (
- f'Page loading was aborted after {max_wait}s with {len(pending_requests)} pending network requests. '
- f'You may want to use the wait action to allow more time for the page to fully load.'
- )
-
- tab_index = await self._get_tab_index(page)
- self.event_bus.dispatch(
- NavigationCompleteEvent(
- tab_index=tab_index,
- url=page.url,
- status=None,
- error_message=f'Network timeout with {len(pending_requests)} pending requests',
- loading_status=loading_status,
- )
- )
- break
-
- except asyncio.CancelledError:
- logger.debug(f'[Session] Network monitoring cancelled for {page.url}')
- raise
- except Exception as e:
- logger.error(f'[Session] Error monitoring network: {e}')
-
- async def _get_page_for_navigation(self, event: NavigateToUrlEvent) -> Page | None:
- """Get the page to navigate based on the event."""
- # Use agent focus watchdog to get current page
- if hasattr(self, '_agent_focus_watchdog') and self._agent_focus_watchdog:
- try:
- return await self._agent_focus_watchdog.get_or_create_page()
- except Exception:
- pass
-
- # Fallback to first page
- if hasattr(self, '_browser_context') and self._browser_context:
- pages = self._browser_context.pages
- if pages:
- return pages[0]
-
- return None
-
- async def _get_tab_index(self, page: Page) -> int:
- """Get the tab index for a page."""
- if hasattr(self, '_browser_context') and self._browser_context:
- pages = self._browser_context.pages
- if page in pages:
- return pages.index(page)
- return 0
-
- def _get_pending_requests(self, page: Page) -> set[Request]:
- """Get pending requests for a page."""
- return self._page_requests.get(page, set()).copy()
-
- def _is_page_loading(self, page: Page) -> bool:
- """Check if a page has pending network requests."""
- return len(self._page_requests.get(page, set())) > 0
-
- async def wait_for_page_load(self, page: Page, timeout: float | None = None) -> None:
- """Wait for a page to finish loading with stable network.
-
- This method can be called externally to wait for page load completion.
- """
- # Skip wait for new tab pages
- if page.url in NEW_TAB_URLS:
- return
-
- # If page not tracked, add it
- if page not in self._tracked_pages:
- self._add_page_tracking(page)
-
- # Wait for stable network
- await self._wait_for_stable_network(page)
-
# ========== PDF API Methods ==========
def set_auto_download_pdfs(self, enabled: bool) -> None:
@@ -1934,15 +1693,6 @@ class BrowserSession(BaseModel):
"""Get current PDF auto-download setting."""
return self._auto_download_pdfs
- def _dispatch_no_page_error(self, error_type: str, message: str) -> None:
- """Dispatch a standard 'no active page' error event."""
- self.event_bus.dispatch(
- BrowserErrorEvent(
- error_type=error_type,
- message=message,
- )
- )
-
# Import uuid7str for ID generation
try:
@@ -1952,3 +1702,24 @@ except ImportError:
def uuid7str() -> str:
return str(uuid.uuid4())
+
+
+# Fix Pydantic circular dependency for all watchdogs
+# This must be called after BrowserSession class is fully defined
+_watchdog_modules = [
+ 'browser_use.browser.crash_watchdog.CrashWatchdog',
+ 'browser_use.browser.downloads_watchdog.DownloadsWatchdog',
+ 'browser_use.browser.storage_state_watchdog.StorageStateWatchdog',
+ 'browser_use.browser.navigation_watchdog.NavigationWatchdog',
+ 'browser_use.browser.aboutblank_watchdog.AboutBlankWatchdog',
+ 'browser_use.browser.human_focus_watchdog.HumanFocusWatchdog',
+]
+
+for module_path in _watchdog_modules:
+ try:
+ module_name, class_name = module_path.rsplit('.', 1)
+ module = __import__(module_name, fromlist=[class_name])
+ watchdog_class = getattr(module, class_name)
+ watchdog_class.model_rebuild()
+ except Exception:
+ pass # Ignore if watchdog can't be imported or rebuilt
diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.py
index 1b4b51f70..3b7e2f79b 100644
--- a/browser_use/browser/storage_state_watchdog.py
+++ b/browser_use/browser/storage_state_watchdog.py
@@ -4,12 +4,11 @@ import asyncio
import json
import os
from pathlib import Path
-from typing import Any
-from weakref import WeakSet
+from typing import Any, ClassVar
-from bubus import EventBus
-from playwright.async_api import BrowserContext, Cookie, Page
-from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
+from bubus import BaseEvent
+from playwright.async_api import Cookie, Page
+from pydantic import Field, PrivateAttr
from browser_use.browser.events import (
BrowserStartedEvent,
@@ -21,60 +20,48 @@ from browser_use.browser.events import (
TabClosedEvent,
TabCreatedEvent,
)
+from browser_use.browser.watchdog_base import BaseWatchdog
from browser_use.utils import logger
-class StorageStateWatchdog(BaseModel):
+class StorageStateWatchdog(BaseWatchdog):
"""Monitors and persists browser storage state including cookies and localStorage."""
- model_config = ConfigDict(
- arbitrary_types_allowed=True,
- validate_assignment=True,
- extra='forbid',
- )
-
- event_bus: EventBus
- browser_session: Any # Avoid circular import
+ # Event contracts
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
+ BrowserStartedEvent,
+ BrowserStoppedEvent,
+ SaveStorageStateEvent,
+ LoadStorageStateEvent,
+ TabCreatedEvent,
+ TabClosedEvent,
+ ]
+ EMITS: ClassVar[list[type[BaseEvent]]] = [
+ StorageStateSavedEvent,
+ StorageStateLoadedEvent,
+ ]
+
+ # Configuration
auto_save_interval: float = Field(default=30.0) # Auto-save every 30 seconds
save_on_change: bool = Field(default=True) # Save immediately when cookies change
# Private state
- _browser_context: BrowserContext | None = PrivateAttr(default=None)
- _pages: WeakSet[Page] = PrivateAttr(default_factory=WeakSet)
_monitoring_task: asyncio.Task | None = PrivateAttr(default=None)
_last_cookie_state: list[Cookie] = PrivateAttr(default_factory=list)
_pending_save: bool = PrivateAttr(default=False)
_save_lock: asyncio.Lock = PrivateAttr(default_factory=asyncio.Lock)
- def __init__(self, event_bus: EventBus, browser_session: Any, **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(BrowserStartedEvent, self._handle_browser_started)
- self.event_bus.on(BrowserStoppedEvent, self._handle_browser_stopped)
- self.event_bus.on(SaveStorageStateEvent, self._handle_save_storage_state)
- self.event_bus.on(LoadStorageStateEvent, self._handle_load_storage_state)
- self.event_bus.on(TabCreatedEvent, self._handle_tab_created)
- self.event_bus.on(TabClosedEvent, self._handle_tab_closed)
-
- async def _handle_browser_started(self, event: BrowserStartedEvent) -> None:
+ async def on_BrowserStartedEvent(self, event: BrowserStartedEvent) -> None:
"""Start monitoring when browser starts."""
logger.info('[StorageStateWatchdog] Browser started, initializing storage monitoring')
- # Get browser context reference
- if hasattr(self.browser_session, '_browser_context'):
- self._browser_context = self.browser_session._browser_context
-
# Start monitoring
await self._start_monitoring()
# Automatically load storage state after browser start
self.event_bus.dispatch(LoadStorageStateEvent())
- async def _handle_browser_stopped(self, event: BrowserStoppedEvent) -> None:
+ async def on_BrowserStoppedEvent(self, event: BrowserStoppedEvent) -> None:
"""Stop monitoring and save state when browser stops."""
logger.info('[StorageStateWatchdog] Browser stopping, saving final storage state')
@@ -85,24 +72,23 @@ class StorageStateWatchdog(BaseModel):
# Stop monitoring
await self._stop_monitoring()
- self._browser_context = None
- self._pages.clear()
+ # No cleanup needed - browser context is managed by session
- async def _handle_tab_created(self, event: TabCreatedEvent) -> None:
+ async def on_TabCreatedEvent(self, event: TabCreatedEvent) -> None:
"""Monitor new tabs for storage changes."""
# Tab will be added when we detect it via browser context
pass
- async def _handle_tab_closed(self, event: TabClosedEvent) -> None:
+ async def on_TabClosedEvent(self, event: TabClosedEvent) -> None:
"""Stop monitoring closed tabs."""
# Tab will be removed automatically via WeakSet
pass
- async def _handle_save_storage_state(self, event: SaveStorageStateEvent) -> None:
+ async def on_SaveStorageStateEvent(self, event: SaveStorageStateEvent) -> None:
"""Handle storage state save request."""
await self._save_storage_state(event.path)
- async def _handle_load_storage_state(self, event: LoadStorageStateEvent) -> None:
+ async def on_LoadStorageStateEvent(self, event: LoadStorageStateEvent) -> None:
"""Handle storage state load request."""
await self._load_storage_state(event.path)
@@ -115,8 +101,8 @@ class StorageStateWatchdog(BaseModel):
logger.info('[StorageStateWatchdog] Started storage monitoring task')
# Set up page monitoring for existing pages
- if self._browser_context:
- for page in self._browser_context.pages:
+ if self.browser_session._browser_context:
+ for page in self.browser_session._browser_context.pages:
self._setup_page_monitoring(page)
async def _stop_monitoring(self) -> None:
@@ -131,8 +117,6 @@ class StorageStateWatchdog(BaseModel):
def _setup_page_monitoring(self, page: Page) -> None:
"""Set up storage change monitoring for a page."""
- self._pages.add(page)
-
# Monitor for cookie changes via response headers
page.on('response', lambda response: asyncio.create_task(self._check_for_cookie_changes(response)))
@@ -175,11 +159,11 @@ class StorageStateWatchdog(BaseModel):
async def _have_cookies_changed(self) -> bool:
"""Check if cookies have changed since last save."""
- if not self._browser_context:
+ if not self.browser_session._browser_context:
return False
try:
- current_cookies = await self._browser_context.cookies()
+ current_cookies = await self.browser_session._browser_context.cookies()
# Convert to comparable format, using .get() for optional fields
current_cookie_set = {
@@ -206,7 +190,7 @@ class StorageStateWatchdog(BaseModel):
async def _save_storage_state(self, path: str | None = None) -> None:
"""Save browser storage state to file."""
async with self._save_lock:
- if not self._browser_context:
+ if not self.browser_session._browser_context:
logger.warning('[StorageStateWatchdog] No browser context available for saving')
return
@@ -216,7 +200,7 @@ class StorageStateWatchdog(BaseModel):
try:
# Get current storage state
- storage_state = await self._browser_context.storage_state()
+ storage_state = await self.browser_session._browser_context.storage_state()
# Update our last known state
self._last_cookie_state = storage_state.get('cookies', []).copy()
@@ -267,7 +251,7 @@ class StorageStateWatchdog(BaseModel):
async def _load_storage_state(self, path: str | None = None) -> None:
"""Load browser storage state from file."""
- if not self._browser_context:
+ if not self.browser_session._browser_context:
logger.warning('[StorageStateWatchdog] No browser context available for loading')
return
@@ -276,13 +260,15 @@ class StorageStateWatchdog(BaseModel):
return
try:
- # Read the storage state file
- with open(str(load_path)) as f:
- storage = json.load(f)
+ # Read the storage state file asynchronously
+ import anyio
+
+ content = await anyio.Path(str(load_path)).read_text()
+ storage = json.loads(content)
# Apply cookies if present
if 'cookies' in storage and storage['cookies']:
- await self._browser_context.add_cookies(storage['cookies'])
+ await self.browser_session._browser_context.add_cookies(storage['cookies'])
self._last_cookie_state = storage['cookies'].copy()
logger.info(f'[StorageStateWatchdog] Added {len(storage["cookies"])} cookies from storage state')
@@ -291,12 +277,12 @@ class StorageStateWatchdog(BaseModel):
for origin in storage['origins']:
if 'localStorage' in origin:
for item in origin['localStorage']:
- await self._browser_context.add_init_script(f"""
+ await self.browser_session._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"""
+ await self.browser_session._browser_context.add_init_script(f"""
window.sessionStorage.setItem({json.dumps(item['name'])}, {json.dumps(item['value'])});
""")
logger.info(f'[StorageStateWatchdog] Applied localStorage/sessionStorage from {len(storage["origins"])} origins')
@@ -340,18 +326,18 @@ class StorageStateWatchdog(BaseModel):
async def get_current_cookies(self) -> list[Cookie]:
"""Get current cookies from browser context."""
- if not self._browser_context:
+ if not self.browser_session._browser_context:
return []
try:
- return await self._browser_context.cookies()
+ return await self.browser_session._browser_context.cookies()
except Exception as e:
logger.error(f'[StorageStateWatchdog] Failed to get cookies: {e}')
return []
async def add_cookies(self, cookies: list[Cookie]) -> None:
"""Add cookies to browser context."""
- if not self._browser_context:
+ if not self.browser_session._browser_context:
logger.warning('[StorageStateWatchdog] No browser context available for adding cookies')
return
@@ -385,8 +371,11 @@ class StorageStateWatchdog(BaseModel):
cookie_params.append(param)
- await self._browser_context.add_cookies(cookie_params) # type: ignore
+ await self.browser_session._browser_context.add_cookies(cookie_params) # type: ignore
self._pending_save = True
logger.info(f'[StorageStateWatchdog] Added {len(cookies)} cookies')
except Exception as e:
logger.error(f'[StorageStateWatchdog] Failed to add cookies: {e}')
+
+
+# Fix Pydantic circular dependency - this will be called from session.py after BrowserSession is defined
diff --git a/browser_use/browser/watchdog_base.py b/browser_use/browser/watchdog_base.py
new file mode 100644
index 000000000..ea3f62f5a
--- /dev/null
+++ b/browser_use/browser/watchdog_base.py
@@ -0,0 +1,101 @@
+"""Base watchdog class for browser monitoring components."""
+
+import inspect
+from typing import TYPE_CHECKING, ClassVar
+
+from bubus import BaseEvent, EventBus
+from playwright.async_api import Page
+from pydantic import BaseModel, ConfigDict
+
+from browser_use.utils import logger
+
+if TYPE_CHECKING:
+ from browser_use.browser.session import BrowserSession
+
+
+class BaseWatchdog(BaseModel):
+ """Base class for all browser watchdogs.
+
+ Watchdogs monitor browser state and emit events based on changes.
+ They automatically register event handlers based on method names.
+
+ Handler methods should be named: on_EventTypeName(self, event: EventTypeName)
+ """
+
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ validate_assignment=True,
+ extra='forbid',
+ )
+
+ # Class variables defining event contracts (optional, for documentation)
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [] # Events this watchdog listens to
+ EMITS: ClassVar[list[type[BaseEvent]]] = [] # Events this watchdog emits
+
+ # Core dependencies
+ event_bus: EventBus
+ browser_session: 'BrowserSession'
+
+ async def attach_to_session(self) -> None:
+ """Attach watchdog to its browser session and start monitoring.
+
+ This method handles event listener registration. The watchdog is already
+ bound to a browser session via self.browser_session from initialization.
+ """
+ # Register event handlers automatically based on method names
+ from browser_use.browser import events
+
+ event_classes = {}
+ for name in dir(events):
+ obj = getattr(events, name)
+ if inspect.isclass(obj) and issubclass(obj, BaseEvent) and obj is not BaseEvent:
+ event_classes[name] = obj
+
+ # Find all handler methods (on_EventName)
+ registered_events = set()
+ for method_name in dir(self):
+ if method_name.startswith('on_') and callable(getattr(self, method_name)):
+ # Extract event name from method name (on_EventName -> EventName)
+ event_name = method_name[3:] # Remove 'on_' prefix
+
+ if event_name in event_classes:
+ event_class = event_classes[event_name]
+
+ # ASSERTION: If LISTENS_TO is defined, enforce it
+ if self.LISTENS_TO:
+ assert event_class in self.LISTENS_TO, (
+ f'[{self.__class__.__name__}] Handler {method_name} listens to {event_name} '
+ f'but {event_name} is not declared in LISTENS_TO: {[e.__name__ for e in self.LISTENS_TO]}'
+ )
+
+ handler = getattr(self, method_name)
+ self.event_bus.on(event_class, handler)
+ registered_events.add(event_class)
+
+ # ASSERTION: If LISTENS_TO is defined, ensure all declared events have handlers
+ if self.LISTENS_TO:
+ missing_handlers = set(self.LISTENS_TO) - registered_events
+ if missing_handlers:
+ missing_names = [e.__name__ for e in missing_handlers]
+ logger.warning(
+ f'[{self.__class__.__name__}] LISTENS_TO declares {missing_names} '
+ f'but no handlers found (missing on_{"_, on_".join(missing_names)} methods)'
+ )
+
+ async def attach_to_page(self, page: Page) -> None:
+ """Set up monitoring for a specific page. Override in subclasses.
+
+ This method should be idempotent - safe to call multiple times on the same page.
+ """
+ pass
+
+ def safe_execute(self, func, *args, **kwargs):
+ """Execute function with automatic error logging."""
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ logger.error(f'[{self.__class__.__name__}] Error in {func.__name__}: {e}')
+ return None
+
+
+# Fix Pydantic circular dependency handling - subclasses should call this after BrowserSession is defined
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index b49650b88..8bb3ed1b9 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -91,9 +91,9 @@ class Controller(Generic[Context]):
if params.new_tab:
# Open in new tab (logic from open_tab function)
page = await browser_session.create_new_tab(params.url)
- tab_idx = browser_session.tabs.index(page)
+ tab_index = browser_session.tabs.index(page)
memory = f'Opened new tab with URL {params.url}'
- msg = f'🔗 Opened new tab #{tab_idx} with url {params.url}'
+ msg = f'🔗 Opened new tab #{tab_index} with url {params.url}'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=memory)
else:
@@ -147,7 +147,10 @@ class Controller(Generic[Context]):
# Element Interaction Actions
- @self.registry.action('Click element by index', param_model=ClickElementAction)
+ @self.registry.action(
+ 'Click element by index, set new_tab=True to open any resulting navigation in a new tab',
+ param_model=ClickElementAction,
+ )
async def click_element_by_index(params: ClickElementAction, browser_session: BrowserSession):
element_node = await browser_session.get_dom_element_by_index(params.index)
if element_node is None:
@@ -165,22 +168,32 @@ class Controller(Generic[Context]):
msg = None
try:
- download_path = await browser_session._click_element_node(element_node)
+ download_path = await browser_session._click_element_node(
+ element_node, expect_download=params.expect_download, new_tab=params.new_tab
+ )
if download_path:
emoji = '💾'
- msg = f'Downloaded file to {download_path}'
+ msg = f'Downloaded file to {download_path}' + (' (new tab)' if params.new_tab else '')
else:
emoji = '🖱️'
- msg = f'Clicked button with index {params.index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'
+ if params.new_tab:
+ msg = f'Clicked element {params.index} with new tab modifier: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'
+ else:
+ msg = f'Clicked button with index {params.index}: {element_node.get_all_text_till_next_clickable_element(max_depth=2)}'
- logger.info(f'{emoji} {msg}')
- logger.debug(f'Element xpath: {element_node.xpath}')
+ # Check for new tab opening (existing behavior for normal clicks, expected for new tab clicks)
if len(browser_session.tabs) > initial_pages:
new_tab_msg = 'New tab opened - switching to it'
- msg += f' - {new_tab_msg}'
+ if params.new_tab:
+ msg = f'Clicked element {params.index} and opened in new tab'
+ else:
+ msg += f' - {new_tab_msg}'
emoji = '🔗'
logger.info(f'{emoji} {new_tab_msg}')
await browser_session.switch_to_tab(-1)
+
+ logger.info(f'{emoji} {msg}')
+ logger.debug(f'Element xpath: {element_node.xpath}')
return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)
except Exception as e:
error_msg = str(e)
@@ -221,9 +234,7 @@ class Controller(Generic[Context]):
if not os.path.exists(params.path):
raise BrowserError(f'File {params.path} does not exist')
- file_upload_dom_el = await browser_session.find_file_upload_element_by_index(
- params.index, max_height=3, max_descendant_depth=3
- )
+ file_upload_dom_el = await browser_session.find_file_upload_element_by_index(params.index)
if file_upload_dom_el is None:
msg = f'No file upload element found at index {params.index}'
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index aa4512e32..06edc7e53 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -1,6 +1,6 @@
from typing import Generic, TypeVar
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
# Action Input Models
@@ -15,6 +15,8 @@ class GoToUrlAction(BaseModel):
class ClickElementAction(BaseModel):
index: int
+ new_tab: bool = Field(default=False, description='set True to open any resulting navigation in a new tab, False otherwise')
+ expect_download: bool = Field(default=False, description='set True if expecting a download, False otherwise')
class InputTextAction(BaseModel):
diff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.py
index 3d18c0dfb..238d0f660 100644
--- a/browser_use/mcp/server.py
+++ b/browser_use/mcp/server.py
@@ -589,8 +589,8 @@ class BrowserUseServer:
if new_tab:
page = await self.browser_session.create_new_tab(url)
- tab_idx = self.browser_session.tabs.index(page)
- return f'Opened new tab #{tab_idx} with URL: {url}'
+ tab_index = self.browser_session.tabs.index(page)
+ return f'Opened new tab #{tab_index} with URL: {url}'
else:
await self.browser_session.navigate_to(url)
return f'Navigated to: {url}'
@@ -622,8 +622,8 @@ class BrowserUseServer:
# Open link in new tab
page = await self.browser_session.create_new_tab(full_url)
- tab_idx = self.browser_session.tabs.index(page)
- return f'Clicked element {index} and opened in new tab #{tab_idx}'
+ tab_index = self.browser_session.tabs.index(page)
+ return f'Clicked element {index} and opened in new tab #{tab_index}'
else:
# For non-link elements, try Cmd/Ctrl+Click
page = await self.browser_session.get_current_page()
diff --git a/tests/ci/test_browser_session_crashed_page_recovery.py b/tests/ci/test_browser_session_crashed_page_recovery.py
index ffa5a2fad..fea17a173 100644
--- a/tests/ci/test_browser_session_crashed_page_recovery.py
+++ b/tests/ci/test_browser_session_crashed_page_recovery.py
@@ -307,7 +307,7 @@ class TestBrowserSessionRecovery:
await browser_session.navigate(httpserver.url_for('/normal'))
# Take a screenshot to verify browser works
- state2 = await browser_session._get_updated_state()
+ state2 = await browser_session.get_browser_state_with_recovery()
assert state2.screenshot is not None
assert len(state2.screenshot) > 100, 'Browser should still work after recovery'
@@ -498,41 +498,6 @@ class TestBrowserSessionRecovery:
print('✅ Browser crash correctly threw hard error without restarting')
- async def test_unresponsive_page_recovery_with_crashed_browser(self, browser_session: BrowserSession):
- """Test that _recover_unresponsive_page throws error if browser has crashed"""
- # Navigate to a page first
- await browser_session.navigate('about:blank')
-
- # Get the browser process PID
- browser_pid = browser_session.browser_pid
- assert browser_pid is not None
-
- print(f'1️⃣ Browser PID: {browser_pid}')
-
- # Force kill the browser process
- print('2️⃣ Killing browser process...')
- try:
- os.kill(browser_pid, signal.SIGKILL)
- except ProcessLookupError:
- pass
-
- # Wait for process to die
- await asyncio.sleep(1)
-
- # Try to recover unresponsive page - should raise RuntimeError
- print('3️⃣ Attempting page recovery on crashed browser...')
- with pytest.raises(RuntimeError) as exc_info:
- await browser_session._recover_unresponsive_page('test_method')
-
- # Verify error indicates browser crash
- error_msg = str(exc_info.value).lower()
- print(f'4️⃣ Got expected error: {error_msg}')
- assert 'browser process has crashed' in error_msg or 'browser connection lost' in error_msg, (
- f'Error should indicate browser crash, got: {error_msg}'
- )
-
- print('✅ Page recovery correctly detected crashed browser and threw error')
-
async def test_singleton_lock_error_throws_hard_error(self, browser_session: BrowserSession):
"""Test that SingletonLock errors throw hard error instead of restarting"""
# Create a conflicting user data directory scenario
diff --git a/tests/ci/test_browser_session_downloads.py b/tests/ci/test_browser_session_downloads.py
index c25851819..749065778 100644
--- a/tests/ci/test_browser_session_downloads.py
+++ b/tests/ci/test_browser_session_downloads.py
@@ -139,11 +139,12 @@ async def test_actual_download_detection(test_server, tmp_path):
downloads_path = tmp_path / 'downloads'
downloads_path.mkdir()
+ # Don't use user_data_dir - it seems to complicate downloads
browser_session = BrowserSession(
browser_profile=BrowserProfile(
headless=True,
downloads_path=str(downloads_path),
- user_data_dir=None, # Don't use persistent context for now
+ user_data_dir=None, # Use temporary context
)
)
@@ -169,44 +170,13 @@ async def test_actual_download_detection(test_server, tmp_path):
print(f'Auto download PDFs enabled: {browser_session._auto_download_pdfs}')
# Since the link has a download attribute, it will trigger a download, not navigation
- # We need to intercept the download event
+ # The downloads watchdog will handle the download automatically
start_time = time.time()
- # Listen for download event on the page
- download_started = False
- received_download = None
-
- async def handle_download(download):
- nonlocal download_started, received_download
- download_started = True
- received_download = download
- print(f'Download started: {download.suggested_filename}')
- # Try saving it manually for debugging
- try:
- # First, let's see the download state
- print(f'Download URL: {download.url}')
- print(f'Download suggested filename: {download.suggested_filename}')
-
- # Try to get the path where it's being downloaded
- path = await download.path()
- print(f'Download path from browser: {path}')
-
- # If path exists, copy it to our downloads dir
- if path and os.path.exists(path):
- import shutil
-
- dest_path = downloads_path / download.suggested_filename
- shutil.copy(path, dest_path)
- print(f'Copied download from {path} to {dest_path}')
- else:
- print(f'Download path does not exist: {path}')
- except Exception as e:
- print(f'Error handling download: {e}')
-
- page.on('download', handle_download)
-
- # Click the download link
- await browser_session._click_element_node(download_node)
+ # We don't need our own download handler - let the downloads watchdog handle it
+
+ # Click the download link with expect_download=True
+ await browser_session._click_element_node(download_node, expect_download=True)
duration = time.time() - start_time
print(f'Click completed in {duration:.2f}s')
@@ -217,7 +187,7 @@ async def test_actual_download_detection(test_server, tmp_path):
# Check if we're still on the same page (download attribute prevents navigation)
current_url = page.url
print(f'Current URL after click: {current_url}')
- print(f'Download started: {download_started}')
+ print('Download was handled by downloads watchdog')
# Wait a bit more
await asyncio.sleep(1.0)
diff --git a/tests/ci/test_browser_session_file_uploads.py b/tests/ci/test_browser_session_file_uploads.py
index 4e6e2493f..1befa29e3 100644
--- a/tests/ci/test_browser_session_file_uploads.py
+++ b/tests/ci/test_browser_session_file_uploads.py
@@ -290,9 +290,7 @@ class TestBrowserSessionFileUploads:
assert file_input is not None
# With very limited traversal, might not find it
- file_input_limited = await browser_session.find_file_upload_element_by_index(
- test_button_idx, max_height=0, max_descendant_depth=1
- )
+ file_input_limited = await browser_session.find_file_upload_element_by_index(test_button_idx)
# Could be None if file is too deep
# Test 2: Direct sibling should be found easily
@@ -303,7 +301,7 @@ class TestBrowserSessionFileUploads:
break
if direct_button_idx is not None:
- file_input = await browser_session.find_file_upload_element_by_index(direct_button_idx, max_height=1)
+ file_input = await browser_session.find_file_upload_element_by_index(direct_button_idx)
assert file_input is not None
assert file_input.attributes.get('id') == 'direct-file'
diff --git a/tests/ci/test_browser_session_ownership.py b/tests/ci/test_browser_session_ownership.py
index 393f96b24..4e802d1f7 100644
--- a/tests/ci/test_browser_session_ownership.py
+++ b/tests/ci/test_browser_session_ownership.py
@@ -31,12 +31,12 @@ class TestBrowserOwnership:
# Verify copy doesn't own the browser
assert copy1._owns_browser_resources is False
- assert copy1._original_browser_session is original
+ # Note: _original_browser_session is not implemented in current architecture
# Create another copy
copy2 = original.model_copy()
assert copy2._owns_browser_resources is False
- assert copy2._original_browser_session is original
+ # Note: _original_browser_session is not implemented in current architecture
async def test_agent_copies_dont_kill_browser(self, httpserver):
"""Test that when agents use a browser session, they don't kill the browser when garbage collected."""
@@ -160,10 +160,10 @@ class TestBrowserOwnership:
# Create a copy (simulating what Agent does)
copied_session = original_session.model_copy()
- copied_session.playwright = original_session.playwright
- copied_session.browser = original_session.browser
- copied_session.browser_context = original_session.browser_context
- copied_session.agent_current_page = original_session.agent_current_page
+ copied_session._playwright = original_session._playwright
+ copied_session._browser = original_session._browser
+ copied_session._browser_context = original_session._browser_context
+ # Note: agent_current_page is a property, not a directly assignable attribute
# Verify copy doesn't own the browser
assert copied_session._owns_browser_resources is False
@@ -201,11 +201,12 @@ class TestBrowserOwnership:
# Verify each copy doesn't own the browser
assert copy._owns_browser_resources is False
- assert copy._original_browser_session is original
+ # Note: _original_browser_session is not implemented in current architecture
+ # Note: _original_browser_session is not implemented in current architecture
# All copies should reference the same original
- for copy in copies:
- assert copy._original_browser_session is original
+ # for copy in copies:
+ # assert copy._original_browser_session is original
# Only the original owns the browser
assert original._owns_browser_resources is True
diff --git a/tests/ci/test_browser_session_recent_events.py b/tests/ci/test_browser_session_recent_events.py
index 5b26b164b..e8342fce9 100644
--- a/tests/ci/test_browser_session_recent_events.py
+++ b/tests/ci/test_browser_session_recent_events.py
@@ -179,7 +179,14 @@ class TestBrowserRecentEvents:
"""
httpserver.expect_request('/slow').respond_with_data(slow_html, content_type='text/html')
- httpserver.expect_request('/slow.js').respond_with_handler(lambda req: (time.sleep(5), 'slow')[1])
+
+ def slow_handler(req):
+ import time
+
+ time.sleep(5)
+ return Response('slow')
+
+ httpserver.expect_request('/slow.js').respond_with_handler(slow_handler)
httpserver.expect_request('/fast').respond_with_data(
'<html><head><title>Fast Page</title></head><body><h1>Fast page</h1></body></html>',
@@ -244,7 +251,14 @@ class TestBrowserRecentEvents:
"""
httpserver.expect_request('/malformed').respond_with_data(malformed_html, content_type='text/html')
- httpserver.expect_request('/slow.js').respond_with_handler(lambda req: (time.sleep(5), 'slow')[1])
+
+ def slow_handler(req):
+ import time
+
+ time.sleep(5)
+ return Response('slow')
+
+ httpserver.expect_request('/slow.js').respond_with_handler(slow_handler)
browser_session = BrowserSession(
browser_profile=BrowserProfile(
@@ -288,7 +302,14 @@ class TestBrowserRecentEvents:
f'<body><h1>Testing {timeout_seconds}s timeout</h1></body></html>',
content_type='text/html',
)
- httpserver.expect_request(f'/slow_{timeout_seconds}.js').respond_with_handler(lambda req: (time.sleep(10), 'slow')[1])
+
+ def very_slow_handler(req):
+ import time
+
+ time.sleep(10)
+ return Response('slow')
+
+ httpserver.expect_request(f'/slow_{timeout_seconds}.js').respond_with_handler(very_slow_handler)
browser_session = BrowserSession(
browser_profile=BrowserProfile(
diff --git a/tests/ci/test_browser_session_start.py b/tests/ci/test_browser_session_start.py
index a17322c7c..f411f1939 100644
--- a/tests/ci/test_browser_session_start.py
+++ b/tests/ci/test_browser_session_start.py
@@ -907,27 +907,27 @@ class TestBrowserSessionReusePatterns:
# Check cookies in each context - they should be separate
context1_cookies = await page1.context.cookies()
context2_cookies = await page2.context.cookies()
- print(f'Context1 cookies: {[c["name"] for c in context1_cookies]}')
- print(f'Context2 cookies: {[c["name"] for c in context2_cookies]}')
+ print(f'Context1 cookies: {[c.get("name", "unknown") for c in context1_cookies]}')
+ print(f'Context2 cookies: {[c.get("name", "unknown") for c in context2_cookies]}')
# Since these are separate browser contexts, they won't share cookies
# But let's verify the cookies exist in their respective contexts
# We need to get cookies for the specific domain
domain_cookies1 = await page1.context.cookies(base_url)
domain_cookies2 = await page2.context.cookies(base_url)
- print(f'Domain cookies window1: {[c["name"] for c in domain_cookies1]}')
- print(f'Domain cookies window2: {[c["name"] for c in domain_cookies2]}')
+ print(f'Domain cookies window1: {[c.get("name", "unknown") for c in domain_cookies1]}')
+ print(f'Domain cookies window2: {[c.get("name", "unknown") for c in domain_cookies2]}')
# Save storage state from window1
await window1.save_storage_state()
storage_state_1 = json.loads(auth_json_path.read_text())
- cookies_1 = {c['name'] for c in storage_state_1['cookies']}
+ cookies_1 = {c.get('name', 'unknown') for c in storage_state_1['cookies']}
print(f'Cookies saved from window1: {cookies_1}')
# Save storage state from window2 (this overwrites the file)
await window2.save_storage_state()
storage_state_2 = json.loads(auth_json_path.read_text())
- cookies_2 = {c['name'] for c in storage_state_2['cookies']}
+ cookies_2 = {c.get('name', 'unknown') for c in storage_state_2['cookies']}
print(f'Cookies saved from window2: {cookies_2}')
# Verify each window saved its own cookies
@@ -947,7 +947,7 @@ class TestBrowserSessionReusePatterns:
page3 = await window3.get_current_page()
await page3.goto(base_url) # Navigate to the domain
loaded_cookies = await page3.context.cookies()
- loaded_cookie_names = {c['name'] for c in loaded_cookies}
+ loaded_cookie_names = {c.get('name', 'unknown') for c in loaded_cookies}
print(f'Cookies loaded in new session: {loaded_cookie_names}')
# Should have the cookies from window2 (last save)
diff --git a/tests/ci/test_browser_session_storage_state.py b/tests/ci/test_browser_session_storage_state.py
index b180d6e33..5d6f39f69 100644
--- a/tests/ci/test_browser_session_storage_state.py
+++ b/tests/ci/test_browser_session_storage_state.py
@@ -197,7 +197,7 @@ class TestBrowserSessionStorageState:
context = session.browser_context
assert context is not None
cookies = await context.cookies()
- localhost_cookies = [c for c in cookies if c['domain'] in ['127.0.0.1', '.127.0.0.1']]
+ localhost_cookies = [c for c in cookies if c.get('domain', '') in ['127.0.0.1', '.127.0.0.1']]
assert len(localhost_cookies) == 0, f'Expected no 127.0.0.1 cookies, but found: {localhost_cookies}'
await session.kill()
@@ -219,7 +219,7 @@ class TestBrowserSessionStorageState:
context = session.browser_context
assert context is not None
cookies = await context.cookies()
- localhost_cookies = [c for c in cookies if c['domain'] in ['127.0.0.1', '.127.0.0.1']]
+ localhost_cookies = [c for c in cookies if c.get('domain', '') in ['127.0.0.1', '.127.0.0.1']]
assert len(localhost_cookies) == 0, f'Expected no 127.0.0.1 cookies, but found: {localhost_cookies}'
await session.kill()
diff --git a/tests/ci/test_browser_session_tab_management.py b/tests/ci/test_browser_session_tab_management.py
index e8be478b2..11ce36c0d 100644
--- a/tests/ci/test_browser_session_tab_management.py
+++ b/tests/ci/test_browser_session_tab_management.py
@@ -109,8 +109,10 @@ class TestTabManagement:
return result
async def _reset_tab_state(self, browser_session: BrowserSession, base_url: str):
- browser_session.human_current_page = None
- browser_session.agent_current_page = None
+ # Reset tab state by switching to first tab
+ from browser_use.browser.events import SwitchTabEvent
+
+ browser_session.event_bus.dispatch(SwitchTabEvent(tab_index=0))
# close all existing tabs
if browser_session.browser_context:
diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.py
index 94de1b428..b76903c14 100644
--- a/tests/ci/test_controller.py
+++ b/tests/ci/test_controller.py
@@ -1189,3 +1189,132 @@ class TestControllerIntegration:
# Test that get_minimal_state_summary always works
summary = await browser_session.get_minimal_state_summary()
assert summary is not None
+
+ async def test_click_element_new_tab(self, controller, browser_session, base_url, http_server):
+ """Test that click_element_by_index with new_tab=True opens links in new tabs."""
+ # Add route for new tab test page
+ http_server.expect_request('/newTab').respond_with_data(
+ """
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>New Tab Test</title>
+ </head>
+ <body>
+ <h1>New Tab Test</h1>
+ <a href="/page1" id="testLink">Open Page 1</a>
+ </body>
+ </html>
+ """,
+ content_type='text/html',
+ )
+
+ # Navigate to the new tab test page
+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/newTab', new_tab=False)}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: GoToUrlAction | None = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await asyncio.sleep(1) # Wait for page to load
+
+ # Count initial tabs
+ initial_tab_count = len(browser_session.tabs)
+
+ # Get the link element (assuming it will be at index 0)
+ # First get the browser state to see what elements are available
+ state = await browser_session.get_browser_state_with_recovery()
+
+ # Find the link element in the selector map
+ link_index = None
+ for index, element in state.selector_map.items():
+ if hasattr(element, 'tag_name') and element.tag_name == 'a':
+ link_index = index
+ break
+
+ assert link_index is not None, 'Could not find link element'
+
+ # Click the link with new_tab=True
+ click_action = {'click_element_by_index': ClickElementAction(index=link_index, new_tab=True)}
+
+ class ClickActionModel(ActionModel):
+ click_element_by_index: ClickElementAction | None = None
+
+ result = await controller.act(ClickActionModel(**click_action), browser_session)
+ await asyncio.sleep(1) # Wait for new tab to open
+
+ # Verify the result
+ assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
+
+ # Verify that a new tab was opened
+ final_tab_count = len(browser_session.tabs)
+ assert final_tab_count == initial_tab_count + 1, f'Expected {initial_tab_count + 1} tabs, got {final_tab_count}'
+
+ # Verify we switched to the new tab and it has the correct URL
+ current_page = await browser_session.get_current_page()
+ assert f'{base_url}/page1' in current_page.url
+
+ async def test_click_element_normal_vs_new_tab(self, controller, browser_session, base_url, http_server):
+ """Test that click_element_by_index behaves differently with new_tab=False vs new_tab=True."""
+ # Add route for comparison test page
+ http_server.expect_request('/comparison').respond_with_data(
+ """
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>Comparison Test</title>
+ </head>
+ <body>
+ <h1>Comparison Test</h1>
+ <a href="/page2" id="normalLink">Normal Link</a>
+ <a href="/page1" id="newTabLink">New Tab Link</a>
+ </body>
+ </html>
+ """,
+ content_type='text/html',
+ )
+
+ # Navigate to the comparison test page
+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/comparison', new_tab=False)}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: GoToUrlAction | None = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await asyncio.sleep(1)
+
+ initial_tab_count = len(browser_session.tabs)
+
+ # Get browser state and find link elements
+ state = await browser_session.get_browser_state_with_recovery()
+ link_indices = []
+ for index, element in state.selector_map.items():
+ if hasattr(element, 'tag_name') and element.tag_name == 'a':
+ link_indices.append(index)
+
+ assert len(link_indices) >= 2, 'Need at least 2 links for comparison test'
+
+ # Test normal click (new_tab=False) - should navigate in current tab
+ click_action_normal = {'click_element_by_index': ClickElementAction(index=link_indices[0], new_tab=False)}
+
+ class ClickActionModel(ActionModel):
+ click_element_by_index: ClickElementAction | None = None
+
+ result = await controller.act(ClickActionModel(**click_action_normal), browser_session)
+ await asyncio.sleep(1)
+
+ # Should still have same number of tabs
+ assert len(browser_session.tabs) == initial_tab_count
+
+ # Navigate back to comparison page for second test
+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+ await asyncio.sleep(1)
+
+ # Test new tab click (new_tab=True) - should open in new tab
+ click_action_new_tab = {'click_element_by_index': ClickElementAction(index=link_indices[1], new_tab=True)}
+ result = await controller.act(ClickActionModel(**click_action_new_tab), browser_session)
+ await asyncio.sleep(1)
+
+ # Should have one more tab
+ assert len(browser_session.tabs) == initial_tab_count + 1
diff --git a/tests/ci/test_navigation_events.py b/tests/ci/test_navigation_events.py
new file mode 100644
index 000000000..23f5b561d
--- /dev/null
+++ b/tests/ci/test_navigation_events.py
@@ -0,0 +1,531 @@
+"""Test navigation events are emitted properly in all cases."""
+
+import asyncio
+import time
+from typing import cast
+
+import pytest
+
+from browser_use.browser.events import (
+ BrowserStartedEvent,
+ ClickElementEvent,
+ NavigateToUrlEvent,
+ NavigationCompleteEvent,
+ NavigationStartedEvent,
+ StartBrowserEvent,
+ StopBrowserEvent,
+ TabCreatedEvent,
+)
+from browser_use.browser.profile import BrowserProfile
+from browser_use.browser.session import BrowserSession
+
+
+async def test_navigation_events_fast_page_load(httpserver):
+ """Test navigation events for page that loads easily/normally within 1s."""
+ # Set up a fast endpoint
+ httpserver.expect_request('/fast').respond_with_data(
+ '<html><head><title>Fast Page</title></head><body><h1>Fast Loading Page</h1></body></html>',
+ status=200,
+ content_type='text/html'
+ )
+ fast_url = httpserver.url_for('/fast')
+
+ profile = BrowserProfile(headless=True)
+ session = BrowserSession(browser_profile=profile)
+
+ # Track navigation events
+ navigation_started_events = []
+ navigation_complete_events = []
+ session.event_bus.on(NavigationStartedEvent, lambda e: navigation_started_events.append(e))
+ session.event_bus.on(NavigationCompleteEvent, lambda e: navigation_complete_events.append(e))
+
+ try:
+ # Start browser
+ await session.start()
+
+ # Navigate to fast page
+ start_time = time.time()
+ session.event_bus.dispatch(NavigateToUrlEvent(url=fast_url))
+
+ # Wait for navigation to complete
+ nav_complete: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+ )
+ end_time = time.time()
+
+ # Verify navigation completed quickly (within 1s)
+ assert (end_time - start_time) < 1.0, "Navigation should complete quickly"
+
+ # Verify NavigationStartedEvent was emitted
+ assert len(navigation_started_events) >= 1, "Should have NavigationStartedEvent"
+ nav_started = navigation_started_events[-1]
+ assert nav_started.url == fast_url
+ assert nav_started.tab_index >= 0
+
+ # Verify NavigationCompleteEvent was emitted with success
+ assert len(navigation_complete_events) >= 1, "Should have NavigationCompleteEvent"
+ assert nav_complete.url == fast_url
+ assert nav_complete.tab_index >= 0
+ assert nav_complete.status == 200, "Should have successful HTTP status"
+ assert nav_complete.error_message is None, "Should have no error message"
+ assert nav_complete.loading_status is None, "Should have no loading status issues"
+
+ finally:
+ await session.stop()
+
+
+async def test_navigation_events_slow_page_with_timeout(httpserver):
+ """Test navigation events for page that takes >10s to load and times out."""
+ # Set up a slow endpoint that takes longer than we want to wait
+ def slow_handler(request):
+ time.sleep(5.0) # 5 seconds - longer than our timeout
+ from werkzeug import Response
+ return Response('<html><body>Finally loaded</body></html>', status=200)
+
+ httpserver.expect_request('/slow').respond_with_handler(slow_handler)
+ slow_url = httpserver.url_for('/slow')
+
+ # Create profile with shorter timeout for faster testing
+ profile = BrowserProfile(
+ headless=True,
+ maximum_wait_page_load_time=2.0, # 2 second timeout for network monitoring
+ wait_for_network_idle_page_load_time=0.5 # 0.5 second network idle
+ )
+ session = BrowserSession(browser_profile=profile)
+
+ # Track navigation events
+ navigation_started_events = []
+ navigation_complete_events = []
+ session.event_bus.on(NavigationStartedEvent, lambda e: navigation_started_events.append(e))
+ session.event_bus.on(NavigationCompleteEvent, lambda e: navigation_complete_events.append(e))
+
+ try:
+ # Start browser
+ await session.start()
+
+ # Navigate to slow page
+ session.event_bus.dispatch(NavigateToUrlEvent(url=slow_url))
+
+ # Wait for navigation to timeout and complete with error
+ nav_complete: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
+ )
+
+ # Verify NavigationStartedEvent was emitted
+ assert len(navigation_started_events) >= 1, "Should have NavigationStartedEvent"
+ nav_started = navigation_started_events[-1]
+ assert nav_started.url == slow_url
+
+ # Verify NavigationCompleteEvent was emitted
+ assert len(navigation_complete_events) >= 1, "Should have NavigationCompleteEvent"
+ assert nav_complete.url == slow_url
+
+ # Either the navigation succeeded after timeout (page loaded) or it timed out
+ # Both are valid outcomes - what matters is that NavigationCompleteEvent was emitted
+ if nav_complete.error_message or nav_complete.loading_status:
+ # Navigation had issues (timeout/loading problems)
+ has_timeout_indicator = (
+ nav_complete.error_message and ('timeout' in nav_complete.error_message.lower() or
+ 'pending' in nav_complete.error_message.lower()) or
+ nav_complete.loading_status and ('aborted' in nav_complete.loading_status.lower() or
+ 'pending' in nav_complete.loading_status.lower() or
+ 'requests' in nav_complete.loading_status.lower())
+ )
+ print(f"Navigation had issues - error_message: '{nav_complete.error_message}', loading_status: '{nav_complete.loading_status}'")
+ assert has_timeout_indicator, (
+ f"Should indicate timeout/loading issues when navigation has problems. "
+ f"error_message='{nav_complete.error_message}', "
+ f"loading_status='{nav_complete.loading_status}'"
+ )
+ else:
+ # Navigation succeeded (slow but successful)
+ print("Navigation succeeded despite being slow")
+ assert nav_complete.status == 200, "Successful navigation should have HTTP 200"
+
+ finally:
+ await session.stop()
+
+
+async def test_navigation_events_history_pushstate(httpserver):
+ """Test that history.pushState/popState behavior and that clicking links produces NavigationCompleteEvent."""
+ # Set up a page with JavaScript that manipulates history and contains navigation links
+ html_content = '''
+ <html>
+ <head><title>History Test</title></head>
+ <body>
+ <h1>History and Navigation Test</h1>
+ <button id="push-btn" onclick="pushState()">Push State</button>
+ <button id="pop-btn" onclick="history.back()">Pop State</button>
+ <a id="same-tab-link" href="/target-page">Same Tab Link</a>
+ <a id="new-tab-link" href="/target-page" target="_blank">New Tab Link</a>
+ <div id="status">Initial state</div>
+ <script>
+ function pushState() {
+ history.pushState({page: 'new'}, 'New Page', '/new-path');
+ document.getElementById('status').textContent = 'Pushed new state';
+ }
+
+ window.addEventListener('popstate', function(event) {
+ document.getElementById('status').textContent = 'Popped state: ' + JSON.stringify(event.state);
+ });
+ </script>
+ </body>
+ </html>
+ '''
+
+ target_page = '''
+ <html>
+ <head><title>Target Page</title></head>
+ <body><h1>Target Page Loaded</h1></body>
+ </html>
+ '''
+
+ httpserver.expect_request('/history-test').respond_with_data(
+ html_content, status=200, content_type='text/html'
+ )
+ httpserver.expect_request('/target-page').respond_with_data(
+ target_page, status=200, content_type='text/html'
+ )
+
+ test_url = httpserver.url_for('/history-test')
+ target_url = httpserver.url_for('/target-page')
+
+ profile = BrowserProfile(headless=True)
+ session = BrowserSession(browser_profile=profile)
+
+ # Track navigation events
+ navigation_complete_events = []
+ tab_created_events = []
+ session.event_bus.on(NavigationCompleteEvent, lambda e: navigation_complete_events.append(e))
+ session.event_bus.on(TabCreatedEvent, lambda e: tab_created_events.append(e))
+
+ try:
+ # Start browser
+ await session.start()
+
+ # Navigate to the test page
+ session.event_bus.dispatch(NavigateToUrlEvent(url=test_url))
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+
+ # Clear previous events to focus on history and link events
+ navigation_complete_events.clear()
+ tab_created_events.clear()
+
+ # Get browser state to interact with the page
+ state = await session.get_browser_state_with_recovery()
+
+ # Test 1: history.pushState (should NOT trigger NavigationCompleteEvent)
+ push_button_found = False
+ for idx, element in state.selector_map.items():
+ if (hasattr(element, 'attributes') and
+ element.attributes.get('id') == 'push-btn'):
+ push_button_found = True
+ session.event_bus.dispatch(ClickElementEvent(index=idx))
+ break
+
+ assert push_button_found, "Should find push state button"
+
+ # Wait for pushState to execute
+ await asyncio.sleep(1.0)
+
+ # Verify history.pushState does NOT trigger NavigationCompleteEvent (expected behavior)
+ assert len(navigation_complete_events) == 0, "history.pushState should not trigger NavigationCompleteEvent"
+
+ # Test 2: Same tab link click (should trigger NavigationCompleteEvent)
+ state = await session.get_browser_state_with_recovery()
+ same_tab_link_found = False
+
+ for idx, element in state.selector_map.items():
+ if (hasattr(element, 'attributes') and
+ element.attributes.get('id') == 'same-tab-link'):
+ same_tab_link_found = True
+ session.event_bus.dispatch(ClickElementEvent(index=idx))
+ break
+
+ assert same_tab_link_found, "Should find same tab link"
+
+ # Wait for navigation to complete
+ nav_complete: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=10.0)
+ )
+
+ assert nav_complete.url == target_url, f"Should navigate to {target_url}"
+ assert nav_complete.error_message is None, "Link navigation should succeed"
+
+ # Test 3: New tab link click (may trigger TabCreatedEvent and/or NavigationCompleteEvent)
+ # Navigate back to main page first
+ session.event_bus.dispatch(NavigateToUrlEvent(url=test_url))
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+
+ # Clear events
+ navigation_complete_events.clear()
+ tab_created_events.clear()
+
+ state = await session.get_browser_state_with_recovery()
+ new_tab_link_found = False
+
+ for idx, element in state.selector_map.items():
+ if (hasattr(element, 'attributes') and
+ element.attributes.get('id') == 'new-tab-link'):
+ new_tab_link_found = True
+ # Use new_tab=True parameter to properly trigger new tab behavior
+ session.event_bus.dispatch(ClickElementEvent(index=idx, new_tab=True))
+ break
+
+ if new_tab_link_found:
+ # Wait for either new tab creation or navigation
+ await asyncio.sleep(2.0) # Give time for tab creation and navigation
+
+ # Should have either tab creation or navigation event (or both)
+ has_new_tab_activity = len(tab_created_events) > 0 or len(navigation_complete_events) > 0
+ assert has_new_tab_activity, "New tab link should trigger tab creation or navigation"
+
+ if navigation_complete_events:
+ nav_complete = navigation_complete_events[-1]
+ assert target_url in nav_complete.url or nav_complete.error_message is None, \
+ f"New tab navigation should succeed, got: {nav_complete.error_message}"
+
+ # Test 4: Verify that normal navigation still works after history manipulation
+ session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>After history test</h1>'))
+ nav_complete_final: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+ )
+
+ assert nav_complete_final.url == 'data:text/html,<h1>After history test</h1>'
+ assert nav_complete_final.error_message is None
+
+ finally:
+ await session.stop()
+
+
+async def test_navigation_events_link_clicks(httpserver):
+ """Test that clicking links (same tab and new tab) triggers NavigationCompleteEvent."""
+ # Set up pages with different types of links
+ main_page = '''
+ <html>
+ <head><title>Link Test</title></head>
+ <body>
+ <h1>Link Click Test</h1>
+ <a id="same-tab-link" href="/target-page">Same Tab Link</a>
+ <a id="new-tab-link" href="/target-page" target="_blank">New Tab Link</a>
+ <a id="js-navigation" href="#" onclick="window.location.href='/js-target'; return false;">JS Navigation</a>
+ </body>
+ </html>
+ '''
+
+ target_page = '''
+ <html>
+ <head><title>Target Page</title></head>
+ <body><h1>Target Page Loaded</h1></body>
+ </html>
+ '''
+
+ js_target_page = '''
+ <html>
+ <head><title>JS Target</title></head>
+ <body><h1>JavaScript Navigation Target</h1></body>
+ </html>
+ '''
+
+ httpserver.expect_request('/link-test').respond_with_data(main_page, status=200, content_type='text/html')
+ httpserver.expect_request('/target-page').respond_with_data(target_page, status=200, content_type='text/html')
+ httpserver.expect_request('/js-target').respond_with_data(js_target_page, status=200, content_type='text/html')
+
+ main_url = httpserver.url_for('/link-test')
+ target_url = httpserver.url_for('/target-page')
+ js_target_url = httpserver.url_for('/js-target')
+
+ profile = BrowserProfile(headless=True)
+ session = BrowserSession(browser_profile=profile)
+
+ # Track navigation and tab events
+ navigation_complete_events = []
+ tab_created_events = []
+ session.event_bus.on(NavigationCompleteEvent, lambda e: navigation_complete_events.append(e))
+ session.event_bus.on(TabCreatedEvent, lambda e: tab_created_events.append(e))
+
+ try:
+ # Start browser
+ await session.start()
+
+ # Navigate to the main page
+ session.event_bus.dispatch(NavigateToUrlEvent(url=main_url))
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+
+ # Clear events to focus on link clicks
+ navigation_complete_events.clear()
+
+ # Test 1: Same tab link click
+ state = await session.get_browser_state_with_recovery()
+ same_tab_link_found = False
+
+ for idx, element in state.selector_map.items():
+ if (hasattr(element, 'attributes') and
+ element.attributes.get('id') == 'same-tab-link'):
+ same_tab_link_found = True
+ session.event_bus.dispatch(ClickElementEvent(index=idx))
+ break
+
+ assert same_tab_link_found, "Should find same tab link"
+
+ # Wait for navigation to complete
+ nav_complete: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+ )
+
+ assert nav_complete.url == target_url, f"Should navigate to {target_url}"
+ assert nav_complete.error_message is None, "Link navigation should succeed"
+
+ # Test 2: New tab link click (if supported)
+ # Navigate back to main page first
+ session.event_bus.dispatch(NavigateToUrlEvent(url=main_url))
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+
+ # Clear events
+ navigation_complete_events.clear()
+ tab_created_events.clear()
+
+ state = await session.get_browser_state_with_recovery()
+ new_tab_link_found = False
+
+ for idx, element in state.selector_map.items():
+ if (hasattr(element, 'attributes') and
+ element.attributes.get('id') == 'new-tab-link'):
+ new_tab_link_found = True
+ session.event_bus.dispatch(ClickElementEvent(index=idx, new_tab=True))
+ break
+
+ if new_tab_link_found:
+ # Wait for either new tab creation or navigation
+ await asyncio.sleep(2.0) # Give time for tab creation and navigation
+
+ # Should have either tab creation or navigation event (or both)
+ has_new_tab_activity = len(tab_created_events) > 0 or len(navigation_complete_events) > 0
+ assert has_new_tab_activity, "New tab link should trigger tab creation or navigation"
+
+ if navigation_complete_events:
+ nav_complete = navigation_complete_events[-1]
+ assert target_url in nav_complete.url or nav_complete.error_message is None
+
+ # Test 3: JavaScript navigation
+ session.event_bus.dispatch(NavigateToUrlEvent(url=main_url))
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+
+ navigation_complete_events.clear()
+
+ state = await session.get_browser_state_with_recovery()
+ js_link_found = False
+
+ for idx, element in state.selector_map.items():
+ if (hasattr(element, 'attributes') and
+ element.attributes.get('id') == 'js-navigation'):
+ js_link_found = True
+ session.event_bus.dispatch(ClickElementEvent(index=idx))
+ break
+
+ if js_link_found:
+ # Wait for JavaScript navigation to complete
+ nav_complete = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+ )
+
+ assert nav_complete.url == js_target_url, "JS navigation should work"
+ assert nav_complete.error_message is None, "JS navigation should succeed"
+
+ finally:
+ await session.stop()
+
+
+async def test_navigation_timeout_event_dispatch():
+ """Test that NavigateToUrlEvent with timeout_ms properly dispatches NavigationCompleteEvent on timeout."""
+ profile = BrowserProfile(headless=True)
+ session = BrowserSession(browser_profile=profile)
+
+ # Track navigation events
+ navigation_complete_events = []
+ session.event_bus.on(NavigationCompleteEvent, lambda e: navigation_complete_events.append(e))
+
+ try:
+ # Start browser
+ await session.start()
+
+ # Navigate with a very short timeout to a valid but slow URL
+ session.event_bus.dispatch(NavigateToUrlEvent(
+ url='data:text/html,<h1>Should timeout</h1>', # Use a data URL that should work
+ timeout_ms=1 # 1ms timeout - should definitely timeout
+ ))
+
+ # Wait for navigation to timeout and complete with error
+ nav_complete: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+ )
+
+ # Verify NavigationCompleteEvent indicates timeout
+ assert nav_complete.error_message is not None, "Should have error message for timeout"
+ assert 'timed out' in nav_complete.error_message.lower(), f"Error should mention timed out: {nav_complete.error_message}"
+ assert nav_complete.loading_status is not None, "Should have loading status"
+ assert 'timeout' in nav_complete.loading_status.lower(), f"Loading status should mention timeout: {nav_complete.loading_status}"
+
+ # Verify specific timeout details
+ assert '1ms' in nav_complete.error_message, "Should mention the specific timeout duration"
+
+ finally:
+ await session.stop()
+
+
+async def test_navigation_error_recovery():
+ """Test that navigation errors are properly reported and don't break subsequent navigation."""
+ profile = BrowserProfile(headless=True)
+ session = BrowserSession(browser_profile=profile)
+
+ # Track navigation events
+ navigation_complete_events = []
+ session.event_bus.on(NavigationCompleteEvent, lambda e: navigation_complete_events.append(e))
+
+ try:
+ # Start browser
+ await session.start()
+
+ # Try to navigate to invalid URL
+ session.event_bus.dispatch(NavigateToUrlEvent(url='invalid://not-a-real-url'))
+
+ # Wait for navigation to fail
+ nav_complete: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+ )
+
+ # Verify NavigationCompleteEvent indicates error
+ assert nav_complete.error_message is not None, "Should have error message for invalid URL"
+ assert nav_complete.url == 'invalid://not-a-real-url'
+
+ # Clear events
+ navigation_complete_events.clear()
+
+ # Verify that subsequent navigation still works
+ session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>Recovery Test</h1>'))
+
+ nav_complete_recovery: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent,
+ await session.event_bus.expect(NavigationCompleteEvent, timeout=5.0)
+ )
+
+ # Verify recovery navigation succeeded
+ assert nav_complete_recovery.url == 'data:text/html,<h1>Recovery Test</h1>'
+ assert nav_complete_recovery.error_message is None, "Recovery navigation should succeed"
+
+ finally:
+ await session.stop()
\ No newline at end of file
diff --git a/tests/ci/test_watchdog.py b/tests/ci/test_watchdog.py
index 4d4096596..345a0b133 100644
--- a/tests/ci/test_watchdog.py
+++ b/tests/ci/test_watchdog.py
@@ -2,6 +2,7 @@
import asyncio
import time
+from typing import cast
import pytest
@@ -9,116 +10,60 @@ from browser_use.browser.events import (
BrowserErrorEvent,
BrowserStartedEvent,
BrowserStoppedEvent,
- CreateTabEvent,
NavigateToUrlEvent,
NavigationCompleteEvent,
- PageCrashedEvent,
StartBrowserEvent,
StopBrowserEvent,
TabCreatedEvent,
)
from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
+from browser_use.utils import logger
@pytest.mark.asyncio
-async def test_watchdog_network_timeout(httpserver):
+async def test_watchdog_network_timeout():
"""Test that watchdog detects network timeouts by monitoring actual network requests."""
- # Set up a slow endpoint (sync handler that blocks)
- def slow_handler(request):
- time.sleep(2.0) # Delay longer than timeout
- from werkzeug import Response
-
- return Response('Slow response', status=200)
-
- httpserver.expect_request('/slow').respond_with_handler(slow_handler)
- slow_url = httpserver.url_for('/slow')
-
- # Create browser with short network timeout
+ # Create browser session
profile = BrowserProfile(headless=True)
session = BrowserSession(browser_profile=profile)
- # Track error events
- error_events = []
- session.event_bus.on(BrowserErrorEvent, lambda e: error_events.append(e))
-
- try:
- # Start browser
- await session.start()
-
- # Configure watchdog for quick timeout detection
- if session._watchdog:
- session._watchdog.network_timeout_seconds = 0.5
- session._watchdog.check_interval_seconds = 0.1
-
- # Navigate to slow endpoint - this will create real network requests
- navigate_event = session.event_bus.dispatch(NavigateToUrlEvent(url=slow_url, wait_until='networkidle'))
-
- # Wait for network timeout error event
- timeout_error = None
- for _ in range(30): # Check for 3 seconds
- await asyncio.sleep(0.1)
- timeout_errors = [e for e in error_events if e.error_type == 'NetworkTimeout']
- if timeout_errors:
- timeout_error = timeout_errors[0]
- break
-
- assert timeout_error is not None, (
- f'NetworkTimeout event was not emitted within 3 seconds. Got {len(error_events)} error events'
- )
- assert 'slow' in timeout_error.details['url']
- assert timeout_error.details['elapsed_seconds'] >= 0.5
-
- finally:
- await session.stop()
-
-
-async def test_watchdog_page_crash_detection():
- """Test that watchdog detects page crashes using CDP crash simulation."""
- profile = BrowserProfile(headless=True)
- session = BrowserSession(browser_profile=profile)
-
- # Track events
- crash_events = []
- error_events = []
- session.event_bus.on(PageCrashedEvent, lambda e: crash_events.append(e))
- session.event_bus.on(BrowserErrorEvent, lambda e: error_events.append(e))
-
try:
- # Start browser
+ # Start browser using event system
session.event_bus.dispatch(StartBrowserEvent())
- await session.event_bus.expect(BrowserStartedEvent, timeout=5.0)
-
- # Create a new tab
- session.event_bus.dispatch(CreateTabEvent(url='about:blank'))
-
- # Wait for tab created event
- tab_created = await session.event_bus.expect(TabCreatedEvent, timeout=2.0)
-
- # Get the created page
- pages = session.tabs
- target_page = pages[-1] if len(pages) > 1 else pages[0]
-
- # Directly simulate page crash since CDP Page.crash isn't available in test environment
- if session._watchdog:
- await session._watchdog._on_page_crash(target_page)
-
- # Wait for crash event to be processed
- await asyncio.sleep(0.5)
-
- # Check crash events
- assert len(crash_events) >= 1, f'Expected crash events but got {len(crash_events)}'
- assert crash_events[0].error == 'Page crashed unexpectedly'
-
- # Check error events
- page_crash_errors = [e for e in error_events if e.error_type == 'PageCrash']
- assert len(page_crash_errors) >= 1, 'No PageCrash BrowserErrorEvent was emitted'
- assert 'blank' in page_crash_errors[0].message
+ await session.event_bus.expect(BrowserStartedEvent, timeout=10.0)
+
+ logger.info('[TEST] Browser started, configuring watchdog timeout')
+
+ # Configure crash watchdog with very short timeout for testing
+ if hasattr(session, '_crash_watchdog') and session._crash_watchdog:
+ session._crash_watchdog.network_timeout_seconds = 1.0 # Very short timeout
+ session._crash_watchdog.check_interval_seconds = 0.2 # Check frequently
+
+ # Try to navigate to a non-existent slow server that will hang
+ # This will create a real network request that will timeout
+ slow_url = 'http://192.0.2.1:8080/timeout-test' # RFC5737 TEST-NET-1 - non-routable
+ logger.info(f'[TEST] Navigating to non-routable URL via events: {slow_url}')
+ session.event_bus.dispatch(NavigateToUrlEvent(url=slow_url))
+
+ # Wait for the network timeout error via event bus
+ logger.info('[TEST] Waiting for NetworkTimeout event via event bus...')
+ timeout_error = cast(BrowserErrorEvent, await session.event_bus.expect(
+ BrowserErrorEvent,
+ predicate=lambda e: cast(BrowserErrorEvent, e).error_type == 'NetworkTimeout',
+ timeout=5.0
+ ))
+
+ # Verify the timeout event details
+ assert 'timeout-test' in timeout_error.details['url']
+ assert timeout_error.details['elapsed_seconds'] >= 0.8 # Should be at least close to our timeout
+ assert timeout_error.message.startswith('Network request timed out after')
+
+ logger.info(f'[TEST] Successfully detected network timeout: {timeout_error.message}')
finally:
- # Stop browser
+ # Stop browser using event system
session.event_bus.dispatch(StopBrowserEvent())
await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)
@@ -136,9 +81,8 @@ async def test_watchdog_browser_disconnect():
# Wait for browser to be fully started
await session.event_bus.expect(BrowserStartedEvent, timeout=5.0)
- # Configure watchdog for faster detection
- if session._watchdog:
- session._watchdog.check_interval_seconds = 0.1
+ # Browser disconnection detection is now handled by the crash watchdog
+ # No configuration needed
# Mock browser disconnection by overriding is_connected
# This simulates what would happen if the browser process crashed
@@ -148,8 +92,13 @@ async def test_watchdog_browser_disconnect():
try:
# Wait for watchdog to detect disconnection
- disconnect_error = await session.event_bus.expect(
- BrowserErrorEvent, predicate=lambda e: e.error_type == 'BrowserDisconnected', timeout=2.0
+ disconnect_error: BrowserErrorEvent = cast(
+ BrowserErrorEvent,
+ await session.event_bus.expect(
+ BrowserErrorEvent,
+ predicate=lambda e: cast(BrowserErrorEvent, e).error_type == 'BrowserDisconnected',
+ timeout=2.0,
+ ),
)
assert 'disconnected unexpectedly' in disconnect_error.message
finally:
@@ -175,11 +124,13 @@ async def test_watchdog_starts_and_stops_with_session():
session.event_bus.dispatch(StartBrowserEvent())
# Wait for browser started event
- started_event = await session.event_bus.expect(BrowserStartedEvent, timeout=5.0)
+ started_event: BrowserStartedEvent = cast(
+ BrowserStartedEvent, await session.event_bus.expect(BrowserStartedEvent, timeout=5.0)
+ )
assert started_event.cdp_url is not None
# Create a test page to ensure watchdog is monitoring something
- session.event_bus.dispatch(CreateTabEvent(url='about:blank'))
+ session.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))
# Wait for tab created event
await session.event_bus.expect(TabCreatedEvent, timeout=2.0)
@@ -188,7 +139,9 @@ async def test_watchdog_starts_and_stops_with_session():
session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>Test</h1>'))
# Wait for navigation to complete successfully (proves watchdog isn't interfering)
- nav_complete = await session.event_bus.expect(NavigationCompleteEvent, timeout=2.0)
+ nav_complete: NavigationCompleteEvent = cast(
+ NavigationCompleteEvent, await session.event_bus.expect(NavigationCompleteEvent, timeout=2.0)
+ )
assert nav_complete.url == 'data:text/html,<h1>Test</h1>'
assert nav_complete.error_message is None
@@ -196,5 +149,110 @@ async def test_watchdog_starts_and_stops_with_session():
session.event_bus.dispatch(StopBrowserEvent())
# Wait for browser stopped event
- stopped_event = await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)
+ stopped_event: BrowserStoppedEvent = cast(
+ BrowserStoppedEvent, await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)
+ )
assert stopped_event.reason is not None
+
+
+async def test_navigation_watchdog_tab_created_events():
+ """Test that the NavigationWatchdog properly emits TabCreatedEvent when pages are added."""
+ profile = BrowserProfile(headless=True)
+ session = BrowserSession(browser_profile=profile)
+
+ # Track TabCreatedEvents
+ tab_created_events = []
+ session.event_bus.on(TabCreatedEvent, lambda e: tab_created_events.append(e))
+
+ try:
+ # Start browser
+ session.event_bus.dispatch(StartBrowserEvent())
+ await session.event_bus.expect(BrowserStartedEvent, timeout=5.0)
+
+ # Verify navigation watchdog was created
+ assert hasattr(session, '_navigation_watchdog'), 'NavigationWatchdog should be created'
+ assert session._navigation_watchdog is not None, 'NavigationWatchdog should not be None'
+
+ # Create first tab - should emit TabCreatedEvent
+ session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>Tab 1</h1>', new_tab=True))
+
+ # Wait for first TabCreatedEvent
+ first_event: TabCreatedEvent = cast(TabCreatedEvent, await session.event_bus.expect(TabCreatedEvent, timeout=3.0))
+ # The first event might be for about:blank or the target URL depending on timing
+ assert first_event.tab_index >= 0
+ assert isinstance(first_event.url, str)
+
+ # Create second tab - should emit another TabCreatedEvent
+ session.event_bus.dispatch(NavigateToUrlEvent(url='data:text/html,<h1>Tab 2</h1>', new_tab=True))
+
+ # Wait for second TabCreatedEvent
+ second_event: TabCreatedEvent = cast(TabCreatedEvent, await session.event_bus.expect(TabCreatedEvent, timeout=3.0))
+ assert second_event.tab_index >= 0
+ assert isinstance(second_event.url, str)
+
+ # Verify we have at least 2 TabCreatedEvents
+ assert len(tab_created_events) >= 2, f'Expected at least 2 TabCreatedEvents, got {len(tab_created_events)}'
+
+ # Verify the events have different tab indices (unless they're reusing the same tab)
+ unique_tab_indexes = {event.tab_index for event in tab_created_events}
+ assert len(unique_tab_indexes) >= 1, 'Should have at least one unique tab index'
+
+ finally:
+ # Stop browser
+ session.event_bus.dispatch(StopBrowserEvent())
+ await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)
+
+
+async def test_navigation_watchdog_security_enforcement():
+ """Test that the NavigationWatchdog enforces allowed_domains security."""
+ # Create a profile with restricted domains
+ from browser_use.browser.profile import BrowserProfile
+
+ profile = BrowserProfile(
+ headless=True,
+ allowed_domains=['example.com', 'httpbin.org'], # Only allow these domains
+ )
+ session = BrowserSession(browser_profile=profile)
+
+ # Track BrowserErrorEvents
+ error_events = []
+ session.event_bus.on(BrowserErrorEvent, lambda e: error_events.append(e))
+
+ try:
+ # Start browser
+ session.event_bus.dispatch(StartBrowserEvent())
+ await session.event_bus.expect(BrowserStartedEvent, timeout=5.0)
+
+ # Verify navigation watchdog was created and has security check
+ assert hasattr(session, '_navigation_watchdog'), 'NavigationWatchdog should be created'
+ assert session._navigation_watchdog is not None, 'NavigationWatchdog should not be None'
+
+ # Test that allowed domains work
+ allowed_url = 'https://httpbin.org/get'
+ allowed = session._navigation_watchdog._is_url_allowed(allowed_url)
+ assert allowed, f'Should allow {allowed_url}'
+
+ # Test that disallowed domains are blocked
+ disallowed_url = 'https://malicious-site.com/bad'
+ disallowed = session._navigation_watchdog._is_url_allowed(disallowed_url)
+ assert not disallowed, f'Should block {disallowed_url}'
+
+ # Test internal URLs are always allowed
+ internal_urls = ['about:blank', 'chrome://newtab/', 'chrome://new-tab-page/']
+ for url in internal_urls:
+ assert session._navigation_watchdog._is_url_allowed(url), f'Should allow internal URL: {url}'
+
+ # Test glob patterns work
+ profile_with_glob = BrowserProfile(headless=True, allowed_domains=['*.github.com'])
+ session._navigation_watchdog.browser_session.browser_profile = profile_with_glob
+
+ assert session._navigation_watchdog._is_url_allowed('https://api.github.com/repos'), 'Should allow subdomain'
+ assert session._navigation_watchdog._is_url_allowed('https://github.com/user'), 'Should allow main domain'
+ assert not session._navigation_watchdog._is_url_allowed('https://evil.com/github.com'), 'Should block non-matching domain'
+
+ finally:
+ # Stop browser
+ session.event_bus.dispatch(StopBrowserEvent())
+ await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)