Skip to content

Add Browser Use Cloud browser environment - #124

Draft
gregpr07 wants to merge 2 commits into
google-gemini:mainfrom
gregpr07:browser-use-env
Draft

gregpr07 wants to merge 2 commits into
google-gemini:mainfrom
gregpr07:browser-use-env

Conversation

@gregpr07

@gregpr07 gregpr07 commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Change

Adds a third environment, --env browser-use, next to playwright and browserbase.

  • computers/browser_use/browser_use.py: BrowserUseComputer subclasses PlaywrightComputer (same pattern as BrowserbaseComputer). On enter it creates a Browser Use Cloud browser with POST /api/v4/browsers at the agent's screen size, connects with connect_over_cdp, pins the viewport, and prints the live view URL. On exit it stops the browser with PATCH /api/v4/browsers/{id}.
  • main.py, computers/__init__.py: wire the new env.
  • README.md, .env.example: document BROWSER_USE_API_KEY.
  • requirements.txt: adds httpx (already installed through google-genai; listed because the new module imports it). No vendor SDK, so the existing pydantic==2.12.0 pin 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 in test_browser_use.py, 1 new in test_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 makes test_stops_browser_when_connect_fails fail.
  • Live run, 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 session stopped (two runs: 34 s and 16 s after start, $0.0003 browser cost each).

Risk

  • Closing a CDP connection does not stop a Browser Use Cloud browser, so cleanup always sends the stop call, in a finally. If that call itself fails, the browser times out server side (default 60 min).
  • Only affects runs with --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

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
@google-cla

google-cla Bot commented Oct 15, 2026

Copy link
Copy Markdown

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread computers/browser_use/browser_use.py Outdated
Comment on lines +87 to +101
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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Make the _cleanup method more robust to prevent exception masking and resource leaks:

  1. Prevent Exception Masking: If _cleanup is called within the except BaseException: block of __enter__ (e.g., if connect_over_cdp fails), any exception raised during cleanup (such as a failed PATCH request) will suppress and mask the original error, making debugging extremely difficult. Catching and logging/printing cleanup errors prevents this.
  2. Ensure Resource Release: If the PATCH request fails or raises an exception, self._http.close() is currently skipped. Wrapping the PATCH call and close() in nested try...finally blocks 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}")

Comment on lines +28 to +37
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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__.

Suggested change
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

Comment on lines +39 to +45
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,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant