Skip to content

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

make pending_events a list of event objects instead of dicts

Nick Sweeting63e5f59cdc54
diff --git a/browser_use/sync/service.py b/browser_use/sync/service.py
index e86a68a55..bf5ad33c7 100644
--- a/browser_use/sync/service.py
+++ b/browser_use/sync/service.py
@@ -24,7 +24,7 @@ class CloudSync:
self.base_url = base_url or BROWSER_USE_CLOUD_URL
self.enable_auth = enable_auth
self.auth_client = DeviceAuthClient(base_url=self.base_url) if enable_auth else None
- self.pending_events: list[dict] = []
+ self.pending_events: list[BaseEvent] = []
self.auth_task = None
self.session_id: str | None = None
@@ -33,42 +33,30 @@ class CloudSync:
try:
# Extract session ID from CreateAgentSessionEvent
if event.event_type == 'CreateAgentSession' and hasattr(event, 'id'):
- self.session_id = event.id
+ self.session_id = str(event.id) # type: ignore
# Start authentication flow if enabled and not authenticated
if self.enable_auth and self.auth_client and not self.auth_client.is_authenticated:
# Start auth in background
self.auth_task = asyncio.create_task(self._background_auth(agent_session_id=self.session_id))
- # Prepare event data
- event_data = self._prepare_event_data(event)
-
# Send event to cloud
- await self._send_event(event_data)
+ await self._send_event(event)
except Exception as e:
logger.error(f'Failed to handle {event.event_type} event: {type(e).__name__}: {e}', exc_info=True)
- def _prepare_event_data(self, event: BaseEvent) -> dict:
- """Prepare event data for cloud API"""
- # Get user_id from auth client or use temp ID
- user_id = self.auth_client.user_id if self.auth_client else TEMP_USER_ID
-
- # Set user_id directly on event (mutating the event)
- # Use setattr to handle cases where user_id might not be a defined field
- if hasattr(event, 'user_id') or hasattr(event, '__dict__'):
- event.user_id = user_id
- else:
- logger.debug(f'Could not set user_id on event type {type(event).__name__}')
-
- # Return event directly as dict
- return event.model_dump(mode='json')
-
- async def _send_event(self, event_data: dict) -> None:
+ async def _send_event(self, event: BaseEvent) -> None:
"""Send event to cloud API"""
try:
headers = {}
+ # override user_id on event with auth client user_id if available
+ if self.auth_client:
+ event.user_id = str(self.auth_client.user_id) # type: ignore
+ else:
+ event.user_id = TEMP_USER_ID # type: ignore
+
# Add auth headers if available
if self.auth_client:
headers.update(self.auth_client.get_headers())
@@ -77,28 +65,30 @@ class CloudSync:
async with httpx.AsyncClient() as client:
response = await client.post(
f'{self.base_url.rstrip("/")}/api/v1/events',
- json={'events': [event_data]},
+ json={'events': [event.model_dump(mode='json')]},
headers=headers,
timeout=10.0,
)
if response.status_code == 401 and self.auth_client and not self.auth_client.is_authenticated:
# Store event for retry after auth
- self.pending_events.append(event_data)
+ self.pending_events.append(event)
elif response.status_code >= 400:
# Log error but don't raise - we want to fail silently
logger.warning(f'Failed to send event to cloud: HTTP {response.status_code} - {response.text[:200]}')
except httpx.TimeoutException:
- logger.warning(f'Event send timed out after 10 seconds - event_type={event_data.get("event_type", "unknown")}')
+ logger.warning(f'⚠️ Event send timed out after 10 seconds: {event}')
except httpx.ConnectError as e:
- logger.warning(f'Failed to connect to cloud service at {self.base_url}: {e}')
+ logger.warning(f'⚠️ Failed to connect to cloud service at {self.base_url}: {e}')
except httpx.HTTPError as e:
- logger.warning(f'HTTP error sending event: {type(e).__name__}: {e}')
+ logger.warning(f'⚠️ HTTP error sending event {event}: {type(e).__name__}: {e}')
except Exception as e:
- logger.warning(f'Unexpected error sending {event_data.get("event_type", "unknown")} event: {type(e).__name__}: {e}')
+ logger.warning(f'⚠️ Unexpected error sending event {event}: {type(e).__name__}: {e}')
async def _background_auth(self, agent_session_id: str) -> None:
"""Run authentication in background"""
+ assert self.auth_client, 'enable_auth=True must be set before calling CloudSync_background_auth()'
+
try:
# Run authentication
success = await self.auth_client.authenticate(
@@ -121,15 +111,10 @@ class CloudSync:
if not self.pending_events:
return
- # Update user_id in pending events
- user_id = self.auth_client.user_id
- for event_data in self.pending_events:
- event_data['user_id'] = user_id
-
# Send all pending events
- for event_data in self.pending_events:
+ for event in self.pending_events:
try:
- await self._send_event(event_data)
+ await self._send_event(event)
except Exception as e:
logger.warning(f'Failed to resend pending event: {e}')
@@ -138,11 +123,13 @@ class CloudSync:
async def _update_wal_user_ids(self, session_id: str) -> None:
"""Update user IDs in WAL file after authentication"""
try:
- from browser_use.utils import BROWSER_USE_CONFIG_DIR
+ assert self.auth_client, 'Cloud sync must be authenticated to update WAL user ID'
wal_path = BROWSER_USE_CONFIG_DIR / 'events' / f'{session_id}.jsonl'
if not await anyio.Path(wal_path).exists():
- return
+ raise FileNotFoundError(
+ f'CloudSync failed to update saved event user_ids after auth: Agent EventBus WAL file not found: {wal_path}'
+ )
# Read all events
events = []