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(filesystem): improve write_file filename handling and error messages
Magnus Müllera2fce46245c2
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.pyindex da1cb9478..25a8f939a 100644--- a/browser_use/filesystem/file_system.py+++ b/browser_use/filesystem/file_system.py@@ -11,6 +11,66 @@ from typing import Anyfrom pydantic import BaseModel, FieldINVALID_FILENAME_ERROR_MESSAGE = 'Error: Invalid filename format. Must be alphanumeric with supported extension.'++UNSUPPORTED_BINARY_EXTENSIONS = {+ 'png',+ 'jpg',+ 'jpeg',+ 'gif',+ 'bmp',+ 'svg',+ 'webp',+ 'ico',+ 'mp3',+ 'mp4',+ 'wav',+ 'avi',+ 'mov',+ 'zip',+ 'tar',+ 'gz',+ 'rar',+ 'exe',+ 'bin',+ 'dll',+ 'so',+}+++def _build_filename_error_message(file_name: str, supported_extensions: list[str]) -> str:+ """Build a specific error message explaining why the filename was rejected and how to fix it."""+ base = os.path.basename(file_name)++ # Check for binary/image extension+ if '.' in base:+ _, ext = base.rsplit('.', 1)+ ext_lower = ext.lower()+ if ext_lower in UNSUPPORTED_BINARY_EXTENSIONS:+ return (+ f"Error: Cannot write binary/image file '{base}'. "+ f"The write_file tool only supports text-based files. "+ f"Supported extensions: {', '.join('.' + e for e in supported_extensions)}. "+ f"For screenshots, the browser automatically captures them - do not try to save screenshots as files."+ )+ if ext_lower not in supported_extensions:+ return (+ f"Error: Unsupported file extension '.{ext_lower}' in '{base}'. "+ f"Supported extensions: {', '.join('.' + e for e in supported_extensions)}. "+ f"Please rename the file to use a supported extension."+ )++ # No extension or no dot+ if '.' not in base:+ return (+ f"Error: Filename '{base}' has no extension. "+ f"Please add a supported extension: {', '.join('.' + e for e in supported_extensions)}."+ )++ return (+ f"Error: Invalid filename '{base}'. "+ f"Filenames must contain only letters, numbers, underscores, hyphens, dots, parentheses, and spaces. "+ f"Supported extensions: {', '.join('.' + e for e in supported_extensions)}."+ )DEFAULT_FILE_SYSTEM_PATH = 'browseruse_agent_data'@@ -208,6 +268,22 @@ class DocxFile(BaseFile):await asyncio.get_event_loop().run_in_executor(executor, lambda: self.sync_to_disk_sync(path))+class HtmlFile(BaseFile):+ """HTML file implementation"""++ @property+ def extension(self) -> str:+ return 'html'+++class XmlFile(BaseFile):+ """XML file implementation"""++ @property+ def extension(self) -> str:+ return 'xml'++class FileSystemState(BaseModel):"""Serializable state of the file system"""@@ -239,6 +315,8 @@ class FileSystem:'csv': CsvFile,'pdf': PdfFile,'docx': DocxFile,+ 'html': HtmlFile,+ 'xml': XmlFile,}self.files = {}@@ -269,12 +347,48 @@ class FileSystem:file_obj.sync_to_disk_sync(self.data_dir)def _is_valid_filename(self, file_name: str) -> bool:- """Check if filename matches the required pattern: name.extension"""- # Build extensions pattern from _file_types+ """Check if filename matches the required pattern: name.extension++ Allows letters, numbers, underscores, hyphens, dots, parentheses, spaces, and Chinese characters+ in the name part, followed by a dot and a supported extension.+ """extensions = '|'.join(self._file_types.keys())- pattern = rf'^[a-zA-Z0-9_\-\u4e00-\u9fff]+\.({extensions})$'+ # Allow dots, spaces, parens in the name part - match everything up to the last dot+ pattern = rf'^[a-zA-Z0-9_\-\.\(\) \u4e00-\u9fff]+\.({extensions})$'file_name_base = os.path.basename(file_name)- return bool(re.match(pattern, file_name_base))+ if not re.match(pattern, file_name_base):+ return False+ # Ensure the name part (before last dot) is non-empty+ name_part = file_name_base.rsplit('.', 1)[0]+ return len(name_part.strip()) > 0++ @staticmethod+ def sanitize_filename(file_name: str) -> str:+ """Sanitize a filename by replacing/removing invalid characters.++ - Replaces spaces with hyphens+ - Removes characters that are not alphanumeric, underscore, hyphen, dot, parentheses, or Chinese+ - Preserves the extension+ - Collapses multiple consecutive hyphens+ """+ base = os.path.basename(file_name)+ if '.' not in base:+ return base++ name_part, ext = base.rsplit('.', 1)+ # Replace spaces with hyphens+ name_part = name_part.replace(' ', '-')+ # Remove invalid characters (keep alphanumeric, underscore, hyphen, dot, parens, Chinese)+ name_part = re.sub(r'[^a-zA-Z0-9_\-\.\(\)\u4e00-\u9fff]', '', name_part)+ # Collapse multiple hyphens+ name_part = re.sub(r'-{2,}', '-', name_part)+ # Strip leading/trailing hyphens and dots+ name_part = name_part.strip('-.')++ if not name_part:+ name_part = 'file'++ return f'{name_part}.{ext.lower()}'def _parse_filename(self, filename: str) -> tuple[str, str]:"""Parse filename into name and extension. Always check _is_valid_filename first."""@@ -419,7 +533,12 @@ class FileSystem:async def write_file(self, full_filename: str, content: str) -> str:"""Write content to file using file-specific write method"""if not self._is_valid_filename(full_filename):- return INVALID_FILENAME_ERROR_MESSAGE+ # Try sanitizing the filename before giving up+ sanitized = self.sanitize_filename(full_filename)+ if sanitized != os.path.basename(full_filename) and self._is_valid_filename(sanitized):+ full_filename = sanitized+ else:+ return _build_filename_error_message(full_filename, self.get_allowed_extensions())try:name_without_ext, extension = self._parse_filename(full_filename)@@ -445,7 +564,11 @@ class FileSystem:async def append_file(self, full_filename: str, content: str) -> str:"""Append content to file using file-specific append method"""if not self._is_valid_filename(full_filename):- return INVALID_FILENAME_ERROR_MESSAGE+ sanitized = self.sanitize_filename(full_filename)+ if sanitized != os.path.basename(full_filename) and self._is_valid_filename(sanitized):+ full_filename = sanitized+ else:+ return _build_filename_error_message(full_filename, self.get_allowed_extensions())file_obj = self.get_file(full_filename)if not file_obj:@@ -462,7 +585,11 @@ class FileSystem:async def replace_file_str(self, full_filename: str, old_str: str, new_str: str) -> str:"""Replace old_str with new_str in file_name"""if not self._is_valid_filename(full_filename):- return INVALID_FILENAME_ERROR_MESSAGE+ sanitized = self.sanitize_filename(full_filename)+ if sanitized != os.path.basename(full_filename) and self._is_valid_filename(sanitized):+ full_filename = sanitized+ else:+ return _build_filename_error_message(full_filename, self.get_allowed_extensions())if not old_str:return 'Error: Cannot replace empty string. Please provide a non-empty string to replace.'@@ -596,23 +723,23 @@ class FileSystem:file_info = file_data['data']# Create the appropriate file object based on type- if file_type == 'MarkdownFile':- file_obj = MarkdownFile(**file_info)- elif file_type == 'TxtFile':- file_obj = TxtFile(**file_info)- elif file_type == 'JsonFile':- file_obj = JsonFile(**file_info)- elif file_type == 'JsonlFile':- file_obj = JsonlFile(**file_info)- elif file_type == 'CsvFile':- file_obj = CsvFile(**file_info)- elif file_type == 'PdfFile':- file_obj = PdfFile(**file_info)- elif file_type == 'DocxFile':- file_obj = DocxFile(**file_info)- else:+ file_type_map: dict[str, type[BaseFile]] = {+ 'MarkdownFile': MarkdownFile,+ 'TxtFile': TxtFile,+ 'JsonFile': JsonFile,+ 'JsonlFile': JsonlFile,+ 'CsvFile': CsvFile,+ 'PdfFile': PdfFile,+ 'DocxFile': DocxFile,+ 'HtmlFile': HtmlFile,+ 'XmlFile': XmlFile,+ }++ file_class = file_type_map.get(file_type)+ if not file_class:# Skip unknown file typescontinue+ file_obj = file_class(**file_info)# Add to files dict and sync to diskfs.files[full_filename] = file_objdiff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex bcd2d9fbc..f18ef02ae 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -1021,7 +1021,11 @@ You will be given a query and the markdown of a webpage that has been filtered t# File System Actions@self.registry.action(- 'Write content to a file in the local file system. Use this to create new files or overwrite entire file contents. For targeted edits within existing files, use replace_file instead. Supports alphanumeric filename and file extension formats: .txt, .md, .json, .jsonl, .csv, .pdf. For PDF files, write content in markdown format and it will be automatically converted to a properly formatted PDF document.'+ 'Write content to a file. By default this OVERWRITES the entire file - use append=true to add to an existing file, or use replace_file for targeted edits within a file. '+ 'FILENAME RULES: Use only letters, numbers, underscores, hyphens, dots, parentheses. Spaces are auto-converted to hyphens. '+ 'SUPPORTED EXTENSIONS: .txt, .md, .json, .jsonl, .csv, .html, .xml, .pdf, .docx. '+ 'CANNOT write binary/image files (.png, .jpg, .mp4, etc.) - do not attempt to save screenshots as files. '+ 'For PDF files, write content in markdown format and it will be auto-converted to PDF.')async def write_file(file_name: str,diff --git a/tests/ci/infrastructure/test_filesystem.py b/tests/ci/infrastructure/test_filesystem.pyindex 1f42b098c..e6cd20104 100644--- a/tests/ci/infrastructure/test_filesystem.py+++ b/tests/ci/infrastructure/test_filesystem.py@@ -12,10 +12,12 @@ from browser_use.filesystem.file_system import (CsvFile,FileSystem,FileSystemState,+ HtmlFile,JsonFile,JsonlFile,MarkdownFile,TxtFile,+ XmlFile,)@@ -261,7 +263,7 @@ class TestFileSystem:"""Test filename validation."""fs = temp_filesystem- # Valid filenames+ # Valid filenames - basicassert fs._is_valid_filename('test.md') is Trueassert fs._is_valid_filename('my_file.txt') is Trueassert fs._is_valid_filename('file-name.md') is True@@ -271,16 +273,30 @@ class TestFileSystem:assert fs._is_valid_filename('users.csv') is Trueassert fs._is_valid_filename('WebVoyager_data.jsonl') is True # with underscores+ # Valid filenames - dots in name part+ assert fs._is_valid_filename('report.v2.md') is True # dots in name+ assert fs._is_valid_filename('file.backup.2024.csv') is True # multiple dots in name+ assert fs._is_valid_filename('useAppStore.json') is True # camelCase with dot-like extension++ # Valid filenames - spaces and parentheses+ assert fs._is_valid_filename('test with spaces.md') is True # spaces allowed+ assert fs._is_valid_filename('report (1).csv') is True # parentheses allowed+ assert fs._is_valid_filename('my file (copy).txt') is True # spaces and parens++ # Valid filenames - new extensions+ assert fs._is_valid_filename('page.html') is True+ assert fs._is_valid_filename('config.xml') is True+# Invalid filenamesassert fs._is_valid_filename('test.doc') is False # wrong extensionassert fs._is_valid_filename('test') is False # no extension- assert fs._is_valid_filename('test.md.txt') is False # multiple extensions- assert fs._is_valid_filename('test with spaces.md') is False # spaces- assert fs._is_valid_filename('[email protected]') is False # special chars+ assert fs._is_valid_filename('[email protected]') is False # special chars (@)assert fs._is_valid_filename('.md') is False # no nameassert fs._is_valid_filename('.json') is False # no nameassert fs._is_valid_filename('.jsonl') is False # no nameassert fs._is_valid_filename('.csv') is False # no name+ assert fs._is_valid_filename('screenshot.png') is False # binary extension+ assert fs._is_valid_filename('image.jpg') is False # binary extensiondef test_filename_parsing(self, temp_filesystem):"""Test filename parsing into name and extension."""@@ -373,13 +389,13 @@ class TestFileSystem:assert 'new_file.txt' in fs.filesassert fs.get_file('new_file.txt').content == 'New file content'- # Write with invalid filename+ # Write with special chars in filename - auto-sanitized to 'invalidname.md'result = await fs.write_file('[email protected]', 'content')- assert result == INVALID_FILENAME_ERROR_MESSAGE+ assert 'successfully' in result- # Write with invalid extension+ # Write with unsupported extension - gives specific errorresult = await fs.write_file('test.doc', 'content')- assert result == INVALID_FILENAME_ERROR_MESSAGE+ assert 'Unsupported file extension' in resultasync def test_write_json_file(self, temp_filesystem):"""Test writing JSON files."""@@ -450,9 +466,9 @@ class TestFileSystem:result = await fs.append_file('nonexistent.md', 'content')assert result == "File 'nonexistent.md' not found."- # Append with invalid filename+ # Append with special chars in filename - auto-sanitized but file doesn't existresult = await fs.append_file('[email protected]', 'content')- assert result == INVALID_FILENAME_ERROR_MESSAGE+ assert 'not found' in resultasync def test_append_json_file(self, temp_filesystem):"""Test appending content to JSON files."""@@ -887,9 +903,10 @@ class TestFileSystemEdgeCases:with tempfile.TemporaryDirectory() as tmp_dir:fs = FileSystem(base_dir=tmp_dir, create_default_files=False)- # Test with invalid extension+ # Test with invalid extension - now gives specific errorresult = await fs.write_file('test.invalid', 'content')- assert result == INVALID_FILENAME_ERROR_MESSAGE+ assert 'Unsupported file extension' in result+ assert '.invalid' in resultfs.nuke()@@ -917,6 +934,108 @@ class TestFileSystemEdgeCases:fs.nuke()+class TestFilenameSanitization:+ """Test filename sanitization and auto-fix behavior."""++ def test_sanitize_spaces_to_hyphens(self):+ """Test that spaces are converted to hyphens."""+ assert FileSystem.sanitize_filename('my file.md') == 'my-file.md'+ assert FileSystem.sanitize_filename('report final v2.csv') == 'report-final-v2.csv'++ def test_sanitize_special_chars_removed(self):+ """Test that unsupported special characters are removed."""+ assert FileSystem.sanitize_filename('[email protected]') == 'testfile.md'+ assert FileSystem.sanitize_filename('data#1.json') == 'data1.json'+ assert FileSystem.sanitize_filename('file!name$.txt') == 'filename.txt'++ def test_sanitize_preserves_valid_chars(self):+ """Test that valid characters are preserved."""+ assert FileSystem.sanitize_filename('my_file-v2.md') == 'my_file-v2.md'+ assert FileSystem.sanitize_filename('report(1).csv') == 'report(1).csv'+ assert FileSystem.sanitize_filename('data.backup.json') == 'data.backup.json'++ def test_sanitize_collapses_hyphens(self):+ """Test that multiple consecutive hyphens are collapsed."""+ assert FileSystem.sanitize_filename('my---file.md') == 'my-file.md'++ def test_sanitize_lowercases_extension(self):+ """Test that extensions are lowercased."""+ assert FileSystem.sanitize_filename('data.JSON') == 'data.json'+ assert FileSystem.sanitize_filename('file.MD') == 'file.md'++ def test_sanitize_fallback_name(self):+ """Test that empty names fall back to 'file'."""+ assert FileSystem.sanitize_filename('@#$.md') == 'file.md'++ async def test_write_file_auto_sanitizes(self):+ """Test that write_file auto-sanitizes invalid filenames when possible."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ # Filename with special chars should be auto-sanitized+ result = await fs.write_file('[email protected]', 'content')+ assert 'successfully' in result++ # Filename with spaces should be auto-sanitized+ result = await fs.write_file('my file.txt', 'content')+ assert 'successfully' in result++ fs.nuke()++ async def test_write_file_binary_extension_error(self):+ """Test that writing to binary extensions gives a clear error."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ result = await fs.write_file('screenshot.png', 'content')+ assert 'binary/image' in result.lower() or 'Cannot write' in result+ assert '.png' not in [f.split('.')[-1] for f in fs.list_files()]++ result = await fs.write_file('photo.jpg', 'content')+ assert 'binary/image' in result.lower() or 'Cannot write' in result++ fs.nuke()++ async def test_write_file_unsupported_extension_error(self):+ """Test that unsupported text extensions give a specific error."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ result = await fs.write_file('styles.css', 'body {}')+ assert 'Unsupported file extension' in result+ assert '.css' in result++ fs.nuke()++ async def test_write_html_file(self):+ """Test writing HTML files."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ result = await fs.write_file('page.html', '<html><body>Hello</body></html>')+ assert 'successfully' in result++ file_obj = fs.get_file('page.html')+ assert file_obj is not None+ assert isinstance(file_obj, HtmlFile)+ assert '<html>' in file_obj.content++ fs.nuke()++ async def test_write_file_with_dots_in_name(self):+ """Test writing files with dots in the name part."""+ with tempfile.TemporaryDirectory() as tmp_dir:+ fs = FileSystem(base_dir=tmp_dir, create_default_files=False)++ result = await fs.write_file('report.v2.md', '# Report v2')+ assert 'successfully' in result++ result = await fs.write_file('data.backup.2024.csv', 'a,b\n1,2')+ assert 'successfully' in result++ fs.nuke()++class TestFileSystemIntegration:"""Integration tests for FileSystem with real file operations."""