Skip to content

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

init and config fixes

Nick Sweetingf463a9383cb2
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index d36a00d08..a67fd10fa 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -429,11 +429,11 @@ class Agent(Generic[Context]):
self.eventbus = EventBus(name='Agent', wal_path=wal_path)
# Cloud sync service
- self.enable_cloud_sync = os.environ.get('BROWSERUSE_CLOUD_SYNC', 'true').lower() == 'true'
+ self.enable_cloud_sync = os.environ.get('BROWSERUSE_CLOUD_SYNC', 'true').lower()[0] in 'ty1'
if self.enable_cloud_sync:
- from browser_use.sync import CloudSyncService
+ from browser_use.sync import CloudSync
- self.cloud_sync = CloudSyncService(base_url=os.environ.get('BROWSER_USE_CLOUD_URL', 'https://cloud.browser-use.com'))
+ self.cloud_sync = CloudSync()
# Register cloud sync handler
self.eventbus.on('*', self.cloud_sync.handle_event)
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 1a9524275..97b661bc4 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -2489,29 +2489,39 @@ class BrowserSession(BaseModel):
# 3. Expand the viewport if we are using one
if original_viewport:
- await page.set_viewport_size({'width': expanded_width, 'height': expanded_height})
+ await asyncio.wait_for(
+ page.set_viewport_size({'width': expanded_width, 'height': expanded_height}), timeout=2000
+ ) # intentionally set short because we want this to be noisy if it's slowing us down
try:
# 4. Take full-viewport screenshot
- screenshot = await page.screenshot(
- full_page=False,
- scale='css',
- timeout=30000,
- clip={'x': 0, 'y': 0, 'width': expanded_width, 'height': expanded_height},
- animations='allow',
- caret='initial',
- # animations='disabled', # these can cause CSP errors on some pages, leading to a red herring "waiting for fonts to load" error
+ screenshot = await asyncio.wait_for(
+ page.screenshot(
+ full_page=False,
+ scale='css',
+ timeout=10000,
+ clip={'x': 0, 'y': 0, 'width': expanded_width, 'height': expanded_height},
+ animations='allow',
+ caret='initial',
+ # animations='disabled', # these can cause CSP errors on some pages, leading to a red herring "waiting for fonts to load" error
+ ),
+ timeout=15000,
)
# TODO: manually take multiple clipped screenshots to capture the full height and stitch them together?
screenshot_b64 = base64.b64encode(screenshot).decode('utf-8')
return screenshot_b64
+ except Exception as e:
+ self.logger.error(f'❌ Failed to take full-page screenshot after 2 tries: {type(e).__name__}: {e}')
+ raise
finally:
# 5. Restore original viewport state if we expanded it
if original_viewport:
# Viewport was originally enabled, restore to original dimensions
- await page.set_viewport_size(original_viewport)
+ await asyncio.wait_for(
+ page.set_viewport_size(original_viewport), timeout=2000
+ ) # intentionally set short because we want this to be noisy if it's slowing us down
else:
# Viewport was originally disabled, no need to restore it
# await page.set_viewport_size(None) # unfortunately this is not supported by playwright
diff --git a/browser_use/sync/__init__.py b/browser_use/sync/__init__.py
index 52f705f23..68b172292 100644
--- a/browser_use/sync/__init__.py
+++ b/browser_use/sync/__init__.py
@@ -1,6 +1,6 @@
"""Cloud sync module for Browser Use."""
from browser_use.sync.auth import CloudAuthConfig, DeviceAuthClient
-from browser_use.sync.service import CloudSyncService
+from browser_use.sync.service import CloudSync
-__all__ = ['CloudAuthConfig', 'DeviceAuthClient', 'CloudSyncService']
+__all__ = ['CloudAuthConfig', 'DeviceAuthClient', 'CloudSync']
diff --git a/browser_use/sync/auth.py b/browser_use/sync/auth.py
index 5f030802a..6e564f7cc 100644
--- a/browser_use/sync/auth.py
+++ b/browser_use/sync/auth.py
@@ -59,9 +59,10 @@ class CloudAuthConfig(BaseModel):
class DeviceAuthClient:
"""Client for OAuth2 device authorization flow"""
- def __init__(self, base_url: str = 'https://cloud.browser-use.com', http_client: httpx.AsyncClient | None = None):
- self.base_url = base_url
- self.client_id = 'bu_cli'
+ def __init__(self, base_url: str | None = None, http_client: httpx.AsyncClient | None = None):
+ # Backend API URL for OAuth requests - can be passed directly or defaults to env var
+ self.base_url = base_url or os.getenv('BROWSER_USE_CLOUD_URL', 'https://cloud.browser-use.com')
+ self.client_id = 'library'
self.scope = 'read write'
# If no client provided, we'll create one per request
@@ -98,7 +99,7 @@ class DeviceAuthClient:
"""
if self.http_client:
response = await self.http_client.post(
- f'{self.base_url}/api/v1/oauth/device/authorize',
+ f'{self.base_url.rstrip("/")}/api/v1/oauth/device/authorize',
data={
'client_id': self.client_id,
'scope': self.scope,
@@ -110,7 +111,7 @@ class DeviceAuthClient:
else:
async with httpx.AsyncClient() as client:
response = await client.post(
- f'{self.base_url}/api/v1/oauth/device/authorize',
+ f'{self.base_url.rstrip("/")}/api/v1/oauth/device/authorize',
data={
'client_id': self.client_id,
'scope': self.scope,
@@ -137,7 +138,7 @@ class DeviceAuthClient:
while time.time() - start_time < timeout:
try:
response = await self.http_client.post(
- f'{self.base_url}/api/v1/oauth/device/token',
+ f'{self.base_url.rstrip("/")}/api/v1/oauth/device/token',
data={
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
'device_code': device_code,
@@ -189,7 +190,7 @@ class DeviceAuthClient:
while time.time() - start_time < timeout:
try:
response = await client.post(
- f'{self.base_url}/api/v1/oauth/device/token',
+ f'{self.base_url.rstrip("/")}/api/v1/oauth/device/token',
data={
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
'device_code': device_code,
@@ -255,8 +256,8 @@ class DeviceAuthClient:
# Start device authorization
device_auth = await self.start_device_authorization(agent_session_id)
- # Override frontend URL if environment variable is set
- frontend_url = os.environ.get('BROWSER_USE_CLOUD_FRONTEND_URL', self.base_url)
+ # Use frontend URL for user-facing links
+ frontend_url = os.getenv('BROWSER_USE_CLOUD_UI_URL', self.base_url)
# Replace backend URL with frontend URL in verification URIs
verification_uri = device_auth['verification_uri'].replace(self.base_url, frontend_url)
diff --git a/browser_use/sync/service.py b/browser_use/sync/service.py
index 813b6991d..0a0be7896 100644
--- a/browser_use/sync/service.py
+++ b/browser_use/sync/service.py
@@ -5,6 +5,7 @@ Cloud sync service for sending events to the Browser Use cloud.
import asyncio
import json
import logging
+import os
import anyio
import httpx
@@ -15,13 +16,14 @@ from browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClient
logger = logging.getLogger(__name__)
-class CloudSyncService:
+class CloudSync:
"""Service for syncing events to the Browser Use cloud"""
- def __init__(self, base_url: str = 'https://cloud.browser-use.com', enable_auth: bool = True):
- self.base_url = base_url
+ def __init__(self, base_url: str | None = None, enable_auth: bool = True):
+ # Backend API URL for all API requests - can be passed directly or defaults to env var
+ self.base_url = base_url or os.getenv('BROWSER_USE_CLOUD_URL', 'https://cloud.browser-use.com')
self.enable_auth = enable_auth
- self.auth_client = DeviceAuthClient(base_url) if enable_auth else None
+ self.auth_client = DeviceAuthClient(base_url=self.base_url) if enable_auth else None
self.pending_events: list[dict] = []
self.auth_task = None
self.session_id: str | None = None
@@ -76,7 +78,7 @@ class CloudSyncService:
# Send event
async with httpx.AsyncClient() as client:
response = await client.post(
- f'{self.base_url}/api/v1/events/',
+ f'{self.base_url.rstrip("/")}/api/v1/events/',
json={'events': [event_data]},
headers=headers,
timeout=10.0,
@@ -162,8 +164,19 @@ class CloudSyncService:
async def send_event(self, event_type: str, event_data: dict, event_schema: str) -> None:
"""Send a single event to the cloud - convenience method for tests"""
- event = BaseEvent(event_type=event_type, **event_data)
- await self.handle_event(event)
+ # Create a dynamic subclass that includes the custom event data
+ from pydantic import ConfigDict, Field
+
+ etype = event_type
+
+ class CustomEvent(BaseEvent):
+ model_config = ConfigDict(
+ extra='allow', arbitrary_types_allowed=True, validate_assignment=True, validate_default=True
+ )
+ event_type: str = Field(default=etype, frozen=True)
+
+ CustomEvent.__name__ = etype
+ await self.handle_event(CustomEvent(**event_data))
async def authenticate(self, show_instructions: bool = True) -> bool:
"""Authenticate with the cloud service"""
diff --git a/tests/ci/test_controller_action_parameter_injection.py b/tests/ci/test_action_parameter_injection.py
similarity index 100%
rename from tests/ci/test_controller_action_parameter_injection.py
rename to tests/ci/test_action_parameter_injection.py
diff --git a/tests/ci/test_agent_cloud_integration.py b/tests/ci/test_agent_cloud_integration.py
deleted file mode 100644
index f3508d4b9..000000000
--- a/tests/ci/test_agent_cloud_integration.py
+++ /dev/null
@@ -1,292 +0,0 @@
-"""
-Tests for browser-use agent integration with cloud sync.
-"""
-
-import asyncio
-import os
-from unittest.mock import AsyncMock, Mock, patch
-
-import pytest
-
-from browser_use.agent.service import Agent
-from browser_use.sync.service import CloudSyncService
-from tests.ci.mocks import create_mocked_browser, create_mocked_model
-
-
-class TestAgentCloudIntegration:
- """Test agent integration with cloud sync."""
-
- @pytest.fixture
- def mock_browser(self):
- """Create mocked browser."""
- return create_mocked_browser()
-
- @pytest.fixture
- def mock_model(self):
- """Create mocked LLM model."""
- return create_mocked_model()
-
- @pytest.fixture
- def mock_cloud_sync(self):
- """Create mocked cloud sync service."""
- sync = Mock(spec=CloudSyncService)
- sync.send_event = AsyncMock()
- sync.authenticate = AsyncMock(return_value=True)
- sync._authenticated = True
- return sync
-
- @pytest.fixture
- def agent_with_cloud(self, mock_browser, mock_model, mock_cloud_sync):
- """Create agent with cloud sync enabled."""
- with patch('browser_use.agent.service.CloudSyncService', return_value=mock_cloud_sync):
- with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'true'}):
- agent = Agent(
- task='Test task',
- llm=mock_model,
- browser_context=mock_browser,
- )
- # Manually set cloud sync since we're mocking
- agent.cloud_sync = mock_cloud_sync
- return agent
-
- async def test_agent_emits_session_start_event(self, agent_with_cloud, mock_cloud_sync):
- """Test that agent emits session start event."""
- # Run agent
- await agent_with_cloud.run()
-
- # Check that session start event was sent
- calls = mock_cloud_sync.send_event.call_args_list
- session_events = [call for call in calls if call[1]['event_type'] == 'CreateAgentSession']
-
- assert len(session_events) == 1
- event_data = session_events[0][1]['event_data']
- assert 'id' in event_data
- assert 'started_at' in event_data
-
- async def test_agent_emits_task_events(self, agent_with_cloud, mock_cloud_sync):
- """Test that agent emits task events."""
- # Run agent
- await agent_with_cloud.run()
-
- # Check task events
- calls = mock_cloud_sync.send_event.call_args_list
-
- # Should have CreateAgentTask event
- create_task_events = [call for call in calls if call[1]['event_type'] == 'CreateAgentTask']
- assert len(create_task_events) == 1
- create_data = create_task_events[0][1]['event_data']
- assert create_data['task'] == 'Test task'
- assert create_data['status'] == 'running'
- assert 'agent_session_id' in create_data
-
- # Should have UpdateAgentTask event when done
- update_task_events = [call for call in calls if call[1]['event_type'] == 'UpdateAgentTask']
- assert len(update_task_events) >= 1
- final_update = update_task_events[-1][1]['event_data']
- assert final_update['status'] in ['completed', 'failed']
- assert 'completed_at' in final_update
-
- async def test_agent_emits_step_events(self, agent_with_cloud, mock_cloud_sync, mock_model):
- """Test that agent emits step events."""
- # Configure model to return specific actions
- mock_model.generate_response.side_effect = [
- (Mock(action_type='click', coordinate=[100, 200]), 'Click button'),
- (Mock(action_type='done'), 'Task completed'),
- ]
-
- # Run agent
- await agent_with_cloud.run()
-
- # Check step events
- calls = mock_cloud_sync.send_event.call_args_list
-
- # Should have CreateAgentStep events
- create_step_events = [call for call in calls if call[1]['event_type'] == 'CreateAgentStep']
- assert len(create_step_events) >= 1
-
- first_step = create_step_events[0][1]['event_data']
- assert first_step['step_number'] == 1
- assert first_step['type'] == 'click'
- assert 'started_at' in first_step
-
- # Should have UpdateAgentStep events
- update_step_events = [call for call in calls if call[1]['event_type'] == 'UpdateAgentStep']
- assert len(update_step_events) >= 1
-
- step_update = update_step_events[0][1]['event_data']
- assert step_update['status'] in ['completed', 'failed']
- assert 'completed_at' in step_update
-
- async def test_agent_with_pre_auth_flow(self, mock_browser, mock_model):
- """Test agent with pre-authentication flow."""
- # Create mock cloud sync that starts unauthenticated
- mock_sync = Mock(spec=CloudSyncService)
- mock_sync.send_event = AsyncMock()
- mock_sync.authenticate = AsyncMock(return_value=True)
- mock_sync._authenticated = False
-
- with patch('browser_use.agent.service.CloudSyncService', return_value=mock_sync):
- with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'true'}):
- agent = Agent(
- task='Test task',
- llm=mock_model,
- browser_context=mock_browser,
- )
- agent.cloud_sync = mock_sync
-
- # Run agent
- await agent.run()
-
- # Check that events were sent even without auth
- assert mock_sync.send_event.call_count > 0
-
- # Authenticate
- mock_sync._authenticated = True
- await mock_sync.authenticate()
-
- # Run another task
- agent.task = 'Second task'
- await agent.run()
-
- # Check that authentication was used
- assert mock_sync.authenticate.called
-
- async def test_cloud_sync_disabled(self, mock_browser, mock_model):
- """Test that cloud sync can be disabled."""
- with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'false'}):
- agent = Agent(
- task='Test task',
- llm=mock_model,
- browser_context=mock_browser,
- )
-
- assert agent.cloud_sync is None
-
- # Run agent - should work without cloud sync
- await agent.run()
-
- async def test_event_data_completeness(self, agent_with_cloud, mock_cloud_sync, mock_model):
- """Test that events contain all required data."""
- # Configure model
- mock_model.generate_response.side_effect = [
- (Mock(action_type='type', text='Hello world'), 'Type greeting'),
- (Mock(action_type='done'), 'Task completed'),
- ]
-
- # Run agent
- result = await agent_with_cloud.run()
-
- # Get all events
- calls = mock_cloud_sync.send_event.call_args_list
-
- # Check session event
- session_event = next(call for call in calls if call[1]['event_type'] == 'CreateAgentSession')
- session_data = session_event[1]['event_data']
- assert isinstance(session_data['id'], str)
- assert isinstance(session_data['started_at'], str)
-
- # Check task event
- task_event = next(call for call in calls if call[1]['event_type'] == 'CreateAgentTask')
- task_data = task_event[1]['event_data']
- assert task_data['task'] == 'Test task'
- assert task_data['status'] == 'running'
- assert task_data['agent_session_id'] == session_data['id']
- assert 'model' in task_data
- assert isinstance(task_data['started_at'], str)
-
- # Check step event
- step_event = next(call for call in calls if call[1]['event_type'] == 'CreateAgentStep')
- step_data = step_event[1]['event_data']
- assert step_data['type'] == 'type'
- assert step_data['step_number'] == 1
- assert 'action_data' in step_data
- assert step_data['agent_session_id'] == session_data['id']
- assert 'agent_task_id' in step_data
- assert isinstance(step_data['started_at'], str)
-
- async def test_error_handling_continues(self, agent_with_cloud, mock_cloud_sync):
- """Test that agent continues even if cloud sync fails."""
- # Make cloud sync fail
- mock_cloud_sync.send_event.side_effect = Exception('Network error')
-
- # Run agent - should not raise
- result = await agent_with_cloud.run()
-
- # Agent should complete successfully
- assert result is not None
- assert mock_cloud_sync.send_event.call_count > 0
-
- async def test_eventbus_integration(self, agent_with_cloud, mock_cloud_sync):
- """Test EventBus integration with cloud sync."""
- from bubus import Event
-
- # Access agent's event bus
- event_bus = agent_with_cloud._event_bus
-
- # Emit custom event
- custom_event = Event(type='test_event', data={'test': 'data'})
- await event_bus.emit(custom_event)
-
- # Process any pending events
- await asyncio.sleep(0.1)
-
- # Cloud sync should handle AgentEvent types
- # Check that only expected events were sent to cloud
- calls = mock_cloud_sync.send_event.call_args_list
- event_types = [call[1]['event_type'] for call in calls]
-
- # Should have session and task events, but not the custom test event
- assert 'CreateAgentSession' in event_types
- assert 'CreateAgentTask' in event_types
- assert 'test_event' not in event_types # Custom events not synced
-
- async def test_session_id_persistence(self, mock_browser, mock_model):
- """Test that agent session ID persists across runs."""
- mock_sync = Mock(spec=CloudSyncService)
- mock_sync.send_event = AsyncMock()
- mock_sync._authenticated = True
-
- with patch('browser_use.agent.service.CloudSyncService', return_value=mock_sync):
- with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'true'}):
- # Create first agent
- agent1 = Agent(
- task='First task',
- llm=mock_model,
- browser_context=mock_browser,
- )
- agent1.cloud_sync = mock_sync
-
- # Run first agent
- await agent1.run()
-
- # Get session ID from first run
- session_calls = [
- call for call in mock_sync.send_event.call_args_list if call[1]['event_type'] == 'CreateAgentSession'
- ]
- session_id_1 = session_calls[0][1]['event_data']['id']
-
- # Create second agent with same session
- agent2 = Agent(
- task='Second task',
- llm=mock_model,
- browser_context=mock_browser,
- agent_id=session_id_1, # Reuse session ID
- )
- agent2.cloud_sync = mock_sync
-
- # Clear previous calls
- mock_sync.send_event.reset_mock()
-
- # Run second agent
- await agent2.run()
-
- # Should not create new session, just new task
- session_calls_2 = [
- call for call in mock_sync.send_event.call_args_list if call[1]['event_type'] == 'CreateAgentSession'
- ]
- assert len(session_calls_2) == 0 # No new session
-
- # But should create new task with same session ID
- task_calls = [call for call in mock_sync.send_event.call_args_list if call[1]['event_type'] == 'CreateAgentTask']
- assert len(task_calls) == 1
- assert task_calls[0][1]['event_data']['agent_session_id'] == session_id_1
diff --git a/tests/ci/test_agent_emits_cloud_events.py b/tests/ci/test_agent_emits_cloud_events.py
deleted file mode 100644
index 93e285708..000000000
--- a/tests/ci/test_agent_emits_cloud_events.py
+++ /dev/null
@@ -1,619 +0,0 @@
-"""
-Integration tests for cloud events emitted during agent lifecycle.
-
-Tests that all cloud events defined in cloud_events.py are properly
-emitted in the correct order during agent execution.
-"""
-
-import base64
-import json
-import os
-from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock
-from uuid import UUID
-
-import pytest
-from langchain_core.language_models import BaseChatModel
-from langchain_core.messages import AIMessage
-from pytest_httpserver import HTTPServer
-from uuid_extensions import uuid7str
-
-from browser_use.agent.cloud_events import (
- CreateAgentOutputFileEvent,
- CreateAgentSessionEvent,
- CreateAgentStepEvent,
- CreateAgentTaskEvent,
- UpdateAgentTaskEvent,
-)
-
-# Skip LLM API key verification for tests
-os.environ['SKIP_LLM_API_KEY_VERIFICATION'] = 'true'
-
-from bubus import BaseEvent
-
-from browser_use import Agent
-from browser_use.browser import BrowserSession
-
-
-async def browser_session():
- """Create a real browser session for testing"""
- session = BrowserSession(
- headless=True,
- user_data_dir=None, # Use temporary directory
- )
- yield session
- await session.stop()
-
-
-def mock_llm():
- """Create a mock LLM that immediately returns done action"""
- llm = MagicMock(spec=BaseChatModel)
-
- # Create the JSON response that the agent would parse
- json_response = {
- 'current_state': {
- 'evaluation_previous_goal': 'Starting task',
- 'memory': 'New task to complete',
- 'next_goal': 'Complete the test task',
- },
- 'action': [{'done': {'success': True, 'text': 'Test completed successfully'}}],
- }
-
- # Create a mock response with the JSON
- mock_response = AIMessage(content=json.dumps(json_response))
-
- # Make the LLM return our mock response
- llm.invoke = lambda *args, **kwargs: mock_response
- llm.ainvoke = AsyncMock(return_value=mock_response)
-
- # Mock the with_structured_output method to return parsed objects
- structured_llm = MagicMock()
-
- async def mock_structured_ainvoke(*args, **kwargs):
- # The agent will create its own AgentOutput and ActionModel classes
- # We return the raw response and let the agent parse it
- return {
- 'raw': mock_response,
- 'parsed': None, # Let the agent parse it from the raw JSON
- }
-
- structured_llm.ainvoke = AsyncMock(side_effect=mock_structured_ainvoke)
- llm.with_structured_output = lambda *args, **kwargs: structured_llm
-
- # Set attributes that agent checks
- llm.model_name = 'gpt-4o'
- llm._verified_api_keys = True
- llm._verified_tool_calling_method = 'function_calling'
-
- return llm
-
-
-def event_collector():
- """Collect all events emitted during tests"""
- events = []
- event_order = []
- event_timestamps = []
-
- class EventCollector:
- def __init__(self):
- self.events = events
- self.event_order = event_order
- self.event_timestamps = event_timestamps
-
- async def collect_event(self, event: BaseEvent):
- import time
-
- collection_time = time.time()
- self.events.append(event)
- self.event_order.append(event.event_type)
- self.event_timestamps.append((event.event_type, event.event_created_at, collection_time))
- return 'collected'
-
- def get_events_by_type(self, event_type: str) -> list[BaseEvent]:
- return [e for e in self.events if e.event_type == event_type]
-
- def clear(self):
- self.events.clear()
- self.event_order.clear()
- self.event_timestamps.clear()
-
- return EventCollector()
-
-
-class TestAgentCloudEvents:
- """Test that cloud events are properly emitted during agent lifecycle"""
-
- async def test_agent_lifecycle_events(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
- """Test that all events are emitted in the correct order during agent lifecycle"""
-
- # Setup a test page
- httpserver.expect_request('/').respond_with_data('<html><body><h1>Test Page</h1></body></html>', content_type='text/html')
-
- # Navigate to test page
- await browser_session.navigate(httpserver.url_for('/'))
-
- # Create agent
- agent = Agent(
- task='Test task',
- llm=mock_llm,
- browser_session=browser_session,
- generate_gif=False, # Don't generate GIF for faster test
- )
-
- # Subscribe to all events
- agent.eventbus.on('*', event_collector.collect_event)
-
- # Run the agent
- history = await agent.run(max_steps=5)
-
- # Verify we got a successful completion
- assert history.is_done()
- assert history.is_successful()
-
- # Verify event order
- assert len(event_collector.event_order) >= 4, (
- f'Expected at least 4 events, got {len(event_collector.event_order)}: {event_collector.event_order}'
- )
-
- # Check the exact order of events - they should be processed in FIFO order
- assert event_collector.event_order[0] == 'CreateAgentSession', (
- f'First event should be CreateAgentSession, got {event_collector.event_order[0]}'
- )
- assert event_collector.event_order[1] == 'CreateAgentTask', (
- f'Second event should be CreateAgentTask, got {event_collector.event_order[1]}'
- )
- assert event_collector.event_order[2] == 'CreateAgentStep', (
- f'Third event should be CreateAgentStep, got {event_collector.event_order[2]}'
- )
- assert event_collector.event_order[3] == 'UpdateAgentTask', (
- f'Fourth event should be UpdateAgentTask, got {event_collector.event_order[3]}'
- )
-
- # Verify that events were collected in the same order they were emitted (FIFO)
- collection_times = [t[2] for t in event_collector.event_timestamps]
- for i in range(1, len(collection_times)):
- assert collection_times[i] >= collection_times[i - 1], (
- f'Event {i} was collected before event {i - 1}, violating FIFO order'
- )
-
- # Verify emission times follow expected order (Session and Task should be emitted before Step)
- session_event = next(e for e in event_collector.events if e.event_type == 'CreateAgentSession')
- task_event = next(e for e in event_collector.events if e.event_type == 'CreateAgentTask')
- step_event = next(e for e in event_collector.events if e.event_type == 'CreateAgentStep')
- update_event = next(e for e in event_collector.events if e.event_type == 'UpdateAgentTask')
-
- # Session should be created before Task (foreign key constraint)
- assert session_event.event_created_at <= task_event.event_created_at, (
- 'Session event should be emitted before or at same time as Task event'
- )
- # Task should be created before Step (foreign key constraint)
- assert task_event.event_created_at <= step_event.event_created_at, (
- 'Task event should be emitted before or at same time as Step event'
- )
- # All create events should happen before update
- assert step_event.event_created_at <= update_event.event_created_at, (
- 'Step event should be emitted before or at same time as UpdateTask event'
- )
-
- # Verify CreateAgentSessionEvent
- assert isinstance(session_event, CreateAgentSessionEvent)
- assert session_event.id # Should have session ID
- assert session_event.browser_session_id == browser_session.id
- assert session_event.user_id == '' # Empty for agent, filled by cloud handler
-
- # Verify CreateAgentTaskEvent
- assert isinstance(task_event, CreateAgentTaskEvent)
- assert task_event.id # Should have task ID
- assert task_event.agent_session_id == session_event.id
- assert task_event.task == 'Test task'
- assert task_event.event_started_at is not None
- assert task_event.stopped is False
- assert task_event.paused is False
- assert task_event.done_output is None # Not done yet at creation
-
- # Verify CreateAgentStepEvent
- assert isinstance(step_event, CreateAgentStepEvent)
- assert step_event.agent_task_id == task_event.id
- assert step_event.step == 2 # Step is incremented before event is emitted
- assert step_event.actions # Should have actions
- assert step_event.url == httpserver.url_for('/')
-
- # Verify screenshot is captured and base64 encoded
- assert step_event.screenshot_url is not None, 'Screenshot should be captured for each step'
- assert step_event.screenshot_url.startswith('data:image/png;base64,'), (
- f'Screenshot should be base64 PNG data URL, got: {step_event.screenshot_url[:50]}...'
- )
-
- # Decode and verify the screenshot is a valid PNG
- try:
- base64_data = step_event.screenshot_url.split(',')[1]
- screenshot_bytes = base64.b64decode(base64_data)
-
- # Verify PNG signature (starts with PNG magic bytes)
- assert screenshot_bytes.startswith(b'\x89PNG\r\n\x1a\n'), (
- f'Invalid PNG signature. First 8 bytes: {screenshot_bytes[:8]}'
- )
-
- # Verify screenshot has reasonable size
- assert len(screenshot_bytes) > 1000, f'Screenshot too small: {len(screenshot_bytes)} bytes'
-
- print(f'Screenshot captured: {len(screenshot_bytes)} bytes')
-
- except Exception as e:
- pytest.fail(f'Failed to decode screenshot: {e}')
-
- # Verify UpdateAgentTaskEvent
- assert isinstance(update_event, UpdateAgentTaskEvent)
- assert update_event.id == task_event.id # Should update the same task
- assert update_event.done_output is not None # Should have final output
- assert update_event.finished_at is not None # Should have completion time
- assert update_event.stopped is False
- assert update_event.paused is False
- assert update_event.agent_state is not None
-
- async def test_agent_with_gif_generation_events(
- self, mock_llm, browser_session, event_collector, httpserver: HTTPServer, tmp_path
- ):
- """Test that GIF generation triggers CreateAgentOutputFileEvent with real base64 content"""
-
- # Setup a test page
- httpserver.expect_request('/').respond_with_data(
- '<html><body><h1>Test Page for GIF</h1></body></html>', content_type='text/html'
- )
-
- # Navigate to test page
- await browser_session.navigate(httpserver.url_for('/'))
-
- # Create agent with GIF generation (using True to auto-generate path)
- agent = Agent(
- task='Test task with GIF',
- llm=mock_llm,
- browser_session=browser_session,
- generate_gif=True, # Use True to auto-generate path
- )
-
- # Subscribe to all events
- agent.eventbus.on('*', event_collector.collect_event)
-
- # Run the agent
- history = await agent.run(max_steps=5)
-
- # Verify CreateAgentOutputFileEvent was emitted
- output_file_events = [e for e in event_collector.events if e.event_type == 'CreateAgentOutputFile']
- assert len(output_file_events) == 1
-
- output_event = output_file_events[0]
- assert isinstance(output_event, CreateAgentOutputFileEvent)
- assert output_event.file_name.endswith('.gif'), f'Expected .gif file, got {output_event.file_name}'
- assert output_event.content_type == 'image/gif'
- assert output_event.task_id # Should reference the task
- assert output_event.file_content is not None, 'GIF file content should not be None'
- assert len(output_event.file_content) > 0, 'GIF file content should not be empty'
-
- # Decode and verify the base64 content is a valid GIF
- try:
- gif_bytes = base64.b64decode(output_event.file_content)
- except Exception as e:
- pytest.fail(f'Failed to decode base64 content: {e}')
-
- # Verify GIF file signature (starts with 'GIF87a' or 'GIF89a')
- assert gif_bytes.startswith(b'GIF87a') or gif_bytes.startswith(b'GIF89a'), (
- f'Invalid GIF signature. First 6 bytes: {gif_bytes[:6]}'
- )
-
- # Verify GIF has reasonable size (should be more than minimal header)
- assert len(gif_bytes) > 100, f'GIF too small: {len(gif_bytes)} bytes'
-
- # Verify the file was actually created if a path was specified
- # Note: Agent might create temp files, so we just verify the event has the content
- print(f'GIF generated: {output_event.file_name}, size: {len(gif_bytes)} bytes')
-
- # Verify event order - GIF event should come after UpdateAgentTask
- update_index = event_collector.event_order.index('UpdateAgentTask')
- gif_index = event_collector.event_order.index('CreateAgentOutputFile')
- assert gif_index > update_index, 'GIF event should come after UpdateAgentTask'
-
- async def test_agent_step_screenshots_captured(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
- """Test that screenshots are captured and properly base64 encoded for each step"""
-
- # Setup test pages for multi-step interaction
- httpserver.expect_request('/page1').respond_with_data(
- '<html><body><h1>Page 1</h1><button onclick="window.location=\'/page2\'">Go to Page 2</button></body></html>',
- content_type='text/html',
- )
- httpserver.expect_request('/page2').respond_with_data(
- '<html><body><h1>Page 2</h1><p>Task completed!</p></body></html>', content_type='text/html'
- )
-
- # Navigate to first page
- await browser_session.navigate(httpserver.url_for('/page1'))
-
- # Create a mock LLM that performs navigation then completes
- llm = MagicMock(spec=BaseChatModel)
- step_count = 0
- base_url = httpserver.url_for('')
-
- def get_response_for_step(*args, **kwargs):
- nonlocal step_count
- step_count += 1
-
- if step_count == 1:
- # First step: navigate to page 2
- json_response = {
- 'current_state': {
- 'evaluation_previous_goal': 'Starting on page 1',
- 'memory': 'Need to navigate to page 2',
- 'next_goal': 'Navigate to page 2',
- },
- 'action': [{'go_to_url': {'url': f'{base_url}page2'}}],
- }
- else:
- # Second step: done
- json_response = {
- 'current_state': {
- 'evaluation_previous_goal': 'Successfully navigated to page 2',
- 'memory': 'Reached final page',
- 'next_goal': 'Task complete',
- },
- 'action': [{'done': {'success': True, 'text': 'Successfully navigated to page 2'}}],
- }
-
- return AIMessage(content=json.dumps(json_response))
-
- llm.invoke = get_response_for_step
- llm.ainvoke = AsyncMock(side_effect=get_response_for_step)
-
- # Mock structured output
- structured_llm = MagicMock()
-
- async def mock_structured(*args, **kwargs):
- response = get_response_for_step()
- return {'raw': response, 'parsed': None}
-
- structured_llm.ainvoke = AsyncMock(side_effect=mock_structured)
- llm.with_structured_output = lambda *args, **kwargs: structured_llm
-
- llm.model_name = 'gpt-4o'
- llm._verified_api_keys = True
- llm._verified_tool_calling_method = 'function_calling'
-
- # Create agent
- agent = Agent(
- task='Navigate from page 1 to page 2',
- llm=llm,
- browser_session=browser_session,
- generate_gif=False,
- )
-
- # Subscribe to all events
- agent.eventbus.on('*', event_collector.collect_event)
-
- # Run the agent
- history = await agent.run(max_steps=3)
-
- # Verify completion
- assert history.is_done()
- assert history.is_successful()
-
- # Get all step events
- step_events = [e for e in event_collector.events if e.event_type == 'CreateAgentStep']
- assert len(step_events) >= 2, f'Expected at least 2 step events, got {len(step_events)}'
-
- # Verify each step has a valid screenshot
- for i, step_event in enumerate(step_events):
- assert isinstance(step_event, CreateAgentStepEvent)
-
- # Check screenshot exists and is properly formatted
- assert step_event.screenshot_url is not None, f'Step {i + 1} missing screenshot'
- assert step_event.screenshot_url.startswith('data:image/png;base64,'), (
- f'Step {i + 1} screenshot should be base64 PNG data URL'
- )
-
- # Decode and validate the screenshot
- try:
- base64_data = step_event.screenshot_url.split(',')[1]
- screenshot_bytes = base64.b64decode(base64_data)
-
- # Verify PNG signature
- assert screenshot_bytes.startswith(b'\x89PNG\r\n\x1a\n'), f'Step {i + 1} has invalid PNG signature'
-
- # Verify reasonable screenshot size
- assert len(screenshot_bytes) > 1000, f'Step {i + 1} screenshot too small: {len(screenshot_bytes)} bytes'
-
- print(f'Step {i + 1} screenshot: {len(screenshot_bytes)} bytes')
-
- except Exception as e:
- pytest.fail(f'Failed to decode step {i + 1} screenshot: {e}')
-
- print(f'Successfully validated screenshots for {len(step_events)} steps')
-
-
-class TestCloudEventValidation:
- """Test cloud event validation and structure"""
-
- async def test_agent_session_event_structure(self):
- """Test CreateAgentSessionEvent structure and validation"""
- event = CreateAgentSessionEvent(
- id='test-session-id',
- user_id='test-user',
- browser_session_id='test-browser-session-id',
- browser_session_live_url='https://example.com',
- browser_session_cdp_url='ws://localhost:9222',
- browser_state={
- 'viewport': {'width': 1920, 'height': 1080},
- 'user_agent': 'Mozilla/5.0 Test User Agent',
- 'headless': True,
- },
- )
-
- # Test validation
- assert event.event_type == 'CreateAgentSession'
- assert event.id == 'test-session-id'
- assert event.user_id == 'test-user'
- assert event.browser_session_id == 'test-browser-session-id'
- assert event.browser_state['viewport']['width'] == 1920
- assert not event.browser_session_stopped
-
- async def test_agent_task_event_structure(self):
- """Test CreateAgentTaskEvent structure and validation"""
- session_id = uuid7str()
- task_id = uuid7str()
-
- event = CreateAgentTaskEvent(
- id=task_id,
- user_id='test-user',
- agent_session_id=session_id,
- task='Test task',
- llm_model='gpt-4o',
- done_output='Task completed successfully',
- started_at=datetime.now(timezone.utc),
- finished_at=datetime.now(timezone.utc),
- agent_state={'n_steps': 1},
- )
-
- # Test validation
- assert event.event_type == 'CreateAgentTask'
- assert event.id == task_id
- assert event.user_id == 'test-user'
- assert event.agent_session_id == session_id
- assert event.task == 'Test task'
- assert event.llm_model == 'gpt-4o'
- assert not event.stopped
- assert not event.paused
- assert isinstance(event.agent_state, dict)
-
- async def test_agent_step_event_structure(self):
- """Test CreateAgentStepEvent structure and validation"""
- task_id = uuid7str()
-
- event = CreateAgentStepEvent(
- id=uuid7str(),
- user_id='test-user',
- agent_task_id=task_id,
- step=1,
- evaluation_previous_goal='Starting the task',
- memory='Memory from previous steps',
- next_goal='Complete the current goal',
- actions=[{'name': 'click', 'args': {'selector': 'button#submit'}}],
- url='https://example.com',
- screenshot_url='data:image/png;base64,iVBORw0KGgo=',
- )
-
- # Test validation
- assert event.event_type == 'CreateAgentStep'
- assert event.step == 1
- assert event.user_id == 'test-user'
- assert event.agent_task_id == task_id
- assert len(event.actions) == 1
- assert event.actions[0]['name'] == 'click'
- assert event.url == 'https://example.com'
- assert event.screenshot_url.startswith('data:image/png;base64,')
-
- async def test_update_agent_task_event_structure(self):
- """Test UpdateAgentTaskEvent structure and validation"""
- task_id = uuid7str()
-
- event = UpdateAgentTaskEvent(
- id=task_id, # The task ID to update
- user_id='test-user',
- # Only update some fields
- stopped=True,
- done_output='Task completed with results',
- finished_at=datetime.now(timezone.utc),
- agent_state={'final_state': True, 'n_steps': 10},
- )
-
- # Test validation
- assert event.event_type == 'UpdateAgentTask'
- assert event.id == task_id
- assert event.user_id == 'test-user'
- assert event.stopped is True
- assert event.paused is None # Not updated
- assert event.done_output == 'Task completed with results'
- assert event.agent_state == {'final_state': True, 'n_steps': 10}
-
- def test_max_string_length_validation(self):
- """Test that string fields enforce max length"""
- # Create event with very long task
- long_task = 'x' * 10000 # Longer than MAX_TASK_LENGTH (5000)
-
- # Should raise validation error for string too long
- with pytest.raises(ValueError, match='String should have at most 5000 characters'):
- CreateAgentTaskEvent(
- user_id='test',
- agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
- llm_model='test-model',
- task=long_task,
- )
-
- def test_all_events_have_required_base_fields(self):
- """Test that all events have required base fields"""
- # Create a few events
- events_to_test = [
- CreateAgentSessionEvent(
- id='0683fb03-c5da-79c9-8000-d3a39c47c651',
- user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
- browser_session_id='test-browser',
- browser_session_live_url='https://example.com',
- browser_session_cdp_url='ws://localhost:9222',
- ),
- CreateAgentTaskEvent(
- id='0683fb03-c5da-79c9-8000-d3a39c47c652',
- user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
- agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c651',
- task='test',
- llm_model='gpt-4o',
- ),
- CreateAgentStepEvent(
- user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
- agent_task_id='0683fb03-c5da-79c9-8000-d3a39c47c652',
- step=1,
- evaluation_previous_goal='eval',
- memory='mem',
- next_goal='next',
- actions=[],
- ),
- CreateAgentOutputFileEvent(
- user_id='test',
- task_id='0683fb03-c5da-79c9-8000-d3a39c47c652',
- file_name='test.txt',
- file_content=base64.b64encode(b'test').decode(),
- ),
- UpdateAgentTaskEvent(
- id='0683fb03-c5da-79c9-8000-d3a39c47c652',
- user_id='test',
- stopped=True,
- done_output='Task completed',
- finished_at=datetime.now(timezone.utc),
- ),
- ]
-
- # Check all events have required fields
- for event in events_to_test:
- # Base event fields
- assert isinstance(event, BaseEvent)
- assert event.event_type is not None
- assert event.event_id is not None
- assert event.event_created_at is not None
- assert isinstance(event.event_path, list)
-
- # Check event_id is a valid UUID string
- try:
- # Should be able to parse as UUID
- uuid_obj = UUID(event.event_id)
- assert str(uuid_obj) == event.event_id
- except ValueError:
- pytest.fail(f'Invalid UUID in event_id: {event.event_id}')
-
- def test_event_type_frozen_field(self):
- """Test that event_type fields are frozen"""
- event = CreateAgentTaskEvent(
- user_id='test', agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659', llm_model='test-model', task='test'
- )
-
- # Should not be able to change event_type
- with pytest.raises(ValueError):
- event.event_type = 'DifferentType'
diff --git a/tests/ci/test_live_oauth2_integration.py b/tests/ci/test_live_oauth2_integration.py
deleted file mode 100644
index 058e67880..000000000
--- a/tests/ci/test_live_oauth2_integration.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""
-Live integration test for OAuth2 device flow with real cloud backend.
-
-This test is skipped by default and only runs when explicitly selected.
-Run with: pytest tests/ci/test_live_oauth2_integration.py::test_live_oauth2_integration -v
-"""
-
-import asyncio
-import json
-import logging
-import os
-import tempfile
-from pathlib import Path
-
-import pytest
-
-from browser_use import Agent
-from browser_use.browser.browser import BrowserSession
-from browser_use.sync.service import CloudSyncService
-from tests.ci.mocks import create_mock_llm
-
-logger = logging.getLogger(__name__)
-
-
-def create_oauth_mock_llm():
- """Create a mock LLM that follows a simple script for OAuth testing."""
- actions = [
- # First action - navigate to a simple page
- json.dumps(
- {
- 'current_state': {
- 'evaluation_previous_goal': 'Starting OAuth integration test',
- 'memory': 'Beginning test sequence',
- 'next_goal': 'Navigate to example page',
- },
- 'action': [
- {'goto': {'url': 'https://example.com', 'reasoning': 'Starting the test by navigating to a simple webpage'}}
- ],
- }
- ),
- # Second action - complete the test
- json.dumps(
- {
- 'current_state': {
- 'evaluation_previous_goal': 'Successfully navigated to example page',
- 'memory': 'OAuth flow test initiated',
- 'next_goal': 'Complete test',
- },
- 'action': [{'done': {'text': 'OAuth integration test completed - cloud sync initiated', 'success': True}}],
- }
- ),
- ]
- return create_mock_llm(actions)
-
-
-def temp_browser_profile():
- """Create a temporary browser profile directory."""
- with tempfile.TemporaryDirectory() as tmpdir:
- profile_dir = Path(tmpdir) / 'browser_profile'
- profile_dir.mkdir(parents=True, exist_ok=True)
- yield str(profile_dir)
-
-
[email protected](not os.getenv('RUN_LIVE_TESTS'), reason='Live integration tests only run when RUN_LIVE_TESTS=1 is set')
-async def test_live_oauth2_integration(temp_browser_profile):
- """
- Live integration test for OAuth2 device flow.
-
- This test:
- 1. Creates a real browser session
- 2. Sets up cloud sync with real backend
- 3. Runs an agent with a mocked LLM
- 4. Verifies the OAuth2 device flow is initiated
- 5. Sends real events to the cloud backend
-
- Environment variables required:
- - RUN_LIVE_TESTS=1 (to enable the test)
- - BROWSER_USE_CLOUD_URL (optional, defaults to https://cloud.browser-use.com)
- """
-
- # Configuration
- backend_url = os.getenv('BROWSER_USE_CLOUD_URL', 'http://localhost:8000')
- logger.info(f'Running live integration test against: {backend_url}')
-
- # Create mock LLM
- mock_llm = create_oauth_mock_llm()
-
- # Set environment variables for cloud sync
- os.environ['BROWSERUSE_CLOUD_SYNC'] = 'true'
- os.environ['BROWSER_USE_CLOUD_URL'] = backend_url
-
- # Create browser session with real profile
- browser_session = BrowserSession(
- user_data_dir=temp_browser_profile,
- headless=False, # Show browser for visual confirmation
- )
-
- # Create agent (cloud sync will be auto-enabled via environment variables)
- agent = Agent(
- task='Visit the Browser Use login page and demonstrate OAuth integration',
- llm=mock_llm,
- browser_session=browser_session,
- )
-
- # Run the agent for a short time
- logger.info('Starting agent with OAuth2 integration...')
-
- # Run with timeout to prevent hanging
- try:
- await asyncio.wait_for(agent.run(), timeout=60)
- except TimeoutError:
- logger.info('Agent run timed out (expected for live test)')
-
- # Get cloud sync from agent
- cloud_sync = agent.cloud_sync
- assert cloud_sync is not None, 'Cloud sync should be enabled'
-
- # Wait for any pending cloud sync operations
- if cloud_sync.auth_task and not cloud_sync.auth_task.done():
- try:
- await asyncio.wait_for(cloud_sync.auth_task, timeout=10)
- except TimeoutError:
- logger.info('Auth task still running (expected for live test)')
-
- # Verify cloud sync was attempted
- assert cloud_sync.auth_client is not None, 'Auth client should be initialized'
-
- logger.info('✅ Live OAuth2 integration test completed successfully')
- logger.info(f'🔗 LLM invocations: {mock_llm.invoke.call_count if hasattr(mock_llm.invoke, "call_count") else "mock"}')
-
- # Print session ID for manual verification
- if cloud_sync.session_id:
- logger.info(f'📊 Agent session ID: {cloud_sync.session_id}')
- logger.info(f'🌐 Check session at: {backend_url}/agent/{cloud_sync.session_id}')
-
- # Test completed - removed excessive sleep
-
-
[email protected](not os.getenv('RUN_LIVE_TESTS'), reason='Live integration tests only run when RUN_LIVE_TESTS=1 is set')
-async def test_live_cloud_sync_events():
- """
- Test that cloud sync can send events to the real backend.
-
- This is a simpler test that just verifies event sending works.
- """
-
- backend_url = os.getenv('BROWSER_USE_CLOUD_URL', 'http://localhost:8000')
- logger.info(f'Testing cloud sync against: {backend_url}')
-
- # Create cloud sync service
- cloud_sync = CloudSyncService(base_url=backend_url, enable_auth=True)
-
- # Import event types
- from uuid import uuid4
-
- from browser_use.agent.cloud_events import CreateAgentSessionEvent
- from browser_use.sync.auth import TEMP_USER_ID
-
- # Create a test session event
- session_event = CreateAgentSessionEvent(
- user_id=TEMP_USER_ID,
- id=str(uuid4()),
- browser_session_id=str(uuid4()),
- browser_session_live_url='https://example.com',
- browser_session_cdp_url='ws://localhost:9222',
- browser_state={'test': 'live_integration'},
- is_source_api=True,
- )
-
- # Send event to cloud
- logger.info('Sending test event to cloud...')
- try:
- await cloud_sync.handle_event(session_event)
- logger.info('✅ Event sent successfully')
- except Exception as e:
- logger.error(f'❌ Failed to send event: {e}')
- raise
-
- # Wait a moment for processing
- await asyncio.sleep(2)
-
- logger.info('✅ Cloud sync event test completed')
-
- if cloud_sync.session_id:
- logger.info(f'📊 Session ID: {cloud_sync.session_id}')
-
- # Test completed - removed excessive sleep
-
-
-if __name__ == '__main__':
- # Allow running the test directly with: python test_live_oauth2_integration.py
- import sys
-
- if len(sys.argv) > 1 and sys.argv[1] == '--live':
- os.environ['RUN_LIVE_TESTS'] = '1'
- pytest.main([__file__, '-v', '-s'])
- else:
- print('To run live integration tests:')
- print('1. Set environment variable: export RUN_LIVE_TESTS=1')
- print('2. Run: pytest tests/ci/test_live_oauth2_integration.py -v')
- print('3. Or run directly: python test_live_oauth2_integration.py --live')
diff --git a/tests/ci/test_sync_agent_events.py b/tests/ci/test_sync_agent_events.py
new file mode 100644
index 000000000..687e72c55
--- /dev/null
+++ b/tests/ci/test_sync_agent_events.py
@@ -0,0 +1,529 @@
+"""
+Streamlined tests for cloud events emitted during agent lifecycle.
+
+Tests the most critical event flows without excessive duplication.
+"""
+
+import base64
+import json
+import os
+from unittest.mock import AsyncMock, MagicMock, Mock, patch
+from uuid import UUID
+
+import pytest
+from dotenv import load_dotenv
+
+# Load environment variables before any imports
+load_dotenv()
+from langchain_core.language_models import BaseChatModel
+from langchain_core.messages import AIMessage
+from pytest_httpserver import HTTPServer
+
+from browser_use.agent.cloud_events import (
+ CreateAgentOutputFileEvent,
+ CreateAgentSessionEvent,
+ CreateAgentStepEvent,
+ CreateAgentTaskEvent,
+ UpdateAgentTaskEvent,
+)
+
+# Skip LLM API key verification for tests
+os.environ['SKIP_LLM_API_KEY_VERIFICATION'] = 'true'
+
+from bubus import BaseEvent
+
+from browser_use import Agent
+from browser_use.browser import BrowserSession
+from browser_use.sync.service import CloudSync
+from tests.ci.mocks import create_mock_llm
+
+
+async def browser_session():
+ """Create a real browser session for testing"""
+ session = BrowserSession(
+ headless=True,
+ user_data_dir=None, # Use temporary directory
+ )
+ yield session
+ await session.stop()
+
+
+def mock_llm():
+ """Create a mock LLM that immediately returns done action"""
+ llm = MagicMock(spec=BaseChatModel)
+
+ # Create the JSON response that the agent would parse
+ json_response = {
+ 'current_state': {
+ 'evaluation_previous_goal': 'Starting task',
+ 'memory': 'New task to complete',
+ 'next_goal': 'Complete the test task',
+ },
+ 'action': [{'done': {'success': True, 'text': 'Test completed successfully'}}],
+ }
+
+ # Create a mock response with the JSON
+ mock_response = AIMessage(content=json.dumps(json_response))
+
+ # Make the LLM return our mock response
+ llm.invoke = lambda *args, **kwargs: mock_response
+ llm.ainvoke = AsyncMock(return_value=mock_response)
+
+ # Mock the with_structured_output method to return parsed objects
+ structured_llm = MagicMock()
+
+ async def mock_structured_ainvoke(*args, **kwargs):
+ # The agent will create its own AgentOutput and ActionModel classes
+ # We return the raw response and let the agent parse it
+ return {
+ 'raw': mock_response,
+ 'parsed': None, # Let the agent parse it from the raw JSON
+ }
+
+ structured_llm.ainvoke = AsyncMock(side_effect=mock_structured_ainvoke)
+ llm.with_structured_output = lambda *args, **kwargs: structured_llm
+
+ # Set attributes that agent checks
+ llm.model_name = 'gpt-4o'
+ llm._verified_api_keys = True
+ llm._verified_tool_calling_method = 'function_calling'
+
+ return llm
+
+
+def event_collector():
+ """Collect all events emitted during tests"""
+ events = []
+ event_order = []
+
+ class EventCollector:
+ def __init__(self):
+ self.events = events
+ self.event_order = event_order
+
+ async def collect_event(self, event: BaseEvent):
+ self.events.append(event)
+ self.event_order.append(event.event_type)
+ return 'collected'
+
+ def get_events_by_type(self, event_type: str) -> list[BaseEvent]:
+ return [e for e in self.events if e.event_type == event_type]
+
+ def clear(self):
+ self.events.clear()
+ self.event_order.clear()
+
+ return EventCollector()
+
+
+def mock_cloud_sync():
+ """Create mocked cloud sync service."""
+ sync = Mock(spec=CloudSync)
+ sync.send_event = AsyncMock()
+ sync.authenticate = AsyncMock(return_value=True)
+ sync._authenticated = True
+ sync.handle_event = AsyncMock()
+ return sync
+
+
+def agent_with_cloud(browser_session, mock_cloud_sync):
+ """Create agent with cloud sync enabled."""
+ with patch('browser_use.sync.CloudSync', return_value=mock_cloud_sync):
+ with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'true'}):
+ agent = Agent(
+ task='Test task',
+ llm=create_mock_llm(),
+ browser_session=browser_session,
+ )
+ return agent
+
+
+class TestAgentEventLifecycle:
+ """Test critical agent event flows with minimal duplication"""
+
+ async def test_agent_lifecycle_events(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
+ """Test that all events are emitted in the correct order during agent lifecycle"""
+
+ # Setup a test page
+ httpserver.expect_request('/').respond_with_data('<html><body><h1>Test Page</h1></body></html>', content_type='text/html')
+
+ # Navigate to test page
+ await browser_session.navigate(httpserver.url_for('/'))
+
+ # Patch environment variables to use localhost for CloudSync
+ with patch.dict(
+ os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000', 'BROWSER_USE_CLOUD_UI_URL': 'http://localhost:3000'}
+ ):
+ # Create agent
+ agent = Agent(
+ task='Test task',
+ llm=mock_llm,
+ browser_session=browser_session,
+ generate_gif=False, # Don't generate GIF for faster test
+ )
+
+ # Subscribe to all events
+ agent.eventbus.on('*', event_collector.collect_event)
+
+ # Run the agent
+ history = await agent.run(max_steps=5)
+
+ # Verify we got a successful completion
+ assert history.is_done()
+ assert history.is_successful()
+
+ # Verify event order - should have core events
+ assert len(event_collector.event_order) >= 4, (
+ f'Expected at least 4 events, got {len(event_collector.event_order)}: {event_collector.event_order}'
+ )
+
+ # Check the exact order of events - they should be processed in FIFO order
+ assert event_collector.event_order[0] == 'CreateAgentSessionEvent'
+ assert event_collector.event_order[1] == 'CreateAgentTaskEvent'
+ assert event_collector.event_order[2] == 'CreateAgentStepEvent'
+ assert event_collector.event_order[3] == 'UpdateAgentTaskEvent'
+
+ # Verify events have required data
+ session_event = next(e for e in event_collector.events if e.event_type == 'CreateAgentSessionEvent')
+ task_event = next(e for e in event_collector.events if e.event_type == 'CreateAgentTaskEvent')
+ step_event = next(e for e in event_collector.events if e.event_type == 'CreateAgentStepEvent')
+ update_event = next(e for e in event_collector.events if e.event_type == 'UpdateAgentTaskEvent')
+
+ # Basic validation
+ assert isinstance(session_event, CreateAgentSessionEvent)
+ assert session_event.id
+ assert session_event.browser_session_id == browser_session.id
+
+ assert isinstance(task_event, CreateAgentTaskEvent)
+ assert task_event.id
+ assert task_event.agent_session_id == session_event.id
+ assert task_event.task == 'Test task'
+
+ assert isinstance(step_event, CreateAgentStepEvent)
+ assert step_event.agent_task_id == task_event.id
+ assert step_event.step == 2 # Step is incremented before event is emitted
+ assert step_event.url == httpserver.url_for('/')
+
+ assert isinstance(update_event, UpdateAgentTaskEvent)
+ assert update_event.id == task_event.id
+ assert update_event.done_output is not None
+
+ async def test_agent_with_gif_generation(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
+ """Test that GIF generation triggers CreateAgentOutputFileEvent"""
+
+ # Setup a test page
+ httpserver.expect_request('/').respond_with_data('<html><body><h1>GIF Test</h1></body></html>', content_type='text/html')
+ await browser_session.navigate(httpserver.url_for('/'))
+
+ # Patch environment variables to use localhost for CloudSync
+ with patch.dict(
+ os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000', 'BROWSER_USE_CLOUD_UI_URL': 'http://localhost:3000'}
+ ):
+ # Create agent with GIF generation
+ agent = Agent(
+ task='Test task with GIF',
+ llm=mock_llm,
+ browser_session=browser_session,
+ generate_gif=True, # Enable GIF generation
+ )
+
+ # Subscribe to all events
+ agent.eventbus.on('*', event_collector.collect_event)
+
+ # Run the agent
+ history = await agent.run(max_steps=5)
+
+ # Verify CreateAgentOutputFileEvent was emitted
+ output_file_events = event_collector.get_events_by_type('CreateAgentOutputFileEvent')
+ assert len(output_file_events) == 1
+
+ output_event = output_file_events[0]
+ assert isinstance(output_event, CreateAgentOutputFileEvent)
+ assert output_event.file_name.endswith('.gif')
+ assert output_event.content_type == 'image/gif'
+ assert output_event.task_id
+ assert output_event.file_content is not None
+ assert len(output_event.file_content) > 0
+
+ # Decode and verify the base64 content is a valid GIF
+ gif_bytes = base64.b64decode(output_event.file_content)
+ assert gif_bytes.startswith(b'GIF87a') or gif_bytes.startswith(b'GIF89a')
+ assert len(gif_bytes) > 100 # Should be a real GIF file
+
+ async def test_step_screenshot_capture(self, mock_llm, browser_session, event_collector, httpserver: HTTPServer):
+ """Test that screenshots are captured for each step"""
+
+ # Setup test page
+ httpserver.expect_request('/').respond_with_data(
+ '<html><body><h1>Screenshot Test</h1></body></html>', content_type='text/html'
+ )
+ await browser_session.navigate(httpserver.url_for('/'))
+
+ # Patch environment variables to use localhost for CloudSync
+ with patch.dict(
+ os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000', 'BROWSER_USE_CLOUD_UI_URL': 'http://localhost:3000'}
+ ):
+ # Create agent
+ agent = Agent(
+ task='Test screenshot capture',
+ llm=mock_llm,
+ browser_session=browser_session,
+ generate_gif=False,
+ )
+
+ # Subscribe to all events
+ agent.eventbus.on('*', event_collector.collect_event)
+
+ # Run the agent
+ await agent.run(max_steps=3)
+
+ # Get all step events
+ step_events = event_collector.get_events_by_type('CreateAgentStepEvent')
+ assert len(step_events) >= 1
+
+ # Verify each step has a valid screenshot
+ for step_event in step_events:
+ assert isinstance(step_event, CreateAgentStepEvent)
+ assert step_event.screenshot_url is not None
+ assert step_event.screenshot_url.startswith('data:image/png;base64,')
+
+ # Decode and validate the screenshot
+ base64_data = step_event.screenshot_url.split(',')[1]
+ screenshot_bytes = base64.b64decode(base64_data)
+
+ # Verify PNG signature
+ assert screenshot_bytes.startswith(b'\x89PNG\r\n\x1a\n')
+ assert len(screenshot_bytes) > 1000 # Should be a real screenshot
+
+
+class TestAgentCloudIntegration:
+ """Test that agent properly integrates with cloud sync service"""
+
+ async def test_agent_emits_events_to_cloud(self, agent_with_cloud, mock_cloud_sync):
+ """Test that agent emits all required events to cloud sync."""
+ # Run agent
+ await agent_with_cloud.run()
+
+ # Check that events were sent to cloud sync
+ calls = mock_cloud_sync.handle_event.call_args_list
+ assert len(calls) >= 4 # At minimum: session, task, step, update
+
+ # Verify we have the core event types
+ event_types = [call.args[0].event_type for call in calls]
+ assert 'CreateAgentSessionEvent' in event_types
+ assert 'CreateAgentTaskEvent' in event_types
+ assert 'CreateAgentStepEvent' in event_types
+ assert 'UpdateAgentTaskEvent' in event_types
+
+ # Verify event content
+ session_events = [call for call in calls if call.args[0].event_type == 'CreateAgentSessionEvent']
+ task_events = [call for call in calls if call.args[0].event_type == 'CreateAgentTaskEvent']
+ step_events = [call for call in calls if call.args[0].event_type == 'CreateAgentStepEvent']
+
+ assert len(session_events) == 1
+ assert len(task_events) == 1
+ assert len(step_events) >= 1
+
+ # Verify event relationships
+ session_event = session_events[0].args[0]
+ task_event = task_events[0].args[0]
+ step_event = step_events[0].args[0]
+
+ assert task_event.agent_session_id == session_event.id
+ assert step_event.agent_task_id == task_event.id
+
+ async def test_agent_emits_session_start_event(self, agent_with_cloud, mock_cloud_sync):
+ """Test that agent emits session start event."""
+ # Run agent
+ await agent_with_cloud.run()
+
+ # Check that session start event was sent
+ calls = mock_cloud_sync.handle_event.call_args_list
+ session_events = [call for call in calls if call.args[0].event_type == 'CreateAgentSessionEvent']
+
+ assert len(session_events) == 1
+ event = session_events[0].args[0]
+ assert hasattr(event, 'id')
+ assert hasattr(event, 'browser_session_id')
+
+ async def test_agent_emits_task_events(self, agent_with_cloud, mock_cloud_sync):
+ """Test that agent emits task events."""
+ # Run agent
+ await agent_with_cloud.run()
+
+ # Check task events
+ calls = mock_cloud_sync.handle_event.call_args_list
+
+ # Should have CreateAgentTaskEvent
+ create_task_events = [call for call in calls if call.args[0].event_type == 'CreateAgentTaskEvent']
+ assert len(create_task_events) == 1
+ create_event = create_task_events[0].args[0]
+ assert create_event.task == 'Test task'
+ assert hasattr(create_event, 'agent_session_id')
+
+ # Should have UpdateAgentTaskEvent when done
+ update_task_events = [call for call in calls if call.args[0].event_type == 'UpdateAgentTaskEvent']
+ assert len(update_task_events) >= 1
+
+ async def test_cloud_sync_disabled(self, browser_session):
+ """Test that cloud sync can be disabled."""
+ with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'false'}):
+ agent = Agent(
+ task='Test task',
+ llm=create_mock_llm(),
+ browser_session=browser_session,
+ )
+
+ assert not hasattr(agent, 'cloud_sync') or agent.cloud_sync is None
+
+ # Run agent - should work without cloud sync
+ await agent.run()
+
+ async def test_agent_error_resilience(self, agent_with_cloud, mock_cloud_sync):
+ """Test that agent continues working even if cloud sync fails."""
+ # Make cloud sync fail
+ mock_cloud_sync.handle_event.side_effect = Exception('Cloud sync error')
+
+ # Run agent - should not raise exception
+ result = await agent_with_cloud.run()
+
+ # Agent should complete successfully despite sync failures
+ assert result is not None
+ assert result.is_done()
+
+ # Verify cloud sync was attempted
+ assert mock_cloud_sync.handle_event.call_count > 0
+
+ async def test_session_id_persistence(self, browser_session):
+ """Test that agent session ID persists across runs."""
+ mock_sync = Mock(spec=CloudSync)
+ mock_sync.send_event = AsyncMock()
+ mock_sync.handle_event = AsyncMock()
+ mock_sync._authenticated = True
+
+ with patch('browser_use.sync.CloudSync', return_value=mock_sync):
+ with patch.dict(os.environ, {'BROWSERUSE_CLOUD_SYNC': 'true'}):
+ # Create first agent
+ agent1 = Agent(
+ task='First task',
+ llm=create_mock_llm(),
+ browser_session=browser_session,
+ )
+ agent1.cloud_sync = mock_sync
+
+ # Run first agent
+ await agent1.run()
+
+ # Get session ID from first run
+ session_calls = [
+ call for call in mock_sync.handle_event.call_args_list if call.args[0].event_type == 'CreateAgentSessionEvent'
+ ]
+ session_id_1 = session_calls[0].args[0].id
+
+ # Create second agent (will have different session ID)
+ agent2 = Agent(
+ task='Second task',
+ llm=create_mock_llm(),
+ browser_session=browser_session,
+ )
+ agent2.cloud_sync = mock_sync
+
+ # Clear previous calls
+ mock_sync.handle_event.reset_mock()
+
+ # Run second agent
+ await agent2.run()
+
+ # Should create new session for new agent
+ session_calls_2 = [
+ call for call in mock_sync.handle_event.call_args_list if call.args[0].event_type == 'CreateAgentSessionEvent'
+ ]
+ assert len(session_calls_2) == 1 # New session created
+
+ # Should create new task with new session ID
+ task_calls = [
+ call for call in mock_sync.handle_event.call_args_list if call.args[0].event_type == 'CreateAgentTaskEvent'
+ ]
+ assert len(task_calls) == 1
+ session_id_2 = session_calls_2[0].args[0].id
+ assert task_calls[0].args[0].agent_session_id == session_id_2
+ assert session_id_2 != session_id_1 # Different session IDs
+
+
+class TestEventValidation:
+ """Test event structure and validation"""
+
+ async def test_event_base_fields(self):
+ """Test that all events have required base fields"""
+ # Create a few events
+ events_to_test = [
+ CreateAgentSessionEvent(
+ id='0683fb03-c5da-79c9-8000-d3a39c47c651',
+ user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
+ browser_session_id='test-browser',
+ browser_session_live_url='https://example.com',
+ browser_session_cdp_url='ws://localhost:9222',
+ ),
+ CreateAgentTaskEvent(
+ id='0683fb03-c5da-79c9-8000-d3a39c47c652',
+ user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
+ agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c651',
+ task='test',
+ llm_model='gpt-4o',
+ ),
+ CreateAgentStepEvent(
+ user_id='0683fb03-c5da-79c9-8000-d3a39c47c650',
+ agent_task_id='0683fb03-c5da-79c9-8000-d3a39c47c652',
+ step=1,
+ evaluation_previous_goal='eval',
+ memory='mem',
+ next_goal='next',
+ actions=[],
+ ),
+ ]
+
+ # Check all events have required fields
+ for event in events_to_test:
+ # Base event fields
+ assert isinstance(event, BaseEvent)
+ assert event.event_type is not None
+ assert event.event_id is not None
+ assert event.event_created_at is not None
+ assert isinstance(event.event_path, list)
+
+ # Check event_id is a valid UUID string
+ uuid_obj = UUID(event.event_id)
+ assert str(uuid_obj) == event.event_id
+
+ def test_max_string_length_validation(self):
+ """Test that string fields enforce max length"""
+ # Create event with very long task
+ long_task = 'x' * 10000 # Longer than MAX_TASK_LENGTH (5000)
+
+ # Should raise validation error for string too long
+ with pytest.raises(ValueError, match='String should have at most 5000 characters'):
+ CreateAgentTaskEvent(
+ user_id='test',
+ agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659',
+ llm_model='test-model',
+ task=long_task,
+ )
+
+ def test_event_type_assignment(self):
+ """Test that event_type is properly set and validated"""
+ event = CreateAgentTaskEvent(
+ user_id='test', agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659', llm_model='test-model', task='test'
+ )
+
+ # Event type should be automatically set
+ assert event.event_type == 'CreateAgentTaskEvent'
+
+ # Event should have valid structure
+ assert event.id is not None
+ assert event.event_id is not None
+ assert event.event_created_at is not None
diff --git a/tests/ci/test_sync_client.py b/tests/ci/test_sync_client.py
new file mode 100644
index 000000000..b5d2ba34d
--- /dev/null
+++ b/tests/ci/test_sync_client.py
@@ -0,0 +1,387 @@
+"""Tests for CloudSync client machinery - retry logic, event handling, backend communication."""
+
+import os
+import tempfile
+from pathlib import Path
+from unittest.mock import patch
+
+import httpx
+import pytest
+from pytest_httpserver import HTTPServer
+
+from browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClient
+from browser_use.sync.service import CloudSync
+
+
+def temp_config_dir():
+ """Create temporary config directory for tests."""
+ with tempfile.TemporaryDirectory() as tmpdir:
+ temp_dir = Path(tmpdir) / '.config' / 'browseruse'
+ temp_dir.mkdir(parents=True, exist_ok=True)
+
+ # Temporarily replace the config dir
+ import browser_use.sync.auth
+ import browser_use.utils
+
+ original_auth = getattr(browser_use.sync.auth, 'BROWSER_USE_CONFIG_DIR', None)
+ original_utils = getattr(browser_use.utils, 'BROWSER_USE_CONFIG_DIR', None)
+
+ browser_use.sync.auth.BROWSER_USE_CONFIG_DIR = temp_dir
+ browser_use.utils.BROWSER_USE_CONFIG_DIR = temp_dir
+
+ yield temp_dir
+
+ # Restore original
+ if original_auth:
+ browser_use.sync.auth.BROWSER_USE_CONFIG_DIR = original_auth
+ if original_utils:
+ browser_use.utils.BROWSER_USE_CONFIG_DIR = original_utils
+
+
+async def http_client(httpserver: HTTPServer):
+ """Create a real HTTP client pointed at the test server."""
+ async with httpx.AsyncClient(base_url=httpserver.url_for('')) as client:
+ yield client
+
+
+class TestCloudSyncInit:
+ """Test CloudSync initialization and configuration."""
+
+ async def test_init_with_auth_enabled(self, temp_config_dir):
+ """Test CloudSync initialization with auth enabled."""
+ # Set test environment variable
+ with patch.dict(os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000'}):
+ service = CloudSync(enable_auth=True)
+
+ assert service.base_url == 'http://localhost:8000'
+ assert service.enable_auth is True
+ assert service.auth_client is not None
+ assert isinstance(service.auth_client, DeviceAuthClient)
+ assert service.pending_events == []
+ assert service.session_id is None
+
+ async def test_init_with_auth_disabled(self, temp_config_dir):
+ """Test CloudSync initialization with auth disabled."""
+ with patch.dict(os.environ, {'BROWSER_USE_CLOUD_URL': 'http://localhost:8000'}):
+ service = CloudSync(enable_auth=False)
+
+ assert service.base_url == 'http://localhost:8000'
+ assert service.enable_auth is False
+ assert service.auth_client is None
+ assert service.pending_events == []
+
+
+class TestCloudSyncEventHandling:
+ """Test CloudSync event validation and processing."""
+
+ @pytest.fixture
+ def authenticated_sync(self, httpserver: HTTPServer, http_client, temp_config_dir):
+ """Create authenticated CloudSync service."""
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''), http_client=http_client)
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
+
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
+ return service
+
+ @pytest.fixture
+ def unauthenticated_sync(self, httpserver: HTTPServer, temp_config_dir):
+ """Create unauthenticated CloudSync service."""
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.session_id = 'test-session-id'
+ return service
+
+ async def test_event_forwarding_authenticated(self, httpserver: HTTPServer, authenticated_sync):
+ """Test event forwarding when authenticated."""
+ # Capture requests
+ requests = []
+
+ def capture_request(request):
+ requests.append(request.get_json())
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Send event
+ await authenticated_sync.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'Test task', 'priority': 'high'},
+ event_schema='[email protected]',
+ )
+
+ # Verify forwarding
+ assert len(requests) == 1
+ event_batch = requests[0]
+ assert len(event_batch['events']) == 1
+
+ event = event_batch['events'][0]
+ assert event['event_type'] == 'CreateAgentTaskEvent'
+ assert event['data']['user_id'] == 'test-user-123'
+ # BaseEvent creates event_type attribute, plus our custom data as attributes
+ assert event['data']['task'] == 'Test task'
+ assert event['data']['priority'] == 'high'
+
+ async def test_event_queueing_unauthenticated(self, httpserver: HTTPServer, unauthenticated_sync):
+ """Test event queueing when unauthenticated."""
+ # Server returns 401
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_json({'error': 'unauthorized'}, status=401)
+
+ # Send event
+ await unauthenticated_sync.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'Queued task'},
+ event_schema='[email protected]',
+ )
+
+ # Event should be queued
+ assert len(unauthenticated_sync.pending_events) == 1
+ queued_event = unauthenticated_sync.pending_events[0]
+ assert queued_event['event_type'] == 'CreateAgentTaskEvent'
+ assert queued_event['data']['user_id'] == TEMP_USER_ID
+ assert queued_event['data']['task'] == 'Queued task'
+
+ async def test_event_user_id_injection_pre_auth(self, httpserver: HTTPServer, unauthenticated_sync):
+ """Test that temp user ID is injected for pre-auth events."""
+ requests = []
+
+ def capture_request(request):
+ requests.append(request.get_json())
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Send event without user_id
+ await unauthenticated_sync.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'Pre-auth task'},
+ event_schema='[email protected]',
+ )
+
+ # Verify temp user ID was injected
+ assert len(requests) == 1
+ event = requests[0]['events'][0]
+ assert event['data']['user_id'] == TEMP_USER_ID
+
+
+class TestCloudSyncRetryLogic:
+ """Test CloudSync retry and error handling logic."""
+
+ @pytest.fixture
+ def sync_with_auth(self, httpserver: HTTPServer, http_client, temp_config_dir):
+ """Create CloudSync with auth."""
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''), http_client=http_client)
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
+
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
+ return service
+
+ async def test_pending_event_resending(self, httpserver: HTTPServer, sync_with_auth):
+ """Test resending of pending events after authentication."""
+ requests = []
+
+ def capture_request(request):
+ requests.append(request.get_json())
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Manually add pending events (simulating 401 scenario)
+ sync_with_auth.pending_events.extend(
+ [
+ {
+ 'event_type': 'CreateAgentTaskEvent',
+ 'data': {'task': 'Pending task 1', 'user_id': TEMP_USER_ID},
+ },
+ {
+ 'event_type': 'CreateAgentTaskEvent',
+ 'data': {'task': 'Pending task 2', 'user_id': TEMP_USER_ID},
+ },
+ ]
+ )
+
+ # Resend pending events
+ await sync_with_auth._resend_pending_events()
+
+ # Should send all pending events with updated user ID
+ assert len(requests) == 2
+ for i, request in enumerate(requests):
+ event = request['events'][0]
+ assert event['data']['user_id'] == 'test-user-123' # Updated from temp ID
+ assert f'Pending task {i + 1}' == event['data']['task']
+
+ # Pending events should be cleared
+ assert len(sync_with_auth.pending_events) == 0
+
+ async def test_backend_error_resilience(self, httpserver: HTTPServer, sync_with_auth):
+ """Test resilience to backend errors."""
+ # Server returns 500 error
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_data('Internal Server Error', status=500)
+
+ # Should not raise exception
+ await sync_with_auth.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'Task during outage'},
+ event_schema='[email protected]',
+ )
+
+ # Events should not be queued for 500 errors (only 401)
+ assert len(sync_with_auth.pending_events) == 0
+
+ async def test_network_error_resilience(self, sync_with_auth):
+ """Test resilience to network errors."""
+ # No server running - will get connection error
+ sync_with_auth.base_url = 'http://localhost:99999' # Invalid port
+
+ # Should not raise exception
+ await sync_with_auth.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'Task during network error'},
+ event_schema='[email protected]',
+ )
+
+ # Should handle gracefully without crashing
+
+ async def test_concurrent_event_sending(self, httpserver: HTTPServer, sync_with_auth):
+ """Test handling of concurrent event sending."""
+ import asyncio
+
+ requests = []
+
+ def capture_request(request):
+ requests.append(request.get_json())
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Send multiple events concurrently
+ tasks = []
+ for i in range(5):
+ task = sync_with_auth.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': f'Concurrent task {i}'},
+ event_schema='[email protected]',
+ )
+ tasks.append(task)
+
+ await asyncio.gather(*tasks)
+
+ # All events should be sent
+ assert len(requests) == 5
+ # Just verify all events have task data - order may vary due to concurrency
+ task_values = [req['events'][0]['data']['task'] for req in requests]
+ expected_tasks = [f'Concurrent task {i}' for i in range(5)]
+ assert sorted(task_values) == sorted(expected_tasks)
+
+
+class TestCloudSyncBackendCommunication:
+ """Test CloudSync backend communication patterns."""
+
+ async def test_request_format_validation(self, httpserver: HTTPServer, temp_config_dir):
+ """Test that requests are formatted correctly for backend."""
+ requests = []
+
+ def capture_request(request):
+ # Validate request structure
+ assert request.content_type == 'application/json'
+ data = request.get_json()
+ requests.append(data)
+
+ # Validate batch structure
+ assert 'events' in data
+ assert isinstance(data['events'], list)
+ assert len(data['events']) == 1
+
+ event = data['events'][0]
+ required_fields = ['event_type', 'event_id', 'event_at', 'event_schema', 'data']
+ for field in required_fields:
+ assert field in event, f'Missing required field: {field}'
+
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Create authenticated service
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''))
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
+
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
+
+ await service.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'Format validation test'},
+ event_schema='[email protected]',
+ )
+
+ assert len(requests) == 1
+
+ async def test_auth_header_handling(self, httpserver: HTTPServer, temp_config_dir):
+ """Test proper auth header handling."""
+ requests = []
+
+ def capture_request(request):
+ requests.append(
+ {
+ 'headers': dict(request.headers),
+ 'json': request.get_json(),
+ }
+ )
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Test authenticated request
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''))
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
+
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+
+ await service.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'Auth header test'},
+ event_schema='[email protected]',
+ )
+
+ # Check auth header was included
+ assert len(requests) == 1
+ headers = requests[0]['headers']
+ assert 'Authorization' in headers
+ assert headers['Authorization'] == 'Bearer test-api-key'
+
+ # Test unauthenticated request
+ requests.clear()
+ service.auth_client = DeviceAuthClient(base_url=httpserver.url_for('')) # No credentials
+
+ await service.send_event(
+ event_type='CreateAgentTaskEvent',
+ event_data={'task': 'No auth test'},
+ event_schema='[email protected]',
+ )
+
+ # Check no auth header
+ assert len(requests) == 1
+ headers = requests[0]['headers']
+ assert 'Authorization' not in headers
diff --git a/tests/ci/test_oauth2_cloud_sync.py b/tests/ci/test_sync_client_auth.py
similarity index 60%
rename from tests/ci/test_oauth2_cloud_sync.py
rename to tests/ci/test_sync_client_auth.py
index 196d027a9..6129cb814 100644
--- a/tests/ci/test_oauth2_cloud_sync.py
+++ b/tests/ci/test_sync_client_auth.py
@@ -3,37 +3,22 @@ Tests for OAuth2 device flow and cloud sync functionality.
"""
import json
-import os
import tempfile
from datetime import datetime
from pathlib import Path
-from unittest.mock import AsyncMock, Mock, patch
+from unittest.mock import patch
-import aiofiles
+import anyio
import httpx
import pytest
+from dotenv import load_dotenv
from pytest_httpserver import HTTPServer
-from browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClient
-from browser_use.sync.service import CloudSyncService
-
-
-class MockResponse:
- """Mock HTTP response for testing."""
-
- def __init__(self, json_data, status=200):
- self.json_data = json_data
- self.status = status
-
- async def json(self):
- return self.json_data
-
-
-def mock_httpx_client():
- """Mock httpx AsyncClient."""
- return patch('httpx.AsyncClient')
+# Load environment variables before any imports
+load_dotenv()
+from browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClient
+from browser_use.sync.service import CloudSync
# Define config dir for tests
# BROWSER_USE_CONFIG_DIR = Path.home() / ".config" / "browseruse"
@@ -52,11 +37,13 @@ def temp_config_dir():
import browser_use.sync.auth
import browser_use.utils
+ browser_use.sync.auth.BROWSER_USE_CONFIG_DIR = temp_dir
browser_use.utils.BROWSER_USE_CONFIG_DIR = temp_dir
yield temp_dir
# Restore original
+ browser_use.sync.auth.BROWSER_USE_CONFIG_DIR = original
browser_use.utils.BROWSER_USE_CONFIG_DIR = original
@@ -167,7 +154,7 @@ class TestDeviceAuthClient:
assert request.method == 'POST'
# Get the body as string
body = request.get_data(as_text=True)
- assert 'client_id=bu_cli' in body
+ assert 'client_id=library' in body
assert 'agent_session_id=test-session-id' in body
async def test_poll_for_token_pending(self, httpserver: HTTPServer, http_client, temp_config_dir):
@@ -335,49 +322,47 @@ class TestDeviceAuthClient:
assert auth2.auth_config.user_id is None
-class TestCloudSyncService:
- """Test CloudSyncService class."""
+class TestCloudSync:
+ """Test CloudSync class."""
- @pytest.fixture
- def mock_auth(self):
- """Mock DeviceAuthClient."""
- auth = Mock(spec=DeviceAuthClient)
- auth.is_authenticated.return_value = True
- auth.get_credentials.return_value = ('test-api-key', 'test-user-123')
- auth.start_device_flow = AsyncMock(
- return_value={
- 'device_code': 'test-device-code',
- 'user_code': 'ABCD-1234',
- 'verification_uri_complete': 'https://example.com/device?user_code=ABCD-1234',
- }
- )
- auth.wait_for_authorization = AsyncMock(return_value=True)
- return auth
-
- async def test_init(self, mock_auth):
- """Test CloudSyncService initialization."""
- service = CloudSyncService(
- agent_session_id='test-session-id',
- auth=mock_auth,
+ async def test_init(self, temp_config_dir):
+ """Test CloudSync initialization."""
+ service = CloudSync(
+ base_url='https://cloud.browser-use.com',
+ enable_auth=True,
)
- assert service.agent_session_id == 'test-session-id'
- assert service.auth == mock_auth
- assert service._authenticated is True
- assert service._pre_auth_events == []
+ assert service.base_url == 'https://cloud.browser-use.com'
+ assert service.enable_auth is True
+ assert service.auth_client is not None
+ assert isinstance(service.auth_client, DeviceAuthClient)
+ assert service.pending_events == []
- async def test_send_event_authenticated(self, mock_auth, mock_httpx_client):
+ async def test_send_event_authenticated(self, httpserver: HTTPServer, temp_config_dir):
"""Test sending event when authenticated."""
- # Mock httpx client
- mock_client = AsyncMock()
- mock_response = MockResponse({'processed': 1, 'failed': 0})
- mock_client.post.return_value = mock_response
- mock_httpx_client.return_value.__aenter__.return_value = mock_client
-
- service = CloudSyncService(
- agent_session_id='test-session-id',
- auth=mock_auth,
- )
+ requests = []
+
+ def capture_request(request):
+ requests.append(
+ {
+ 'headers': dict(request.headers),
+ 'json': request.get_json(),
+ }
+ )
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Create authenticated service
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''))
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
+
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
# Send event
event_data = {
@@ -386,45 +371,51 @@ class TestCloudSyncService:
}
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data=event_data,
event_schema='[email protected]',
)
# Check request was made
- mock_client.post.assert_called_once()
- call_args = mock_client.post.call_args
-
- # Check URL
- assert call_args[0][0] == 'https://api.browser-use.com/api/v1/events/'
+ assert len(requests) == 1
+ request_data = requests[0]
# Check auth header
- assert call_args[1]['headers']['Authorization'] == 'Bearer test-api-key'
+ assert request_data['headers']['Authorization'] == 'Bearer test-api-key'
# Check event data
- json_data = call_args[1]['json']
+ json_data = request_data['json']
assert len(json_data['events']) == 1
event = json_data['events'][0]
- assert event['event_type'] == 'CreateAgentTask'
- assert event['data'] == event_data
+ assert event['event_type'] == 'CreateAgentTaskEvent'
assert event['data']['user_id'] == 'test-user-123'
+ assert event['data']['task'] == 'Test task'
+ assert event['data']['status'] == 'running'
- async def test_send_event_pre_auth(self, mock_httpx_client):
+ async def test_send_event_pre_auth(self, httpserver: HTTPServer, temp_config_dir):
"""Test sending event before authentication."""
- # Mock auth that's not authenticated
- mock_auth = Mock(spec=DeviceAuthClient)
- mock_auth.is_authenticated.return_value = False
-
- # Mock httpx client
- mock_client = AsyncMock()
- mock_response = MockResponse({'processed': 1, 'failed': 0})
- mock_client.post.return_value = mock_response
- mock_httpx_client.return_value.__aenter__.return_value = mock_client
-
- service = CloudSyncService(
- agent_session_id='test-session-id',
- auth=mock_auth,
- )
+ requests = []
+
+ def capture_request(request):
+ requests.append(
+ {
+ 'headers': dict(request.headers),
+ 'json': request.get_json(),
+ }
+ )
+ from werkzeug.wrappers import Response
+
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(capture_request)
+
+ # Create unauthenticated service
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''))
+ # Don't set api_token - leave it unauthenticated
+
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
# Send event
event_data = {
@@ -433,223 +424,277 @@ class TestCloudSyncService:
}
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data=event_data,
event_schema='[email protected]',
)
# Check request was made without auth header
- mock_client.post.assert_called_once()
- call_args = mock_client.post.call_args
- assert 'Authorization' not in call_args[1]['headers']
+ assert len(requests) == 1
+ request_data = requests[0]
+ assert 'Authorization' not in request_data['headers']
- # Check event was stored for later
- assert len(service._pre_auth_events) == 1
- assert service._pre_auth_events[0]['event_type'] == 'CreateAgentTask'
+ # Check event was sent with temp user ID
+ json_data = request_data['json']
+ assert len(json_data['events']) == 1
+ event = json_data['events'][0]
+ assert event['event_type'] == 'CreateAgentTaskEvent'
+ assert event['data']['user_id'] == TEMP_USER_ID
+ assert event['data']['task'] == 'Test task'
+ assert event['data']['status'] == 'running'
- async def test_authenticate_and_resend(self, mock_auth, mock_httpx_client):
+ async def test_authenticate_and_resend(self, httpserver: HTTPServer, temp_config_dir):
"""Test authentication flow with pre-auth event resending."""
+ requests = []
+ request_count = 0
+
+ def handle_events_request(request):
+ nonlocal request_count
+ request_count += 1
+ requests.append(
+ {
+ 'headers': dict(request.headers),
+ 'json': request.get_json(),
+ }
+ )
+
+ from werkzeug.wrappers import Response
+
+ if request_count == 1:
+ # First request: unauthenticated, return 401
+ return Response('{"error": "unauthorized"}', status=401, mimetype='application/json')
+ else:
+ # Subsequent requests: success
+ return Response('{"processed": 1, "failed": 0}', status=200, mimetype='application/json')
+
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_handler(handle_events_request)
+
+ # Create service with unauthenticated auth client
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''))
# Start unauthenticated
- mock_auth.is_authenticated.side_effect = [False, False, True, True]
- mock_auth.get_credentials.return_value = ('test-api-key', 'test-user-123')
-
- # Mock httpx client
- mock_client = AsyncMock()
- mock_response = MockResponse({'processed': 1, 'failed': 0})
- mock_client.post.return_value = mock_response
- mock_httpx_client.return_value.__aenter__.return_value = mock_client
-
- service = CloudSyncService(
- agent_session_id='test-session-id',
- auth=mock_auth,
- )
- # Send pre-auth event
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
+
+ # Send pre-auth event (should get 401 and be queued)
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': 'Pre-auth task'},
event_schema='[email protected]',
)
- assert len(service._pre_auth_events) == 1
+ # Event should be in pending_events since we got 401
+ assert len(service.pending_events) == 1
+ assert service.pending_events[0]['data']['task'] == 'Pre-auth task'
+ assert service.pending_events[0]['data']['user_id'] == TEMP_USER_ID
- # Authenticate
- authenticated = await service.authenticate()
- assert authenticated is True
+ # Now authenticate the auth client
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
- # Pre-auth events should be cleared after resending
- assert len(service._pre_auth_events) == 0
+ # Manually trigger resend of pending events
+ await service._resend_pending_events()
- # Check that events were sent (1 pre-auth + 1 resend after auth)
- assert mock_client.post.call_count == 2
+ # Pre-auth events should be cleared after successful resend
+ assert len(service.pending_events) == 0
- # First call should be without auth
- first_call = mock_client.post.call_args_list[0]
- assert 'Authorization' not in first_call[1]['headers']
+ # Check that events were sent (1 original attempt + 1 resend)
+ assert len(requests) == 2
- # Second call should be with auth
- second_call = mock_client.post.call_args_list[1]
- assert second_call[1]['headers']['Authorization'] == 'Bearer test-api-key'
+ # Check first request was unauthenticated
+ assert 'Authorization' not in requests[0]['headers']
+ assert requests[0]['json']['events'][0]['data']['user_id'] == TEMP_USER_ID
- async def test_error_handling(self, mock_auth, mock_httpx_client):
+ # Check second request was authenticated with updated user_id
+ assert requests[1]['headers']['Authorization'] == 'Bearer test-api-key'
+ assert requests[1]['json']['events'][0]['data']['user_id'] == 'test-user-123'
+
+ async def test_error_handling(self, httpserver: HTTPServer, temp_config_dir):
"""Test error handling during event sending."""
- # Mock httpx client to raise error
- mock_client = AsyncMock()
- mock_client.post.side_effect = Exception('Network error')
- mock_httpx_client.return_value.__aenter__.return_value = mock_client
-
- service = CloudSyncService(
- agent_session_id='test-session-id',
- auth=mock_auth,
- )
+ # Set up server to return 500 error
+ httpserver.expect_request('/api/v1/events/', method='POST').respond_with_data('Internal Server Error', status=500)
+
+ # Create service with real auth
+ auth = DeviceAuthClient(base_url=httpserver.url_for(''))
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
+
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
- # Send event - should not raise
+ # Send event - should not raise exception but handle gracefully
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': 'Test task'},
event_schema='[email protected]',
)
- # Event should still be logged even if send fails
- mock_client.post.assert_called_once()
+ # Should handle error gracefully without crashing
- async def test_update_wal_events(self, mock_auth):
+ async def test_update_wal_events(self, temp_config_dir):
"""Test updating WAL events with real user ID."""
- service = CloudSyncService(
- agent_session_id='test-session-id',
- auth=mock_auth,
+ # Create real auth client
+ auth = DeviceAuthClient(base_url='http://localhost:8000')
+ auth.auth_config.api_token = 'test-api-key'
+ auth.auth_config.user_id = 'test-user-123'
+
+ service = CloudSync(
+ base_url='http://localhost:8000',
+ enable_auth=True,
)
+ service.auth_client = auth
+ service.session_id = 'test-session-id'
- # Mock WAL file
- with tempfile.NamedTemporaryFile(suffix='.jsonl', delete=False) as temp_file:
- wal_path = Path(temp_file.name)
+ # Create the events directory structure that the method expects
+ events_dir = temp_config_dir / 'events'
+ events_dir.mkdir(exist_ok=True)
- # Write test events
+ # Create WAL file with temp user IDs
+ wal_path = events_dir / f'{service.session_id}.jsonl'
events = [
{
- 'event_type': 'CreateAgentTask',
- 'data': {'user_id': '99999999-9999-9999-9999-999999999999', 'task': 'Task 1'},
+ 'event_type': 'CreateAgentTaskEvent',
+ 'user_id': '99999999-9999-9999-9999-999999999999', # TEMP_USER_ID
+ 'task': 'Task 1',
},
{
- 'event_type': 'UpdateAgentTask',
- 'data': {'user_id': '99999999-9999-9999-9999-999999999999', 'status': 'done'},
+ 'event_type': 'UpdateAgentTaskEvent',
+ 'user_id': '99999999-9999-9999-9999-999999999999', # TEMP_USER_ID
+ 'status': 'done',
},
{
- 'event_type': 'CreateAgentStep',
- 'data': {'user_id': 'other-user', 'step': 1},
+ 'event_type': 'CreateAgentStepEvent',
+ 'user_id': 'some-other-user', # Different user, should still be updated
+ 'step': 1,
},
]
- async with aiofiles.open(wal_path, 'w') as f:
- for event in events:
- await f.write(json.dumps(event) + '\n')
+ # Write events to WAL file
+ content = '\n'.join(json.dumps(event) for event in events) + '\n'
+ await anyio.Path(wal_path).write_text(content)
+
+ # Patch BROWSER_USE_CONFIG_DIR to point to our temp directory
+ with patch('browser_use.utils.BROWSER_USE_CONFIG_DIR', temp_config_dir):
+ # Call the method under test
+ await service._update_wal_user_ids(service.session_id)
- # Update WAL
- updated = await service._update_wal_events(wal_path, 'real-user-123')
- assert updated == 2 # Only temp user events should be updated
+ # Read back the updated file and verify changes
+ content = await anyio.Path(wal_path).read_text()
- # Read back and verify
- async with aiofiles.open(wal_path) as f:
- lines = await f.readlines()
+ updated_events = []
+ for line in content.splitlines():
+ if line.strip():
+ updated_events.append(json.loads(line))
- updated_events = [json.loads(line) for line in lines]
- assert updated_events[0]['data']['user_id'] == 'real-user-123'
- assert updated_events[1]['data']['user_id'] == 'real-user-123'
- assert updated_events[2]['data']['user_id'] == 'other-user' # Unchanged
+ # Verify all user_ids were updated to the authenticated user's ID
+ assert len(updated_events) == 3
+ for event in updated_events:
+ assert event['user_id'] == 'test-user-123'
- # Cleanup
- wal_path.unlink()
+ # Verify other fields remained unchanged
+ assert updated_events[0]['event_type'] == 'CreateAgentTaskEvent'
+ assert updated_events[0]['task'] == 'Task 1'
+ assert updated_events[1]['event_type'] == 'UpdateAgentTaskEvent'
+ assert updated_events[1]['status'] == 'done'
+ assert updated_events[2]['event_type'] == 'CreateAgentStepEvent'
+ assert updated_events[2]['step'] == 1
class TestIntegration:
"""Integration tests for OAuth2 and cloud sync."""
- @pytest.fixture
- def temp_home(self):
- """Create temporary home directory."""
- with tempfile.TemporaryDirectory() as tmpdir:
- original_home = os.environ.get('HOME')
- os.environ['HOME'] = tmpdir
- yield Path(tmpdir)
- if original_home:
- os.environ['HOME'] = original_home
+ async def test_full_auth_flow(self, httpserver: HTTPServer, temp_config_dir):
+ """Test complete authentication flow."""
+ # Track token polling attempts
+ token_attempts = 0
+
+ def handle_token_request(request):
+ nonlocal token_attempts
+ token_attempts += 1
+
+ from werkzeug.wrappers import Response
+
+ if token_attempts == 1:
+ # First attempt: pending
+ return Response(
+ json.dumps({'error': 'authorization_pending'}),
+ status=200,
+ mimetype='application/json',
+ )
else:
- del os.environ['HOME']
+ # Second attempt: success
+ return Response(
+ json.dumps(
+ {
+ 'access_token': 'test-api-key',
+ 'token_type': 'Bearer',
+ 'user_id': 'test-user-123',
+ }
+ ),
+ status=200,
+ mimetype='application/json',
+ )
- async def test_full_auth_flow(self, temp_home, mock_httpx_client):
- """Test complete authentication flow."""
- # Mock responses
- auth_response = MockResponse(
+ # Set up auth flow endpoints
+ httpserver.expect_request(
+ '/api/v1/oauth/device/authorize',
+ method='POST',
+ ).respond_with_json(
{
'device_code': 'test-device-code',
'user_code': 'ABCD-1234',
- 'verification_uri_complete': 'https://example.com/device?user_code=ABCD-1234',
+ 'verification_uri': f'{httpserver.url_for("")}/device',
+ 'verification_uri_complete': f'{httpserver.url_for("")}/device?user_code=ABCD-1234',
'expires_in': 1800,
- 'interval': 5,
+ 'interval': 0.1, # Fast polling for test
}
)
- token_responses = [
- MockResponse({'error': 'authorization_pending'}),
- MockResponse(
- {
- 'access_token': 'test-api-key',
- 'token_type': 'Bearer',
- 'user_id': 'test-user-123',
- }
- ),
- ]
-
- event_response = MockResponse({'processed': 1, 'failed': 0})
+ httpserver.expect_request(
+ '/api/v1/oauth/device/token',
+ method='POST',
+ ).respond_with_handler(handle_token_request)
- # Mock httpx client
- mock_client = AsyncMock()
- mock_client.post.side_effect = [
- event_response, # Pre-auth event
- auth_response, # Start device flow
- *token_responses, # Polling
- event_response, # Resend after auth
- event_response, # New authenticated event
- ]
- mock_httpx_client.return_value.__aenter__.return_value = mock_client
+ # Set up events endpoint
+ httpserver.expect_request(
+ '/api/v1/events/',
+ method='POST',
+ ).respond_with_json({'processed': 1, 'failed': 0})
# Create service
- service = CloudSyncService(agent_session_id='test-session-id')
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
+ service.session_id = 'test-session-id'
# Send pre-auth event
await service.send_event(
- event_type='CreateAgentSession',
+ event_type='CreateAgentSessionEvent',
event_data={'started_at': datetime.utcnow().isoformat()},
event_schema='[email protected]',
)
- # Authenticate (with quick polling for test)
- with patch.object(service.auth, 'wait_for_authorization', side_effect=service.auth.wait_for_authorization) as mock_wait:
- mock_wait.return_value = True
- authenticated = await service.authenticate()
-
+ # Authenticate
+ authenticated = await service.authenticate(show_instructions=False)
assert authenticated is True
- assert service._authenticated is True
+ assert service.auth_client.is_authenticated
+ assert service.auth_client.api_token == 'test-api-key'
+ assert service.auth_client.user_id == 'test-user-123'
# Send authenticated event
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': 'Authenticated task'},
event_schema='[email protected]',
)
- # Verify all calls were made
- assert mock_client.post.call_count == 5
-
# Verify auth was saved
- config_dir = temp_home / '.config' / 'browseruse'
- auth_file = config_dir / 'cloud_auth.json'
- assert auth_file.exists()
-
- async with aiofiles.open(auth_file) as f:
- content = await f.read()
- saved_auth = json.loads(content)
- assert saved_auth['api_key'] == 'test-api-key'
+ auth_file = temp_config_dir / 'cloud_auth.json'
+ assert await anyio.Path(auth_file).exists()
+
+ content = await anyio.Path(auth_file).read_text()
+ saved_auth = json.loads(content)
+ assert saved_auth['api_token'] == 'test-api-key'
assert saved_auth['user_id'] == 'test-user-123'
@@ -697,14 +742,14 @@ class TestAuthResilience:
).respond_with_json({'error': 'unauthorized', 'detail': 'Token expired'}, status=401)
# Create cloud sync service
- from browser_use.sync.service import CloudSyncService
+ from browser_use.sync.service import CloudSync
- service = CloudSyncService(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
service.auth_client = auth
# Send event - should not raise exception even though token is expired
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': 'Test task after token expiry'},
event_schema='[email protected]',
)
@@ -727,9 +772,9 @@ class TestAuthResilience:
assert success is False
# Should still be able to create sync service
- from browser_use.sync.service import CloudSyncService
+ from browser_use.sync.service import CloudSync
- service = CloudSyncService(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
service.auth_client = auth
# Set up events endpoint to handle unauthenticated requests
@@ -740,7 +785,7 @@ class TestAuthResilience:
# Should be able to send events without auth (pre-auth mode)
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': 'Test task without auth'},
event_schema='[email protected]',
)
@@ -755,15 +800,15 @@ class TestAuthResilience:
result = await auth.poll_for_token('fake-device-code', interval=0.1, timeout=0.3)
assert result is None
- from browser_use.sync.service import CloudSyncService
+ from browser_use.sync.service import CloudSync
- service = CloudSyncService(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
service.auth_client = auth
# Should be able to send events even when server is down
# They will be queued locally
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': 'Test task during server downtime'},
event_schema='[email protected]',
)
@@ -772,15 +817,15 @@ class TestAuthResilience:
"""Test that excessive event queuing doesn't break the agent."""
auth = DeviceAuthClient(base_url=httpserver.url_for(''), http_client=http_client)
- from browser_use.sync.service import CloudSyncService
+ from browser_use.sync.service import CloudSync
- service = CloudSyncService(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
service.auth_client = auth
# Send many events while server is down (no responses configured)
for i in range(100):
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': f'Test task {i}'},
event_schema='[email protected]',
)
@@ -810,14 +855,14 @@ class TestAuthResilience:
method='POST',
).respond_with_data('malformed response', status=500)
- from browser_use.sync.service import CloudSyncService
+ from browser_use.sync.service import CloudSync
- service = CloudSyncService(base_url=httpserver.url_for(''), enable_auth=True)
+ service = CloudSync(base_url=httpserver.url_for(''), enable_auth=True)
service.auth_client = auth
# Should handle malformed event response gracefully
await service.send_event(
- event_type='CreateAgentTask',
+ event_type='CreateAgentTaskEvent',
event_data={'task': 'Test task with malformed response'},
event_schema='[email protected]',
)
diff --git a/tests/ci/test_sync_live.py b/tests/ci/test_sync_live.py
new file mode 100644
index 000000000..24a51e72d
--- /dev/null
+++ b/tests/ci/test_sync_live.py
@@ -0,0 +1,204 @@
+# """
+# Live integration test for OAuth2 device flow with real cloud backend.
+
+# This test is skipped by default and only runs when explicitly selected.
+# Run with: pytest tests/ci/test_live_oauth2_integration.py::test_live_oauth2_integration -v
+# """
+
+# import asyncio
+# import json
+# import logging
+# import os
+# import tempfile
+# from pathlib import Path
+
+# import pytest
+
+# from browser_use import Agent
+# from browser_use.browser.browser import BrowserSession
+# from browser_use.sync.service import CloudSync
+# from tests.ci.mocks import create_mock_llm
+
+# logger = logging.getLogger(__name__)
+
+
+# def create_oauth_mock_llm():
+# """Create a mock LLM that follows a simple script for OAuth testing."""
+# actions = [
+# # First action - navigate to a simple page
+# json.dumps(
+# {
+# 'current_state': {
+# 'evaluation_previous_goal': 'Starting OAuth integration test',
+# 'memory': 'Beginning test sequence',
+# 'next_goal': 'Navigate to example page',
+# },
+# 'action': [
+# {'goto': {'url': 'https://example.com', 'reasoning': 'Starting the test by navigating to a simple webpage'}}
+# ],
+# }
+# ),
+# # Second action - complete the test
+# json.dumps(
+# {
+# 'current_state': {
+# 'evaluation_previous_goal': 'Successfully navigated to example page',
+# 'memory': 'OAuth flow test initiated',
+# 'next_goal': 'Complete test',
+# },
+# 'action': [{'done': {'text': 'OAuth integration test completed - cloud sync initiated', 'success': True}}],
+# }
+# ),
+# ]
+# return create_mock_llm(actions)
+
+
+# @pytest.fixture
+# def temp_browser_profile():
+# """Create a temporary browser profile directory."""
+# with tempfile.TemporaryDirectory() as tmpdir:
+# profile_dir = Path(tmpdir) / 'browser_profile'
+# profile_dir.mkdir(parents=True, exist_ok=True)
+# yield str(profile_dir)
+
+
+# @pytest.mark.skipif(not os.getenv('RUN_LIVE_TESTS'), reason='Live integration tests only run when RUN_LIVE_TESTS=1 is set')
+# @pytest.mark.asyncio
+# async def test_live_oauth2_integration(temp_browser_profile):
+# """
+# Live integration test for OAuth2 device flow.
+
+# This test:
+# 1. Creates a real browser session
+# 2. Sets up cloud sync with real backend
+# 3. Runs an agent with a mocked LLM
+# 4. Verifies the OAuth2 device flow is initiated
+# 5. Sends real events to the cloud backend
+
+# Environment variables required:
+# - RUN_LIVE_TESTS=1 (to enable the test)
+# - BROWSER_USE_CLOUD_URL (optional, defaults to https://cloud.browser-use.com)
+# """
+
+# # Configuration
+# backend_url = os.getenv('BROWSER_USE_CLOUD_URL', 'http://localhost:8000')
+# logger.info(f'Running live integration test against: {backend_url}')
+
+# # Create mock LLM
+# mock_llm = create_oauth_mock_llm()
+
+# # Set environment variables for cloud sync
+# os.environ['BROWSERUSE_CLOUD_SYNC'] = 'true'
+# os.environ['BROWSER_USE_CLOUD_URL'] = backend_url
+
+# # Create browser session with real profile
+# browser_session = BrowserSession(
+# user_data_dir=temp_browser_profile,
+# headless=False, # Show browser for visual confirmation
+# )
+
+# # Create agent (cloud sync will be auto-enabled via environment variables)
+# agent = Agent(
+# task='Visit the Browser Use login page and demonstrate OAuth integration',
+# llm=mock_llm,
+# browser_session=browser_session,
+# )
+
+# # Run the agent for a short time
+# logger.info('Starting agent with OAuth2 integration...')
+
+# # Run with timeout to prevent hanging
+# try:
+# await asyncio.wait_for(agent.run(), timeout=60)
+# except TimeoutError:
+# logger.info('Agent run timed out (expected for live test)')
+
+# # Get cloud sync from agent
+# cloud_sync = agent.cloud_sync
+# assert cloud_sync is not None, 'Cloud sync should be enabled'
+
+# # Wait for any pending cloud sync operations
+# if cloud_sync.auth_task and not cloud_sync.auth_task.done():
+# try:
+# await asyncio.wait_for(cloud_sync.auth_task, timeout=10)
+# except TimeoutError:
+# logger.info('Auth task still running (expected for live test)')
+
+# # Verify cloud sync was attempted
+# assert cloud_sync.auth_client is not None, 'Auth client should be initialized'
+
+# logger.info('✅ Live OAuth2 integration test completed successfully')
+# logger.info(f'🔗 LLM invocations: {mock_llm.invoke.call_count if hasattr(mock_llm.invoke, "call_count") else "mock"}')
+
+# # Print session ID for manual verification
+# if cloud_sync.session_id:
+# logger.info(f'📊 Agent session ID: {cloud_sync.session_id}')
+# logger.info(f'🌐 Check session at: {backend_url}/agent/{cloud_sync.session_id}')
+
+# await asyncio.sleep(60000)
+
+
+# @pytest.mark.skipif(not os.getenv('RUN_LIVE_TESTS'), reason='Live integration tests only run when RUN_LIVE_TESTS=1 is set')
+# @pytest.mark.asyncio
+# async def test_live_cloud_sync_events():
+# """
+# Test that cloud sync can send events to the real backend.
+
+# This is a simpler test that just verifies event sending works.
+# """
+
+# backend_url = os.getenv('BROWSER_USE_CLOUD_URL', 'http://localhost:8000')
+# logger.info(f'Testing cloud sync against: {backend_url}')
+
+# # Create cloud sync service
+# cloud_sync = CloudSync(base_url=backend_url, enable_auth=True)
+
+# # Import event types
+# from uuid import uuid4
+
+# from browser_use.agent.cloud_events import CreateAgentSessionEvent
+# from browser_use.sync.auth import TEMP_USER_ID
+
+# # Create a test session event
+# session_event = CreateAgentSessionEvent(
+# user_id=TEMP_USER_ID,
+# id=str(uuid4()),
+# browser_session_id=str(uuid4()),
+# browser_session_live_url='https://example.com',
+# browser_session_cdp_url='ws://localhost:9222',
+# browser_state={'test': 'live_integration'},
+# is_source_api=True,
+# )
+
+# # Send event to cloud
+# logger.info('Sending test event to cloud...')
+# try:
+# await cloud_sync.handle_event(session_event)
+# logger.info('✅ Event sent successfully')
+# except Exception as e:
+# logger.error(f'❌ Failed to send event: {e}')
+# raise
+
+# # Wait a moment for processing
+# await asyncio.sleep(2)
+
+# logger.info('✅ Cloud sync event test completed')
+
+# if cloud_sync.session_id:
+# logger.info(f'📊 Session ID: {cloud_sync.session_id}')
+
+# await asyncio.sleep(60000)
+
+
+# if __name__ == '__main__':
+# # Allow running the test directly with: python test_live_oauth2_integration.py
+# import sys
+
+# if len(sys.argv) > 1 and sys.argv[1] == '--live':
+# os.environ['RUN_LIVE_TESTS'] = '1'
+# pytest.main([__file__, '-v', '-s'])
+# else:
+# print('To run live integration tests:')
+# print('1. Set environment variable: export RUN_LIVE_TESTS=1')
+# print('2. Run: pytest tests/ci/test_live_oauth2_integration.py -v')
+# print('3. Or run directly: python test_live_oauth2_integration.py --live')
diff --git a/tests/test_action_params.py b/tests/test_action_params.py
index c0594c264..d8f051065 100644
--- a/tests/test_action_params.py
+++ b/tests/test_action_params.py
@@ -14,13 +14,13 @@ logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
-# Test model
-class TestActionParams(ActionModel):
+# Test model - renamed to avoid pytest collection warnings
+class TestActionParamsModel(ActionModel):
value: str = Field(description='Test value')
-# Our Context type for the Registry
-class TestContext:
+# Our Context type for the Registry - renamed to avoid pytest collection warnings
+class TestContextHelper:
def __init__(self, value):
self.value = value
@@ -29,13 +29,13 @@ class TestContext:
async def test_registry_param_handling():
"""Test how Registry handles parameter passing for different function signatures."""
# Create a Registry instance
- registry = Registry[TestContext]()
+ registry = Registry[TestContextHelper]()
# Create test functions with different signatures
# 1. Function with browser_session as a positional parameter
- @registry.action('Test action with browser_session', param_model=TestActionParams)
- async def action_with_browser_session(params: TestActionParams, browser_session: BrowserSession):
+ @registry.action('Test action with browser_session', param_model=TestActionParamsModel)
+ async def action_with_browser_session(params: TestActionParamsModel, browser_session: BrowserSession):
logger.debug(f'action_with_browser_session called with params={params}, browser_session={browser_session}')
return {'params': params.model_dump(), 'has_browser': browser_session is not None}
@@ -51,7 +51,7 @@ async def test_registry_param_handling():
# 3. Function using **kwargs
@registry.action('Test action with kwargs')
- async def action_with_kwargs(params: TestActionParams, **kwargs):
+ async def action_with_kwargs(params: TestActionParamsModel, **kwargs):
logger.debug(f'action_with_kwargs called with params={params}, kwargs={kwargs}')
return {'params': params.model_dump(), 'kwargs': kwargs}
diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.py
index b52eb9fda..bdd276b16 100644
--- a/tests/test_agent_actions.py
+++ b/tests/test_agent_actions.py
@@ -6,7 +6,7 @@ from pydantic import BaseModel, SecretStr
from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
-from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser import BrowserSession
@pytest.fixture
@@ -26,9 +26,8 @@ def llm():
@pytest.fixture
async def browser_session():
browser_session = BrowserSession(
- browser_profile=BrowserProfile(
- headless=True,
- )
+ headless=True,
+ user_data_dir=None,
)
await browser_session.start()
yield browser_session
diff --git a/tests/test_models.py b/tests/test_models.py
index 8afd6ce1b..dfe355ee4 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -12,6 +12,15 @@ from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
from browser_use.browser import BrowserProfile, BrowserSession
+# Set env vars for testing
+os.environ.setdefault('SKIP_LLM_API_KEY_VERIFICATION', 'true')
+os.environ.setdefault('AZURE_OPENAI_ENDPOINT', 'https://test.openai.azure.com')
+os.environ.setdefault('AZURE_OPENAI_KEY', 'test-key')
+os.environ.setdefault('ANTHROPIC_API_KEY', 'test-key')
+os.environ.setdefault('GOOGLE_API_KEY', 'test-key')
+os.environ.setdefault('DEEPSEEK_API_KEY', 'test-key')
+os.environ.setdefault('OPENAI_API_KEY', 'test-key')
+
@pytest.fixture
async def browser_session():