Skip to content

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

Handle Rust agent close cleanup errors

Magnus Müllercb3cf78cb0b7
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index 3f87abe4d..bd8a0b01c 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -810,10 +810,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- Keep-alive sessions are preserved, and lightweight custom sessions without a Browser Use browser process remain safe.
- Proof: `test_rust_agent_close_kills_non_keep_alive_browser_session`.
+160. Rust Agent close cleanup-error parity
+ - `Agent.close()` now mirrors Browser Use cleanup resilience by logging browser-session cleanup failures instead of propagating them to callers.
+ - This keeps close idempotent and safe for user cleanup/finally blocks even when a supplied BrowserSession fails during `kill()`.
+ - Proof: `test_rust_agent_close_logs_cleanup_errors_without_raising`.
+
## 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` (131 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (132 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 798d445dd..727c8365c 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -3607,17 +3607,20 @@ class Agent(Generic[Context, AgentStructuredOutput]):
async def close(self):
"""Close Browser Use session resources when the caller did not request keep-alive."""
- if self.browser_session is not None:
- profile = getattr(self.browser_session, 'browser_profile', None) or self.browser_profile
- if not getattr(profile, 'keep_alive', False):
- kill = getattr(self.browser_session, 'kill', None)
- if callable(kill):
- result = kill()
- if inspect.isawaitable(result):
- await result
- import gc
-
- gc.collect()
+ try:
+ if self.browser_session is not None:
+ profile = getattr(self.browser_session, 'browser_profile', None) or self.browser_profile
+ if not getattr(profile, 'keep_alive', False):
+ kill = getattr(self.browser_session, 'kill', None)
+ if callable(kill):
+ result = kill()
+ if inspect.isawaitable(result):
+ await result
+ import gc
+
+ gc.collect()
+ except Exception as exc:
+ self.logger.error(f'Error during cleanup: {exc}')
return None
async def log_completion(self) -> None:
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index aaf8567e8..e3c313f85 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -3454,6 +3454,34 @@ async def test_rust_agent_close_kills_non_keep_alive_browser_session():
assert keep_alive_session.kill_calls == 0
+async def test_rust_agent_close_logs_cleanup_errors_without_raising(monkeypatch):
+ from browser_use.rust import Agent
+
+ class RecordingLogger:
+ def __init__(self):
+ self.errors = []
+
+ def error(self, message, *args, **kwargs):
+ self.errors.append(message)
+
+ logger = RecordingLogger()
+ monkeypatch.setattr(Agent, 'logger', property(lambda self: logger))
+
+ class BrowserProfile:
+ keep_alive = False
+
+ class BrowserSession:
+ browser_profile = BrowserProfile()
+
+ async def kill(self):
+ raise RuntimeError('cleanup failed')
+
+ agent = Agent(task='close failed session', browser_session=BrowserSession(), directly_open_url=False)
+
+ assert await agent.close() is None
+ assert logger.errors == ['Error during cleanup: cleanup failed']
+
+
async def test_rust_agent_check_stop_or_pause_matches_browser_use_lifecycle():
from browser_use.rust import Agent