Skip to content

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

add storage state events and show recent events summary to llm

Nick Sweetingae479d633073
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index 9cd06c898..0a7383baa 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -196,6 +196,8 @@ class NavigationCompleteEvent(BaseEvent):
tab_index: int
url: str
status: int | None = None
+ error_message: str | None = None # Error/timeout message if navigation had issues
+ loading_status: str | None = None # Detailed loading status (e.g., network timeout info)
# ============================================================================
@@ -239,3 +241,36 @@ class EvaluateResponse(BaseEvent):
result: Any
error: str | None = None
+
+
+# ============================================================================
+# Storage State Events
+# ============================================================================
+
+
+class SaveStorageStateEvent(BaseEvent):
+ """Request to save browser storage state."""
+
+ path: str | None = None # Optional path, uses profile default if not provided
+
+
+class StorageStateSavedEvent(BaseEvent):
+ """Notification that storage state was saved."""
+
+ path: str
+ cookies_count: int
+ origins_count: int
+
+
+class LoadStorageStateEvent(BaseEvent):
+ """Request to load browser storage state."""
+
+ path: str | None = None # Optional path, uses profile default if not provided
+
+
+class StorageStateLoadedEvent(BaseEvent):
+ """Notification that storage state was loaded."""
+
+ path: str
+ cookies_count: int
+ origins_count: int
diff --git a/browser_use/browser/views.py b/browser_use/browser/views.py
index 03dffe6e3..dc511869c 100644
--- a/browser_use/browser/views.py
+++ b/browser_use/browser/views.py
@@ -65,7 +65,7 @@ class BrowserStateSummary(DOMState):
pixels_below: int = 0
browser_errors: list[str] = field(default_factory=list)
is_pdf_viewer: bool = False # Whether the current page is a PDF viewer
- loading_status: str | None = None # Message about page loading status (e.g., network timeout)
+ recent_events: str | None = None # Text summary of recent browser events
@dataclass
diff --git a/tests/ci/test_browser_session_loading_state.py b/tests/ci/test_browser_session_loading_state.py
index 36df96b8e..0222056f0 100644
--- a/tests/ci/test_browser_session_loading_state.py
+++ b/tests/ci/test_browser_session_loading_state.py
@@ -2,7 +2,6 @@
Test browser session loading state notification when network timeout occurs.
"""
-import asyncio
import time
import pytest
@@ -33,10 +32,10 @@ class TestBrowserLoadingState:
</body>
</html>
"""
-
+
# Main page loads immediately
httpserver.expect_request('/').respond_with_data(html_content, content_type='text/html')
-
+
# Handler that sleeps longer than the timeout
def slow_handler(request):
# Sleep for 5 seconds - longer than the 1s maximum_wait_page_load_time
@@ -66,26 +65,34 @@ class TestBrowserLoadingState:
# Navigate to the page with the slow iframe
await browser_session.navigate(httpserver.url_for('/'))
-
+
# Get state - the iframe should still be loading
# and _wait_for_stable_network should detect it and timeout
state = await browser_session.get_browser_state_with_recovery()
-
- # Verify loading status was set
- assert state.loading_status is not None, 'Loading status should be set when network timeout occurs'
- assert 'aborted after 1.0s' in state.loading_status
- assert 'pending network requests' in state.loading_status
- assert 'wait action' in state.loading_status
- # Verify the full message format
- expected_pattern = 'Page loading was aborted after 1.0s with'
- assert state.loading_status.startswith(expected_pattern)
+ # Verify recent events contains navigation timeout info
+ assert state.recent_events is not None, 'Recent events should be set'
+
+ # Parse JSON events
+ import json
+ events = json.loads(state.recent_events)
+ assert len(events) > 0, 'Should have at least one event'
+
+ # Find NavigationCompleteEvent with loading status
+ nav_events = [e for e in events if e.get('event_type') == 'NavigationCompleteEvent']
+ assert len(nav_events) > 0, 'Should have NavigationCompleteEvent'
+
+ # Check that at least one navigation event has loading status info
+ nav_event = nav_events[-1] # Get most recent
+ assert nav_event.get('loading_status') is not None
+ assert 'aborted after 1.0s' in nav_event['loading_status']
+ assert 'pending network requests' in nav_event['loading_status']
finally:
await browser_session.kill()
async def test_loading_status_cleared_on_successful_load(self, httpserver: HTTPServer):
- """Test that loading status is cleared when page loads successfully"""
+ """Test that recent events shows successful navigation when page loads successfully"""
# Set up a simple page that loads quickly
httpserver.expect_request('/fast').respond_with_data(
'<html><head><title>Fast Page</title></head><body><h1>Quick loading page</h1></body></html>',
@@ -110,14 +117,25 @@ class TestBrowserLoadingState:
# Get browser state
state = await browser_session.get_browser_state_with_recovery()
- # Loading status should be None for successful loads
- assert state.loading_status is None, 'Loading status should be None when page loads successfully'
+ # Recent events should show successful navigation without errors
+ assert state.recent_events is not None
+
+ # Parse JSON and check NavigationCompleteEvent
+ import json
+ events = json.loads(state.recent_events)
+ nav_events = [e for e in events if e.get('event_type') == 'NavigationCompleteEvent']
+ assert len(nav_events) > 0
+
+ # Should not contain timeout or error messages in the navigation event
+ nav_event = nav_events[-1]
+ assert nav_event.get('loading_status') is None
+ assert nav_event.get('error_message') is None
finally:
await browser_session.kill()
async def test_loading_status_reset_on_navigation(self, httpserver: HTTPServer):
- """Test that loading status is reset when navigating to a new page"""
+ """Test that recent events properly tracks navigation between slow and fast pages"""
# Set up pages
slow_html = """
<html>
@@ -152,20 +170,24 @@ class TestBrowserLoadingState:
# Navigate to slow page (should timeout)
await browser_session.navigate(httpserver.url_for('/slow'))
state1 = await browser_session.get_browser_state_with_recovery()
- assert state1.loading_status is not None, 'Loading status should be set for slow page'
+ assert state1.recent_events is not None
+ assert 'NavigationCompleteEvent' in state1.recent_events
+ assert 'aborted' in state1.recent_events
# Navigate to fast page
await browser_session.navigate(httpserver.url_for('/fast'))
state2 = await browser_session.get_browser_state_with_recovery()
- # Loading status should be cleared after successful navigation
- assert state2.loading_status is None, 'Loading status should be cleared after navigating to new page'
+ # Recent events should show the latest navigation completed successfully
+ assert state2.recent_events is not None
+ # Should contain both navigation events
+ assert state2.recent_events.count('NavigationCompleteEvent') >= 2
finally:
await browser_session.kill()
async def test_loading_status_in_minimal_state_fallback(self, httpserver: HTTPServer):
- """Test that loading status is preserved even when falling back to minimal state"""
+ """Test that recent events is preserved even when falling back to minimal state"""
# Create a page that causes DOM processing to fail
malformed_html = """
<html>
@@ -204,17 +226,18 @@ class TestBrowserLoadingState:
# Get browser state - this might fall back to minimal state
state = await browser_session.get_browser_state_with_recovery()
- # Even if we get minimal state, loading status should be preserved
- if state.loading_status is not None:
- assert 'aborted after 0.5s' in state.loading_status
- assert 'pending network requests' in state.loading_status
+ # Even if we get minimal state, recent events should be preserved
+ assert state.recent_events is not None
+ if 'NavigationCompleteEvent' in state.recent_events and 'aborted' in state.recent_events:
+ assert 'aborted after 0.5s' in state.recent_events
+ assert 'pending network requests' in state.recent_events
finally:
await browser_session.kill()
@pytest.mark.parametrize('timeout_seconds', [0.5, 1.0, 2.0])
async def test_loading_status_with_different_timeouts(self, httpserver: HTTPServer, timeout_seconds: float):
- """Test that loading status correctly reports the configured timeout value"""
+ """Test that recent events correctly reports the configured timeout value"""
# Set up a slow page
httpserver.expect_request(f'/timeout_{timeout_seconds}').respond_with_data(
f'<html><head><title>Timeout Test {timeout_seconds}s</title>'
@@ -244,10 +267,11 @@ class TestBrowserLoadingState:
# Get browser state
state = await browser_session.get_browser_state_with_recovery()
- # Verify loading status contains the correct timeout value
- if state.loading_status is not None:
- assert f'aborted after {timeout_seconds}s' in state.loading_status
- assert 'pending network requests' in state.loading_status
+ # Verify recent events contains the correct timeout value
+ assert state.recent_events is not None
+ if 'NavigationCompleteEvent' in state.recent_events and 'aborted' in state.recent_events:
+ assert f'aborted after {timeout_seconds}s' in state.recent_events
+ assert 'pending network requests' in state.recent_events
finally:
await browser_session.kill()
diff --git a/tests/ci/test_browser_session_start.py b/tests/ci/test_browser_session_start.py
index c71e8d349..e7ec7d6e3 100644
--- a/tests/ci/test_browser_session_start.py
+++ b/tests/ci/test_browser_session_start.py
@@ -538,7 +538,6 @@ class TestBrowserSessionStart:
assert profile3.user_data_dir == CONFIG.BROWSER_USE_DEFAULT_USER_DATA_DIR.parent / 'default-msedge'
-
class TestBrowserSessionReusePatterns:
"""Tests for all browser re-use patterns documented in docs/customize/real-browser.mdx"""
@@ -819,21 +818,21 @@ class TestBrowserSessionReusePatterns:
from browser_use import Agent
from browser_use.browser import BrowserProfile, BrowserSession
- # Set up HTTP server with cookie-setting endpoint
+ # Set up HTTP server with cookie-setting endpoint using HTTP headers
httpserver.expect_request('/set-cookies').respond_with_data(
- '<html><body>Cookies set!</body></html>',
+ '<html><body>Cookies set via HTTP headers!</body></html>',
headers={
- 'Set-Cookie': 'session_id=test123; Path=/; HttpOnly',
'Content-Type': 'text/html',
- }
+ 'Set-Cookie': ['session_id=test123; Path=/', 'auth_token=abc456; Path=/'],
+ },
)
-
+
httpserver.expect_request('/page2').respond_with_data(
- '<html><body>Page 2</body></html>',
+ '<html><body>Page 2 with preferences!</body></html>',
headers={
- 'Set-Cookie': 'user_pref=dark_mode; Path=/',
'Content-Type': 'text/html',
- }
+ 'Set-Cookie': ['user_pref=dark_mode; Path=/', 'theme=night; Path=/'],
+ },
)
# Create a shared profile with storage state
@@ -853,7 +852,7 @@ class TestBrowserSessionReusePatterns:
storage_state=str(auth_json_path), # Load/save cookies to/from json file
keep_alive=True,
)
- print(f"Profile storage_state: {shared_profile.storage_state}")
+ print(f'Profile storage_state: {shared_profile.storage_state}')
try:
# Create separate browser sessions from the same profile
@@ -866,8 +865,29 @@ class TestBrowserSessionReusePatterns:
agent2 = Agent(task='Second agent task...', llm=mock_llm, browser_session=window2, enable_memory=False)
# Navigate to pages that set cookies
- await window1.navigate_to(httpserver.url_for('/set-cookies'))
- await window2.navigate_to(httpserver.url_for('/page2'))
+ # Use 127.0.0.1 instead of localhost for cookie persistence
+ base_url = httpserver.url_for('/')
+ if 'localhost' in base_url:
+ base_url = base_url.replace('localhost', '127.0.0.1')
+
+ await window1.navigate_to(base_url.rstrip('/') + '/set-cookies')
+ await window2.navigate_to(base_url.rstrip('/') + '/page2')
+
+ # Wait for pages to load
+ page1 = await window1.get_current_page()
+ page2 = await window2.get_current_page()
+ await page1.wait_for_load_state('networkidle')
+ await page2.wait_for_load_state('networkidle')
+
+ # Inject cookies directly via CDP to ensure they're set
+ await page1.context.add_cookies([
+ {'name': 'session_id', 'value': 'test123', 'domain': '127.0.0.1', 'path': '/'},
+ {'name': 'auth_token', 'value': 'abc456', 'domain': '127.0.0.1', 'path': '/'},
+ ])
+ await page2.context.add_cookies([
+ {'name': 'user_pref', 'value': 'dark_mode', 'domain': '127.0.0.1', 'path': '/'},
+ {'name': 'theme', 'value': 'night', 'domain': '127.0.0.1', 'path': '/'},
+ ])
# Run agents in parallel
_results = await asyncio.gather(agent1.run(), agent2.run())
@@ -880,33 +900,74 @@ class TestBrowserSessionReusePatterns:
assert window1.initialized
assert window2.initialized
- # Save storage state from both sessions
- await window1.save_storage_state()
+ # 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]}")
- # Check what was saved from window1
- storage_state_1 = json.loads(auth_json_path.read_text())
- print(f"Storage state after window1 save: {storage_state_1}")
+ # 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]}")
- await window2.save_storage_state()
+ # 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']}
+ print(f'Cookies saved from window1: {cookies_1}')
- # Verify storage state file exists
- assert Path(auth_json_path).exists()
+ # 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']}
+ print(f'Cookies saved from window2: {cookies_2}')
- # Read final storage state
- storage_state = json.loads(auth_json_path.read_text())
- print(f"Final storage state: {storage_state}")
+ # Verify each window saved its own cookies
+ assert len(cookies_1) >= 2, f"Window1 should have saved at least 2 cookies, got {cookies_1}"
+ assert len(cookies_2) >= 2, f"Window2 should have saved at least 2 cookies, got {cookies_2}"
- # Verify storage state file has content
- assert 'cookies' in storage_state
- # The test might be too strict - cookies might not persist in headless mode
- # or with certain cookie settings. Let's just verify the structure is correct
- assert isinstance(storage_state['cookies'], list)
- assert 'origins' in storage_state
- assert isinstance(storage_state['origins'], list)
-
- finally:
+ # Now test that a new session can load the saved cookies
+ print("\nTesting cookie persistence with new session...")
await window1.kill()
await window2.kill()
+
+ # Create a new session with the same profile
+ window3 = BrowserSession(browser_profile=shared_profile)
+ await window3.start()
+
+ # Check if cookies were loaded
+ 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}
+ print(f"Cookies loaded in new session: {loaded_cookie_names}")
+
+ # Should have the cookies from window2 (last save)
+ assert len(loaded_cookie_names) >= 2, f"Expected loaded cookies, got {loaded_cookie_names}"
+
+ await window3.kill()
+
+ finally:
+ # Clean up any remaining sessions
+ try:
+ if 'window1' in locals():
+ await window1.kill()
+ except:
+ pass
+ try:
+ if 'window2' in locals():
+ await window2.kill()
+ except:
+ pass
+ try:
+ if 'window3' in locals():
+ await window3.kill()
+ except:
+ pass
auth_json_path.unlink(missing_ok=True)
async def test_browser_shutdown_isolated(self):