Skip to content

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

Finalize Rust agent runs after exceptions

Magnus Müller236b9c3da80c
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index a4646602a..a062bfa16 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -861,10 +861,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- SIGINT handling is wired to the wrapper's `pause()`, `resume()`, force-exit telemetry, telemetry flush, and cleanup-time unregister path.
- Proof: `test_rust_agent_run_registers_browser_use_signal_handler`.
+170. Rust Agent run exception-finalization parity
+ - Terminal-backed `Agent.run()` now finalizes Browser Use run lifecycle state when Rust terminal execution raises before producing history.
+ - Exceptional runs log usage summaries, record telemetry with the exception text, dispatch the final task update, log final guidance, unregister signal handlers, close browser resources, and then re-raise the original exception.
+ - Proof: `test_rust_agent_run_finalizes_after_terminal_exception`.
+
## 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` (141 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (142 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.py
index 3032d358b..7de02dacc 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -2873,6 +2873,14 @@ class Agent(Generic[Context, AgentStructuredOutput]):
await self._stop_eventbus_after_run()
await self.close()
+ 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."""
+ 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()
+ self._log_final_outcome_messages()
+ await self._finalize_run_cleanup()
+
def _initialize_run_lifecycle_state(self) -> None:
"""Initialize Browser Use run timing and session state."""
self._session_start_time = time.time()
@@ -2906,6 +2914,23 @@ class Agent(Generic[Context, AgentStructuredOutput]):
on_step_end: AgentHookFunc | None = None,
) -> AgentHistoryList[AgentStructuredOutput]:
self._register_run_signal_handler(max_steps)
+ try:
+ return await self._run_terminal(max_steps=max_steps, on_step_start=on_step_start, on_step_end=on_step_end)
+ except KeyboardInterrupt:
+ self.logger.debug('Got KeyboardInterrupt during execution, returning current history')
+ await self._finalize_exceptional_run(max_steps=max_steps, agent_run_error='KeyboardInterrupt')
+ return self.history
+ except Exception as exc:
+ self.logger.error(f'Agent run failed with exception: {exc}', exc_info=True)
+ await self._finalize_exceptional_run(max_steps=max_steps, agent_run_error=str(exc))
+ raise
+
+ async def _run_terminal(
+ self,
+ max_steps: int,
+ on_step_start: AgentHookFunc | None,
+ on_step_end: AgentHookFunc | None,
+ ) -> AgentHistoryList[AgentStructuredOutput]:
await self._log_agent_run()
await self._call_callback(on_step_start, self)
self._initialize_run_lifecycle_state()
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index 7170a4035..ee8dc320d 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -3148,6 +3148,96 @@ async def test_rust_agent_run_registers_browser_use_signal_handler(monkeypatch):
assert captured_events[0].error_message == 'SIGINT: Cancelled by user'
+async def test_rust_agent_run_finalizes_after_terminal_exception(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 = []
+ 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 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='Clean up failed terminal run.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)
+ agent.token_cost_service = TokenCostService()
+ agent.telemetry = Telemetry()
+
+ async def fake_run_process(argv, timeout_seconds=None):
+ events.append('run_process')
+ raise RuntimeError('terminal exploded')
+
+ agent._run_process = fake_run_process
+
+ with pytest.raises(RuntimeError, match='terminal exploded'):
+ await agent.run(max_steps=7)
+
+ assert events == ['init_signal', 'register_signal', 'run_process', 'usage_summary', 'unregister_signal', 'kill_browser']
+ 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 == 'terminal exploded'
+ assert logger.errors[0] == 'Agent run failed with exception: terminal exploded'
+
+
async def test_rust_agent_run_logs_token_usage_summary(monkeypatch):
from browser_use.rust import Agent