Skip to content

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

switch to external bubus lib

Nick Sweeting474476f0ae8f
diff --git a/browser_use/agent/cloud_events.py b/browser_use/agent/cloud_events.py
index 457b4ea02..d703839f4 100644
--- a/browser_use/agent/cloud_events.py
+++ b/browser_use/agent/cloud_events.py
@@ -1,10 +1,9 @@
from datetime import datetime, timezone
+from bubus import BaseEvent
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
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 1157f3847..b16735e90 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -26,6 +26,8 @@ from browser_use.browser.session import DEFAULT_BROWSER_PROFILE
load_dotenv()
+# from lmnr.sdk.decorators import observe
+from bubus import EventBus
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import (
BaseMessage,
@@ -60,13 +62,10 @@ from browser_use.agent.views import (
ToolCallingMethod,
)
from browser_use.browser import BrowserProfile, BrowserSession
-
-# from lmnr.sdk.decorators import observe
from browser_use.browser.views import BrowserStateSummary
from browser_use.controller.registry.views import ActionModel
from browser_use.controller.service import Controller
from browser_use.dom.history_tree_processor.service import DOMHistoryElement, HistoryTreeProcessor
-from browser_use.eventbus import EventBus
from browser_use.exceptions import LLMException
from browser_use.telemetry.service import ProductTelemetry
from browser_use.telemetry.views import AgentTelemetryEvent
diff --git a/browser_use/eventbus/__init__.py b/browser_use/eventbus/__init__.py
deleted file mode 100644
index 4a52c23d1..000000000
--- a/browser_use/eventbus/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""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.py
deleted file mode 100644
index 9e2595639..000000000
--- a/browser_use/eventbus/models.py
+++ /dev/null
@@ -1,337 +0,0 @@
-import asyncio
-import logging
-from collections.abc import Awaitable, Callable
-from datetime import UTC, datetime
-from typing import TYPE_CHECKING, Annotated, Any, Self
-from uuid import UUID
-
-from pydantic import AfterValidator, BaseModel, ConfigDict, Field, PrivateAttr
-from uuid_extensions import uuid7str
-
-from browser_use.utils import get_browser_use_version
-
-if TYPE_CHECKING:
- from browser_use.eventbus.service import EventBus
-
-
-logger = logging.getLogger(__name__)
-
-
-def is_valid_event_name(s: str) -> bool:
- assert str(s).isidentifier() and not str(s).startswith('_'), f'Invalid event name: {s}'
- return str(s)
-
-
-def is_valid_python_id(s: str) -> bool:
- assert str(s).isdigit(), f'Invalid Python ID: {s}'
- return str(s)
-
-
-UUIDStr = Annotated[str, AfterValidator(lambda s: str(UUID(s)))]
-PythonIdStr = Annotated[str, AfterValidator(is_valid_python_id)]
-PythonIdentifierStr = Annotated[str, AfterValidator(is_valid_event_name)]
-EventHandler = Callable[['BaseEvent'], Any] | Callable[['BaseEvent'], Awaitable[Any]]
-
-
-class BaseEvent(BaseModel):
- """
- The base model used for all Events that flow through the EventBus system.
- """
-
- model_config = ConfigDict(arbitrary_types_allowed=True, validate_assignment=True, validate_default=True)
-
- event_type: PythonIdentifierStr
- event_schema: str | None = Field(default=None, description='Event schema version in format ClassName@version', max_length=100)
- event_timeout: float | None = Field(default=60.0, description='Timeout in seconds for event to complete')
-
- # Runtime metadata
- event_id: UUIDStr = Field(default_factory=uuid7str, max_length=36)
- event_path: list[PythonIdentifierStr] = Field(default_factory=list, description='Path tracking for event routing')
- event_parent_id: UUIDStr | None = Field(
- default=None, description='ID of the parent event that triggered this event', max_length=36
- )
-
- # Completion tracking fields
- event_created_at: datetime = Field(
- default_factory=lambda: datetime.now(UTC),
- description='Timestamp when event was first dispatched to an EventBus aka marked pending',
- )
-
- event_results: dict[PythonIdStr, 'EventResult'] = Field(
- default_factory=dict, exclude=True
- ) # Results indexed by str(id(handler_func))
-
- # Completion signal
- _event_completed: asyncio.Event | None = PrivateAttr(default=None)
- _event_processed_at: datetime | None = PrivateAttr(default=None)
-
- def __str__(self) -> str:
- icon = (
- '⏳'
- if self.event_status == 'pending'
- else '✅'
- if self.event_status == 'completed'
- else '❌'
- if self.event_status == 'error'
- else '🏃'
- )
- return f'{self.__class__.__name__}#{self.event_id[-4:]}{icon}{">".join(self.event_path[1:])})'
-
- def _log_safe_summary(self) -> str:
- """only event metadata without contents, avoid potentially sensitive event contents in logs"""
- return {k: v for k, v in self.model_dump(mode='json').items() if k.startswith('event_') and 'results' not in k}
-
- def __await__(self) -> Self:
- """Wait for event to complete and return self"""
-
- async def wait_for_handlers_to_complete_then_return_event():
- assert self.event_completed is not None
- try:
- await asyncio.wait_for(self.event_completed.wait(), timeout=self.event_timeout)
- except TimeoutError as err:
- raise RuntimeError(
- f'{self} waiting for results timed out after {self.event_timeout}s (being processed by {len(self.event_results)} handlers)'
- ) from err
- return self
-
- return wait_for_handlers_to_complete_then_return_event().__await__()
-
- def __hash__(self) -> int:
- """Make events hashable using their unique event_id"""
- return hash(self.event_id)
-
- @property
- def event_completed(self) -> asyncio.Event | None:
- """Lazily create asyncio.Event when accessed"""
- if self._event_completed is None:
- try:
- asyncio.get_running_loop()
- self._event_completed = asyncio.Event()
- except RuntimeError:
- pass # Keep it None if no event loop
- return self._event_completed
-
- @property
- def event_started_at(self) -> datetime | None:
- """Timestamp when event first started being processed by any handler"""
- started_times = [result.started_at for result in self.event_results.values() if result.started_at is not None]
- # If no handlers but event was processed, use the processed timestamp
- if not started_times and self._event_processed_at:
- return self._event_processed_at
- return min(started_times) if started_times else None
-
- @property
- def event_completed_at(self) -> datetime | None:
- """Timestamp when event was completed by all handlers"""
- # If no handlers at all but event was processed, use the processed timestamp
- if not self.event_results and self._event_processed_at:
- return self._event_processed_at
-
- # All handlers must be done (completed or error)
- all_done = all(result.status in ('completed', 'error') for result in self.event_results.values())
- if not all_done:
- return None
-
- # Return the latest completion time
- completed_times = [result.completed_at for result in self.event_results.values() if result.completed_at is not None]
- return max(completed_times) if completed_times else self._event_processed_at
-
- @property
- def event_status(self) -> str:
- return 'completed' if self.event_completed_at else 'started' if self.event_started_at else 'pending'
-
- def model_post_init(self, __context: Any) -> None:
- """Append the library version number to the event schema so we know what version was used to create any JSON dump"""
- if self.event_schema is None:
- version = get_browser_use_version()
- self.event_schema = f'{self.__class__.__module__}.{self.__class__.__qualname__}@{version}'
-
- def event_result_update(
- self, handler: EventHandler | None = None, eventbus: 'EventBus | None' = None, **kwargs
- ) -> 'EventResult':
- """Create or update an EventResult for a handler"""
- handler_id: PythonIdStr = str(id(handler))
- eventbus = eventbus or (handler and hasattr(handler, '__self__') and handler.__self__) or None
- eventbus_id: PythonIdStr = str(id(eventbus))
-
- # Get or create EventResult
- if handler_id not in self.event_results:
- self.event_results[handler_id] = EventResult(
- handler_id=handler_id,
- handler_name=handler and handler.__name__ or str(handler),
- eventbus_id=eventbus_id,
- eventbus_name=eventbus and eventbus.name or str(eventbus),
- event_parent_id=self.event_id,
- status=kwargs.get('status', 'pending'),
- timeout=self.event_timeout,
- )
- logger.debug(f'Created EventResult for handler {handler_id}: {handler.__name__}')
-
- # Update the EventResult with provided kwargs
- self.event_results[handler_id].update(**kwargs)
- logger.debug(
- f'Updated EventResult for handler {handler_id}: status={self.event_results[handler_id].status}, total_results={len(self.event_results)}'
- )
- # Don't mark complete here - let the EventBus do it after all handlers are done
- return self.event_results[handler_id]
-
- def _mark_complete_if_all_handlers_completed(self) -> None:
- """Check if all handlers are done and signal completion"""
- if self.event_completed and not self.event_completed.is_set():
- # If there are no results at all, the event is complete
- if not self.event_results:
- self._event_processed_at = datetime.now(UTC)
- self.event_completed.set()
- return
-
- # Otherwise check if all results are done
- all_done = all(result.status in ('completed', 'error') for result in self.event_results.values())
- if all_done:
- self._event_processed_at = datetime.now(UTC)
- self.event_completed.set()
-
- async def event_results_by_handler_id(self, timeout: float | None = None) -> dict[PythonIdStr, Any]:
- """Get all results by handler id"""
- try:
- await asyncio.wait_for(self.event_completed.wait(), timeout=timeout or self.event_timeout)
- except TimeoutError:
- pass
- return {handler_id: await event_result for handler_id, event_result in self.event_results.items()}
-
- async def event_results_flat_dict(self, timeout: float | None = None) -> dict[Any, Any]:
- """Merge all dict results into single dict"""
-
- try:
- await asyncio.wait_for(self.event_completed.wait(), timeout=timeout or self.event_timeout)
- except TimeoutError:
- pass
-
- merged_results: dict[Any, Any] = {}
- for event_result in self.event_results.values():
- if event_result.status == 'completed' and event_result.result is not None:
- if not event_result.result: # skip if result is {} or None
- continue
- if isinstance(event_result.result, BaseEvent): # skip if result is another Event
- continue
- if not isinstance(event_result.result, dict):
- # raise TypeError(f"Handler '{event_result.handler_name}' returned {type(event_result.result).__name__} instead of dict")
- continue
- merged_results.update(event_result.result) # update the merged dict with the contents of the result dict
- return merged_results
-
- async def event_results_flat_list(self, timeout: float | None = None) -> list[Any]:
- """Merge all list results into single list"""
-
- try:
- await asyncio.wait_for(self.event_completed.wait(), timeout=timeout or self.event_timeout)
- except TimeoutError:
- pass
-
- merged_results = []
- for event_result in self.event_results.values():
- if event_result.status == 'completed' and event_result.result is not None:
- if isinstance(event_result.result, list):
- merged_results.extend(event_result.result) # append the contents of the list to the merged list
- elif isinstance(event_result.result, BaseEvent): # skip if result is another Event
- continue
- else:
- merged_results.append(event_result.result) # append individual item to the merged list
- return merged_results
-
- async def event_result(self, timeout: float | None = None) -> Any:
- results = await self.event_results_flat_list(timeout=timeout)
- return results[0] if results else None
-
-
-# PSA: All BaseEvent buil-in attrs and methods must be prefixed with "event_" in order to avoid clashing with data contents (which share a namespace with the metadata)
-# This is the same approach Pydantic uses for their special `model_*` attrs (and BaseEvent is also a pydantic model, so model_ prefixes are reserved too)
-# resist the urge to nest the event data in an inner object unless absolutely necessary, flat simplifies most of the code and makes it easier to read JSON logs with less nesting
-pydantic_builtin_attrs = dir(BaseModel)
-event_builtin_attrs = {key for key in dir(BaseEvent) if key.startswith('event_')}
-attr_name_allowed = lambda key: key in pydantic_builtin_attrs or key in event_builtin_attrs or key.startswith('_')
-illegal_attrs = {key for key in dir(BaseEvent) if not attr_name_allowed(key)}
-assert not illegal_attrs, (
- f'All BaseEvent attrs and methods must be prefixed with "event_" in order to avoid clashing with BaseEvent subclass fields used to store event contents (which share a namespace with the event_ metadata). not allowed: {illegal_attrs}'
-)
-
-
-class EventResult(BaseModel):
- """Individual result from a single handler"""
-
- id: str = Field(default_factory=uuid7str)
- handler_id: str
- handler_name: str
- eventbus_id: str
- eventbus_name: str
- timeout: float = 60.0
- status: str = 'pending' # pending, started, completed, error
- result: Any = None
- error: str | None = None
- started_at: datetime | None = None
- completed_at: datetime | None = None
- event_parent_id: str | None = None
-
- # Completion signal
- _completed: asyncio.Event | None = PrivateAttr(default=None)
-
- @property
- def completed(self) -> asyncio.Event | None:
- """Lazily create asyncio.Event when accessed"""
- if self._completed is None:
- try:
- asyncio.get_running_loop()
- self._completed = asyncio.Event()
- except RuntimeError:
- pass # Keep it None if no event loop
- return self._completed
-
- # _event: BaseEvent | None = PrivateAttr(default=None) # in a db we'd store a foreign key to the event
-
- model_config = {'arbitrary_types_allowed': True}
-
- def __str__(self) -> str:
- handler_qualname = f'{self.eventbus_name}.{self.handler_name}'
- return f'{handler_qualname}() -> {self.result or self.error or "..."} ({self.status})'
-
- def __repr__(self) -> str:
- icon = '🏃' if self.status == 'pending' else '✅' if self.status == 'completed' else '❌'
- return f'{self.handler_name}#{self.handler_id[-4:]}(e) {icon}'
-
- def __await__(self):
- """Wait for this result to complete and return the result or raise error"""
-
- async def wait_for_handler_to_complete_and_return_result():
- try:
- await asyncio.wait_for(self.completed.wait(), timeout=self.timeout)
- except TimeoutError as err:
- raise RuntimeError(f'Handler {self.handler_name} timed out after {self.event_timeout}s') from err
-
- if self.status == 'error' and self.error:
- raise RuntimeError(f'Handler {self.handler_name} failed: {self.error}')
-
- return self.result
-
- return wait_for_handler_to_complete_and_return_result().__await__()
-
- def update(self, **kwargs) -> None:
- """Update the EventResult with provided kwargs"""
- if 'result' in kwargs:
- self.result = kwargs['result']
- self.status = 'completed'
- self.completed_at = datetime.now(UTC)
- if self.completed:
- self.completed.set()
- elif 'error' in kwargs:
- self.error = kwargs['error']
- self.status = 'error'
- self.completed_at = datetime.now(UTC)
- if self.completed:
- self.completed.set()
- elif 'status' in kwargs:
- self.status = kwargs['status']
- if self.status == 'started' and not self.started_at:
- self.started_at = datetime.now(UTC)
-
-
-# Resolve forward references
-BaseEvent.model_rebuild()
diff --git a/browser_use/eventbus/service.py b/browser_use/eventbus/service.py
deleted file mode 100644
index 9443a5df7..000000000
--- a/browser_use/eventbus/service.py
+++ /dev/null
@@ -1,606 +0,0 @@
-import asyncio
-import inspect
-import logging
-import warnings
-from collections import defaultdict
-from collections.abc import Callable
-from contextvars import ContextVar
-from pathlib import Path
-from typing import Any, Literal
-
-import anyio
-from pydantic import BaseModel
-from uuid_extensions import uuid7str
-
-from browser_use.eventbus.models import BaseEvent, EventHandler, PythonIdentifierStr, PythonIdStr, UUIDStr
-from browser_use.utils import _log_pretty_path
-
-logger = logging.getLogger(__name__)
-
-
-# Context variable to track the current event being processed (for setting event_parent_id from inside a child event)
-_current_event_context: ContextVar[BaseEvent | None] = ContextVar('current_event', default=None)
-
-
-class EventBus:
- """
- Async event bus with write-ahead logging and guaranteed FIFO processing.
-
- Features:
- - Enqueue events synchronously, await their results using 'await Event()'
- - FIFP Write-ahead logging with UUIDs and timestamps,
- - Serial event processing, parallel handler execution per event
- """
-
- # Class Attributes
- name: PythonIdentifierStr
- parallel_handlers: bool = False
- wal_path: Path | None = None
- handlers: dict[PythonIdStr, list[EventHandler]] # collected by .on(<event_type>, <handler>)
-
- # Runtime State
- id: UUIDStr
- event_queue: asyncio.Queue[BaseEvent] | None
- event_history: dict[UUIDStr, BaseEvent] # collected by .dispatch(<event>)
-
- _is_running: bool = False
- _runloop_task: asyncio.Task | None = None
- _runloop_lock: asyncio.Lock | None = None
- _on_idle: asyncio.Event | None = None
-
- def __init__(
- self, name: PythonIdentifierStr | None = None, wal_path: Path | str | None = None, parallel_handlers: bool = False
- ):
- self.id = uuid7str()
- self.name = name or f'EventBus_{self.id[-8:]}'
- assert self.name.isidentifier(), f'EventBus name must be a unique identifier string, got: {self.name}'
- self.event_queue = None
- self.event_history = {}
- self.handlers = defaultdict(list)
- self.parallel_handlers = parallel_handlers
- self.wal_path = Path(wal_path) if wal_path else None
- self._runloop_lock = None
- self._on_idle = None
-
- # Instead of registering as normal event handlers,
- # these special handlers are just called manually at the end of _run_loop_step
- # self.on('*', self._default_log_handler)
- # self.on('*', self._default_wal_handler)
-
- def __del__(self):
- """Auto-cleanup on garbage collection"""
- if self._is_running:
- self._is_running = False
-
- if self._runloop_task and not self._runloop_task.done():
- try:
- self._runloop_task.cancel()
- except RuntimeError:
- pass # No event loop - that's fine
-
- # Suppress the warning by accessing internal asyncio attributes
- # This prevents "Task was destroyed but it is pending" warnings
- if hasattr(self._runloop_task, '_log_destroy_pending'):
- self._runloop_task._log_destroy_pending = False
-
- # Also try to get the exception to mark it as handled
- try:
- self._runloop_task.exception()
- except (asyncio.CancelledError, asyncio.InvalidStateError):
- pass # Expected for cancelled or pending tasks
- except RuntimeError:
- pass # No event loop - that's fine
-
- def __str__(self) -> str:
- icon = '🟢' if self._is_running else '🔴'
- return f'{self.name}{icon}(⏳ {len(self.events_pending or [])} | ▶️ {len(self.events_started or [])} | ✅ {len(self.events_completed or [])} ➡️ {len(self.handlers)} 👂)'
-
- def __repr__(self) -> str:
- return str(self)
-
- @property
- def events_pending(self) -> list[BaseEvent]:
- """Get events that haven't started processing yet (does not include events that have not even finished dispatching yet in self.event_queue)"""
- return [
- event for event in self.event_history.values() if event.event_started_at is None and event.event_completed_at is None
- ]
-
- @property
- def events_started(self) -> list[BaseEvent]:
- """Get events currently being processed"""
- return [event for event in self.event_history.values() if event.event_started_at and not event.event_completed_at]
-
- @property
- def events_completed(self) -> list[BaseEvent]:
- """Get events that have completed processing"""
- return [event for event in self.event_history.values() if event.event_completed_at is not None]
-
- def on(self, event_pattern: PythonIdentifierStr | Literal['*'] | type[BaseModel], handler: EventHandler) -> None:
- """
- Subscribe to events matching a pattern, event type name, or event model class.
- Use event_pattern='*' to subscribe to all events. Handler can be sync or async function or method.
-
- Examples:
- eventbus.on('TaskStartedEvent', handler) # Specific event type
- eventbus.on(TaskStartedEvent, handler) # Event model class
- eventbus.on('*', handler) # Subscribe to all events
- eventbus.on('*', other_eventbus.dispatch) # Forward all events to another EventBus
-
- Note: When forwarding events between buses, all handler results are automatically
- flattened into the original event's results, so EventResults sees all handlers
- from all buses as a single flat collection.
- """
- # Determine event key
- if event_pattern == '*':
- event_key = '*'
- elif isinstance(event_pattern, type) and issubclass(event_pattern, BaseModel):
- event_key = event_pattern.__name__
- else:
- event_key = str(event_pattern)
-
- # Check for duplicate handler names
- if hasattr(handler, '__self__'):
- handler_name = f'{handler.__self__}.{handler.__name__}()'
- else:
- handler_name = handler.__name__
- existing_names = [h.__name__ for h in self.handlers.get(event_key, [])]
-
- if handler_name in existing_names:
- warnings.warn(
- f"⚠️ Handler '{handler_name}' already registered for event '{event_key}'. "
- f'This may cause ambiguous results when using name-based access. '
- f'Consider using unique function names.',
- UserWarning,
- stacklevel=2,
- )
-
- # Register handler
- self.handlers[event_key].append(handler)
- logger.debug(f'👂 {self}.on({event_key}, {handler_name}) Registered event handler')
-
- def dispatch(self, event: BaseEvent) -> BaseEvent:
- """
- Enqueue an event for processing and immediately return an Event(status='pending') version (synchronous).
- You can then await the Event(status='pending') object to block until its Event(status='completed') versionis ready,
- or you can interact with the unawaited Event(status='pending') before its handlers have finished.
-
- (The first EventBus.dispatch() call will auto-start a bus's async _run_loop() if it's not already running)
-
- >>> completed_event = await eventbus.dispatch(SomeEvent())
- # 1. enqueues the event synchronously
- # 2. returns an awaitable SomeEvent() with pending results in .event_results
- # 3. awaits the SomeEvent() which waits until all pending results are complete and returns the completed SomeEvent()
-
- >>> result_value = await eventbus.dispatch(SomeEvent()).event_result()
- # 1. enqueues the event synchronously
- # 2. returns a pending SomeEvent() with pending results in .event_results
- # 3. awaiting .event_result() waits until all pending results are complete, and returns the raw result value of the first one
- """
- assert event.event_id, 'Missing event.event_id: UUIDStr = uuid7str()'
- assert event.event_created_at, 'Missing event.event_created_at: datetime = datetime.now(UTC)'
- assert event.event_type and event.event_type.isidentifier(), 'Missing event.event_type: str'
- assert event.event_schema and '@' in event.event_schema, 'Missing event.event_schema: str (with @version)'
-
- # Automatically set event_parent_id from context if not already set
- if event.event_parent_id is None:
- current_event = _current_event_context.get()
- if current_event is not None:
- event.event_parent_id = current_event.event_id
-
- # Add this EventBus to the event_path if not already there
- if self.name not in event.event_path:
- # preserve identity of the original object instead of creating a new one, so that the original object remains awaitable to get the result
- # NOT: event = event.model_copy(update={'event_path': event.event_path + [self.name]})
- event.event_path.append(self.name)
- else:
- logger.debug(
- f'⚠️ {self}.dispatch({event.event_type}) - Bus already in path, not adding again. Path: {event.event_path}'
- )
-
- assert event.event_path, 'Missing event.event_path: list[str] (with at least the origin function name recorded in it)'
- assert all(entry.isidentifier() for entry in event.event_path), (
- f'Event.event_path must be a list of valid EventBus names, got: {event.event_path}'
- )
-
- # Add event to history
- self.event_history[event.event_id] = event
- logger.debug(f'📝 {self}.dispatch() adding event {event.event_id} to history')
-
- # Auto-start if needed
- self._start()
-
- # Put event in queue synchronously using put_nowait
- if self.event_queue:
- try:
- self.event_queue.put_nowait(event)
- logger.debug(
- f'🗣️ {self}.dispatch({event.event_type}) ➡️ Event#{event.event_id[-8:]}({event.event_status} #{self.event_queue.qsize()})'
- )
- except asyncio.QueueFull:
- logger.error(
- f'⚠️ {self} Event queue is full! Dropping event and aborting {event.event_type}:\n{event.model_dump_json()}'
- )
- raise # could also block indefinitely until queue has space, but dont drop silently or delete events
- else:
- logger.warning(f'⚠️ {self}.dispatch() called but event_queue is None! Event not queued: {event.event_type}')
-
- # Note: We do NOT pre-create EventResults here anymore.
- # EventResults are created only when handlers actually start executing.
- # This avoids "orphaned" pending results for handlers that get filtered out later.
-
- return event
-
- async def expect(
- self,
- event_type: PythonIdentifierStr | type[BaseModel],
- timeout: float | None = None,
- predicate: Callable[[BaseEvent], bool] | None = None,
- ) -> BaseEvent:
- """
- Wait for an event matching the given type/pattern with optional predicate filter.
-
- Args:
- event_type: The event type string or model class to wait for
- timeout: Maximum time to wait in seconds (None = wait forever)
- predicate: Optional filter function that must return True for the event to match
-
- Returns:
- The first matching event
-
- Raises:
- asyncio.TimeoutError: If timeout is reached before a matching event
-
- Example:
- # Wait for any response event
- response = await eventbus.expect('ResponseEvent', timeout=30)
-
- # Wait for specific response with predicate
- response = await eventbus.expect(
- 'ResponseEvent',
- predicate=lambda e: e.request_id == my_request_id,
- timeout=30
- )
- """
- future: asyncio.Future[BaseEvent] = asyncio.Future()
-
- def notify_expect_handler(event: BaseEvent) -> None:
- """Handler that resolves the future when a matching event is found"""
- if not future.done() and (predicate is None or predicate(event)):
- future.set_result(event)
-
- notify_expect_handler.__name__ = f'{self}.expect({event_type}, predicate={predicate and id(predicate)})@{_log_pretty_path(inspect.currentframe().f_code.co_filename)}:{inspect.currentframe().f_lineno}' # add file and line number to the name
-
- # Register temporary handler
- self.on(event_type, notify_expect_handler)
-
- try:
- # Wait for the future with optional timeout
- return await asyncio.wait_for(future, timeout=timeout)
- finally:
- # Clean up handler
- event_key = event_type.__name__ if isinstance(event_type, type) else str(event_type)
- if event_key in self.handlers and notify_expect_handler in self.handlers[event_key]:
- self.handlers[event_key].remove(notify_expect_handler)
-
- def _start(self) -> None:
- """Start the event bus if not already running"""
- if not self._is_running:
- try:
- loop = asyncio.get_running_loop()
- # Create async objects if needed
- if self.event_queue is None:
- self.event_queue = asyncio.Queue()
- self._runloop_lock = asyncio.Lock()
- self._on_idle = asyncio.Event()
- self._on_idle.clear() # Start in a busy state unless we confirm queue is empty by running _run_loop_step() at least once
- # Create and start the run loop task
- self._runloop_task = loop.create_task(self._run_loop(), name=f'{self}._run_loop')
- self._is_running = True
- except RuntimeError:
- # No event loop - will start when one becomes available
- pass
-
- async def stop(self, timeout: float = 0.0) -> None:
- """Stop the event bus, optionally waiting for events to complete"""
- if not self._is_running:
- return
-
- # Wait for completion if timeout specified
- if timeout:
- try:
- await self.wait_until_idle(timeout=timeout)
- except TimeoutError:
- pass
-
- queue_size = self.event_queue.qsize() if self.event_queue else 0
- if queue_size or self.events_pending or self.events_started:
- logger.debug(
- f'⚠️ {self} stopping with pending events: Pending {len(self.events_pending) + queue_size} | Started {len(self.events_started)} | Completed {len(self.events_completed)}\n'
- f'PENDING={self.events_pending}\nSTARTED={self.events_started}'
- )
-
- # Signal shutdown
- self._is_running = False
-
- # Cancel the run loop task if it exists
- if self._runloop_task and not self._runloop_task.done():
- self._runloop_task.cancel()
- try:
- # Wait for task to finish cancellation
- await asyncio.wait_for(self._runloop_task, timeout=1.0)
- except (asyncio.CancelledError, TimeoutError):
- # Expected - task was cancelled or timed out
- pass
- except Exception as e:
- logger.debug(f'Exception while stopping {self}: {e}')
-
- # Clear references
- self._runloop_task = None
- self._runloop_lock = None
- if self._on_idle:
- self._on_idle.set()
-
- logger.debug(f'🛑 {self} shut down gracefully' if timeout is not None else f'🛑 {self} killed')
-
- async def wait_until_idle(self, timeout: float | None = None) -> None:
- """Wait until the event bus is idle (no events being processed and all handlers completed)"""
-
- self._start()
- assert self._on_idle and self.event_queue, 'EventBus._start() must be called before wait_until_idle() is reached'
-
- # First wait for the queue to be empty
- # Then wait for idle state with timeout
- try:
- await asyncio.wait_for(self.event_queue.join(), timeout=timeout)
- await asyncio.wait_for(self._on_idle.wait(), timeout=timeout)
- except TimeoutError:
- logger.warning(
- f'⌛️ {self} Timeout waiting for event bus to be idle after {timeout}s (processing: {len(self.events_started)})'
- )
-
- async def _run_loop(self) -> None:
- """Main event processing loop"""
- try:
- while self._is_running:
- try:
- _processed_event = await self._run_loop_step()
- except RuntimeError as e:
- # Event loop is closing
- if 'Event loop is closed' in str(e) or 'no running event loop' in str(e):
- break
- else:
- logger.exception(f'❌ {self} Runtime error in event loop: {e}')
- # Continue running even if there's an error
- except Exception as e:
- logger.exception(f'❌ {self} Error in event loop: {type(e).__name__} {e}')
- # Continue running even if there's an error
- except asyncio.CancelledError:
- # Task was cancelled, clean exit
- # logger.debug(f'🛑 {self} Event loop task cancelled')
- pass
- finally:
- await self.stop()
-
- async def _run_loop_step(
- self, event: BaseEvent | None = None, timeout: float | None = None, wait_for_timeout: float = 0.1
- ) -> BaseEvent:
- """Process a single event from the queue"""
-
- assert self._runloop_lock, 'EventBus._start() must be called before _run_loop_step()'
- assert self._on_idle, 'EventBus._start() must be called before _run_loop_step()'
-
- # Wait for next event with timeout to periodically check idle state
- if event is None:
- try:
- event = await asyncio.wait_for(self.event_queue.get(), timeout=wait_for_timeout)
- except TimeoutError:
- if not (self.events_pending or self.events_started or self.event_queue.qsize()):
- logger.debug(f'🛑 {self} idle')
- self._on_idle.set()
- return None
-
- logger.debug(f'🏃 {self}._run_loop_step({event}) STARTING')
-
- # Clear idle state when we get an event
- self._on_idle.clear()
-
- # Process the event
- async with self._runloop_lock:
- # Execute all handlers for this event
- applicable_handlers = self._get_applicable_handlers(event)
- await self._execute_handlers(event, handlers=applicable_handlers, timeout=timeout)
-
- await self._default_log_handler(event)
- await self._default_wal_handler(event)
-
- # Mark event as complete if all handlers are done
- event._mark_complete_if_all_handlers_completed()
-
- # Mark task as done
- self.event_queue.task_done()
-
- logger.debug(f'✅ {self}._run_loop_step({event}) COMPLETE')
- return event
-
- 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 event-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 id->handler mapping
- # Use handler id as key to preserve all handlers even with duplicate names
- filtered_handlers = {}
- for handler in applicable_handlers:
- if self._would_create_loop(event, handler):
- logger.debug(f'⚠️ {self} Skipping {handler.__name__}#{str(id(handler))[-4:]}({event}) to prevent infinite loop')
- continue
- else:
- handler_id = str(id(handler))
- filtered_handlers[handler_id] = handler
-
- return filtered_handlers
-
- async def _execute_handlers(
- self, event: BaseEvent, handlers: dict[PythonIdStr, EventHandler] | None = None, timeout: float | None = None
- ) -> None:
- """Execute all handlers for an event in parallel"""
- applicable_handlers = handlers if (handlers is not None) else self._get_applicable_handlers(event)
- if not applicable_handlers:
- event._mark_complete_if_all_handlers_completed() # mark event completed immediately if it has no handlers
- return
-
- # Execute all handlers in parallel
- if self.parallel_handlers:
- handler_tasks = {}
- for handler_id, handler in applicable_handlers.items():
- task = asyncio.create_task(
- self._execute_sync_or_async_handler(event, handler, timeout=timeout), name=f'{self}.{handler.__name__}'
- )
- handler_tasks[handler_id] = (task, handler)
-
- # Wait for all handlers to complete
- for handler_id, (task, handler) in handler_tasks.items():
- try:
- await task
- except Exception as e:
- # Error already logged and recorded in _execute_sync_or_async_handler
- pass
- else:
- # otherwise, execute handlers serially, wait until each one completes before moving on to the next
- for handler_id, handler in applicable_handlers.items():
- try:
- await self._execute_sync_or_async_handler(event, handler, timeout=timeout)
- except Exception as e:
- # Error already logged and recorded in _execute_sync_or_async_handler
- logger.debug(
- f'❌ {self} Handler {handler.__name__}#{str(id(handler))[-4:]}({event}) failed with {type(e).__name__}: {e}'
- )
- pass
-
- async def _execute_sync_or_async_handler(self, event: BaseEvent, handler: EventHandler, timeout: float | None = None) -> Any:
- """Safely execute a single handler with deadlock detection"""
-
- logger.debug(f' ↳ {self}._execute_handler({event}, handler={handler.__name__}#{str(id(handler))[-4:]})')
-
- # Check if this handler has already been executed for this event
- handler_id = str(id(handler))
- if handler_id in event.event_results:
- existing_result = event.event_results[handler_id]
- if existing_result.started_at is not None:
- raise RuntimeError(
- f'Handler {handler.__name__}#{handler_id[-4:]} has already been executed for event {event.event_id}. '
- f'Previous execution started at {existing_result.started_at}'
- )
-
- # Mark handler as started
- event_result = event.event_result_update(
- handler=handler, eventbus=self, status='started', timeout=timeout or event.event_timeout
- )
-
- # Set the current event in context so child events can reference it
- token = _current_event_context.set(event)
-
- # Create a task to monitor for potential deadlock / slow handlers
- async def deadlock_monitor():
- await asyncio.sleep(15.0)
- logger.warning(
- f'⚠️ {self}.{handler.__name__}() has been running for >15s on event. Possible slow processing or deadlock.\n'
- '(handler could be trying to await its own result or another blocked async task).\n'
- f'{self}.{handler.__name__}({event})'
- )
-
- monitor_task = asyncio.create_task(deadlock_monitor(), name=f'{self}.deadlock_monitor.{handler.__name__}')
-
- try:
- if inspect.iscoroutinefunction(handler):
- result = await asyncio.wait_for(handler(event), timeout=event_result.timeout)
- else:
- # Run sync handler directly in the main thread
- # This blocks but ensures we have access to the event loop
- result = handler(event)
- logger.debug(f' ↳ Sync handler {handler.__name__}#{handler_id[-4:]} returned: {result}')
- # Cancel the monitor task since handler completed successfully
- monitor_task.cancel()
-
- # Record successful result
- event.event_result_update(handler=handler, eventbus=self, result=result)
- if handler_id in event.event_results:
- logger.debug(
- f' ↳ Updated result for {handler.__name__}#{handler_id[-4:]}: {event.event_results[handler_id].status}'
- )
- else:
- logger.error(f' ↳ ERROR: Result not found for {handler.__name__}#{handler_id[-4:]} after update!')
- return result
-
- except Exception as e:
- # Cancel the monitor task on error too
- monitor_task.cancel()
-
- # Record error
- event.event_result_update(handler=handler, eventbus=self, error=str(e))
-
- logger.exception(
- f'❌ {self} Error in handler {handler.__name__}#{str(id(handler))[-4:]}({event}): {type(e).__name__} {e}'
- )
- raise
- finally:
- # Reset context
- _current_event_context.reset(token)
- # Ensure monitor task is cancelled
- try:
- if not monitor_task.done():
- monitor_task.cancel()
- await monitor_task
- except asyncio.CancelledError:
- pass # Expected when we cancel the monitor
- except Exception as e:
- # logger.debug(f"❌ {self} Handler monitor task cleanup error for {handler.__name__}#{str(id(handler))[-4:]}({event}): {type(e).__name__}: {e}")
- pass
-
- def _would_create_loop(self, event: BaseEvent, handler: EventHandler) -> bool:
- """Check if calling this handler would create a loop (i.e. re-process an event that has already been processed by this EventBus)"""
-
- # First check: If handler is another EventBus.dispatch method, check if we're forwarding to another bus that it's already been processed by
- if hasattr(handler, '__self__') and isinstance(handler.__self__, EventBus) and handler.__name__ == 'dispatch':
- target_bus = handler.__self__
- if target_bus.name in event.event_path:
- return True
-
- # Second check: Check if there's already a completed result for this handler ID
- # This prevents the same handler from being called multiple times on the same event
- handler_id = str(id(handler))
- if handler_id in event.event_results:
- existing_result = event.event_results[handler_id]
- if existing_result.completed_at is not None:
- logger.debug(
- f'⚠️ Preventing loop: handler {handler.__name__} (id={handler_id}) already completed at {existing_result.completed_at} for event {event.event_id}'
- )
- return True
-
- return False
-
- async def _default_log_handler(self, event: BaseEvent) -> None:
- """Default handler that logs all events"""
- # logger.debug(
- # f'✅ {self} completed: {event} -> {list(event.event_results.values()) or '<no handlers matched>'}'
- # )
- pass
-
- async def _default_wal_handler(self, event: BaseEvent) -> None:
- """Persist completed event to WAL file as JSONL"""
-
- if not self.wal_path:
- return None
-
- try:
- event_json = event.model_dump_json()
- self.wal_path.parent.mkdir(parents=True, exist_ok=True)
- async with await anyio.open_file(self.wal_path, 'a') as f:
- await f.write(event_json + '\n')
- except Exception as e:
- logger.error(f'❌ {self} Failed to save event {event.event_id} to WAL file: {type(e).__name__} {e}\n{event}')
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 21fcb7821..0d9c1ac41 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -527,12 +527,16 @@ def get_browser_use_version() -> str:
content = f.read()
match = re.search(r'version\s*=\s*["\']([^"\']+)["\']', content)
if match:
- return f'{match.group(1)}'
+ version = f'{match.group(1)}'
+ os.environ['LIBRARY_VERSION'] = version
+ return version
# If pyproject.toml doesn't exist, try getting version from pip
from importlib.metadata import version as get_version
- return str(get_version('browser-use'))
+ version = str(get_version('browser-use'))
+ os.environ['LIBRARY_VERSION'] = version
+ return version
except Exception as e:
logger.debug(f'Error detecting browser-use version: {type(e).__name__}: {e}')
diff --git a/pyproject.toml b/pyproject.toml
index d981fa0a7..86a984598 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -13,6 +13,7 @@ classifiers = [
dependencies = [
"aiofiles>=24.1.0",
"anyio>=4.9.0",
+ "bubus>=1.0.1",
"faiss-cpu>=1.11.0",
"google-api-core>=2.25.0",
"httpx>=0.28.1",
diff --git a/tests/ci/test_agent_emits_cloud_events.py b/tests/ci/test_agent_emits_cloud_events.py
index de1a8d52b..93e285708 100644
--- a/tests/ci/test_agent_emits_cloud_events.py
+++ b/tests/ci/test_agent_emits_cloud_events.py
@@ -29,11 +29,10 @@ from browser_use.agent.cloud_events import (
# Skip LLM API key verification for tests
os.environ['SKIP_LLM_API_KEY_VERIFICATION'] = 'true'
+from bubus import BaseEvent
+
from browser_use import Agent
from browser_use.browser import BrowserSession
-from browser_use.eventbus import (
- BaseEvent,
-)
@pytest.fixture
diff --git a/tests/ci/test_eventbus.py b/tests/ci/test_eventbus.py
deleted file mode 100644
index 03af8c4ab..000000000
--- a/tests/ci/test_eventbus.py
+++ /dev/null
@@ -1,1459 +0,0 @@
-"""
-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, timezone
-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
-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()
-
-
-async def parallel_eventbus():
- """Create an event bus with parallel handler execution"""
- bus = EventBus(parallel_handlers=True)
- 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['*']) == 0 # No default logger anymore
-
- 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.dispatch(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_and_result(self, eventbus):
- """Test event emission in async and sync contexts, and result() pattern"""
- # Test async emission
- event = UserActionEvent(action='login', user_id='user123', event_timeout=1)
- queued = eventbus.dispatch(event)
-
- # Check immediate result
- assert isinstance(queued, UserActionEvent)
- assert queued.event_type == 'UserActionEvent'
- assert queued.action == 'login'
- assert queued.user_id == 'user123'
- assert queued.event_id is not None
- assert queued.event_created_at is not None
- assert queued.event_started_at is None # Not started yet
- assert queued.event_completed_at is None # Not completed yet
- assert queued.event_status == 'pending'
-
- # Test result() pattern
- processed = await queued
- assert processed.event_started_at is not None
- assert processed.event_completed_at is not None
- assert processed.event_status == 'completed'
- # Check that we have no results (no default handler anymore)
- assert len(processed.event_results) == 0
-
- # Check event history
- assert len(eventbus.event_history) == 1
-
- def test_emit_sync(self, mock_agent):
- """Test sync event emission"""
- bus = EventBus()
- event = SystemEventModel(event_name='startup', severity='info')
- result = bus.dispatch(event)
-
- # Check result and write-ahead log
- assert isinstance(result, SystemEventModel)
- assert result.event_type == 'SystemEventModel'
- assert len(bus.event_history) == 1
-
-
-class TestHandlerRegistration:
- """Test handler registration and execution"""
-
- async def test_handler_registration(self, eventbus):
- """Test handler registration via string, model class, and wildcard"""
- results = {'specific': [], 'model': [], 'universal': []}
-
- # Handler for specific event type by string
- async def user_handler(event: UserActionEvent) -> str:
- results['specific'].append(event.action)
- return 'user_handled'
-
- # Handler for event type by model class
- async def system_handler(event: SystemEventModel) -> str:
- results['model'].append(event.event_name)
- return 'system_handled'
-
- # Universal handler
- async def universal_handler(event: BaseEvent) -> str:
- results['universal'].append(event.event_type)
- return 'universal'
-
- # Register handlers
- eventbus.on('UserActionEvent', user_handler)
- eventbus.on(SystemEventModel, system_handler)
- eventbus.on('*', universal_handler)
-
- # Emit events
- eventbus.dispatch(UserActionEvent(action='login', user_id='u1'))
- eventbus.dispatch(SystemEventModel(event_name='startup'))
- await eventbus.wait_until_idle()
-
- # Verify all handlers were called correctly
- assert results['specific'] == ['login']
- assert results['model'] == ['startup']
- assert set(results['universal']) == {'UserActionEvent', 'SystemEventModel'}
-
- async def test_multiple_handlers_parallel(self, parallel_eventbus):
- """Test that multiple handlers run in parallel"""
- eventbus = parallel_eventbus
- 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.dispatch(UserActionEvent(action='test', user_id='u1'))
- 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
- handler1_result = next((r for r in event.event_results.values() if r.handler_name == 'slow_handler_1'), None)
- handler2_result = next((r for r in event.event_results.values() if r.handler_name == 'slow_handler_2'), None)
- assert handler1_result is not None and handler1_result.result == 'handler1'
- assert handler2_result is not None and handler2_result.result == '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_with_varying_handler_delays(self, eventbus):
- """Test FIFO order is maintained with varying handler processing times"""
- processed_order = []
- handler_start_times = []
-
- async def handler(event: UserActionEvent) -> int:
- order = event.metadata.get('order', -1)
- handler_start_times.append((order, asyncio.get_event_loop().time()))
- # Variable delays to test ordering
- if order % 2 == 0:
- await asyncio.sleep(0.05) # Even events take longer
- else:
- await asyncio.sleep(0.01) # Odd events are quick
- processed_order.append(order)
- return order
-
- eventbus.on('UserActionEvent', handler)
-
- # Emit 20 events rapidly
- for i in range(20):
- eventbus.dispatch(UserActionEvent(action=f'test_{i}', user_id='u1', metadata={'order': i}))
-
- await eventbus.wait_until_idle()
-
- # Verify FIFO order maintained
- assert processed_order == list(range(20))
- # Verify handler start times are in order
- for i in range(1, len(handler_start_times)):
- assert handler_start_times[i][1] >= handler_start_times[i - 1][1]
-
-
-class TestErrorHandling:
- """Test error handling in handlers"""
-
- async def test_error_handling(self, eventbus):
- """Test handler error capture and isolation"""
- results = []
-
- async def failing_handler(event: BaseEvent) -> str:
- raise ValueError('Expected to fail')
-
- async def working_handler(event: BaseEvent) -> str:
- results.append('success')
- return 'worked'
-
- # Register both handlers
- eventbus.on('UserActionEvent', failing_handler)
- eventbus.on('UserActionEvent', working_handler)
-
- # Emit and wait for result
- event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1'))
-
- # Verify error capture and isolation
- failing_result = next((r for r in event.event_results.values() if r.handler_name == 'failing_handler'), None)
- assert failing_result is not None
- assert failing_result.status == 'error'
- assert 'Expected to fail' in failing_result.error
- working_result = next((r for r in event.event_results.values() if r.handler_name == 'working_handler'), None)
- assert working_result is not None
- assert working_result.result == 'worked'
- assert results == ['success']
-
-
-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.dispatch(event) for event in events]
- results = await asyncio.gather(*emitted_events)
-
- # Check all processed
- assert len(results) == 3
- for result in results:
- assert result.event_completed_at is not None
-
-
-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.dispatch(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.values()):
- assert event.action == f'action_{i}'
-
- # Check event state properties
- completed = eventbus.events_completed
- pending = eventbus.events_pending
- 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 TestEventCompletion:
- """Test event completion tracking"""
-
- async def test_wait_for_result(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.dispatch(UserActionEvent(action='test', user_id='u1'))
- completion_order.append('enqueue_done')
-
- # Wait for completion
- event = await event
- completion_order.append('wait_done')
-
- # Check order
- assert completion_order == ['enqueue_done', 'handler_done', 'wait_done']
- assert event.event_completed_at is not None
-
-
-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.dispatch(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.now(timezone.utc),
- 'none': None,
- }
- }
-
- event = SystemEventModel(event_name='complex', details=complex_data)
-
- result = await eventbus.dispatch(event)
-
- # 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 syncresultsonously, but we need to wait for completion
- emitted_event = eventbus.dispatch(event)
- tasks.append(emitted_event)
-
- # 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_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.dispatch(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}'
-
-
-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.dispatch(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.utils import get_browser_use_version
-
- version = get_browser_use_version()
-
- # Test various event types
- base_event = BaseEvent(event_type='TestEvent')
- assert base_event.event_schema == f'browser_use.eventbus.models.BaseEvent@{version}'
-
- task_event = CreateAgentTaskEvent(
- user_id='test_user', agent_session_id='12345678-1234-5678-1234-567812345678', llm_model='test-model', task='test task'
- )
- assert task_event.event_schema == f'browser_use.agent.cloud_events.CreateAgentTaskEvent@{version}'
-
- user_event = UserActionEvent(action='login', user_id='user123')
- assert user_event.event_schema == f'test_eventbus.UserActionEvent@{version}'
-
- # Check schema is preserved after emit
- result = eventbus.dispatch(task_event)
- assert result.event_schema == task_event.event_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.dispatch(event)
- completed_event = await emitted_event
- events.append(completed_event)
-
- # 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['action'] == f'action_{i}'
- assert data['user_id'] == f'user_{i}'
- assert data['event_type'] == 'UserActionEvent'
- assert isinstance(data['event_created_at'], str)
- datetime.fromisoformat(data['event_created_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)
-
- try:
- # Emit an event
- event = bus.dispatch(UserActionEvent(action='test', user_id='u1'))
- await event
-
- # Wait for WAL persistence to complete
- await bus.wait_until_idle()
-
- # Parent directory should be created after event is processed
- assert wal_path.parent.exists()
-
- # 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.dispatch(UserActionEvent(action='test', user_id='u1'))
-
- # Check file doesn't exist yet (event not completed)
- assert not wal_path.exists()
-
- # Wait for completion
- event = await event
- 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'
- # The WAL should have been written after the event completed
- assert data['action'] == 'test'
- assert data['user_id'] == 'u1'
-
- finally:
- await bus.stop()
-
-
-class TestEventBusHierarchy:
- """Test hierarchical EventBus subscription patterns"""
-
- async def test_tresultsee_level_hierarchy_bubbling(self):
- """Test that events bubble up tresultsough a 3-level hierarchy and event_path is correct"""
- # Create tresultsee EventBus instances in a hierarchy
- parent_bus = EventBus(name='ParentBus')
- child_bus = EventBus(name='ChildBus')
- subchild_bus = EventBus(name='SubchildBus')
-
- # Track events received at each level
- events_at_parent = []
- events_at_child = []
- events_at_subchild = []
-
- async def parent_handler(event: BaseEvent) -> str:
- events_at_parent.append(event)
- return 'parent_received'
-
- async def child_handler(event: BaseEvent) -> str:
- events_at_child.append(event)
- return 'child_received'
-
- async def subchild_handler(event: BaseEvent) -> str:
- events_at_subchild.append(event)
- return 'subchild_received'
-
- # Register handlers
- parent_bus.on('*', parent_handler)
- child_bus.on('*', child_handler)
- subchild_bus.on('*', subchild_handler)
-
- # Subscribe buses to each other: parent <- child <- subchild
- # Child forwards events to parent
- child_bus.on('*', parent_bus.dispatch)
- # Subchild forwards events to child
- subchild_bus.on('*', child_bus.dispatch)
-
- try:
- # Emit event from the bottom of hierarchy
- event = UserActionEvent(action='bubble_test', user_id='test_user')
- emitted = subchild_bus.dispatch(event)
-
- # Wait for event to bubble up
- await subchild_bus.wait_until_idle()
- await child_bus.wait_until_idle()
- await parent_bus.wait_until_idle()
-
- # Verify event was received at all levels
- assert len(events_at_subchild) == 1
- assert len(events_at_child) == 1
- assert len(events_at_parent) == 1
-
- # Verify event_path shows the complete journey
- final_event = events_at_parent[0]
- assert final_event.event_path == ['SubchildBus', 'ChildBus', 'ParentBus']
-
- # Verify it's the same event content
- assert final_event.action == 'bubble_test'
- assert final_event.user_id == 'test_user'
- assert final_event.event_id == emitted.event_id
-
- # Test event emitted at middle level
- events_at_parent.clear()
- events_at_child.clear()
- events_at_subchild.clear()
-
- middle_event = SystemEventModel(event_name='middle_test')
- child_bus.dispatch(middle_event)
-
- await child_bus.wait_until_idle()
- await parent_bus.wait_until_idle()
-
- # Should only reach child and parent, not subchild
- assert len(events_at_subchild) == 0
- assert len(events_at_child) == 1
- assert len(events_at_parent) == 1
- assert events_at_parent[0].event_path == ['ChildBus', 'ParentBus']
-
- finally:
- await parent_bus.stop()
- await child_bus.stop()
- await subchild_bus.stop()
-
- async def test_circular_subscription_prevention(self):
- """Test that circular EventBus subscriptions don't create infinite loops"""
- # Create tresultsee peer EventBus instances
- peer1 = EventBus(name='Peer1')
- peer2 = EventBus(name='Peer2')
- peer3 = EventBus(name='Peer3')
-
- # Track events at each peer
- events_at_peer1 = []
- events_at_peer2 = []
- events_at_peer3 = []
-
- async def peer1_handler(event: BaseEvent) -> str:
- events_at_peer1.append(event)
- return 'peer1_received'
-
- async def peer2_handler(event: BaseEvent) -> str:
- events_at_peer2.append(event)
- return 'peer2_received'
-
- async def peer3_handler(event: BaseEvent) -> str:
- events_at_peer3.append(event)
- return 'peer3_received'
-
- # Register handlers
- peer1.on('*', peer1_handler)
- peer2.on('*', peer2_handler)
- peer3.on('*', peer3_handler)
-
- # Create circular subscription: peer1 -> peer2 -> peer3 -> peer1
- peer1.on('*', peer2.dispatch)
- peer2.on('*', peer3.dispatch)
- peer3.on('*', peer1.dispatch) # This completes the circle
-
- try:
- # Emit event from peer1
- event = UserActionEvent(action='circular_test', user_id='test_user')
- emitted = peer1.dispatch(event)
-
- # Wait for all processing to complete
- await asyncio.sleep(0.2) # Give time for any potential loops
- await peer1.wait_until_idle()
- await peer2.wait_until_idle()
- await peer3.wait_until_idle()
-
- # Each peer should receive the event exactly once
- assert len(events_at_peer1) == 1
- assert len(events_at_peer2) == 1
- assert len(events_at_peer3) == 1
-
- # Check event paths show the propagation but no loops
- assert events_at_peer1[0].event_path == ['Peer1', 'Peer2', 'Peer3']
- assert events_at_peer2[0].event_path == ['Peer1', 'Peer2', 'Peer3']
- assert events_at_peer3[0].event_path == ['Peer1', 'Peer2', 'Peer3']
-
- # The event should NOT come back to peer1 from peer3
- # because peer3's emit handler will detect peer1 is already in the path
-
- # Verify all events have the same ID (same event, not duplicates)
- assert all(e.event_id == emitted.event_id for e in [events_at_peer1[0], events_at_peer2[0], events_at_peer3[0]])
-
- # Test starting from a different peer
- events_at_peer1.clear()
- events_at_peer2.clear()
- events_at_peer3.clear()
-
- event2 = SystemEventModel(event_name='circular_test_2')
- peer2.dispatch(event2)
-
- await asyncio.sleep(0.2)
- await peer1.wait_until_idle()
- await peer2.wait_until_idle()
- await peer3.wait_until_idle()
-
- # Should visit peer2 -> peer3 -> peer1, then stop
- assert len(events_at_peer1) == 1
- assert len(events_at_peer2) == 1
- assert len(events_at_peer3) == 1
-
- assert events_at_peer2[0].event_path == ['Peer2', 'Peer3', 'Peer1']
- assert events_at_peer3[0].event_path == ['Peer2', 'Peer3', 'Peer1']
- assert events_at_peer1[0].event_path == ['Peer2', 'Peer3', 'Peer1']
-
- finally:
- await peer1.stop()
- await peer2.stop()
- await peer3.stop()
-
-
-class TestExpectMethod:
- """Test the expect() method functionality"""
-
- async def test_expect_basic(self, eventbus):
- """Test basic expect functionality"""
- # Start waiting for an event that hasn't been dispatched yet
- expect_task = asyncio.create_task(eventbus.expect('UserActionEvent', timeout=1.0))
-
- # Give expect time to register handler
- await asyncio.sleep(0.01)
-
- # Dispatch the event
- dispatched = eventbus.dispatch(UserActionEvent(action='login', user_id='user123'))
-
- # Wait for expect to resolve
- received = await expect_task
-
- # Verify we got the right event
- assert received.event_type == 'UserActionEvent'
- assert received.action == 'login'
- assert received.user_id == 'user123'
- assert received.event_id == dispatched.event_id
-
- async def test_expect_with_predicate(self, eventbus):
- """Test expect with predicate filtering"""
- # Dispatch some events that don't match
- eventbus.dispatch(UserActionEvent(action='logout', user_id='user456'))
- eventbus.dispatch(UserActionEvent(action='login', user_id='user789'))
-
- # Start expecting with predicate
- expect_task = asyncio.create_task(
- eventbus.expect('UserActionEvent', predicate=lambda e: e.user_id == 'user123', timeout=1.0)
- )
-
- # Give expect time to register
- await asyncio.sleep(0.01)
-
- # Dispatch more events
- eventbus.dispatch(UserActionEvent(action='update', user_id='user456'))
- target_event = eventbus.dispatch(UserActionEvent(action='login', user_id='user123'))
- eventbus.dispatch(UserActionEvent(action='delete', user_id='user789'))
-
- # Wait for the matching event
- received = await expect_task
-
- # Should get the event matching the predicate
- assert received.user_id == 'user123'
- assert received.event_id == target_event.event_id
-
- async def test_expect_timeout(self, eventbus):
- """Test expect timeout behavior"""
- # Expect an event that will never come
- with pytest.raises(asyncio.TimeoutError):
- await eventbus.expect('NonExistentEvent', timeout=0.1)
-
- async def test_expect_with_model_class(self, eventbus):
- """Test expect with model class instead of string"""
- # Start expecting by model class
- expect_task = asyncio.create_task(eventbus.expect(SystemEventModel, timeout=1.0))
-
- await asyncio.sleep(0.01)
-
- # Dispatch different event types
- eventbus.dispatch(UserActionEvent(action='test', user_id='u1'))
- target = eventbus.dispatch(SystemEventModel(event_name='startup', severity='info'))
-
- # Should receive the SystemEventModel
- received = await expect_task
- assert isinstance(received, SystemEventModel)
- assert received.event_name == 'startup'
- assert received.event_id == target.event_id
-
- async def test_multiple_concurrent_expects(self, eventbus):
- """Test multiple concurrent expect calls"""
- # Set up multiple expects for different events
- expect1 = asyncio.create_task(eventbus.expect('UserActionEvent', predicate=lambda e: e.action == 'normal', timeout=2.0))
- expect2 = asyncio.create_task(eventbus.expect('SystemEventModel', timeout=2.0))
- expect3 = asyncio.create_task(eventbus.expect('UserActionEvent', predicate=lambda e: e.action == 'special', timeout=2.0))
-
- await asyncio.sleep(0.1) # Give more time for handlers to register
-
- # Dispatch events
- e1 = eventbus.dispatch(UserActionEvent(action='normal', user_id='u1'))
- e2 = eventbus.dispatch(SystemEventModel(event_name='test'))
- e3 = eventbus.dispatch(UserActionEvent(action='special', user_id='u2'))
-
- # Wait for all events to be processed
- await eventbus.wait_until_idle()
-
- # Wait for all expects
- r1, r2, r3 = await asyncio.gather(expect1, expect2, expect3)
-
- # Verify results
- assert r1.event_id == e1.event_id # Normal UserActionEvent
- assert r2.event_id == e2.event_id # SystemEventModel
- assert r3.event_id == e3.event_id # Special UserActionEvent
-
- async def test_expect_handler_cleanup(self, eventbus):
- """Test that temporary handlers are properly cleaned up"""
- # Check initial handler count
- initial_handlers = len(eventbus.handlers.get('TestEvent', []))
-
- # Create an expect that times out
- try:
- await eventbus.expect('TestEvent', timeout=0.1)
- except TimeoutError:
- pass
-
- # Handler should be cleaned up
- assert len(eventbus.handlers.get('TestEvent', [])) == initial_handlers
-
- # Create an expect that succeeds
- expect_task = asyncio.create_task(eventbus.expect('TestEvent2', timeout=1.0))
- await asyncio.sleep(0.01)
- eventbus.dispatch(BaseEvent(event_type='TestEvent2'))
- await expect_task
-
- # Handler should be cleaned up
- assert len(eventbus.handlers.get('TestEvent2', [])) == 0
-
- async def test_expect_receives_completed_event(self, eventbus):
- """Test that expect receives events after they're fully processed"""
- processing_complete = False
-
- async def slow_handler(event: BaseEvent) -> str:
- await asyncio.sleep(0.1)
- nonlocal processing_complete
- processing_complete = True
- return 'done'
-
- # Register a slow handler
- eventbus.on('SlowEvent', slow_handler)
-
- # Start expecting
- expect_task = asyncio.create_task(eventbus.expect('SlowEvent', timeout=1.0))
-
- await asyncio.sleep(0.01)
-
- # Dispatch event
- eventbus.dispatch(BaseEvent(event_type='SlowEvent'))
-
- # Wait for expect
- received = await expect_task
-
- # At this point, the slow handler should have run
- # but we receive the event as soon as it matches
- assert received.event_type == 'SlowEvent'
- # The event might not be fully completed yet since expect
- # triggers as soon as the event is processed by its handler
-
- async def test_expect_with_complex_predicate(self, eventbus):
- """Test expect with complex predicate logic"""
- events_seen = []
-
- def complex_predicate(event: BaseEvent) -> bool:
- if hasattr(event, 'action'):
- # Only match after seeing at least 3 events and action is 'target'
- result = len(events_seen) >= 3 and event.action == 'target'
- events_seen.append(event.action)
- return result
- return False
-
- expect_task = asyncio.create_task(eventbus.expect('UserActionEvent', predicate=complex_predicate, timeout=1.0))
-
- await asyncio.sleep(0.01)
-
- # Dispatch events
- eventbus.dispatch(UserActionEvent(action='first', user_id='u1'))
- eventbus.dispatch(UserActionEvent(action='second', user_id='u2'))
- eventbus.dispatch(UserActionEvent(action='target', user_id='u3')) # Won't match yet
- eventbus.dispatch(UserActionEvent(action='target', user_id='u4')) # This should match
-
- received = await expect_task
-
- assert received.user_id == 'u4'
- assert len(events_seen) == 4
-
- async def test_expect_in_sync_context(self, mock_agent):
- """Test that expect can be used from sync code that later awaits"""
- bus = EventBus()
-
- # This simulates calling expect from sync code
- expect_coroutine = bus.expect('SyncEvent', timeout=1.0)
-
- # Dispatch event
- bus.dispatch(BaseEvent(event_type='SyncEvent'))
-
- # Later await the coroutine
- result = await expect_coroutine
- assert result.event_type == 'SyncEvent'
-
- await bus.stop()
-
-
-class TestEventResults:
- """Test the event results functionality on BaseEvent"""
-
- async def test_dispatch_returns_event_results(self, eventbus):
- """Test that dispatch returns BaseEvent with result methods"""
-
- # Register a specific handler
- async def test_handler(event):
- return {'result': 'test_result'}
-
- eventbus.on('UserActionEvent', test_handler)
-
- result = eventbus.dispatch(UserActionEvent(action='test', user_id='u1'))
- assert isinstance(result, BaseEvent)
-
- # Wait for completion
- await result
- # Get results by handler ID
- all_results = await result.event_results_flat_dict()
- assert isinstance(all_results, dict)
- # Should contain only test_handler result
- assert len(all_results) == 1
- assert all_results['result'] == 'test_result'
-
- # Test with no specific handlers
- result_no_handlers = eventbus.dispatch(BaseEvent(event_type='NoHandlersEvent'))
- await result_no_handlers
- # Should have no handlers
- assert len(result_no_handlers.event_results) == 0
-
- async def test_event_results_indexing(self, eventbus):
- """Test indexing by handler name and ID"""
- order = []
-
- async def handler1(event):
- order.append(1)
- return 'first'
-
- async def handler2(event):
- order.append(2)
- return 'second'
-
- async def handler3(event):
- order.append(3)
- return 'third'
-
- eventbus.on('TestEvent', handler1)
- eventbus.on('TestEvent', handler2)
- eventbus.on('TestEvent', handler3)
-
- # Test indexing
- event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))
-
- # Get results by handler name
- handler1_result = next((r for r in event.event_results.values() if r.handler_name == 'handler1'), None)
- handler2_result = next((r for r in event.event_results.values() if r.handler_name == 'handler2'), None)
- handler3_result = next((r for r in event.event_results.values() if r.handler_name == 'handler3'), None)
-
- assert handler1_result is not None and handler1_result.result == 'first'
- assert handler2_result is not None and handler2_result.result == 'second'
- assert handler3_result is not None and handler3_result.result == 'third'
-
- async def test_event_results_access(self, eventbus):
- """Test accessing event results"""
-
- async def early_handler(event):
- return 'early'
-
- async def late_handler(event):
- await asyncio.sleep(0.01)
- return 'late'
-
- eventbus.on('TestEvent', early_handler)
- eventbus.on('TestEvent', late_handler)
-
- result = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))
-
- # Check both handlers ran
- assert len(result.event_results) == 2
- early_result = next((r for r in result.event_results.values() if r.handler_name == 'early_handler'), None)
- late_result = next((r for r in result.event_results.values() if r.handler_name == 'late_handler'), None)
- assert early_result is not None and early_result.result == 'early'
- assert late_result is not None and late_result.result == 'late'
-
- # With empty handlers
- eventbus.handlers['EmptyEvent'] = []
- results_empty = eventbus.dispatch(BaseEvent(event_type='EmptyEvent'))
- await results_empty
- # Should have no handlers
- assert len(results_empty.event_results) == 0
-
- async def test_by_handler_name(self, eventbus):
- """Test handler results with duplicate names"""
-
- async def process_data(event):
- return 'version1'
-
- async def process_data2(event): # Different function, same __name__
- return 'version2'
-
- process_data2.__name__ = 'process_data' # Same name!
-
- async def unique_handler(event):
- return 'unique'
-
- # Should get warning about duplicate name
- with pytest.warns(UserWarning, match='already registered'):
- eventbus.on('TestEvent', process_data)
- eventbus.on('TestEvent', process_data2)
- eventbus.on('TestEvent', unique_handler)
-
- event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))
-
- # Check results - with duplicate names, both handlers run
- process_results = [r for r in event.event_results.values() if r.handler_name == 'process_data']
- assert len(process_results) == 2
- assert {r.result for r in process_results} == {'version1', 'version2'}
-
- unique_result = next((r for r in event.event_results.values() if r.handler_name == 'unique_handler'), None)
- assert unique_result is not None and unique_result.result == 'unique'
-
- async def test_by_handler_id(self, eventbus):
- """Test that all handlers run with unique IDs even with same name"""
-
- async def handler1(event):
- return 'v1'
-
- async def handler2(event):
- return 'v2'
-
- # Give them the same name for the test
- handler1.__name__ = 'handler'
- handler2.__name__ = 'handler'
-
- with pytest.warns(UserWarning, match='already registered'):
- eventbus.on('TestEvent', handler1)
- eventbus.on('TestEvent', handler2)
-
- event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))
-
- # Get results by handler ID using the method that exists
- results = await event.event_results_by_handler_id()
-
- # All handlers present with unique IDs even with same name
- # Should have 2 results: handler1, handler2
- assert len(results) == 2
- assert 'v1' in results.values()
- assert 'v2' in results.values()
-
- async def test_flat_dict(self, eventbus):
- """Test event_results_flat_dict() merging"""
-
- async def config_base(event):
- return {'debug': False, 'port': 8080, 'name': 'base'}
-
- async def config_override(event):
- return {'debug': True, 'timeout': 30, 'name': 'override'}
-
- eventbus.on('GetConfig', config_base)
- eventbus.on('GetConfig', config_override)
-
- event = await eventbus.dispatch(BaseEvent(event_type='GetConfig'))
- merged = await event.event_results_flat_dict()
-
- # Later handlers override earlier ones
- assert merged == {
- 'debug': True, # Overridden
- 'port': 8080, # From base
- 'timeout': 30, # From override
- 'name': 'override', # Overridden
- }
-
- # Test non-dict handler (should be skipped)
- async def bad_handler(event):
- return 'not a dict'
-
- eventbus.on('BadConfig', bad_handler)
- event_bad = await eventbus.dispatch(BaseEvent(event_type='BadConfig'))
-
- # Non-dict results should be skipped, not raise error
- merged_bad = await event_bad.event_results_flat_dict()
- assert merged_bad == {} # Empty dict since no dict results
-
- async def test_flat_list(self, eventbus):
- """Test event_results_flat_list() concatenation"""
-
- async def errors1(event):
- return ['error1', 'error2']
-
- async def errors2(event):
- return ['error3']
-
- async def errors3(event):
- return ['error4', 'error5']
-
- eventbus.on('GetErrors', errors1)
- eventbus.on('GetErrors', errors2)
- eventbus.on('GetErrors', errors3)
-
- event = await eventbus.dispatch(BaseEvent(event_type='GetErrors'))
- all_errors = await event.event_results_flat_list()
-
- # Check that all errors are collected (order may vary due to handler execution)
- assert set(all_errors) == {'error1', 'error2', 'error3', 'error4', 'error5'}
-
- # Test with non-list handler
- async def single_value(event):
- return 'single'
-
- eventbus.on('GetSingle', single_value)
- event_single = await eventbus.dispatch(BaseEvent(event_type='GetSingle'))
-
- result = await event_single.event_results_flat_list()
- assert 'single' in result # Single values are appended
- assert len(result) == 1
-
- async def test_by_handler_name_access(self, eventbus):
- """Test accessing results by handler name"""
-
- async def handler_a(event):
- return 'result_a'
-
- async def handler_b(event):
- return 'result_b'
-
- eventbus.on('TestEvent', handler_a)
- eventbus.on('TestEvent', handler_b)
-
- event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))
-
- # Access results by handler name
- handler_a_result = next((r for r in event.event_results.values() if r.handler_name == 'handler_a'), None)
- handler_b_result = next((r for r in event.event_results.values() if r.handler_name == 'handler_b'), None)
-
- assert handler_a_result is not None and handler_a_result.result == 'result_a'
- assert handler_b_result is not None and handler_b_result.result == 'result_b'
-
- async def test_string_indexing(self, eventbus):
- """Test accessing handler results"""
-
- async def my_handler(event):
- return 'my_result'
-
- eventbus.on('TestEvent', my_handler)
- event = await eventbus.dispatch(BaseEvent(event_type='TestEvent'))
-
- # Access result by handler name
- my_handler_result = next((r for r in event.event_results.values() if r.handler_name == 'my_handler'), None)
- assert my_handler_result is not None and my_handler_result.result == 'my_result'
-
- # Check missing handler returns None
- missing_result = next((r for r in event.event_results.values() if r.handler_name == 'missing'), None)
- assert missing_result is None
-
-
-class TestEventBusForwarding:
- """Test event forwarding between buses with new EventResults"""
-
- async def test_forwarding_flattens_results(self):
- """Test that forwarding events between buses flattens all results"""
- bus1 = EventBus(name='Bus1')
- bus2 = EventBus(name='Bus2')
- bus3 = EventBus(name='Bus3')
-
- results = []
-
- async def bus1_handler(event):
- results.append('bus1')
- return 'from_bus1'
-
- async def bus2_handler(event):
- results.append('bus2')
- return 'from_bus2'
-
- async def bus3_handler(event):
- results.append('bus3')
- return 'from_bus3'
-
- # Register handlers
- bus1.on('TestEvent', bus1_handler)
- bus2.on('TestEvent', bus2_handler)
- bus3.on('TestEvent', bus3_handler)
-
- # Set up forwarding chain
- bus1.on('*', bus2.dispatch)
- bus2.on('*', bus3.dispatch)
-
- try:
- # Dispatch from bus1
- event = bus1.dispatch(BaseEvent(event_type='TestEvent'))
-
- # Wait for all buses to complete processing
- await bus1.wait_until_idle()
- await bus2.wait_until_idle()
- await bus3.wait_until_idle()
-
- # Wait for event completion
- event = await event
-
- # All handlers from all buses should be visible
- bus1_result = next((r for r in event.event_results.values() if r.handler_name == 'bus1_handler'), None)
- bus2_result = next((r for r in event.event_results.values() if r.handler_name == 'bus2_handler'), None)
- bus3_result = next((r for r in event.event_results.values() if r.handler_name == 'bus3_handler'), None)
-
- assert bus1_result is not None and bus1_result.result == 'from_bus1'
- assert bus2_result is not None and bus2_result.result == 'from_bus2'
- assert bus3_result is not None and bus3_result.result == 'from_bus3'
-
- # Check execution order
- assert results == ['bus1', 'bus2', 'bus3']
-
- finally:
- await bus1.stop()
- await bus2.stop()
- await bus3.stop()
-
- async def test_by_eventbus_id_and_path(self):
- """Test by_eventbus_id() and by_path() with forwarding"""
- bus1 = EventBus(name='MainBus')
- bus2 = EventBus(name='PluginBus')
-
- async def main_handler(event):
- return 'main_result'
-
- async def plugin_handler1(event):
- return 'plugin_result1'
-
- async def plugin_handler2(event):
- return 'plugin_result2'
-
- bus1.on('DataEvent', main_handler)
- bus2.on('DataEvent', plugin_handler1)
- bus2.on('DataEvent', plugin_handler2)
-
- # Forward from bus1 to bus2
- bus1.on('*', bus2.dispatch)
-
- try:
- event = bus1.dispatch(BaseEvent(event_type='DataEvent'))
-
- # Wait for processing
- await bus1.wait_until_idle()
- await bus2.wait_until_idle()
- event = await event
-
- # Check results from both buses
- main_result = next((r for r in event.event_results.values() if r.handler_name == 'main_handler'), None)
- plugin1_result = next((r for r in event.event_results.values() if r.handler_name == 'plugin_handler1'), None)
- plugin2_result = next((r for r in event.event_results.values() if r.handler_name == 'plugin_handler2'), None)
-
- assert main_result is not None and main_result.result == 'main_result'
- assert plugin1_result is not None and plugin1_result.result == 'plugin_result1'
- assert plugin2_result is not None and plugin2_result.result == 'plugin_result2'
-
- # Check event path shows forwarding
- assert event.event_path == ['MainBus', 'PluginBus']
-
- finally:
- await bus1.stop()
- await bus2.stop()
-
-
-class TestComplexIntegration:
- """Complex integration test with all features"""
-
- async def test_complex_multi_bus_scenario(self):
- """Test complex scenario with multiple buses, duplicate names, and all query methods"""
- # Create a hierarchy of buses
- app_bus = EventBus(name='AppBus')
- auth_bus = EventBus(name='AuthBus')
- data_bus = EventBus(name='DataBus')
-
- # Handlers with conflicting names
- async def app_validate(event):
- """App validation"""
- return {'app_valid': True, 'timestamp': 1000}
-
- app_validate.__name__ = 'validate'
-
- async def auth_validate(event):
- """Auth validation"""
- return {'auth_valid': True, 'user': 'alice'}
-
- auth_validate.__name__ = 'validate'
-
- async def data_validate(event):
- """Data validation"""
- return {'data_valid': True, 'schema': 'v2'}
-
- data_validate.__name__ = 'validate'
-
- async def auth_process(event):
- """Auth processing"""
- return ['auth_log_1', 'auth_log_2']
-
- auth_process.__name__ = 'process'
-
- async def data_process(event):
- """Data processing"""
- return ['data_log_1', 'data_log_2', 'data_log_3']
-
- data_process.__name__ = 'process'
-
- # Register handlers with same names on different buses
- app_bus.on('ValidationRequest', app_validate)
- auth_bus.on('ValidationRequest', auth_validate)
- auth_bus.on('ValidationRequest', auth_process) # Different return type!
- data_bus.on('ValidationRequest', data_validate)
- data_bus.on('ValidationRequest', data_process)
-
- # Set up forwarding
- app_bus.on('*', auth_bus.dispatch)
- auth_bus.on('*', data_bus.dispatch)
-
- try:
- # Dispatch event
- event = app_bus.dispatch(BaseEvent(event_type='ValidationRequest'))
-
- # Wait for all processing
- await app_bus.wait_until_idle()
- await auth_bus.wait_until_idle()
- await data_bus.wait_until_idle()
- event = await event
-
- # Test that all handlers ran
- # Count handlers by name
- validate_results = [r for r in event.event_results.values() if r.handler_name == 'validate']
- process_results = [r for r in event.event_results.values() if r.handler_name == 'process']
-
- # Should have multiple validate and process handlers from different buses
- assert len(validate_results) >= 3 # One per bus
- assert len(process_results) >= 2 # Auth and Data buses
-
- # Check event path shows forwarding through all buses
- assert 'AppBus' in event.event_path
- assert 'AuthBus' in event.event_path
- assert 'DataBus' in event.event_path
-
- # Test flat dict merging
- dict_result = await event.event_results_flat_dict()
- # Should have merged all dict returns
- assert 'app_valid' in dict_result and 'auth_valid' in dict_result and 'data_valid' in dict_result
-
- # Test flat list
- list_result = await event.event_results_flat_list()
- # Should include all list items and non-list values
- assert any('log' in str(item) for item in list_result)
-
- finally:
- await app_bus.stop()
- await auth_bus.stop()
- await data_bus.stop()
-
-
-if __name__ == '__main__':
- pytest.main([__file__, '-v'])
diff --git a/tests/ci/test_parent_event_tracking.py b/tests/ci/test_parent_event_tracking.py
index 27608521f..790a2d674 100644
--- a/tests/ci/test_parent_event_tracking.py
+++ b/tests/ci/test_parent_event_tracking.py
@@ -5,8 +5,7 @@ Test parent event tracking functionality in EventBus.
import asyncio
import pytest
-
-from browser_use.eventbus import BaseEvent, EventBus
+from bubus import BaseEvent, EventBus
class ParentEvent(BaseEvent):