Skip to content

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

Keep Rust terminal steps monotonic

Magnus Müllerf11cfbd6cae2
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index 555f6d2b0..60494ecd6 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -1006,10 +1006,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- Follow-up terminal stdout/stderr from both the append and rerun subprocesses are now preserved on the agent and in saved conversation snapshots.
- Proof: `test_rust_agent_direct_follow_up_updates_task_state_and_transcript`.
+199. Rust Agent monotonic terminal step-state parity
+ - Reconstructed terminal histories now advance Browser Use-facing `agent.state.n_steps` cumulatively by reconstructed history item count instead of replacing it with a terminal run-local step number.
+ - Re-syncing the same history object is idempotent, while subsequent `run()`/`follow_up()` histories produce distinct conversation snapshot step suffixes and monotonic new-step callback numbers.
+ - Proof: `test_rust_agent_sync_state_counts_terminal_histories_monotonically`, `test_rust_agent_direct_follow_up_updates_task_state_and_transcript`.
+
## 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` (167 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (168 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`
@@ -1091,6 +1096,7 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- Follow-up/callback script output: `{"smoke": "python_api_followup_callbacks", "first": "Example Domain", "second": "example.com", "callback_kinds": ["step", "done", "step", "done"], "conversation_files": 2}`.
- Initial-actions/files/structured-output script output: `{"smoke": "python_api_initial_files_structured", "answer": {"title": "Example Domain", "host": "example.com", "marker": "file-marker-ok"}, "history_urls": ["", "", "", "https://example.com", "https://example.com"], "available_files": ["/tmp/.../input-note.txt"]}`.
- 2026-06-03 rerun after step-error parity: both scripts passed concurrently through the Python `Agent` import with `provider=rust-terminal`; follow-up/callback output was `Example Domain` then `example.com`, and initial-actions/files/structured-output produced `{"title":"Example Domain","host":"example.com","marker":"file-marker-ok"}`.
+ - 2026-06-03 rerun after monotonic step-state parity: both scripts passed concurrently through the Python `Agent` import with `provider=rust-terminal`; follow-up/callback/conversation output was `{"first":"Example Domain","second":"example.com","step_numbers":[4,14],"conversation_files":2}`, and initial-actions/files/structured-output produced `{"title":"Example Domain","host":"example.com","marker":"file-marker-monotonic-smoke"}`.
- Multi-feature Python API cloud end-to-end:
- Source `/home/exedev/.evaluation_tool_env`, unset browser-mode overrides, and construct `Agent(..., browser_profile=BrowserProfile(use_cloud=True), register_new_step_callback=..., register_done_callback=..., save_conversation_path=..., step_timeout=300)`.
- Output: first run `Example Domain`; follow-up `example.com`; callback sequence `step, done, step, done`; two conversation JSON snapshots written; terminal session id present.
diff --git a/browser_use/rust/service.py b/browser_use/rust/service.py
index 9e2faaf5b..84bf7e0bd 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -2607,6 +2607,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self.last_events: list[dict[str, Any]] = []
self.last_stdout = ''
self.last_stderr = ''
+ self._last_synced_history_id: int | None = None
self._external_pause_event = asyncio.Event()
self._external_pause_event.set()
@@ -4074,17 +4075,17 @@ class Agent(Generic[Context, AgentStructuredOutput]):
if self.register_new_step_callback is None or not self.history.history:
return
history_item = self.history.history[-1]
- step_number = history_item.metadata.step_number if history_item.metadata else len(self.history.history)
- result = self.register_new_step_callback(history_item.state, None, step_number)
+ result = self.register_new_step_callback(history_item.state, None, self.state.n_steps)
if inspect.isawaitable(result):
await result
def _sync_state_from_history(self) -> None:
if not self.history.history:
return
- metadata = self.history.history[-1].metadata
- if metadata is not None:
- self.state.n_steps = metadata.step_number
+ history_id = id(self.history)
+ if history_id != self._last_synced_history_id:
+ self.state.n_steps += max(1, len(self.history.history))
+ self._last_synced_history_id = history_id
action_results = self.history.action_results()
if action_results:
self.state.last_result = action_results
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index bdba25080..43c1d50b7 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -4190,12 +4190,19 @@ async def test_rust_agent_direct_follow_up_updates_task_state_and_transcript(tmp
monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')
process_calls = []
load_count = 0
+ step_numbers = []
+
+ def new_step_callback(browser_state, model_output, step_number):
+ step_numbers.append(step_number)
+
agent = Agent(
task='Start direct follow-up state.',
llm=type('LLM', (), {'model': 'gpt-test'})(),
task_id='direct-followup',
save_conversation_path=tmp_path,
+ register_new_step_callback=new_step_callback,
)
+ starting_steps = agent.state.n_steps
async def fake_run_process(argv, timeout_seconds=None):
process_calls.append(argv)
@@ -4226,15 +4233,23 @@ async def test_rust_agent_direct_follow_up_updates_task_state_and_transcript(tmp
'12345678-1234-1234-1234-123456789abc',
'Direct raw follow-up task.',
]
+ assert step_numbers == [starting_steps + 1, starting_steps + 2]
+ assert agent.state.n_steps == starting_steps + 2
assert agent.last_stdout == 'followup accepted\nrerun stdout'
assert agent.last_stderr == 'followup stderr\nrerun stderr'
- files = list(tmp_path.glob('conversation_direct-followup_*.json'))
- assert len(files) == 1
- snapshot = json.loads(files[0].read_text(encoding='utf-8'))
- assert snapshot['task'] == 'Direct raw follow-up task.'
- assert snapshot['stdout'] == 'followup accepted\nrerun stdout'
- assert snapshot['stderr'] == 'followup stderr\nrerun stderr'
+ files = sorted(tmp_path.glob('conversation_direct-followup_*.json'))
+ assert [path.name for path in files] == [
+ f'conversation_direct-followup_{starting_steps + 1}.json',
+ f'conversation_direct-followup_{starting_steps + 2}.json',
+ ]
+ initial_snapshot = json.loads(files[0].read_text(encoding='utf-8'))
+ follow_up_snapshot = json.loads(files[1].read_text(encoding='utf-8'))
+ assert initial_snapshot['task'] == 'Start direct follow-up state.'
+ assert initial_snapshot['final_result'] == 'direct follow-up 1'
+ assert follow_up_snapshot['task'] == 'Direct raw follow-up task.'
+ assert follow_up_snapshot['stdout'] == 'followup accepted\nrerun stdout'
+ assert follow_up_snapshot['stderr'] == 'followup stderr\nrerun stderr'
async def test_rust_agent_run_logs_browser_use_lifecycle_dispatch(monkeypatch):
@@ -5122,6 +5137,41 @@ def test_rust_agent_lifecycle_state_and_save_history(tmp_path):
assert 'saved answer' in history_file.read_text(encoding='utf-8')
+def test_rust_agent_sync_state_counts_terminal_histories_monotonically():
+ from browser_use.rust import Agent
+ from browser_use.rust.service import _history_from_events
+
+ def history_from_result(result: str):
+ return _history_from_events(
+ [{'event_type': 'session.done', 'payload': {'result': result}}],
+ model='gpt-test',
+ started=1.0,
+ finished=2.0,
+ output_model_schema=None,
+ process_error=None,
+ )
+
+ agent = Agent(task='Sync terminal history steps.', llm=type('LLM', (), {'model': 'gpt-test'})())
+ starting_steps = agent.state.n_steps
+
+ agent.history = history_from_result('first answer')
+ agent._sync_state_from_history()
+
+ assert agent.state.n_steps == starting_steps + 1
+ assert agent.state.last_result is not None
+ assert agent.state.last_result[-1].extracted_content == 'first answer'
+
+ agent._sync_state_from_history()
+ assert agent.state.n_steps == starting_steps + 1
+
+ agent.history = history_from_result('follow-up answer')
+ agent._sync_state_from_history()
+
+ assert agent.state.n_steps == starting_steps + 2
+ assert agent.state.last_result is not None
+ assert agent.state.last_result[-1].extracted_content == 'follow-up answer'
+
+
async def test_rust_agent_close_kills_non_keep_alive_browser_session():
from browser_use.rust import Agent