Skip to content

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

filesystem: let write_file create tiny binary images (png/gif/jpg/webp) from base64

MagMueller257bcfd5f28b
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.py
index 25d41cc35..b1d23f5f8 100644
--- a/browser_use/filesystem/file_system.py
+++ b/browser_use/filesystem/file_system.py
@@ -14,13 +14,8 @@ from typing import Any
from pydantic import BaseModel, Field
UNSUPPORTED_BINARY_EXTENSIONS = {
- 'png',
- 'jpg',
- 'jpeg',
- 'gif',
'bmp',
'svg',
- 'webp',
'ico',
'mp3',
'mp4',
@@ -394,6 +389,73 @@ class XmlFile(BaseFile):
return 'xml'
+class Base64BinaryFile(BaseFile):
+ """Small binary file the agent authors as base64 text.
+
+ ``content`` holds the base64 string; the decoded bytes are written to disk so the
+ file is a real, uploadable image. ``read()`` returns a short stub instead of the
+ base64 so it never bloats or confuses the agent prompt (describe() calls read()
+ every step). Intended for tiny fixtures (e.g. a 1x1 PNG) for upload-validation
+ flows, not for arbitrary large binaries.
+ """
+
+ def _decoded(self) -> bytes:
+ # Strip all whitespace (the write_file action appends a trailing newline) then
+ # decode strictly so non-base64 text is rejected rather than silently corrupted.
+ return base64.b64decode(''.join(self.content.split()), validate=True)
+
+ def sync_to_disk_sync(self, path: Path) -> None:
+ (path / self.full_name).write_bytes(self._decoded())
+
+ async def sync_to_disk(self, path: Path) -> None:
+ with ThreadPoolExecutor() as executor:
+ await asyncio.get_event_loop().run_in_executor(executor, lambda: self.sync_to_disk_sync(path))
+
+ def read(self) -> str:
+ try:
+ n = len(self._decoded())
+ except Exception:
+ return '[binary file: content is not valid base64]'
+ return f'[binary {self.extension} file, {n} bytes]'
+
+ @property
+ def get_size(self) -> int:
+ try:
+ return len(self._decoded())
+ except Exception:
+ return 0
+
+
+class PngFile(Base64BinaryFile):
+ @property
+ def extension(self) -> str:
+ return 'png'
+
+
+class GifFile(Base64BinaryFile):
+ @property
+ def extension(self) -> str:
+ return 'gif'
+
+
+class JpgFile(Base64BinaryFile):
+ @property
+ def extension(self) -> str:
+ return 'jpg'
+
+
+class JpegFile(Base64BinaryFile):
+ @property
+ def extension(self) -> str:
+ return 'jpeg'
+
+
+class WebpFile(Base64BinaryFile):
+ @property
+ def extension(self) -> str:
+ return 'webp'
+
+
class FileSystemState(BaseModel):
"""Serializable state of the file system"""
@@ -427,6 +489,11 @@ class FileSystem:
'docx': DocxFile,
'html': HtmlFile,
'xml': XmlFile,
+ 'png': PngFile,
+ 'gif': GifFile,
+ 'jpg': JpgFile,
+ 'jpeg': JpegFile,
+ 'webp': WebpFile,
}
self.files = {}
@@ -576,7 +643,7 @@ class FileSystem:
return result
# Text-based extensions: derive from _file_types, excluding those with special readers
- _special_extensions = {'docx', 'pdf', 'jpg', 'jpeg', 'png'}
+ _special_extensions = {'docx', 'pdf', 'jpg', 'jpeg', 'png', 'gif', 'webp'}
text_extensions = [ext for ext in self._file_types if ext not in _special_extensions]
if extension in text_extensions:
@@ -711,7 +778,7 @@ class FileSystem:
)
return result
- elif extension in ['jpg', 'jpeg', 'png']:
+ elif extension in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
import anyio
# Read image file and convert to base64
@@ -980,6 +1047,11 @@ class FileSystem:
'DocxFile': DocxFile,
'HtmlFile': HtmlFile,
'XmlFile': XmlFile,
+ 'PngFile': PngFile,
+ 'GifFile': GifFile,
+ 'JpgFile': JpgFile,
+ 'JpegFile': JpegFile,
+ 'WebpFile': WebpFile,
}
file_class = file_type_map.get(file_type)
diff --git a/browser_use/tools/service.py b/browser_use/tools/service.py
index 9898c7ccf..e699b609f 100644
--- a/browser_use/tools/service.py
+++ b/browser_use/tools/service.py
@@ -1755,7 +1755,9 @@ You will be given a query and the markdown of a webpage that has been filtered t
'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 small images (.png, .gif, .jpg, .webp) — e.g. a tiny file to upload — set content to the '
+ 'base64 of a valid image (a 1x1 PNG is ~92 base64 chars); the bytes are decoded and written for you. '
+ 'CANNOT write other binary files (.mp4, .zip, etc.) and 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(
diff --git a/tests/ci/test_file_system_images.py b/tests/ci/test_file_system_images.py
index 8325853a6..88b9fb293 100644
--- a/tests/ci/test_file_system_images.py
+++ b/tests/ci/test_file_system_images.py
@@ -247,3 +247,44 @@ class TestActionResultImages:
if __name__ == '__main__':
pytest.main([__file__, '-v'])
+
+
+class TestBinaryFileCreation:
+ """The agent can author a tiny binary file (base64) that becomes a real, uploadable image."""
+
+ PNG_1X1 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII='
+
+ async def test_write_png_produces_real_bytes(self, tmp_path: Path):
+ fs = FileSystem(str(tmp_path))
+ # write_file action appends a trailing newline; that must be tolerated
+ result = await fs.write_file('logo.png', self.PNG_1X1 + '\n')
+ assert 'successfully' in result
+ raw = (fs.get_dir() / 'logo.png').read_bytes()
+ assert raw[:8] == b'\x89PNG\r\n\x1a\n' # real PNG magic, not base64 text
+ assert len(raw) > 0
+
+ async def test_binary_file_is_uploadable_by_basename(self, tmp_path: Path):
+ fs = FileSystem(str(tmp_path))
+ await fs.write_file('pic.gif', 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
+ fobj = fs.get_file('pic.gif') # the exact resolution upload_file uses
+ assert fobj is not None
+ assert fobj.full_name == 'pic.gif'
+
+ async def test_describe_does_not_leak_base64(self, tmp_path: Path):
+ fs = FileSystem(str(tmp_path))
+ await fs.write_file('logo.png', self.PNG_1X1)
+ desc = fs.describe()
+ assert self.PNG_1X1[:24] not in desc # base64 never enters the prompt
+ assert '[binary png file' in desc
+
+ async def test_invalid_base64_is_rejected_no_corrupt_file(self, tmp_path: Path):
+ fs = FileSystem(str(tmp_path))
+ result = await fs.write_file('bad.png', 'this is definitely not base64 @@@')
+ assert 'Error' in result
+ assert not (fs.get_dir() / 'bad.png').exists() # no 0-byte / corrupt file left for upload
+
+ async def test_state_round_trip_preserves_binary(self, tmp_path: Path):
+ fs = FileSystem(str(tmp_path))
+ await fs.write_file('logo.png', self.PNG_1X1)
+ fs2 = FileSystem.from_state(fs.get_state())
+ assert fs2.get_file('logo.png') is not None