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
better circular loop prevention for eventbus
Nick Sweetingf3c5672c4606
diff --git a/browser_use/eventbus/models.py b/browser_use/eventbus/models.pyindex 4ddca0f70..f8dd7887e 100644--- a/browser_use/eventbus/models.py+++ b/browser_use/eventbus/models.py@@ -1,8 +1,9 @@import asynciofrom datetime import UTC, datetime-from typing import Any+from typing import Annotated, Any+from uuid import UUID-from pydantic import BaseModel, Field, PrivateAttr+from pydantic import AfterValidator, BaseModel, Field, PrivateAttrfrom uuid_extensions import uuid7strfrom browser_use.utils import get_browser_use_version@@ -14,6 +15,8 @@ MAX_TASK_LENGTH = 5000MAX_COMMENT_LENGTH = 2000MAX_FILE_CONTENT_SIZE = 50 * 1024 * 1024 # 50MB+UUIDStr = Annotated[str, AfterValidator(lambda s: str(UUID(s)))]+class BaseEvent(BaseModel):"""diff --git a/browser_use/eventbus/service.py b/browser_use/eventbus/service.pyindex 51a767020..be0d173ac 100644--- a/browser_use/eventbus/service.py+++ b/browser_use/eventbus/service.py@@ -9,8 +9,9 @@ from typing import Any, Unionimport anyiofrom pydantic import BaseModel+from uuid_extensions import uuid7str-from browser_use.eventbus.models import BaseEvent+from browser_use.eventbus.models import BaseEvent, UUIDStrlogger = logging.getLogger(__name__)@@ -30,20 +31,23 @@ class EventBus:name: strevent_queue: asyncio.Queue[BaseEvent]- event_history: list[BaseEvent]+ event_history: dict[UUIDStr, BaseEvent]handlers: dict[str, list[EventHandler]]wal_path: Path | None = Noneparallel_handlers: bool = True+ id: UUIDStr_is_running: bool = False_runloop_task: asyncio.Task | None = None_runloop_lock: asyncio.Lock_on_idle: asyncio.Eventdef __init__(self, name: str | None = None, wal_path: Path | str | None = None, parallel_handlers: bool = True):- self.name = name or f'EventBus_{hex(id(self))[-6:]}'+ 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_history = []+ self.event_history = {}self.handlers = defaultdict(list)self.parallel_handlers = parallel_handlersself._runloop_lock = asyncio.Lock()@@ -71,26 +75,29 @@ class EventBus:@propertydef events_queued(self) -> list[BaseEvent]:"""Get events that haven't started processing yet"""- return [event for event in self.event_history if event.started_at is None]+ return [event for event in self.event_history.values() if event.started_at is None]@propertydef events_started(self) -> list[BaseEvent]:"""Get events currently being processed"""- return [event for event in self.event_history if event.started_at and not event.completed_at]+ return [event for event in self.event_history.values() if event.started_at and not event.completed_at]@propertydef events_completed(self) -> list[BaseEvent]:"""Get events that have completed processing"""- return [event for event in self.event_history if event.completed_at is not None]+ return [event for event in self.event_history.values() if event.completed_at is not None]def on(self, event_pattern: str | type[BaseModel], handler: EventHandler) -> None:"""Subscribe to events matching a pattern, event type name, or event model class.- Use '*' for all events. Similar to JS EventListener.addEventListener()+ 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.Examples:- eventbus.on('*', handler) # All eventseventbus.on('TaskStartedEvent', handler) # Specific event typeeventbus.on(TaskStartedEvent, handler) # Event model class+ eventbus.on('*', handler) # Subscribe to all events+ eventbus.on('*', other_eventbus.emit) # Forward all events to another EventBus"""# Allow both sync and async handlersif event_pattern == '*':@@ -105,36 +112,50 @@ class EventBus:def emit(self, event: BaseEvent) -> BaseEvent:"""- Enqueue an event for processing. Returns awaitable event object.- Auto-starts the EventBus if not already running. similar to JS EventListener.dispatchEvent()- """- # Auto-start if not running- if not self._is_running:- try:- loop = asyncio.get_running_loop()- self._is_running = True- self._runloop_task = loop.create_task(self._run_loop())- except RuntimeError:- # No event loop - will start when one becomes available- pass+ Enqueue an event for processing by the handlers. Returns awaitable event object.+ (Auto-starts the EventBus's async _run_loop() if not already running)- # All events must inherit from BaseEvent- actual_event = event+ 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_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)'# Add this EventBus to the event_path if not already there- if self.name not in actual_event.event_path:- actual_event = actual_event.model_copy(update={'event_path': actual_event.event_path + [self.name]})+ 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)++ 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}'+ )++ # Add event to history+ self.event_history[event.event_id] = event- self.event_history.append(actual_event)+ self._start()# Put event in queue synchronously using put_nowaittry:- self.event_queue.put_nowait(actual_event)+ self.event_queue.put_nowait(event)except asyncio.QueueFull:- logger.error(f'Event queue is full, dropping event {actual_event.event_type}')+ logger.error(f'⚠️ Event queue is full! Dropping event {event.event_type}:\n{event.model_dump_json()}')- logger.debug(f'Emitting event {actual_event.event_type} to queue')- return actual_event+ logger.debug(f'Emitting event {event.event_type} to queue')+ return event++ def _start(self) -> None:+ """Start the event bus if not already running"""+ if not self._is_running:+ try:+ loop = asyncio.get_running_loop()+ self._is_running = True+ self._runloop_task = loop.create_task(self._run_loop())+ except RuntimeError:+ pass # No event loop - will start when one becomes availableasync def stop(self, timeout: float | None = None) -> None:"""Stop the event bus, optionally waiting for events to complete"""@@ -168,6 +189,8 @@ class EventBus:async def wait_until_idle(self, timeout: float | None = None) -> None:"""Wait until the event bus is idle (no events being processed)"""+ self._start()+# First wait for the queue to be emptyawait self.event_queue.join()# logger.debug(f'Queue joined, processing events: {len(self.events_started)}')@@ -302,7 +325,13 @@ class EventBus:@staticmethodasync def _default_log_handler(event: BaseEvent) -> str:"""Default handler that logs all events"""- logger.debug(f'Event processed: {event.event_type} [{event.event_id}] - {event.model_dump_json()}')+ 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})')return 'logged'async def _default_wal_handler(self, event: BaseEvent) -> str:diff --git a/tests/ci/test_eventbus.py b/tests/ci/test_eventbus.pyindex fb1bcab97..c79018037 100644--- a/tests/ci/test_eventbus.py+++ b/tests/ci/test_eventbus.py@@ -335,7 +335,7 @@ class TestWriteAheadLog:# Check write-ahead loglog = eventbus.event_history.copy()assert len(log) == 5- for i, event in enumerate(log):+ for i, event in enumerate(log.values()):assert event.action == f'action_{i}'# Check event state properties@@ -617,5 +617,180 @@ class TestWALPersistence:await bus.stop()+class TestEventBusHierarchy:+ """Test hierarchical EventBus subscription patterns"""++ async def test_three_level_hierarchy_bubbling(self):+ """Test that events bubble up through a 3-level hierarchy and event_path is correct"""+ # Create three 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.emit)+ # Subchild forwards events to child+ subchild_bus.on('*', child_bus.emit)++ try:+ # Emit event from the bottom of hierarchy+ event = UserActionEvent(action='bubble_test', user_id='test_user')+ emitted = subchild_bus.emit(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.emit(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 three 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.emit)+ peer2.on('*', peer3.emit)+ peer3.on('*', peer1.emit) # This completes the circle++ try:+ # Emit event from peer1+ event = UserActionEvent(action='circular_test', user_id='test_user')+ emitted = peer1.emit(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+ # Since event_path is mutated in place, all handlers see the final path+ 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.emit(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++ # Since event_path is mutated in place, all see final path+ 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()++if __name__ == '__main__':pytest.main([__file__, '-v'])