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
wip
Nick Sweeting0b7ada473106
diff --git a/browser_use/eventbus/models.py b/browser_use/eventbus/models.pyindex bf0e616df..3b7ad8b7c 100644--- a/browser_use/eventbus/models.py+++ b/browser_use/eventbus/models.py@@ -24,7 +24,6 @@ MAX_FILE_CONTENT_SIZE = 50 * 1024 * 1024 # 50MBUUIDStr = Annotated[str, AfterValidator(lambda s: str(UUID(s)))]-class BaseEvent(BaseModel):"""The base model used for all Events that flow through the EventBus system.@@ -36,7 +35,7 @@ class BaseEvent(BaseModel):event_type: strevent_id: str = Field(default_factory=uuid7str)event_path: list[str] = Field(default_factory=list, description='Path tracking for event routing')- parent_event_id: str | None = Field(default=None, description='ID of the parent event that triggered this event')+ event_parent_id: str | None = Field(default=None, description='ID of the parent event that triggered this event')# Completion tracking fieldsevent_created_at: datetime = Field(@@ -44,283 +43,186 @@ class BaseEvent(BaseModel):)event_started_at: datetime | None = Field(default=None, description='Timestamp when event was started')event_completed_at: datetime | None = Field(default=None, description='Timestamp when event was completed')- # Store results by handler id to avoid name clashes- event_results: dict[str, Any] = Field(- default_factory=dict, exclude=True, description='Handler results {str(id(handler)): result}'- )- event_errors: dict[str, str] = Field(- default_factory=dict, exclude=True, description='Handler errors {str(id(handler)): error_str}'- )- # Map handler ids to metadata for result grouping- _handler_metadata: dict[str, dict[str, Any]] = PrivateAttr(default_factory=dict)- _event_completed_signal: asyncio.Event | None = PrivateAttr(default=None)- _eventbus: 'EventBus | None' = PrivateAttr(default=None)- results: 'EventResults | None' = Field(default=None, exclude=True)++ # Results indexed by handler ID+ event_results: dict[str, 'EventResult'] = Field(default_factory=dict, exclude=True)++ # Completion signal+ _event_completed: asyncio.Event | None = PrivateAttr(default=None)++ @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@propertydef state(self) -> str:return 'completed' if self.event_completed_at else 'started' if self.event_started_at else 'queued'- def result(self, timeout: float = 30.0) -> 'EventResults':- """Return the EventResults object for accessing handler results"""- if not self.results:- raise RuntimeError("Event must be dispatched through an EventBus to use .result()")- return self.results-- def record_result(self, handler: Any, result: Any, eventbus: 'EventBus | None' = None) -> None:- """Record a handler result with metadata"""- # Special handling for EventResults from forwarded events- if isinstance(result, EventResults):- # Don't record the EventResults object itself- # The forwarded event's results are already recorded in the same event- return-- handler_id = str(id(handler))- self.event_results[handler_id] = result- self._handler_metadata[handler_id] = {- 'handler': handler,- 'name': handler.__name__,- 'eventbus': eventbus,- 'eventbus_name': eventbus.name if eventbus else None,- 'eventbus_id': str(id(eventbus)) if eventbus else None- }-- def record_error(self, handler: Any, error: str) -> None:- """Record a handler error"""- self.event_errors[str(id(handler))] = error-- def mark_complete(self) -> None:- """Mark event as completed"""- self.event_completed_at = datetime.now(UTC)- if self._event_completed_signal:- self._event_completed_signal.set()-def model_post_init(self, __context: Any) -> None:"""Initialize completion event and set event schema after model creation"""-if self.event_schema is None:version = get_browser_use_version()self.event_schema = f'{self.__class__.__module__}.{self.__class__.__qualname__}@{version}'- try:- asyncio.get_running_loop() # Only create event if we're in an async context- self._event_completed_signal = asyncio.Event()- except RuntimeError:- self._event_completed_signal = None # Not in async context, skip---class EventResults:- """Lazy mapping of handler results that supports efficient slicing and aggregation"""-- def __init__(self, event: BaseEvent, eventbus: 'EventBus', timeout: float = 30.0, include_wildcards: bool = False):- self.event = event- self.eventbus = eventbus- self.timeout = timeout- try:- self._start_time = asyncio.get_event_loop().time()- except RuntimeError:- # No event loop in sync context, use time.time()- import time- self._start_time = time.time()- self.include_wildcards = include_wildcards-- # Only precompute the first handler for efficient .first() access- event_key = event.event_type- specific_handlers = self.eventbus.handlers.get(event_key, [])- wildcard_handlers = self.eventbus.handlers.get('*', []) if include_wildcards else []-- local_handlers = specific_handlers + wildcard_handlers- self._first_handler = local_handlers[0] if local_handlers else None-- # Track EventBuses that have dispatched this event- self._seen_eventbus_ids: set[str] = {str(id(eventbus))}-- def __getitem__(self, key: str | Any):- """Get by handler ID, handler name, or handler function"""- if callable(key):- # Convert handler function to its ID- key = str(id(key))- if not isinstance(key, str):- raise TypeError("EventResults accepts handler IDs (str), handler names (str), or handler functions")-- # First try as handler ID- if key in self.event.event_results:- return self.event.event_results[key]-- # Then try as handler name - find first matching handler- for handler_id, metadata in self.event._handler_metadata.items():- if metadata['name'] == key and handler_id in self.event.event_results:- return self.event.event_results[handler_id]-- raise KeyError(f"No result found for key: {key}")-- def __await__(self):- """Default to by_handler_id() when awaited directly"""- return self.by_handler_id().__await__()-- async def _wait_for_all_handlers(self) -> None:- """Wait for all handlers across all seen EventBuses to complete"""- start_time = asyncio.get_event_loop().time()-- while True:- # Check if we've timed out- if asyncio.get_event_loop().time() - start_time > self.timeout:- logger.warning(f"Timeout waiting for all handlers after {self.timeout}s")- break-- # Get all eventbus IDs that have registered handlers- seen_handler_buses = set()- for handler_id, metadata in self.event._handler_metadata.items():- if metadata.get('eventbus_id'):- seen_handler_buses.add(metadata['eventbus_id'])-- # Check if all seen buses have registered their handlers- all_buses_handled = self._seen_eventbus_ids.issubset(seen_handler_buses)-- # Check if all registered handlers have results or errors- all_handlers_done = all(- handler_id in self.event.event_results or handler_id in self.event.event_errors- for handler_id in self.event._handler_metadata- )-- if all_buses_handled and all_handlers_done:- break-- # Small delay before checking again- await asyncio.sleep(0.01)-- async def _wait_for_handler(self, handler: Any) -> Any:- """Wait for a specific handler by id"""+ def event_result_update(self, handler: Any=None, eventbus: 'EventBus'=None, **kwargs) -> None:+ """Create or update an EventResult for a handler"""handler_id = str(id(handler))- while handler_id not in self.event.event_results and not self._is_timeout():- await asyncio.sleep(0.001)- return self.event.event_results.get(handler_id)-- async def _get_all_results(self) -> dict[str, Any]:- """Wait for all handlers to complete and return all results"""- await self._wait_for_all_handlers()- return self.event.event_results-- async def first(self, default=None) -> Any:- """Get first handler result - only waits for the first handler"""- if not self._first_handler:- return default- return await self._wait_for_handler(self._first_handler) or default-- async def last(self) -> Any:- """Get last handler result - waits for all handlers to complete"""- await self._wait_for_all_handlers()-- # Get all handlers from metadata in order- handler_items = list(self.event._handler_metadata.items())-- if handler_items:- # Get the last handler- handler_id = handler_items[-1][0]- return self.event.event_results.get(handler_id)-- return None--- async def by_handler_name(self) -> dict[str, Any]:- """Get results keyed by handler name (last handler with each name wins)"""- await self._wait_for_all_handlers()-- results = {}- for handler_id, metadata in self.event._handler_metadata.items():- if handler_id in self.event.event_results:- value = self.event.event_results[handler_id]- if value is not None:- results[metadata['name']] = value- return results-- async def by_handler_id(self) -> dict[str, Any]:- """Get results keyed by handler id string"""- await self._wait_for_all_handlers()-- results = {}- for handler_id in self.event.event_results:- value = self.event.event_results[handler_id]- if value is not None:- results[handler_id] = value- return results-- async def by_eventbus_id(self) -> dict[str, Any]:- """Get results keyed by eventbus id (last handler per eventbus wins)"""- await self._wait_for_all_handlers()+ eventbus = eventbus or (handler and hasattr(handler, '__self__') and handler.__self__) or None+ eventbus_id = 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 '??unknown_handler??',+ eventbus_id=eventbus_id,+ eventbus_name=eventbus and eventbus.name or '??unknown_eventbus??',+ event_parent_id=self.event_id,+ status=kwargs.get('status', 'pending'),+ )- results = {}- for handler_id, metadata in self.event._handler_metadata.items():- if handler_id in self.event.event_results:- eventbus_id = metadata.get('eventbus_id')- value = self.event.event_results[handler_id]- if value is not None and eventbus_id:- results[eventbus_id] = value- return results+ # Update the EventResult with provided kwargs+ self.event_results[handler_id].update(**kwargs)+ self._check_completion()++ def _check_completion(self) -> None:+ """Check if all handlers are done and signal completion"""+ if self.event_completed and not self.event_completed.is_set():+ all_done = all(+ result.status in ('completed', 'error')+ for result in self.event_results.values()+ )+ if all_done:+ self.event_completed_at = datetime.now(UTC)+ self.event_completed.set()- async def by_path(self) -> dict[str, Any]:- """Get results keyed by path: eventbus_name#eventbus_id.handler_name"""- await self._wait_for_all_handlers()+ async def event_results_by_handler_id(self) -> dict[str, Any]:+ """Get results keyed by handler ID"""+ # Wait for completion+ if self.event_completed:+ await self.event_completed.wait()results = {}- for handler_id, metadata in self.event._handler_metadata.items():- if handler_id in self.event.event_results:- if metadata.get('eventbus_name') and metadata.get('eventbus_id'):- path = f"{metadata['eventbus_name']}#{metadata['eventbus_id']}.{metadata['name']}"- value = self.event.event_results[handler_id]- if value is not None:- results[path] = value+ for handler_id, event_result in self.event_results.items():+ if event_result.status == 'completed' and event_result.result is not None:+ results[handler_id] = event_result.resultreturn results- async def values(self) -> list[Any]:- """Get all results as list"""- await self._wait_for_all_handlers()-- # Return results in handler registration order- results = []- for handler_id in self.event._handler_metadata:- if handler_id in self.event.event_results:- value = self.event.event_results[handler_id]- if value is not None:- results.append(value)- return results-- async def flat_dict(self) -> dict[str, Any]:- """Merge results into single dict"""- await self._wait_for_all_handlers()+ async def event_results_flat_dict(self) -> dict[str, Any]:+ """Merge all dict results into single dict"""++ await self.event_completed.wait()merged = {}- for handler_id, metadata in self.event._handler_metadata.items():- if handler_id in self.event.event_results:- result = self.event.event_results[handler_id]- if result is not None:- if not isinstance(result, dict):- handler_name = metadata.get('name', 'unknown')- raise TypeError(f"Handler '{handler_name}' returned {type(result).__name__} instead of dict")- merged.update(result)+ 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 not isinstance(event_result.result, dict):+ raise TypeError(f"Handler '{event_result.handler_name}' returned {type(event_result.result).__name__} instead of dict")+ merged.update(event_result.result) # update the merged dict with the contents of the result dictreturn merged- async def flat_list(self) -> list[Any]:- """Merge results into single list"""- await self._wait_for_all_handlers()+ async def event_results_flat_list(self) -> list[Any]:+ """Merge all list results into single list"""++ await self.event_completed.wait()merged = []- for handler_id, metadata in self.event._handler_metadata.items():- if handler_id in self.event.event_results:- result = self.event.event_results[handler_id]- if result is not None:- if not isinstance(result, list):- handler_name = metadata.get('name', 'unknown')- raise TypeError(f"Handler '{handler_name}' returned {type(result).__name__} instead of list")- merged.extend(result)+ 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.extend(event_result.result) # append the contents of the list to the merged list+ else:+ merged.append(event_result.result) # append individual item to the merged listreturn merged++ async def event_result(self, timeout: float = 30.0) -> Any:+ results = await self.event_results_flat_list()+ return results[0] if results else None++ async def result(self, timeout: float = 30.0) -> 'BaseEvent':+ """Wait for event to complete and return self"""+ if self.event_completed:+ await self.event_completed.wait()+ return self+++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+ 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 _is_timeout(self) -> bool:- """Check timeout"""- try:- current_time = asyncio.get_event_loop().time()- except RuntimeError:- # No event loop in sync context, use time.time()- import time- current_time = time.time()- return current_time - self._start_time > self.timeout++ def __await__(self):+ """Wait for this result to complete and return the result or raise error"""+ async def wait_and_return():+ await self.completed.wait()++ if self.status == 'error' and self.error:+ raise RuntimeError(f"Handler {self.handler_name} failed: {self.error}")++ return self.result++ return wait_and_return().__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.pyindex 86bd35d84..33ec6e797 100644--- a/browser_use/eventbus/service.py+++ b/browser_use/eventbus/service.py@@ -13,7 +13,7 @@ import anyiofrom pydantic import BaseModelfrom uuid_extensions import uuid7str-from browser_use.eventbus.models import BaseEvent, EventResults, UUIDStr+from browser_use.eventbus.models import BaseEvent, UUIDStrlogger = logging.getLogger(__name__)@@ -35,29 +35,28 @@ class EventBus:"""name: str- event_queue: asyncio.Queue[BaseEvent]+ event_queue: asyncio.Queue[BaseEvent] | Noneevent_history: dict[UUIDStr, BaseEvent]handlers: dict[str, list[EventHandler]]wal_path: Path | None = None- parallel_handlers: bool = True+ parallel_handlers: bool = Falseid: UUIDStr_is_running: bool = False_runloop_task: asyncio.Task | None = None- _runloop_lock: asyncio.Lock- _on_idle: asyncio.Event+ _runloop_lock: asyncio.Lock | None = None+ _on_idle: asyncio.Event | None = None- def __init__(self, name: str | None = None, wal_path: Path | str | None = None, parallel_handlers: bool = True):+ def __init__(self, name: str | 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 = asyncio.Queue()+ self.event_queue = Noneself.event_history = {}self.handlers = defaultdict(list)self.parallel_handlers = parallel_handlers- self._runloop_lock = asyncio.Lock()- self._on_idle = asyncio.Event()- self._on_idle.set() # Start in idle state+ self._runloop_lock = None+ self._on_idle = None# Set up WAL path and create parent directory if neededif wal_path:@@ -70,12 +69,12 @@ class EventBus: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+ self._is_running = False+ if self._runloop_task and not self._runloop_task.done():+ try:+ self._runloop_task.cancel()+ except RuntimeError:+ passdef __str__(self) -> str:return self.name@@ -138,39 +137,33 @@ class EventBus:self.handlers[event_key].append(handler)logger.debug(f"✅ {self} Registered handler {handler_name} for event {event_key}")- # Auto-start if needed- if not self._is_running:+ # Auto-start if needed (but not for the default logger)+ if not self._is_running and handler_name != '_default_log_handler':self._start()- def dispatch(self, event: BaseEvent, timeout: float = 30.0) -> EventResults:+ def dispatch(self, event: BaseEvent, timeout: float = 30.0) -> BaseEvent:"""- Enqueue an event for processing and return EventResults for accessing responses.+ Enqueue an event for processing and return the event.(Auto-starts the EventBus's async _run_loop() if not already running)- Returns EventResults which can be awaited directly or used to access specific results.- Access the original event via EventResults.event.+ Returns the event which can be awaited using event.result() or other query methods."""assert event.event_id, 'Missing event.event_id: UUIDStr = uuid7str()'assert event.event_created_at, 'Missing event.queued_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 parent_event_id from context if not already set- if event.parent_event_id is None:+ # 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.parent_event_id = current_event.event_id+ event.event_parent_id = current_event.event_id# Add this EventBus to the event_path if not already thereif 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)-- # Store reference to this EventBus for result() method- if not event._eventbus:- event._eventbus = self-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), (@@ -183,20 +176,19 @@ class EventBus:self._start()# Put event in queue synchronously using put_nowait- try:- logger.debug(f'📋 {self} Dispatching event {event.event_type} to queue')- self.event_queue.put_nowait(event)- except asyncio.QueueFull:- logger.error(f'⚠️ {self} Event queue is full! Dropping event {event.event_type}:\n{event.model_dump_json()}')-- # Create or update the single EventResults instance- if not event.results:- event.results = EventResults(event, self, timeout)- else:- # Just update the seen eventbus IDs- event.results._seen_eventbus_ids.add(str(id(self)))+ if self.event_queue:+ try:+ logger.debug(f'📋 {self} Dispatching event {event.event_type} to queue')+ self.event_queue.put_nowait(event)+ except asyncio.QueueFull:+ logger.error(f'⚠️ {self} Event queue is full! Dropping event {event.event_type}:\n{event.model_dump_json()}')++ # Record pending results for all applicable handlers+ applicable_handlers = self._get_applicable_handlers(event)+ for handler in applicable_handlers.values():+ event.event_result_update(handler=handler, eventbus=self, status='pending')- return event.results+ return eventasync def expect(self,@@ -253,8 +245,15 @@ class EventBus:if not self._is_running:try:loop = asyncio.get_running_loop()- self._is_running = True+ # 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.set() # Start in idle state+ # Create and start the run loop taskself._runloop_task = loop.create_task(self._run_loop())+ self._is_running = Trueexcept RuntimeError:pass # No event loop - will start when one becomes available@@ -269,9 +268,10 @@ class EventBus:if timeout is not None:await self.wait_until_idle(timeout=timeout)- if self.event_queue.qsize() or self.events_queued or self.events_started:+ queue_size = self.event_queue.qsize() if self.event_queue else 0+ if queue_size or self.events_queued or self.events_started:logger.warning(- f'⚠️ {self} stopping with pending events: Queued {self.event_queue.qsize()} | Pending {len(self.events_queued)} | Processing {len(self.events_started)} | Completed {len(self.events_completed)}'+ f'⚠️ {self} stopping with pending events: Queued {queue_size} | Pending {len(self.events_queued)} | Processing {len(self.events_started)} | Completed {len(self.events_completed)}')# Force shutdown@@ -295,22 +295,29 @@ class EventBus:# 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'⌛️ {self} Timeout waiting for event bus to be idle after {timeout}s (processing: {len(self.events_started)})'- )+ if self._on_idle:+ try:+ 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"""while self._is_running:try:+ # Ensure we have async objects+ if not self.event_queue:+ logger.error(f'❌ {self} Event queue not initialized in _run_loop')+ break+# 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()+ if self._on_idle:+ if self.event_queue.empty() and len(self.events_started) == 0:+ self._on_idle.set()+ else:+ self._on_idle.clear()try:await self._run_loop_step()@@ -329,27 +336,28 @@ class EventBus:event = event or await asyncio.wait_for(self.event_queue.get(), timeout=0.1)# Clear idle state when we get an event- self._on_idle.clear()+ if self._on_idle:+ self._on_idle.clear()# Process the event- async with self._runloop_lock:- event.event_started_at = datetime.now(UTC)-- # Execute all handlers for this event- applicable_handlers = self._get_applicable_handlers(event)+ if self._runloop_lock:+ async with self._runloop_lock:+ event.event_started_at = datetime.now(UTC)- await self._execute_handlers(event, handlers=applicable_handlers)+ # Execute all handlers for this event+ applicable_handlers = self._get_applicable_handlers(event)+ await self._execute_handlers(event, handlers=applicable_handlers)- # Mark event as completed- event.mark_complete()+ # Mark event as completed+ event.event_completed_at = datetime.now(UTC)- # 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}')+ # 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()+ # Mark task as done+ self.event_queue.task_done()return eventdef _get_applicable_handlers(self, event: BaseEvent) -> dict[str, EventHandler]:@@ -392,9 +400,9 @@ class EventBus:for handler_id, (task, handler) in handler_tasks.items():try:result = await task- event.record_result(handler, result, self)+ event.event_result_update(handler=handler, eventbus=self, result=result)except Exception as e:- event.record_error(handler, str(e))+ event.event_result_update(handler=handler, eventbus=self, error=str(e))logger.error(f'❌ {self} Handler {handler.__name__} failed for event {event.event_id}: {type(e).__name__} {e}\n{event.model_dump()}')@@ -402,10 +410,17 @@ class EventBus:# otherwise, execute handlers serially, wait until each one completes before moving on to the nextfor handler_id, handler in applicable_handlers.items():try:+ # Mark handler as started+ event.event_result_update(handler=handler, eventbus=self, status='started')++ # Execute the handlerresult = await self._execute_sync_or_async_handler(event, handler)- event.record_result(handler, result, self)++ # Record successful result+ event.event_result_update(handler=handler, eventbus=self, result=result)except Exception as e:- event.record_error(handler, str(e))+ # Record error+ event.event_result_update(handler=handler, eventbus=self, error=str(e))logger.error(f'❌ {self} Handler {handler.__name__} failed for event {event.event_id}: {type(e).__name__} {e}\n{event.model_dump()}')diff --git a/tests/ci/test_eventbus.py b/tests/ci/test_eventbus.pyindex 6f687fcf8..376563fd0 100644--- a/tests/ci/test_eventbus.py+++ b/tests/ci/test_eventbus.py@@ -24,7 +24,6 @@ from pydantic import Fieldfrom browser_use.agent.cloud_events import CreateAgentTaskEventfrom browser_use.eventbus import BaseEvent, EventBus-from browser_use.eventbus.models import EventResults# Test event models@@ -129,7 +128,15 @@ class TestEventEnqueueing:processed = await result.result()assert processed.event_started_at is not Noneassert processed.event_completed_at is not None- assert processed.event_results['_default_log_handler'] == 'logged'+ # Check that we have results from the default handler+ assert len(processed.event_results) == 1+ # Get the result from the default handler (by checking handler name)+ default_handler_result = None+ for event_result in processed.event_results.values():+ if event_result.handler_name == '_default_log_handler':+ default_handler_result = event_result.result+ break+ assert default_handler_result == 'logged'# Check event historyassert len(eventbus.event_history) == 1@@ -215,8 +222,10 @@ class TestHandlerRegistration:assert len(end_times) == 2# Check results- assert event.event_results['slow_handler_1'] == 'handler1'- assert event.event_results['slow_handler_2'] == 'handler2'+ 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"""@@ -292,9 +301,13 @@ class TestErrorHandling:event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1')).result()# Verify error capture and isolation- assert 'failing_handler' in event.event_errors- assert 'Expected to fail' in event.event_errors['failing_handler']- assert event.event_results['working_handler'] == 'worked'+ 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']@@ -317,7 +330,7 @@ class TestBatchOperations:assert len(results) == 3for result in results:assert result.event_completed_at is not None- assert '_default_log_handler' in result.event_results+ assert any(r.handler_name == '_default_log_handler' for r in result.event_results.values())class TestWriteAheadLog:@@ -1013,10 +1026,10 @@ class TestExpectMethod:class TestEventResults:- """Test the new EventResults functionality"""+ """Test the event results functionality on BaseEvent"""async def test_dispatch_returns_event_results(self, eventbus):- """Test that dispatch now returns EventResults"""+ """Test that dispatch returns BaseEvent with result methods"""# Register a specific handlerasync def test_handler(event):return 'test_result'@@ -1024,10 +1037,12 @@ class TestEventResults:eventbus.on('UserActionEvent', test_handler)result = eventbus.dispatch(UserActionEvent(action='test', user_id='u1'))- assert isinstance(result, EventResults)+ assert isinstance(result, BaseEvent)- # Can be awaited directly (returns by_handler_id dict)- all_results = await result+ # Wait for completion+ await result.result()+ # Get results by handler ID+ all_results = await result.event_results_by_handler_id()assert isinstance(all_results, dict)# Should contain both test_handler and default log handler resultsassert len(all_results) == 2@@ -1036,11 +1051,12 @@ class TestEventResults:# Test with no specific handlers (only wildcard)result_no_handlers = eventbus.dispatch(BaseEvent(event_type='NoHandlersEvent'))- assert await result_no_handlers.first() is None # No specific handlers-- # Test including wildcards explicitly- result_with_wildcards = EventResults(result_no_handlers.event, eventbus, include_wildcards=True)- assert await result_with_wildcards.first() == 'logged' # Wildcard handler result+ await result_no_handlers.result()+ # Should only have the default log handler+ assert len(result_no_handlers.event_results) == 1+ default_result = next((r for r in result_no_handlers.event_results.values() if r.handler_name == '_default_log_handler'), None)+ assert default_result is not None+ assert default_result.result == 'logged'async def test_event_results_indexing(self, eventbus):"""Test indexing by handler name and ID"""@@ -1066,20 +1082,19 @@ class TestEventResults:hr = eventbus.dispatch(BaseEvent(event_type='TestEvent'))# Wait for all handlers to complete- await hr+ await hr.result()- # Index by handler name- assert hr['handler1'] == 'first'- assert hr['handler2'] == 'second'- assert hr['handler3'] == 'third'+ # Get results by handler name+ handler1_result = next((r for r in hr.event_results.values() if r.handler_name == 'handler1'), None)+ handler2_result = next((r for r in hr.event_results.values() if r.handler_name == 'handler2'), None)+ handler3_result = next((r for r in hr.event_results.values() if r.handler_name == 'handler3'), None)- # Index by handler function- assert hr[handler1] == 'first'- assert hr[handler2] == 'second'- assert hr[handler3] == 'third'+ 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_first_last_methods(self, eventbus):- """Test first() and last() methods"""+ async def test_event_results_access(self, eventbus):+ """Test accessing event results"""async def early_handler(event):return 'early'@@ -1090,19 +1105,21 @@ class TestEventResults:eventbus.on('TestEvent', early_handler)eventbus.on('TestEvent', late_handler)- results = eventbus.dispatch(BaseEvent(event_type='TestEvent'))-- # first() returns first handler result- assert await results.first() == 'early'+ result = eventbus.dispatch(BaseEvent(event_type='TestEvent'))+ await result.result()- # last() returns last handler result- assert await results.last() == 'late'+ # 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 handlerseventbus.handlers['EmptyEvent'] = []results_empty = eventbus.dispatch(BaseEvent(event_type='EmptyEvent'))- assert await results_empty.first(default='none') == 'none'- assert await results_empty.last() is None+ await results_empty.result()+ assert len(results_empty.event_results) == 0async def test_by_handler_name(self, eventbus):"""Test by_handler_name() with duplicate names"""diff --git a/tests/ci/test_parent_event_tracking.py b/tests/ci/test_parent_event_tracking.pyindex c23fa708d..41a3f4059 100644--- a/tests/ci/test_parent_event_tracking.py+++ b/tests/ci/test_parent_event_tracking.py@@ -39,7 +39,7 @@ class TestParentEventTracking:"""Test automatic parent event ID tracking"""async def test_basic_parent_tracking(self, eventbus):- """Test that child events automatically get parent_event_id"""+ """Test that child events automatically get event_parent_id"""child_events = []async def parent_handler(event: ParentEvent) -> str:@@ -61,10 +61,10 @@ class TestParentEventTracking:# Verify parent processedassert await parent_result.get('parent_handler') == 'parent_handled'- # Verify child has parent_event_id set+ # Verify child has event_parent_id setassert len(child_events) == 1child = child_events[0]- assert child.parent_event_id == parent.event_id+ assert child.event_parent_id == parent.event_idasync def test_multi_level_parent_tracking(self, eventbus):"""Test parent tracking across multiple levels"""@@ -99,9 +99,9 @@ class TestParentEventTracking:await eventbus.wait_until_idle()# Verify the parent chain- assert events_by_level['parent'].parent_event_id is None # Root has no parent- assert events_by_level['child'].parent_event_id == parent.event_id- assert events_by_level['grandchild'].parent_event_id == events_by_level['child'].event_id+ assert events_by_level['parent'].event_parent_id is None # Root has no parent+ assert events_by_level['child'].event_parent_id == parent.event_id+ assert events_by_level['grandchild'].event_parent_id == events_by_level['child'].event_idasync def test_multiple_children_same_parent(self, eventbus):"""Test multiple child events from same parent"""@@ -126,7 +126,7 @@ class TestParentEventTracking:# All children should have same parentassert len(child_events) == 3for child in child_events:- assert child.parent_event_id == parent.event_id+ assert child.event_parent_id == parent.event_idasync def test_parallel_handlers_parent_tracking(self, eventbus):"""Test parent tracking with parallel handlers"""@@ -159,17 +159,17 @@ class TestParentEventTracking:# Both children should have same parent despite parallel executionassert len(events_from_handlers['h1']) == 1assert len(events_from_handlers['h2']) == 1- assert events_from_handlers['h1'][0].parent_event_id == parent.event_id- assert events_from_handlers['h2'][0].parent_event_id == parent.event_id+ assert events_from_handlers['h1'][0].event_parent_id == parent.event_id+ assert events_from_handlers['h2'][0].event_parent_id == parent.event_idasync def test_explicit_parent_not_overridden(self, eventbus):- """Test that explicitly set parent_event_id is not overridden"""+ """Test that explicitly set event_parent_id is not overridden"""captured_child = Noneasync def parent_handler(event: ParentEvent) -> str:nonlocal captured_child- # Create child with explicit parent_event_id- child = ChildEvent(data='explicit', parent_event_id='explicit_parent_id')+ # Create child with explicit event_parent_id+ child = ChildEvent(data='explicit', event_parent_id='explicit_parent_id')eventbus.dispatch(child)captured_child = childreturn 'dispatched'@@ -181,10 +181,10 @@ class TestParentEventTracking:await eventbus.wait_until_idle()- # Explicit parent_event_id should be preserved+ # Explicit event_parent_id should be preservedassert captured_child is not None- assert captured_child.parent_event_id == 'explicit_parent_id'- assert captured_child.parent_event_id != parent.event_id+ assert captured_child.event_parent_id == 'explicit_parent_id'+ assert captured_child.event_parent_id != parent.event_idasync def test_cross_eventbus_parent_tracking(self):"""Test parent tracking across multiple EventBuses"""@@ -220,8 +220,8 @@ class TestParentEventTracking:_, parent_event, child_event = captured_events[0]_, received_child = captured_events[1]- assert child_event.parent_event_id == parent.event_id- assert received_child.parent_event_id == parent.event_id+ assert child_event.event_parent_id == parent.event_id+ assert received_child.event_parent_id == parent.event_idfinally:await bus1.stop()@@ -247,7 +247,7 @@ class TestParentEventTracking:# Parent tracking should work even with sync handlersassert len(child_events) == 1- assert child_events[0].parent_event_id == parent.event_id+ assert child_events[0].event_parent_id == parent.event_idasync def test_error_handler_parent_tracking(self, eventbus):"""Test parent tracking when handler errors occur"""@@ -275,10 +275,10 @@ class TestParentEventTracking:await eventbus.wait_until_idle()- # Both children should have parent_event_id despite error+ # Both children should have event_parent_id despite errorassert len(child_events) == 2for child in child_events:- assert child.parent_event_id == parent.event_id+ assert child.event_parent_id == parent.event_idif __name__ == '__main__':