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
feat: convert synchronous file operations to async in BrowserSession - Convert 6 file operations from sync to async using anyio.Path() - Fix critical merge logic bug in save_storage_state - Improves I/O performance by preventing event loop blocking - Maintains backward compatibility and existing error handling
tinkerer-shubh3582a4922e72
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 1f1e9dd2c..267819fd8 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -15,6 +15,7 @@ from urllib.parse import urlparseos.environ['PW_TEST_SCREENSHOT_NO_FONTS_READY'] = '1' # https://github.com/microsoft/playwright/issues/35972+import anyioimport psutilfrom patchright.async_api import Playwright as PatchrightPlaywrightfrom playwright.async_api import Browser as PlaywrightBrowser@@ -1116,8 +1117,9 @@ class BrowserSession(BaseModel):try:cookies_file_path = Path(path or self.browser_profile.cookies_file).expanduser().resolve()cookies_file_path.parent.mkdir(parents=True, exist_ok=True)- cookies_file_path.write_text(json.dumps(cookies, indent=4)) # TODO: convert to async+ 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)}')+ returnexcept Exception as e:logger.warning(f'❌ Failed to save cookies to cookies_file={_log_pretty_path(cookies_file_path)}: {type(e).__name__}: {e}'@@ -1145,18 +1147,21 @@ class BrowserSession(BaseModel):# 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 = json.loads(storage_state_path.read_text()) # TODO: convert to async+ 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- storage_state_path.write_text(json.dumps(merged_storage_state, indent=4)) # TODO: convert to async+ 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-- storage_state_path.write_text(json.dumps(storage_state, indent=4)) # TODO: convert to async+ 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)}')@@ -1184,7 +1189,8 @@ class BrowserSession(BaseModel):cookies_path = Path(self.browser_profile.downloads_dir or '.') / cookies_pathtry:- cookies_data = json.loads(cookies_path.read_text())+ cookies_data_text = await anyio.Path(cookies_path).read_text()+ cookies_data = json.loads(cookies_data_text)if cookies_data:await self.browser_context.add_cookies(cookies_data)logger.info(f'🍪 Loaded {len(cookies_data)} cookies from cookies_file={_log_pretty_path(cookies_path)}')@@ -1197,7 +1203,8 @@ class BrowserSession(BaseModel):storage_state = self.browser_profile.storage_stateif isinstance(storage_state, (str, Path)):try:- storage_state = json.loads(Path(storage_state).read_text())+ storage_state_text = await anyio.Path(storage_state).read_text()+ storage_state = json.loads(storage_state_text)except Exception as e:logger.warning(f'❌ Failed to load cookies from storage_state={_log_pretty_path(self.browser_profile.storage_state)}: {type(e).__name__}: {e}'