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(browser): apply storage_state cookies when passed as an in-memory dict
ayaangazalib3b7e12fa3d9
diff --git a/browser_use/browser/watchdogs/storage_state_watchdog.py b/browser_use/browser/watchdogs/storage_state_watchdog.pyindex 736235129..25ce39806 100644--- a/browser_use/browser/watchdogs/storage_state_watchdog.py+++ b/browser_use/browser/watchdogs/storage_state_watchdog.py@@ -63,27 +63,18 @@ class StorageStateWatchdog(BaseWatchdog):async def on_SaveStorageStateEvent(self, event: SaveStorageStateEvent) -> None:"""Handle storage state save request."""- # Use provided path or fall back to profile default- path = event.path- if path is None:- # Use profile default path if available- if self.browser_session.browser_profile.storage_state:- path = str(self.browser_session.browser_profile.storage_state)- else:- path = None # Skip saving if no path available- await self._save_storage_state(path)+ await self._save_storage_state(event.path if event.path is not None else self._profile_storage_state())async def on_LoadStorageStateEvent(self, event: LoadStorageStateEvent) -> None:"""Handle storage state load request."""- # Use provided path or fall back to profile default- path = event.path- if path is None:- # Use profile default path if available- if self.browser_session.browser_profile.storage_state:- path = str(self.browser_session.browser_profile.storage_state)- else:- path = None # Skip loading if no path available- await self._load_storage_state(path)+ await self._load_storage_state(event.path if event.path is not None else self._profile_storage_state())++ def _profile_storage_state(self) -> str | dict[str, Any] | None:+ """Profile default storage_state, preserving in-memory dicts instead of stringifying them."""+ storage_state = self.browser_session.browser_profile.storage_state+ if storage_state is None or isinstance(storage_state, dict):+ return storage_state+ return str(storage_state)async def _start_monitoring(self) -> None:"""Start the monitoring task."""@@ -164,7 +155,7 @@ class StorageStateWatchdog(BaseWatchdog):self.logger.debug(f'[StorageStateWatchdog] Error comparing cookies: {e}')return False- async def _save_storage_state(self, path: str | None = None) -> None:+ async def _save_storage_state(self, path: str | dict[str, Any] | None = None) -> None:"""Save browser storage state to file."""async with self._save_lock:# Check if CDP client is available@@ -230,22 +221,31 @@ class StorageStateWatchdog(BaseWatchdog):except Exception as e:self.logger.error(f'[StorageStateWatchdog] Failed to save storage state: {e}')- async def _load_storage_state(self, path: str | None = None) -> None:- """Load browser storage state from file."""+ async def _load_storage_state(self, path: str | dict[str, Any] | None = None) -> None:+ """Load browser storage state from a file path or an in-memory dict."""if not self.browser_session.cdp_client:self.logger.warning('[StorageStateWatchdog] No CDP client available for loading')returnload_path = path or self.browser_session.browser_profile.storage_state- if not load_path or not os.path.exists(str(load_path)):+ if isinstance(load_path, dict):+ # storage_state was provided as an in-memory dict, apply it directly (never stringify it:+ # dicts are not file paths, and repr would leak cookie values into logs/events)+ load_source = '<in-memory storage_state dict>'+ elif not load_path or not os.path.exists(str(load_path)):return+ else:+ load_source = str(load_path)try:- # Read the storage state file asynchronously- import anyio+ if isinstance(load_path, dict):+ storage = load_path+ else:+ # Read the storage state file asynchronously+ import anyio- content = await anyio.Path(str(load_path)).read_text()- storage = json.loads(content)+ content = await anyio.Path(load_source).read_text()+ storage = json.loads(content)# Apply cookies if presentif 'cookies' in storage and storage['cookies']:@@ -309,13 +309,13 @@ class StorageStateWatchdog(BaseWatchdog):self.event_bus.dispatch(StorageStateLoadedEvent(- path=str(load_path),+ path=load_source,cookies_count=len(storage.get('cookies', [])),origins_count=len(storage.get('origins', [])),))- self.logger.debug(f'[StorageStateWatchdog] Loaded storage state from: {load_path}')+ self.logger.debug(f'[StorageStateWatchdog] Loaded storage state from: {load_source}')except Exception as e:self.logger.error(f'[StorageStateWatchdog] Failed to load storage state: {e}')diff --git a/tests/ci/test_action_LoadStorageStateEvent.py b/tests/ci/test_action_LoadStorageStateEvent.pynew file mode 100644index 000000000..3270b5d07--- /dev/null+++ b/tests/ci/test_action_LoadStorageStateEvent.py@@ -0,0 +1,66 @@+"""Tests for LoadStorageStateEvent handling of in-memory dict storage_state (#4257).++BrowserProfile.storage_state accepts `str | Path | dict` (profile.py), but the+load path used to stringify the profile value unconditionally, so a dict became+"{'cookies': [...]}" and failed the os.path.exists() check, silently applying+nothing. Cookies passed as a dict must reach the browser via CDP.+"""++from browser_use.browser.profile import BrowserProfile+from browser_use.browser.session import BrowserSession++TEST_COOKIE = {+ 'name': 'bu_dict_state_test',+ 'value': 'loaded-from-dict',+ 'domain': '127.0.0.1',+ 'path': '/',+ 'httpOnly': False,+ 'secure': False,+ 'sameSite': 'Lax',+}+++async def test_dict_storage_state_cookies_are_applied_on_start():+ """storage_state passed as a dict (not a file path) must load its cookies into the browser."""+ session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=False,+ storage_state={'cookies': [TEST_COOKIE], 'origins': []},+ )+ )+ await session.start()+ try:+ cookies = await session._cdp_get_cookies()+ by_name = {c.get('name'): c for c in cookies}+ assert 'bu_dict_state_test' in by_name, (+ f'dict storage_state cookie never reached the browser; browser has {sorted(by_name)}. '+ f'The LoadStorageStateEvent path dropped the in-memory dict (#4257).'+ )+ assert by_name['bu_dict_state_test'].get('value') == 'loaded-from-dict'+ assert by_name['bu_dict_state_test'].get('domain') == '127.0.0.1'+ finally:+ await session.kill()+ await session.event_bus.stop(clear=True, timeout=5)+++async def test_session_cookie_expiry_normalized_from_dict():+ """Session cookies with expires=0/-1 in a dict storage_state must not be treated as expired."""+ session_cookie = dict(TEST_COOKIE, name='bu_session_cookie', expires=-1)+ session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=False,+ storage_state={'cookies': [session_cookie]},+ )+ )+ await session.start()+ try:+ cookies = await session._cdp_get_cookies()+ names = {c.get('name') for c in cookies}+ assert 'bu_session_cookie' in names, f'session cookie (expires=-1) from dict was dropped; browser has {sorted(names)}'+ finally:+ await session.kill()+ await session.event_bus.stop(clear=True, timeout=5)