fix(telegram): preserve fence syntax across message chunks
This commit is contained in:
1 parent
b3fba7c78f
commit
3d25912510
2 files changed
+90
-38
No files matched your search
@@ -100,6 +100,22 @@ class _LivenessTrackedRequest(BaseRequest):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
_FENCE_OPEN_RE = re.compile(r'^[ \t]*(`{3,}|~{3,})(.*)$')
|
||||||
|
_INLINE_FENCE_RE = re.compile(r'```(?:[^\n]*\n)?([\s\S]*?)```')
|
||||||
|
|
||||||
|
|
||||||
|
def _opening_code_fence(line: str) -> str | None:
|
||||||
|
match = _FENCE_OPEN_RE.match(line)
|
||||||
|
if match and not (match.group(1)[0] == '`' and '`' in match.group(2)):
|
||||||
|
return match.group(1)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _closes_code_fence(line: str, fence: str) -> bool:
|
||||||
|
closing = line.strip()
|
||||||
|
return len(closing) >= len(fence) and closing == fence[0] * len(closing)
|
||||||
|
|
||||||
|
|
||||||
def _split_telegram_markdown(content: str, max_len: int) -> list[str]:
|
def _split_telegram_markdown(content: str, max_len: int) -> list[str]:
|
||||||
"""Split raw Telegram Markdown without leaving fenced code blocks unbalanced."""
|
"""Split raw Telegram Markdown without leaving fenced code blocks unbalanced."""
|
||||||
if not content:
|
if not content:
|
||||||
@@ -116,13 +132,33 @@ def _split_telegram_markdown(content: str, max_len: int) -> list[str]:
|
|||||||
return content[fence_pos:]
|
return content[fence_pos:]
|
||||||
return content[fence_pos:line_end]
|
return content[fence_pos:line_end]
|
||||||
|
|
||||||
def split_inside_fenced_code_block(pos: int) -> tuple[bool, int, str]:
|
def split_inside_fenced_code_block(pos: int) -> tuple[int, str, str] | None:
|
||||||
if content[:pos].count("```") % 2 == 0:
|
fence = None
|
||||||
return False, -1, ""
|
opening = -1
|
||||||
opening = content.rfind("```", 0, pos)
|
inline = False
|
||||||
if opening < 0:
|
offset = 0
|
||||||
return True, -1, "```"
|
for line in content[:pos].split("\n"):
|
||||||
return True, opening, fence_line(opening)
|
if fence is not None and not inline:
|
||||||
|
if _closes_code_fence(line, fence):
|
||||||
|
fence = None
|
||||||
|
else:
|
||||||
|
marker = _opening_code_fence(line) if fence is None else None
|
||||||
|
if marker is not None:
|
||||||
|
fence = marker
|
||||||
|
opening = offset
|
||||||
|
inline = False
|
||||||
|
else:
|
||||||
|
# Keep the legacy renderer's inline triple-backtick blocks.
|
||||||
|
for match in re.finditer("```", line):
|
||||||
|
if fence is None:
|
||||||
|
fence = "```"
|
||||||
|
opening = offset + match.start()
|
||||||
|
inline = True
|
||||||
|
else:
|
||||||
|
fence = None
|
||||||
|
inline = False
|
||||||
|
offset += len(line) + 1
|
||||||
|
return (opening, fence_line(opening), fence) if fence is not None else None
|
||||||
|
|
||||||
chunks: list[str] = []
|
chunks: list[str] = []
|
||||||
while content:
|
while content:
|
||||||
@@ -137,12 +173,13 @@ def _split_telegram_markdown(content: str, max_len: int) -> list[str]:
|
|||||||
if pos <= 0:
|
if pos <= 0:
|
||||||
pos = max_len
|
pos = max_len
|
||||||
|
|
||||||
inside_code, opening, fence = split_inside_fenced_code_block(pos)
|
active_fence = split_inside_fenced_code_block(pos)
|
||||||
if inside_code:
|
if active_fence is not None:
|
||||||
|
opening, fence, marker = active_fence
|
||||||
if opening > 0:
|
if opening > 0:
|
||||||
pos = opening
|
pos = opening
|
||||||
else:
|
else:
|
||||||
closing = "\n```"
|
closing = "\n" + marker
|
||||||
min_code_pos = len(fence)
|
min_code_pos = len(fence)
|
||||||
if content.startswith(fence + "\n"):
|
if content.startswith(fence + "\n"):
|
||||||
min_code_pos += 1
|
min_code_pos += 1
|
||||||
@@ -205,10 +242,6 @@ def _strip_md(s: str) -> str:
|
|||||||
return s.strip()
|
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:
|
def _replace_fenced_code(text: str, replace: Callable[[str], str]) -> str:
|
||||||
"""Replace fenced code blocks with ``replace(code)``.
|
"""Replace fenced code blocks with ``replace(code)``.
|
||||||
|
|
||||||
@@ -221,12 +254,10 @@ def _replace_fenced_code(text: str, replace: Callable[[str], str]) -> str:
|
|||||||
out: list[str] = []
|
out: list[str] = []
|
||||||
i = 0
|
i = 0
|
||||||
while i < len(lines):
|
while i < len(lines):
|
||||||
match = _FENCE_OPEN_RE.match(lines[i])
|
fence = _opening_code_fence(lines[i])
|
||||||
if match and not (match.group(1)[0] == '`' and '`' in match.group(2)):
|
if fence is not None:
|
||||||
fence = match.group(1)
|
|
||||||
for j in range(i + 1, len(lines)):
|
for j in range(i + 1, len(lines)):
|
||||||
closing = lines[j].strip()
|
if _closes_code_fence(lines[j], fence):
|
||||||
if len(closing) >= len(fence) and closing == fence[0] * len(closing):
|
|
||||||
out.append(replace(''.join(line + '\n' for line in lines[i + 1:j])))
|
out.append(replace(''.join(line + '\n' for line in lines[i + 1:j])))
|
||||||
i = j + 1
|
i = j + 1
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -207,26 +207,28 @@ def _assert_code_blocks_render_balanced(chunks: list[str]) -> None:
|
|||||||
assert html.count("<pre><code>") == html.count("</code></pre>")
|
assert html.count("<pre><code>") == html.count("</code></pre>")
|
||||||
|
|
||||||
|
|
||||||
def test_split_telegram_markdown_inside_code_block_moves_before_fence() -> None:
|
@pytest.mark.parametrize("prefix", ["Intro paragraph.\n", "Intro paragraph. "])
|
||||||
content = "Intro paragraph.\n```python\nprint('a')\nprint('b')\n```\nDone"
|
def test_split_telegram_markdown_inside_code_block_moves_before_fence(prefix) -> None:
|
||||||
|
content = prefix + "```python\nprint('a')\nprint('b')\n```\nDone"
|
||||||
|
|
||||||
chunks = _split_telegram_markdown(content, max_len=35)
|
chunks = _split_telegram_markdown(content, max_len=35)
|
||||||
|
|
||||||
assert chunks[0] == "Intro paragraph.\n"
|
assert chunks[0] == prefix
|
||||||
assert chunks[1].startswith("```python\nprint('a')")
|
assert chunks[1].startswith("```python\nprint('a')")
|
||||||
_assert_code_blocks_render_balanced(chunks)
|
_assert_code_blocks_render_balanced(chunks)
|
||||||
|
|
||||||
|
|
||||||
def test_split_telegram_markdown_long_code_block_closes_and_reopens() -> None:
|
@pytest.mark.parametrize("fence", ["```", "~~~", "````"])
|
||||||
content = "```python\n" + ("print('line one')\n" * 6) + "```\nDone"
|
def test_split_telegram_markdown_long_code_block_closes_and_reopens(fence) -> None:
|
||||||
|
content = f"{fence}python\n" + ("print('line one')\n" * 6) + f"{fence}\nDone"
|
||||||
|
|
||||||
chunks = _split_telegram_markdown(content, max_len=60)
|
chunks = _split_telegram_markdown(content, max_len=60)
|
||||||
|
|
||||||
assert len(chunks) > 1
|
assert len(chunks) > 1
|
||||||
assert all(len(chunk) <= 60 for chunk in chunks)
|
assert all(len(chunk) <= 60 for chunk in chunks)
|
||||||
assert chunks[0].startswith("```python\n")
|
assert chunks[0].startswith(f"{fence}python\n")
|
||||||
assert chunks[0].endswith("\n```")
|
assert chunks[0].endswith(f"\n{fence}")
|
||||||
assert chunks[1].startswith("```python\n")
|
assert chunks[1].startswith(f"{fence}python\n")
|
||||||
_assert_code_blocks_render_balanced(chunks)
|
_assert_code_blocks_render_balanced(chunks)
|
||||||
|
|
||||||
|
|
||||||
@@ -251,6 +253,20 @@ def test_split_telegram_markdown_multiple_code_blocks() -> None:
|
|||||||
_assert_code_blocks_render_balanced(chunks)
|
_assert_code_blocks_render_balanced(chunks)
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_telegram_markdown_keeps_nested_shorter_fence() -> None:
|
||||||
|
content = "````markdown\n```python\n" + "# raw example\n" * 40 + "```\n````"
|
||||||
|
|
||||||
|
chunks = _split_telegram_markdown(content, max_len=80)
|
||||||
|
|
||||||
|
assert len(chunks) > 1
|
||||||
|
assert all(len(chunk) <= 80 for chunk in chunks)
|
||||||
|
assert all(chunk.startswith("````markdown\n") and chunk.endswith("\n````") for chunk in chunks)
|
||||||
|
html = "".join(_markdown_to_telegram_html(chunk) for chunk in chunks)
|
||||||
|
assert html.count("# raw example") == 40
|
||||||
|
assert html.count("```") == 2
|
||||||
|
assert "<b>" not in html
|
||||||
|
|
||||||
|
|
||||||
def test_split_telegram_markdown_leading_whitespace_before_fence() -> None:
|
def test_split_telegram_markdown_leading_whitespace_before_fence() -> None:
|
||||||
content = "\n```python\n" + ("print('line one')\n" * 6) + "```\nDone"
|
content = "\n```python\n" + ("print('line one')\n" * 6) + "```\nDone"
|
||||||
|
|
||||||
@@ -262,25 +278,26 @@ def test_split_telegram_markdown_leading_whitespace_before_fence() -> None:
|
|||||||
_assert_code_blocks_render_balanced(chunks)
|
_assert_code_blocks_render_balanced(chunks)
|
||||||
|
|
||||||
|
|
||||||
def test_split_telegram_markdown_long_single_line_code_body() -> None:
|
@pytest.mark.parametrize("fence", ["```", "~~~", "````"])
|
||||||
|
def test_split_telegram_markdown_long_single_line_code_body(fence) -> None:
|
||||||
"""Long fence bodies with no interior newlines must still advance."""
|
"""Long fence bodies with no interior newlines must still advance."""
|
||||||
body = "a" * 4500
|
body = "a" * 4500
|
||||||
content = f"```\n{body}\n```"
|
content = f"{fence}\n{body}\n{fence}"
|
||||||
|
|
||||||
chunks = _split_telegram_markdown(content, TELEGRAM_MAX_MESSAGE_LEN)
|
chunks = _split_telegram_markdown(content, TELEGRAM_MAX_MESSAGE_LEN)
|
||||||
|
|
||||||
assert len(chunks) > 1
|
assert len(chunks) > 1
|
||||||
assert all(len(chunk) <= TELEGRAM_MAX_MESSAGE_LEN for chunk in chunks)
|
assert all(len(chunk) <= TELEGRAM_MAX_MESSAGE_LEN for chunk in chunks)
|
||||||
assert chunks[0].startswith("```\n")
|
assert chunks[0].startswith(f"{fence}\n")
|
||||||
assert chunks[0].endswith("\n```")
|
assert chunks[0].endswith(f"\n{fence}")
|
||||||
assert chunks[1].startswith("```\n")
|
assert chunks[1].startswith(f"{fence}\n")
|
||||||
reassembled = []
|
reassembled = []
|
||||||
for chunk in chunks:
|
for chunk in chunks:
|
||||||
part = chunk.split("\n", 1)[1]
|
part = chunk.split("\n", 1)[1]
|
||||||
if part.endswith("\n```"):
|
if part.endswith(f"\n{fence}"):
|
||||||
part = part[:-4]
|
part = part[:-(len(fence) + 1)]
|
||||||
elif part.endswith("```"):
|
elif part.endswith(fence):
|
||||||
part = part[:-3]
|
part = part[:-len(fence)]
|
||||||
reassembled.append(part)
|
reassembled.append(part)
|
||||||
assert "".join(reassembled) == body
|
assert "".join(reassembled) == body
|
||||||
_assert_code_blocks_render_balanced(chunks)
|
_assert_code_blocks_render_balanced(chunks)
|
||||||
@@ -1616,7 +1633,8 @@ async def test_send_delta_stream_end_html_expansion_does_not_overflow() -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_send_delta_stream_end_splits_long_code_block_before_html_rendering() -> None:
|
@pytest.mark.parametrize("fence", ["```", "~~~", "````"])
|
||||||
|
async def test_send_delta_stream_end_splits_long_code_block_before_html_rendering(fence) -> None:
|
||||||
"""Final streamed replies must not split Telegram HTML inside <pre><code>."""
|
"""Final streamed replies must not split Telegram HTML inside <pre><code>."""
|
||||||
channel = TelegramChannel(
|
channel = TelegramChannel(
|
||||||
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),
|
TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]),
|
||||||
@@ -1626,7 +1644,7 @@ async def test_send_delta_stream_end_splits_long_code_block_before_html_renderin
|
|||||||
channel._app.bot.edit_message_text = AsyncMock()
|
channel._app.bot.edit_message_text = AsyncMock()
|
||||||
channel._app.bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=99))
|
channel._app.bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=99))
|
||||||
|
|
||||||
raw_text = "```python\n" + ("print(\"line\")\n" * 450) + "```\nDone"
|
raw_text = f"{fence}python\n" + ("print(\"line\")\n" * 450) + f"{fence}\nDone"
|
||||||
channel._stream_bufs["123"] = _StreamBuf(text=raw_text, message_id=7, last_edit=0.0)
|
channel._stream_bufs["123"] = _StreamBuf(text=raw_text, message_id=7, last_edit=0.0)
|
||||||
|
|
||||||
await channel.send_delta("123", "", stream_end=True)
|
await channel.send_delta("123", "", stream_end=True)
|
||||||
@@ -1642,6 +1660,9 @@ async def test_send_delta_stream_end_splits_long_code_block_before_html_renderin
|
|||||||
for html in html_chunks:
|
for html in html_chunks:
|
||||||
assert len(html) <= 4096
|
assert len(html) <= 4096
|
||||||
assert html.count("<pre><code>") == html.count("</code></pre>")
|
assert html.count("<pre><code>") == html.count("</code></pre>")
|
||||||
|
if 'print("line")' in html:
|
||||||
|
assert html.startswith("<pre><code>")
|
||||||
|
assert "".join(html_chunks).count('print("line")') == 450
|
||||||
assert "123" not in channel._stream_bufs
|
assert "123" not in channel._stream_bufs
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user