Repository navigation
Conversation
Adds `--env browser-use`, which creates a Browser Use Cloud browser through the REST API, connects Playwright over CDP, and stops the browser on exit (including when setup fails), since closing CDP alone does not stop it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CAqWMdQGK6TSv1ozTgUteS
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
There was a problem hiding this comment.
Code Review
This pull request introduces support for the Browser Use Cloud environment (browser-use) connected over CDP, adding the BrowserUseComputer class, updating CLI options, documentation, and adding corresponding unit tests. The review feedback suggests making the _cleanup method more robust to prevent exception masking and resource leaks, initializing self._http in __init__ to avoid potential AttributeErrors, and explicitly validating the presence of the BROWSER_USE_API_KEY environment variable to provide a clearer error message.
| def _cleanup(self): | ||
| # Closing the CDP connection does not stop a Browser Use Cloud browser, | ||
| # so always stop it explicitly to end billing. | ||
| try: | ||
| if self._browser: | ||
| self._browser.close() | ||
| if self._playwright: | ||
| self._playwright.stop() | ||
| finally: | ||
| if self._session_id: | ||
| self._http.patch( | ||
| f"/browsers/{self._session_id}", json={"action": "stop"} | ||
| ).raise_for_status() | ||
| self._session_id = None | ||
| self._http.close() |
There was a problem hiding this comment.
Make the _cleanup method more robust to prevent exception masking and resource leaks:
- Prevent Exception Masking: If
_cleanupis called within theexcept BaseException:block of__enter__(e.g., ifconnect_over_cdpfails), any exception raised during cleanup (such as a failedPATCHrequest) will suppress and mask the original error, making debugging extremely difficult. Catching and logging/printing cleanup errors prevents this. - Ensure Resource Release: If the
PATCHrequest fails or raises an exception,self._http.close()is currently skipped. Wrapping thePATCHcall andclose()in nestedtry...finallyblocks ensures that the HTTP client is always closed.
def _cleanup(self):
# Closing the CDP connection does not stop a Browser Use Cloud browser,
# so always stop it explicitly to end billing.
try:
if self._browser:
try:
self._browser.close()
except Exception as e:
print(f"Error closing browser: {e}")
if self._playwright:
try:
self._playwright.stop()
except Exception as e:
print(f"Error stopping playwright: {e}")
finally:
try:
if self._session_id and self._http:
self._http.patch(
f"/browsers/{self._session_id}", json={"action": "stop"}
).raise_for_status()
except Exception as e:
print(f"Error stopping Browser Use session: {e}")
finally:
self._session_id = None
if self._http:
try:
self._http.close()
except Exception as e:
print(f"Error closing HTTP client: {e}")| def __init__( | ||
| self, | ||
| screen_size: tuple[int, int], | ||
| initial_url: str = "https://www.google.com", | ||
| ): | ||
| super().__init__(screen_size, initial_url) | ||
| self._session_id = None | ||
| self._playwright = None | ||
| self._browser = None | ||
| self._context = None |
There was a problem hiding this comment.
Initialize self._http to None in __init__ to ensure the attribute always exists. This prevents potential AttributeErrors in _cleanup if cleanup is invoked before self._http is instantiated in __enter__.
| def __init__( | |
| self, | |
| screen_size: tuple[int, int], | |
| initial_url: str = "https://www.google.com", | |
| ): | |
| super().__init__(screen_size, initial_url) | |
| self._session_id = None | |
| self._playwright = None | |
| self._browser = None | |
| self._context = None | |
| def __init__( | |
| self, | |
| screen_size: tuple[int, int], | |
| initial_url: str = "https://www.google.com", | |
| ): | |
| super().__init__(screen_size, initial_url) | |
| self._session_id = None | |
| self._playwright = None | |
| self._browser = None | |
| self._context = None | |
| self._http = None |
| def __enter__(self): | ||
| print("Creating session...") | ||
| self._http = httpx.Client( | ||
| base_url=BROWSER_USE_API_URL, | ||
| headers={"X-Browser-Use-API-Key": os.environ["BROWSER_USE_API_KEY"]}, | ||
| timeout=60, | ||
| ) |
There was a problem hiding this comment.
Check for the presence of the BROWSER_USE_API_KEY environment variable explicitly and raise a clear ValueError if it is missing. This provides a much better user experience than a raw KeyError traceback when the key is not set.
def __enter__(self):
api_key = os.environ.get("BROWSER_USE_API_KEY")
if not api_key:
raise ValueError("BROWSER_USE_API_KEY environment variable is not set")
print("Creating session...")
self._http = httpx.Client(
base_url=BROWSER_USE_API_URL,
headers={"X-Browser-Use-API-Key": api_key},
timeout=60,
)A failed stop request during a failed start no longer hides the start error, and the HTTP client is always closed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CAqWMdQGK6TSv1ozTgUteS
Change
Adds a third environment,
--env browser-use, next toplaywrightandbrowserbase.computers/browser_use/browser_use.py:BrowserUseComputersubclassesPlaywrightComputer(same pattern asBrowserbaseComputer). On enter it creates a Browser Use Cloud browser withPOST /api/v4/browsersat the agent's screen size, connects withconnect_over_cdp, pins the viewport, and prints the live view URL. On exit it stops the browser withPATCH /api/v4/browsers/{id}.main.py,computers/__init__.py: wire the new env.README.md,.env.example: documentBROWSER_USE_API_KEY.requirements.txt: addshttpx(already installed throughgoogle-genai; listed because the new module imports it). No vendor SDK, so the existingpydantic==2.12.0pin is untouched.Why
Gives users a second hosted browser option for the reference implementation, with one env var and no extra SDK.
Proof
pytest: 17 passed (13 existing, 3 new intest_browser_use.py, 1 new intest_main.py). The new tests mock HTTP and Playwright and check the request shape, the CDP connect, the viewport, and that the cloud browser is stopped both on normal exit and when the CDP connect fails, and that a failed stop call does not hide the original connect error. Reverting the failure-path cleanup makestest_stops_browser_when_connect_failsfail.gemini-3.6-flash:python main.py --env=browser-use --initial_url=https://example.com --query="What is the main heading on this page? Answer with just the heading."The agent took screenshots and issued actions (
triple_click), returned the page text, exit 0. The browser API then reported the sessionstopped(two runs: 34 s and 16 s after start, $0.0003 browser cost each).Risk
finally. If that call itself fails, the browser times out server side (default 60 min).--env browser-use. Default env and existing envs are unchanged.Rollout / rollback
Opt in through
--env browser-use. Rollback is reverting this commit.🤖 Generated with Claude Code
https://claude.ai/code/session_01CAqWMdQGK6TSv1ozTgUteS