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 prepare context parity
Magnus Müller15bfe2903894
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex d0b54a3b2..0b02fafa8 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -506,10 +506,15 @@ Terminal core branch: `magnus/browser-use-rust-integration` at terminal main `ee- The helpers preserve long-URL restoration in parsed LLM actions, max-action truncation, empty-action retry, step callbacks, conversation saving, and action execution through the Rust-backed `multi_act` path.- Proof: `test_rust_agent_exposes_model_output_helper_methods`.+100. Rust Agent prepare-context helper parity+ - The Rust-backed `Agent` now exposes Browser Use's `_prepare_context(...)` helper.+ - The helper captures browser state with screenshots/recent events, updates downloads, logs step context, refreshes page-filtered action models, creates state messages with sensitive-data and available-file context, and applies last-step/failure done-only switching.+ - Proof: `test_rust_agent_exposes_prepare_context_helper_method`.+## 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` (73 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (74 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 4b35e8cc3..ab7948f2a 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -1788,6 +1788,43 @@ class Agent(Generic[AgentStructuredOutput]):"""Save current Browser Use file system state back onto AgentState."""self.state.file_system_state = self.file_system.get_state()+ async def _prepare_context(self, step_info: AgentStepInfo | None = None) -> Any:+ """Prepare Browser Use step context from the configured browser session."""+ if self.browser_session is None:+ raise AssertionError('BrowserSession is not set up')+ get_state = getattr(self.browser_session, 'get_browser_state_summary', None)+ if not callable(get_state):+ raise ValueError('BrowserSession does not expose get_browser_state_summary')++ browser_state_summary = await get_state(+ include_screenshot=True,+ include_recent_events=self.include_recent_events,+ )+ await self._check_and_update_downloads(f'Step {self.state.n_steps}: after getting browser state')+ self._log_step_context(browser_state_summary)+ await self._check_stop_or_pause()+ await self._update_action_models_for_page(browser_state_summary.url)++ page_filtered_actions = None+ registry = getattr(getattr(self.tools, 'registry', None), 'get_prompt_description', None)+ if callable(registry):+ page_filtered_actions = registry(browser_state_summary.url)++ self._message_manager.create_state_messages(+ browser_state_summary=browser_state_summary,+ model_output=self.state.last_model_output,+ result=self.state.last_result,+ step_info=step_info,+ use_vision=self.settings.use_vision,+ page_filtered_actions=page_filtered_actions if page_filtered_actions else None,+ sensitive_data=self.sensitive_data,+ available_file_paths=self.available_file_paths,+ )++ await self._force_done_after_last_step(step_info)+ await self._force_done_after_failure()+ return browser_state_summary+async def get_model_output(self, input_messages: list[Any]) -> AgentOutput:"""Get next Browser Use action output from the configured Python LLM."""if self.llm is None or not hasattr(self.llm, 'ainvoke'):diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex fb4481c29..9cf3805ae 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -1913,6 +1913,84 @@ async def test_rust_agent_exposes_model_output_helper_methods(tmp_path):assert retry_output.action+async def test_rust_agent_exposes_prepare_context_helper_method(monkeypatch):+ from types import SimpleNamespace++ from browser_use.agent.views import AgentStepInfo+ from browser_use.rust import Agent++ state_requests = []+ browser_state = SimpleNamespace(+ url='https://example.com/settings',+ title='Settings',+ screenshot='base64-screen',+ dom_state=SimpleNamespace(selector_map={1: object(), 2: object()}),+ )++ class BrowserProfile:+ downloads_path = None++ class BrowserSession:+ browser_profile = BrowserProfile()++ async def get_browser_state_summary(self, include_screenshot=False, include_recent_events=False):+ state_requests.append((include_screenshot, include_recent_events))+ return browser_state++ agent = Agent(+ task='Prepare context.',+ browser_session=BrowserSession(),+ include_recent_events=True,+ use_vision=False,+ available_file_paths=['/tmp/input.txt'],+ sensitive_data={'api_key': 'secret-value'},+ )+ download_contexts = []+ updated_pages = []+ prompt_urls = []+ created_messages = []++ async def fake_check_downloads(context=''):+ download_contexts.append(context)++ async def fake_update_action_models(page_url):+ updated_pages.append(page_url)++ def fake_prompt_description(page_url):+ prompt_urls.append(page_url)+ return 'filtered action prompt'++ def fake_create_state_messages(**kwargs):+ created_messages.append(kwargs)++ monkeypatch.setattr(agent, '_check_and_update_downloads', fake_check_downloads)+ monkeypatch.setattr(agent, '_update_action_models_for_page', fake_update_action_models)+ monkeypatch.setattr(agent.tools.registry, 'get_prompt_description', fake_prompt_description)+ monkeypatch.setattr(agent._message_manager, 'create_state_messages', fake_create_state_messages)++ step_info = AgentStepInfo(step_number=2, max_steps=3)+ result = await agent._prepare_context(step_info)++ assert result is browser_state+ assert state_requests == [(True, True)]+ assert download_contexts == ['Step 1: after getting browser state']+ assert updated_pages == ['https://example.com/settings']+ assert prompt_urls == ['https://example.com/settings']+ assert created_messages == [+ {+ 'browser_state_summary': browser_state,+ 'model_output': agent.state.last_model_output,+ 'result': agent.state.last_result,+ 'step_info': step_info,+ 'use_vision': False,+ 'page_filtered_actions': 'filtered action prompt',+ 'sensitive_data': {'api_key': 'secret-value'},+ 'available_file_paths': ['/tmp/input.txt'],+ }+ ]+ assert agent.AgentOutput is agent.DoneAgentOutput++async def test_rust_agent_trace_and_cloud_auth_helpers():from browser_use.rust import Agentfrom browser_use.rust.service import _history_from_events