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
Dispatch Rust agent run lifecycle events
Magnus Müller2be8801a2e40
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex f67d9fd36..c5ba24613 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -825,10 +825,16 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai- The wrapper sets `_session_start_time`, `_task_start_time`, and flips `state.session_initialized`, matching the observable Python Agent state callers can inspect around completed runs.- Proof: `test_rust_agent_run_initializes_browser_use_session_state`.+163. Rust Agent event-bus run lifecycle parity+ - Terminal-backed `Agent.run()` and `Agent.follow_up()` now dispatch Browser Use cloud event-bus lifecycle events around Rust core execution.+ - The wrapper emits `CreateAgentSessionEvent` once per Browser Use session, `CreateAgentTaskEvent` at each run start, and `UpdateAgentTaskEvent` after reconstructed terminal history is available.+ - Run event buses are stopped after completion and recreated before later runs when needed, matching Browser Use's per-run eventbus lifecycle without leaving pending no-handler events in local tests.+ - Proof: `test_rust_agent_run_dispatches_browser_use_lifecycle_events`.+## Current Verification- `python3 -m py_compile browser_use/agent/service.py browser_use/rust/service.py browser_use/rust/__init__.py browser_use/__init__.py tests/ci/test_rust_agent.py examples/rust_agent/basic.py examples/rust_agent/real_v8_smoke.py`-- `uv run pytest -q tests/ci/test_rust_agent.py` (134 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (135 tests)- `cargo build -q -p browser-use-cli` on terminal branch `magnus/browser-use-rust-main-integration`- `cargo test -q -p browser-use-cli run_codex_session_command_accepts_task_id_and_model -- --nocapture`- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent selected_remote_cdp_mode_allows_remote_cdp_connect -- --nocapture`diff --git a/browser_use/rust/service.py b/browser_use/rust/service.pyindex 5802b0ed3..db97f3472 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -22,6 +22,7 @@ from pydantic import BaseModel, ValidationError, create_modelfrom typing_extensions import TypeVarfrom uuid_extensions import uuid7str+from browser_use.agent.cloud_events import CreateAgentSessionEvent, CreateAgentTaskEvent, UpdateAgentTaskEventfrom browser_use.agent.message_manager.utils import save_conversationfrom browser_use.agent.message_manager.service import MessageManagerfrom browser_use.agent.prompts import SystemPrompt@@ -2308,6 +2309,20 @@ def _eventbus_name(agent_id: str, prefix: str = 'Agent') -> str:return f'{prefix}_{suffix or "agent"}'+class _CloudEventLLMProxy:+ def __init__(self, model_name: str):+ self.model_name = model_name+++class _CloudEventAgentProxy:+ def __init__(self, agent: 'Agent'):+ self._agent = agent+ self.llm = _CloudEventLLMProxy(getattr(agent, 'model', None) or _model_name(getattr(agent, 'llm', None)))++ def __getattr__(self, name: str) -> Any:+ return getattr(self._agent, name)++def _unique_eventbus_name(agent_id: str, prefix: str = 'Agent') -> str:unique_suffix = re.sub(r'\W', '_', uuid7str()[-8:])return f'{_eventbus_name(agent_id, prefix)}_{unique_suffix}'@@ -2502,6 +2517,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):_register_llm_for_usage(self.token_cost_service, page_extraction_llm)self.telemetry = ProductTelemetry()self.eventbus = EventBus(name=_eventbus_name(self.id))+ self._eventbus_stopped = Falseself.available_file_paths = available_file_paths or []self.allowed_domains = _extract_profile_domains(self.browser_session, self.browser_profile, 'allowed_domains')self.prohibited_domains = _extract_profile_domains(self.browser_session, self.browser_profile, 'prohibited_domains')@@ -2769,12 +2785,50 @@ class Agent(Generic[Context, AgentStructuredOutput]):except Exception as exc:self.logger.error(f'Failed to log telemetry event: {exc}', exc_info=True)+ def _cloud_event_agent(self):+ llm_model_name = getattr(getattr(self, 'llm', None), 'model_name', None)+ if isinstance(llm_model_name, str) and llm_model_name:+ return self+ return _CloudEventAgentProxy(self)++ def _ensure_eventbus(self) -> None:+ if getattr(self, '_eventbus_stopped', False):+ self.eventbus = EventBus(name=_unique_eventbus_name(self.id))+ self._eventbus_stopped = False++ def _dispatch_run_start_events(self) -> None:+ """Emit Browser Use cloud lifecycle create events for a Rust-backed run."""+ self._ensure_eventbus()+ event_agent = self._cloud_event_agent()+ if not self.state.session_initialized:+ self.eventbus.dispatch(CreateAgentSessionEvent.from_agent(event_agent))+ self.state.session_initialized = True+ self.eventbus.dispatch(CreateAgentTaskEvent.from_agent(event_agent))++ def _dispatch_run_update_event(self) -> None:+ """Emit Browser Use cloud lifecycle update event for a completed Rust-backed run."""+ self.eventbus.dispatch(UpdateAgentTaskEvent.from_agent(self._cloud_event_agent()))++ async def _stop_eventbus_after_run(self) -> None:+ """Stop the eventbus after run-level events have been dispatched."""+ stop = getattr(self.eventbus, 'stop', None)+ if not callable(stop):+ return+ handlers = getattr(self.eventbus, 'handlers', None)+ has_handlers = any(handlers.values()) if isinstance(handlers, dict) else True+ try:+ result = stop(timeout=3.0, clear=not has_handlers)+ except TypeError:+ result = stop(timeout=3.0)+ if inspect.isawaitable(result):+ await result+ self._eventbus_stopped = True+def _initialize_run_lifecycle_state(self) -> None:"""Initialize Browser Use run timing and session state."""self._session_start_time = time.time()self._task_start_time = self._session_start_time- if not self.state.session_initialized:- self.state.session_initialized = True+ self._dispatch_run_start_events()def _log_action(self, action, action_name: str, action_num: int, total_actions: int) -> None:"""Log an action before execution with Browser Use-style structure."""@@ -2817,7 +2871,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):)self.history = self.resultself._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent stopped before terminal run.')+ self._dispatch_run_update_event()await self._call_callback(on_step_end, self)+ await self._stop_eventbus_after_run()return self.historyif self.state.paused:finished = time.time()@@ -2831,7 +2887,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):)self.history = self.resultself._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent is paused before terminal run.')+ self._dispatch_run_update_event()await self._call_callback(on_step_end, self)+ await self._stop_eventbus_after_run()return self.historyif self.state.follow_up_task and self.terminal_session_id:self.state.follow_up_task = False@@ -2860,12 +2918,14 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.history = self.resultself._sync_state_from_history()self._record_run_telemetry(max_steps=max_steps, agent_run_error=process_error)+ self._dispatch_run_update_event()await self._check_and_update_downloads('run')await self._save_conversation_if_requested()await self._call_new_step_callback()await self._call_callback(on_step_end, self)await self._call_done_callback()self._generate_gif_if_requested()+ await self._stop_eventbus_after_run()return self.historyasync def follow_up(self, task: str, max_steps: int | None = None) -> AgentHistoryList[AgentStructuredOutput]:@@ -2901,11 +2961,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._sync_state_from_history()resolved_max_steps = max_steps if max_steps is not None else self.kwargs.get('max_steps', 100)self._record_run_telemetry(max_steps=resolved_max_steps, agent_run_error=process_error)+ self._dispatch_run_update_event()await self._check_and_update_downloads('follow_up')await self._save_conversation_if_requested()await self._call_new_step_callback()await self._call_done_callback()self._generate_gif_if_requested()+ await self._stop_eventbus_after_run()return self.historyfollow_up_task = follow_up@@ -3578,6 +3640,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.state.stopped = Falseself.state.paused = Falseself.eventbus = EventBus(name=_unique_eventbus_name(self.id))+ self._eventbus_stopped = Falseself._external_pause_event.set()def save_history(self, file_path: str | Path | None = None) -> None:diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 5c42613c4..169cad4c9 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -3043,6 +3043,55 @@ async def test_rust_agent_run_initializes_browser_use_session_state(monkeypatch)assert agent._task_start_time == agent._session_start_time+async def test_rust_agent_run_dispatches_browser_use_lifecycle_events(monkeypatch):+ from browser_use.rust import Agent++ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')+ dispatched = []+ run_count = 0++ class EventBus:+ def dispatch(self, event):+ dispatched.append(event)+ return event++ agent = Agent(task='Dispatch lifecycle events.', llm=type('LLM', (), {'model': 'gpt-test'})())+ agent.eventbus = EventBus()++ async def fake_run_process(argv, timeout_seconds=None):+ nonlocal run_count+ run_count += 1+ return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''++ async def fake_load_events():+ return [{'event_type': 'session.done', 'payload': {'result': f'dispatched {run_count}'}}]++ agent._run_process = fake_run_process+ agent._load_events = fake_load_events++ history = await agent.run(max_steps=4)++ assert history.final_result() == 'dispatched 1'+ assert [type(event).__name__ for event in dispatched] == [+ 'CreateAgentSessionEvent',+ 'CreateAgentTaskEvent',+ 'UpdateAgentTaskEvent',+ ]+ assert dispatched[0].id == str(agent.session_id)+ assert dispatched[1].id == str(agent.task_id)+ assert dispatched[1].llm_model == 'gpt-test'+ assert dispatched[2].id == str(agent.task_id)+ assert dispatched[2].done_output == 'dispatched 1'++ dispatched.clear()+ history = await agent.run(max_steps=4)++ assert history.final_result() == 'dispatched 2'+ assert [type(event).__name__ for event in dispatched] == ['CreateAgentTaskEvent', 'UpdateAgentTaskEvent']+ assert dispatched[0].llm_model == 'gpt-test'+ assert dispatched[1].done_output == 'dispatched 2'++async def test_rust_agent_exposes_step_finalization_helper_methods(tmp_path):import base64import time