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
always raise a hard error when browser crashes instead of restarting it
Nick Sweeting39dfa7f624cd
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex d87085d81..723a4464f 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -966,33 +966,34 @@ class BrowserSession(BaseModel):raise RuntimeError('Failed parsing extensions: Chrome profile incompatibility detected')elif 'SingletonLock' in stderr_output or 'ProcessSingleton' in stderr_output:# Chrome exited due to singleton lock- self._fallback_to_temp_profile('Chrome process exit due to SingletonLock')- # Kill the subprocess and retry with new profile+ self.logger.error(+ f'❌ Chrome process {self.browser_pid} crashed due to SingletonLock error: {stderr_output[:500]}'+ )+ # Kill the subprocesstry:self._subprocess.terminate()await self._subprocess.wait()except Exception:passself.browser_pid = None- # Retry with the new temp directory- await self._unsafe_setup_new_browser_context()- return+ # Throw hard error instead of restarting+ raise RuntimeError(f'Chrome process crashed due to SingletonLock error: {stderr_output[:500]}')else:- # Chrome exited for unknown reason, try fallback to temp profile- self.logger.warning(- f'⚠️ Chrome process {self.browser_pid} exited unexpectedly. Error: {stderr_output[:500] if stderr_output else "No error output"}'+ # Chrome exited for unknown reason+ self.logger.error(+ f'❌ Chrome process {self.browser_pid} crashed unexpectedly. Error: {stderr_output[:500] if stderr_output else "No error output"}')- self._fallback_to_temp_profile('Chrome process exit with unknown error')- # Kill the subprocess and retry with new profile+ # Kill the subprocesstry:self._subprocess.terminate()await self._subprocess.wait()except Exception:passself.browser_pid = None- # Retry with the new temp directory- await self._unsafe_setup_new_browser_context()- return+ # Throw hard error instead of restarting+ raise RuntimeError(+ f'Chrome process crashed unexpectedly: {stderr_output[:500] if stderr_output else "No error output"}'+ )self.logger.error(f'❌ Chrome process {self.browser_pid} exited unexpectedly')self.browser_pid = Nonereturn@@ -1013,7 +1014,7 @@ class BrowserSession(BaseModel):else:self.logger.error(f'❌ Chrome CDP port {debug_port} did not become available after 30 seconds')self.browser_pid = None- return+ raise RuntimeError(f'Chrome CDP port {debug_port} did not become available - browser process may have crashed')# Determine if this is a newly spawned subprocess or an existing processif hasattr(self, '_subprocess') and self._subprocess and self._subprocess.pid == self.browser_pid:@@ -1234,12 +1235,12 @@ class BrowserSession(BaseModel):elif 'SingletonLock' in stderr_output or 'ProcessSingleton' in stderr_output:raise RuntimeError(f'SingletonLock error: {stderr_output[:500]}')else:- # For any other error, log it and raise to trigger fallback- self.logger.warning(- f'⚠️ Chrome subprocess exited with code {process.returncode}. Error: {stderr_output[:500] if stderr_output else "No error output"}'+ # For any other error, raise hard error+ self.logger.error(+ f'❌ Chrome subprocess crashed with code {process.returncode}. Error: {stderr_output[:500] if stderr_output else "No error output"}')raise RuntimeError(- f'Chrome subprocess exited with code {process.returncode}. Error output: {stderr_output[:500] if stderr_output else "No error output"}'+ f'Chrome subprocess crashed with code {process.returncode}. Error output: {stderr_output[:500] if stderr_output else "No error output"}')else:# Kill the subprocess if it's still running but we couldn't connect@@ -1258,13 +1259,8 @@ class BrowserSession(BaseModel):or 'Chrome subprocess exited' in str(e)or isinstance(e, RuntimeError)):- # Fall back to temporary directory- reason = (- 'Chrome launch error due to SingletonLock'- if 'SingletonLock' in str(e)- else 'Chrome subprocess failed to start'- )- self._fallback_to_temp_profile(reason)+ # Chrome has crashed - throw hard error instead of restarting+ self.logger.error(f'❌ Chrome process crashed and cannot be recovered: {str(e)}')# Kill the failed subprocess if it existsif hasattr(self, '_subprocess') and self._subprocess:try:@@ -1272,30 +1268,23 @@ class BrowserSession(BaseModel):await self._subprocess.wait()except Exception:pass- # Retry the launch with the new temporary directory- await self._unsafe_setup_new_browser_context()- return+ # Throw hard error instead of restarting+ raise RuntimeError(f'Chrome process crashed and cannot be recovered: {str(e)}')# Re-raise if not a timeoutelif not isinstance(e, asyncio.TimeoutError):raiseexcept TimeoutError:- self.logger.warning(- 'Browser operation timed out. This may indicate the playwright instance is invalid due to event loop changes. '- 'Recreating playwright instance and retrying...'+ self.logger.error(+ '❌ Browser operation timed out. This may indicate the playwright instance is invalid or the browser has crashed.')- # Force recreation of the playwright object- self.playwright = await self._start_global_playwright_subprocess(is_stealth=self.browser_profile.stealth)- # Retry the whole subprocess launch- await self._unsafe_setup_new_browser_context()- return+ # Throw hard error instead of retrying+ raise RuntimeError('Browser operation timed out - browser may have crashed or become unresponsive')except Exception as e:# Check if it's a SingletonLock error from the subprocessif 'SingletonLock' in str(e) or 'ProcessSingleton' in str(e):- # Fall back to temporary directory- self._fallback_to_temp_profile('Chrome launch error due to SingletonLock')- # Retry the launch with the new temporary directory- await self._unsafe_setup_new_browser_context()- return+ # Chrome crashed due to SingletonLock - throw hard error+ self.logger.error(f'❌ Chrome launch failed due to SingletonLock error: {str(e)}')+ raise RuntimeError(f'Chrome launch failed due to SingletonLock error: {str(e)}')# show a nice logger hint explaining what went wrong with the user_data_dir# calculate the version of the browser that the user_data_dir is for, and the version of the browser we are running with@@ -3538,6 +3527,24 @@ class BrowserSession(BaseModel):self.logger.warning(f'⚠️ Page JS engine became unresponsive in {calling_method}(), attempting recovery...')timeout_ms = min(3000, int(timeout_ms or self.browser_profile.default_navigation_timeout or 5000))+ # Check if browser process is still alive before attempting recovery+ if self.browser_pid:+ try:+ import psutil++ proc = psutil.Process(self.browser_pid)+ if proc.status() in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD):+ self.logger.error(f'❌ Browser process {self.browser_pid} has crashed and cannot be recovered')+ raise RuntimeError('Browser process has crashed - cannot recover unresponsive page')+ except psutil.NoSuchProcess:+ self.logger.error(f'❌ Browser process {self.browser_pid} no longer exists')+ raise RuntimeError('Browser process has crashed - cannot recover unresponsive page')++ # Check if browser connection is still alive+ if self.browser and not self.browser.is_connected():+ self.logger.error('❌ Browser connection lost - browser process may have crashed')+ raise RuntimeError('Browser connection lost - cannot recover unresponsive page')+# Prevent re-entranceself._in_recovery = Truetry:diff --git a/tests/ci/test_browser_session_crashed_page_recovery.py b/tests/ci/test_browser_session_crashed_page_recovery.pyindex bbc15acd6..65124516f 100644--- a/tests/ci/test_browser_session_crashed_page_recovery.py+++ b/tests/ci/test_browser_session_crashed_page_recovery.py@@ -10,6 +10,8 @@ This test module covers:"""import asyncio+import os+import signalimport timeimport warnings@@ -428,6 +430,134 @@ class TestBrowserSessionRecovery:page2 = await browser_session.navigate(httpserver.url_for('/normal'))assert 'normal' in page2.url+ async def test_browser_crash_throws_hard_error_no_restart(self, browser_session: BrowserSession):+ """Test that browser crashes throw hard errors instead of restarting the browser"""+ # Get the browser process PID+ browser_pid = browser_session.browser_pid+ assert browser_pid is not None, 'Browser PID must be available'++ print(f'1️⃣ Browser PID: {browser_pid}')++ # Force kill the browser process to simulate a hard crash+ print('2️⃣ Killing browser process to simulate crash...')+ try:+ os.kill(browser_pid, signal.SIGKILL)+ except ProcessLookupError:+ # Process might have already exited+ pass++ # Wait a bit for the process to die+ await asyncio.sleep(1)++ # Try to use the browser session - should raise error (TargetClosedError or RuntimeError)+ print('3️⃣ Attempting to use crashed browser session...')+ with pytest.raises(Exception) as exc_info:+ await browser_session.navigate('about:blank')++ # Verify the error indicates browser disconnection/crash+ error_msg = str(exc_info.value).lower()+ error_type = type(exc_info.value).__name__+ print(f'4️⃣ Got expected error ({error_type}): {error_msg}')+ assert (+ 'closed' in error_msg or 'crash' in error_msg or 'cannot be recovered' in error_msg or 'connection lost' in error_msg+ ), f'Error message should indicate browser crash/closure, got: {error_msg}'++ # Verify browser was NOT restarted (PID should still be the same dead one)+ assert browser_session.browser_pid == browser_pid or browser_session.browser_pid is None, (+ 'Browser PID should not change (no restart should occur)'+ )++ 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+ import tempfile+ from pathlib import Path++ # Create a temp directory for user data+ temp_dir = tempfile.mkdtemp(prefix='browseruse-test-')++ # Create a fake SingletonLock file to simulate conflict+ singleton_lock = Path(temp_dir) / 'SingletonLock'+ singleton_lock.write_text('fake-lock')++ # Create a session with this directory+ session = BrowserSession(browser_profile=BrowserProfile(user_data_dir=temp_dir, headless=True))++ # Modify the Chrome launch args to trigger SingletonLock error+ original_args = session.browser_profile.args.copy()+ # Add an arg that will cause Chrome to exit with SingletonLock error+ session.browser_profile.args.append('--no-sandbox')+ session.browser_profile.args.append('--disable-setuid-sandbox')++ print(f'1️⃣ Attempting to launch browser with potentially conflicting user_data_dir: {temp_dir}')++ # Note: This test is checking that IF a SingletonLock error occurs,+ # it throws a hard error instead of restarting. The actual error might+ # not always occur depending on the system state.+ try:+ await session.start()+ # If it succeeds, that's OK - we can't reliably trigger SingletonLock+ print('2️⃣ Browser launched successfully (SingletonLock error did not occur)')+ await session.kill()+ except RuntimeError as e:+ # If we get a RuntimeError with SingletonLock, that's what we want+ error_msg = str(e)+ print(f'2️⃣ Got expected error: {error_msg}')+ if 'SingletonLock' in error_msg:+ print('✅ SingletonLock error correctly threw hard error without restart')+ else:+ # Some other RuntimeError - re-raise it+ raise+ except Exception as e:+ # Unexpected error type+ print(f'2️⃣ Got unexpected error type {type(e).__name__}: {e}')+ raise+ finally:+ # Cleanup+ import shutil++ try:+ shutil.rmtree(temp_dir, ignore_errors=True)+ except Exception:+ pass+@pytest.mark.timeout(90)async def test_multiple_sessions_with_blocking_pages(httpserver: HTTPServer):diff --git a/tests/ci/test_browser_session_output_paths.py b/tests/ci/test_browser_session_output_paths.pyindex 6c2bcec7c..5472781ea 100644--- a/tests/ci/test_browser_session_output_paths.py+++ b/tests/ci/test_browser_session_output_paths.py@@ -24,20 +24,24 @@ def test_dir(tmp_path):@pytest.fixtureasync def httpserver_url(httpserver):"""Simple test page."""- httpserver.expect_request('/').respond_with_data(- """- <!DOCTYPE html>- <html>- <head><title>Test Page</title></head>- <body>- <h1>Test Recording Page</h1>- <input type="text" id="search" placeholder="Search here">- <button id="submit">Submit</button>- </body>- </html>- """,- content_type='text/html',- )+ # Use expect_ordered_request with multiple handlers to handle repeated requests+ for _ in range(10): # Allow up to 10 requests to the same URL+ httpserver.expect_ordered_request('/').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head>+ <title>Test Page</title>+ </head>+ <body>+ <h1>Test Recording Page</h1>+ <input type="text" id="search" placeholder="Search here" />+ <button type="button" id="submit">Submit</button>+ </body>+ </html>+ """,+ content_type='text/html',+ )return httpserver.url_for('/')@@ -117,6 +121,23 @@ def interactive_llm(httpserver_url):]}""",+ # Fifth action: Done - task completed+ """+ {+ "thinking": "null",+ "evaluation_previous_goal": "Clicked the submit button",+ "memory": "Successfully navigated to the page, typed 'test' in the search box, and clicked submit",+ "next_goal": "Task completed",+ "action": [+ {+ "done": {+ "text": "Task completed - typed 'test' in search box and clicked submit",+ "success": true+ }+ }+ ]+ }+ """,]return create_mock_llm(actions)@@ -451,8 +472,9 @@ class TestCombinedRecordings:conversation_files = list(conversation_path.glob('conversation_*.txt'))assert len(conversation_files) > 0, 'Conversation file was not created'- # Check GIF+ # Check GIF - should be created since we navigate to a real pageassert gif_path.exists(), 'GIF was not created'+ assert gif_path.stat().st_size > 10000, 'GIF file is too small'# Check video directoryassert video_dir.exists(), 'Video directory was not created'