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
Add Rust agent session identity parity
Magnus Müller32a579cc30bf
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex b8fc7b440..5df670356 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -446,10 +446,15 @@ Terminal core branch: `magnus/browser-use-rust-integration` at terminal main `ee- GIF creation uses Browser Use's `create_history_gif(...)` with the same default `agent_history.gif` output path or caller-provided string path.- Proof: `test_rust_agent_generates_gif_after_done_callback`.+88. Rust Agent session identity parity+ - The Rust-backed `Agent` now initializes `agent.session_id` during construction as a Browser Use agent session id, matching the Python Agent public interface.+ - Rust terminal session identity is tracked separately as `agent.terminal_session_id` and is used for `run-codex-session`, event loading, follow-ups, and transcript metadata.+ - Proof: `test_rust_agent_keeps_browser_use_session_id_separate_from_terminal_session`.+## Current Verification- `python3 -m py_compile 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` (61 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (62 tests)- `cargo build -q -p browser-use-cli`- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent selected_remote_cdp_mode_allows_remote_cdp_connect -- --nocapture`- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent bare_browser_connect_resolves_to_selected_managed_mode_with_launch_args -- --nocapture`diff --git a/browser_use/rust/service.py b/browser_use/rust/service.pyindex 5b9f4fffa..5e13285e2 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -1222,7 +1222,8 @@ class Agent(Generic[AgentStructuredOutput]):include_recent_events=self.include_recent_events,sample_images=self.sample_images,)- self.session_id: str | None = None+ self.session_id: str = uuid7str()+ self.terminal_session_id: str | None = Noneself.history: AgentHistoryList[AgentStructuredOutput] = AgentHistoryList(history=[], usage=None)self.result: AgentHistoryList[AgentStructuredOutput] | None = Noneself.last_events: list[dict[str, Any]] = []@@ -1265,7 +1266,7 @@ class Agent(Generic[AgentStructuredOutput]):self.history = self.resultawait self._call_callback(on_step_end, self)return self.history- if self.state.follow_up_task and self.session_id:+ if self.state.follow_up_task and self.terminal_session_id:self.state.follow_up_task = Falsereturn await self.follow_up(self.task, max_steps=max_steps)@@ -1273,12 +1274,12 @@ class Agent(Generic[AgentStructuredOutput]):finished = time.time()self.last_stdout = stdout_textself.last_stderr = stderr_text- self.session_id = self._session_id_from_stdout(stdout_text)+ self.terminal_session_id = self._session_id_from_stdout(stdout_text)events = await self._load_events()process_error = Noneif returncode:process_error = stderr_text.strip() or f'browser-use-terminal exited with code {returncode}'- elif not self.session_id:+ elif not self.terminal_session_id:process_error = 'browser-use-terminal did not print a session id.'self.last_events = eventsself.result = _history_from_events(@@ -1300,12 +1301,12 @@ class Agent(Generic[AgentStructuredOutput]):return self.historyasync def follow_up(self, task: str, max_steps: int | None = None) -> AgentHistoryList[AgentStructuredOutput]:- if not self.session_id:+ if not self.terminal_session_id:raise RustAgentError('No active Rust session. Call run() before follow_up().')started = time.time()binary = find_browser_use_terminal_binary()returncode, stdout_text, stderr_text = await self._run_process(- [binary, *self._state_dir_args(), 'followup', self.session_id, task],+ [binary, *self._state_dir_args(), 'followup', self.terminal_session_id, task],timeout_seconds=self.settings.step_timeout,)if returncode:@@ -1471,7 +1472,7 @@ class Agent(Generic[AgentStructuredOutput]):return [done_result]instruction = _actions_instruction(payloads)max_steps = max(1, len(payloads))- if self.session_id:+ if self.terminal_session_id:history = await self.follow_up(instruction, max_steps=max_steps)return history.action_results()original_task = self.task@@ -1731,6 +1732,7 @@ class Agent(Generic[AgentStructuredOutput]):'agent': 'browser_use.rust.Agent','task_id': self.task_id,'session_id': self.session_id,+ 'terminal_session_id': self.terminal_session_id,'model': self.model,'browser_mode': self._browser_mode(),'task': self.task,@@ -1765,7 +1767,7 @@ class Agent(Generic[AgentStructuredOutput]):return Falsedef _run_existing_argv(self, max_steps: int) -> list[str]:- if not self.session_id:+ if not self.terminal_session_id:raise RustAgentError('No active Rust session. Call run() before rerunning an existing session.')binary = find_browser_use_terminal_binary()return [@@ -1776,7 +1778,7 @@ class Agent(Generic[AgentStructuredOutput]):'-c',f'browser_mode="{self._browser_mode()}"','run-codex-session',- self.session_id,+ self.terminal_session_id,'--model',self.model,]@@ -1858,14 +1860,14 @@ class Agent(Generic[AgentStructuredOutput]):return Noneasync def _load_events(self) -> list[dict[str, Any]]:- if not self.session_id:+ if not self.terminal_session_id:return []binary = find_browser_use_terminal_binary()proc = await asyncio.create_subprocess_exec(binary,*self._state_dir_args(),'events',- self.session_id,+ self.terminal_session_id,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,env=self._run_env(),diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 9704fa75a..31bd8720e 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -964,15 +964,42 @@ def test_rust_agent_translates_followup_to_existing_terminal_session(monkeypatchmonkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')agent = Agent(task='start', llm=type('LLM', (), {'model': 'gpt-test'})())- agent.session_id = '12345678-1234-1234-1234-123456789abc'+ agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'argv = agent._run_existing_argv(max_steps=9)assert argv[0] == '/tmp/browser-use-terminal'- assert argv[-4:] == ['run-codex-session', agent.session_id, '--model', 'gpt-test']+ assert argv[-4:] == ['run-codex-session', agent.terminal_session_id, '--model', 'gpt-test']assert 'max_turns=9' in argv+async def test_rust_agent_keeps_browser_use_session_id_separate_from_terminal_session(monkeypatch):+ from browser_use.rust import Agent++ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')+ agent = Agent(task='start', task_id='task-1', llm=type('LLM', (), {'model': 'gpt-test'})())+ browser_use_session_id = agent.session_id++ assert isinstance(browser_use_session_id, str)+ assert browser_use_session_id+ assert agent.terminal_session_id is None++ 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': 'session answer'}}]++ agent._run_process = fake_run_process+ agent._load_events = fake_load_events++ await agent.run(max_steps=1)++ assert agent.session_id == browser_use_session_id+ assert agent.terminal_session_id == '12345678-1234-1234-1234-123456789abc'+ assert agent.session_id != agent.terminal_session_id++async def test_rust_agent_invokes_browser_use_style_callbacks(monkeypatch):from browser_use.rust import Agent@@ -1316,7 +1343,7 @@ async def test_rust_agent_multi_act_routes_actions_to_followup():from browser_use.rust.service import _history_from_eventsagent = Agent(task='act on current page')- agent.session_id = '12345678-1234-1234-1234-123456789abc'+ agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'seen = []async def fake_follow_up(task, max_steps=None):@@ -1405,7 +1432,8 @@ async def test_rust_agent_saves_terminal_conversation(tmp_path, monkeypatch):assert len(files) == 1snapshot = json.loads(files[0].read_text(encoding='utf-8'))assert snapshot['task_id'] == 'task-1'- assert snapshot['session_id'] == '12345678-1234-1234-1234-123456789abc'+ assert snapshot['session_id'] == agent.session_id+ assert snapshot['terminal_session_id'] == '12345678-1234-1234-1234-123456789abc'assert snapshot['final_result'] == 'saved transcript'assert snapshot['events'][0]['event_type'] == 'browser.state'assert agent.state.n_steps == 2