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
Order Rust run start hooks after lifecycle
Magnus Müller6b6f9ae32929
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex 359ae5e8f..444c8edf8 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -921,10 +921,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai- Cancelled runs log usage summaries, record cancellation telemetry, dispatch the final task update, unregister signal handlers, close browser resources, and then re-raise cancellation to the caller.- Proof: `test_rust_agent_run_finalizes_after_cancellation`.+182. Rust Agent start-hook lifecycle ordering parity+ - Terminal-backed `Agent.run()` now initializes Browser Use run lifecycle state before invoking `on_step_start`, matching the Python Agent's run-start event ordering before per-step hooks.+ - `on_step_start` now fires only when the Rust terminal execution or run-delegated follow-up path is about to execute, so stopped or paused-before-run paths do not report a step start that never happened.+ - Proof: `test_rust_agent_run_initializes_lifecycle_before_start_callback_error`.+## 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` (153 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (154 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 bbf5850a5..39be9b362 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -2952,7 +2952,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):) -> AgentHistoryList[AgentStructuredOutput]:await self._log_agent_run()self._log_agent_setup()- await self._call_callback(on_step_start, self)self._initialize_run_lifecycle_state()self._log_first_step_startup()started = time.time()@@ -2994,6 +2993,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):return self.historyif self.state.follow_up_task and self.terminal_session_id:self.state.follow_up_task = False+ await self._call_callback(on_step_start, self)self._log_main_execution_start(max_steps)return await self._follow_up_terminal(self.task,@@ -3003,6 +3003,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):on_step_end=on_step_end,)+ await self._call_callback(on_step_start, self)self._log_main_execution_start(max_steps)returncode, stdout_text, stderr_text = await self._run_process(self._run_argv(max_steps), timeout_seconds=self.settings.step_timeout)finished = time.time()diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 3f1c8edcf..3428350f9 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -3425,6 +3425,113 @@ async def test_rust_agent_run_finalizes_after_terminal_exception(monkeypatch):assert logger.errors[0] == 'Agent run failed with exception: terminal exploded'+async def test_rust_agent_run_initializes_lifecycle_before_start_callback_error(monkeypatch):+ import browser_use.rust.service as rust_service+ from browser_use.rust import Agent++ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')+ events = []+ dispatched = []+ captured_events = []++ class FakeSignalHandler:+ def __init__(self, **kwargs):+ events.append('init_signal')++ def register(self):+ events.append('register_signal')++ def unregister(self):+ events.append('unregister_signal')++ class RecordingLogger:+ def __init__(self):+ self.infos = []+ self.debugs = []+ self.errors = []+ self.warnings = []++ def info(self, message, *args, **kwargs):+ self.infos.append(message)++ def debug(self, message, *args, **kwargs):+ self.debugs.append(message)++ def error(self, message, *args, **kwargs):+ self.errors.append(message)++ def warning(self, message, *args, **kwargs):+ self.warnings.append(message)++ class EventBus:+ def dispatch(self, event):+ dispatched.append(event)+ return event++ class BrowserProfile:+ keep_alive = False+ viewport = {'width': 1280, 'height': 720}+ user_agent = None+ headless = True+ allowed_domains = []++ class BrowserSession:+ id = 'browser-session-1234'+ browser_profile = BrowserProfile()+ cdp_url = None++ def __init__(self):+ self.kill_calls = 0++ async def kill(self):+ events.append('kill_browser')+ self.kill_calls += 1++ class TokenCostService:+ async def log_usage_summary(self):+ events.append('usage_summary')++ class Telemetry:+ def capture(self, event):+ captured_events.append(event)++ session = BrowserSession()+ logger = RecordingLogger()+ monkeypatch.setattr(rust_service, 'SignalHandler', FakeSignalHandler)+ monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))+ agent = Agent(task='Fail from start callback.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)+ agent.eventbus = EventBus()+ agent.token_cost_service = TokenCostService()+ agent.telemetry = Telemetry()++ async def fake_run_process(argv, timeout_seconds=None):+ events.append('run_process')+ raise AssertionError('terminal process should not start')++ async def on_step_start(callback_agent):+ events.append('start_callback')+ assert callback_agent is agent+ raise RuntimeError('start callback failed')++ agent._run_process = fake_run_process++ with pytest.raises(RuntimeError, match='start callback failed'):+ await agent.run(max_steps=3, on_step_start=on_step_start)++ assert events == ['init_signal', 'register_signal', 'start_callback', 'usage_summary', 'unregister_signal', 'kill_browser']+ assert [type(event).__name__ for event in dispatched] == [+ 'CreateAgentSessionEvent',+ 'CreateAgentTaskEvent',+ 'UpdateAgentTaskEvent',+ ]+ assert session.kill_calls == 1+ assert getattr(agent, '_run_signal_handler') is None+ assert len(captured_events) == 1+ assert captured_events[0].max_steps == 3+ assert captured_events[0].error_message == 'start callback failed'+ assert logger.errors[0] == 'Agent run failed with exception: start callback failed'++async def test_rust_agent_run_finalizes_after_cancellation(monkeypatch):import asyncio