Skip to content

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

Apply Rust terminal session rollbacks

Magnus Müller39ec8c57ddd7
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index aa8c009a8..508e4dfd2 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -699,10 +699,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- This preserves provider replay/import reasoning summaries, including OpenAI Responses `summary_text` parts, while keeping assistant message response items on the existing memory surface.
- Proof: `test_rust_history_reconstructs_terminal_response_item_reasoning`.
+138. Rust terminal session-rollback reconstruction
+ - Terminal `session.rollback` events now filter rolled-back user turns before Browser Use history reconstruction.
+ - This keeps rolled-back model outputs, tool actions, tool results, usage, attachments, and final results off Python-visible surfaces such as `action_names()`, `model_outputs()`, `action_history()`, and `final_result()`.
+ - Proof: `test_rust_history_applies_terminal_session_rollback`.
+
## 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` (109 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (110 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 fc5cf65dc..d68219a61 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -702,6 +702,77 @@ def _event_payload(event: dict[str, Any]) -> dict[str, Any]:
return payload if isinstance(payload, dict) else {}
+def _event_seq(event: dict[str, Any]) -> int | None:
+ for key in ('seq', 'event_seq', 'sequence'):
+ value = event.get(key)
+ if isinstance(value, bool):
+ continue
+ if isinstance(value, int):
+ return value
+ return None
+
+
+def _rollback_turn_count(payload: dict[str, Any]) -> int:
+ for key in ('num_turns', 'turns', 'n'):
+ value = payload.get(key)
+ if isinstance(value, bool):
+ continue
+ if isinstance(value, int) and value >= 0:
+ return value
+ return 1
+
+
+def _is_terminal_user_turn_event(event: dict[str, Any]) -> bool:
+ event_type = _event_type(event)
+ if event_type in ('session.input', 'session.followup'):
+ return True
+ if event_type in ('agent.message', 'agent.mailbox_input'):
+ content = _event_payload(event).get('content')
+ return isinstance(content, str) and bool(content.strip())
+ return False
+
+
+def _contextual_event_targets_turn(event: dict[str, Any], target_seq: int | None) -> bool:
+ if target_seq is None:
+ return False
+ if _event_type(event) not in (
+ 'workspace.context',
+ 'model.switch_context',
+ 'model.personality_context',
+ 'model.collaboration_context',
+ 'model.generated_image_context',
+ ):
+ return False
+ before_seq = _event_payload(event).get('before_seq')
+ return isinstance(before_seq, int) and before_seq == target_seq
+
+
+def _rollback_last_terminal_user_turn(events: list[dict[str, Any]]) -> bool:
+ user_pos = next((index for index in range(len(events) - 1, -1, -1) if _is_terminal_user_turn_event(events[index])), None)
+ if user_pos is None:
+ return False
+ target_seq = _event_seq(events[user_pos])
+ truncate_at = user_pos
+ while truncate_at > 0 and _contextual_event_targets_turn(events[truncate_at - 1], target_seq):
+ truncate_at -= 1
+ del events[truncate_at:]
+ return True
+
+
+def _events_after_terminal_rollbacks(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ if not any(_event_type(event) == 'session.rollback' for event in events):
+ return events
+ replay_events: list[dict[str, Any]] = []
+ for event in events:
+ if _event_type(event) == 'session.rollback':
+ for _ in range(_rollback_turn_count(_event_payload(event))):
+ if not _rollback_last_terminal_user_turn(replay_events):
+ break
+ continue
+ replay_events.append(event)
+ return replay_events
+
+
def _result_file_pointer(payload: dict[str, Any]) -> str | None:
result_file = payload.get('result_file')
if isinstance(result_file, dict):
@@ -1499,6 +1570,7 @@ def _history_from_events(
output_model_schema: type[AgentStructuredOutput] | None,
process_error: str | None,
) -> AgentHistoryList[AgentStructuredOutput]:
+ events = _events_after_terminal_rollbacks(events)
final_result = _structured_result_text(_result_from_events(events), output_model_schema)
failure = process_error or _failure_from_events(events)
if final_result is None and failure is None:
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index 209a2fbb5..77611503b 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -683,6 +683,85 @@ def test_rust_history_reconstructs_terminal_model_turn_steps():
assert history.is_done() is True
+def test_rust_history_applies_terminal_session_rollback():
+ from browser_use.rust.service import _history_from_events
+
+ history = _history_from_events(
+ [
+ {'event_type': 'session.input', 'seq': 1, 'payload': {'text': 'first task'}},
+ {'event_type': 'model.turn.request', 'seq': 2, 'ts_ms': 2_000, 'payload': {'model': 'gpt-test'}},
+ {'event_type': 'model.stream_delta', 'seq': 3, 'payload': {'text': 'First turn'}},
+ {
+ 'event_type': 'tool.started',
+ 'seq': 4,
+ 'payload': {
+ 'name': 'browser',
+ 'tool_call_id': 'call-first',
+ 'arguments': {'cmd': 'connect managed --headless'},
+ },
+ },
+ {
+ 'event_type': 'tool.output',
+ 'seq': 5,
+ 'payload': {'name': 'browser', 'tool_call_id': 'call-first', 'text': 'First kept'},
+ },
+ {'event_type': 'session.followup', 'seq': 6, 'payload': {'text': 'second task'}},
+ {'event_type': 'model.turn.request', 'seq': 7, 'ts_ms': 3_000, 'payload': {'model': 'gpt-test'}},
+ {'event_type': 'model.stream_delta', 'seq': 8, 'payload': {'text': 'Second rolled back'}},
+ {
+ 'event_type': 'tool.started',
+ 'seq': 9,
+ 'payload': {
+ 'name': 'browser_script',
+ 'tool_call_id': 'call-second',
+ 'arguments': {'code': "goto_url('https://rolled-back.example')"},
+ },
+ },
+ {
+ 'event_type': 'tool.output',
+ 'seq': 10,
+ 'payload': {'name': 'browser_script', 'tool_call_id': 'call-second', 'text': 'Second removed'},
+ },
+ {'event_type': 'session.done', 'seq': 11, 'payload': {'result': 'Rolled Back Result'}},
+ {'event_type': 'session.rollback', 'seq': 12, 'payload': {'num_turns': 1}},
+ {'event_type': 'session.followup', 'seq': 13, 'payload': {'text': 'third task'}},
+ {'event_type': 'model.turn.request', 'seq': 14, 'ts_ms': 4_000, 'payload': {'model': 'gpt-test'}},
+ {'event_type': 'model.stream_delta', 'seq': 15, 'payload': {'text': 'Third turn'}},
+ {
+ 'event_type': 'tool.started',
+ 'seq': 16,
+ 'payload': {
+ 'name': 'browser_script',
+ 'tool_call_id': 'call-third',
+ 'arguments': {'code': "goto_url('https://example.com')"},
+ },
+ },
+ {
+ 'event_type': 'tool.output',
+ 'seq': 17,
+ 'payload': {'name': 'browser_script', 'tool_call_id': 'call-third', 'text': 'Third kept'},
+ },
+ {'event_type': 'session.done', 'seq': 18, 'payload': {'result': 'Third result'}},
+ ],
+ model='gpt-test',
+ started=1.0,
+ finished=5.0,
+ output_model_schema=None,
+ process_error=None,
+ )
+
+ serialized_actions = json.dumps(history.model_actions(), sort_keys=True)
+
+ assert history.number_of_steps() == 2
+ assert history.action_names() == ['browser', 'browser_script', 'done']
+ assert [output.memory for output in history.model_outputs()] == ['First turn', 'Third turn']
+ assert history.action_history()[0][0]['result'] == 'First kept'
+ assert history.action_history()[1][0]['result'] == 'Third kept'
+ assert history.final_result() == 'Third result'
+ assert 'Second rolled back' not in serialized_actions
+ assert 'rolled-back.example' not in serialized_actions
+
+
def test_rust_history_reconstructs_terminal_streamed_model_thoughts():
from browser_use.rust.service import _history_from_events