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
Close Rust agent after runs
Magnus Müller2b1cfd0c761b
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.mdindex 8c7e82331..139a46b2d 100644--- a/RUST_AGENT_INTEGRATION_FEATURES.md+++ b/RUST_AGENT_INTEGRATION_FEATURES.md@@ -836,10 +836,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai- The output-file event carries the generated GIF file name, `image/gif` content type, task ID, and base64 file content before the run eventbus is stopped.- Proof: `test_rust_agent_dispatches_gif_output_file_event`.+165. Rust Agent run close-cleanup parity+ - Terminal-backed `Agent.run()` and `Agent.follow_up()` now mirror Browser Use's final cleanup ordering by stopping the run eventbus and calling `close()` before returning history.+ - Non-keep-alive browser sessions are closed automatically after completed, stopped, paused, and follow-up runs while the existing `close()` keep-alive behavior remains intact.+ - Proof: `test_rust_agent_run_closes_non_keep_alive_browser_session`.+## 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` (136 tests)+- `uv run pytest -q tests/ci/test_rust_agent.py` (137 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 8215a072b..d8a56c942 100644--- a/browser_use/rust/service.py+++ b/browser_use/rust/service.py@@ -2829,6 +2829,11 @@ class Agent(Generic[Context, AgentStructuredOutput]):await resultself._eventbus_stopped = True+ async def _finalize_run_cleanup(self) -> None:+ """Mirror Browser Use run cleanup ordering."""+ await self._stop_eventbus_after_run()+ await self.close()+def _initialize_run_lifecycle_state(self) -> None:"""Initialize Browser Use run timing and session state."""self._session_start_time = time.time()@@ -2878,7 +2883,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent stopped before terminal run.')self._dispatch_run_update_event()await self._call_callback(on_step_end, self)- await self._stop_eventbus_after_run()+ await self._finalize_run_cleanup()return self.historyif self.state.paused:finished = time.time()@@ -2894,7 +2899,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._record_run_telemetry(max_steps=max_steps, agent_run_error='Rust agent is paused before terminal run.')self._dispatch_run_update_event()await self._call_callback(on_step_end, self)- await self._stop_eventbus_after_run()+ await self._finalize_run_cleanup()return self.historyif self.state.follow_up_task and self.terminal_session_id:self.state.follow_up_task = False@@ -2930,7 +2935,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):await self._call_callback(on_step_end, self)await self._call_done_callback()await self._generate_gif_if_requested()- await self._stop_eventbus_after_run()+ await self._finalize_run_cleanup()return self.historyasync def follow_up(self, task: str, max_steps: int | None = None) -> AgentHistoryList[AgentStructuredOutput]:@@ -2972,7 +2977,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):await self._call_new_step_callback()await self._call_done_callback()await self._generate_gif_if_requested()- await self._stop_eventbus_after_run()+ await self._finalize_run_cleanup()return self.historyfollow_up_task = follow_updiff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.pyindex 9b0e75532..404a69c97 100644--- a/tests/ci/test_rust_agent.py+++ b/tests/ci/test_rust_agent.py@@ -3652,6 +3652,51 @@ async def test_rust_agent_close_kills_non_keep_alive_browser_session():assert keep_alive_session.kill_calls == 0+async def test_rust_agent_run_closes_non_keep_alive_browser_session(monkeypatch):+ from browser_use.rust import Agent++ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')++ class BrowserProfile:+ keep_alive = False+ viewport = {'width': 1280, 'height': 720}+ user_agent = None+ headless = True+ allowed_domains = []++ class BrowserSession:+ id = 'browser-session-1234'+ browser_profile = BrowserProfile()++ def __init__(self):+ self.kill_calls = 0++ async def kill(self):+ self.kill_calls += 1++ session = BrowserSession()+ agent = Agent(+ task='Run cleanup closes session.',+ llm=type('LLM', (), {'model': 'gpt-test'})(),+ browser_session=session,+ directly_open_url=False,+ )++ 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': 'cleanup answer'}}]++ agent._run_process = fake_run_process+ agent._load_events = fake_load_events++ history = await agent.run(max_steps=1)++ assert history.final_result() == 'cleanup answer'+ assert session.kill_calls == 1++async def test_rust_agent_close_logs_cleanup_errors_without_raising(monkeypatch):from browser_use.rust import Agent