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
Initialize Rust agent run session state
Magnus Müllere57d55215c0b
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex f1ff7be0e..f67d9fd36 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -820,10 +820,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai- 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`.+162. Rust Agent run session-state parity+ - Terminal-backed `Agent.run()` and `Agent.follow_up()` now initialize Browser Use run lifecycle state before execution.+ - The wrapper sets `_session_start_time`, `_task_start_time`, and flips `state.session_initialized`, matching the observable Python Agent state callers can inspect around completed runs.+ - Proof: `test_rust_agent_run_initializes_browser_use_session_state`.+## 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` (133 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (134 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 b119ab04b..5802b0ed3 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -2769,6 +2769,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):except Exception as exc:self.logger.error(f'Failed to log telemetry event: {exc}', exc_info=True)+ def _initialize_run_lifecycle_state(self) -> None:+ """Initialize Browser Use run timing and session state."""+ self._session_start_time = time.time()+ self._task_start_time = self._session_start_time+ if not self.state.session_initialized:+ self.state.session_initialized = 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}:'@@ -2796,6 +2803,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):on_step_end: AgentHookFunc | None = None,) -> AgentHistoryList[AgentStructuredOutput]:await self._call_callback(on_step_start, self)+ self._initialize_run_lifecycle_state()started = time.time()if await self._should_stop_before_run():finished = time.time()@@ -2863,6 +2871,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):async def follow_up(self, task: str, max_steps: int | None = None) -> AgentHistoryList[AgentStructuredOutput]:if not self.terminal_session_id:raise RustAgentError('No active Rust session. Call run() before follow_up().')+ self._initialize_run_lifecycle_state()started = time.time()binary = find_browser_use_terminal_binary()returncode, stdout_text, stderr_text = await self._run_process(diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 771b6fd8f..5c42613c4 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -3016,6 +3016,33 @@ 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_initializes_browser_use_session_state(monkeypatch):+ from browser_use.rust import Agent++ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')+ agent = Agent(task='Initialize session state.', llm=type('LLM', (), {'model': 'gpt-test'})())++ assert agent.state.session_initialized is False+ assert not hasattr(agent, '_session_start_time')+ assert not hasattr(agent, '_task_start_time')++ 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': 'initialized'}}]++ agent._run_process = fake_run_process+ agent._load_events = fake_load_events++ history = await agent.run(max_steps=4)++ assert history.final_result() == 'initialized'+ assert agent.state.session_initialized is True+ assert agent._session_start_time > 0+ assert agent._task_start_time == agent._session_start_time++async def test_rust_agent_exposes_step_finalization_helper_methods(tmp_path):import base64import time