Skip to content

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

- file system is initialized based on agent id - available file paths are updated when something is downloaded

mertunsall53d277a2e366
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index ce4b3e8e9..222b989c3 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -9,7 +9,6 @@ import shutil
import sys
import tempfile
import time
-import uuid
from collections.abc import Awaitable, Callable
from pathlib import Path
from threading import Thread
@@ -453,6 +452,13 @@ class Agent(Generic[Context]):
if 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)}')
+
+ # Initialize download tracking
+ self.has_downloads_path = self.browser_session.browser_profile.downloads_path is not None
+ if self.has_downloads_path:
+ self._last_known_downloads: list[str] = []
+ self.logger.info('πŸ“ Initialized download tracking for agent')
+
self._external_pause_event = asyncio.Event()
self._external_pause_event.set()
@@ -481,15 +487,37 @@ class Agent(Generic[Context]):
assert self.browser_session is not None, 'BrowserSession is not set up'
return self.browser_session.browser_profile
+ def _update_available_file_paths(self, downloads: list[str]) -> None:
+ """Update available_file_paths with downloaded files."""
+ if not self.has_downloads_path:
+ return
+
+ current_files = set(self.settings.available_file_paths or [])
+ new_files = set(downloads) - current_files
+
+ if new_files:
+ self.settings.available_file_paths = list(current_files | new_files)
+ # Update message manager with new file paths
+ self._message_manager.settings.available_file_paths = self.settings.available_file_paths
+ self._message_manager.available_file_paths = self.settings.available_file_paths
+
+ self.logger.info(
+ f'πŸ“ Added {len(new_files)} downloaded files to available_file_paths (total: {len(self.settings.available_file_paths)} files)'
+ )
+ for file_path in new_files:
+ self.logger.info(f'πŸ“„ New file available: {file_path}')
+ else:
+ self.logger.info(f'πŸ“ No new downloads detected (tracking {len(current_files)} files)')
+
def _set_file_system(self, file_system_path: str | None = None) -> None:
# Initialize file system
if file_system_path:
self.file_system = FileSystem(file_system_path)
self.file_system_path = file_system_path
else:
- # create a temporary file system
+ # create a temporary file system using agent ID
base_tmp = tempfile.gettempdir() # e.g., /tmp on Unix
- self.file_system_path = os.path.join(base_tmp, str(uuid.uuid4()))
+ self.file_system_path = os.path.join(base_tmp, f'browser_use_agent_{self.id}')
self.file_system = FileSystem(self.file_system_path)
logger.info(f'πŸ’Ύ File system path: {self.file_system_path}')
@@ -1004,6 +1032,16 @@ class Agent(Generic[Context]):
self.state.last_result = result
self.state.last_model_output = model_output
+ # Check for new downloads after executing actions
+ if self.has_downloads_path:
+ try:
+ current_downloads = self.browser_session.downloaded_files
+ if current_downloads != self._last_known_downloads:
+ self._update_available_file_paths(current_downloads)
+ self._last_known_downloads = current_downloads
+ except Exception as e:
+ self.logger.debug(f'πŸ“ Failed to check for new downloads: {type(e).__name__}: {e}')
+
if len(result) > 0 and result[-1].is_done:
self.logger.info(f'πŸ“„ Result: {result[-1].extracted_content}')
if result[-1].attachments:
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 6d08d1e3f..7b0199415 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -212,6 +212,7 @@ class BrowserSession(BaseModel):
_start_lock: asyncio.Lock = PrivateAttr(default_factory=asyncio.Lock)
_tab_visibility_callback: Any = PrivateAttr(default=None)
_logger: logging.Logger | None = PrivateAttr(default=None)
+ _downloaded_files: list[str] = PrivateAttr(default_factory=list)
@model_validator(mode='after')
def apply_session_overrides_to_profile(self) -> Self:
@@ -1542,10 +1543,15 @@ class BrowserSession(BaseModel):
download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)
await download.save_as(download_path)
self.logger.info(f'⬇️ Downloaded file to: {download_path}')
+
+ # Track the downloaded file in the session
+ self._downloaded_files.append(download_path)
+ self.logger.info(f'πŸ“ Added download to session tracking (total: {len(self._downloaded_files)} files)')
+
return download_path
except Exception:
# If no download is triggered, treat as normal click
- # self.logger.debug('No download triggered within timeout. Checking navigation...')
+ self.logger.debug('No download triggered within timeout. Checking navigation...')
try:
await page.wait_for_load_state()
except Exception as e:
@@ -1870,6 +1876,17 @@ class BrowserSession(BaseModel):
"""
await self.load_storage_state(*args, **kwargs)
+ @property
+ def downloaded_files(self) -> list[str]:
+ """
+ Get list of all files downloaded during this browser session.
+
+ Returns:
+ list[str]: List of absolute file paths to downloaded files
+ """
+ self.logger.debug(f'πŸ“ Retrieved {len(self._downloaded_files)} downloaded files from session tracking')
+ return self._downloaded_files.copy()
+
# @property
# def browser_extension_pages(self) -> list[Page]:
# if not self.browser_context: