Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Finalize Rust startup cancellations

Magnus Müllere4c0a98708ed
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index 207512f41..74b799239 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -1176,12 +1176,19 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- The Rust-backed implementation is now opt-in via `from browser_use.rust import Agent`, preserving Browser Use's existing package behavior while keeping the Rust wrapper's constructor/signature metadata aligned with the Python service surface.
- Proof: `test_top_level_agent_preserves_python_service`, `test_agent_package_export_preserves_python_service`, `test_agent_service_export_preserves_python_service`, `test_rust_agent_class_metadata_matches_browser_use_service_surface`, `test_rust_agent_generic_subscription_matches_browser_use`, and `test_rust_agent_constructor_signature_matches_browser_use_order`; live managed-headless opt-in smoke below completed with `agents_are_distinct=true`, `successful=true`, `final_result` containing `Example Domain`, and no history errors.
+233. Rust Agent startup-cancellation finalization parity
+ - Exceptional Rust-agent finalization now initializes Browser Use lifecycle timing/session state when cancellation or startup failure happens before the normal run lifecycle setup.
+ - This prevents a secondary `UpdateAgentTaskEvent.from_agent(...)` failure from masking the original cancellation/error when a parallel caller cancels an agent during startup.
+ - Proof: `test_rust_agent_run_finalizes_after_startup_cancellation` and `test_rust_agent_run_finalizes_after_cancellation`.
+
## 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 browser_use/llm/models.py tests/ci/test_rust_agent.py tests/ci/models/test_llm_model_factory.py examples/rust_agent/basic.py examples/rust_agent/real_v8_smoke.py`
- `uv run python -m py_compile browser_use/__init__.py browser_use/agent/__init__.py browser_use/agent/service.py examples/rust_agent/basic.py examples/rust_agent/real_v8_smoke.py tests/ci/test_rust_agent.py`
+- `uv run python -m py_compile browser_use/rust/service.py tests/ci/test_rust_agent.py`
- `uv run pytest -q tests/ci/test_rust_agent.py` (previous full run before latest focused additions: 186 tests)
- `uv run pytest -q tests/ci/test_rust_agent.py -k 'top_level_agent_preserves_python_service or agent_package_export_preserves_python_service or agent_service_export_preserves_python_service or rust_agent_class_metadata_matches_browser_use_service_surface or rust_agent_generic_subscription_matches_browser_use or rust_agent_constructor_signature_matches_browser_use_order'`
+- `uv run pytest -q tests/ci/test_rust_agent.py -k 'run_finalizes_after_startup_cancellation or run_finalizes_after_cancellation or top_level_agent_preserves_python_service or agent_package_export_preserves_python_service or agent_service_export_preserves_python_service'`
- `uv run pytest -q tests/ci/test_rust_agent.py -k prefers_done_tool_text`
- `uv run pytest -q tests/ci/models/test_llm_model_factory.py`
- `uv run --with pytest pytest -q python/tests/test_worker_package.py` on terminal branch `magnus/browser-use-rust-main-integration` (28 tests)
diff --git a/browser_use/rust/service.py b/browser_use/rust/service.py
index ff72661e4..e0b024c3e 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -3015,6 +3015,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
async def _finalize_exceptional_run(self, max_steps: int, agent_run_error: str) -> None:
"""Mirror Browser Use run finalization for exceptions that escape Rust execution."""
+ if not hasattr(self, '_task_start_time') or not hasattr(self, '_session_start_time'):
+ self._initialize_run_lifecycle_state()
await self._log_run_usage_summary()
self._record_run_telemetry(max_steps=max_steps, agent_run_error=agent_run_error)
self._dispatch_run_update_event()
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index 457546c84..783e64ee3 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -4249,6 +4249,116 @@ async def test_rust_agent_run_finalizes_after_cancellation(monkeypatch):
assert logger.errors == []
+async def test_rust_agent_run_finalizes_after_startup_cancellation(monkeypatch):
+ import asyncio
+
+ 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='Cancel during startup.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)
+ agent.eventbus = EventBus()
+ agent.token_cost_service = TokenCostService()
+ agent.telemetry = Telemetry()
+
+ async def fake_log_agent_run():
+ events.append('log_agent_run')
+ raise asyncio.CancelledError
+
+ async def fake_run_process(argv, timeout_seconds=None):
+ raise AssertionError('terminal process should not start')
+
+ agent._log_agent_run = fake_log_agent_run
+ agent._run_process = fake_run_process
+
+ with pytest.raises(asyncio.CancelledError):
+ await agent.run(max_steps=7)
+
+ assert events == ['init_signal', 'register_signal', 'log_agent_run', 'usage_summary', 'unregister_signal', 'kill_browser']
+ assert [type(event).__name__ for event in dispatched] == [
+ 'CreateAgentSessionEvent',
+ 'CreateAgentTaskEvent',
+ 'UpdateAgentTaskEvent',
+ ]
+ assert agent.state.session_initialized is True
+ assert agent._task_start_time == agent._session_start_time
+ assert session.kill_calls == 1
+ assert getattr(agent, '_run_signal_handler') is None
+ assert len(captured_events) == 1
+ assert captured_events[0].max_steps == 7
+ assert captured_events[0].error_message == 'CancelledError'
+ assert logger.errors == []
+
+
async def test_rust_agent_follow_up_finalizes_after_terminal_exception(monkeypatch):
import browser_use.rust.service as rust_service
from browser_use.rust import Agent