Skip to content

The agent that grows with you

fix(telegram): anchor fenced-code regex so inline triple backticks aren't mangled

PRATHAMESH755f7b1e2d6582
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 019fd69d1a6..9469223299a 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -5717,19 +5717,39 @@ class TelegramAdapter(BasePlatformAdapter):
def _ph_wrap(open_: str, close: str):
return lambda m: _ph(f"{open_}{_escape_mdv2(m.group(1))}{close}")
- # 0) GFM pipe tables → Telegram-friendly row groups, before the MarkdownV2 conversions.
+ # 0) Rewrite GFM-style pipe tables into Telegram-friendly row groups
+ # before the normal MarkdownV2 conversions run.
text = _wrap_markdown_tables(content)
- # 1) Protect fenced code blocks; per MarkdownV2 spec \ and ` inside pre/code must be escaped.
+
+ # 1) Protect fenced code blocks (``` ... ```)
+ # Per MarkdownV2 spec, \ and ` inside pre/code must be escaped.
+ # The fence must open and close on its own line (0-3 spaces of
+ # indent allowed). Anchoring to line starts keeps *inline* triple
+ # backticks (e.g. "the syntax is ```x``` inline") from being
+ # swallowed and mangled into broken MarkdownV2 <pre> entities.
def _protect_fenced(m):
- raw = m.group(0)
- open_end = raw.index('\n') + 1 if '\n' in raw[3:] else 3 # opening ``` (+ optional language)
- body = raw[open_end:][:-3].replace('\\', '\\\\').replace('`', '\\`')
- return _ph(raw[:open_end] + body + '```')
-
- text = re.sub(r'(```(?:[^\n]*\n)?[\s\S]*?```)', _protect_fenced, text)
- # 2) Protect inline code; escape \ inside it per MarkdownV2 spec.
- text = re.sub(r'(`[^`]+`)', lambda m: _ph(m.group(0).replace('\\', '\\\\')), text)
- # 3) Links: escape display text; inside the URL only ')' and '\' need escaping.
+ opening = m.group(1) # opening fence line, incl. trailing newline
+ body = m.group(2) # code body (may be empty)
+ closing = m.group(3) # closing fence (with its indent)
+ body = body.replace('\\', '\\\\').replace('`', '\\`')
+ return _ph(opening + body + closing)
+
+ text = re.sub(
+ r'(?m)^([ ]{0,3}`{3}[^\n]*\n)([\s\S]*?)(^[ ]{0,3}`{3})[ \t]*$',
+ _protect_fenced,
+ text,
+ )
+
+ # 2) Protect inline code (`...`)
+ # Escape \ inside inline code per MarkdownV2 spec.
+ text = re.sub(
+ r'(`[^`]+`)',
+ lambda m: _ph(m.group(0).replace('\\', '\\\\')),
+ text,
+ )
+
+ # 3) Convert markdown links – escape the display text; inside the URL
+ # only ')' and '\' need escaping per the MarkdownV2 spec.
def _convert_link(m):
url = m.group(2).replace('\\', '\\\\').replace(')', '\\)')
return _ph(f'[{_escape_mdv2(m.group(1))}]({url})')
diff --git a/tests/gateway/test_telegram_format.py b/tests/gateway/test_telegram_format.py
index bb9593632f6..321adc24888 100644
--- a/tests/gateway/test_telegram_format.py
+++ b/tests/gateway/test_telegram_format.py
@@ -114,6 +114,42 @@ class TestFormatMessageCodeBlocks:
# \\ in input → \\\\ in output (each \ escaped once)
assert r"`\\\\server\\share`" in result
+ def test_inline_triple_backticks_not_treated_as_fence(self, adapter):
+ r"""Inline ``` spans must not be swallowed by the fenced-block regex.
+
+ Regression for the over-matching fence regex that turned a single-line
+ inline triple-backtick span into a mangled MarkdownV2 <pre> entity
+ (Telegram: "can't find end of pre entity"), forcing a plain-text
+ fallback that dropped all rich formatting.
+ """
+ text = "the syntax is ```like this``` inline"
+ result = adapter.format_message(text)
+ # Content is preserved, and the inline span is NOT emitted as a raw
+ # fenced block: no unescaped triple-backtick run survives to open an
+ # unbalanced <pre> entity (the literal backticks are escaped instead).
+ assert "like this" in result
+ assert "```" not in result
+
+ def test_fence_and_inline_backticks_mixed(self, adapter):
+ r"""A real fenced block still gets protected even when the same message
+ also contains inline triple backticks elsewhere."""
+ text = "```\nx = 1\n```\nand inline ```y``` after"
+ result = adapter.format_message(text)
+ # The standalone fenced block is protected verbatim...
+ assert "```\nx = 1\n```" in result
+ # ...and the trailing inline ```y``` does not spawn a second,
+ # unbalanced fence — only the real block's two fences remain.
+ assert result.count("```") == 2
+ assert "y" in result
+
+ def test_fence_with_trailing_whitespace_on_close(self, adapter):
+ r"""A closing fence with trailing spaces must not double up the ```."""
+ text = "```\ncode\n``` "
+ result = adapter.format_message(text)
+ # Exactly one closing fence, not "``````".
+ assert "``````" not in result
+ assert "code" in result
+
@pytest.mark.asyncio
async def test_final_send_does_not_retrigger_typing(adapter):