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
rename .emit to .dispatch and prefix event params to prevent clashes
Nick Sweeting23d3bf420531
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 2ec242275..019261eda 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -959,7 +959,7 @@ class Agent(Generic[Context]):# Emit CreateAgentStepEventstep_event = CreateAgentStepEvent.from_agent_step(self, model_output, result, actions_data, browser_state_summary)- self.eventbus.emit(step_event)+ self.eventbus.dispatch(step_event)@time_execution_async('--handle_step_error (agent)')async def _handle_step_error(self, error: Exception) -> list[ActionResult]:@@ -1349,10 +1349,10 @@ class Agent(Generic[Context]):self._task_start_time = self._session_start_time # Initialize task start time# Emit CreateAgentSessionEvent at the START of run()- self.eventbus.emit(CreateAgentSessionEvent.from_agent(self))+ self.eventbus.dispatch(CreateAgentSessionEvent.from_agent(self))# Emit CreateAgentTaskEvent at the START of run()- self.eventbus.emit(CreateAgentTaskEvent.from_agent(self))+ self.eventbus.dispatch(CreateAgentTaskEvent.from_agent(self))# Execute initial actions if providedif self.initial_actions:@@ -1452,7 +1452,7 @@ class Agent(Generic[Context]):# not when they are completed# Emit UpdateAgentTaskEvent at the END of run() with final task state- self.eventbus.emit(UpdateAgentTaskEvent.from_agent(self))+ self.eventbus.dispatch(UpdateAgentTaskEvent.from_agent(self))# Generate GIF if needed before stopping event busif self.settings.generate_gif:@@ -1464,7 +1464,7 @@ class Agent(Generic[Context]):# Emit output file generated event for GIFoutput_event = await CreateAgentOutputFileEvent.from_agent_and_file(self, output_path)- self.eventbus.emit(output_event)+ self.eventbus.dispatch(output_event)# Stop the event bus gracefully, waiting for all events to be processedawait self.eventbus.stop(timeout=5.0)diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 2cccc810b..58a505333 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -379,9 +379,9 @@ class BrowserSession(BaseModel):if self.browser_pid:try:proc = psutil.Process(pid=self.browser_pid)- cmd = proc.cmdline()[0]+ executable_path = proc.cmdline()[0]proc.terminate()- logger.info(f' ↳ {self} Killed browser subprocess with browser_pid={self.browser_pid} {cmd}')+ logger.info(f' ↳ {self} Killed browser_pid={self.browser_pid} {_log_pretty_path(executable_path)}')self.browser_pid = Noneexcept Exception as e:if 'NoSuchProcess' not in type(e).__name__:@@ -663,9 +663,7 @@ class BrowserSession(BaseModel):if new_chrome_procs and not self.browser_pid:self.browser_pid = new_chrome_procs[0].pid- logger.info(- f' ↳ {self} Spawned browser subprocess with browser_pid={self.browser_pid} {_log_pretty_path(new_chrome_procs[0].cmdline()[0])}'- )+ logger.info(f' ↳ {self} Spawned browser_pid={self.browser_pid} {_log_pretty_path(new_chrome_procs[0].cmdline()[0])}')logger.debug(' '.join(new_chrome_procs[0].cmdline())) # print the entire launch command for debuggingself._set_browser_keep_alive(False) # close the browser at the end because we launched itdiff --git a/browser_use/eventbus/models.py b/browser_use/eventbus/models.pyindex f8dd7887e..14ae41ef6 100644--- a/browser_use/eventbus/models.py+++ b/browser_use/eventbus/models.py@@ -27,35 +27,41 @@ 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')- queued_at: datetime = Field(default_factory=lambda: datetime.now(UTC))# Completion tracking fields- started_at: datetime | None = Field(default=None)- completed_at: datetime | None = Field(default=None)- results: dict[str, Any] = Field(default_factory=dict) # {handler_name: result}- errors: dict[str, str] = Field(default_factory=dict) # {handler_name: error_str}- _completion_event: asyncio.Event | None = PrivateAttr(default=None)+ event_created_at: datetime = Field(+ default_factory=lambda: datetime.now(UTC), description='Timestamp when event was queued/created'+ )+ 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')+ event_results: dict[str, Any] = Field(+ default_factory=dict, exclude=True, description='Handler results {handler_name: result}'+ )+ event_errors: dict[str, str] = Field(+ default_factory=dict, exclude=True, description='Handler errors {handler_name: error_str}'+ )+ _event_completed_signal: asyncio.Event | None = PrivateAttr(default=None)@propertydef state(self) -> str:- return 'completed' if self.completed_at else 'started' if self.started_at else 'queued'+ return 'completed' if self.event_completed_at else 'started' if self.event_started_at else 'queued'async def result(self):"""Wait for completion and return self with results"""- if self._completion_event:- await self._completion_event.wait()+ if self._event_completed_signal:+ await self._event_completed_signal.wait()return selfdef record_results(self, results: dict[str, Any] | None = None, complete: bool = True) -> None:"""Update the event results and optionally mark it as completed"""- self.results = {- **(self.results or {}),+ self.event_results = {+ **(self.event_results or {}),**(results or {}),}if complete:- self.completed_at = datetime.now(UTC)- if self._completion_event:- self._completion_event.set()+ 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"""@@ -66,6 +72,6 @@ class BaseEvent(BaseModel):try:asyncio.get_running_loop() # Only create event if we're in an async context- self._completion_event = asyncio.Event()+ self._event_completed_signal = asyncio.Event()except RuntimeError:- self._completion_event = None # Not in async context, skip+ self._event_completed_signal = None # Not in async context, skipdiff --git a/browser_use/eventbus/service.py b/browser_use/eventbus/service.pyindex be0d173ac..f955989c5 100644--- a/browser_use/eventbus/service.py+++ b/browser_use/eventbus/service.py@@ -44,7 +44,7 @@ class EventBus:def __init__(self, name: str | None = None, wal_path: Path | str | None = None, parallel_handlers: bool = True):self.id = uuid7str()- self.name = name or f'EventBus{self.id[-8:]}'+ 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_history = {}@@ -72,32 +72,37 @@ class EventBus:# No event loop, nothing to cleanpass+ def __str__(self) -> str:+ return self.name++ def __repr__(self) -> str:+ return self.name+@propertydef events_queued(self) -> list[BaseEvent]:"""Get events that haven't started processing yet"""- return [event for event in self.event_history.values() if event.started_at is None]+ return [event for event in self.event_history.values() if event.event_started_at is None]@propertydef events_started(self) -> list[BaseEvent]:"""Get events currently being processed"""- return [event for event in self.event_history.values() if event.started_at and not event.completed_at]+ return [event for event in self.event_history.values() if event.event_started_at and not event.event_completed_at]@propertydef events_completed(self) -> list[BaseEvent]:"""Get events that have completed processing"""- return [event for event in self.event_history.values() if event.completed_at is not None]+ return [event for event in self.event_history.values() if event.event_completed_at is not None]def on(self, event_pattern: str | type[BaseModel], handler: EventHandler) -> None:- """Subscribe to events matching a pattern, event type name, or event model class.- Use event_pattern='*' to subscribe to all events. (can be used to forward all events to another EventBus)-- Similar to EventListener.addEventListener() or eventbus.subscribe() in other languages.+ """+ 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 typeeventbus.on(TaskStartedEvent, handler) # Event model classeventbus.on('*', handler) # Subscribe to all events- eventbus.on('*', other_eventbus.emit) # Forward all events to another EventBus+ eventbus.on('*', other_eventbus.dispatch) # Forward all events to another EventBus"""# Allow both sync and async handlersif event_pattern == '*':@@ -110,7 +115,7 @@ class EventBus:# Subscribe by string event typeself.handlers[str(event_pattern)].append(handler)- def emit(self, event: BaseEvent) -> BaseEvent:+ def dispatch(self, event: BaseEvent) -> BaseEvent:"""Enqueue an event for processing by the handlers. Returns awaitable event object.(Auto-starts the EventBus's async _run_loop() if not already running)@@ -118,7 +123,7 @@ class EventBus:Similar to JS EventListener.dispatchEvent() or eventbus.dispatch() in other languages."""assert event.event_id, 'Missing event.event_id: UUIDStr = uuid7str()'- assert event.queued_at, 'Missing event.queued_at: datetime = datetime.now(UTC)'+ 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)'@@ -130,7 +135,7 @@ class EventBus: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 or function names, got: {event.event_path}'+ f'Event.event_path must be a list of valid EventBus names, got: {event.event_path}')# Add event to history@@ -140,11 +145,11 @@ class EventBus:# Put event in queue synchronously using put_nowaittry:+ logger.debug(f'📋 {self} Dispatching event {event.event_type} to queue')self.event_queue.put_nowait(event)except asyncio.QueueFull:- logger.error(f'⚠️ Event queue is full! Dropping event {event.event_type}:\n{event.model_dump_json()}')+ logger.error(f'⚠️ {self} Event queue is full! Dropping event {event.event_type}:\n{event.model_dump_json()}')- logger.debug(f'Emitting event {event.event_type} to queue')return eventdef _start(self) -> None:@@ -163,17 +168,18 @@ class EventBus:return# Log current state- logger.debug(- f'EventBus stopping: Queued {self.event_queue.qsize()} | Pending {len(self.events_queued)} | Processing {len(self.events_started)} | Completed {len(self.events_completed)}'- )# Wait for completion if timeout specifiedif timeout is not None:await self.wait_until_idle(timeout=timeout)+ if self.event_queue.qsize() 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)}'+ )+# Force shutdownself._is_running = False-if self._runloop_task:self._runloop_task.cancel()try:@@ -181,10 +187,7 @@ class EventBus:except asyncio.CancelledError:pass- if timeout is not None:- logger.debug(f'{self.name} stopped gracefully')- else:- logger.debug(f'{self.name} stopped immediately')+ logger.debug(f'⏹ {self} stopped gracefully' if timeout is not None else f'🛑 {self} stopped immediately')async def wait_until_idle(self, timeout: float | None = None) -> None:"""Wait until the event bus is idle (no events being processed)"""@@ -199,7 +202,9 @@ class EventBus:try:await asyncio.wait_for(self._on_idle.wait(), timeout=timeout)except TimeoutError:- logger.warning(f'Timeout waiting for event bus to be idle after {timeout}s (processing: {len(self.events_started)})')+ 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"""@@ -218,7 +223,7 @@ class EventBus:except asyncio.CancelledError:breakexcept Exception as e:- logger.exception(f'{self.name} Error in event loop: {type(e).__name__} {e}')+ logger.exception(f'❌ {self} Error in event loop: {type(e).__name__} {e}')# Continue running even if there's an errorasync def _run_loop_step(self, event: BaseEvent | None = None) -> BaseEvent:@@ -232,8 +237,7 @@ class EventBus:# Process the eventasync with self._runloop_lock:- # Record start time- event.started_at = datetime.now(UTC)+ event.event_started_at = datetime.now(UTC)# Execute all handlers for this eventapplicable_handlers = self._get_applicable_handlers(event)@@ -266,7 +270,7 @@ class EventBus:filtered_handlers = {}for handler in applicable_handlers:if self._would_create_loop(event, handler):- # logger.debug(f'Skipping {handler.__name__} to prevent loop for {event.event_type}')+ logger.debug(f'Skipping {handler.__name__} to prevent loop for {event.event_type}')continueelse:filtered_handlers[handler.__name__] = handler@@ -275,7 +279,7 @@ class EventBus:async def _execute_handlers(self, event: BaseEvent, handlers: dict[str, EventHandler] | 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)+ applicable_handlers = handlers if (handlers is not None) else self._get_applicable_handlers(event)if not applicable_handlers:return@@ -292,8 +296,10 @@ class EventBus:result = await taskevent.record_results({handler_name: result}, complete=False)except Exception as e:- event.errors[handler_name] = str(e)- logger.error(f'Handler {handler_name} failed for event {event.event_id}: {e}')+ event.event_errors[handler_name] = str(e)+ logger.error(+ f'❌ {self} Handler {handler_name} failed for event {event.event_id}: {type(e).__name__} {e}\n{event.model_dump()}'+ )else:# otherwise, execute handlers serially, wait until each one completes before moving on to the nextfor handler_name, handler in applicable_handlers.items():@@ -310,28 +316,25 @@ class EventBus:loop = asyncio.get_event_loop()return await loop.run_in_executor(None, handler, event)except Exception as e:- logger.exception(f'Error in handler {handler.__name__} for event {event.event_id}')+ logger.exception(+ f'❌ {self} Error in handler {handler.__name__} for event {event.event_id}: {type(e).__name__} {e}\n{event.model_dump()}'+ )raise@staticmethoddef _would_create_loop(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)"""- # If handler is another EventBus.emit method- if hasattr(handler, '__self__') and isinstance(handler.__self__, EventBus):+ # If handler is another EventBus.dispatch method+ if hasattr(handler, '__self__') and isinstance(handler.__self__, EventBus) and handler.__name__ == 'dispatch':target_bus = handler.__self__return target_bus.name in event.event_pathreturn False- @staticmethod- async def _default_log_handler(event: BaseEvent) -> str:+ async def _default_log_handler(self, event: BaseEvent) -> str:"""Default handler that logs all events"""- try:- # Try to serialize the event- event_json = event.model_dump_json()- logger.debug(f'Event processed: {event.event_type} [{event.event_id}] - {event_json}')- except Exception as e:- # If serialization fails (e.g., circular reference), log without the full JSON- logger.debug(f'Event processed: {event.event_type} [{event.event_id}] - (serialization failed: {e})')+ logger.debug(+ f'✅ {self} Event processed: {event.event_type} [{event.event_id}] -> {len(event.event_results)} results @ {event.event_completed_at}'+ )return 'logged'async def _default_wal_handler(self, event: BaseEvent) -> str:@@ -350,5 +353,7 @@ class EventBus:return 'appended'except Exception as e:- logger.error(f'Failed to persist event {event.event_id} to WAL: {e}')+ logger.error(+ f'❌ {self} Failed to save event {event.event_id} to WAL file: {type(e).__name__} {e}\n{event.model_dump()}'+ )return 'failed'diff --git a/tests/ci/test_agent_emits_cloud_events.py b/tests/ci/test_agent_emits_cloud_events.pyindex dee734c2b..7a8937669 100644--- a/tests/ci/test_agent_emits_cloud_events.py+++ b/tests/ci/test_agent_emits_cloud_events.py@@ -111,7 +111,7 @@ def event_collector():collection_time = time.time()self.events.append(event)self.event_order.append(event.event_type)- self.event_timestamps.append((event.event_type, event.queued_at, collection_time))+ self.event_timestamps.append((event.event_type, event.event_created_at, collection_time))return 'collected'def get_events_by_type(self, event_type: str) -> list[BaseEvent]:@@ -188,13 +188,15 @@ class TestAgentCloudEvents:update_event = next(e for e in event_collector.events if e.event_type == 'UpdateAgentTask')# Session should be created before Task (foreign key constraint)- assert session_event.queued_at <= task_event.queued_at, (+ assert session_event.event_created_at <= task_event.event_created_at, ('Session event should be emitted before or at same time as Task event')# Task should be created before Step (foreign key constraint)- assert task_event.queued_at <= step_event.queued_at, 'Task event should be emitted before or at same time as Step event'+ assert task_event.event_created_at <= step_event.event_created_at, (+ 'Task event should be emitted before or at same time as Step event'+ )# All create events should happen before update- assert step_event.queued_at <= update_event.queued_at, (+ assert step_event.event_created_at <= update_event.event_created_at, ('Step event should be emitted before or at same time as UpdateTask event')@@ -209,7 +211,7 @@ class TestAgentCloudEvents:assert task_event.id # Should have task IDassert task_event.agent_session_id == session_event.idassert task_event.task == 'Test task'- assert task_event.started_at is not None+ assert task_event.event_started_at is not Noneassert task_event.stopped is Falseassert task_event.paused is Falseassert task_event.done_output is None # Not done yet at creation@@ -580,7 +582,7 @@ class TestCloudEventValidation:assert isinstance(event, BaseEvent)assert event.event_type is not Noneassert event.event_id is not None- assert event.queued_at is not None+ assert event.event_created_at is not Noneassert isinstance(event.event_path, list)# Check event_id is a valid UUID string@@ -659,7 +661,7 @@ class TestEventBusIntegration:# Emit all eventsfor event in events:- bus.emit(event)+ bus.dispatch(event)# Wait for processingawait bus.wait_until_idle()diff --git a/tests/ci/test_eventbus.py b/tests/ci/test_eventbus.pyindex c79018037..90c8fd9b1 100644--- a/tests/ci/test_eventbus.py+++ b/tests/ci/test_eventbus.py@@ -89,7 +89,7 @@ class TestEventBusBasics:assert bus._runloop_task is None# Auto-start by emitting an event- bus.emit(UserActionEvent(action='test', user_id='user123'))+ bus.dispatch(UserActionEvent(action='test', user_id='user123'))await bus.wait_until_idle()# Should be running after auto-start@@ -112,7 +112,7 @@ class TestEventEnqueueing:"""Test event emission in async and sync contexts, and result() pattern"""# Test async emissionevent = UserActionEvent(action='login', user_id='user123')- result = eventbus.emit(event)+ result = eventbus.dispatch(event)# Check immediate resultassert isinstance(result, UserActionEvent)@@ -120,15 +120,15 @@ class TestEventEnqueueing:assert result.action == 'login'assert result.user_id == 'user123'assert result.event_id is not None- assert result.queued_at is not None- assert result.started_at is None # Not started yet- assert result.completed_at is None # Not completed yet+ assert result.event_created_at is not None+ assert result.event_started_at is None # Not started yet+ assert result.event_completed_at is None # Not completed yet# Test result() patternprocessed = await result.result()- assert processed.started_at is not None- assert processed.completed_at is not None- assert processed.results['_default_log_handler'] == 'logged'+ assert processed.event_started_at is not None+ assert processed.event_completed_at is not None+ assert processed.event_results['_default_log_handler'] == 'logged'# Check event historyassert len(eventbus.event_history) == 1@@ -137,7 +137,7 @@ class TestEventEnqueueing:"""Test sync event emission"""bus = EventBus()event = SystemEventModel(event_name='startup', severity='info')- result = bus.emit(event)+ result = bus.dispatch(event)# Check result and write-ahead logassert isinstance(result, SystemEventModel)@@ -173,8 +173,8 @@ class TestHandlerRegistration:eventbus.on('*', universal_handler)# Emit events- eventbus.emit(UserActionEvent(action='login', user_id='u1'))- eventbus.emit(SystemEventModel(event_name='startup'))+ 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@@ -205,7 +205,7 @@ class TestHandlerRegistration:# Emit event and waitstart = time.time()- event = await eventbus.emit(UserActionEvent(action='test', user_id='u1')).result()+ event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1')).result()duration = time.time() - start# Check handlers ran in parallel (should take ~0.1s, not 0.2s)@@ -214,8 +214,8 @@ class TestHandlerRegistration:assert len(end_times) == 2# Check results- assert event.results['slow_handler_1'] == 'handler1'- assert event.results['slow_handler_2'] == 'handler2'+ assert event.event_results['slow_handler_1'] == 'handler1'+ assert event.event_results['slow_handler_2'] == 'handler2'def test_handler_can_be_sync_or_async(self, mock_agent):"""Test that both sync and async handlers are accepted"""@@ -258,7 +258,7 @@ class TestFIFOOrdering:# Emit 20 events rapidlyfor i in range(20):- eventbus.emit(UserActionEvent(action=f'test_{i}', user_id='u1', metadata={'order': i}))+ eventbus.dispatch(UserActionEvent(action=f'test_{i}', user_id='u1', metadata={'order': i}))await eventbus.wait_until_idle()@@ -288,12 +288,12 @@ class TestErrorHandling:eventbus.on('UserActionEvent', working_handler)# Emit and wait for result- event = await eventbus.emit(UserActionEvent(action='test', user_id='u1')).result()+ event = await eventbus.dispatch(UserActionEvent(action='test', user_id='u1')).result()# Verify error capture and isolation- assert 'failing_handler' in event.errors- assert 'Expected to fail' in event.errors['failing_handler']- assert event.results['working_handler'] == 'worked'+ assert 'failing_handler' in event.event_errors+ assert 'Expected to fail' in event.event_errors['failing_handler']+ assert event.event_results['working_handler'] == 'worked'assert results == ['success']@@ -309,14 +309,14 @@ class TestBatchOperations:]# Enqueue batch- emitted_events = [eventbus.emit(event) for event in events]+ emitted_events = [eventbus.dispatch(event) for event in events]results = await asyncio.gather(*[event.result() for event in emitted_events])# Check all processedassert len(results) == 3for result in results:- assert result.completed_at is not None- assert '_default_log_handler' in result.results+ assert result.event_completed_at is not None+ assert '_default_log_handler' in result.event_resultsclass TestWriteAheadLog:@@ -328,7 +328,7 @@ class TestWriteAheadLog:events = []for i in range(5):event = UserActionEvent(action=f'action_{i}', user_id='u1')- events.append(eventbus.emit(event))+ events.append(eventbus.dispatch(event))await eventbus.wait_until_idle()@@ -363,7 +363,7 @@ class TestEventCompletion:eventbus.on('UserActionEvent', slow_handler)# Enqueue without waiting- event = eventbus.emit(UserActionEvent(action='test', user_id='u1'))+ event = eventbus.dispatch(UserActionEvent(action='test', user_id='u1'))completion_order.append('enqueue_done')# Wait for completion@@ -372,7 +372,7 @@ class TestEventCompletion:# Check orderassert completion_order == ['enqueue_done', 'handler_done', 'wait_done']- assert event.completed_at is not None+ assert event.event_completed_at is not Noneclass TestEdgeCases:@@ -391,7 +391,7 @@ class TestEdgeCases:# Enqueue events but don't waitfor i in range(5):- bus.emit(UserActionEvent(action=f'action_{i}', user_id='u1'))+ bus.dispatch(UserActionEvent(action=f'action_{i}', user_id='u1'))# Stop immediatelyawait bus.stop()@@ -411,7 +411,7 @@ class TestEdgeCases:event = SystemEventModel(event_name='complex', details=complex_data)- result = await eventbus.emit(event).result()+ result = await eventbus.dispatch(event).result()# Check data preservedassert result.details['nested']['list'][2]['inner'] == 'value'@@ -423,7 +423,7 @@ class TestEdgeCases:for i in range(100):event = UserActionEvent(action=f'concurrent_{i}', user_id='u1')# Emit returns the event synchronously, but we need to wait for completion- emitted_event = eventbus.emit(event)+ emitted_event = eventbus.dispatch(event)tasks.append(emitted_event.result())# Wait for all events to complete@@ -458,7 +458,7 @@ class TestEdgeCases:num_events = 20for i in range(num_events):event = UserActionEvent(action=f'mixed_{i}', user_id='u1', metadata={'order': i})- eventbus.emit(event)+ eventbus.dispatch(event)# Wait for all events to processawait eventbus.wait_until_idle()@@ -486,7 +486,7 @@ class TestEventTypeOverride:)# Enqueue it- result = eventbus.emit(event)+ result = eventbus.dispatch(event)# Check type is preserved - should be class nameassert result.event_type == 'CreateAgentTask'@@ -511,7 +511,7 @@ class TestEventTypeOverride:assert user_event.event_schema == f'test_eventbus.UserActionEvent@{version}'# Check schema is preserved after emit- result = eventbus.emit(task_event)+ result = eventbus.dispatch(task_event)assert result.event_schema == task_event.event_schema@@ -529,7 +529,7 @@ class TestWALPersistence:events = []for i in range(3):event = UserActionEvent(action=f'action_{i}', user_id=f'user_{i}')- emitted_event = bus.emit(event)+ emitted_event = bus.dispatch(event)result = await emitted_event.result()events.append(result)@@ -546,15 +546,13 @@ class TestWALPersistence:# Parse each line as JSONfor i, line in enumerate(lines):data = json.loads(line)- assert data['event_type'] == 'UserActionEvent'assert data['action'] == f'action_{i}'assert data['user_id'] == f'user_{i}'- # Check that datetime fields are properly serialized- assert isinstance(data['queued_at'], str)- assert isinstance(data['completed_at'], str)- # Should be parseable as ISO format- datetime.fromisoformat(data['queued_at'])- datetime.fromisoformat(data['completed_at'])+ assert data['event_type'] == 'UserActionEvent'+ assert isinstance(data['event_created_at'], str)+ assert isinstance(data['event_completed_at'], str)+ datetime.fromisoformat(data['event_created_at'])+ datetime.fromisoformat(data['event_completed_at'])finally:await bus.stop()@@ -572,7 +570,7 @@ class TestWALPersistence:assert wal_path.parent.exists()try:# Emit an event- await bus.emit(UserActionEvent(action='test', user_id='u1')).result()+ await bus.dispatch(UserActionEvent(action='test', user_id='u1')).result()# Wait for WAL persistence to completeawait bus.wait_until_idle()@@ -596,7 +594,7 @@ class TestWALPersistence:bus.on('UserActionEvent', slow_handler)# Emit event without waiting- event = bus.emit(UserActionEvent(action='test', user_id='u1'))+ event = bus.dispatch(UserActionEvent(action='test', user_id='u1'))# Check file doesn't exist yet (event not completed)assert not wal_path.exists()@@ -611,7 +609,7 @@ class TestWALPersistence:assert len(lines) == 1data = json.loads(lines[0])assert data['event_type'] == 'UserActionEvent'- assert 'completed_at' in data+ assert 'event_completed_at' in datafinally:await bus.stop()@@ -651,14 +649,14 @@ class TestEventBusHierarchy:# Subscribe buses to each other: parent <- child <- subchild# Child forwards events to parent- child_bus.on('*', parent_bus.emit)+ child_bus.on('*', parent_bus.dispatch)# Subchild forwards events to child- subchild_bus.on('*', child_bus.emit)+ subchild_bus.on('*', child_bus.dispatch)try:# Emit event from the bottom of hierarchyevent = UserActionEvent(action='bubble_test', user_id='test_user')- emitted = subchild_bus.emit(event)+ emitted = subchild_bus.dispatch(event)# Wait for event to bubble upawait subchild_bus.wait_until_idle()@@ -685,7 +683,7 @@ class TestEventBusHierarchy:events_at_subchild.clear()middle_event = SystemEventModel(event_name='middle_test')- child_bus.emit(middle_event)+ child_bus.dispatch(middle_event)await child_bus.wait_until_idle()await parent_bus.wait_until_idle()@@ -731,14 +729,14 @@ class TestEventBusHierarchy:peer3.on('*', peer3_handler)# Create circular subscription: peer1 -> peer2 -> peer3 -> peer1- peer1.on('*', peer2.emit)- peer2.on('*', peer3.emit)- peer3.on('*', peer1.emit) # This completes the circle+ peer1.on('*', peer2.dispatch)+ peer2.on('*', peer3.dispatch)+ peer3.on('*', peer1.dispatch) # This completes the circletry:# Emit event from peer1event = UserActionEvent(action='circular_test', user_id='test_user')- emitted = peer1.emit(event)+ emitted = peer1.dispatch(event)# Wait for all processing to completeawait asyncio.sleep(0.2) # Give time for any potential loops@@ -752,7 +750,6 @@ class TestEventBusHierarchy:assert len(events_at_peer3) == 1# Check event paths show the propagation but no loops- # Since event_path is mutated in place, all handlers see the final pathassert 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']@@ -769,7 +766,7 @@ class TestEventBusHierarchy:events_at_peer3.clear()event2 = SystemEventModel(event_name='circular_test_2')- peer2.emit(event2)+ peer2.dispatch(event2)await asyncio.sleep(0.2)await peer1.wait_until_idle()@@ -781,7 +778,6 @@ class TestEventBusHierarchy:assert len(events_at_peer2) == 1assert len(events_at_peer3) == 1- # Since event_path is mutated in place, all see final pathassert 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']