Skip to content

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

refc: removed auth message and cloud_sync_field

Saurav Pandaf8be13b7081a
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index c9d314a4f..6326ac6bf 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -60,7 +60,6 @@ from browser_use.config import CONFIG
from browser_use.dom.views import DOMInteractedElement
from browser_use.filesystem.file_system import FileSystem
from browser_use.observability import observe, observe_debug
-from browser_use.sync import CloudSync
from browser_use.telemetry.service import ProductTelemetry
from browser_use.telemetry.views import AgentTelemetryEvent
from browser_use.tools.registry.views import ActionModel
@@ -172,7 +171,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
source: str | None = None,
file_system_path: str | None = None,
task_id: str | None = None,
- cloud_sync: CloudSync | None = None,
calculate_cost: bool = False,
display_files_in_done_text: bool = True,
include_tool_call_examples: bool = False,
@@ -438,15 +436,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# wal_path = CONFIG.BROWSER_USE_CONFIG_DIR / 'events' / f'{self.session_id}.jsonl'
self.eventbus = EventBus(name=f'Agent_{str(self.id)[-4:]}')
- # Cloud sync service
- self.enable_cloud_sync = CONFIG.BROWSER_USE_CLOUD_SYNC
- if self.enable_cloud_sync or cloud_sync is not None:
- self.cloud_sync = cloud_sync or CloudSync()
- # Register cloud sync handler
- self.eventbus.on('*', self.cloud_sync.handle_event)
- else:
- self.cloud_sync = None
-
if self.settings.save_conversation_path:
self.settings.save_conversation_path = Path(self.settings.save_conversation_path).expanduser().resolve()
self.logger.info(f'πŸ’¬ Saving conversation to {_log_pretty_path(self.settings.save_conversation_path)}')
@@ -631,10 +620,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
agent_id_suffix = 'a' + agent_id_suffix
self.eventbus = EventBus(name=f'Agent_{agent_id_suffix}')
- # Re-register cloud sync handler if it exists (if not disabled)
- if hasattr(self, 'cloud_sync') and self.cloud_sync and self.enable_cloud_sync:
- self.eventbus.on('*', self.cloud_sync.handle_event)
-
async def _check_stop_or_pause(self) -> None:
"""Check if the agent should stop or pause, and handle accordingly."""
@@ -865,16 +850,15 @@ class Agent(Generic[Context, AgentStructuredOutput]):
action_dict = action.model_dump() if hasattr(action, 'model_dump') else {}
actions_data.append(action_dict)
- # Emit CreateAgentStepEvent only if cloud sync is enabled
- if self.enable_cloud_sync:
- step_event = CreateAgentStepEvent.from_agent_step(
- self,
- self.state.last_model_output,
- self.state.last_result,
- actions_data,
- browser_state_summary,
- )
- self.eventbus.dispatch(step_event)
+ # Emit CreateAgentStepEvent
+ step_event = CreateAgentStepEvent.from_agent_step(
+ self,
+ self.state.last_model_output,
+ self.state.last_result,
+ actions_data,
+ browser_state_summary,
+ )
+ self.eventbus.dispatch(step_event)
# Increment step counter after step is fully completed
self.state.n_steps += 1
@@ -1459,20 +1443,18 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Only dispatch session events if this is the first run
if not self.state.session_initialized:
- if self.enable_cloud_sync:
- self.logger.debug('πŸ“‘ Dispatching CreateAgentSessionEvent...')
- # Emit CreateAgentSessionEvent at the START of run()
- self.eventbus.dispatch(CreateAgentSessionEvent.from_agent(self))
+ self.logger.debug('πŸ“‘ Dispatching CreateAgentSessionEvent...')
+ # Emit CreateAgentSessionEvent at the START of run()
+ self.eventbus.dispatch(CreateAgentSessionEvent.from_agent(self))
- # Brief delay to ensure session is created in backend before sending task
- await asyncio.sleep(0.2)
+ # Brief delay to ensure session is created in backend before sending task
+ await asyncio.sleep(0.2)
self.state.session_initialized = True
- if self.enable_cloud_sync:
- self.logger.debug('πŸ“‘ Dispatching CreateAgentTaskEvent...')
- # Emit CreateAgentTaskEvent at the START of run()
- self.eventbus.dispatch(CreateAgentTaskEvent.from_agent(self))
+ self.logger.debug('πŸ“‘ Dispatching CreateAgentTaskEvent...')
+ # Emit CreateAgentTaskEvent at the START of run()
+ self.eventbus.dispatch(CreateAgentTaskEvent.from_agent(self))
# Log startup message on first step (only if we haven't already done steps)
self._log_first_step_startup()
@@ -1608,8 +1590,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# not when they are completed
# Emit UpdateAgentTaskEvent at the END of run() with final task state
- if self.enable_cloud_sync:
- self.eventbus.dispatch(UpdateAgentTaskEvent.from_agent(self))
+ self.eventbus.dispatch(UpdateAgentTaskEvent.from_agent(self))
# Generate GIF if needed before stopping event bus
if self.settings.generate_gif:
@@ -1627,17 +1608,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
output_event = await CreateAgentOutputFileEvent.from_agent_and_file(self, output_path)
self.eventbus.dispatch(output_event)
- # Wait briefly for cloud auth to start and print the URL, but don't block for completion
- if self.enable_cloud_sync and hasattr(self, 'cloud_sync') and self.cloud_sync is not None:
- if self.cloud_sync.auth_task and not self.cloud_sync.auth_task.done():
- try:
- # Wait up to 1 second for auth to start and print URL
- await asyncio.wait_for(self.cloud_sync.auth_task, timeout=1.0)
- except TimeoutError:
- logger.debug('Cloud authentication started - continuing in background')
- except Exception as e:
- logger.debug(f'Cloud authentication error: {e}')
-
# Stop the event bus gracefully, waiting for all events to be processed
# Use longer timeout to avoid deadlocks in tests with multiple agents
await self.eventbus.stop(timeout=3.0)
@@ -2184,11 +2154,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
Returns:
bool: True if authentication was successful
"""
- if not hasattr(self, 'cloud_sync') or self.cloud_sync is None:
- self.logger.warning('Cloud sync is not available for this agent')
- return False
-
- return await self.cloud_sync.authenticate(show_instructions=show_instructions)
+ self.logger.warning('Cloud sync has been removed and is no longer available')
+ return False
def run_sync(
self,
diff --git a/browser_use/sync/service.py b/browser_use/sync/service.py
index f046d2831..47c0aa538 100644
--- a/browser_use/sync/service.py
+++ b/browser_use/sync/service.py
@@ -2,9 +2,7 @@
Cloud sync service for sending events to the Browser Use cloud.
"""
-import asyncio
import logging
-import shutil
import httpx
from bubus import BaseEvent
@@ -22,7 +20,6 @@ class CloudSync:
# Backend API URL for all API requests - can be passed directly or defaults to env var
self.base_url = base_url or CONFIG.BROWSER_USE_CLOUD_API_URL
self.auth_client = DeviceAuthClient(base_url=self.base_url)
- self.auth_task = None
self.session_id: str | None = None
self.allow_session_events_for_auth = allow_session_events_for_auth
self.auth_flow_active = False # Flag to indicate auth flow is running
@@ -40,14 +37,6 @@ class CloudSync:
if event.event_type == 'CreateAgentSessionEvent' and hasattr(event, 'id'):
self.session_id = str(event.id) # type: ignore
- # Start authentication immediately when session is created
- if not hasattr(self, 'auth_task') or self.auth_task is None:
- if self.session_id:
- # Start auth in background immediately
- self.auth_task = asyncio.create_task(self._background_auth(agent_session_id=self.session_id))
- else:
- logger.warning('Cannot start auth - session_id not set yet')
-
# Send events based on authentication status and context
if self.auth_client.is_authenticated:
# User is authenticated - send all events
@@ -58,13 +47,6 @@ class CloudSync:
# Mark auth flow as active when we see a session event
if event.event_type == 'CreateAgentSessionEvent':
self.auth_flow_active = True
- elif self.auth_task and not self.auth_task.done():
- # Authentication is in progress - only send session creation events
- # to preserve session context, but don't leak other data
- if event.event_type in ['CreateAgentSessionEvent']:
- await self._send_event(event)
- else:
- logger.debug(f'Skipping event {event.event_type} during auth - not authenticated yet')
else:
# User is not authenticated and no auth in progress - don't send anything
logger.debug(f'Skipping event {event.event_type} - user not authenticated')
@@ -122,37 +104,6 @@ class CloudSync:
except Exception as e:
logger.debug(f'Unexpected error sending event {event}: {type(e).__name__}: {e}')
- async def _background_auth(self, agent_session_id: str) -> None:
- """Run authentication in background or show cloud URL if already authenticated"""
- assert self.auth_client, 'auth_client must exist before calling CloudSync._background_auth()'
- assert self.session_id, 'session_id must be set before calling CloudSync._background_auth() can fire'
- try:
- # Only show cloud URLs if cloud sync is enabled
- if not self.enabled:
- return
-
- # Always show the cloud URL (auth happens immediately when session starts now)
- frontend_url = CONFIG.BROWSER_USE_CLOUD_UI_URL or self.base_url.replace('//api.', '//cloud.')
- session_url = f'{frontend_url.rstrip("/")}/agent/{agent_session_id}'
- terminal_width, _terminal_height = shutil.get_terminal_size((80, 20))
-
- if self.auth_client.is_authenticated:
- # User is authenticated - show direct link
- logger.info('─' * max(terminal_width - 40, 20))
- logger.info('🌐 View the details of this run in Browser Use Cloud:')
- logger.info(f' πŸ‘‰ {session_url}')
- logger.info('─' * max(terminal_width - 40, 20) + '\n')
- else:
- # User not authenticated - show auth prompt
- logger.info('─' * max(terminal_width - 40, 20))
- logger.info('πŸ” To view this run in Browser Use Cloud, authenticate with:')
- logger.info(' πŸ‘‰ browser-use auth')
- logger.info(' or: python -m browser_use.cli auth')
- logger.info('─' * max(terminal_width - 40, 20) + '\n')
-
- except Exception as e:
- logger.debug(f'Cloud sync authentication failed: {e}')
-
# async def _update_wal_user_ids(self, session_id: str) -> None:
# """Update user IDs in WAL file after authentication"""
# try:
@@ -187,11 +138,6 @@ class CloudSync:
# except Exception as e:
# logger.warning(f'Failed to update WAL user IDs: {e}')
- async def wait_for_auth(self) -> None:
- """Wait for authentication to complete if in progress"""
- if self.auth_task and not self.auth_task.done():
- await self.auth_task
-
def set_auth_flow_active(self) -> None:
"""Mark auth flow as active to allow all events"""
self.auth_flow_active = True
diff --git a/tests/ci/conftest.py b/tests/ci/conftest.py
index 318e80fd1..848fec122 100644
--- a/tests/ci/conftest.py
+++ b/tests/ci/conftest.py
@@ -203,12 +203,11 @@ def mock_llm():
@pytest.fixture(scope='function')
def agent_with_cloud(browser_session, mock_llm, cloud_sync):
- """Create agent with cloud sync enabled (using real CloudSync)."""
+ """Create agent (cloud_sync parameter removed)."""
agent = Agent(
task='Test task',
llm=mock_llm,
browser_session=browser_session,
- cloud_sync=cloud_sync,
)
return agent
diff --git a/tests/ci/test_sync_client_auth.py b/tests/ci/test_sync_client_auth.py
index 11160396a..9533db5bf 100644
--- a/tests/ci/test_sync_client_auth.py
+++ b/tests/ci/test_sync_client_auth.py
@@ -423,92 +423,6 @@ class TestCloudSync:
# Check that no requests were made
assert len(requests) == 0
- async def test_block_events_during_auth_progress(self, httpserver: HTTPServer, temp_config_dir):
- """Test that task events are BLOCKED when authentication is in progress (prevents data leak)."""
- 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)
-
- # Set up auth endpoints to simulate background auth in progress
- httpserver.expect_request(
- '/api/v1/oauth/device/authorize',
- method='POST',
- ).respond_with_json(
- {
- 'device_code': 'test-device-code',
- 'user_code': 'ABCD-1234',
- 'verification_uri': 'https://example.com/device',
- 'verification_uri_complete': 'https://example.com/device?user_code=ABCD-1234',
- 'expires_in': 1800,
- 'interval': 5,
- }
- )
-
- httpserver.expect_request(
- '/api/v1/oauth/device/token',
- method='POST',
- ).respond_with_json(
- {
- 'error': 'authorization_pending',
- 'error_description': 'Authorization pending',
- }
- )
-
- # 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(''))
- service.auth_client = auth
-
- # Manually start an auth task to simulate the scenario where auth is in progress
- import asyncio
-
- async def fake_auth():
- await asyncio.sleep(1) # Simulate auth taking some time
-
- service.auth_task = asyncio.create_task(fake_auth())
-
- # Set session ID
- service.session_id = 'test-session-id'
-
- # Send task event while auth is in progress (should be BLOCKED for security)
- await service.handle_event(
- CreateAgentTaskEvent(
- agent_session_id='test-session',
- llm_model='test-model',
- task='Test task during auth',
- user_id=TEMP_USER_ID,
- done_output=None,
- user_feedback_type=None,
- user_comment=None,
- gif_url=None,
- device_id='test-device-id',
- )
- )
-
- # Check that the task event was NOT sent (blocked for security during auth)
- assert len(requests) == 0
-
- # Clean up the background task to avoid test flakiness
- if service.auth_task and not service.auth_task.done():
- service.auth_task.cancel()
- try:
- await service.auth_task
- except asyncio.CancelledError:
- pass
-
async def test_authenticate_then_send(self, httpserver: HTTPServer, temp_config_dir):
"""Test that events are only sent after authentication."""
requests = []