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
Finalize Rust agent cancellations
Magnus Müller9f38c90f8bba
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex 197c5cd3e..359ae5e8f 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -916,10 +916,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai- Completed single-step results continue to return `(True, True)`, matching Browser Use's done-step contract.- Proof: `test_rust_agent_take_step_matches_browser_use_non_final_status`.+181. Rust Agent cancellation-finalization parity+ - Terminal-backed `Agent.run()` and direct `Agent.follow_up()` now finalize Browser Use lifecycle state when terminal execution is cancelled with `asyncio.CancelledError`.+ - 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`.+## 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` (152 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (153 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 35c3a5782..bbf5850a5 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -2932,6 +2932,9 @@ class Agent(Generic[Context, 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 asyncio.CancelledError:+ await self._finalize_exceptional_run(max_steps=max_steps, agent_run_error='CancelledError')+ raiseexcept KeyboardInterrupt:self.logger.debug('Got KeyboardInterrupt during execution, returning current history')await self._finalize_exceptional_run(max_steps=max_steps, agent_run_error='KeyboardInterrupt')@@ -3043,6 +3046,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._register_run_signal_handler(resolved_max_steps)try:return await self._follow_up_terminal(task, max_steps=max_steps, resolved_max_steps=resolved_max_steps)+ except asyncio.CancelledError:+ await self._finalize_exceptional_run(max_steps=resolved_max_steps, agent_run_error='CancelledError')+ raiseexcept KeyboardInterrupt:self.logger.debug('Got KeyboardInterrupt during execution, returning current history')await self._finalize_exceptional_run(max_steps=resolved_max_steps, agent_run_error='KeyboardInterrupt')diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex ec384697c..3f1c8edcf 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -3425,6 +3425,98 @@ 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_finalizes_after_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 = []+ 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='Cancel 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 asyncio.CancelledError++ agent._run_process = fake_run_process++ with pytest.raises(asyncio.CancelledError):+ 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 == 'CancelledError'+ assert logger.errors == []++async def test_rust_agent_follow_up_finalizes_after_terminal_exception(monkeypatch):import browser_use.rust.service as rust_servicefrom browser_use.rust import Agent