Skip to content

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

fix(filesystem): make PDF markdown restoration collision-safe

MagMuellerf168606cb97b
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.py
index 5864af92f..25d41cc35 100644
--- a/browser_use/filesystem/file_system.py
+++ b/browser_use/filesystem/file_system.py
@@ -104,23 +104,19 @@ def _markdown_inline_to_rml(text: str) -> str:
like ``**/foo/**`` stay literal.
"""
text = html.escape(text)
- # Stash code spans first — Markdown renders their contents literally.
- code_spans: list[str] = []
-
- def _stash_code(match: re.Match[str]) -> str:
- code_spans.append(match.group(1))
- return f'\x00C{len(code_spans) - 1}\x00'
-
- text = re.sub(r'`([^`]+)`', _stash_code, text)
- # Bold before italic so ``**`` is not treated as two italic markers.
- # Content cannot contain ``*`` — otherwise globs like ``*.txt and **/*.py`` pair across tokens.
- # Content cannot start with ``/`` — otherwise ``**/foo/**`` is treated as bold.
- text = re.sub(r'\*\*([^\s*/](?:[^*]*[^\s*])?)\*\*', r'<b>\1</b>', text)
- # Non-space boundaries keep ``2 * 3 * 4`` literal; leading ``* `` is a bullet, not italic
- text = re.sub(r'(?<!\*)\*([^\s*](?:[^*]*[^\s*])?)\*(?!\*)', r'<i>\1</i>', text)
- for i, span in enumerate(code_spans):
- text = text.replace(f'\x00C{i}\x00', f'<font face="Courier">{span}</font>')
- return text
+ rendered: list[str] = []
+ for part in re.split(r'(`[^`]+`)', text):
+ if part.startswith('`') and part.endswith('`'):
+ rendered.append(f'<font face="Courier">{part[1:-1]}</font>')
+ continue
+ # Bold before italic so ``**`` is not treated as two italic markers.
+ # Content cannot contain ``*`` — otherwise globs like ``*.txt and **/*.py`` pair across tokens.
+ # Content cannot start with ``/`` — otherwise ``**/foo/**`` is treated as bold.
+ part = re.sub(r'\*\*([^\s*/](?:[^*]*[^\s*])?)\*\*', r'<b>\1</b>', part)
+ # Non-space boundaries keep ``2 * 3 * 4`` literal; leading ``* `` is a bullet, not italic
+ part = re.sub(r'(?<!\*)\*([^\s*](?:[^*]*[^\s*])?)\*(?!\*)', r'<i>\1</i>', part)
+ rendered.append(part)
+ return ''.join(rendered)
DEFAULT_FILE_SYSTEM_PATH = 'browseruse_agent_data'
diff --git a/tests/ci/infrastructure/test_filesystem.py b/tests/ci/infrastructure/test_filesystem.py
index 0bf457482..7875715d5 100644
--- a/tests/ci/infrastructure/test_filesystem.py
+++ b/tests/ci/infrastructure/test_filesystem.py
@@ -31,6 +31,21 @@ def _extract_pdf_text(path: Path) -> tuple[str, list[str]]:
return ' '.join(text.split()), [line.strip() for line in text.splitlines() if line.strip()]
+def _extract_pdf_fonts(path: Path) -> set[str]:
+ """Return the PDF base fonts used to render non-empty text."""
+ fonts: set[str] = set()
+
+ def _record_font(text: str, _cm, _tm, font_dictionary, _font_size) -> None:
+ if text.strip() and font_dictionary is not None:
+ base_font = font_dictionary.get('/BaseFont')
+ if base_font is not None:
+ fonts.add(str(base_font))
+
+ for page in PdfReader(path).pages:
+ page.extract_text(visitor_text=_record_font)
+ return fonts
+
+
class TestBaseFile:
"""Test the BaseFile abstract base class and its implementations."""
@@ -64,6 +79,15 @@ class TestBaseFile:
assert _markdown_inline_to_rml('`*literal*`') == '<font face="Courier">*literal*</font>'
assert _markdown_inline_to_rml('`**bold**`') == '<font face="Courier">**bold**</font>'
+ def test_markdown_inline_code_token_cannot_replace_user_text(self):
+ """A user-provided placeholder-like sequence must survive code-span restoration."""
+ literal = '\x00C0\x00'
+ assert _markdown_inline_to_rml(f'Keep {literal} and `code`.') == (f'Keep {literal} and <font face="Courier">code</font>.')
+ prefix_literal = '\x00BROWSER_USE_INLINE_CODE_0\x00'
+ assert _markdown_inline_to_rml(f'Keep {prefix_literal} and `code`.') == (
+ f'Keep {prefix_literal} and <font face="Courier">code</font>.'
+ )
+
def test_txt_file_creation(self):
"""Test TxtFile creation and basic properties."""
txt_file = TxtFile(name='notes', content='Hello\nWorld')
@@ -300,7 +324,9 @@ class TestFileSystem:
)
result = await empty_filesystem.write_file('formatted.pdf', source)
assert result == 'Data written to file formatted.pdf successfully.'
- blob, lines = _extract_pdf_text(empty_filesystem.data_dir / 'formatted.pdf')
+ pdf_path = empty_filesystem.data_dir / 'formatted.pdf'
+ blob, lines = _extract_pdf_text(pdf_path)
+ fonts = _extract_pdf_fonts(pdf_path)
assert 'bold text' in blob
assert '**bold text**' not in blob
@@ -312,6 +338,7 @@ class TestFileSystem:
assert 'second bullet item' in blob
assert 'star bullet item' in blob
assert not any(line.startswith(('- ', '* ')) for line in lines)
+ assert {'/Helvetica-Bold', '/Helvetica-Oblique', '/Courier'} <= fonts
async def test_write_pdf_star_overload_is_not_emphasis(self, empty_filesystem):
"""Arithmetic and glob stars must not be treated as italic or bullets."""