Skip to content

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

use async lock to protect BrowserSession.start from race conditions

Nick Sweeting8f6f90724792
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index e95b6cf08..edbd488ca 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -15,6 +15,7 @@ from urllib.parse import urlparse
os.environ['PW_TEST_SCREENSHOT_NO_FONTS_READY'] = '1' # https://github.com/microsoft/playwright/issues/35972
+import anyio
import psutil
from patchright.async_api import Browser as PatchrightBrowser
from patchright.async_api import BrowserContext as PatchrightBrowserContext
@@ -30,6 +31,7 @@ from playwright.async_api import FrameLocator as PlaywrightFrameLocator
from playwright.async_api import Page as PlaywrightPage
from playwright.async_api import Playwright, async_playwright
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, InstanceOf, PrivateAttr, model_validator
+from uuid_extensions import uuid7str
from browser_use.browser.profile import BrowserChannel, BrowserProfile
from browser_use.browser.views import (
@@ -167,6 +169,9 @@ class BrowserSession(BaseModel):
# this class accepts arbitrary extra **kwargs in init because of the extra='allow' pydantic option
# they are saved on the model, then applied to self.browser_profile via .apply_session_overrides_to_profile()
+ # Persistent ID for this browser session
+ id: str = Field(default_factory=uuid7str)
+
# template profile for the BrowserSession, will be copied at init/validation time, and overrides applied to the copy
browser_profile: InstanceOf[BrowserProfile] = Field(
default=DEFAULT_BROWSER_PROFILE,
@@ -275,9 +280,14 @@ class BrowserSession(BaseModel):
async with self._start_lock:
# if we're already initialized and the connection is still valid, return the existing session state and start from scratch
- if self.initialized and self.is_connected():
- return self
- self._reset_connection_state()
+ if self.initialized:
+ if self.is_connected():
+ return self
+ else:
+ # only reset connection state if we expected to be already connected but we're not
+ # avoid calling this on *first* start() as it just immediately clears many
+ # of the params passed in to BrowserSession(...) init, which the .setup_...() methods below expect
+ self._reset_connection_state()
self.initialized = True # set this first to ensure two parallel calls to start() don't clash with each other
try:
@@ -308,46 +318,65 @@ class BrowserSession(BaseModel):
return self
async def stop(self) -> None:
- """Shuts down the BrowserSession, killing the browser process (only works if keep_alive=False)"""
+ """Shuts down the BrowserSession, killing the browser process if keep_alive=False"""
- self.initialized = False
+ # trying to launch/kill browsers at the same time is an easy way to trash an entire user_data_dir
+ # it's worth the 1s or 2s of delay in the worst case to avoid race conditions, user_data_dir can be a few GBs
+ async with self._start_lock:
+ # save cookies to disk if cookies_file or storage_state is configured
+ # but only if the browser context is still connected
+ if self.is_connected():
+ try:
+ await self.save_storage_state()
+ except Exception as e:
+ logger.debug(f'Failed to save storage state during stop: {type(e).__name__}: {e}')
- if self.browser_profile.keep_alive:
- return # nothing to do if keep_alive=True, leave the browser running
+ # reset connection state
+ self.initialized = False
- if self.browser_context or self.browser:
- try:
- await (self.browser_context or self.browser).close()
- logger.info(
- f'πŸ›‘ Stopped the {self.browser_profile.channel.name.lower()} browser '
- f'keep_alive=False user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} cdp_url={self.cdp_url or self.wss_url} pid={self.browser_pid}'
- )
- self.browser_context = None
- except Exception as e:
- logger.debug(f'❌ Error closing playwright BrowserContext {self.browser_context}: {type(e).__name__}: {e}')
+ if self.browser_profile.keep_alive:
+ return # nothing to do if keep_alive=True, leave the browser running
- # kill the chrome subprocess if we were the ones that started it
- if self.browser_pid:
- try:
- psutil.Process(pid=self.browser_pid).terminate()
- logger.info(f' ↳ Killed browser subprocess with browser_pid={self.browser_pid} keep_alive=False')
- self.browser_pid = None
- except Exception as e:
- if 'NoSuchProcess' not in type(e).__name__:
- logger.debug(f'❌ Error terminating subprocess with browser_pid={self.browser_pid}: {type(e).__name__}: {e}')
+ if self.browser_context or self.browser:
+ try:
+ await (self.browser_context or self.browser).close()
+ logger.info(
+ f'πŸ›‘ Stopped the {self.browser_profile.channel.name.lower()} browser '
+ f'keep_alive=False user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"} cdp_url={self.cdp_url or self.wss_url} pid={self.browser_pid}'
+ )
+ except Exception as e:
+ logger.debug(f'❌ Error closing playwright BrowserContext {self.browser_context}: {type(e).__name__}: {e}')
+ finally:
+ # Always clear references to ensure a fresh start next time
+ self.browser_context = None
+ self.browser = None
- async def close(self) -> None:
- """Deprecated: Provides backwards-compatibility with old method Browser().close() and playwright BrowserContext.close()"""
- await self.stop()
+ # kill the chrome subprocess if we were the ones that started it
+ if self.browser_pid:
+ try:
+ psutil.Process(pid=self.browser_pid).terminate()
+ logger.info(f' ↳ Killed browser subprocess with browser_pid={self.browser_pid} keep_alive=False')
+ self.browser_pid = None
+ except Exception as e:
+ if 'NoSuchProcess' not in type(e).__name__:
+ logger.debug(
+ f'❌ Error terminating subprocess with browser_pid={self.browser_pid}: {type(e).__name__}: {e}'
+ )
- async def kill(self) -> None:
- """Stop the BrowserSession even if keep_alive=True"""
- self.browser_profile.keep_alive = False
+ # Close playwright if we own it
+ if self.playwright:
+ try:
+ await self.playwright.stop()
+ self.playwright = None
+ except Exception as e:
+ logger.debug(f'Error stopping playwright: {type(e).__name__}: {e}')
+
+ async def close(self) -> None:
+ """Deprecated: Provides backwards-compatibility with old class method Browser().close()"""
await self.stop()
async def new_context(self, **kwargs):
- """Deprecated: Provides backwards-compatibility with old class method Browser().new_context()."""
- # TODO: remove this after >=0.3.0
+ """Deprecated: Provides backwards-compatibility with old class method Browser().new_context()"""
return self
async def __aenter__(self) -> BrowserSession:
@@ -909,8 +938,22 @@ class BrowserSession(BaseModel):
self.initialized = False
self.browser = None
self.browser_context = None
- # Also clear browser_pid since the process may no longer exist
- self.browser_pid = None
+ self.agent_current_page = None
+ self.human_current_page = None
+ self._cached_clickable_element_hashes = None
+ self._cached_browser_state_summary = None
+ if self.browser_pid:
+ try:
+ # browser_pid is different from all the other state objects, it's closer to cdp_url or wss_url
+ # because we might still be able to reconnect to the same browser even if self.browser_context died
+ # if we have a self.browser_pid, check if it's still alive and serving a remote debugging port
+ # if so, don't clear it because there's a chance we can re-use it by just reconnecting to the same pid's port
+ proc = psutil.Process(self.browser_pid)
+ proc_is_alive = proc.status() not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD)
+ assert proc_is_alive and '--remote-debugging-port' in ' '.join(proc.cmdline())
+ except Exception:
+ # process has gone away or crashed, pid is no longer valid so we clear it
+ self.browser_pid = None
# --- Tab management ---
async def get_current_page(self) -> Page:
@@ -1145,6 +1188,59 @@ class BrowserSession(BaseModel):
"""
await self.save_storage_state(*args, **kwargs)
+ async def _save_cookies_to_file(self, cookies: list[dict[str, Any]], path: Path) -> None:
+ try:
+ cookies_file_path = Path(path or self.browser_profile.cookies_file).expanduser().resolve()
+ cookies_file_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # Write to a temporary file first
+ temp_path = cookies_file_path.with_suffix('.tmp')
+ temp_path.write_text(json.dumps(cookies, indent=4))
+
+ try:
+ # backup any existing cookies_file if one is already present
+ cookies_file_path.replace(cookies_file_path.with_suffix('.json.bak'))
+ except Exception:
+ pass
+ temp_path.replace(cookies_file_path)
+
+ logger.info(f'πŸͺ Saved {len(cookies)} cookies to cookies_file={_log_pretty_path(cookies_file_path)}')
+ except Exception as e:
+ logger.warning(
+ f'❌ Failed to save cookies to cookies_file={_log_pretty_path(cookies_file_path)}: {type(e).__name__}: {e}'
+ )
+
+ async def _save_storage_state_to_file(self, storage_state: dict[str, Any], path: Path) -> None:
+ try:
+ json_path = Path(path).expanduser().resolve()
+ json_path.parent.mkdir(parents=True, exist_ok=True)
+ storage_state = await self.browser_context.storage_state()
+
+ # always atomic merge storage states, never overwrite (so two browsers can share the same storage_state.json)
+ merged_storage_state = storage_state
+ if json_path.exists():
+ try:
+ existing_storage_state = json.loads(json_path.read_text())
+ merged_storage_state = merge_dicts(existing_storage_state, storage_state)
+ except Exception as e:
+ logger.error(
+ f'❌ Failed to merge updated storage_state with existing storage_state={_log_pretty_path(json_path)}: {type(e).__name__}: {e}'
+ )
+ return
+
+ # write to .tmp file first to avoid partial writes, then mv original to .bak and .tmp to original
+ temp_path = json_path.with_suffix('.json.tmp')
+ temp_path.write_text(json.dumps(merged_storage_state, indent=4))
+ try:
+ json_path.replace(json_path.with_suffix('.json.bak'))
+ except Exception:
+ pass
+ temp_path.replace(json_path)
+
+ logger.info(f'πŸͺ Saved {len(storage_state["cookies"])} cookies to storage_state={_log_pretty_path(json_path)}')
+ except Exception as e:
+ logger.warning(f'❌ Failed to save storage state to storage_state={_log_pretty_path(path)}: {type(e).__name__}: {e}')
+
@require_initialization
async def save_storage_state(self, path: Path | None = None) -> None:
"""
@@ -1152,72 +1248,53 @@ class BrowserSession(BaseModel):
"""
storage_state = await self.browser_context.storage_state()
cookies = storage_state['cookies']
+
+ # they passed an explicit path, only save to that path and return
+ if path:
+ if path.name == 'storage_state.json':
+ await self._save_storage_state_to_file(storage_state, path)
+ return
+ else:
+ # assume they're using the old API when path meant a cookies_file path,
+ # also save new format next to it for convenience to help them migrate
+ await self._save_cookies_to_file(cookies, path)
+ await self._save_storage_state_to_file(storage_state, path.parent / 'storage_state.json')
+ logger.warning(
+ '⚠️ cookies_file is deprecated and will be removed in a future version. '
+ 'Please use storage_state="path/to/storage_state.json" instead for persisting cookies and other browser state. '
+ 'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
+ )
+ return
+
+ # save cookies_file if passed a cookies file path or if profile cookies_file is configured
if cookies and self.browser_profile.cookies_file:
# only show warning if they configured cookies_file (not if they passed in a path to this function as an arg)
logger.warning(
'⚠️ cookies_file is deprecated and will be removed in a future version. '
- 'Please use storage_state instead for loading cookies and other browser state. '
+ 'Please use storage_state="path/to/storage_state.json" instead for persisting cookies and other browser state. '
'See: https://playwright.dev/python/docs/api/class-browsercontext#browser-context-storage-state'
)
+ await self._save_cookies_to_file(cookies, path or self.browser_profile.cookies_file)
+ await self._save_storage_state_to_file(storage_state, path.parent / 'storage_state.json')
- # save cookies_file if passed a cookies file path or if profile cookies_file is configured
- path_is_storage_state = path and str(path).endswith('storage_state.json')
- if (path and not path_is_storage_state) or self.browser_profile.cookies_file:
- try:
- cookies_file_path = Path(path or self.browser_profile.cookies_file).expanduser().resolve()
- cookies_file_path.parent.mkdir(parents=True, exist_ok=True)
- await anyio.Path(cookies_file_path).write_text(json.dumps(cookies, indent=4))
- logger.info(f'πŸͺ Saved {len(cookies)} cookies to cookies_file={_log_pretty_path(cookies_file_path)}')
- return
- except Exception as e:
- logger.warning(
- f'❌ Failed to save cookies to cookies_file={_log_pretty_path(cookies_file_path)}: {type(e).__name__}: {e}'
- )
-
- if path:
- # if they passed in a path to the old save_cookies function,
- # also save a new storage_state.json next to it to encourage adoption of the new format
- storage_state_path = Path(path).expanduser().resolve().parent / 'storage_state.json'
- else:
- # otherwise use configured storage_state path
- storage_state_path = self.browser_profile.storage_state
-
- if storage_state_path is None:
+ if self.browser_profile.storage_state is None:
return
- elif not isinstance(storage_state_path, (str, Path)):
- logger.warning('⚠️ storage_state must be a json file path to be able to update it, skipping...')
- return
-
- try:
- storage_state_path = Path(storage_state_path).expanduser().resolve()
- storage_state_path.parent.mkdir(parents=True, exist_ok=True)
- storage_state = await self.browser_context.storage_state()
-
- # always merge storage states, never overwrite (so two browsers can share the same storage_state.json)
- if storage_state_path.exists():
- try:
- existing_storage_state_text = await anyio.Path(storage_state_path).read_text()
- existing_storage_state = json.loads(existing_storage_state_text)
- merged_storage_state = merge_dicts(existing_storage_state, storage_state)
- # in case another process races us and updates the file here, we will overwrite their changes
- # if we really want to support real concurrency we need a sqlite database or something
- await anyio.Path(storage_state_path).write_text(json.dumps(merged_storage_state, indent=4))
- except Exception as e:
- logger.warning(
- f'❌ Failed to merge storage state with existing storage_state={_log_pretty_path(storage_state_path)}: {type(e).__name__}: {e}'
- )
- return
- else:
- # No existing file, write the new storage state
- await anyio.Path(storage_state_path).write_text(json.dumps(storage_state, indent=4))
- logger.info(
- f'πŸͺ Saved {len(storage_state["cookies"])} cookies to storage_state={_log_pretty_path(storage_state_path)}'
- )
- except Exception as e:
+ if isinstance(self.browser_profile.storage_state, dict):
+ # cookies that never get updated rapidly expire or become invalid,
+ # e.g. cloudflare bumps a nonce + does a tiny proof-of-work chain on every request that gets stored back into the cookie
+ # if your cookies are frozen in time and don't update, they'll block you as a bot almost immediately
+ # if they pass a dict in it means they have to get the updated cookies manually with browser_context.cookies()
+ # and persist them manually on every change. most people don't realize they have to do that, so show a warning
logger.warning(
- f'❌ Failed to save storage state to storage_state={_log_pretty_path(storage_state_path)}: {type(e).__name__}: {e}'
+ f'⚠️ storage_state was set as a {type(self.browser_profile.storage_state)} and will not be updated with any cookie changes, use a json file path instead to persist changes'
)
+ return
+
+ if isinstance(self.browser_profile.storage_state, (str, Path)):
+ await self._save_storage_state_to_file(storage_state, self.browser_profile.storage_state)
+
+ raise Exception(f'Got unexpected type for storage_state: {type(self.browser_profile.storage_state)}')
@require_initialization
async def load_storage_state(self) -> None:
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 6d01dc9f3..4597cdc81 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -6,7 +6,8 @@ import signal
import time
from collections.abc import Callable, Coroutine
from fnmatch import fnmatch
-from functools import wraps
+from functools import cache, wraps
+from pathlib import Path
from sys import stderr
from typing import Any, ParamSpec, TypeVar
from urllib.parse import urlparse
@@ -491,3 +492,35 @@ def merge_dicts(a: dict, b: dict, path: tuple[str, ...] = ()):
else:
a[key] = b[key]
return a
+
+
+@cache
+def get_browser_use_version() -> str:
+ """Get the browser-use package version using the same logic as Agent._set_browser_use_version_and_source"""
+ try:
+ package_root = Path(__file__).parent.parent
+ pyproject_path = package_root / 'pyproject.toml'
+
+ # Try to read version from pyproject.toml
+ if pyproject_path.exists():
+ import re
+
+ with open(pyproject_path) as f:
+ content = f.read()
+ match = re.search(r'version\s*=\s*["\']([^"\']+)["\']', content)
+ if match:
+ return f'v{match.group(1)}'
+ else:
+ # Fallback to importlib if regex doesn't find version
+ from importlib.metadata import version as get_version
+
+ return f'v{get_version("browser-use")}'
+ else:
+ # If pyproject.toml doesn't exist, try getting version from pip
+ from importlib.metadata import version as get_version
+
+ return f'v{get_version("browser-use")}'
+
+ except Exception as e:
+ logger.debug(f'Error getting version: {e}')
+ return 'vunknown'