Skip to content

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

fix tests and other improvements

Nick Sweetingb2a84b22960f
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index f2a54c7fd..da35026c7 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -52,7 +52,14 @@ from browser_use.browser.views import (
from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor
from browser_use.dom.service import DomService
from browser_use.dom.views import DOMElementNode, SelectorMap
-from browser_use.utils import match_url_with_domain_pattern, merge_dicts, retry, time_execution_async, time_execution_sync
+from browser_use.utils import (
+ is_new_tab_page,
+ match_url_with_domain_pattern,
+ merge_dicts,
+ retry,
+ time_execution_async,
+ time_execution_sync,
+)
_GLOB_WARNING_SHOWN = False # used inside _is_url_allowed to avoid spamming the logs with the same warning multiple times
@@ -704,14 +711,14 @@ class BrowserSession(BaseModel):
@observe_debug(ignore_output=True)
@retry(
- wait=2, # wait 2s between each attempt to take a screenshot
+ wait=1, # wait 1s between each attempt to take a screenshot
retries=2, # try up to 2 times to take the screenshot
- timeout=35, # allow up to 35s for each attempt to take a screenshot
+ timeout=20, # allow up to 20s for each attempt to take a screenshot
semaphore_name='screenshot_global',
- semaphore_limit=3, # only 3 concurrent screenshots at a time total on the entire machine (ideally)
- semaphore_scope='global', # because it's a hardware VRAM bottleneck, chrome crashes if too many concurrent screenshots are rendered via CDP
- semaphore_timeout=10, # wait up to 10s for a lock
- semaphore_lax=True, # proceed anyway if we cant get a lock
+ semaphore_limit=1, # only 1 screenshot at a time total on the entire machine
+ semaphore_scope='multiprocess', # because it's a hardware VRAM bottleneck, chrome crashes if too many concurrent screenshots are rendered via CDP
+ semaphore_timeout=30, # wait up to 30s for a lock
+ semaphore_lax=True, # do not proceed without getting a lock
)
async def _take_screenshot_hybrid(self, page: Page, clip: dict[str, int] | None = None) -> str:
"""Take screenshot using Playwright, with retry and semaphore protection."""
@@ -909,6 +916,19 @@ class BrowserSession(BaseModel):
if 'Failed parsing extensions' in stderr_output:
self.logger.error(f'❌ Chrome process {self.browser_pid} exited: Failed parsing extensions')
raise RuntimeError('Failed parsing extensions: Chrome profile incompatibility detected')
+ elif 'SingletonLock' in stderr_output or 'ProcessSingleton' in stderr_output:
+ # Chrome exited due to singleton lock
+ self._fallback_to_temp_profile('Chrome process exit due to SingletonLock')
+ # Kill the subprocess and retry with new profile
+ try:
+ self._subprocess.terminate()
+ await self._subprocess.wait()
+ except Exception:
+ pass
+ self.browser_pid = None
+ # Retry with the new temp directory
+ await self._unsafe_setup_new_browser_context()
+ return
self.logger.error(f'❌ Chrome process {self.browser_pid} exited unexpectedly')
self.browser_pid = None
return
@@ -1034,26 +1054,8 @@ class BrowserSession(BaseModel):
# user data dir was provided, prepare it for use
self.prepare_user_data_dir()
- # search for potentially conflicting local processes running on the same user_data_dir
- for proc in psutil.process_iter(['pid', 'cmdline']):
- if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
- # If this is a temp directory, automatically create a new one
- if Path(self.browser_profile.user_data_dir).name.startswith('browseruse-tmp-'):
- old_dir = self.browser_profile.user_data_dir
- self.browser_profile.user_data_dir = Path(tempfile.mkdtemp(prefix='browseruse-tmp-'))
- self.logger.warning(
- f'⚠️ Found conflicting browser process pid={proc.info["pid"]} using temp dir {_log_pretty_path(old_dir)}. '
- f'Creating new temp dir: {_log_pretty_path(self.browser_profile.user_data_dir)}'
- )
- # Re-prepare the new user data dir
- self.prepare_user_data_dir()
- else:
- # For non-temp directories, just log the error
- self.logger.error(
- f'🚨 Found potentially conflicting browser process browser_pid={proc.info["pid"]} '
- f'already running with the same user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)}'
- )
- break
+ # user data dir was provided, prepare it for use (handles conflicts automatically)
+ self.prepare_user_data_dir()
# if a user_data_dir is provided, launch Chrome as subprocess then connect via CDP
try:
@@ -1148,15 +1150,18 @@ class BrowserSession(BaseModel):
except Exception as e:
# Check if it's a SingletonLock error
if 'SingletonLock' in str(e) or 'ProcessSingleton' in str(e):
- self.logger.warning('⚠️ SingletonLock error detected. Cleaning up and retrying...')
- # Remove the stale lock file
- singleton_lock = Path(self.browser_profile.user_data_dir) / 'SingletonLock'
- if singleton_lock.exists():
- singleton_lock.unlink()
- # Wait a moment for cleanup
- await asyncio.sleep(0.1)
- # Retry the launch (recursively call this method)
- raise # Will be caught by outer try-except to retry
+ # Fall back to temporary directory
+ self._fallback_to_temp_profile('Chrome launch error due to SingletonLock')
+ # Kill the failed subprocess if it exists
+ if hasattr(self, '_subprocess') and self._subprocess:
+ try:
+ self._subprocess.terminate()
+ await self._subprocess.wait()
+ except Exception:
+ pass
+ # Retry the launch with the new temporary directory
+ await self._unsafe_setup_new_browser_context()
+ return
# Re-raise if not a timeout
elif not isinstance(e, asyncio.TimeoutError):
raise
@@ -1171,6 +1176,14 @@ class BrowserSession(BaseModel):
await self._unsafe_setup_new_browser_context()
return
except Exception as e:
+ # Check if it's a SingletonLock error from the subprocess
+ if 'SingletonLock' in str(e) or 'ProcessSingleton' in str(e):
+ # Fall back to temporary directory
+ self._fallback_to_temp_profile('Chrome launch error due to SingletonLock')
+ # Retry the launch with the new temporary directory
+ await self._unsafe_setup_new_browser_context()
+ return
+
# show a nice logger hint explaining what went wrong with the user_data_dir
# calculate the version of the browser that the user_data_dir is for, and the version of the browser we are running with
user_data_dir_chrome_version = '???'
@@ -1427,8 +1440,8 @@ class BrowserSession(BaseModel):
# self.logger.info(f'Setting up visibility listeners for {len(self.browser_context.pages)} pages')
for page in self.browser_context.pages:
# self.logger.info(f'Processing page with URL: {repr(page.url)}')
- # Skip about:blank pages as they can hang when evaluating scripts
- if page.url == 'about:blank':
+ # Skip new tab pages as they can hang when evaluating scripts
+ if is_new_tab_page(page.url):
continue
try:
@@ -1516,8 +1529,8 @@ class BrowserSession(BaseModel):
if viewport:
await page.set_viewport_size(viewport)
- # show browser-use dvd screensaver-style bouncing loading animation on any about:blank pages
- if page.url == 'about:blank':
+ # show browser-use dvd screensaver-style bouncing loading animation on any new tab pages
+ if is_new_tab_page(page.url):
await self._show_dvd_screensaver_loading_animation(page)
page = page or (await self.browser_context.new_page())
@@ -1649,11 +1662,51 @@ class BrowserSession(BaseModel):
if not already_disconnected:
self.logger.debug(f'⚰️ Browser {self._connection_str} disconnected')
+ def _check_for_singleton_lock_conflict(self) -> bool:
+ """Check if the user data directory has a conflicting browser process.
+
+ Returns:
+ True if there's a conflict (active process using this profile), False otherwise
+ """
+ if not self.browser_profile.user_data_dir:
+ return False
+
+ # Check for running processes using this user data dir
+ for proc in psutil.process_iter(['pid', 'cmdline']):
+ if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
+ return True
+
+ # Note: We don't consider a SingletonLock file alone as a conflict
+ # because it might be stale. Only actual running processes count as conflicts.
+ return False
+
+ def _fallback_to_temp_profile(self, reason: str = 'SingletonLock conflict') -> None:
+ """Fallback to a temporary profile directory when the current one is locked.
+
+ Args:
+ reason: Human-readable reason for the fallback
+ """
+ old_dir = self.browser_profile.user_data_dir
+ self.browser_profile.user_data_dir = Path(tempfile.mkdtemp(prefix='browseruse-tmp-singleton-'))
+ self.logger.warning(
+ f'⚠️ {reason} detected. Profile at {_log_pretty_path(old_dir)} is locked. '
+ f'Using temporary profile instead: {_log_pretty_path(self.browser_profile.user_data_dir)}'
+ )
+
@observe_debug(name='prepare_user_data_dir')
- def prepare_user_data_dir(self) -> None:
- """Create and unlock the user data dir and ensure all recording paths exist."""
+ def prepare_user_data_dir(self, check_conflicts: bool = True) -> None:
+ """Create and prepare the user data dir, handling conflicts if needed.
+ Args:
+ check_conflicts: Whether to check for and handle singleton lock conflicts
+ """
if self.browser_profile.user_data_dir:
+ # Check for conflicts and fallback if needed
+ if check_conflicts and self._check_for_singleton_lock_conflict():
+ self._fallback_to_temp_profile()
+ # Recursive call without conflict checking to prepare the new temp dir
+ return self.prepare_user_data_dir(check_conflicts=False)
+
try:
self.browser_profile.user_data_dir = Path(self.browser_profile.user_data_dir).expanduser().resolve()
self.browser_profile.user_data_dir.mkdir(parents=True, exist_ok=True)
@@ -1663,13 +1716,23 @@ class BrowserSession(BaseModel):
f'Unusable path provided for user_data_dir= {_log_pretty_path(self.browser_profile.user_data_dir)} (check for typos/permissions issues)'
) from e
- # clear any existing locks by any other chrome processes (hacky)
+ # Remove stale singleton lock file ONLY if no process is using this profile
singleton_lock = self.browser_profile.user_data_dir / 'SingletonLock'
if singleton_lock.exists():
- singleton_lock.unlink()
- self.logger.warning(
- f'⚠️ Multiple chrome processes may be trying to share user_data_dir={self.browser_profile.user_data_dir} which can lead to crashes and profile data corruption!'
- )
+ # Check if any process is actually using this user_data_dir
+ has_active_process = False
+ for proc in psutil.process_iter(['pid', 'cmdline']):
+ if f'--user-data-dir={self.browser_profile.user_data_dir}' in (proc.info['cmdline'] or []):
+ has_active_process = True
+ break
+
+ if not has_active_process:
+ # No active process, safe to remove stale lock
+ try:
+ singleton_lock.unlink()
+ self.logger.debug('Removed stale SingletonLock file (no active Chrome process found)')
+ except Exception:
+ pass # Ignore errors removing lock file
# Create directories for all paths that need them
dir_paths = {
@@ -1775,7 +1838,7 @@ class BrowserSession(BaseModel):
@observe_debug(name='remove_highlights', ignore_output=True, ignore_input=True)
@require_initialization
@time_execution_async('--remove_highlights')
- @retry(timeout=5, retries=0)
+ @retry(timeout=10, retries=0)
async def remove_highlights(self):
"""
Removes all highlight overlays and labels created by the highlightElement function.
@@ -1934,7 +1997,7 @@ class BrowserSession(BaseModel):
title = await self._get_page_title(page)
tab_info = TabInfo(page_id=page_id, url=page.url, title=title)
except Exception:
- # page.title() can hang forever on tabs that are crashed/disappeared/about:blank
+ # page.title() can hang forever on tabs that are crashed/disappeared/new tab pages
# we dont want to try automating those tabs because they will hang the whole script
self.logger.debug(f'⚠️ Failed to get tab info for tab #{page_id}: {_log_pretty_url(page.url)} (ignoring)')
tab_info = TabInfo(page_id=page_id, url='about:blank', title='ignore this tab and do not use it')
@@ -1942,7 +2005,7 @@ class BrowserSession(BaseModel):
return tabs_info
- @retry(timeout=1, retries=0) # Single attempt with 1s timeout, no retries
+ @retry(timeout=3, retries=0) # Single attempt with 3s timeout, no retries
async def _get_page_title(self, page: Page) -> str:
"""Get page title with timeout protection."""
return await page.title()
@@ -2478,8 +2541,8 @@ class BrowserSession(BaseModel):
if not self.browser_profile.allowed_domains:
return True # allowed_domains are not configured, allow everything by default
- # Special case: Always allow 'about:blank' new tab page
- if url == 'about:blank':
+ # Special case: Always allow new tab pages
+ if is_new_tab_page(url):
return True
for allowed_domain in self.browser_profile.allowed_domains:
@@ -2492,7 +2555,7 @@ class BrowserSession(BaseModel):
_log_glob_warning(domain, allowed_domain, self.logger)
return True
except AssertionError:
- # This would only happen if about:blank is passed to match_url_with_domain_pattern,
+ # This would only happen if a new tab page is passed to match_url_with_domain_pattern,
# which shouldn't occur since we check for it above
continue
@@ -3519,7 +3582,7 @@ class BrowserSession(BaseModel):
# else:
# assert self.agent_current_page.url == 'about:blank'
- # if there are any unused about:blank tabs after we open a new tab, close them to clean up unused tabs
+ # if there are any unused new tab pages after we open a new tab, close them to clean up unused tabs
assert self.browser_context is not None, 'Browser context is not set'
# hacky way to be sure we only close our own tabs, check the title of the tab for our BrowserSession name
title_of_our_setup_tab = (
@@ -3532,14 +3595,14 @@ class BrowserSession(BaseModel):
except Exception:
page_title = 'Title unavailable'
- if page.url == 'about:blank' and page != self.agent_current_page and page_title == title_of_our_setup_tab:
+ if is_new_tab_page(page.url) and page != self.agent_current_page and page_title == title_of_our_setup_tab:
await page.close()
self.human_current_page = ( # in case we just closed the human's tab, fix the refs
self.human_current_page if not self.human_current_page.is_closed() else self.agent_current_page
)
- break # only close a maximum of one unused about:blank tab,
+ break # only close a maximum of one unused new tab page,
# if multiple parallel agents share one BrowserSession
- # closing every new_page() tab (which start on about:blank) causes lots of problems
+ # closing every new_page() tab (which start on new tab pages) causes lots of problems
# (the title check is not enough when they share a single BrowserSession)
return new_page
@@ -3644,8 +3707,9 @@ class BrowserSession(BaseModel):
scroll_y = await page.evaluate('window.scrollY')
viewport_height = await page.evaluate('window.innerHeight')
total_height = await page.evaluate('document.documentElement.scrollHeight')
- pixels_above = scroll_y
- pixels_below = total_height - (scroll_y + viewport_height)
+ # Convert to int to handle fractional pixels
+ pixels_above = int(scroll_y)
+ pixels_below = int(max(0, total_height - (scroll_y + viewport_height)))
return pixels_above, pixels_below
@require_initialization
@@ -3674,13 +3738,13 @@ class BrowserSession(BaseModel):
};
}""")
- # Calculate derived values
- viewport_width = page_data['viewport_width']
- viewport_height = page_data['viewport_height']
- page_width = page_data['page_width']
- page_height = page_data['page_height']
- scroll_x = page_data['scroll_x']
- scroll_y = page_data['scroll_y']
+ # Calculate derived values (convert to int to handle fractional pixels)
+ viewport_width = int(page_data['viewport_width'])
+ viewport_height = int(page_data['viewport_height'])
+ page_width = int(page_data['page_width'])
+ page_height = int(page_data['page_height'])
+ scroll_x = int(page_data['scroll_x'])
+ scroll_y = int(page_data['scroll_y'])
# Calculate scroll information
pixels_above = scroll_y
@@ -3748,7 +3812,7 @@ class BrowserSession(BaseModel):
return
# we could enforce this, but maybe it's useful to be able to show it on other tabs?
- # assert page.url == 'about:blank', 'DVD screensaver loading animation should only be shown on about:blank tabs'
+ # assert is_new_tab_page(page.url), 'DVD screensaver loading animation should only be shown on new tab pages'
# all in one JS function for speed, we want as few roundtrip CDP calls as possible
# between opening the tab and showing the animation
diff --git a/browser_use/cli.py b/browser_use/cli.py
index 592b7d8af..4faef6679 100644
--- a/browser_use/cli.py
+++ b/browser_use/cli.py
@@ -1022,11 +1022,26 @@ class BrowserUseApp(App):
# Panel updates are already happening via the timer in update_info_panels
+ task_start_time = time.time()
+ error_msg = None
+
try:
+ # Capture telemetry for message sent
+ self._telemetry.capture(
+ CLITelemetryEvent(
+ version=get_browser_use_version(),
+ action='message_sent',
+ mode='interactive',
+ model=self.llm.model if self.llm and hasattr(self.llm, 'model') else None,
+ model_provider=self.llm.provider if self.llm and hasattr(self.llm, 'provider') else None,
+ )
+ )
+
# Run the agent task, redirecting output to RichLog through our handler
if self.agent:
await self.agent.run()
except Exception as e:
+ error_msg = str(e)
logger.error('\nError running agent: %s', str(e))
finally:
# Clear the running flag
@@ -1035,6 +1050,20 @@ class BrowserUseApp(App):
# No need to call update_info_panels() here as it's already updating via timer
+ # Capture telemetry for task completion
+ duration = time.time() - task_start_time
+ self._telemetry.capture(
+ CLITelemetryEvent(
+ version=get_browser_use_version(),
+ action='task_completed' if error_msg is None else 'error',
+ mode='interactive',
+ model=self.llm.model if self.llm and hasattr(self.llm, 'model') else None,
+ model_provider=self.llm.provider if self.llm and hasattr(self.llm, 'provider') else None,
+ duration_seconds=duration,
+ error_message=error_msg,
+ )
+ )
+
logger.debug('\n✅ Task completed!')
# Make sure the task input container is visible
@@ -1085,13 +1114,13 @@ class BrowserUseApp(App):
async def action_quit(self) -> None:
"""Quit the application and clean up resources."""
- # Close the browser session if it exists
- if self.browser_session:
- try:
- await self.browser_session.close()
- logging.debug('Browser session closed successfully')
- except Exception as e:
- logging.error(f'Error closing browser session: {str(e)}')
+ # Note: We don't need to close the browser session here because:
+ # 1. If an agent exists, it already called browser_session.stop() in its run() method
+ # 2. If keep_alive=True (default), we want to leave the browser running anyway
+ # This prevents the duplicate "stop() called" messages in the logs
+
+ # Flush telemetry before exiting
+ self._telemetry.flush()
# Exit the application
self.exit()
@@ -1199,6 +1228,17 @@ async def run_prompt_mode(prompt: str, ctx: click.Context, debug: bool = False):
# Get LLM
llm = get_llm(config)
+ # Capture telemetry for CLI start in oneshot mode
+ telemetry.capture(
+ CLITelemetryEvent(
+ version=get_browser_use_version(),
+ action='start',
+ mode='oneshot',
+ model=llm.model if hasattr(llm, 'model') else None,
+ model_provider=llm.__class__.__name__ if llm else None,
+ )
+ )
+
# Get agent settings from config
agent_settings = AgentSettings.model_validate(config.get('agent', {}))
@@ -1223,10 +1263,36 @@ async def run_prompt_mode(prompt: str, ctx: click.Context, debug: bool = False):
await agent.run()
- # Close browser session
- await browser_session.close()
+ # Note: We don't close the browser session here because:
+ # 1. The agent already called browser_session.stop() in its run() method
+ # 2. This prevents duplicate "stop() called" messages in the logs
+
+ # Capture telemetry for successful completion
+ telemetry.capture(
+ CLITelemetryEvent(
+ version=get_browser_use_version(),
+ action='task_completed',
+ mode='oneshot',
+ model=llm.model if hasattr(llm, 'model') else None,
+ model_provider=llm.__class__.__name__ if llm else None,
+ duration_seconds=time.time() - start_time,
+ )
+ )
except Exception as e:
+ error_msg = str(e)
+ # Capture telemetry for error
+ telemetry.capture(
+ CLITelemetryEvent(
+ version=get_browser_use_version(),
+ action='error',
+ mode='oneshot',
+ model=llm.model if hasattr(llm, 'model') else None,
+ model_provider=llm.__class__.__name__ if llm and 'llm' in locals() else None,
+ duration_seconds=time.time() - start_time,
+ error_message=error_msg,
+ )
+ )
if debug:
import traceback
@@ -1234,6 +1300,9 @@ async def run_prompt_mode(prompt: str, ctx: click.Context, debug: bool = False):
else:
print(f'Error: {str(e)}', file=sys.stderr)
sys.exit(1)
+ finally:
+ # Ensure telemetry is flushed
+ telemetry.flush()
async def textual_interface(config: dict[str, Any]):
@@ -1336,9 +1405,8 @@ async def textual_interface(config: dict[str, Any]):
await app.run_async()
except Exception as e:
logger.error(f'Error in textual_interface: {str(e)}', exc_info=True)
- # Make sure to close browser session if app initialization fails
- if 'browser_session' in locals():
- await browser_session.close()
+ # Note: We don't close the browser session here to avoid duplicate stop() calls
+ # The browser session will be cleaned up by its __del__ method if needed
raise
@@ -1350,12 +1418,12 @@ async def textual_interface(config: dict[str, Any]):
@click.option('--window-width', type=int, help='Browser window width')
@click.option('--window-height', type=int, help='Browser window height')
@click.option(
- '--user-data-dir', type=str, help='Path to Chrome user data directory (e.g., ~/Library/Application Support/Google/Chrome)'
+ '--user-data-dir', type=str, help='Path to Chrome user data directory (e.g. ~/Library/Application Support/Google/Chrome)'
)
[email protected]('--profile-directory', type=str, help='Chrome profile directory name (e.g., "Default", "Profile 1")')
[email protected]('--cdp-url', type=str, help='Connect to existing Chrome via CDP URL (e.g., http://localhost:9222)')
[email protected]('--profile-directory', type=str, help='Chrome profile directory name (e.g. "Default", "Profile 1")')
[email protected]('--cdp-url', type=str, help='Connect to existing Chrome via CDP URL (e.g. http://localhost:9222)')
@click.option('-p', '--prompt', type=str, help='Run a single task without the TUI (headless mode)')
[email protected]('--mcp', is_flag=True, help='Run as MCP server')
[email protected]('--mcp', is_flag=True, help='Run as MCP server (exposes JSON RPC via stdin/stdout)')
@click.pass_context
def main(ctx: click.Context, debug: bool = False, **kwargs):
"""Browser-Use Interactive TUI or Command Line Executor
@@ -1378,6 +1446,15 @@ def main(ctx: click.Context, debug: bool = False, **kwargs):
# Check if MCP server mode is activated
if kwargs.get('mcp'):
+ # Capture telemetry for MCP server mode via CLI
+ telemetry = ProductTelemetry()
+ telemetry.capture(
+ CLITelemetryEvent(
+ version=get_browser_use_version(),
+ action='start',
+ mode='mcp_server',
+ )
+ )
# Run as MCP server
from browser_use.mcp.server import main as mcp_main
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.py
index 49ec2c412..d59384c67 100644
--- a/browser_use/controller/registry/service.py
+++ b/browser_use/controller/registry/service.py
@@ -22,7 +22,7 @@ from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.base import BaseChatModel
from browser_use.observability import observe_debug
from browser_use.telemetry.service import ProductTelemetry
-from browser_use.utils import match_url_with_domain_pattern, time_execution_async
+from browser_use.utils import is_new_tab_page, match_url_with_domain_pattern, time_execution_async
Context = TypeVar('Context')
@@ -395,7 +395,7 @@ class Registry(Generic[Context]):
def _log_sensitive_data_usage(self, placeholders_used: set[str], current_url: str | None) -> None:
"""Log when sensitive data is being used on a page"""
if placeholders_used:
- url_info = f' on {current_url}' if current_url and current_url != 'about:blank' else ''
+ url_info = f' on {current_url}' if current_url and not is_new_tab_page(current_url) else ''
logger.info(f'🔒 Using sensitive data placeholders: {", ".join(sorted(placeholders_used))}{url_info}')
def _replace_sensitive_data(
@@ -427,7 +427,7 @@ class Registry(Generic[Context]):
if isinstance(content, dict):
# New format: {domain_pattern: {key: value}}
# Only include secrets for domains that match the current URL
- if current_url and current_url != 'about:blank':
+ if current_url and not is_new_tab_page(current_url):
# it's a real url, check it using our custom allowed_domains scheme://*.example.com glob matching
if match_url_with_domain_pattern(current_url, domain_or_key):
applicable_secrets.update(content)
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 92dde5228..dc059732a 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -15,7 +15,7 @@ from browser_use.dom.views import (
SelectorMap,
ViewportInfo,
)
-from browser_use.utils import time_execution_async
+from browser_use.utils import is_new_tab_page, time_execution_async
# @dataclass
# class ViewportInfo:
@@ -56,7 +56,7 @@ class DomService:
return [
frame.url
for frame in self.page.frames
- if urlparse(frame.url).netloc # exclude data:urls and about:blank
+ if urlparse(frame.url).netloc # exclude data:urls and new tab pages
and urlparse(frame.url).netloc != urlparse(self.page.url).netloc # exclude same-origin iframes
and frame.url not in hidden_frame_urls # exclude hidden frames
and not is_ad_url(frame.url) # exclude most common ad network tracker frame URLs
@@ -72,7 +72,7 @@ class DomService:
if await self.page.evaluate('1+1') != 2:
raise ValueError('The page cannot evaluate javascript code properly')
- if self.page.url == 'about:blank':
+ if is_new_tab_page(self.page.url):
# short-circuit if the page is a new empty tab for speed, no need to inject buildDomTree.js
return (
DOMElementNode(
diff --git a/browser_use/mcp/server.py b/browser_use/mcp/server.py
index 76fb259a5..0e8ca777a 100644
--- a/browser_use/mcp/server.py
+++ b/browser_use/mcp/server.py
@@ -32,6 +32,13 @@ import time
from pathlib import Path
from typing import Any, Literal
+try:
+ import psutil
+
+ PSUTIL_AVAILABLE = True
+except ImportError:
+ PSUTIL_AVAILABLE = False
+
# Set environment to suppress browser-use logging during import
os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'error'
os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false' # Prevent automatic logging setup
@@ -125,6 +132,37 @@ from browser_use.telemetry import MCPServerTelemetryEvent, ProductTelemetry
from browser_use.utils import get_browser_use_version
+def get_parent_process_cmdline() -> str | None:
+ """Get the command line of all parent processes up the chain."""
+ if not PSUTIL_AVAILABLE:
+ return None
+
+ try:
+ cmdlines = []
+ current_process = psutil.Process()
+ parent = current_process.parent()
+
+ while parent:
+ try:
+ cmdline = parent.cmdline()
+ if cmdline:
+ cmdlines.append(' '.join(cmdline))
+ except (psutil.AccessDenied, psutil.NoSuchProcess):
+ # Skip processes we can't access (like system processes)
+ pass
+
+ try:
+ parent = parent.parent()
+ except (psutil.AccessDenied, psutil.NoSuchProcess):
+ # Can't go further up the chain
+ break
+
+ return ';'.join(cmdlines) if cmdlines else None
+ except Exception:
+ # If we can't get parent process info, just return None
+ return None
+
+
class BrowserUseServer:
"""MCP Server for browser-use capabilities."""
@@ -770,6 +808,7 @@ async def main():
MCPServerTelemetryEvent(
version=get_browser_use_version(),
action='start',
+ parent_process_cmdline=get_parent_process_cmdline(),
)
)
try:
@@ -782,6 +821,7 @@ async def main():
version=get_browser_use_version(),
action='stop',
duration_seconds=duration,
+ parent_process_cmdline=get_parent_process_cmdline(),
)
)
server._telemetry.flush()
diff --git a/browser_use/sync/service.py b/browser_use/sync/service.py
index a46dd5786..e7a412391 100644
--- a/browser_use/sync/service.py
+++ b/browser_use/sync/service.py
@@ -5,6 +5,7 @@ Cloud sync service for sending events to the Browser Use cloud.
import asyncio
import json
import logging
+import shutil
import anyio
import httpx
@@ -113,11 +114,11 @@ class CloudSync:
# Use frontend URL for user-facing links
frontend_url = CONFIG.BROWSER_USE_CLOUD_UI_URL or self.base_url.replace('//api.', '//cloud.')
session_url = f'{frontend_url.rstrip("/")}/agent/{agent_session_id}'
-
- logger.info('\n\n' + '─' * 70)
+ terminal_width, _terminal_height = shutil.get_terminal_size((80, 20))
+ logger.info('─' * (terminal_width - 1) + '\n')
logger.info('🌐 View the details of this run in Browser Use Cloud:')
logger.info(f' 👉 {session_url}')
- logger.info('─' * 70 + '\n')
+ logger.info('─' * (terminal_width - 1) + '\n\n')
return
# Otherwise run full authentication
diff --git a/browser_use/telemetry/service.py b/browser_use/telemetry/service.py
index 5fbab3905..ebba180a8 100644
--- a/browser_use/telemetry/service.py
+++ b/browser_use/telemetry/service.py
@@ -1,6 +1,5 @@
import logging
import os
-from pathlib import Path
from dotenv import load_dotenv
from posthog import Posthog
@@ -21,13 +20,6 @@ POSTHOG_EVENT_SETTINGS = {
}
-def xdg_cache_home() -> Path:
- default = Path.home() / '.cache'
- if CONFIG.XDG_CACHE_HOME and (path := Path(CONFIG.XDG_CACHE_HOME)).is_absolute():
- return path
- return default
-
-
@singleton
class ProductTelemetry:
"""
@@ -36,7 +28,7 @@ class ProductTelemetry:
If the environment variable `ANONYMIZED_TELEMETRY=False`, anonymized telemetry will be disabled.
"""
- USER_ID_PATH = str(xdg_cache_home() / 'browser_use' / 'telemetry_user_id')
+ USER_ID_PATH = str(CONFIG.BROWSER_USE_CONFIG_DIR / 'device_id')
PROJECT_API_KEY = 'phc_F8JMNjW1i2KbGUTaW1unnDdLSPCoyc52SGRU0JecaUh'
HOST = 'https://eu.i.posthog.com'
UNKNOWN_USER_ID = 'UNKNOWN'
diff --git a/browser_use/telemetry/views.py b/browser_use/telemetry/views.py
index b4ec7f20b..c6c7a8046 100644
--- a/browser_use/telemetry/views.py
+++ b/browser_use/telemetry/views.py
@@ -69,6 +69,7 @@ class MCPServerTelemetryEvent(BaseTelemetryEvent):
tool_name: str | None = None
duration_seconds: float | None = None
error_message: str | None = None
+ parent_process_cmdline: str | None = None
name: str = 'mcp_server_event'
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 2897f4cde..ea4f4a76c 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -424,6 +424,19 @@ def is_unsafe_pattern(pattern: str) -> bool:
return '*' in bare_domain
+def is_new_tab_page(url: str) -> bool:
+ """
+ Check if a URL is a new tab page (about:blank or chrome://new-tab-page).
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ bool: True if the URL is a new tab page, False otherwise
+ """
+ return url in ('about:blank', 'chrome://new-tab-page/', 'chrome://new-tab-page')
+
+
def match_url_with_domain_pattern(url: str, domain_pattern: str, log_warnings: bool = False) -> bool:
"""
Check if a URL matches a domain pattern. SECURITY CRITICAL.
@@ -437,7 +450,7 @@ def match_url_with_domain_pattern(url: str, domain_pattern: str, log_warnings: b
When no scheme is specified, https is used by default for security.
For example, 'example.com' will match 'https://example.com' but not 'http://example.com'.
- Note: about:blank must be handled at the callsite, not inside this function.
+ Note: New tab pages (about:blank, chrome://new-tab-page) must be handled at the callsite, not inside this function.
Args:
url: The URL to check
@@ -448,8 +461,8 @@ def match_url_with_domain_pattern(url: str, domain_pattern: str, log_warnings: b
bool: True if the URL matches the pattern, False otherwise
"""
try:
- # Note: about:blank should be handled at the callsite, not here
- if url == 'about:blank':
+ # Note: new tab pages should be handled at the callsite, not here
+ if is_new_tab_page(url):
return False
parsed_url = urlparse(url)
@@ -835,10 +848,18 @@ def retry(
# Calculate wait time with backoff
current_wait = wait * (backoff_factor**attempt)
- logger.warning(
- f'{func.__name__} failed (attempt {attempt + 1}/{retries + 1}): '
- f'{type(e).__name__}: {e}. Waiting {current_wait:.1f}s before retry...'
- )
+ # Only log warning on the final retry attempt (second-to-last overall attempt)
+ if attempt == retries - 1:
+ logger.warning(
+ f'{func.__name__} failed (attempt {attempt + 1}/{retries + 1}): '
+ f'{type(e).__name__}: {e}. Waiting {current_wait:.1f}s before retry...'
+ )
+ # else:
+ # # For earlier attempts, skip logging to reduce noise
+ # logger.debug(
+ # f'{func.__name__} failed (attempt {attempt + 1}/{retries + 1}): '
+ # f'{type(e).__name__}: {e}. Waiting {current_wait:.1f}s before retry...'
+ # )
await asyncio.sleep(current_wait)
else:
# Final failure
diff --git a/pyproject.toml b/pyproject.toml
index 131c0fad9..bd57db61f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -13,7 +13,7 @@ classifiers = [
dependencies = [
"aiofiles>=24.1.0",
"anyio>=4.9.0",
- "bubus>=1.4.1",
+ "bubus>=1.4.2",
"google-api-core>=2.25.0",
"httpx>=0.28.1",
"markdownify==1.1.0",