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
make save_context and other file operations async, setup traces and other dirs on startup
Nick Sweeting582c039c159b
diff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.pyindex b682cbd7e..3cb25693a 100644--- a/browser_use/agent/message_manager/utils.py+++ b/browser_use/agent/message_manager/utils.py@@ -2,10 +2,11 @@ from __future__ import annotationsimport jsonimport logging-import osimport re-from typing import Any+from pathlib import Path+from typing import Any, TextIO+import anyiofrom langchain_core.messages import (AIMessage,BaseMessage,@@ -108,42 +109,47 @@ def _merge_successive_messages(messages: list[BaseMessage], class_to_merge: typereturn merged_messages-def save_conversation(input_messages: list[BaseMessage], response: Any, target: str, encoding: str | None = None) -> None:- """Save conversation history to file."""-+async def save_conversation(input_messages: list[BaseMessage], response: Any, target: str | Path, encoding: str | None = None) -> None:+ """Save conversation history to file asynchronously."""+ target_path = Path(target)+# create folders if not exists- if dirname := os.path.dirname(target):- os.makedirs(dirname, exist_ok=True)+ if target_path.parent:+ await anyio.Path(target_path.parent).mkdir(parents=True, exist_ok=True)- with open(- target,- 'w',- encoding=encoding,- ) as f:- _write_messages_to_file(f, input_messages)- _write_response_to_file(f, response)+ await anyio.Path(target_path).write_text(+ await _format_conversation(input_messages, response),+ encoding=encoding or 'utf-8'+ )-def _write_messages_to_file(f: Any, messages: list[BaseMessage]) -> None:- """Write messages to conversation file"""+async def _format_conversation(messages: list[BaseMessage], response: Any) -> str:+ """Format the conversation including messages and response."""+ lines = []++ # Format messagesfor message in messages:- f.write(f' {message.__class__.__name__} \n')-+ lines.append(f' {message.__class__.__name__} ')+if isinstance(message.content, list):for item in message.content:if isinstance(item, dict) and item.get('type') == 'text':- f.write(item['text'].strip() + '\n')+ lines.append(item['text'].strip())elif isinstance(message.content, str):try:content = json.loads(message.content)- f.write(json.dumps(content, indent=2) + '\n')+ lines.append(json.dumps(content, indent=2))except json.JSONDecodeError:- f.write(message.content.strip() + '\n')-- f.write('\n')---def _write_response_to_file(f: Any, response: Any) -> None:- """Write model response to conversation file"""- f.write(' RESPONSE\n')- f.write(json.dumps(json.loads(response.model_dump_json(exclude_unset=True)), indent=2))+ lines.append(message.content.strip())++ lines.append('') # Empty line after each message++ # Format response+ lines.append(' RESPONSE')+ lines.append(json.dumps(json.loads(response.model_dump_json(exclude_unset=True)), indent=2))++ return '\n'.join(lines)+++# Note: _write_messages_to_file and _write_response_to_file have been merged into _format_conversation+# This is more efficient for async operations and reduces file I/Odiff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 56d266b7d..2444edc7e 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -15,7 +15,6 @@ from typing import Any, Generic, TypeVarfrom dotenv import load_dotenv-from browser_use.browser.session import DEFAULT_BROWSER_PROFILEload_dotenv()@@ -29,6 +28,7 @@ from playwright.async_api import Browser, BrowserContext, Pagefrom pydantic import BaseModel, ValidationErrorfrom uuid_extensions import uuid7str+from browser_use.browser.session import DEFAULT_BROWSER_PROFILEfrom browser_use.agent.gif import create_history_giffrom browser_use.agent.memory import Memory, MemoryConfigfrom browser_use.agent.message_manager.service import MessageManager, MessageManagerSettings@@ -38,6 +38,7 @@ from browser_use.agent.message_manager.utils import (is_model_without_tool_support,save_conversation,)+from browser_use.utils import _log_pretty_pathfrom browser_use.agent.prompts import AgentMessagePrompt, PlannerPrompt, SystemPromptfrom browser_use.agent.views import (ActionResult,@@ -132,7 +133,7 @@ class Agent(Generic[Context]):# Agent settingsuse_vision: bool = True,use_vision_for_planner: bool = False,- save_conversation_path: str | None = None,+ save_conversation_path: str | Path | None = None,save_conversation_path_encoding: str | None = 'utf-8',max_failures: int = 3,retry_delay: int = 10,@@ -417,7 +418,8 @@ class Agent(Generic[Context]):self.telemetry = ProductTelemetry()if self.settings.save_conversation_path:- self.logger.info(f'Saving conversation to {self.settings.save_conversation_path}')+ self.settings.save_conversation_path = Path(self.settings.save_conversation_path).expanduser().resolve()+ self.logger.info(f'Saving conversation to {_log_pretty_path(self.settings.save_conversation_path)}')self._external_pause_event = asyncio.Event()self._external_pause_event.set()@@ -910,8 +912,8 @@ class Agent(Generic[Context]):else:self.register_new_step_callback(browser_state_summary, model_output, self.state.n_steps)if self.settings.save_conversation_path:- target = self.settings.save_conversation_path + f'_{self.state.n_steps}.txt'- save_conversation(input_messages, model_output, target, self.settings.save_conversation_path_encoding)+ target = Path(self.settings.save_conversation_path).with_suffix('').as_posix() + f'_{self.state.n_steps}.txt'+ await save_conversation(input_messages, model_output, target, self.settings.save_conversation_path_encoding)self._message_manager._remove_last_state_message() # we dont want the whole state in the chat historydiff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex c9deea510..e3b080762 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -39,7 +39,7 @@ class AgentSettings(BaseModel):use_vision: bool = Trueuse_vision_for_planner: bool = False- save_conversation_path: str | None = None+ save_conversation_path: str | Path | None = Nonesave_conversation_path_encoding: str | None = 'utf-8'max_failures: int = 3retry_delay: int = 10diff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.pyindex bd9e89cc6..54b55303e 100644--- a/browser_use/browser/profile.py+++ b/browser_use/browser/profile.py@@ -375,9 +375,9 @@ class BrowserContextArgs(BaseModel):record_har_content: RecordHarContent = RecordHarContent.EMBEDrecord_har_mode: RecordHarMode = RecordHarMode.FULLrecord_har_omit_content: bool = False- record_har_path: str | Path | None = None+ record_har_path: str | Path | None = Field(default=None, validation_alias=AliasChoices('save_har_path', 'record_har_path'))record_har_url_filter: str | Pattern | None = None- record_video_dir: str | Path | None = None+ record_video_dir: str | Path | None = Field(default=None, validation_alias=AliasChoices('save_recording_path', 'record_video_dir'))record_video_size: ViewportSize | None = None@@ -452,7 +452,7 @@ class BrowserLaunchArgs(BaseModel):description='Directory to save downloads to.',validation_alias=AliasChoices('downloads_dir', 'save_downloads_path'),)- traces_dir: str | Path | None = Field(default=None, description='Directory to save HAR trace files to.')+ traces_dir: str | Path | None = Field(default=None, description='Directory for saving playwright trace.zip files (playwright actions, screenshots, DOM snapshots, HAR traces).', validation_alias=AliasChoices('trace_path', 'traces_dir'))handle_sighup: bool = Field(default=True, description='Whether playwright should swallow SIGHUP signals and kill the browser.')@@ -599,9 +599,10 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Broprofile_directory: str = 'Default' # e.g. 'Profile 1', 'Profile 2', 'Custom Profile', etc.- save_recording_path: str | None = Field(default=None, description='Directory for video recordings.')- save_har_path: str | None = Field(default=None, description='Directory for saving HAR files.')- trace_path: str | None = Field(default=None, description='Directory for saving trace files.')+ # these can be found in BrowserLaunchArgs, BrowserLaunchPersistentContextArgs, BrowserNewContextArgs, BrowserConnectArgs:+ # save_recording_path: alias of record_video_dir+ # save_har_path: alias of record_har_path+ # trace_path: alias of traces_dircookies_file: Path | None = Field(default=None, description='File to save cookies to. DEPRECATED, use `storage_state` instead.'@@ -712,7 +713,7 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Broreturn BrowserLaunchArgs(**self.model_dump(exclude={'args'}), args=self.get_args())def prepare_user_data_dir(self) -> None:- """Create and unlock the user data dir for first-run initialization."""+ """Create and unlock the user data dir and ensure all recording paths exist."""if self.user_data_dir:try:@@ -734,9 +735,49 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Brof'⚠️ Multiple chrome processes may be trying to share user_data_dir={self.user_data_dir} which can lead to crashes and profile data corruption!')- if self.downloads_path:- self.downloads_path = Path(self.downloads_path).expanduser().resolve()- self.downloads_path.mkdir(parents=True, exist_ok=True)+ # Ensure all recording and download paths exist+ paths_to_create = [+ ('downloads_path', self.downloads_path),+ ('record_video_dir', self.record_video_dir),+ ]++ for path_name, path_value in paths_to_create:+ if path_value:+ try:+ path_obj = Path(path_value).expanduser().resolve()+ path_obj.mkdir(parents=True, exist_ok=True)+ # Update the field with the resolved path+ setattr(self, path_name, path_obj)+ except Exception as e:+ logger.error(f'❌ Failed to create {path_name} directory {path_value}: {e}')++ # Handle traces_dir - ensure parent directory is writable+ if self.traces_dir:+ try:+ traces_path = Path(self.traces_dir).expanduser().resolve()+ traces_path.parent.mkdir(parents=True, exist_ok=True)+ # Test that parent directory is writable by touching a test file+ test_file = traces_path.parent / '.browseruse_test'+ test_file.touch()+ test_file.unlink()+ # Keep the original path (could be file or directory)+ setattr(self, 'traces_dir', str(traces_path))+ except Exception as e:+ logger.error(f'❌ Failed to create or access traces_dir {self.traces_dir}: {e}')++ # Ensure parent directories exist for file paths+ file_paths_to_create_parents = [+ ('record_har_path', self.record_har_path),+ ]++ for path_name, path_value in file_paths_to_create_parents:+ if path_value:+ try:+ path_obj = Path(path_value).expanduser().resolve()+ path_obj.parent.mkdir(parents=True, exist_ok=True)+ # logger.debug(f'📁 Created parent directory for {path_name}: {path_obj.parent}')+ except Exception as e:+ logger.error(f'❌ Failed to create parent directory for {path_name} {path_value}: {e}')# def preinstall_extensions(self) -> None:# """Preinstall the extensions."""diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 2eb2413b8..6fe8662f9 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -325,6 +325,7 @@ class BrowserSession(BaseModel):# resize the existing pages and set up foreground tab detectionawait self._setup_viewports()await self._setup_current_page_change_listeners()+ await self._start_context_tracing()except BaseException:self.initialized = Falseraise@@ -361,6 +362,30 @@ class BrowserSession(BaseModel):async def stop(self) -> None:"""Shuts down the BrowserSession, killing the browser process (only works if keep_alive=False)"""+ # cleanly stop any active HAR/gif/mp4/trace recording+ if self.browser_profile.traces_dir and self.browser_context:+ try:+ traces_path = Path(self.browser_profile.traces_dir)+ if traces_path.suffix:+ # Path has extension, use as-is (user specified exact file path)+ final_trace_path = traces_path+ else:+ # Path has no extension, treat as directory and create filename+ trace_filename = f'BrowserSession_{self.id}.zip'+ final_trace_path = traces_path / trace_filename++ self.logger.info(f'🎥 Saving browser context trace to {final_trace_path}...')+ async with asyncio.timeout(30):+ await self.browser_context.tracing.stop(path=str(final_trace_path))+ except Exception as e:+ self.logger.error(f'❌ Error saving browser context trace: {type(e).__name__}: {e}')+ if self.browser_profile.traces_dir and self.browser:+ try:+ async with asyncio.timeout(30):+ await self.browser.stop_tracing()+ except Exception as e:+ self.logger.error(f'❌ Error saving browser trace to {_log_pretty_path(self.browser_profile.traces_dir)}: {type(e).__name__}: {e}')+# 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# Use timeout to prevent indefinite waiting on lock acquisition@@ -382,10 +407,17 @@ class BrowserSession(BaseModel):if self.browser_context or self.browser:self.logger.info(f'🛑 Closing {self._connection_str} browser context {self.browser_context or self.browser}')++ # playwright saves these on browser.close() automatically+ if self.browser_profile.record_video_dir:+ self.logger.info(f'🎥 Saving video recording to record_video_dir= {self.browser_profile.record_video_dir}...')+ if self.browser_profile.record_har_path:+ self.logger.info(f'🎥 Saving HAR file to record_har_path= {self.browser_profile.record_har_path}...')+try:# Add timeout to prevent hanging on close if context is already closedtry:- async with asyncio.timeout(5): # 5 second timeout for close operation+ async with asyncio.timeout(30): # 5 second timeout for close operationawait (self.browser or self.browser_context.browser or self.browser_context).close()except TimeoutError:self.logger.warning('⏱️ Timeout while closing browser/context, has it become unresponsive?')@@ -534,14 +566,34 @@ class BrowserSession(BaseModel):except Exception as e:self.logger.warning(f'Error force-killing browser in BrowserSession.__del__: {type(e).__name__}: {e}')+ @staticmethod+ async def _start_global_playwright_subprocess(is_stealth: bool) -> Playwright | Patchright:+ """Create and return a new playwright or patchright node.js subprocess / API connector"""+ global GLOBAL_PLAYWRIGHT_API_OBJECT, GLOBAL_PATCHRIGHT_API_OBJECT+ global GLOBAL_PLAYWRIGHT_EVENT_LOOP, GLOBAL_PATCHRIGHT_EVENT_LOOP++ try:+ current_loop = asyncio.get_running_loop()+ except RuntimeError:+ current_loop = None++ if is_stealth:+ GLOBAL_PATCHRIGHT_API_OBJECT = await async_patchright().start()+ GLOBAL_PATCHRIGHT_EVENT_LOOP = current_loop+ return GLOBAL_PATCHRIGHT_API_OBJECT+ else:+ GLOBAL_PLAYWRIGHT_API_OBJECT = await async_playwright().start()+ GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loop+ return GLOBAL_PLAYWRIGHT_API_OBJECT+async def setup_playwright(self) -> None:"""Set up playwright library client object: usually the result of (await async_playwright().start())Override to customize the set up of the playwright or patchright library object"""- global GLOBAL_PLAYWRIGHT_API_OBJECT+ global GLOBAL_PLAYWRIGHT_API_OBJECT # one per thread, represents a node.js playwright subprocess that relays comamnds to the browser via CDPglobal GLOBAL_PATCHRIGHT_API_OBJECT- global GLOBAL_PLAYWRIGHT_EVENT_LOOP+ global GLOBAL_PLAYWRIGHT_EVENT_LOOP # one per thread, represents a node.js playwright subprocess that relays comamnds to the browser via CDPglobal GLOBAL_PATCHRIGHT_EVENT_LOOP# Get current event loop@@ -550,44 +602,46 @@ class BrowserSession(BaseModel):except RuntimeError:current_loop = None- if self.browser_profile.stealth:+ is_stealth = self.browser_profile.stealth++ # Configure browser channel based on stealth mode+ if is_stealth:# use patchright + chrome when stealth=Trueself.browser_profile.channel = self.browser_profile.channel or BrowserChannel.CHROMEself.logger.info(f'🕶️ Activated stealth mode using patchright {self.browser_profile.channel.name.lower()} browser...')- if not self.playwright:- # Check if the global object is still valid- should_recreate = False+ else:+ # use playwright + chromium by default+ self.browser_profile.channel = self.browser_profile.channel or BrowserChannel.CHROMIUM- # Check if we're in a different event loop than the one that created the global object- if GLOBAL_PATCHRIGHT_API_OBJECT and GLOBAL_PATCHRIGHT_EVENT_LOOP != current_loop:- self.logger.debug(- 'Detected event loop change. Previous patchright instance was created in a different event loop. '- 'Creating new instance to avoid asyncio conflicts.'- )- should_recreate = True- # Also check if the object exists but is no longer functional- if GLOBAL_PATCHRIGHT_API_OBJECT and not should_recreate:- try:- # Try to access the chromium property to verify the object is still valid- _ = GLOBAL_PATCHRIGHT_API_OBJECT.chromium- except Exception as e:- self.logger.debug(f'Detected invalid patchright instance: {type(e).__name__}. Creating new instance.')- should_recreate = True+ # Check if we're in a different event loop than the one that created the global object+ should_recreate = False+ driver_name = 'patchright' if is_stealth else 'playwright'+ global_api_object = GLOBAL_PATCHRIGHT_API_OBJECT if is_stealth else GLOBAL_PLAYWRIGHT_API_OBJECT+ global_event_loop = GLOBAL_PATCHRIGHT_EVENT_LOOP if is_stealth else GLOBAL_PLAYWRIGHT_EVENT_LOOP+ self.playwright = self.playwright or global_api_object or await self._start_global_playwright_subprocess(is_stealth=is_stealth)- if should_recreate:- # Reset the global object since we need a new one- GLOBAL_PATCHRIGHT_API_OBJECT = None- GLOBAL_PATCHRIGHT_EVENT_LOOP = None+ if (global_api_object and global_event_loop != current_loop):+ self.logger.debug(+ f'Detected event loop change. Previous {driver_name} instance was created in a different event loop. '+ 'Creating new instance to avoid disconnection when the previous loop closes.'+ )+ should_recreate = True- if GLOBAL_PATCHRIGHT_API_OBJECT:- self.playwright = GLOBAL_PATCHRIGHT_API_OBJECT- else:- GLOBAL_PATCHRIGHT_API_OBJECT = await async_patchright().start() # never start more than one per thread, never try to close it if any other code might be trying to use it, cannot be re-opened once closed- GLOBAL_PATCHRIGHT_EVENT_LOOP = current_loop- self.playwright = GLOBAL_PATCHRIGHT_API_OBJECT+ # Also check if the object exists but is no longer functional+ if global_api_object and not should_recreate:+ try:+ # Try to access the chromium property to verify the object is still valid+ _ = global_api_object.chromium.executable_path+ except Exception as e:+ self.logger.debug(f'Detected invalid {driver_name} instance: {type(e).__name__}. Creating new instance.')+ should_recreate = True++ if should_recreate:+ self.playwright = await self._start_global_playwright_subprocess(is_stealth=is_stealth)- # check for stealth best-practices+ # Log stealth best-practices warnings if applicable+ if is_stealth:if self.browser_profile.channel and self.browser_profile.channel != BrowserChannel.CHROME:self.logger.info(' 🪄 For maximum stealth, BrowserSession(...) should be passed channel=None or BrowserChannel.CHROME'@@ -596,68 +650,6 @@ class BrowserSession(BaseModel):self.logger.info(' 🪄 For maximum stealth, BrowserSession(...) should be passed a persistent user_data_dir=...')if self.browser_profile.headless or not self.browser_profile.no_viewport:self.logger.info(' 🪄 For maximum stealth, BrowserSession(...) should be passed headless=False & viewport=None')- else:- # use playwright + chromium by default- self.browser_profile.channel = self.browser_profile.channel or BrowserChannel.CHROMIUM- if not self.playwright:- # Check if the global object is still valid- should_recreate = False-- # Check if we're in a different event loop than the one that created the global object- if GLOBAL_PLAYWRIGHT_API_OBJECT and GLOBAL_PLAYWRIGHT_EVENT_LOOP != current_loop:- self.logger.debug(- 'Detected event loop change. Previous playwright instance was created in a different event loop. '- 'Creating new instance to avoid asyncio conflicts.'- )- should_recreate = True-- # Also check if the object exists but is no longer functional- if GLOBAL_PLAYWRIGHT_API_OBJECT and not should_recreate:- try:- # Try to access the chromium property to verify the object is still valid- _ = GLOBAL_PLAYWRIGHT_API_OBJECT.chromium- except Exception as e:- self.logger.debug(f'Detected invalid playwright instance: {type(e).__name__}. Creating new instance.')- should_recreate = True-- if should_recreate:- # Reset the global object since we need a new one- GLOBAL_PLAYWRIGHT_API_OBJECT = None- GLOBAL_PLAYWRIGHT_EVENT_LOOP = None-- if GLOBAL_PLAYWRIGHT_API_OBJECT:- self.playwright = GLOBAL_PLAYWRIGHT_API_OBJECT- else:- GLOBAL_PLAYWRIGHT_API_OBJECT = await async_playwright().start() # never start more than one per thread, never try to close it if any other code might be trying to use it, cannot be re-opened once closed- GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loop- self.playwright = GLOBAL_PLAYWRIGHT_API_OBJECT-- async def _recreate_playwright_instance(self) -> None:- """Force recreation of the playwright instance when it's detected to be invalid"""- global GLOBAL_PLAYWRIGHT_API_OBJECT- global GLOBAL_PATCHRIGHT_API_OBJECT- global GLOBAL_PLAYWRIGHT_EVENT_LOOP- global GLOBAL_PATCHRIGHT_EVENT_LOOP-- try:- current_loop = asyncio.get_running_loop()- except RuntimeError:- current_loop = None-- if self.browser_profile.stealth:- # Reset patchright- GLOBAL_PATCHRIGHT_API_OBJECT = None- GLOBAL_PATCHRIGHT_EVENT_LOOP = None- GLOBAL_PATCHRIGHT_API_OBJECT = await async_patchright().start()- GLOBAL_PATCHRIGHT_EVENT_LOOP = current_loop- self.playwright = GLOBAL_PATCHRIGHT_API_OBJECT- else:- # Reset playwright- GLOBAL_PLAYWRIGHT_API_OBJECT = None- GLOBAL_PLAYWRIGHT_EVENT_LOOP = None- GLOBAL_PLAYWRIGHT_API_OBJECT = await async_playwright().start()- GLOBAL_PLAYWRIGHT_EVENT_LOOP = current_loop- self.playwright = GLOBAL_PLAYWRIGHT_API_OBJECTasync def setup_browser_via_passed_objects(self) -> None:"""Override to customize the set up of the connection to an existing browser"""@@ -795,7 +787,7 @@ class BrowserSession(BaseModel):'Recreating playwright instance and retrying...')# Force recreation of the playwright object- await self._recreate_playwright_instance()+ self.playwright = await self._start_global_playwright_subprocess(is_stealth=self.browser_profile.stealth)# Retry the operation with the new playwright instanceasync with asyncio.timeout(10):self.browser = await self.playwright.chromium.launch(@@ -824,7 +816,7 @@ class BrowserSession(BaseModel):async with asyncio.timeout(10): # Reduced timeout from 30s to 10stry:self.browser_context = await self.playwright.chromium.launch_persistent_context(- **self.browser_profile.kwargs_for_launch_persistent_context().model_dump()+ **self.browser_profile.kwargs_for_launch_persistent_context().model_dump(mode='json'))except Exception as e:# Re-raise if not a timeout@@ -836,7 +828,7 @@ class BrowserSession(BaseModel):'Recreating playwright instance and retrying...')# Force recreation of the playwright object- await self._recreate_playwright_instance()+ self.playwright = await self._start_global_playwright_subprocess(is_stealth=self.browser_profile.stealth)# Retry the operation with the new playwright instanceasync with asyncio.timeout(10):self.browser_context = await self.playwright.chromium.launch_persistent_context(@@ -1460,7 +1452,9 @@ class BrowserSession(BaseModel):try:await page.wait_for_load_state()except Exception as e:- self.logger.warning(f'⚠️ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}')+ self.logger.warning(+ f'⚠️ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}'+ )await self._check_and_handle_navigation(page)else:# If downloads are disabled, just perform the click@@ -1468,7 +1462,9 @@ class BrowserSession(BaseModel):try:await page.wait_for_load_state()except Exception as e:- self.logger.warning(f'⚠️ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}')+ self.logger.warning(+ f'⚠️ Page {_log_pretty_url(page.url)} failed to finish loading after click: {type(e).__name__}: {e}'+ )await self._check_and_handle_navigation(page)try:@@ -2073,7 +2069,9 @@ class BrowserSession(BaseModel):try:await page.wait_for_load_state()except Exception as e:- self.logger.warning(f'⚠️ Page {_log_pretty_url(page.url)} failed to fully load after navigation: {type(e).__name__}: {e}')+ self.logger.warning(+ f'⚠️ Page {_log_pretty_url(page.url)} failed to fully load after navigation: {type(e).__name__}: {e}'+ )async def refresh_page(self):"""Refresh the agent's current page"""@@ -2419,6 +2417,41 @@ class BrowserSession(BaseModel):counter += 1return new_filename+ async def _start_context_tracing(self):+ """Start tracing on browser context if trace_path is configured."""+ if self.browser_profile.traces_dir:+ try:+ if self.browser_context:+ self.logger.debug(f'📽️ Starting tracing (will save to: {self.browser_profile.traces_dir})')+ # Don't pass any path to start() - let Playwright handle internal temp files+ await self.browser_context.tracing.start(+ screenshots=True,+ snapshots=True,+ sources=False # Reduce trace size+ )+ elif self.browser:+ # Fallback to browser.start_tracing() if context not available+ await self.browser.start_tracing()+ traces_path = Path(self.browser_profile.traces_dir)++ # Determine trace file path (same logic as in stop method)+ if str(traces_path).endswith('.zip'):+ # User wants exact zip file path+ if traces_path.exists() and traces_path.is_dir():+ self.logger.error(f'Cannot start trace: directory exists at zip path {traces_path}')+ return+ trace_file = traces_path+ else:+ # User wants directory (intuitive default)+ if traces_path.exists() and traces_path.is_file():+ self.logger.error(f'Cannot start trace: file exists at directory path {traces_path}')+ return+ trace_file = traces_path / f'BrowserSession_{self.id}.zip'++ self.logger.debug(f'📽️ Started tracing, will save to: {trace_file}')+ except Exception as e:+ self.logger.warning(f'Failed to start tracing: {e}')+@staticmethoddef _convert_simple_xpath_to_css_selector(xpath: str) -> str:"""Converts simple XPath expressions to CSS selectors."""@@ -2880,7 +2913,9 @@ class BrowserSession(BaseModel):try:await new_page.wait_for_load_state()except Exception as e:- self.logger.warning(f'⚠️ New page [{tab_idx}]{_log_pretty_url(new_page.url)} failed to fully load: {type(e).__name__}: {e}')+ self.logger.warning(+ f'⚠️ New page [{tab_idx}]{_log_pretty_url(new_page.url)} failed to fully load: {type(e).__name__}: {e}'+ )# Set the viewport size for the new tabif self.browser_profile.viewport:diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 254ee61fc..fe067a8ba 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -111,7 +111,16 @@ class Controller(Generic[Context]):except Exception as e:error_msg = str(e)# Check for network-related errors- if any(err in error_msg for err in ['ERR_NAME_NOT_RESOLVED', 'ERR_INTERNET_DISCONNECTED', 'ERR_CONNECTION_REFUSED', 'ERR_TIMED_OUT', 'net::']):+ if any(+ err in error_msg+ for err in [+ 'ERR_NAME_NOT_RESOLVED',+ 'ERR_INTERNET_DISCONNECTED',+ 'ERR_CONNECTION_REFUSED',+ 'ERR_TIMED_OUT',+ 'net::',+ ]+ ):site_unavailable_msg = f'Site unavailable: {params.url} - {error_msg}'logger.warning(site_unavailable_msg)return ActionResult(success=False, error=site_unavailable_msg, include_in_memory=True)