Skip to content

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

Log Rust agent run usage summaries

Magnus Müllerbbf36790d91d
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index 139a46b2d..e1eccb2eb 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -841,10 +841,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- Non-keep-alive browser sessions are closed automatically after completed, stopped, paused, and follow-up runs while the existing `close()` keep-alive behavior remains intact.
- Proof: `test_rust_agent_run_closes_non_keep_alive_browser_session`.
+166. Rust Agent token usage summary parity
+ - Terminal-backed `Agent.run()` and `Agent.follow_up()` now await Browser Use `token_cost_service.log_usage_summary()` after reconstructed Rust history is available.
+ - Usage-summary logging runs before telemetry/event finalization, matching the Python Agent's observable run finalization order.
+ - Proof: `test_rust_agent_run_logs_token_usage_summary`.
+
## 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` (137 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (138 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 d8a56c942..b765f946d 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -2790,6 +2790,10 @@ class Agent(Generic[Context, AgentStructuredOutput]):
except Exception as exc:
self.logger.error(f'Failed to log telemetry event: {exc}', exc_info=True)
+ async def _log_run_usage_summary(self) -> None:
+ """Log Browser Use token usage summary for a completed Rust-backed run."""
+ await self.token_cost_service.log_usage_summary()
+
def _cloud_event_agent(self):
llm_model_name = getattr(getattr(self, 'llm', None), 'model_name', None)
if isinstance(llm_model_name, str) and llm_model_name:
@@ -2880,6 +2884,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error='Rust agent stopped before terminal run.',
)
self.history = self.result
+ await self._log_run_usage_summary()
self._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent stopped before terminal run.')
self._dispatch_run_update_event()
await self._call_callback(on_step_end, self)
@@ -2896,6 +2901,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error='Rust agent is paused before terminal run.',
)
self.history = self.result
+ await self._log_run_usage_summary()
self._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent is paused before terminal run.')
self._dispatch_run_update_event()
await self._call_callback(on_step_end, self)
@@ -2927,6 +2933,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
)
self.history = self.result
self._sync_state_from_history()
+ await self._log_run_usage_summary()
self._record_run_telemetry(max_steps=max_steps, agent_run_error=process_error)
self._dispatch_run_update_event()
await self._check_and_update_downloads('run')
@@ -2970,6 +2977,7 @@ 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)
+ await self._log_run_usage_summary()
self._record_run_telemetry(max_steps=resolved_max_steps, agent_run_error=process_error)
self._dispatch_run_update_event()
await self._check_and_update_downloads('follow_up')
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index 404a69c97..403ea26c5 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -3016,6 +3016,42 @@ async def test_rust_agent_run_records_terminal_telemetry(monkeypatch):
assert logger.errors == ['Failed to log telemetry event: telemetry failed']
+async def test_rust_agent_run_logs_token_usage_summary(monkeypatch):
+ from browser_use.rust import Agent
+
+ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')
+ seen = []
+
+ class TokenCostService:
+ async def log_usage_summary(self):
+ seen.append(('usage_summary', agent.history.final_result()))
+
+ class Telemetry:
+ def capture(self, event):
+ seen.append(('telemetry', event.final_result_response))
+
+ agent = Agent(task='Log usage summary.', llm=type('LLM', (), {'model': 'gpt-test'})())
+ agent.token_cost_service = TokenCostService()
+ 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': 'session.done', 'payload': {'result': 'usage summary answer'}}]
+
+ agent._run_process = fake_run_process
+ agent._load_events = fake_load_events
+
+ history = await agent.run(max_steps=3)
+
+ assert history.final_result() == 'usage summary answer'
+ assert seen == [
+ ('usage_summary', 'usage summary answer'),
+ ('telemetry', '"usage summary answer"'),
+ ]
+
+
async def test_rust_agent_run_initializes_browser_use_session_state(monkeypatch):
from browser_use.rust import Agent