Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
implement new EventBus module with cloud_events to send on agent steps
Nick Sweeting9da6c485b740
diff --git a/browser_use/agent/cloud_events.py b/browser_use/agent/cloud_events.pynew file mode 100644index 000000000..718aab433--- /dev/null+++ b/browser_use/agent/cloud_events.py@@ -0,0 +1,247 @@+from datetime import datetime++from pydantic import Field, field_validator+from uuid_extensions import uuid7str++from browser_use.eventbus.models import BaseEvent++MAX_STRING_LENGTH = 10000 # 10K chars for most strings+MAX_URL_LENGTH = 2000+MAX_TASK_LENGTH = 5000+MAX_COMMENT_LENGTH = 2000+MAX_FILE_CONTENT_SIZE = 50 * 1024 * 1024 # 50MB+++class UpdateAgentTaskEvent(BaseEvent):+ event_type: str = Field(default='UpdateAgentTask', frozen=True)++ # Required fields for identification+ id: str # The task ID to update+ user_id: str = Field(max_length=255) # For authorization++ # Optional fields that can be updated+ stopped: bool | None = None+ paused: bool | None = None+ done_output: str | None = Field(None, max_length=MAX_STRING_LENGTH)+ finished_at: datetime | None = None+ agent_state: dict | None = None+ user_feedback_type: str | None = Field(None, max_length=10) # UserFeedbackType enum value as string+ user_comment: str | None = Field(None, max_length=MAX_COMMENT_LENGTH)+ gif_url: str | None = Field(None, max_length=MAX_URL_LENGTH)++ @classmethod+ def from_agent(cls, agent) -> 'UpdateAgentTaskEvent':+ """Create an UpdateAgentTaskEvent from an Agent instance"""+ if not hasattr(agent, '_task_start_time'):+ raise ValueError('Agent must have _task_start_time attribute')++ done_output = agent.state.history.final_result() if agent.state.history else None+ return cls(+ id=str(agent.task_id),+ user_id='', # To be filled by cloud handler+ stopped=agent.state.stopped if hasattr(agent.state, 'stopped') else False,+ paused=agent.state.paused if hasattr(agent.state, 'paused') else False,+ done_output=done_output,+ finished_at=datetime.utcnow() if agent.state.history.is_done() else None,+ agent_state=agent.state.model_dump() if hasattr(agent.state, 'model_dump') else {},+ # user_feedback_type and user_comment would be set by the API/frontend+ # gif_url would be set after GIF generation if needed+ )+++class CreateAgentOutputFileEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentOutputFile', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255)+ task_id: str+ file_name: str = Field(max_length=255)+ file_content: str | None = None # Base64 encoded file content+ content_type: str | None = Field(None, max_length=100) # MIME type for file uploads+ created_at: datetime = Field(default_factory=datetime.utcnow)++ @field_validator('file_content')+ @classmethod+ def validate_file_size(cls, v: str | None) -> str | None:+ """Validate base64 file content size."""+ if v is None:+ return v+ # Remove data URL prefix if present+ if ',' in v:+ v = v.split(',')[1]+ # Estimate decoded size (base64 is ~33% larger)+ estimated_size = len(v) * 3 / 4+ if estimated_size > MAX_FILE_CONTENT_SIZE:+ raise ValueError(f'File content exceeds maximum size of {MAX_FILE_CONTENT_SIZE / 1024 / 1024}MB')+ return v++ @classmethod+ async def from_agent_and_file(cls, agent, output_path: str) -> 'CreateAgentOutputFileEvent':+ """Create a CreateAgentOutputFileEvent from a file path"""+ import base64+ import os+ from pathlib import Path++ import anyio++ gif_path = Path(output_path)+ if not gif_path.exists():+ raise FileNotFoundError(f'File not found: {output_path}')++ gif_size = os.path.getsize(gif_path)++ # Read GIF content for base64 encoding if needed+ gif_content = None+ if gif_size < 50 * 1024 * 1024: # Only read if < 50MB+ async with await anyio.open_file(gif_path, 'rb') as f:+ gif_bytes = await f.read()+ gif_content = base64.b64encode(gif_bytes).decode('utf-8')++ return cls(+ user_id='', # To be filled by cloud handler+ task_id=str(agent.task_id),+ file_name=gif_path.name,+ file_content=gif_content, # Base64 encoded+ content_type='image/gif',+ )+++class CreateAgentStepEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentStep', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255) # Added for authorization checks+ created_at: datetime = Field(default_factory=datetime.utcnow)+ agent_task_id: str+ step: int+ evaluation_previous_goal: str = Field(max_length=MAX_STRING_LENGTH)+ memory: str = Field(max_length=MAX_STRING_LENGTH)+ next_goal: str = Field(max_length=MAX_STRING_LENGTH)+ actions: list[dict]+ screenshot_url: str | None = Field(None, max_length=MAX_FILE_CONTENT_SIZE) # ~50MB for base64 images+ url: str = Field(default='', max_length=MAX_URL_LENGTH)++ @field_validator('screenshot_url')+ @classmethod+ def validate_screenshot_size(cls, v: str | None) -> str | None:+ """Validate screenshot URL or base64 content size."""+ if v is None or not v.startswith('data:'):+ return v+ # It's base64 data, check size+ if ',' in v:+ base64_part = v.split(',')[1]+ estimated_size = len(base64_part) * 3 / 4+ if estimated_size > MAX_FILE_CONTENT_SIZE:+ raise ValueError(f'Screenshot content exceeds maximum size of {MAX_FILE_CONTENT_SIZE / 1024 / 1024}MB')+ return v++ @classmethod+ def from_agent_step(+ cls, agent, model_output, result: list, actions_data: list[dict], browser_state_summary+ ) -> 'CreateAgentStepEvent':+ """Create a CreateAgentStepEvent from agent step data"""+ # Get first action details if available+ first_action = model_output.action[0] if model_output.action else None++ # Extract current state from model output+ current_state = model_output.current_state if hasattr(model_output, 'current_state') else None++ # Capture screenshot as base64 data URL if available+ screenshot_url = None+ if browser_state_summary.screenshot:+ screenshot_url = f'data:image/png;base64,{browser_state_summary.screenshot}'++ return cls(+ user_id='', # To be filled by cloud handler+ agent_task_id=str(agent.task_id),+ step=agent.state.n_steps,+ evaluation_previous_goal=current_state.evaluation_previous_goal if current_state else '',+ memory=current_state.memory if current_state else '',+ next_goal=current_state.next_goal if current_state else '',+ actions=actions_data, # List of action dicts+ url=browser_state_summary.url,+ screenshot_url=screenshot_url,+ )+++class CreateAgentTaskEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentTask', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255) # Added for authorization checks+ agent_session_id: str+ llm_model: str = Field(max_length=100) # LLMModel enum value as string+ stopped: bool = False+ paused: bool = False+ task: str = Field(max_length=MAX_TASK_LENGTH)+ done_output: str | None = Field(None, max_length=MAX_STRING_LENGTH)+ scheduled_task_id: str | None = None+ started_at: datetime = Field(default_factory=datetime.utcnow)+ finished_at: datetime | None = None+ agent_state: dict = Field(default_factory=dict)+ user_feedback_type: str | None = Field(None, max_length=10) # UserFeedbackType enum value as string+ user_comment: str | None = Field(None, max_length=MAX_COMMENT_LENGTH)+ gif_url: str | None = Field(None, max_length=MAX_URL_LENGTH)++ @classmethod+ def from_agent(cls, agent) -> 'CreateAgentTaskEvent':+ """Create a CreateAgentTaskEvent from an Agent instance"""+ return cls(+ id=str(agent.task_id),+ user_id='', # To be filled by cloud handler+ agent_session_id=str(agent.session_id),+ task=agent.task,+ llm_model=agent.model_name,+ agent_state=agent.state.model_dump() if hasattr(agent.state, 'model_dump') else {},+ stopped=False,+ paused=False,+ done_output=None,+ started_at=datetime.fromtimestamp(agent._task_start_time),+ finished_at=None,+ )+++class CreateAgentSessionEvent(BaseEvent):+ event_type: str = Field(default='CreateAgentSession', frozen=True)++ # Model fields+ id: str = Field(default_factory=uuid7str)+ user_id: str = Field(max_length=255)+ browser_session_id: str = Field(max_length=255)+ browser_session_live_url: str = Field(max_length=MAX_URL_LENGTH)+ browser_session_cdp_url: str = Field(max_length=MAX_URL_LENGTH)+ browser_session_stopped: bool = False+ browser_session_stopped_at: datetime | None = None+ is_source_api: bool | None = None+ browser_state: dict = Field(default_factory=dict)+ browser_session_data: dict | None = None++ @classmethod+ def from_agent(cls, agent) -> 'CreateAgentSessionEvent':+ """Create a CreateAgentSessionEvent from an Agent instance"""+ return cls(+ id=str(agent.session_id),+ user_id='', # To be filled by cloud handler+ browser_session_id=agent.browser_session.id,+ browser_session_live_url='', # To be filled by cloud handler+ browser_session_cdp_url='', # To be filled by cloud handler+ browser_state={+ 'viewport': agent.browser_profile.viewport if agent.browser_profile else {'width': 1280, 'height': 720},+ 'user_agent': agent.browser_profile.user_agent if agent.browser_profile else None,+ 'headless': agent.browser_profile.headless if agent.browser_profile else True,+ 'initial_url': None, # Will be updated during execution+ 'final_url': None, # Will be updated during execution+ 'total_pages_visited': 0, # Will be updated during execution+ 'session_duration_seconds': 0, # Will be updated during execution+ },+ browser_session_data={+ 'cookies': [],+ 'secrets': {},+ # TODO: send secrets safely so tasks can be replayed on cloud seamlessly+ # 'secrets': dict(agent.sensitive_data) if agent.sensitive_data else {},+ 'allowed_domains': agent.browser_profile.allowed_domains if agent.browser_profile else [],+ },+ )diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex d0a8b0566..2ec242275 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -12,9 +12,17 @@ from collections.abc import Awaitable, Callablefrom pathlib import Pathfrom threading import Threadfrom typing import Any, Generic, TypeVar+from uuid import UUIDfrom dotenv import load_dotenv+from browser_use.agent.cloud_events import (+ CreateAgentOutputFileEvent,+ CreateAgentSessionEvent,+ CreateAgentStepEvent,+ CreateAgentTaskEvent,+ UpdateAgentTaskEvent,+)from browser_use.browser.session import DEFAULT_BROWSER_PROFILEload_dotenv()@@ -27,6 +35,7 @@ from langchain_core.messages import ()from playwright.async_api import Browser, BrowserContext, Pagefrom pydantic import BaseModel, ValidationError+from uuid_extensions import uuid7strfrom browser_use.agent.gif import create_history_giffrom browser_use.agent.memory import Memory, MemoryConfig@@ -57,15 +66,11 @@ from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.browser.views import BrowserStateSummaryfrom browser_use.controller.registry.views import ActionModelfrom browser_use.controller.service import Controller-from browser_use.dom.history_tree_processor.service import (- DOMHistoryElement,- HistoryTreeProcessor,-)+from browser_use.dom.history_tree_processor.service import DOMHistoryElement, HistoryTreeProcessor+from browser_use.eventbus import EventBusfrom browser_use.exceptions import LLMExceptionfrom browser_use.telemetry.service import ProductTelemetry-from browser_use.telemetry.views import (- AgentTelemetryEvent,-)+from browser_use.telemetry.views import AgentTelemetryEventfrom browser_use.utils import get_browser_use_version, time_execution_async, time_execution_synclogger = logging.getLogger(__name__)@@ -101,13 +106,13 @@ class Agent(Generic[Context]):llm: BaseChatModel,# Optional parameterspage: Page | None = None,- browser: Browser | None = None,+ browser: Browser | BrowserSession | None = None,browser_context: BrowserContext | None = None,browser_profile: BrowserProfile | None = None,browser_session: BrowserSession | None = None,controller: Controller[Context] = Controller(),# Initial agent run parameters- sensitive_data: dict[str, str | dict[str, str]] | None = None,+ sensitive_data: dict[str, str] | dict[str, dict[str, str]] | None = None,initial_actions: list[dict[str, dict[str, Any]]] | None = None,# Cloud Callbacksregister_new_step_callback: (@@ -286,6 +291,9 @@ class Agent(Generic[Context]):else:self.memory = None+ if isinstance(browser, BrowserSession):+ browser_session = browser_session or browser+browser_context = page.context if page else browser_context# assert not (browser_session and browser_profile), 'Cannot provide both browser_session and browser_profile'# assert not (browser_session and browser), 'Cannot provide both browser_session and browser'@@ -383,6 +391,15 @@ class Agent(Generic[Context]):# Telemetryself.telemetry = ProductTelemetry()+ # Generate unique IDs for this agent session and task+ self.session_id: UUID = UUID(uuid7str())+ self.task_id: UUID = UUID(uuid7str())++ # Event bus with WAL persistence+ # Default to ~/.config/browseruse/events/{agent_task_id}.jsonl+ wal_path = Path.home() / '.config' / 'browseruse' / 'events' / f'{self.task_id}.jsonl'+ self.eventbus = EventBus(name='Agent', wal_path=wal_path)+if self.settings.save_conversation_path:logger.info(f'Saving conversation to {self.settings.save_conversation_path}')self._external_pause_event = asyncio.Event()@@ -736,6 +753,10 @@ class Agent(Generic[Context]):return self._detect_best_tool_calling_method()def add_new_task(self, new_task: str) -> None:+ """Add a new task to the agent, keeping the same task_id as tasks are continuous"""+ # Simply delegate to message manager - no need for new task_id or events+ # The task continues with new instructions, it doesn't end and start a new one+ self.task = new_taskself._message_manager.add_new_task(new_task)async def _raise_if_stopped_or_paused(self) -> None:@@ -927,6 +948,19 @@ class Agent(Generic[Context]):# Log step completion summaryself._log_step_completion_summary(step_start_time, result)+ # Emit both step created and executed events+ if browser_state_summary and model_output:+ # Extract key step data for the event+ actions_data = []+ if model_output.action:+ for action in model_output.action:+ action_dict = action.model_dump() if hasattr(action, 'model_dump') else {}+ actions_data.append(action_dict)++ # Emit CreateAgentStepEvent+ step_event = CreateAgentStepEvent.from_agent_step(self, model_output, result, actions_data, browser_state_summary)+ self.eventbus.emit(step_event)+@time_execution_async('--handle_step_error (agent)')async def _handle_step_error(self, error: Exception) -> list[ActionResult]:"""Handle all types of errors that can occur during a step"""@@ -1310,6 +1344,16 @@ class Agent(Generic[Context]):try:self._log_agent_run()+ # Initialize timing for session and task+ self._session_start_time = time.time()+ self._task_start_time = self._session_start_time # Initialize task start time++ # Emit CreateAgentSessionEvent at the START of run()+ self.eventbus.emit(CreateAgentSessionEvent.from_agent(self))++ # Emit CreateAgentTaskEvent at the START of run()+ self.eventbus.emit(CreateAgentTaskEvent.from_agent(self))+# Execute initial actions if providedif self.initial_actions:result = await self.multi_act(self.initial_actions, check_for_new_elements=False)@@ -1354,6 +1398,8 @@ class Agent(Generic[Context]):continueawait self.log_completion()++ # Task completedbreakelse:agent_run_error = 'Failed to complete task in maximum steps'@@ -1401,8 +1447,14 @@ class Agent(Generic[Context]):# ADDED: Info message when custom telemetry for SIGINT was already loggedlogger.info('Telemetry for force exit (SIGINT) was logged by custom exit callback.')- await self.close()+ # NOTE: CreateAgentSessionEvent and CreateAgentTaskEvent are now emitted at the START of run()+ # to match backend requirements for CREATE events to be fired when entities are created,+ # not when they are completed++ # Emit UpdateAgentTaskEvent at the END of run() with final task state+ self.eventbus.emit(UpdateAgentTaskEvent.from_agent(self))+ # Generate GIF if needed before stopping event busif self.settings.generate_gif:output_path: str = 'agent_history.gif'if isinstance(self.settings.generate_gif, str):@@ -1410,6 +1462,15 @@ class Agent(Generic[Context]):create_history_gif(task=self.task, history=self.state.history, output_path=output_path)+ # Emit output file generated event for GIF+ output_event = await CreateAgentOutputFileEvent.from_agent_and_file(self, output_path)+ self.eventbus.emit(output_event)++ # Stop the event bus gracefully, waiting for all events to be processed+ await self.eventbus.stop(timeout=5.0)++ await self.close()+# @observe(name='controller.multi_act')@time_execution_async('--multi_act')async def multi_act(@@ -1684,6 +1745,8 @@ class Agent(Generic[Context]):self.state.paused = Trueself._external_pause_event.clear()+ # Task paused+# The signal handler will handle the asyncio pause logic for us# No need to duplicate the code here@@ -1694,6 +1757,8 @@ class Agent(Generic[Context]):self.state.paused = Falseself._external_pause_event.set()+ # Task resumed+# The signal handler should have already reset the flags# through its reset() method when called from run()@@ -1710,6 +1775,8 @@ class Agent(Generic[Context]):logger.info('⏹️ Agent stopping')self.state.stopped = True+ # Task stopped+def _convert_initial_actions(self, actions: list[dict[str, dict[str, Any]]]) -> list[ActionModel]:"""Convert dictionary-based actions to ActionModel instances"""converted_actions = []diff --git a/browser_use/eventbus/__init__.py b/browser_use/eventbus/__init__.pynew file mode 100644index 000000000..4a52c23d1--- /dev/null+++ b/browser_use/eventbus/__init__.py@@ -0,0 +1,9 @@+"""Event bus for the browser-use agent."""++from browser_use.eventbus.models import BaseEvent+from browser_use.eventbus.service import EventBus++__all__ = [+ 'EventBus',+ 'BaseEvent',+]diff --git a/browser_use/eventbus/models.py b/browser_use/eventbus/models.pynew file mode 100644index 000000000..b820b730c--- /dev/null+++ b/browser_use/eventbus/models.py@@ -0,0 +1,85 @@+import asyncio+from datetime import UTC, datetime+from typing import Any++from pydantic import BaseModel, Field, PrivateAttr+from uuid_extensions import uuid7str++from browser_use.utils import get_browser_use_version++# Constants for validation+MAX_STRING_LENGTH = 10000 # 10K chars for most strings+MAX_URL_LENGTH = 2000+MAX_TASK_LENGTH = 5000+MAX_COMMENT_LENGTH = 2000+MAX_FILE_CONTENT_SIZE = 50 * 1024 * 1024 # 50MB+++class BaseEvent(BaseModel):+ """+ The base model used for all Events that flow through the EventBus system.+ """++ event_schema: str | None = Field(default=None, description='Event schema version in format ClassName@version', max_length=100)+ event_type: str+ event_id: str = Field(default_factory=uuid7str)+ queued_at: datetime = Field(default_factory=datetime.utcnow)+ event_path: list[str] = Field(default_factory=list, description='Path tracking for event routing')++ # Completion tracking fields+ started_at: datetime | None = Field(default=None)+ completed_at: datetime | None = Field(default=None)+ results: dict[str, Any] = Field(default_factory=dict)+ errors: dict[str, str] = Field(default_factory=dict) # Store error messages as strings++ # Private field for completion tracking+ _completion_event: asyncio.Event | None = PrivateAttr(default=None)++ async def result(self):+ """Wait for completion and return self with results"""+ await self.wait_for_completion()+ return self++ @property+ def state(self) -> str:+ """Return current event state: 'queued' | 'started' | 'completed'"""+ if self.completed_at:+ return 'completed'+ elif self.started_at:+ return 'started'+ return 'queued'++ @property+ def duration(self) -> float | None:+ """Return processing duration in seconds, or None if not completed"""+ if self.started_at:+ return ((self.completed_at or datetime.now(UTC)) - self.started_at).total_seconds()+ return None++ def model_post_init(self, __context: Any) -> None:+ """Initialize completion event and set event schema after model creation"""+ # Set event_schema if not already set+ if self.event_schema is None:+ version = get_browser_use_version()+ class_module = self.__class__.__module__+ class_qualname = self.__class__.__qualname__+ self.event_schema = f'{class_module}.{class_qualname}@{version}'++ try:+ # Only create event if we're in an async context+ asyncio.get_running_loop()+ self._completion_event = asyncio.Event()+ except RuntimeError:+ # Not in async context, skip+ self._completion_event = None++ async def wait_for_completion(self) -> None:+ """Wait for this event to be fully processed"""+ if self._completion_event:+ await self._completion_event.wait()++ def mark_completed(self) -> None:+ """Mark this event as completed"""+ self.completed_at = datetime.now(UTC)+ if self._completion_event:+ self._completion_event.set()diff --git a/browser_use/eventbus/service.py b/browser_use/eventbus/service.pynew file mode 100644index 000000000..2c9edf87b--- /dev/null+++ b/browser_use/eventbus/service.py@@ -0,0 +1,305 @@+import asyncio+import inspect+import logging+from collections import defaultdict+from collections.abc import Awaitable, Callable+from datetime import UTC, datetime+from pathlib import Path+from typing import Any, Union++import anyio+from pydantic import BaseModel++from browser_use.eventbus.models import BaseEvent++logger = logging.getLogger(__name__)++# Type alias for event handlers+EventHandler = Union[Callable[[BaseEvent], Any], Callable[[BaseEvent], Awaitable[Any]]]+++class EventBus:+ """+ Async event bus with write-ahead logging and guaranteed FIFO processing.++ Features:+ - Sync and async event enqueueing+ - Blocking and non-blocking dispatch+ - Write-ahead logging with UUIDs and timestamps+ - FIFO event processing+ - Parallel handler execution per event+ - Serial event processing+ """++ def __init__(self, name: str | None = None, wal_path: Path | str | None = None):+ self.name = name or f'EventBus_{hex(id(self))[-6:]}'+ self.event_queue: asyncio.Queue[BaseEvent] = asyncio.Queue()+ self.event_history: list[BaseEvent] = []+ self.handlers: dict[str, list[EventHandler]] = defaultdict(list)+ self._is_running = False+ self._runloop_task: asyncio.Task | None = None+ self._runloop_lock = asyncio.Lock()++ # Set up WAL path and create parent directory if needed+ self.wal_path = None+ if wal_path:+ self.wal_path = Path(wal_path)+ self.wal_path.parent.mkdir(parents=True, exist_ok=True)++ # Signal that fires when the event bus is idle (no events being processed)+ self._on_idle = asyncio.Event()+ self._on_idle.set() # Start in idle state++ # Register default logger handler+ self.on('*', self._default_log_handler)++ def __del__(self):+ """Auto-cleanup on garbage collection"""+ if self._is_running:+ try:+ loop = asyncio.get_running_loop()+ loop.create_task(self.stop())+ except RuntimeError:+ # No event loop, nothing to clean+ pass++ @property+ def events_queued(self) -> list[BaseEvent]:+ """Get events that haven't started processing yet"""+ return [event for event in self.event_history if event.started_at is None]++ @property+ def events_started(self) -> list[BaseEvent]:+ """Get events currently being processed"""+ return [event for event in self.event_history if event.started_at and not event.completed_at]++ @property+ def events_completed(self) -> list[BaseEvent]:+ """Get events that have completed processing"""+ return [event for event in self.event_history if event.completed_at is not None]++ def on(self, event_pattern: str | type[BaseModel], handler: EventHandler) -> None:+ """Subscribe to events matching a pattern, event type name, or event model class.+ Use '*' for all events.++ Examples:+ eventbus.on('*', handler) # All events+ eventbus.on('TaskStartedEvent', handler) # Specific event type+ eventbus.on(TaskStartedEvent, handler) # Event model class+ """+ # Allow both sync and async handlers+ if event_pattern == '*':+ # Subscribe to all events using '*' as the key+ self.handlers['*'].append(handler)+ elif isinstance(event_pattern, type) and issubclass(event_pattern, BaseModel):+ # Subscribe by model class+ self.handlers[event_pattern.__name__].append(handler)+ else:+ # Subscribe by string event type+ self.handlers[str(event_pattern)].append(handler)++ def emit(self, event: BaseEvent) -> BaseEvent:+ """+ Enqueue an event for processing. Returns awaitable event object.+ Auto-starts the EventBus if not already running.+ """+ # Auto-start if not running+ if not self._is_running:+ try:+ loop = asyncio.get_running_loop()+ self._is_running = True+ self._runloop_task = loop.create_task(self._run_loop())+ except RuntimeError:+ # No event loop - will start when one becomes available+ pass++ # All events must inherit from BaseEvent+ actual_event = event++ # Add this EventBus to the event_path if not already there+ if self.name not in actual_event.event_path:+ actual_event = actual_event.model_copy(update={'event_path': actual_event.event_path + [self.name]})++ self.event_history.append(actual_event)++ # Put event in queue synchronously using put_nowait+ try:+ self.event_queue.put_nowait(actual_event)+ except asyncio.QueueFull:+ logger.error(f'Event queue is full, dropping event {actual_event.event_type}')++ logger.debug(f'Emitting event {actual_event.event_type} to queue')+ return actual_event++ async def stop(self, timeout: float | None = None) -> None:+ """Stop the event bus, optionally waiting for events to complete"""+ if not self._is_running:+ return++ # Log current state+ logger.debug(f'EventBus stopping - Queue size: {self.event_queue.qsize()}, Processing events: {len(self.events_started)}')++ # Wait for completion if timeout specified+ if timeout is not None:+ await self.wait_until_idle(timeout=timeout)++ # Force shutdown+ self._is_running = False++ if self._runloop_task:+ self._runloop_task.cancel()+ try:+ await self._runloop_task+ except asyncio.CancelledError:+ pass++ if timeout is not None:+ logger.debug(f'{self.name} stopped gracefully')+ else:+ logger.debug(f'{self.name} stopped immediately')++ async def wait_until_idle(self, timeout: float | None = None) -> None:+ """Wait until the event bus is idle (no events being processed)"""+ # First wait for the queue to be empty+ await self.event_queue.join()+ logger.debug(f'Queue joined, processing events: {len(self.events_started)}')++ # Then wait for idle state with timeout+ try:+ await asyncio.wait_for(self._on_idle.wait(), timeout=timeout)+ except TimeoutError:+ logger.warning(f'Timeout waiting for event bus to be idle after {timeout}s (processing: {len(self.events_started)})')++ def _get_applicable_handlers(self, event: BaseEvent) -> dict[str, EventHandler]:+ """Get all handlers that should process the given event, filtering out those that would create loops"""+ applicable_handlers = []++ # Add type-specific handlers+ applicable_handlers.extend(self.handlers.get(event.event_type, []))++ # Add wildcard handlers (handlers registered for '*')+ applicable_handlers.extend(self.handlers.get('*', []))++ # Filter out handlers that would create loops and build name->handler mapping+ filtered_handlers = {}+ for handler in applicable_handlers:+ if self._would_create_loop(handler, event):+ logger.debug(f'Skipping {handler.__name__} to prevent loop for {event.event_type}')+ else:+ filtered_handlers[handler.__name__] = handler++ return filtered_handlers++ async def _execute_handlers(self, event: BaseEvent) -> None:+ """Execute all handlers for an event in parallel"""+ applicable_handlers = self._get_applicable_handlers(event)++ if not applicable_handlers:+ return++ # Execute all handlers in parallel+ handler_tasks = {}+ for handler_name, handler in applicable_handlers.items():+ task = asyncio.create_task(self._safe_execute_handler(handler, event))+ handler_tasks[handler_name] = task++ # Wait for all handlers to complete and build results+ for handler_name, task in handler_tasks.items():+ try:+ result = await task+ event.results[handler_name] = result+ except Exception as e:+ event.errors[handler_name] = str(e)+ logger.error(f'Handler {handler_name} failed for event {event.event_id}: {e}')++ async def _safe_execute_handler(self, handler: EventHandler, event: BaseEvent) -> Any:+ """Safely execute a single handler"""+ try:+ if inspect.iscoroutinefunction(handler):+ return await handler(event)+ else:+ # Run sync handler in thread pool to avoid blocking+ loop = asyncio.get_event_loop()+ return await loop.run_in_executor(None, handler, event)+ except Exception as e:+ logger.exception(f'Error in handler {handler.__name__} for event {event.event_id}')+ raise++ async def _run_loop(self) -> None:+ """Main event processing loop"""+ while self._is_running:+ try:+ # Check if we're idle+ if self.event_queue.empty() and len(self.events_started) == 0:+ self._on_idle.set()+ else:+ self._on_idle.clear()++ # Wait for next event with timeout to periodically check idle state+ try:+ event = await asyncio.wait_for(self.event_queue.get(), timeout=0.1)++ # Clear idle state when we get an event+ self._on_idle.clear()++ # Process the event+ async with self._runloop_lock:+ # Record start time+ event.started_at = datetime.now(UTC)++ # Execute all handlers for this event+ await self._execute_handlers(event)++ # Mark event as completed+ event.mark_completed()++ # Persist to WAL if configured+ if self.wal_path:+ wal_result = await self._default_wal_handler(event)+ # logger.debug(f'WAL persistence result: {wal_result}')++ # Mark task as done+ self.event_queue.task_done()++ except TimeoutError:+ # No events in queue, continue to check idle state+ continue+ except asyncio.CancelledError:+ break+ except Exception as e:+ logger.exception(f'{self.name} Error in event loop: {e}')+ # Continue running even if there's an error++ @staticmethod+ def _would_create_loop(handler: EventHandler, event: BaseEvent) -> bool:+ """Check if calling this handler would create a loop"""+ # If handler is another EventBus.emit method+ if hasattr(handler, '__self__') and isinstance(handler.__self__, EventBus):+ target_bus = handler.__self__+ return target_bus.name in event.event_path+ return False++ @staticmethod+ async def _default_log_handler(event: BaseEvent) -> str:+ """Default handler that logs all events"""+ logger.debug(f'Event processed: {event.event_type} [{event.event_id}] - {event.model_dump_json()}')+ return 'logged'++ async def _default_wal_handler(self, event: BaseEvent) -> str:+ """Persist completed event to WAL file as JSONL"""+ if not self.wal_path:+ return 'skipped'++ try:+ # Use model_dump_json which already handles datetime serialization+ event_json = event.model_dump_json()++ # Append as JSONL (one JSON object per line)+ async with await anyio.open_file(self.wal_path, 'a') as f:+ await f.write(event_json + '\n')++ return 'appended'++ except Exception as e:+ logger.error(f'Failed to persist event {event.event_id} to WAL: {e}')+ return 'failed'diff --git a/tests/ci/test_agent_emits_cloud_events.py b/tests/ci/test_agent_emits_cloud_events.pynew file mode 100644index 000000000..dee734c2b--- /dev/null+++ b/tests/ci/test_agent_emits_cloud_events.py@@ -0,0 +1,680 @@+"""+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+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 browser_use import Agent+from browser_use.browser import BrowserSession+from browser_use.eventbus import (+ BaseEvent,+ EventBus,+)+++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.queued_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.queued_at <= task_event.queued_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.queued_at <= step_event.queued_at, 'Task event should be emitted before or at same time as Step event'+ # All create events should happen before update+ assert step_event.queued_at <= update_event.queued_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.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.utcnow(),+ finished_at=datetime.utcnow(),+ 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.utcnow(),+ 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='test-session',+ user_id='test-user',+ browser_session_id='test-browser',+ browser_session_live_url='https://example.com',+ browser_session_cdp_url='ws://localhost:9222',+ ),+ CreateAgentTaskEvent(+ user_id='test-user',+ agent_session_id='test-session',+ task='test',+ llm_model='gpt-4o',+ ),+ CreateAgentStepEvent(+ user_id='test-user',+ agent_task_id='test-task',+ 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.queued_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'+++class TestEventBusIntegration:+ """Test EventBus integration with cloud events"""++ async def test_eventbus_processes_all_cloud_events(self):+ """Test that EventBus can process all types of cloud events"""+ bus = EventBus()++ collected = []++ async def collect(event: BaseEvent):+ collected.append(event)+ return 'ok'++ bus.on('*', collect)++ try:+ # Emit one of each event type+ events = [+ CreateAgentSessionEvent(+ id='0683fb03-c5da-79c9-8000-d3a39c47c659',+ user_id='test',+ browser_session_id='session1',+ browser_session_live_url='https://example.com',+ browser_session_cdp_url='ws://localhost:9222',+ ),+ CreateAgentTaskEvent(+ user_id='test',+ agent_session_id='0683fb03-c5da-79c9-8000-d3a39c47c659',+ llm_model='test-model',+ task='test task',+ ),+ CreateAgentStepEvent(+ user_id='test',+ agent_task_id='0683fb03-c5da-79c9-8000-d3a39c47c659',+ step=1,+ evaluation_previous_goal='eval',+ memory='memory',+ next_goal='goal',+ actions=[{'name': 'test'}],+ ),+ CreateAgentOutputFileEvent(+ user_id='test',+ task_id='0683fb03-c5da-79c9-8000-d3a39c47c659',+ file_name='test.txt',+ file_content=base64.b64encode(b'test').decode(),+ ),+ UpdateAgentTaskEvent(+ id='0683fb03-c5da-79c9-8000-d3a39c47c659',+ user_id='test',+ stopped=True,+ done_output='Task completed',+ finished_at=datetime.utcnow(),+ ),+ ]++ # Emit all events+ for event in events:+ bus.emit(event)++ # Wait for processing+ await bus.wait_until_idle()++ # Check all were collected+ assert len(collected) == len(events)+ event_types = {e.event_type for e in collected}+ expected_types = {+ 'CreateAgentSession',+ 'CreateAgentTask',+ 'CreateAgentStep',+ 'CreateAgentOutputFile',+ 'UpdateAgentTask',+ }+ assert event_types == expected_types++ finally:+ await bus.stop()diff --git a/tests/ci/test_event_bus.py b/tests/ci/test_event_bus.pynew file mode 100644index 000000000..9bd72553a--- /dev/null+++ b/tests/ci/test_event_bus.py@@ -0,0 +1,894 @@+"""+Comprehensive tests for the EventBus implementation.++Tests cover:+- Basic event enqueueing and processing+- Sync and async contexts+- Handler registration and execution+- FIFO ordering+- Parallel handler execution+- Error handling+- Write-ahead logging+- Serialization+- Batch operations+"""++import asyncio+import json+import time+from datetime import datetime+from typing import Any++import pytest+from pydantic import Field++from browser_use.agent.cloud_events import CreateAgentTaskEvent+from browser_use.eventbus import BaseEvent, EventBus+++# Test event models - using proper Event subclasses+class UserActionEvent(BaseEvent):+ """Test event model for user actions"""++ event_type: str = Field(default='UserActionEvent', frozen=True)+ action: str+ user_id: str+ metadata: dict[str, Any] = Field(default_factory=dict)+++class SystemEventModel(BaseEvent):+ """Test event model for system events"""++ event_type: str = Field(default='SystemEventModel', frozen=True)+ event_name: str+ severity: str = 'info'+ details: dict[str, Any] = Field(default_factory=dict)+++class MockAgent:+ """Mock agent for testing"""++ def __init__(self, name: str = 'TestAgent'):+ self.name = name+ self.events_received = []+++async def eventbus():+ """Create an event bus for testing"""+ agent = MockAgent()+ bus = EventBus()+ yield bus+ await bus.stop()+++def mock_agent():+ """Create a mock agent"""+ return MockAgent()+++class TestEventBusBasics:+ """Test basic EventBus functionality"""++ async def test_eventbus_initialization(self, mock_agent):+ """Test that EventBus initializes correctly"""+ bus = EventBus()++ assert bus._is_running is False+ assert bus._runloop_task is None+ assert len(bus.event_history) == 0+ assert len(bus.handlers['*']) == 1 # Default logger++ async def test_auto_start_and_stop(self, mock_agent):+ """Test auto-start functionality and stopping the event bus"""+ bus = EventBus()++ # Should not be running initially+ assert bus._is_running is False+ assert bus._runloop_task is None++ # Auto-start by emitting an event+ bus.emit(UserActionEvent(action='test', user_id='user123'))+ await bus.wait_until_idle()++ # Should be running after auto-start+ assert bus._is_running is True+ assert bus._runloop_task is not None++ # Stop the bus+ await bus.stop()+ assert bus._is_running is False++ # Stop again should be idempotent+ await bus.stop()+ assert bus._is_running is False+++class TestEventEnqueueing:+ """Test event enqueueing functionality"""++ async def test_emit(self, eventbus):+ """Test event emission"""+ event = UserActionEvent(action='login', user_id='user123')++ # Emit event+ result = eventbus.emit(event)++ # Check result+ assert isinstance(result, UserActionEvent)+ assert result.event_type == 'UserActionEvent'+ assert result.action == 'login'+ assert result.user_id == 'user123'+ assert result.event_id is not None+ assert result.queued_at is not None++ # Wait for processing+ await eventbus.wait_until_idle()++ # Check event history+ assert len(eventbus.event_history) == 1+ # The returned result should have completion information after waiting+ assert result.completed_at is not None+ assert result.started_at is not None++ def test_emit_sync(self, mock_agent):+ """Test sync event emission"""+ bus = EventBus()+ event = SystemEventModel(event_name='startup', severity='info')++ # Emit event from sync context+ result = bus.emit(event)++ # Check result+ assert isinstance(result, SystemEventModel)+ assert result.event_type == 'SystemEventModel'+ assert result.event_name == 'startup'+ assert result.severity == 'info'++ # Check write-ahead log+ assert len(bus.event_history) == 1++ async def test_event_result(self, eventbus):+ """Test event.result() pattern"""+ event = UserActionEvent(action='logout', user_id='user123')++ # Emit returns immediately+ emitted_event = eventbus.emit(event)+ assert emitted_event.queued_at is not None+ assert emitted_event.started_at is None # Not started yet+ assert emitted_event.completed_at is None # Not completed yet++ # Wait for completion+ result = await emitted_event.result()++ # Check that event was processed+ assert result.started_at is not None+ assert result.completed_at is not None+ assert result.results['_default_log_handler'] == 'logged'++ async def test_emit_convenience_method(self, eventbus):+ """Test the emit() convenience method"""+ event = UserActionEvent(action='click', user_id='user123')++ # Use emit() method+ result = eventbus.emit(event)++ assert isinstance(result, BaseEvent)+ assert result.event_type == 'UserActionEvent'++ # Wait for processing+ await eventbus.wait_until_idle()+++class TestHandlerRegistration:+ """Test handler registration and execution"""++ async def test_subscribe_handler(self, eventbus):+ """Test subscribing a handler to specific event type"""+ results = []++ async def user_action_handler(event: UserActionEvent) -> str:+ results.append(f'Handled {event.action}')+ return f'Processed {event.action}'++ # Subscribe handler+ eventbus.on('UserActionEvent', user_action_handler)++ # Emit event+ event = UserActionEvent(action='login', user_id='user123')+ eventbus.emit(event)+ await eventbus.wait_until_idle()++ # Check handler was called+ assert len(results) == 1+ assert results[0] == 'Handled login'++ async def test_subscribe_by_model(self, eventbus):+ """Test subscribing a handler using model class"""+ results = []++ async def system_handler(event: SystemEventModel) -> str:+ results.append(event.event_name)+ return 'handled'++ # Subscribe using model+ eventbus.on(SystemEventModel, system_handler)++ # Emit event+ event = SystemEventModel(event_name='config_loaded')+ eventbus.emit(event)+ await eventbus.wait_until_idle()++ # Check handler was called+ assert len(results) == 1+ assert results[0] == 'config_loaded'++ async def test_subscribe_to_all(self, eventbus):+ """Test subscribing a handler to all events"""+ all_events = []++ async def universal_handler(event: BaseEvent) -> str:+ all_events.append(event.event_type)+ return 'universal'++ # Subscribe to all+ eventbus.on('*', universal_handler)++ # Emit different event types+ eventbus.emit(UserActionEvent(action='login', user_id='u1'))+ eventbus.emit(SystemEventModel(event_name='startup'))+ await eventbus.wait_until_idle()++ # Check both events were handled+ assert len(all_events) == 2+ assert 'UserActionEvent' in all_events+ assert 'SystemEventModel' in all_events++ async def test_multiple_handlers_parallel(self, eventbus):+ """Test that multiple handlers run in parallel"""+ start_times = []+ end_times = []++ async def slow_handler_1(event: BaseEvent) -> str:+ start_times.append(('h1', time.time()))+ await asyncio.sleep(0.1)+ end_times.append(('h1', time.time()))+ return 'handler1'++ async def slow_handler_2(event: BaseEvent) -> str:+ start_times.append(('h2', time.time()))+ await asyncio.sleep(0.1)+ end_times.append(('h2', time.time()))+ return 'handler2'++ # Subscribe both handlers+ eventbus.on('UserActionEvent', slow_handler_1)+ eventbus.on('UserActionEvent', slow_handler_2)++ # Emit event and wait+ start = time.time()+ event = await eventbus.emit(UserActionEvent(action='test', user_id='u1')).result()+ duration = time.time() - start++ # Check handlers ran in parallel (should take ~0.1s, not 0.2s)+ assert duration < 0.15+ assert len(start_times) == 2+ assert len(end_times) == 2++ # Check results+ assert event.results['slow_handler_1'] == 'handler1'+ assert event.results['slow_handler_2'] == 'handler2'++ def test_handler_can_be_sync_or_async(self, mock_agent):+ """Test that both sync and async handlers are accepted"""+ bus = EventBus()++ def sync_handler(event: BaseEvent) -> str:+ return 'sync'++ async def async_handler(event: BaseEvent) -> str:+ return 'async'++ # Both should work+ bus.on('TestEvent', sync_handler)+ bus.on('TestEvent', async_handler)++ # Check both were registered+ assert len(bus.handlers['TestEvent']) == 2+++class TestFIFOOrdering:+ """Test FIFO event processing"""++ async def test_fifo_processing(self, eventbus):+ """Test that events are processed in FIFO order"""+ processed_order = []++ async def order_handler(event: UserActionEvent) -> int:+ # Extract order from the metadata+ order = event.metadata.get('order', 0)+ processed_order.append(order)+ return order++ eventbus.on('*', order_handler)++ # Enqueue multiple events rapidly+ events = []+ for i in range(10):+ event = UserActionEvent(action=f'action_{i}', user_id='u1', metadata={'order': i})+ events.append(eventbus.emit(event))++ # Wait for all to process+ await eventbus.wait_until_idle()++ # Check order+ assert processed_order == list(range(10))+++class TestErrorHandling:+ """Test error handling in handlers"""++ async def test_handler_error_captured(self, eventbus):+ """Test that handler errors are captured in event"""++ async def failing_handler(event: BaseEvent) -> str:+ raise ValueError('Handler failed!')++ eventbus.on('UserActionEvent', failing_handler)++ # Emit event+ event = await eventbus.emit(UserActionEvent(action='fail', user_id='u1')).result()++ # Check error was captured+ assert 'failing_handler' in event.errors+ assert isinstance(event.errors['failing_handler'], str)+ assert 'Handler failed!' in event.errors['failing_handler']++ async def test_one_handler_failure_doesnt_stop_others(self, eventbus):+ """Test that one handler failing doesn't prevent others from running"""+ results = []++ async def failing_handler(event: BaseEvent) -> str:+ raise RuntimeError('I fail!')++ async def working_handler(event: BaseEvent) -> str:+ results.append('I work!')+ return 'success'++ eventbus.on('UserActionEvent', failing_handler)+ eventbus.on('UserActionEvent', working_handler)++ # Emit event+ event = await eventbus.emit(UserActionEvent(action='test', user_id='u1')).result()++ # Check both handlers ran+ assert len(results) == 1+ assert results[0] == 'I work!'+ assert event.results['working_handler'] == 'success'+ assert 'failing_handler' in event.errors+++class TestBatchOperations:+ """Test batch event operations"""++ async def test_batch_emit_with_gather(self, eventbus):+ """Test batch event emission with asyncio.gather"""+ events = [+ UserActionEvent(action='login', user_id='u1'),+ SystemEventModel(event_name='startup'),+ UserActionEvent(action='logout', user_id='u1'),+ ]++ # Enqueue batch+ emitted_events = [eventbus.emit(event) for event in events]+ results = await asyncio.gather(*[event.result() for event in emitted_events])++ # Check all processed+ assert len(results) == 3+ for result in results:+ assert result.completed_at is not None+ assert '_default_log_handler' in result.results++ async def test_empty_batch(self, eventbus):+ """Test empty batch handling"""+ empty_events = []+ emitted_events = [eventbus.emit(event) for event in empty_events]+ results = await asyncio.gather(*[event.result() for event in emitted_events])+ assert results == []+++class TestWriteAheadLog:+ """Test write-ahead logging functionality"""++ async def test_write_ahead_log_captures_all_events(self, eventbus):+ """Test that all events are captured in write-ahead log"""+ # Emit several events+ events = []+ for i in range(5):+ event = UserActionEvent(action=f'action_{i}', user_id='u1')+ events.append(eventbus.emit(event))++ await eventbus.wait_until_idle()++ # Check write-ahead log+ log = eventbus.event_history.copy()+ assert len(log) == 5+ for i, event in enumerate(log):+ assert event.action == f'action_{i}'++ # Check event state properties+ completed = eventbus.events_completed+ pending = eventbus.events_queued+ processing = eventbus.events_started+ assert len(completed) + len(pending) + len(processing) == len(log)+ assert len(completed) == 5 # All events should be completed+ assert len(pending) == 0 # No events should be pending+ assert len(processing) == 0 # No events should be processing+++class TestSerialization:+ """Test event serialization functionality"""++ async def test_wal_functionality_replaces_serialize(self, eventbus, tmp_path):+ """Test that WAL persistence replaces old serialize functionality"""+ # WAL persistence is now tested in TestWALPersistence+ # This test confirms the old serialize functionality is no longer needed+ assert hasattr(eventbus, '_default_wal_handler')+ assert not hasattr(eventbus, 'serialize_events_to_file')+++class TestEventCompletion:+ """Test event completion tracking"""++ async def test_wait_for_completion(self, eventbus):+ """Test waiting for event completion"""+ completion_order = []++ async def slow_handler(event: BaseEvent) -> str:+ await asyncio.sleep(0.1)+ completion_order.append('handler_done')+ return 'done'++ eventbus.on('UserActionEvent', slow_handler)++ # Enqueue without waiting+ event = eventbus.emit(UserActionEvent(action='test', user_id='u1'))+ completion_order.append('enqueue_done')++ # Wait for completion+ await event.wait_for_completion()+ completion_order.append('wait_done')++ # Check order+ assert completion_order == ['enqueue_done', 'handler_done', 'wait_done']+ assert event.completed_at is not None++ def test_completion_event_not_in_async_context(self):+ """Test that completion event is None when not in async context"""+ # This test must run in sync context+ import threading++ result = {}++ def sync_test():+ # Create event outside async context+ event = UserActionEvent(action='test', user_id='u1')+ result['has_completion_event'] = event._completion_event is not None++ thread = threading.Thread(target=sync_test)+ thread.start()+ thread.join()++ # In sync context, completion event should be None+ assert not result.get('has_completion_event', True)+++class TestEdgeCases:+ """Test edge cases and special scenarios"""++ async def test_stop_with_pending_events(self, mock_agent):+ """Test stopping event bus with events still in queue"""+ bus = EventBus()++ # Add a slow handler+ async def slow_handler(event: BaseEvent) -> str:+ await asyncio.sleep(1)+ return 'done'++ bus.on('*', slow_handler)++ # Enqueue events but don't wait+ for i in range(5):+ bus.emit(UserActionEvent(action=f'action_{i}', user_id='u1'))++ # Stop immediately+ await bus.stop()++ # Bus should stop even with pending events+ assert not bus._is_running++ async def test_event_with_complex_data(self, eventbus):+ """Test events with complex nested data"""+ complex_data = {+ 'nested': {+ 'list': [1, 2, {'inner': 'value'}],+ 'datetime': datetime.utcnow(),+ 'none': None,+ }+ }++ event = SystemEventModel(event_name='complex', details=complex_data)++ result = await eventbus.emit(event).result()++ # Check data preserved+ assert result.details['nested']['list'][2]['inner'] == 'value'++ async def test_concurrent_emit_calls(self, eventbus):+ """Test multiple concurrent emit calls"""+ # Create many events concurrently+ tasks = []+ for i in range(100):+ event = UserActionEvent(action=f'concurrent_{i}', user_id='u1')+ # Emit returns the event synchronously, but we need to wait for completion+ emitted_event = eventbus.emit(event)+ tasks.append(emitted_event.wait_for_completion())++ # Wait for all events to complete+ await asyncio.gather(*tasks)++ # Wait for processing+ await eventbus.wait_until_idle()++ # Check all events in log+ log = eventbus.event_history.copy()+ assert len(log) == 100++ async def test_rapid_fire_events_maintain_order(self, eventbus):+ """Test that rapidly emitted events maintain strict FIFO order"""+ collected_orders = []++ async def handler(event: UserActionEvent):+ # Extract order from metadata+ order = event.metadata.get('order', -1)+ collected_orders.append(order)+ return f'handled_{order}'++ eventbus.on('UserActionEvent', handler)++ # Emit 100 events as fast as possible+ num_events = 100+ for i in range(num_events):+ event = UserActionEvent(action=f'rapid_{i}', user_id='u1', metadata={'order': i})+ eventbus.emit(event)++ # Wait for all events to process+ await eventbus.wait_until_idle()++ # Verify exact FIFO order+ assert collected_orders == list(range(num_events)), f'Events processed out of order: {collected_orders[:10]}...'++ async def test_mixed_delay_handlers_maintain_order(self, eventbus):+ """Test that events with different handler delays still maintain FIFO order"""+ collected_orders = []+ handler_start_times = []++ async def handler(event: UserActionEvent):+ order = event.metadata.get('order', -1)+ handler_start_times.append((order, asyncio.get_event_loop().time()))+ # Simulate varying processing times+ if order % 2 == 0:+ await asyncio.sleep(0.05) # Even events take longer+ else:+ await asyncio.sleep(0.01) # Odd events are quick+ collected_orders.append(order)+ return f'handled_{order}'++ eventbus.on('UserActionEvent', handler)++ # Emit events+ num_events = 20+ for i in range(num_events):+ event = UserActionEvent(action=f'mixed_{i}', user_id='u1', metadata={'order': i})+ eventbus.emit(event)++ # Wait for all events to process+ await eventbus.wait_until_idle()++ # Verify exact FIFO order despite different processing times+ assert collected_orders == list(range(num_events)), f'Events processed out of order: {collected_orders}'++ # Verify handler start times are in order (events are dequeued in FIFO order)+ for i in range(1, len(handler_start_times)):+ prev_order, prev_time = handler_start_times[i - 1]+ curr_order, curr_time = handler_start_times[i]+ assert curr_time >= prev_time, f'Event {curr_order} started before event {prev_order}'++ async def test_all_handlers_complete_before_next_event(self, eventbus):+ """Test that all handlers for an event complete before the next event is processed"""+ event_processing_log = []++ async def handler1(event: UserActionEvent):+ order = event.metadata.get('order', -1)+ event_processing_log.append(f'h1_start_{order}')+ await asyncio.sleep(0.05)+ event_processing_log.append(f'h1_end_{order}')+ return 'handler1'++ async def handler2(event: UserActionEvent):+ order = event.metadata.get('order', -1)+ event_processing_log.append(f'h2_start_{order}')+ await asyncio.sleep(0.03)+ event_processing_log.append(f'h2_end_{order}')+ return 'handler2'++ async def handler3(event: UserActionEvent):+ order = event.metadata.get('order', -1)+ event_processing_log.append(f'h3_start_{order}')+ await asyncio.sleep(0.01)+ event_processing_log.append(f'h3_end_{order}')+ return 'handler3'++ # Register all handlers+ eventbus.on('UserActionEvent', handler1)+ eventbus.on('UserActionEvent', handler2)+ eventbus.on('UserActionEvent', handler3)++ # Emit 3 events+ for i in range(3):+ event = UserActionEvent(action=f'multi_{i}', user_id='u1', metadata={'order': i})+ eventbus.emit(event)++ # Wait for all events to process+ await eventbus.wait_until_idle()++ # Verify that all handlers for event 0 complete before any handler for event 1 starts+ event0_starts = [log for log in event_processing_log if log.endswith('_start_0')]+ event0_ends = [log for log in event_processing_log if log.endswith('_end_0')]+ event1_starts = [log for log in event_processing_log if log.endswith('_start_1')]++ # All starts for event 0 should happen before all starts for event 1+ event0_last_start_idx = max(event_processing_log.index(s) for s in event0_starts)+ event1_first_start_idx = min(event_processing_log.index(s) for s in event1_starts)++ # All ends for event 0 should happen before any start for event 1+ event0_last_end_idx = max(event_processing_log.index(e) for e in event0_ends)++ assert event0_last_start_idx < event1_first_start_idx, 'Event 1 handlers started before event 0 handlers'+ assert event0_last_end_idx < event1_first_start_idx, 'Event 1 started before event 0 completed'++ async def test_event_completion_order_matches_emission_order(self, eventbus):+ """Test that event completion tracking maintains FIFO order"""+ completion_order = []++ async def handler(event: UserActionEvent):+ order = event.metadata.get('order', -1)+ # Variable delays to test completion tracking+ delay = 0.1 - (order * 0.01) # Later events process faster+ await asyncio.sleep(delay)+ return f'handled_{order}'++ eventbus.on('UserActionEvent', handler)++ # Emit events and track their completion+ events = []+ for i in range(10):+ event = UserActionEvent(action=f'track_{i}', user_id='u1', metadata={'order': i})+ eventbus.emit(event)+ events.append(event)++ # Wait for each event to complete and track order+ async def wait_and_track(event, order):+ await event.wait_for_completion()+ completion_order.append(order)++ # Wait for all completions in parallel+ await asyncio.gather(*[wait_and_track(e, e.metadata['order']) for e in events])++ # Verify completion order matches emission order+ assert completion_order == list(range(10)), f'Events completed out of order: {completion_order}'++ async def test_concurrent_emit_from_multiple_tasks_maintains_order(self, eventbus):+ """Test that concurrent emits from multiple tasks maintain order within each task"""+ collected_events = []++ async def handler(event: UserActionEvent):+ order = event.metadata.get('order', -1)+ task_id = event.metadata.get('task_id', 'unknown')+ collected_events.append((order, task_id))+ return 'handled'++ eventbus.on('UserActionEvent', handler)++ # Create multiple tasks that emit events concurrently+ async def emit_task(task_id: str, start: int, count: int):+ for i in range(count):+ event = UserActionEvent(+ action=f'task_{task_id}_{i}', user_id='u1', metadata={'order': start + i, 'task_id': task_id}+ )+ eventbus.emit(event)+ # Small delay to interleave with other tasks+ await asyncio.sleep(0.001)++ # Start 3 tasks concurrently+ await asyncio.gather(emit_task('task1', 0, 5), emit_task('task2', 100, 5), emit_task('task3', 200, 5))++ # Wait for processing+ await eventbus.wait_until_idle()++ # Verify that events from each task maintain their relative order+ task1_events = [(order, task) for order, task in collected_events if task == 'task1']+ task2_events = [(order, task) for order, task in collected_events if task == 'task2']+ task3_events = [(order, task) for order, task in collected_events if task == 'task3']++ # Check order within each task+ assert [e[0] for e in task1_events] == list(range(0, 5))+ assert [e[0] for e in task2_events] == list(range(100, 105))+ assert [e[0] for e in task3_events] == list(range(200, 205))+++class TestEventTypeOverride:+ """Test that Event subclasses properly override event_type"""++ async def test_event_subclass_type(self, eventbus):+ """Test that event subclasses maintain their type"""+ from browser_use.agent.cloud_events import CreateAgentTaskEvent++ # Create a specific event type+ event = CreateAgentTaskEvent(+ user_id='test_user', agent_session_id='12345678-1234-5678-1234-567812345678', llm_model='test-model', task='test task'+ )++ # Enqueue it+ result = eventbus.emit(event)++ # Check type is preserved - should be class name+ assert result.event_type == 'CreateAgentTask'+ assert isinstance(result, BaseEvent)++ async def test_event_schema_auto_generation(self, eventbus):+ """Test that event_schema is automatically set with the correct format"""+ from browser_use.agent.cloud_events import CreateAgentSessionEvent+ from browser_use.utils import get_browser_use_version++ # Get the expected version+ version = get_browser_use_version()++ # Test with BaseEvent+ base_event = BaseEvent(event_type='TestEvent')+ assert base_event.event_schema is not None+ expected_base_schema = f'browser_use.eventbus.models.BaseEvent@{version}'+ assert base_event.event_schema == expected_base_schema++ # Test with CreateAgentTaskEvent+ task_event = CreateAgentTaskEvent(+ user_id='test_user', agent_session_id='12345678-1234-5678-1234-567812345678', llm_model='test-model', task='test task'+ )+ expected_task_schema = f'browser_use.agent.cloud_events.CreateAgentTaskEvent@{version}'+ assert task_event.event_schema == expected_task_schema++ # Test with CreateAgentSessionEvent+ session_event = CreateAgentSessionEvent(+ user_id='test_user',+ browser_session_id='test_session',+ browser_session_live_url='http://example.com',+ browser_session_cdp_url='ws://example.com',+ )+ expected_session_schema = f'browser_use.agent.cloud_events.CreateAgentSessionEvent@{version}'+ assert session_event.event_schema == expected_session_schema++ # Test custom event from this test file+ user_event = UserActionEvent(action='login', user_id='user123')+ expected_user_schema = f'test_eventbus.UserActionEvent@{version}'+ assert user_event.event_schema == expected_user_schema++ # Emit and check schema is preserved+ result = eventbus.emit(task_event)+ assert result.event_schema == expected_task_schema+++class TestWALPersistence:+ """Test automatic WAL persistence functionality"""++ async def test_wal_persistence_handler(self, tmp_path):+ """Test that events are automatically persisted to WAL file"""+ # Create event bus with WAL path+ wal_path = tmp_path / 'test_events.jsonl'+ bus = EventBus(name='TestBus', wal_path=wal_path)++ try:+ # Emit some events+ events = []+ for i in range(3):+ event = UserActionEvent(action=f'action_{i}', user_id=f'user_{i}')+ emitted_event = bus.emit(event)+ result = await emitted_event.result()+ events.append(result)++ # Wait for processing+ await bus.wait_until_idle()++ # Check WAL file exists+ assert wal_path.exists()++ # Read and verify JSONL content+ lines = wal_path.read_text().strip().split('\n')+ assert len(lines) == 3++ # Parse each line as JSON+ for i, line in enumerate(lines):+ data = json.loads(line)+ assert data['event_type'] == 'UserActionEvent'+ assert data['action'] == f'action_{i}'+ assert data['user_id'] == f'user_{i}'+ # Check that datetime fields are properly serialized+ assert isinstance(data['queued_at'], str)+ assert isinstance(data['completed_at'], str)+ # Should be parseable as ISO format+ datetime.fromisoformat(data['queued_at'])+ datetime.fromisoformat(data['completed_at'])++ finally:+ await bus.stop()++ async def test_wal_persistence_creates_parent_dir(self, tmp_path):+ """Test that WAL persistence creates parent directories"""+ # Use a nested path that doesn't exist+ wal_path = tmp_path / 'nested' / 'dirs' / 'events.jsonl'+ assert not wal_path.parent.exists()++ # Create event bus+ bus = EventBus(name='TestBus', wal_path=wal_path)++ # Parent directory should be created+ assert wal_path.parent.exists()+ try:+ # Emit an event+ await bus.emit(UserActionEvent(action='test', user_id='u1')).result()++ # Wait for WAL persistence to complete+ await bus.wait_until_idle()++ # Check file was created+ assert wal_path.exists()+ finally:+ await bus.stop()++ async def test_wal_persistence_skips_incomplete_events(self, tmp_path):+ """Test that WAL persistence only writes completed events"""+ wal_path = tmp_path / 'incomplete_events.jsonl'+ bus = EventBus(name='TestBus', wal_path=wal_path)++ try:+ # Add a slow handler that will delay completion+ async def slow_handler(event: BaseEvent) -> str:+ await asyncio.sleep(0.1)+ return 'slow'++ bus.on('UserActionEvent', slow_handler)++ # Emit event without waiting+ event = bus.emit(UserActionEvent(action='test', user_id='u1'))++ # Check file doesn't exist yet (event not completed)+ assert not wal_path.exists()++ # Wait for completion+ await event.wait_for_completion()+ await bus.wait_until_idle()++ # Now file should exist with completed event+ assert wal_path.exists()+ lines = wal_path.read_text().strip().split('\n')+ assert len(lines) == 1+ data = json.loads(lines[0])+ assert data['event_type'] == 'UserActionEvent'+ assert 'completed_at' in data++ finally:+ await bus.stop()+++if __name__ == '__main__':+ pytest.main([__file__, '-v'])