Skip to content

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

fix(filesystem): render markdown emphasis in PDF export

lei_lei25b88477a7c7
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.py
index 292636c83..f008eee19 100644
--- a/browser_use/filesystem/file_system.py
+++ b/browser_use/filesystem/file_system.py
@@ -74,6 +74,43 @@ def _build_filename_error_message(file_name: str, supported_extensions: list[str
)
+def _split_heading(line: str) -> tuple[str, int | None]:
+ """Split a markdown ATX heading into (text, level).
+
+ Only ``# `` / ``## `` / ``### `` (note the required space) are headings.
+ Anything else, including ``#hashtag``, is returned unchanged with level None.
+ """
+ if line.startswith('### '):
+ return line[4:], 3
+ if line.startswith('## '):
+ return line[3:], 2
+ if line.startswith('# '):
+ return line[2:], 1
+ return line, None
+
+
+_BULLET_RE = re.compile(r'^(\s*)[-*]\s+(.*)$')
+
+
+def _markdown_inline_to_rml(text: str) -> str:
+ """Escape plain text, then convert a markdown subset to ReportLab markup.
+
+ Order matters: after html.escape there are no user-supplied ``<`` left, so
+ injected ``<b>`` / ``<i>`` / ``<font>`` tags are unambiguous.
+
+ Underscore emphasis is intentionally unsupported so ``snake_case`` identifiers
+ survive unchanged.
+ """
+ text = html.escape(text)
+ # Bold before italic so ``**`` is not treated as two italic markers.
+ # Content cannot contain ``*`` — otherwise globs like ``*.txt and **/*.py`` pair across tokens.
+ 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)
+ text = re.sub(r'`([^`]+)`', r'<font face="Courier">\1</font>', text)
+ return text
+
+
DEFAULT_FILE_SYSTEM_PATH = 'browseruse_agent_data'
@@ -257,25 +294,36 @@ class PdfFile(BaseFile):
doc = SimpleDocTemplate(str(file_path), pagesize=letter)
styles = getSampleStyleSheet()
story = []
+ heading_styles = {1: styles['Title'], 2: styles['Heading1'], 3: styles['Heading2']}
- # Plain text plus markdown headers only, to avoid an AGPL markdown-to-PDF dependency
- content_lines = self.content.split('\n')
+ # Escape first, then markdown → RML. Avoids an AGPL markdown-to-PDF dependency.
+ in_fence = False
+ for line in self.content.split('\n'):
+ stripped = line.strip()
+ if stripped.startswith('```'):
+ in_fence = not in_fence
+ continue
- for line in content_lines:
- if line.strip():
- # Handle basic markdown headers
- if line.startswith('# '):
- text, style = line[2:], styles['Title']
- elif line.startswith('## '):
- text, style = line[3:], styles['Heading1']
- elif line.startswith('### '):
- text, style = line[4:], styles['Heading2']
- else:
- text, style = line, styles['Normal']
- # Paragraph parses its input as ReportLab markup, but our content is plain text
- story.append(Paragraph(html.escape(text), style))
- else:
+ if not stripped:
story.append(Spacer(1, 6))
+ continue
+
+ if in_fence:
+ # Fenced blocks are literal: no emphasis / inline-code conversion
+ story.append(Paragraph(html.escape(line), styles['Code']))
+ continue
+
+ text, heading_level = _split_heading(line)
+ if heading_level is not None:
+ story.append(Paragraph(_markdown_inline_to_rml(text), heading_styles[heading_level]))
+ continue
+
+ bullet = _BULLET_RE.match(line)
+ if bullet:
+ story.append(Paragraph(f'&bull; {_markdown_inline_to_rml(bullet.group(2))}', styles['Normal']))
+ continue
+
+ story.append(Paragraph(_markdown_inline_to_rml(line), styles['Normal']))
doc.build(story)
except Exception as e:
@@ -305,13 +353,9 @@ class DocxFile(BaseFile):
for line in content_lines:
if line.strip():
- # Handle basic markdown headers
- if line.startswith('# '):
- doc.add_heading(line[2:], level=1)
- elif line.startswith('## '):
- doc.add_heading(line[3:], level=2)
- elif line.startswith('### '):
- doc.add_heading(line[4:], level=3)
+ text, heading_level = _split_heading(line)
+ if heading_level is not None:
+ doc.add_heading(text, level=heading_level)
else:
doc.add_paragraph(line)
else:
diff --git a/tests/ci/infrastructure/test_filesystem.py b/tests/ci/infrastructure/test_filesystem.py
index 15bc60bed..f5cd81937 100644
--- a/tests/ci/infrastructure/test_filesystem.py
+++ b/tests/ci/infrastructure/test_filesystem.py
@@ -17,6 +17,7 @@ from browser_use.filesystem.file_system import (
JsonlFile,
MarkdownFile,
TxtFile,
+ _split_heading,
)
@@ -43,6 +44,15 @@ class TestBaseFile:
assert md_file.get_size == 13
assert md_file.get_line_count == 1
+ def test_split_heading_levels(self):
+ """PdfFile and DocxFile share one heading parser."""
+ assert _split_heading('# Title') == ('Title', 1)
+ assert _split_heading('## Section') == ('Section', 2)
+ assert _split_heading('### Notes') == ('Notes', 3)
+ assert _split_heading('#hashtag is not a header') == ('#hashtag is not a header', None)
+ assert _split_heading('plain') == ('plain', None)
+ assert _split_heading('#### too deep') == ('#### too deep', None)
+
def test_txt_file_creation(self):
"""Test TxtFile creation and basic properties."""
txt_file = TxtFile(name='notes', content='Hello\nWorld')
@@ -265,6 +275,73 @@ class TestFileSystem:
assert 'First & half' in blob
assert 'Second <b half > 2' in blob
+ async def test_write_pdf_renders_markdown_formatting(self, empty_filesystem):
+ """PDF export honors bold, italic, inline code, and bullets."""
+ source = '\n'.join(
+ [
+ 'This is **bold text** in a sentence.',
+ 'This is *italic text* in a sentence.',
+ 'Use `inline_code` here.',
+ '- first bullet item',
+ '- second bullet item',
+ '* star bullet item',
+ ]
+ )
+ 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')
+
+ assert 'bold text' in blob
+ assert '**bold text**' not in blob
+ assert 'italic text' in blob
+ assert '*italic text*' not in blob
+ assert 'inline_code' in blob
+ assert '`inline_code`' not in blob
+ assert 'first bullet item' in blob
+ assert 'second bullet item' in blob
+ assert 'star bullet item' in blob
+ assert not any(line.startswith(('- ', '* ')) for line in lines)
+
+ 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."""
+ source = '\n'.join(
+ [
+ 'Arithmetic 2 * 3 * 4 stays literal',
+ 'Glob pattern *.txt and **/*.py stay literal',
+ ]
+ )
+ result = await empty_filesystem.write_file('stars.pdf', source)
+ assert result == 'Data written to file stars.pdf successfully.'
+ blob, _ = _extract_pdf_text(empty_filesystem.data_dir / 'stars.pdf')
+ assert '2 * 3 * 4' in blob
+ assert '*.txt' in blob
+ assert '**/*.py' in blob
+
+ async def test_write_pdf_underscore_is_not_italic(self, empty_filesystem):
+ """Underscores are identifiers, not emphasis."""
+ source = 'Keep snake_case_names and file_name_here unchanged.'
+ result = await empty_filesystem.write_file('names.pdf', source)
+ assert result == 'Data written to file names.pdf successfully.'
+ blob, _ = _extract_pdf_text(empty_filesystem.data_dir / 'names.pdf')
+ assert 'snake_case_names' in blob
+ assert 'file_name_here' in blob
+
+ async def test_write_pdf_fenced_backticks_stay_literal(self, empty_filesystem):
+ """Inline code strips backticks; fenced shell snippets keep them."""
+ source = '\n'.join(
+ [
+ 'Run `$(cmd)` inline.',
+ '```',
+ 'echo `$(cmd)`',
+ '```',
+ ]
+ )
+ result = await empty_filesystem.write_file('backticks.pdf', source)
+ assert result == 'Data written to file backticks.pdf successfully.'
+ blob, _ = _extract_pdf_text(empty_filesystem.data_dir / 'backticks.pdf')
+ assert 'Run $(cmd) inline.' in blob
+ assert 'echo `$(cmd)`' in blob
+
def test_filesystem_initialization(self, temp_filesystem):
"""Test FileSystem initialization with default files."""
fs = temp_filesystem