Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
fix tests and other improvements
Nick Sweetingaf0697f12bda
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex 06685bf32..fccda50b8 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Optionalfrom browser_use.llm.messages import ContentPartImageParam, ContentPartTextParam, ImageURL, SystemMessage, UserMessagefrom browser_use.observability import observe_debug+from browser_use.utils import is_new_tab_pageif TYPE_CHECKING:from browser_use.agent.views import AgentStepInfo@@ -231,9 +232,9 @@ Interactive elements from top layer of the current page inside the viewport{trun@observe_debug(name='get_user_message')def get_user_message(self, use_vision: bool = True) -> UserMessage:- # Don't pass screenshot to model if page is about:blank, step is 0, and there's only one tab+ # Don't pass screenshot to model if page is a new tab page, step is 0, and there's only one tabif (- self.browser_state.url == 'about:blank'+ is_new_tab_page(self.browser_state.url)and self.step_info is not Noneand self.step_info.step_number == 0and len(self.browser_state.tabs) == 1diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex da35026c7..81b2048f5 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -951,7 +951,13 @@ class BrowserSession(BaseModel):self.browser_pid = Nonereturn- self.logger.info(f'π Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')+ # Determine if this is a newly spawned subprocess or an existing process+ if hasattr(self, '_subprocess') and self._subprocess and self._subprocess.pid == self.browser_pid:+ self.logger.info(+ f'π Connecting to newly spawned browser subprocess: browser_pid={self.browser_pid} on {self.cdp_url}'+ )+ else:+ self.logger.info(f'π Connecting to existing local browser process: browser_pid={self.browser_pid} on {self.cdp_url}')assert self.playwright is not None, 'playwright instance is None'self.browser = self.browser or await self.playwright.chromium.connect_over_cdp(self.cdp_url,@@ -3006,6 +3012,7 @@ class BrowserSession(BaseModel):'page has been closed','crashed target','page is closed',+ 'timeout', # Add timeout to trigger reconnection with fresh page]):self.logger.warning(f'π¨ Detected crashed target during screenshot: {type(e).__name__}: {e}')@@ -3014,7 +3021,9 @@ class BrowserSession(BaseModel):self._reset_connection_state()await self.start()page = await self.get_current_page()- return await self._take_screenshot_hybrid(page)+ result = await self._take_screenshot_hybrid(page)+ self.logger.info('β Screenshot successful after browser restart')+ return resultexcept Exception as restart_error:self.logger.error(f'β Failed to restart browser after crash: {type(restart_error).__name__}: {restart_error}'diff --git a/browser_use/browser/utils.py b/browser_use/browser/utils.pyindex a408c48c1..744ebb065 100644--- a/browser_use/browser/utils.py+++ b/browser_use/browser/utils.py@@ -3,8 +3,8 @@ def normalize_url(url: str) -> str:Normalize a URL by adding https:// protocol if needed, while preserving special URLs.This function safely adds https:// to URLs that lack a protocol, but preserves- special URLs like "about:blank", "mailto:...", "tel:...", etc. that should not- be prefixed with https://.+ special URLs like "about:blank", "chrome://new-tab-page", "mailto:...", "tel:...", etc.+ that should not be prefixed with https://.Args:url: The URL string to normalizediff --git a/browser_use/mcp/client.py b/browser_use/mcp/client.pyindex 34ab08761..7ab2d7166 100644--- a/browser_use/mcp/client.py+++ b/browser_use/mcp/client.py@@ -33,7 +33,7 @@ from browser_use.agent.views import ActionResultfrom browser_use.controller.registry.service import Registryfrom browser_use.controller.service import Controllerfrom browser_use.telemetry import MCPClientTelemetryEvent, ProductTelemetry-from browser_use.utils import get_browser_use_version+from browser_use.utils import get_browser_use_version, is_new_tab_pagelogger = logging.getLogger(__name__)@@ -292,7 +292,7 @@ class MCPClient:if is_browser_tool:# Browser tools should only be available when on a web page- page_filter = lambda page: page and page.url != 'about:blank'+ page_filter = lambda page: page and not is_new_tab_page(page.url)# Create async wrapper function for the MCP tool# Need to define function with explicit parameters to satisfy registry validationdiff --git a/browser_use/mcp/controller.py b/browser_use/mcp/controller.pyindex 91598036c..df12fa517 100644--- a/browser_use/mcp/controller.py+++ b/browser_use/mcp/controller.py@@ -12,6 +12,7 @@ from pydantic import Field, create_modelfrom browser_use.agent.views import ActionResultfrom browser_use.controller.registry.service import Registry+from browser_use.utils import is_new_tab_pagelogger = logging.getLogger(__name__)@@ -133,7 +134,7 @@ class MCPToolWrapper:if is_browser_tool:# Browser tools should only be available when on a web page- page_filter = lambda page: page.url != 'about:blank'+ page_filter = lambda page: not is_new_tab_page(page.url)# Create wrapper function for the MCP toolasync def mcp_action_wrapper(**kwargs):diff --git a/tests/ci/test_agent_sensitive_data.py b/tests/ci/test_agent_sensitive_data.pyindex 7edbc2f35..f9312d784 100644--- a/tests/ci/test_agent_sensitive_data.py+++ b/tests/ci/test_agent_sensitive_data.py@@ -7,7 +7,7 @@ from browser_use.controller.registry.service import Registryfrom browser_use.filesystem.file_system import FileSystemfrom browser_use.llm import SystemMessage, UserMessagefrom browser_use.llm.messages import ContentPartTextParam-from browser_use.utils import match_url_with_domain_pattern+from browser_use.utils import is_new_tab_page, match_url_with_domain_patternclass SensitiveParams(BaseModel):@@ -123,9 +123,13 @@ def test_match_url_with_domain_pattern():assert match_url_with_domain_pattern('chrome-extension://abcdefghijkl', 'chrome-extension://*') is Trueassert match_url_with_domain_pattern('chrome-extension://mnopqrstuvwx', 'chrome-extension://abcdefghijkl') is False- # Test about:blank handling+ # Test new tab page handlingassert match_url_with_domain_pattern('about:blank', 'example.com') is Falseassert match_url_with_domain_pattern('about:blank', '*://*') is False+ assert match_url_with_domain_pattern('chrome://new-tab-page/', 'example.com') is False+ assert match_url_with_domain_pattern('chrome://new-tab-page/', '*://*') is False+ assert match_url_with_domain_pattern('chrome://new-tab-page', 'example.com') is False+ assert match_url_with_domain_pattern('chrome://new-tab-page', '*://*') is Falsedef test_unsafe_domain_patterns():@@ -249,3 +253,19 @@ def test_filter_sensitive_data(message_manager):assert '<secret>username</secret>' in result.contentassert '<secret>password</secret>' in result.contentassert '<secret>email</secret>' in result.content+++def test_is_new_tab_page():+ """Test is_new_tab_page function"""+ # Test about:blank+ assert is_new_tab_page('about:blank') is True++ # Test chrome://new-tab-page variations+ assert is_new_tab_page('chrome://new-tab-page/') is True+ assert is_new_tab_page('chrome://new-tab-page') is True++ # Test regular URLs+ assert is_new_tab_page('https://example.com') is False+ assert is_new_tab_page('http://google.com') is False+ assert is_new_tab_page('') is False+ assert is_new_tab_page('chrome://settings') is Falsediff --git a/tests/ci/test_browser_session_allowed_domains.py b/tests/ci/test_browser_session_allowed_domains.pyindex 080acd3b3..06c4fba3f 100644--- a/tests/ci/test_browser_session_allowed_domains.py+++ b/tests/ci/test_browser_session_allowed_domains.py@@ -66,6 +66,8 @@ class TestUrlAllowlistSecurity:assert browser_session._is_url_allowed('chrome-extension://version/') is Falseassert browser_session._is_url_allowed('brave://anything/') is Trueassert browser_session._is_url_allowed('about:blank') is True+ assert browser_session._is_url_allowed('chrome://new-tab-page/') is True+ assert browser_session._is_url_allowed('chrome://new-tab-page') is True# Test security for glob patterns (authentication credentials bypass attempts)# These should all be detected as malicious despite containing allowed domain patternsdiff --git a/tests/ci/test_telemetry.py b/tests/ci/test_telemetry.pynew file mode 100644index 000000000..3c12bff12--- /dev/null+++ b/tests/ci/test_telemetry.py@@ -0,0 +1,282 @@+"""Test telemetry functionality."""++from unittest.mock import MagicMock, patch++import pytest++from browser_use.config import CONFIG+from browser_use.telemetry import (+ CLITelemetryEvent,+ MCPClientTelemetryEvent,+ MCPServerTelemetryEvent,+ ProductTelemetry,+)+from browser_use.utils import get_browser_use_version+++def reset_telemetry_singleton():+ """Reset the telemetry singleton between tests."""+ # The singleton decorator stores instance in a list at index 0+ # We need to access the closure variable which stores the singleton instance+ # Import the actual module to access the wrapped function+ from browser_use.telemetry import service++ # Get the ProductTelemetry wrapper function created by @singleton+ wrapper_func = service.ProductTelemetry++ # Access the closure variable (instance list) and reset it+ # The closure contains the 'instance' list at index 0+ # Type ignore needed because pyright doesn't know this is a wrapper function+ if hasattr(wrapper_func, '__closure__') and wrapper_func.__closure__: # type: ignore+ for cell in wrapper_func.__closure__: # type: ignore+ if hasattr(cell.cell_contents, '__setitem__'):+ # This is the instance list+ cell.cell_contents[0] = None+ break++ yield++ # Reset again after test+ if hasattr(wrapper_func, '__closure__') and wrapper_func.__closure__: # type: ignore+ for cell in wrapper_func.__closure__: # type: ignore+ if hasattr(cell.cell_contents, '__setitem__'):+ cell.cell_contents[0] = None+ break+++def mock_posthog():+ """Mock PostHog client."""+ with patch('browser_use.telemetry.service.Posthog') as mock:+ yield mock+++def test_telemetry_disabled_when_config_false(monkeypatch, reset_telemetry_singleton):+ """Test that telemetry is disabled when ANONYMIZED_TELEMETRY is False."""+ # Set env var to disable telemetry+ monkeypatch.setattr(CONFIG, 'ANONYMIZED_TELEMETRY', False)++ # Create telemetry instance+ telemetry = ProductTelemetry()++ # Check that posthog client is None+ assert telemetry._posthog_client is None++ # Try to capture an event - should not fail+ event = CLITelemetryEvent(+ version=get_browser_use_version(),+ action='start',+ mode='interactive',+ )+ telemetry.capture(event) # Should not raise+++def test_telemetry_enabled_when_config_true(monkeypatch, mock_posthog, reset_telemetry_singleton):+ """Test that telemetry is enabled when ANONYMIZED_TELEMETRY is True."""+ # Set env var to enable telemetry+ monkeypatch.setattr(CONFIG, 'ANONYMIZED_TELEMETRY', True)++ # Create telemetry instance+ telemetry = ProductTelemetry()++ # Check that posthog client is created+ assert telemetry._posthog_client is not None+ mock_posthog.assert_called_once()+++def test_cli_telemetry_event():+ """Test CLITelemetryEvent structure."""+ event = CLITelemetryEvent(+ version='1.0.0',+ action='start',+ mode='interactive',+ model='gpt-4o',+ model_provider='OpenAI',+ duration_seconds=10.5,+ error_message=None,+ )++ assert event.name == 'cli_event'+ assert event.version == '1.0.0'+ assert event.action == 'start'+ assert event.mode == 'interactive'+ assert event.model == 'gpt-4o'+ assert event.model_provider == 'OpenAI'+ assert event.duration_seconds == 10.5+ assert event.error_message is None++ # Check properties+ props = event.properties+ assert 'version' in props+ assert 'action' in props+ assert 'mode' in props+ assert 'name' not in props # name should not be in properties+++def test_mcp_client_telemetry_event():+ """Test MCPClientTelemetryEvent structure."""+ event = MCPClientTelemetryEvent(+ server_name='test-server',+ command='npx',+ tools_discovered=5,+ version='1.0.0',+ action='connect',+ tool_name='browser_navigate',+ duration_seconds=2.5,+ error_message=None,+ )++ assert event.name == 'mcp_client_event'+ assert event.server_name == 'test-server'+ assert event.command == 'npx'+ assert event.tools_discovered == 5+ assert event.version == '1.0.0'+ assert event.action == 'connect'+ assert event.tool_name == 'browser_navigate'+ assert event.duration_seconds == 2.5+ assert event.error_message is None+++def test_mcp_server_telemetry_event():+ """Test MCPServerTelemetryEvent structure."""+ event = MCPServerTelemetryEvent(+ version='1.0.0',+ action='start',+ tool_name='browser_click',+ duration_seconds=1.2,+ error_message='Test error',+ )++ assert event.name == 'mcp_server_event'+ assert event.version == '1.0.0'+ assert event.action == 'start'+ assert event.tool_name == 'browser_click'+ assert event.duration_seconds == 1.2+ assert event.error_message == 'Test error'+++def test_telemetry_capture_with_mock(monkeypatch, reset_telemetry_singleton):+ """Test telemetry capture with mocked PostHog client."""+ # Enable telemetry+ monkeypatch.setattr(CONFIG, 'ANONYMIZED_TELEMETRY', True)++ # Create mock posthog client+ mock_client = MagicMock()++ # Create telemetry instance and inject mock+ telemetry = ProductTelemetry()+ telemetry._posthog_client = mock_client++ # Capture an event+ event = CLITelemetryEvent(+ version='1.0.0',+ action='start',+ mode='oneshot',+ )+ telemetry.capture(event)++ # Check that capture was called+ mock_client.capture.assert_called_once()+ call_args = mock_client.capture.call_args+ assert call_args[1]['event'] == 'cli_event'+ assert 'properties' in call_args[1]+ assert call_args[1]['properties']['version'] == '1.0.0'+ assert call_args[1]['properties']['action'] == 'start'+ assert call_args[1]['properties']['mode'] == 'oneshot'+++def test_telemetry_flush(monkeypatch, reset_telemetry_singleton):+ """Test telemetry flush method."""+ # Enable telemetry+ monkeypatch.setattr(CONFIG, 'ANONYMIZED_TELEMETRY', True)++ # Create mock posthog client+ mock_client = MagicMock()++ # Create telemetry instance and inject mock+ telemetry = ProductTelemetry()+ telemetry._posthog_client = mock_client++ # Call flush+ telemetry.flush()++ # Check that flush was called+ mock_client.flush.assert_called_once()+++def test_telemetry_user_id_generation(tmp_path, monkeypatch, reset_telemetry_singleton):+ """Test that telemetry generates and persists user ID."""+ # Set BROWSER_USE_CONFIG_DIR to temp directory+ config_dir = tmp_path / 'config' / 'browseruse'+ config_dir.mkdir(parents=True)+ monkeypatch.setenv('BROWSER_USE_CONFIG_DIR', str(config_dir))++ # Enable telemetry+ monkeypatch.setattr(CONFIG, 'ANONYMIZED_TELEMETRY', True)++ # Create telemetry instance with patched path+ telemetry1 = ProductTelemetry()+ # Manually patch the USER_ID_PATH on the instance+ telemetry1.USER_ID_PATH = str(config_dir / 'device_id')++ user_id1 = telemetry1.user_id++ # Check that user ID is generated+ assert user_id1 != 'UNKNOWN_USER_ID'+ assert len(user_id1) > 0++ # Create another instance - should get same ID+ telemetry2 = ProductTelemetry()+ telemetry2.USER_ID_PATH = str(config_dir / 'device_id')+ user_id2 = telemetry2.user_id++ assert user_id1 == user_id2++ # Check that ID was persisted in config directory+ id_file = config_dir / 'device_id'+ assert id_file.exists()+ assert id_file.read_text() == user_id1+++def test_mcp_server_telemetry_event_with_parent_process():+ """Test MCPServerTelemetryEvent with parent_process_cmdline field."""+ event = MCPServerTelemetryEvent(+ version='1.0.0',+ action='start',+ tool_name=None,+ duration_seconds=None,+ error_message=None,+ parent_process_cmdline='python -m browser_use.mcp.server',+ )++ assert event.name == 'mcp_server_event'+ assert event.version == '1.0.0'+ assert event.action == 'start'+ assert event.parent_process_cmdline == 'python -m browser_use.mcp.server'++ # Check properties includes parent_process_cmdline+ props = event.properties+ assert 'parent_process_cmdline' in props+ assert props['parent_process_cmdline'] == 'python -m browser_use.mcp.server'+++def test_telemetry_device_id_uses_config_dir():+ """Test that telemetry device_id is stored in config directory, not cache directory."""+ # This test verifies that the ProductTelemetry class uses CONFIG.BROWSER_USE_CONFIG_DIR+ # for the device_id file location instead of the cache directory.++ # Import ProductTelemetry to check the path+ from browser_use.telemetry.service import ProductTelemetry++ # Create telemetry instance+ telemetry = ProductTelemetry()++ # The USER_ID_PATH should use the config directory+ # We check that it contains the config dir path and ends with 'device_id'+ assert 'browseruse/device_id' in telemetry.USER_ID_PATH or 'browseruse\\device_id' in telemetry.USER_ID_PATH+ assert telemetry.USER_ID_PATH.endswith('device_id')++ # Verify it's not using the cache directory path+ assert 'cache' not in telemetry.USER_ID_PATH+ assert 'telemetry_user_id' not in telemetry.USER_ID_PATH