Skip to content

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

Record Rust agent run telemetry

Magnus Müllera5d762ec3243
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index bd8a0b01c..f1ff7be0e 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -815,10 +815,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- This keeps close idempotent and safe for user cleanup/finally blocks even when a supplied BrowserSession fails during `kill()`.
- Proof: `test_rust_agent_close_logs_cleanup_errors_without_raising`.
+161. Rust Agent run telemetry parity
+ - Terminal-backed `Agent.run()` and `Agent.follow_up()` now emit Browser Use `AgentTelemetryEvent` records from reconstructed Rust history.
+ - Telemetry captures task/model metadata, URLs, usage, final result, success, and terminal process errors, while telemetry failures are logged and do not break the returned history.
+ - Proof: `test_rust_agent_run_records_terminal_telemetry`.
+
## 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` (132 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (133 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 727c8365c..b119ab04b 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -2762,6 +2762,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):
)
)
+ def _record_run_telemetry(self, max_steps: int, agent_run_error: str | None = None) -> None:
+ """Record Browser Use run telemetry without allowing telemetry failures to break the run."""
+ try:
+ self._log_agent_event(max_steps=max_steps, agent_run_error=agent_run_error)
+ except Exception as exc:
+ self.logger.error(f'Failed to log telemetry event: {exc}', exc_info=True)
+
def _log_action(self, action, action_name: str, action_num: int, total_actions: int) -> None:
"""Log an action before execution with Browser Use-style structure."""
action_header = f'[{action_num}/{total_actions}] {action_name}:' if total_actions > 1 else f'{action_name}:'
@@ -2801,6 +2808,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error='Rust agent stopped before terminal run.',
)
self.history = self.result
+ self._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent stopped before terminal run.')
await self._call_callback(on_step_end, self)
return self.history
if self.state.paused:
@@ -2814,6 +2822,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error='Rust agent is paused before terminal run.',
)
self.history = self.result
+ self._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent is paused before terminal run.')
await self._call_callback(on_step_end, self)
return self.history
if self.state.follow_up_task and self.terminal_session_id:
@@ -2842,6 +2851,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
)
self.history = self.result
self._sync_state_from_history()
+ self._record_run_telemetry(max_steps=max_steps, agent_run_error=process_error)
await self._check_and_update_downloads('run')
await self._save_conversation_if_requested()
await self._call_new_step_callback()
@@ -2880,6 +2890,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
)
self.history = self.result
self._sync_state_from_history()
+ resolved_max_steps = max_steps if max_steps is not None else self.kwargs.get('max_steps', 100)
+ self._record_run_telemetry(max_steps=resolved_max_steps, agent_run_error=process_error)
await self._check_and_update_downloads('follow_up')
await self._save_conversation_if_requested()
await self._call_new_step_callback()
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index e3c313f85..771b6fd8f 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -2944,6 +2944,78 @@ async def test_rust_agent_exposes_logging_helper_methods(monkeypatch):
assert captured_events[0].error_message == 'manual-error'
+async def test_rust_agent_run_records_terminal_telemetry(monkeypatch):
+ from browser_use.rust import Agent
+
+ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')
+ captured_events = []
+
+ class Telemetry:
+ def capture(self, event):
+ captured_events.append(event)
+
+ class LLM:
+ model = 'gpt-test'
+ provider = 'test-provider'
+
+ agent = Agent(task='Record telemetry.', llm=LLM(), source='ci')
+ agent.telemetry = Telemetry()
+
+ async def fake_run_process(argv, timeout_seconds=None):
+ return 0, 'Session: 12345678-1234-1234-1234-123456789abc\n', ''
+
+ async def fake_load_events():
+ return [
+ {'event_type': 'browser.state', 'payload': {'url': 'https://example.com', 'title': 'Example'}},
+ {'event_type': 'model.usage', 'payload': {'input_tokens': 13, 'output_tokens': 5}},
+ {'event_type': 'session.done', 'payload': {'result': 'telemetry answer'}},
+ ]
+
+ agent._run_process = fake_run_process
+ agent._load_events = fake_load_events
+
+ history = await agent.run(max_steps=5)
+
+ assert history.final_result() == 'telemetry answer'
+ assert len(captured_events) == 1
+ event = captured_events[0]
+ assert event.task == agent.task
+ assert event.max_steps == 5
+ assert event.model == 'gpt-test'
+ assert event.model_provider == 'test-provider'
+ assert event.urls_visited == ['https://example.com']
+ assert event.total_input_tokens == 13
+ assert event.total_output_tokens == 5
+ assert event.final_result_response == '"telemetry answer"'
+ assert event.error_message is None
+
+ class FailingTelemetry:
+ def capture(self, event):
+ raise RuntimeError('telemetry failed')
+
+ class RecordingLogger:
+ def __init__(self):
+ self.errors = []
+
+ def info(self, message, *args, **kwargs):
+ pass
+
+ def error(self, message, *args, **kwargs):
+ self.errors.append(message)
+
+ logger = RecordingLogger()
+ failing_agent = Agent(task='Record failing telemetry.', llm=LLM())
+ failing_agent.telemetry = FailingTelemetry()
+ monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))
+ failing_agent._run_process = fake_run_process
+ failing_agent._load_events = fake_load_events
+
+ failing_history = await failing_agent.run(max_steps=2)
+
+ assert failing_history.final_result() == 'telemetry answer'
+ assert logger.errors == ['Failed to log telemetry event: telemetry failed']
+
+
async def test_rust_agent_exposes_step_finalization_helper_methods(tmp_path):
import base64
import time