From 7f64efbb959da7c00dee9e40b9a8bdc17497648d Mon Sep 17 00:00:00 2001 From: Hui Date: Thu, 24 Sep 2026 17:40:12 -0400 Subject: [PATCH] fix(telegram): render tilde and longer code fences as code The Markdown-to-HTML converter only protected ``` blocks, and closed a block at the first ``` it met. A ~~~ block was formatted as prose ("# setup" turned bold, __init__ into init), and a ```` block showing a ``` example rendered as an empty
 followed by leaked, re-formatted
text.

Protect fenced blocks line by line first: open on ``` or ~~~, close on a
run of the same character at least as long. One-line ```code``` and
unclosed fences keep the previous regex handling. The streaming preview
strips fences through the same helper.

Co-Authored-By: Claude Opus 5.5 
---
 nanobot/channels/telegram/runtime.py          | 43 +++++++++++++++++--
 .../telegram/tests/test_telegram_channel.py   | 34 +++++++++++++++
 2 files changed, 73 insertions(+), 4 deletions(-)

diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.py
index e00593840..42ba780bb 100644
--- a/nanobot/channels/telegram/runtime.py
+++ b/nanobot/channels/telegram/runtime.py
@@ -205,6 +205,41 @@ def _strip_md(s: str) -> str:
     return s.strip()
 
 
+_FENCE_OPEN_RE = re.compile(r'^[ \t]*(`{3,}|~{3,})(.*)$')
+_INLINE_FENCE_RE = re.compile(r'```(?:[^\n]*\n)?([\s\S]*?)```')
+
+
+def _replace_fenced_code(text: str, replace: Callable[[str], str]) -> str:
+    """Replace fenced code blocks with ``replace(code)``.
+
+    A block opens on a ``` or ~~~ line and closes on a line holding only a run
+    of the same character that is at least as long, so tilde fences work and a
+    ```` fence can show a ``` example. What remains (one-line ```code``` and
+    unclosed fences) keeps the previous regex handling.
+    """
+    lines = text.split('\n')
+    out: list[str] = []
+    i = 0
+    while i < len(lines):
+        match = _FENCE_OPEN_RE.match(lines[i])
+        if match and not (match.group(1)[0] == '`' and '`' in match.group(2)):
+            fence = match.group(1)
+            for j in range(i + 1, len(lines)):
+                closing = lines[j].strip()
+                if len(closing) >= len(fence) and closing == fence[0] * len(closing):
+                    out.append(replace(''.join(line + '\n' for line in lines[i + 1:j])))
+                    i = j + 1
+                    break
+            else:
+                out.append(lines[i])
+                i += 1
+            continue
+        out.append(lines[i])
+        i += 1
+    text = '\n'.join(out)
+    return _INLINE_FENCE_RE.sub(lambda m: replace(m.group(1)), text)
+
+
 def _strip_md_block(text: str) -> str:
     """Strip block-level and inline markdown for readable plain-text preview.
 
@@ -212,7 +247,7 @@ def _strip_md_block(text: str) -> str:
     markdown syntax while the response is still being generated.
     """
     # Code blocks -> just the code
-    text = re.sub(r'```(?:[^\n]*\n)?([\s\S]*?)```', r'\1', text)
+    text = _replace_fenced_code(text, lambda code: code)
     # Headers -> plain text
     text = re.sub(r'^#{1,6}\s+(.+)$', r'\1', text, flags=re.MULTILINE)
     # Blockquotes
@@ -274,11 +309,11 @@ def _markdown_to_telegram_html(text: str) -> str:
 
     # 1. Extract and protect code blocks (preserve content from other processing)
     code_blocks: list[str] = []
-    def save_code_block(m: re.Match[str]) -> str:
-        code_blocks.append(m.group(1))
+    def save_code_block(code: str) -> str:
+        code_blocks.append(code)
         return f"\x00CB{len(code_blocks) - 1}\x00"
 
-    text = re.sub(r'```(?:[^\n]*\n)?([\s\S]*?)```', save_code_block, text)
+    text = _replace_fenced_code(text, save_code_block)
 
     # 1.5. Convert markdown tables to box-drawing (reuse code_block placeholders)
     lines = text.split('\n')
diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.py
index 680690451..423372274 100644
--- a/nanobot/channels/telegram/tests/test_telegram_channel.py
+++ b/nanobot/channels/telegram/tests/test_telegram_channel.py
@@ -2965,6 +2965,34 @@ def test_markdown_to_html_headers_become_bold() -> None:
     assert _markdown_to_telegram_html("### Deep") == "Deep"
 
 
+def test_markdown_to_html_tilde_fence_is_code() -> None:
+    from nanobot.channels.telegram.runtime import _markdown_to_telegram_html
+
+    text = "Run:\n~~~python\n# setup\ndef __init__(self): pass\n~~~\nDone"
+    assert _markdown_to_telegram_html(text) == (
+        "Run:\n
# setup\ndef __init__(self): pass\n
\nDone" + ) + + +def test_markdown_to_html_longer_fence_keeps_nested_example() -> None: + from nanobot.channels.telegram.runtime import _markdown_to_telegram_html + + text = "Example:\n````markdown\n```python\nx = a * b\n```\n**raw**\n````\nAfter **bold**" + assert _markdown_to_telegram_html(text) == ( + "Example:\n
```python\nx = a * b\n```\n**raw**\n
\n" + "After bold" + ) + + +def test_markdown_to_html_single_line_and_backtick_fences_unchanged() -> None: + from nanobot.channels.telegram.runtime import _markdown_to_telegram_html + + assert _markdown_to_telegram_html("```py\n# c\nx = __y__\n```") == ( + "
# c\nx = __y__\n
" + ) + assert _markdown_to_telegram_html("Use ```ls -la``` now") == "Use
ls -la
now" + + def test_markdown_to_html_numbered_lists_preserved() -> None: from nanobot.channels.telegram.runtime import _markdown_to_telegram_html @@ -3067,6 +3095,12 @@ def test_strip_md_block_converts_bullets_and_numbers() -> None: assert "2. item c" in result +def test_strip_md_block_strips_tilde_fences() -> None: + from nanobot.channels.telegram.runtime import _strip_md_block + + assert _strip_md_block("~~~bash\nls\n~~~\nDone") == "ls\n\nDone" + + def test_strip_md_block_strips_links() -> None: from nanobot.channels.telegram.runtime import _strip_md_block