Skip to content

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

better cloud params

Gregor Žunič9c88c5a828af
diff --git a/browser_use/browser/cloud.py b/browser_use/browser/cloud/cloud.py
similarity index 74%
rename from browser_use/browser/cloud.py
rename to browser_use/browser/cloud/cloud.py
index af178f77d..b6e6bfd74 100644
--- a/browser_use/browser/cloud.py
+++ b/browser_use/browser/cloud/cloud.py
@@ -9,37 +9,13 @@ import logging
import os
import httpx
-from pydantic import BaseModel, Field
+from browser_use.browser.cloud.views import CloudBrowserAuthError, CloudBrowserError, CloudBrowserResponse, CreateBrowserRequest
from browser_use.sync.auth import CloudAuthConfig
logger = logging.getLogger(__name__)
-class CloudBrowserResponse(BaseModel):
- """Response from cloud browser API."""
-
- id: str
- status: str
- liveUrl: str = Field(alias='liveUrl')
- cdpUrl: str = Field(alias='cdpUrl')
- timeoutAt: str = Field(alias='timeoutAt')
- startedAt: str = Field(alias='startedAt')
- finishedAt: str | None = Field(alias='finishedAt', default=None)
-
-
-class CloudBrowserError(Exception):
- """Exception raised when cloud browser operations fail."""
-
- pass
-
-
-class CloudBrowserAuthError(CloudBrowserError):
- """Exception raised when cloud browser authentication fails."""
-
- pass
-
-
class CloudBrowserClient:
"""Client for browser-use cloud browser service."""
@@ -48,15 +24,14 @@ class CloudBrowserClient:
self.client = httpx.AsyncClient(timeout=30.0)
self.current_session_id: str | None = None
- async def create_browser(self) -> CloudBrowserResponse:
- """Create a new cloud browser instance.
+ async def create_browser(self, request: CreateBrowserRequest) -> CloudBrowserResponse:
+ """Create a new cloud browser instance. For full docs refer to https://docs.cloud.browser-use.com/api-reference/v-2-api-current/browsers/create-browser-session-browsers-post
+
+ Args:
+ request: CreateBrowserRequest object containing browser creation parameters
Returns:
CloudBrowserResponse: Contains CDP URL and other browser info
-
- Raises:
- CloudBrowserAuthError: If authentication fails
- CloudBrowserError: If browser creation fails
"""
url = f'{self.api_base_url}/api/v2/browsers'
@@ -78,8 +53,8 @@ class CloudBrowserClient:
headers = {'X-Browser-Use-API-Key': api_token, 'Content-Type': 'application/json'}
- # Empty request body as per API specification
- request_body = {}
+ # Convert request to dictionary and exclude unset fields
+ request_body = request.model_dump(exclude_unset=True)
try:
logger.info('🌤️ Creating cloud browser instance...')
@@ -222,66 +197,3 @@ class CloudBrowserClient:
logger.debug(f'Failed to stop cloud browser session during cleanup: {e}')
await self.client.aclose()
-
-
-# Global client instance
-_cloud_client: CloudBrowserClient | None = None
-
-
-async def get_cloud_browser_cdp_url() -> str:
- """Get a CDP URL for a new cloud browser instance.
-
- Returns:
- str: CDP URL for connecting to the cloud browser
-
- Raises:
- CloudBrowserAuthError: If authentication fails
- CloudBrowserError: If browser creation fails
- """
- global _cloud_client
-
- if _cloud_client is None:
- _cloud_client = CloudBrowserClient()
-
- try:
- browser_response = await _cloud_client.create_browser()
- return browser_response.cdpUrl
- except Exception:
- # Clean up client on error
- if _cloud_client:
- await _cloud_client.close()
- _cloud_client = None
- raise
-
-
-async def stop_cloud_browser_session(session_id: str | None = None) -> CloudBrowserResponse:
- """Stop a cloud browser session.
-
- Args:
- session_id: Session ID to stop. If None, uses current session from global client.
-
- Returns:
- CloudBrowserResponse: Updated browser info with stopped status
-
- Raises:
- CloudBrowserAuthError: If authentication fails
- CloudBrowserError: If stopping fails
- """
- global _cloud_client
-
- if _cloud_client is None:
- _cloud_client = CloudBrowserClient()
-
- try:
- return await _cloud_client.stop_browser(session_id)
- except Exception:
- # Don't clean up client on stop errors - session might still be valid
- raise
-
-
-async def cleanup_cloud_client():
- """Clean up the global cloud client."""
- global _cloud_client
- if _cloud_client:
- await _cloud_client.close()
- _cloud_client = None
diff --git a/browser_use/browser/cloud/views.py b/browser_use/browser/cloud/views.py
new file mode 100644
index 000000000..cb378dd2c
--- /dev/null
+++ b/browser_use/browser/cloud/views.py
@@ -0,0 +1,89 @@
+from typing import Literal
+from uuid import UUID
+
+from pydantic import BaseModel, ConfigDict, Field
+
+ProxyCountryCode = (
+ Literal[
+ 'us', # United States
+ 'uk', # United Kingdom
+ 'fr', # France
+ 'it', # Italy
+ 'jp', # Japan
+ 'au', # Australia
+ 'de', # Germany
+ 'fi', # Finland
+ 'ca', # Canada
+ 'in', # India
+ ]
+ | str
+)
+
+# Browser session timeout limits (in minutes)
+MAX_FREE_USER_SESSION_TIMEOUT = 15 # Free users limited to 15 minutes
+MAX_PAID_USER_SESSION_TIMEOUT = 240 # Paid users can go up to 4 hours
+
+
+# Requests
+class CreateBrowserRequest(BaseModel):
+ """Request to create a cloud browser instance.
+
+ Args:
+ cloud_profile_id: The ID of the profile to use for the session
+ cloud_proxy_country_code: Country code for proxy location
+ cloud_timeout: The timeout for the session in minutes
+ """
+
+ model_config = ConfigDict(extra='forbid', populate_by_name=True)
+
+ profile_id: UUID | str | None = Field(
+ default=None,
+ alias='cloud_profile_id',
+ description='The ID of the profile to use for the session. Can be a UUID or a string of UUID.',
+ title='Cloud Profile ID',
+ )
+
+ proxy_country_code: ProxyCountryCode | None = Field(
+ default=None,
+ alias='cloud_proxy_country_code',
+ description='Country code for proxy location.',
+ title='Cloud Proxy Country Code',
+ )
+
+ timeout: int | None = Field(
+ ge=1,
+ le=MAX_PAID_USER_SESSION_TIMEOUT,
+ default=None,
+ alias='cloud_timeout',
+ description=f'The timeout for the session in minutes. Free users are limited to {MAX_FREE_USER_SESSION_TIMEOUT} minutes, paid users can use up to {MAX_PAID_USER_SESSION_TIMEOUT} minutes ({MAX_PAID_USER_SESSION_TIMEOUT // 60} hours).',
+ title='Cloud Timeout',
+ )
+
+
+CloudBrowserParams = CreateBrowserRequest # alias for easier readability
+
+
+# Responses
+class CloudBrowserResponse(BaseModel):
+ """Response from cloud browser API."""
+
+ id: str
+ status: str
+ liveUrl: str = Field(alias='liveUrl')
+ cdpUrl: str = Field(alias='cdpUrl')
+ timeoutAt: str = Field(alias='timeoutAt')
+ startedAt: str = Field(alias='startedAt')
+ finishedAt: str | None = Field(alias='finishedAt', default=None)
+
+
+# Errors
+class CloudBrowserError(Exception):
+ """Exception raised when cloud browser operations fail."""
+
+ pass
+
+
+class CloudBrowserAuthError(CloudBrowserError):
+ """Exception raised when cloud browser authentication fails."""
+
+ pass
diff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.py
index 53ffed993..22055a066 100644
--- a/browser_use/browser/profile.py
+++ b/browser_use/browser/profile.py
@@ -9,6 +9,7 @@ from urllib.parse import urlparse
from pydantic import AfterValidator, AliasChoices, BaseModel, ConfigDict, Field, field_validator, model_validator
+from browser_use.browser.cloud.views import CloudBrowserParams
from browser_use.config import CONFIG
from browser_use.utils import _log_pretty_path, logger
@@ -559,6 +560,10 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro
"""Alias for use_cloud field for compatibility."""
return self.use_cloud
+ cloud_browser_params: CloudBrowserParams | None = Field(
+ default=None, description='Parameters for creating a cloud browser instance'
+ )
+
# custom options we provide that aren't native playwright kwargs
disable_security: bool = Field(default=False, description='Disable browser security features.')
deterministic_rendering: bool = Field(default=False, description='Enable deterministic rendering flags.')
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 60c975147..0c5ed43bb 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -4,7 +4,8 @@ import asyncio
import logging
from functools import cached_property
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Literal, Self, Union, cast
+from typing import TYPE_CHECKING, Any, Literal, Self, Union, cast, overload
+from uuid import UUID
import httpx
from bubus import EventBus
@@ -15,10 +16,11 @@ from cdp_use.cdp.target import AttachedToTargetEvent, SessionID, TargetID
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
from uuid_extensions import uuid7str
-from browser_use.browser.cloud import CloudBrowserAuthError, CloudBrowserError, get_cloud_browser_cdp_url
+from browser_use.browser.cloud.cloud import CloudBrowserAuthError, CloudBrowserClient, CloudBrowserError
# CDP logging is now handled by setup_logging() in logging_config.py
# It automatically sets CDP logs to the same level as browser_use logs
+from browser_use.browser.cloud.views import CloudBrowserParams, CreateBrowserRequest, ProxyCountryCode
from browser_use.browser.events import (
AgentFocusChangedEvent,
BrowserConnectedEvent,
@@ -183,6 +185,101 @@ class BrowserSession(BaseModel):
revalidate_instances='never', # resets private attrs on every model rebuild
)
+ # Overload 1: Cloud browser mode (use cloud-specific params)
+ @overload
+ def __init__(
+ self,
+ *,
+ # Cloud browser params - use these for cloud mode
+ cloud_profile_id: UUID | str | None = None,
+ cloud_proxy_country_code: ProxyCountryCode | None = None,
+ cloud_timeout: int | None = None,
+ # Backward compatibility aliases
+ profile_id: UUID | str | None = None,
+ proxy_country_code: ProxyCountryCode | None = None,
+ timeout: int | None = None,
+ use_cloud: bool | None = None,
+ cloud_browser: bool | None = None, # Backward compatibility alias
+ cloud_browser_params: CloudBrowserParams | None = None,
+ # Common params that work with cloud
+ id: str | None = None,
+ headers: dict[str, str] | None = None,
+ allowed_domains: list[str] | None = None,
+ keep_alive: bool | None = None,
+ minimum_wait_page_load_time: float | None = None,
+ wait_for_network_idle_page_load_time: float | None = None,
+ wait_between_actions: float | None = None,
+ auto_download_pdfs: bool | None = None,
+ cookie_whitelist_domains: list[str] | None = None,
+ cross_origin_iframes: bool | None = None,
+ highlight_elements: bool | None = None,
+ dom_highlight_elements: bool | None = None,
+ paint_order_filtering: bool | None = None,
+ max_iframes: int | None = None,
+ max_iframe_depth: int | None = None,
+ ) -> None: ...
+
+ # Overload 2: Local browser mode (use local browser params)
+ @overload
+ def __init__(
+ self,
+ *,
+ # Core configuration for local
+ id: str | None = None,
+ cdp_url: str | None = None,
+ browser_profile: BrowserProfile | None = None,
+ # Local browser launch params
+ executable_path: str | Path | None = None,
+ headless: bool | None = None,
+ user_data_dir: str | Path | None = None,
+ args: list[str] | None = None,
+ downloads_path: str | Path | None = None,
+ # Common params
+ headers: dict[str, str] | None = None,
+ allowed_domains: list[str] | None = None,
+ keep_alive: bool | None = None,
+ minimum_wait_page_load_time: float | None = None,
+ wait_for_network_idle_page_load_time: float | None = None,
+ wait_between_actions: float | None = None,
+ auto_download_pdfs: bool | None = None,
+ cookie_whitelist_domains: list[str] | None = None,
+ cross_origin_iframes: bool | None = None,
+ highlight_elements: bool | None = None,
+ dom_highlight_elements: bool | None = None,
+ paint_order_filtering: bool | None = None,
+ max_iframes: int | None = None,
+ max_iframe_depth: int | None = None,
+ # All other local params
+ env: dict[str, str | float | bool] | None = None,
+ ignore_default_args: list[str] | Literal[True] | None = None,
+ channel: str | None = None,
+ chromium_sandbox: bool | None = None,
+ devtools: bool | None = None,
+ traces_dir: str | Path | None = None,
+ accept_downloads: bool | None = None,
+ permissions: list[str] | None = None,
+ user_agent: str | None = None,
+ screen: dict | None = None,
+ viewport: dict | None = None,
+ no_viewport: bool | None = None,
+ device_scale_factor: float | None = None,
+ record_har_content: str | None = None,
+ record_har_mode: str | None = None,
+ record_har_path: str | Path | None = None,
+ record_video_dir: str | Path | None = None,
+ record_video_framerate: int | None = None,
+ record_video_size: dict | None = None,
+ storage_state: str | Path | dict[str, Any] | None = None,
+ disable_security: bool | None = None,
+ deterministic_rendering: bool | None = None,
+ proxy: ProxySettings | None = None,
+ enable_default_extensions: bool | None = None,
+ window_size: dict | None = None,
+ window_position: dict | None = None,
+ filter_highlight_ids: bool | None = None,
+ profile_directory: str | None = None,
+ ) -> None: ...
+
def __init__(
self,
# Core configuration
@@ -190,6 +287,14 @@ class BrowserSession(BaseModel):
cdp_url: str | None = None,
is_local: bool = False,
browser_profile: BrowserProfile | None = None,
+ # Cloud browser params (don't mix with local browser params)
+ cloud_profile_id: UUID | str | None = None,
+ cloud_proxy_country_code: ProxyCountryCode | None = None,
+ cloud_timeout: int | None = None,
+ # Backward compatibility aliases for cloud params
+ profile_id: UUID | str | None = None,
+ proxy_country_code: ProxyCountryCode | None = None,
+ timeout: int | None = None,
# BrowserProfile fields that can be passed directly
# From BrowserConnectArgs
headers: dict[str, str] | None = None,
@@ -223,8 +328,11 @@ class BrowserSession(BaseModel):
# From BrowserNewContextArgs
storage_state: str | Path | dict[str, Any] | None = None,
# BrowserProfile specific fields
+ ## Cloud Browser Fields
use_cloud: bool | None = None,
cloud_browser: bool | None = None, # Backward compatibility alias
+ cloud_browser_params: CloudBrowserParams | None = None,
+ ## Other params
disable_security: bool | None = None,
deterministic_rendering: bool | None = None,
allowed_domains: list[str] | None = None,
@@ -251,16 +359,54 @@ class BrowserSession(BaseModel):
):
# Following the same pattern as AgentSettings in service.py
# Only pass non-None values to avoid validation errors
- profile_kwargs = {k: v for k, v in locals().items() if k not in ['self', 'browser_profile', 'id'] and v is not None}
+ profile_kwargs = {
+ k: v
+ for k, v in locals().items()
+ if k
+ not in [
+ 'self',
+ 'browser_profile',
+ 'id',
+ 'cloud_profile_id',
+ 'cloud_proxy_country_code',
+ 'cloud_timeout',
+ 'profile_id',
+ 'proxy_country_code',
+ 'timeout',
+ ]
+ and v is not None
+ }
+
+ # Handle backward compatibility: prefer cloud_* params over old names
+ final_profile_id = cloud_profile_id if cloud_profile_id is not None else profile_id
+ final_proxy_country_code = cloud_proxy_country_code if cloud_proxy_country_code is not None else proxy_country_code
+ final_timeout = cloud_timeout if cloud_timeout is not None else timeout
+
+ # If any cloud params are provided, create cloud_browser_params
+ if final_profile_id is not None or final_proxy_country_code is not None or final_timeout is not None:
+ cloud_params = CreateBrowserRequest(
+ cloud_profile_id=final_profile_id,
+ cloud_proxy_country_code=final_proxy_country_code,
+ cloud_timeout=final_timeout,
+ )
+ profile_kwargs['cloud_browser_params'] = cloud_params
+ profile_kwargs['use_cloud'] = True
# Handle backward compatibility: map cloud_browser to use_cloud
if 'cloud_browser' in profile_kwargs:
profile_kwargs['use_cloud'] = profile_kwargs.pop('cloud_browser')
+ # If cloud_browser_params is set, force use_cloud=True
+ if cloud_browser_params is not None:
+ profile_kwargs['use_cloud'] = True
+
# if is_local is False but executable_path is provided, set is_local to True
if is_local is False and executable_path is not None:
profile_kwargs['is_local'] = True
- if not cdp_url:
+ # Only set is_local=True when cdp_url is missing if we're not using cloud browser
+ # (cloud browser will provide cdp_url later)
+ use_cloud = profile_kwargs.get('use_cloud') or profile_kwargs.get('cloud_browser')
+ if not cdp_url and not use_cloud:
profile_kwargs['is_local'] = True
# Create browser profile from direct parameters or use provided one
@@ -329,6 +475,8 @@ class BrowserSession(BaseModel):
_permissions_watchdog: Any | None = PrivateAttr(default=None)
_recording_watchdog: Any | None = PrivateAttr(default=None)
+ _cloud_browser_client: CloudBrowserClient = PrivateAttr(default_factory=lambda: CloudBrowserClient())
+
_logger: Any = PrivateAttr(default=None)
@property
@@ -487,11 +635,13 @@ class BrowserSession(BaseModel):
try:
# If no CDP URL, launch local browser or cloud browser
if not self.cdp_url:
- if self.browser_profile.use_cloud:
+ if self.browser_profile.use_cloud or self.browser_profile.cloud_browser_params is not None:
# Use cloud browser service
try:
- cloud_cdp_url = await get_cloud_browser_cdp_url()
- self.browser_profile.cdp_url = cloud_cdp_url
+ # Use cloud_browser_params if provided, otherwise create empty request
+ cloud_params = self.browser_profile.cloud_browser_params or CreateBrowserRequest()
+ cloud_browser_response = await self._cloud_browser_client.create_browser(cloud_params)
+ self.browser_profile.cdp_url = cloud_browser_response.cdpUrl
self.browser_profile.is_local = False
self.logger.info('🌤️ Successfully connected to cloud browser service')
except CloudBrowserAuthError:
@@ -845,9 +995,7 @@ class BrowserSession(BaseModel):
# Clean up cloud browser session if using cloud browser
if self.browser_profile.use_cloud:
try:
- from browser_use.browser.cloud import cleanup_cloud_client
-
- await cleanup_cloud_client()
+ await self._cloud_browser_client.stop_browser()
self.logger.info('🌤️ Cloud browser session cleaned up')
except Exception as e:
self.logger.debug(f'Failed to cleanup cloud browser session: {e}')
diff --git a/docs/customize/browser/remote.mdx b/docs/customize/browser/remote.mdx
index 1272eb53a..c9472b9ad 100644
--- a/docs/customize/browser/remote.mdx
+++ b/docs/customize/browser/remote.mdx
@@ -11,17 +11,29 @@ mode: "wide"
The easiest way to use a cloud browser is with the built-in Browser-Use cloud service:
```python
-from browser_use import Agent, Browser, ChatOpenAI
+from browser_use import Agent, Browser, ChatBrowserUse
-# Use Browser-Use cloud browser service
+# Simple: Use Browser-Use cloud browser service
browser = Browser(
use_cloud=True, # Automatically provisions a cloud browser
- # cdp_url="http://remote-server:9222" # Get a CDP URL from our hosted cloud browsers https://docs.cloud.browser-use.com/concepts/browser
+)
+
+# Advanced: Configure cloud browser parameters
+# Using this settings can bypass any captcha protection on any website
+browser = Browser(
+ cloud_profile_id='your-profile-id', # Optional: specific browser profile
+ cloud_proxy_country_code='us', # Optional: proxy location (us, uk, fr, it, jp, au, de, fi, ca, in)
+ cloud_timeout=30, # Optional: session timeout in minutes (MAX free: 15min, paid: 240min)
+)
+
+# Or use a CDP URL from any cloud browser provider
+browser = Browser(
+ cdp_url="http://remote-server:9222" # Get a CDP URL from any provider
)
agent = Agent(
task="Your task here",
- llm=ChatOpenAI(model='gpt-4.1-mini'),
+ llm=ChatBrowserUse(),
browser=browser,
)
```
@@ -30,12 +42,18 @@ agent = Agent(
1. Get an API key from [cloud.browser-use.com](https://cloud.browser-use.com/new-api-key)
2. Set BROWSER_USE_API_KEY environment variable
+**Cloud Browser Parameters:**
+- `cloud_profile_id`: UUID of a browser profile (optional, uses default if not specified)
+- `cloud_proxy_country_code`: Country code for proxy location - supports: us, uk, fr, it, jp, au, de, fi, ca, in
+- `cloud_timeout`: Session timeout in minutes (free users: max 15 min, paid users: max 240 min)
+
**Benefits:**
- ✅ No local browser setup required
- ✅ Scalable and fast cloud infrastructure
- ✅ Automatic provisioning and teardown
- ✅ Built-in authentication handling
- ✅ Optimized for browser automation
+- ✅ Global proxy support for geo-restricted content
### Third-Party Cloud Browsers
You can pass in a CDP URL from any remote browser
diff --git a/examples/browser/cloud_browser.py b/examples/browser/cloud_browser.py
index 247407002..8bdb36a2a 100644
--- a/examples/browser/cloud_browser.py
+++ b/examples/browser/cloud_browser.py
@@ -1,5 +1,5 @@
"""
-Simple example of using Browser-Use cloud browser service.
+Examples of using Browser-Use cloud browser service.
Prerequisites:
1. Set BROWSER_USE_API_KEY environment variable
@@ -10,33 +10,49 @@ import asyncio
from dotenv import load_dotenv
-# Load environment variables
+from browser_use import Agent, Browser, ChatBrowserUse
+
load_dotenv()
-from browser_use import Agent, Browser, ChatOpenAI
+async def basic():
+ """Simplest usage - just pass cloud params directly."""
+ browser = Browser(use_cloud=True)
-async def main():
- """Basic cloud browser example."""
+ agent = Agent(
+ task='Go to github.com/browser-use/browser-use and tell me the star count',
+ llm=ChatBrowserUse(),
+ browser=browser,
+ )
+
+ result = await agent.run()
+ print(f'Result: {result}')
- print('🌤️ Using Browser-Use Cloud Browser')
- # Create agent with cloud browser enabled
+async def full_config():
+ """Full cloud configuration with specific profile."""
+ browser = Browser(
+ # cloud_profile_id='21182245-590f-4712-8888-9611651a024c',
+ cloud_proxy_country_code='jp',
+ cloud_timeout=60,
+ )
+
agent = Agent(
- task='Go to https://github.com/browser-use/browser-use and find the number of stars',
- llm=ChatOpenAI(model='gpt-4.1-mini'),
- browser=Browser(use_cloud=True), # Enable cloud browser
+ task='go and check my ip address and the location',
+ llm=ChatBrowserUse(),
+ browser=browser,
)
+ result = await agent.run()
+ print(f'Result: {result}')
+
+
+async def main():
try:
- result = await agent.run()
- print(f'✅ Result: {result}')
+ # await basic()
+ await full_config()
except Exception as e:
- print(f'❌ Error: {e}')
- if 'Authentication' in str(e):
- print(
- '💡 Set BROWSER_USE_API_KEY environment variable. You can also create an API key at https://cloud.browser-use.com/new-api-key'
- )
+ print(f'Error: {e}')
if __name__ == '__main__':
diff --git a/tests/ci/browser/test_cloud_browser.py b/tests/ci/browser/test_cloud_browser.py
index f0fc76672..8c0ef4cb7 100644
--- a/tests/ci/browser/test_cloud_browser.py
+++ b/tests/ci/browser/test_cloud_browser.py
@@ -6,13 +6,12 @@ from unittest.mock import AsyncMock, patch
import pytest
-from browser_use.browser.cloud import (
+from browser_use.browser.cloud.cloud import (
CloudBrowserAuthError,
CloudBrowserClient,
CloudBrowserError,
- get_cloud_browser_cdp_url,
- stop_cloud_browser_session,
)
+from browser_use.browser.cloud.views import CreateBrowserRequest
from browser_use.browser.profile import BrowserProfile
from browser_use.browser.session import BrowserSession
from browser_use.sync.auth import CloudAuthConfig
@@ -73,7 +72,7 @@ class TestCloudBrowserClient:
client = CloudBrowserClient()
client.client = mock_client
- result = await client.create_browser()
+ result = await client.create_browser(CreateBrowserRequest())
assert result.id == 'test-browser-id'
assert result.status == 'active'
@@ -94,7 +93,7 @@ class TestCloudBrowserClient:
client = CloudBrowserClient()
with pytest.raises(CloudBrowserAuthError) as exc_info:
- await client.create_browser()
+ await client.create_browser(CreateBrowserRequest())
assert 'BROWSER_USE_API_KEY environment variable' in str(exc_info.value)
@@ -117,7 +116,7 @@ class TestCloudBrowserClient:
client.client = mock_client
with pytest.raises(CloudBrowserAuthError) as exc_info:
- await client.create_browser()
+ await client.create_browser(CreateBrowserRequest())
assert 'Authentication failed' in str(exc_info.value)
@@ -151,7 +150,7 @@ class TestCloudBrowserClient:
client = CloudBrowserClient()
client.client = mock_client
- result = await client.create_browser()
+ result = await client.create_browser(CreateBrowserRequest())
assert result.id == 'test-browser-id'
assert result.status == 'active'
@@ -237,8 +236,9 @@ class TestBrowserSessionCloudIntegration:
async def test_cloud_browser_profile_property(self):
"""Test that cloud_browser property works correctly."""
+ # Just test the profile and session properties without connecting
profile = BrowserProfile(use_cloud=True)
- session = BrowserSession(browser_profile=profile)
+ session = BrowserSession(browser_profile=profile, cdp_url='ws://mock-url') # Provide CDP URL to avoid connection
assert session.cloud_browser is True
assert session.browser_profile.use_cloud is True
@@ -254,96 +254,6 @@ class TestBrowserSessionCloudIntegration:
assert profile.use_cloud is True
# Test that BrowserSession respects cloud_browser setting
- session = BrowserSession(browser_profile=profile)
+ # Provide CDP URL to avoid actual connection attempts
+ session = BrowserSession(browser_profile=profile, cdp_url='ws://mock-url')
assert session.cloud_browser is True
-
- # Test that get_cloud_browser_cdp_url works with mocked API
- with patch('browser_use.browser.cloud.get_cloud_browser_cdp_url') as mock_get_cdp_url:
- mock_get_cdp_url.return_value = 'wss://test.proxy.daytona.works'
-
- cdp_url = await mock_get_cdp_url()
- assert cdp_url == 'wss://test.proxy.daytona.works'
- mock_get_cdp_url.assert_called_once()
-
-
-async def test_get_cloud_browser_cdp_url_function(mock_auth_config, monkeypatch):
- """Test the get_cloud_browser_cdp_url convenience function."""
-
- # Clear environment variable so test uses mock_auth_config
- monkeypatch.delenv('BROWSER_USE_API_KEY', raising=False)
-
- mock_response_data = {
- 'id': 'test-browser-id',
- 'status': 'active',
- 'liveUrl': 'https://live.browser-use.com?wss=test',
- 'cdpUrl': 'wss://test.proxy.daytona.works',
- 'timeoutAt': '2025-09-17T04:35:36.049892',
- 'startedAt': '2025-09-17T03:35:36.049974',
- 'finishedAt': None,
- }
-
- with patch('httpx.AsyncClient') as mock_client_class:
- mock_response = AsyncMock()
- mock_response.status_code = 201
- mock_response.is_success = True
- mock_response.json = lambda: mock_response_data
-
- mock_client = AsyncMock()
- mock_client.post.return_value = mock_response
- mock_client_class.return_value = mock_client
-
- cdp_url = await get_cloud_browser_cdp_url()
-
- assert cdp_url == 'wss://test.proxy.daytona.works'
-
-
-async def test_cloud_browser_auth_error_no_fallback(temp_config_dir, monkeypatch):
- """Test that cloud browser throws error when auth fails (no fallback)."""
-
- # Clear environment variable and don't create auth config to trigger auth error
- monkeypatch.delenv('BROWSER_USE_API_KEY', raising=False)
-
- # Don't create auth config to trigger auth error
- profile = BrowserProfile(use_cloud=True)
-
- # Verify that the cloud browser client raises the expected error
- with pytest.raises(CloudBrowserAuthError) as exc_info:
- await get_cloud_browser_cdp_url()
-
- assert 'BROWSER_USE_API_KEY environment variable' in str(exc_info.value)
-
- # Verify profile state unchanged (no fallback)
- assert profile.use_cloud is True
- assert profile.is_local is False
-
-
-async def test_stop_cloud_browser_session_function(mock_auth_config, monkeypatch):
- """Test the stop_cloud_browser_session convenience function."""
-
- # Clear environment variable so test uses mock_auth_config
- monkeypatch.delenv('BROWSER_USE_API_KEY', raising=False)
-
- mock_response_data = {
- 'id': 'test-browser-id',
- 'status': 'stopped',
- 'liveUrl': 'https://live.browser-use.com?wss=test',
- 'cdpUrl': 'wss://test.proxy.daytona.works',
- 'timeoutAt': '2025-09-17T04:35:36.049892',
- 'startedAt': '2025-09-17T03:35:36.049974',
- 'finishedAt': '2025-09-17T04:35:36.049892',
- }
-
- with patch('httpx.AsyncClient') as mock_client_class:
- mock_response = AsyncMock()
- mock_response.status_code = 200
- mock_response.is_success = True
- mock_response.json = lambda: mock_response_data
-
- mock_client = AsyncMock()
- mock_client.patch.return_value = mock_response
- mock_client_class.return_value = mock_client
-
- result = await stop_cloud_browser_session('test-browser-id')
-
- assert result.id == 'test-browser-id'
- assert result.status == 'stopped'