Repository navigation
Add Browser Use Cloud browser environment #124
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
gregpr07
wants to merge
2
commits into
google-gemini:main
Choose a base branch
from
gregpr07:browser-use-env
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| import os | ||
|
|
||
| import httpx | ||
| import termcolor | ||
| from playwright.sync_api import sync_playwright | ||
|
|
||
| from ..playwright.playwright import PlaywrightComputer | ||
|
|
||
| BROWSER_USE_API_URL = "https://api.browser-use.com/api/v4" | ||
|
|
||
|
|
||
| class BrowserUseComputer(PlaywrightComputer): | ||
| """Runs the agent in a Browser Use Cloud browser, connected over CDP.""" | ||
|
|
||
| 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, | ||
| ) | ||
|
Comment on lines
+40
to
+46
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check for the presence of the 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,
) |
||
| try: | ||
| response = self._http.post( | ||
| "/browsers", | ||
| json={ | ||
| "browserScreenWidth": self._screen_size[0], | ||
| "browserScreenHeight": self._screen_size[1], | ||
| }, | ||
| ) | ||
| response.raise_for_status() | ||
| session = response.json() | ||
| self._session_id = session["id"] | ||
|
|
||
| self._playwright = sync_playwright().start() | ||
| self._browser = self._playwright.chromium.connect_over_cdp( | ||
| session["cdpUrl"] | ||
| ) | ||
| self._context = self._browser.contexts[0] | ||
| self._page = ( | ||
| self._context.pages[0] | ||
| if self._context.pages | ||
| else self._context.new_page() | ||
| ) | ||
| self._page.set_viewport_size( | ||
| {"width": self._screen_size[0], "height": self._screen_size[1]} | ||
| ) | ||
| self._page.goto(self._initial_url) | ||
| self._context.on("page", self._handle_new_page) | ||
| except BaseException: | ||
| try: | ||
| self._cleanup() | ||
| except Exception as e: | ||
| # Keep the original error; report the cleanup failure. | ||
| termcolor.cprint(f"Cleanup failed: {e}", color="red") | ||
| raise | ||
|
|
||
| termcolor.cprint( | ||
| f"Session started. Watch it live at {session.get('liveUrl')}", | ||
| color="green", | ||
| attrs=["bold"], | ||
| ) | ||
| return self | ||
|
|
||
| def __exit__(self, exc_type, exc_val, exc_tb): | ||
| self._cleanup() | ||
|
|
||
| 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: | ||
| try: | ||
| if self._session_id: | ||
| self._http.patch( | ||
| f"/browsers/{self._session_id}", json={"action": "stop"} | ||
| ).raise_for_status() | ||
| self._session_id = None | ||
| finally: | ||
| if self._http: | ||
| self._http.close() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,7 @@ pydantic==2.12.0 | |
| google-genai>=2.7.0 | ||
| playwright==1.55.0 | ||
| browserbase==1.4.0 | ||
| httpx | ||
| rich | ||
| pytest | ||
| python-dotenv==1.0.1 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import json | ||
| import os | ||
| import unittest | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| import httpx | ||
|
|
||
| from computers.browser_use import browser_use as browser_use_module | ||
| from computers import BrowserUseComputer | ||
|
|
||
|
|
||
| class TestBrowserUseComputer(unittest.TestCase): | ||
|
|
||
| def setUp(self): | ||
| self.requests = [] | ||
|
|
||
| self.stop_status = 200 | ||
|
|
||
| def handler(request): | ||
| self.requests.append(request) | ||
| if request.method == 'POST': | ||
| return httpx.Response(201, json={ | ||
| 'id': 'session-1', | ||
| 'cdpUrl': 'wss://cdp.example/session-1', | ||
| 'liveUrl': 'https://live.example/session-1', | ||
| }) | ||
| return httpx.Response(self.stop_status, json={'id': 'session-1', 'status': 'stopped'}) | ||
|
|
||
| real_client = httpx.Client | ||
| client_patcher = patch.object( | ||
| browser_use_module.httpx, 'Client', | ||
| side_effect=lambda **kwargs: real_client(transport=httpx.MockTransport(handler), **kwargs), | ||
| ) | ||
| client_patcher.start() | ||
| self.addCleanup(client_patcher.stop) | ||
|
|
||
| playwright_patcher = patch.object(browser_use_module, 'sync_playwright') | ||
| self.mock_sync_playwright = playwright_patcher.start() | ||
| self.addCleanup(playwright_patcher.stop) | ||
| self.mock_playwright = self.mock_sync_playwright.return_value.start.return_value | ||
| self.mock_browser = self.mock_playwright.chromium.connect_over_cdp.return_value | ||
| self.mock_page = MagicMock() | ||
| self.mock_browser.contexts = [MagicMock(pages=[self.mock_page])] | ||
|
|
||
| env_patcher = patch.dict(os.environ, {'BROWSER_USE_API_KEY': 'test-key'}) | ||
| env_patcher.start() | ||
| self.addCleanup(env_patcher.stop) | ||
|
|
||
| def test_creates_connects_and_stops_browser(self): | ||
| computer = BrowserUseComputer(screen_size=(1440, 900), initial_url='https://example.com') | ||
| with computer: | ||
| self.mock_playwright.chromium.connect_over_cdp.assert_called_once_with('wss://cdp.example/session-1') | ||
| self.mock_page.set_viewport_size.assert_called_once_with({'width': 1440, 'height': 900}) | ||
| self.mock_page.goto.assert_called_once_with('https://example.com') | ||
|
|
||
| create, stop = self.requests | ||
| self.assertEqual(create.method, 'POST') | ||
| self.assertEqual(create.url.path, '/api/v4/browsers') | ||
| self.assertEqual(create.headers['X-Browser-Use-API-Key'], 'test-key') | ||
| self.assertEqual(json.loads(create.content), {'browserScreenWidth': 1440, 'browserScreenHeight': 900}) | ||
| self.assertEqual(stop.method, 'PATCH') | ||
| self.assertEqual(stop.url.path, '/api/v4/browsers/session-1') | ||
| self.assertEqual(json.loads(stop.content), {'action': 'stop'}) | ||
| self.mock_browser.close.assert_called_once() | ||
| self.mock_playwright.stop.assert_called_once() | ||
|
|
||
| def test_stops_browser_when_connect_fails(self): | ||
| self.mock_playwright.chromium.connect_over_cdp.side_effect = RuntimeError('connect failed') | ||
| computer = BrowserUseComputer(screen_size=(1440, 900)) | ||
| with self.assertRaises(RuntimeError): | ||
| computer.__enter__() | ||
|
|
||
| self.assertEqual([r.method for r in self.requests], ['POST', 'PATCH']) | ||
| self.mock_playwright.stop.assert_called_once() | ||
|
|
||
| def test_stop_failure_does_not_hide_connect_error(self): | ||
| self.mock_playwright.chromium.connect_over_cdp.side_effect = RuntimeError('connect failed') | ||
| self.stop_status = 500 | ||
| computer = BrowserUseComputer(screen_size=(1440, 900)) | ||
| with self.assertRaisesRegex(RuntimeError, 'connect failed'): | ||
| computer.__enter__() | ||
|
|
||
| self.assertEqual([r.method for r in self.requests], ['POST', 'PATCH']) | ||
| self.assertTrue(computer._http.is_closed) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| unittest.main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Initialize
self._httptoNonein__init__to ensure the attribute always exists. This prevents potentialAttributeErrors in_cleanupif cleanup is invoked beforeself._httpis instantiated in__enter__.