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 follow-ups after exceptions

Magnus Müllerff0e08c4d9a9
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index a062bfa16..909586cc2 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -866,10 +866,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- 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`.
+171. Rust Agent follow-up exception-finalization parity
+ - Direct terminal-backed `Agent.follow_up()` now finalizes Browser Use run lifecycle state when the Rust follow-up command fails before producing history.
+ - Failed follow-ups log usage summaries, record telemetry with the follow-up error 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_follow_up_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` (142 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (143 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 7de02dacc..0daf8cce2 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -2973,7 +2973,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
return self.history
if self.state.follow_up_task and self.terminal_session_id:
self.state.follow_up_task = False
- return await self.follow_up(self.task, max_steps=max_steps)
+ return await self._follow_up_terminal(self.task, max_steps=max_steps, resolved_max_steps=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()
@@ -3015,6 +3015,19 @@ class Agent(Generic[Context, AgentStructuredOutput]):
raise RustAgentError('No active Rust session. Call run() before follow_up().')
resolved_max_steps = max_steps if max_steps is not None else self.kwargs.get('max_steps', 100)
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 Exception as exc:
+ self.logger.error(f'Agent follow-up failed with exception: {exc}', exc_info=True)
+ await self._finalize_exceptional_run(max_steps=resolved_max_steps, agent_run_error=str(exc))
+ raise
+
+ async def _follow_up_terminal(
+ self,
+ task: str,
+ max_steps: int | None,
+ resolved_max_steps: int,
+ ) -> AgentHistoryList[AgentStructuredOutput]:
self._initialize_run_lifecycle_state()
started = time.time()
binary = find_browser_use_terminal_binary()
@@ -3025,7 +3038,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
if returncode:
raise RustAgentError(stderr_text or stdout_text)
returncode, _stdout_text, stderr_text = await self._run_process(
- self._run_existing_argv(max_steps if max_steps is not None else self.kwargs.get('max_steps', 100)),
+ self._run_existing_argv(resolved_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.py
index ee8dc320d..c24128439 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -3238,6 +3238,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_follow_up_finalizes_after_terminal_exception(monkeypatch):
+ import browser_use.rust.service as rust_service
+ from browser_use.rust import Agent
+ from browser_use.rust.service import RustAgentError
+
+ 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='Continue failed terminal run.', llm=type('LLM', (), {'model': 'gpt-test'})(), browser_session=session)
+ agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'
+ agent.token_cost_service = TokenCostService()
+ agent.telemetry = Telemetry()
+
+ async def fake_run_process(argv, timeout_seconds=None):
+ events.append('run_process')
+ return 1, '', 'followup exploded'
+
+ agent._run_process = fake_run_process
+
+ with pytest.raises(RustAgentError, match='followup exploded'):
+ await agent.follow_up('Continue the task.', max_steps=5)
+
+ 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 == 5
+ assert captured_events[0].error_message == 'followup exploded'
+ assert logger.errors[0] == 'Agent follow-up failed with exception: followup exploded'
+
+
async def test_rust_agent_run_logs_token_usage_summary(monkeypatch):
from browser_use.rust import Agent