Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
add local browser watchdog
Nick Sweetingd8ffff64916e
diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.pyindex dbca95ef2..39ba7d9a4 100644--- a/browser_use/browser/crash_watchdog.py+++ b/browser_use/browser/crash_watchdog.py@@ -12,7 +12,6 @@ from pydantic import Field, PrivateAttrfrom browser_use.browser.events import (BrowserConnectedEvent,BrowserErrorEvent,- BrowserLaunchedEvent,BrowserStoppedEvent,PageCrashedEvent,)@@ -40,7 +39,6 @@ class CrashWatchdog(BaseWatchdog):# Event contractsLISTENS_TO: ClassVar[list[type[BaseEvent]]] = [BrowserConnectedEvent,- BrowserLaunchedEvent,BrowserStoppedEvent,]EMITS: ClassVar[list[type[BaseEvent]]] = [@@ -53,25 +51,15 @@ class CrashWatchdog(BaseWatchdog):check_interval_seconds: float = Field(default=1.0)# Private state- _browser_pid: int | None = PrivateAttr(default=None)_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- async def on_BrowserLaunchedEvent(self, event: BrowserLaunchedEvent) -> None:- """Store browser PID when local browser is launched."""- logger.info(f'[CrashWatchdog] Browser launched event received, storing PID: {event.browser_pid}')- self._browser_pid = event.browser_pid-async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:"""Start monitoring when browser is connected."""logger.info('[CrashWatchdog] Browser connected event received, beginning monitoring')- # Get browser pid from session if not already set by BrowserLaunchedEvent- if not self._browser_pid:- self._browser_pid = self.browser_session.browser_pid-await self._start_monitoring()logger.info(f'[CrashWatchdog] Monitoring task started: {self._monitoring_task and not self._monitoring_task.done()}')diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 2a08da097..70e956aec 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -103,13 +103,6 @@ class BrowserLaunchEvent(BaseEvent[dict[str, str]]):pass-class BrowserLaunchedEvent(BaseEvent):- """Local browser process has been launched successfully."""-- cdp_url: str- browser_pid: int--class BrowserKillEvent(BaseEvent):"""Kill local browser subprocess."""diff --git a/browser_use/browser/local.py b/browser_use/browser/local.pyindex e226e47a3..01772372a 100644--- a/browser_use/browser/local.py+++ b/browser_use/browser/local.py@@ -39,7 +39,7 @@ class LocalBrowserHelpers:for attempt in range(max_retries):try:# Get launch args from profile- launch_args = profile.args_for_browser_launch()+ launch_args = profile.get_args()# Add debugging portdebug_port = LocalBrowserHelpers.find_free_port()diff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.pynew file mode 100644index 000000000..39b5ae011--- /dev/null+++ b/browser_use/browser/local_browser_watchdog.py@@ -0,0 +1,292 @@+"""Local browser watchdog for managing browser subprocess lifecycle."""++import asyncio+import shutil+import tempfile+from pathlib import Path+from typing import TYPE_CHECKING, Any, ClassVar++import psutil+from bubus import BaseEvent+from playwright.async_api import async_playwright+from pydantic import PrivateAttr++from browser_use.browser.events import (+ BrowserKillEvent,+ BrowserLaunchEvent,+ BrowserStopEvent,+)+from browser_use.browser.watchdog_base import BaseWatchdog+from browser_use.utils import logger++if TYPE_CHECKING:+ pass+++class LocalBrowserWatchdog(BaseWatchdog):+ """Manages local browser subprocess lifecycle."""++ # Events this watchdog listens to+ LISTENS_TO: ClassVar[list[type[BaseEvent[Any]]]] = [+ BrowserLaunchEvent,+ BrowserKillEvent,+ BrowserStopEvent,+ ]++ # Events this watchdog emits+ EMITS: ClassVar[list[type[BaseEvent[Any]]]] = []++ # Private state for subprocess management+ _subprocess: psutil.Process | None = PrivateAttr(default=None)+ _owns_browser_resources: bool = PrivateAttr(default=True)+ _temp_dirs_to_cleanup: list[Path] = PrivateAttr(default_factory=list)+ _original_user_data_dir: str | None = PrivateAttr(default=None)++ async def on_BrowserLaunchEvent(self, event: BrowserLaunchEvent) -> dict[str, str]:+ """Launch a local browser process."""+ try:+ logger.info(+ f'[LocalBrowserWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}, launching local browser'+ )++ process, cdp_url = await self._launch_browser()+ self._subprocess = process++ logger.info(f'[LocalBrowserWatchdog] Browser launched successfully at {cdp_url}, PID: {process.pid}')+ return {'cdp_url': cdp_url}+ except Exception as e:+ logger.error(f'[LocalBrowserWatchdog] Exception in on_BrowserLaunchEvent: {e}', exc_info=True)+ raise++ async def on_BrowserKillEvent(self, event: BrowserKillEvent) -> None:+ """Kill the local browser subprocess."""+ logger.info('[LocalBrowserWatchdog] Killing local browser process')++ if self._subprocess:+ await self._cleanup_process(self._subprocess)+ self._subprocess = None++ # Clean up temp directories if any were created+ for temp_dir in self._temp_dirs_to_cleanup:+ self._cleanup_temp_dir(temp_dir)+ self._temp_dirs_to_cleanup.clear()++ # Restore original user_data_dir if it was modified+ if self._original_user_data_dir is not None:+ self.browser_session.browser_profile.user_data_dir = self._original_user_data_dir+ self._original_user_data_dir = None++ logger.info('[LocalBrowserWatchdog] Browser cleanup completed')++ async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:+ """Listen for BrowserStopEvent and dispatch BrowserKillEvent without awaiting it."""+ if self.browser_session.is_local and self._subprocess:+ logger.info('[LocalBrowserWatchdog] BrowserStopEvent received, dispatching BrowserKillEvent')+ # Dispatch BrowserKillEvent without awaiting so it gets processed after all BrowserStopEvent handlers+ self.event_bus.dispatch(BrowserKillEvent())++ async def _launch_browser(self, max_retries: int = 3) -> tuple[psutil.Process, str]:+ """Launch browser process and return (process, cdp_url).++ Handles launch errors by falling back to temporary directories if needed.++ Returns:+ Tuple of (psutil.Process, cdp_url)+ """+ # Keep track of original user_data_dir to restore if needed+ profile = self.browser_session.browser_profile+ self._original_user_data_dir = str(profile.user_data_dir) if profile.user_data_dir else None+ self._temp_dirs_to_cleanup = []++ for attempt in range(max_retries):+ try:+ # Get launch args from profile+ launch_args = profile.get_args()++ # Add debugging port+ debug_port = self._find_free_port()+ launch_args.extend(+ [+ f'--remote-debugging-port={debug_port}',+ ]+ )++ # Get browser executable from playwright+ playwright = await async_playwright().start()+ try:+ # Use custom executable if provided, otherwise use playwright's+ if profile.executable_path:+ browser_path = profile.executable_path+ else:+ browser_path = playwright.chromium.executable_path++ # Launch browser subprocess directly+ subprocess = await asyncio.create_subprocess_exec(+ browser_path,+ *launch_args,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )++ # Convert to psutil.Process+ process = psutil.Process(subprocess.pid)++ # Wait for CDP to be ready and get the URL+ cdp_url = await self._wait_for_cdp_url(debug_port)++ # Success! Clean up any temp dirs we created but didn't use+ for tmp_dir in self._temp_dirs_to_cleanup:+ try:+ shutil.rmtree(tmp_dir, ignore_errors=True)+ except Exception:+ pass++ return process, cdp_url++ finally:+ # Clean up playwright instance+ await playwright.stop()++ except Exception as e:+ error_str = str(e).lower()++ # Check if this is a user_data_dir related error+ if any(err in error_str for err in ['singletonlock', 'user data directory', 'cannot create', 'already in use']):+ logger.warning(f'Browser launch failed (attempt {attempt + 1}/{max_retries}): {e}')++ if attempt < max_retries - 1:+ # Create a temporary directory for next attempt+ tmp_dir = Path(tempfile.mkdtemp(prefix='browseruse-tmp-'))+ self._temp_dirs_to_cleanup.append(tmp_dir)++ # Update profile to use temp directory+ profile.user_data_dir = str(tmp_dir)+ logger.info(f'Retrying with temporary user_data_dir: {tmp_dir}')++ # Small delay before retry+ await asyncio.sleep(0.5)+ continue++ # Not a recoverable error or last attempt failed+ # Restore original user_data_dir before raising+ if self._original_user_data_dir is not None:+ profile.user_data_dir = self._original_user_data_dir++ # Clean up any temp dirs we created+ for tmp_dir in self._temp_dirs_to_cleanup:+ try:+ shutil.rmtree(tmp_dir, ignore_errors=True)+ except Exception:+ pass++ raise++ # Should not reach here, but just in case+ if self._original_user_data_dir is not None:+ profile.user_data_dir = self._original_user_data_dir+ raise RuntimeError(f'Failed to launch browser after {max_retries} attempts')++ @staticmethod+ def _find_free_port() -> int:+ """Find a free port for the debugging interface."""+ import socket++ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(('127.0.0.1', 0))+ s.listen(1)+ port = s.getsockname()[1]+ return port++ @staticmethod+ async def _wait_for_cdp_url(port: int, timeout: float = 30) -> str:+ """Wait for the browser to start and return the CDP URL."""+ import aiohttp++ start_time = asyncio.get_event_loop().time()++ while asyncio.get_event_loop().time() - start_time < timeout:+ try:+ async with aiohttp.ClientSession() as session:+ async with session.get(f'http://localhost:{port}/json/version') as resp:+ if resp.status == 200:+ # Chrome is ready+ return f'http://localhost:{port}/'+ else:+ # Chrome is starting up and returning 502/500 errors+ await asyncio.sleep(0.1)+ except Exception:+ # Connection error - Chrome might not be ready yet+ await asyncio.sleep(0.1)++ raise TimeoutError(f'Browser did not start within {timeout} seconds')++ @staticmethod+ async def _cleanup_process(process: psutil.Process) -> None:+ """Clean up browser process.++ Args:+ process: psutil.Process to terminate+ """+ if not process:+ return++ try:+ # Try graceful shutdown first+ process.terminate()+ # Wait up to 5 seconds for process to exit+ process.wait(timeout=5)+ except psutil.TimeoutExpired:+ # Force kill if needed+ try:+ process.kill()+ except psutil.NoSuchProcess:+ pass+ except psutil.NoSuchProcess:+ # Process already gone+ pass++ @staticmethod+ def _cleanup_temp_dir(temp_dir: Path | str) -> None:+ """Clean up temporary directory.++ Args:+ temp_dir: Path to temporary directory to remove+ """+ if not temp_dir:+ return++ try:+ temp_path = Path(temp_dir)+ # Only remove if it's actually a temp directory we created+ if 'browseruse-tmp-' in str(temp_path):+ shutil.rmtree(temp_path, ignore_errors=True)+ except Exception as e:+ logger.debug(f'Failed to cleanup temp dir {temp_dir}: {e}')++ @property+ def browser_pid(self) -> int | None:+ """Get the browser process ID."""+ if self._subprocess:+ return self._subprocess.pid+ return None++ @staticmethod+ async def get_browser_pid_via_cdp(browser) -> int | None:+ """Get the browser process ID via CDP SystemInfo.getProcessInfo.++ Args:+ browser: Playwright Browser instance++ Returns:+ Process ID or None if failed+ """+ try:+ cdp_session = await browser.new_browser_cdp_session()+ result = await cdp_session.send('SystemInfo.getProcessInfo')+ process_info = result.get('processInfo', {})+ pid = process_info.get('id')+ await cdp_session.detach()+ return pid+ except Exception:+ # If we can't get PID via CDP, it's not critical+ return Nonediff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.pyindex 551f2a5d6..a90d52ce3 100644--- a/browser_use/browser/profile.py+++ b/browser_use/browser/profile.py@@ -461,11 +461,12 @@ class BrowserLaunchArgs(BaseModel):@model_validator(mode='after')def set_default_downloads_path(self) -> Self:- """Set a default downloads path if none is provided."""+ """Set a unique default downloads path if none is provided."""if self.downloads_path is None:import tempfile- self.downloads_path = Path(tempfile.gettempdir()) / 'browser-use-downloads'+ # Create unique temporary directory for downloads+ self.downloads_path = Path(tempfile.mkdtemp(prefix='browser-use-downloads-'))return self@staticmethod@@ -906,16 +907,6 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro"""Return the kwargs for BrowserType.connect_over_cdp()."""return BrowserLaunchArgs(**self.model_dump(exclude={'args'}), args=self.get_args())- def kwargs_for_cdp_connection(self) -> dict[str, Any]:- """Return the kwargs for BrowserType.connect_over_cdp()."""- # Extract only the fields relevant for CDP connection- connect_args = BrowserConnectArgs(**self.model_dump())- return connect_args.model_dump(exclude_none=True)-- def args_for_browser_launch(self) -> list[str]:- """Return the command line args for launching a browser subprocess."""- return self.get_args()-@observe_debug(ignore_input=True, ignore_output=True, name='detect_display_configuration')def detect_display_configuration(self) -> None:"""diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex cf2cca7d9..347ca11ce 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -237,7 +237,7 @@ class BrowserSession(BaseModel):self._playwright = await async_playwright().start()self._browser = await self._playwright.chromium.connect_over_cdp(self.cdp_url,- **self.browser_profile.kwargs_for_cdp_connection(),+ **self.browser_profile.kwargs_for_connect().model_dump(),)# Set up browser contextdiff --git a/tests/ci/test_aboutblank_watchdog.py b/tests/ci/test_aboutblank_watchdog.pyindex 27c6e8c6b..013ce2ff1 100644--- a/tests/ci/test_aboutblank_watchdog.py+++ b/tests/ci/test_aboutblank_watchdog.py@@ -171,3 +171,68 @@ async def test_aboutblank_watchdog_animation_tab_management():# Stop browsersession.event_bus.dispatch(BrowserStopEvent())await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)+++async def test_aboutblank_watchdog_javascript_execution():+ """Test that the DVD screensaver JavaScript executes without errors."""+ profile = BrowserProfile(headless=True)+ session = BrowserSession(browser_profile=profile)++ try:+ # Start browser+ session.event_bus.dispatch(BrowserStartEvent())+ await session.event_bus.expect(BrowserConnectedEvent, timeout=5.0)++ # Create an about:blank page+ session.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))+ await asyncio.sleep(0.5)++ # Get the about:blank page+ pages = session.pages+ about_blank_page = next((p for p in pages if p.url == 'about:blank'), None)+ assert about_blank_page is not None, 'Should have an about:blank page'++ # Get aboutblank watchdog+ watchdog = session._aboutblank_watchdog++ # Capture console errors+ console_errors = []++ async def capture_console_error(msg):+ if msg.type == 'error':+ console_errors.append(msg.text)++ about_blank_page.on('console', capture_console_error)++ # Try to inject the DVD screensaver+ browser_session_id = str(session.id)[-4:]+ await watchdog._show_dvd_screensaver_loading_animation(about_blank_page, browser_session_id)++ # Give time for any errors to surface+ await asyncio.sleep(0.5)++ # Check for console errors+ if console_errors:+ # Check specifically for arguments.callee error+ for error in console_errors:+ if 'arguments' in error.lower() and ('callee' in error.lower() or 'arrow function' in error.lower()):+ pytest.fail(f'JavaScript error related to arguments.callee in arrow function: {error}')+ # Also fail on any other errors for completeness+ pytest.fail(f'JavaScript console error: {error}')++ # Also verify the animation was actually created+ animation_exists = await about_blank_page.evaluate("""() => {+ return document.getElementById('pretty-loading-animation') !== null;+ }""")+ assert animation_exists, 'DVD screensaver animation should have been created'++ # Check that the title was set+ title = await about_blank_page.title()+ expected_title = f'Starting agent {browser_session_id}...'+ assert title == expected_title, f'Title should be "{expected_title}" but was "{title}"'++ finally:+ # Stop browser+ session.event_bus.dispatch(BrowserStopEvent())+ await session.event_bus.expect(BrowserStoppedEvent, timeout=5.0)diff --git a/tests/ci/test_downloads_watchdog.py b/tests/ci/test_downloads_watchdog.pyindex 8fd8a7e9b..9c0a54a11 100644--- a/tests/ci/test_downloads_watchdog.py+++ b/tests/ci/test_downloads_watchdog.py@@ -218,6 +218,44 @@ async def test_downloads_watchdog_default_downloads_path():await session.kill()+async def test_unique_downloads_directories():+ """Test that different browser profiles get unique downloads directories."""+ # Create two profiles without specifying downloads_path+ profile1 = BrowserProfile(headless=True)+ profile2 = BrowserProfile(headless=True)++ # Ensure they have different downloads paths+ assert profile1.downloads_path != profile2.downloads_path+ assert profile1.downloads_path is not None+ assert profile2.downloads_path is not None++ # Ensure both directories exist+ assert Path(profile1.downloads_path).exists()+ assert Path(profile2.downloads_path).exists()++ # Ensure they are both under the temp directory with the correct prefix+ import tempfile++ temp_dir = Path(tempfile.gettempdir())+ assert Path(profile1.downloads_path).parent == temp_dir+ assert Path(profile2.downloads_path).parent == temp_dir+ assert 'browser-use-downloads-' in str(profile1.downloads_path)+ assert 'browser-use-downloads-' in str(profile2.downloads_path)++ print(f'✅ Profile 1 downloads path: {profile1.downloads_path}')+ print(f'✅ Profile 2 downloads path: {profile2.downloads_path}')++ # Test that explicit downloads_path is preserved+ with tempfile.TemporaryDirectory() as tmpdir:+ explicit_path = Path(tmpdir) / 'custom-downloads'+ explicit_path.mkdir()++ profile3 = BrowserProfile(headless=True, downloads_path=str(explicit_path))+ assert profile3.downloads_path and Path(profile3.downloads_path) == explicit_path+ print(f'✅ Explicit downloads path preserved: {profile3.downloads_path}')++@pytest.fixture(scope='function')async def comprehensive_download_test_server(httpserver):"""Setup test HTTP server with comprehensive download test page."""