fix(channels): keep code blocks rendering across Discord message splits (#8384)

* fix(channels): keep code blocks rendering across Discord message splits

DiscordChannel._split_text cut a long reply at the last line break within
2000 characters without looking at code fences. A block cut in two left
the first message with an unclosed fence and the second with bare code,
so neither rendered as code and the code was read as markdown.

Track the open fence while splitting. A message cut inside a block now
ends with a closing fence and the next one reopens it with the same
opening line, indent included, with room for both reserved in the 2000
characters. Fence parsing follows CommonMark: a shorter or different run
does not close a block, and a backtick info string cannot hold a
backtick. A block opening on a message's last line moves to the next
message, and a fence line too long to repeat is split as plain text.

* fix(channels): read Discord code blocks the way Discord renders them

The split tracked CommonMark fences, but Discord's client closes a block at
the next three backticks, also right after the last code on a line, has no
tilde fences and no nesting. A block closed inline was taken as still open,
so the prose after it was reopened as code in every later message.

The reply is now parsed once with Discord's code-block rule, since which run
closes a block can depend on text past the split. Inside a block the split
takes the latest line end or closing run where both the closed and the
reopened block keep code, and a cut inside a line no longer splits a
backtick run or an escape.

* fix(channels): keep a Discord block's opener whole and read CRLF line breaks

When no line break fits, the split falls back to a hard cut, and that cut
could land in a block's opening run or language tag, or before its first
code: the message ended with "```p" and the next one reopened the block
with "ython" as its first code line. A hard cut that leaves this message
no code of the block now ends the message before the opening run instead,
so the block moves to the next message whole.

Discord's parser turns CRLF and a lone CR into LF before it reads code
blocks, but the splitter required LF after the language tag, so a long
CRLF block reopened with a bare fence. The block patterns now accept
either line ending, the empty-block checks strip CR too, and a cut inside
a line no longer separates CR from LF.
This commit is contained in:
Hyeonsang Cho 2026-11-21 20:13:17 +09:00 committed by GitHub
parent 7810b807f2
commit 2c98fe40d4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 363 additions and 14 deletions

View File

@ -6,10 +6,11 @@ import asyncio
import io
import json
import logging
import re
import threading
from concurrent.futures import Future
from pathlib import Path
from typing import Any
from typing import Any, NamedTuple
from urllib.parse import urlsplit
import httpx
@ -35,6 +36,139 @@ logger = logging.getLogger(__name__)
_DISCORD_MAX_MESSAGE_LEN = 2000
# Discord's client does not follow CommonMark for code blocks. A block starts
# at a run of three backticks anywhere in a line, takes a language tag only when
# a line break follows it directly, and ends at the next three backticks, even
# right after the last code text. There are no tilde fences, and a longer run
# does not nest a shorter one. A backslash escapes a backtick outside a block.
# The pattern mirrors the client's code-block rule; a run with nothing but
# line breaks before the next run opens no block. The client's parser turns
# CRLF and a lone CR into LF first, so each counts as one line break here.
_CODE_FENCE = "```"
_LINE_BREAK = r"(?:\r\n?|\n)"
_CODE_BLOCK_RE = re.compile(rf"```(?:([a-z0-9_+\-.#]+?){_LINE_BREAK})?{_LINE_BREAK}*([^\r\n][\s\S]*?){_LINE_BREAK}*```", re.IGNORECASE)
_CODE_LANGUAGE_RE = re.compile(rf"([a-z0-9_+\-.#]+?){_LINE_BREAK}", re.IGNORECASE)
_FENCE_OR_ESCAPE_RE = re.compile(r"\\[^0-9A-Za-z\s]|```")
_CODE_FENCE_RE = re.compile(_CODE_FENCE)
# Appended to a message that ends inside a block; the client drops the line
# break before the closing run.
_CODE_FENCE_CLOSE_LEN = len("\n" + _CODE_FENCE)
class _CodeBlock(NamedTuple):
"""A code block of the reply as Discord renders the whole reply."""
start: int # index of the opening run
end: int | None # index after the closing run; None when the reply never closes it
opener: str # the opening run and its language tag, repeated to reopen the block
def _code_blocks(text: str) -> list[_CodeBlock]:
"""The code blocks of *text*, in order.
Parsed once over the whole reply: which run closes a block can depend on
text far past a split, so a single message cannot tell.
"""
blocks: list[_CodeBlock] = []
pos = 0
while (match := _FENCE_OR_ESCAPE_RE.search(text, pos)) is not None:
start = match.start()
if match.group() != _CODE_FENCE:
pos = match.end()
continue
if (block := _CODE_BLOCK_RE.match(text, start)) is not None:
blocks.append(_CodeBlock(start, block.end(), _CODE_FENCE + (block.group(1) or "")))
pos = block.end()
continue
if text.find(_CODE_FENCE, start + len(_CODE_FENCE)) < 0:
language = _CODE_LANGUAGE_RE.match(text, start + len(_CODE_FENCE))
blocks.append(_CodeBlock(start, None, _CODE_FENCE + (language.group(1) if language else "")))
break
# An empty block is plain text; a later run may still open one.
pos = start + 1
return blocks
def _block_at(blocks: list[_CodeBlock], index: int) -> _CodeBlock | None:
"""The block that a cut of the reply at *index* falls inside."""
for block in blocks:
if block.start >= index:
break
if block.end is None or index < block.end:
return block
return None
def _fence_is_carried(block: _CodeBlock | None) -> bool:
"""Whether a split closes *block* and reopens it in the next message.
The added lines must leave most of the next message for content; a longer
language tag is split like plain text.
"""
return block is not None and len(block.opener) + 1 + _CODE_FENCE_CLOSE_LEN <= _DISCORD_MAX_MESSAGE_LEN // 4
def _close_code_block(piece: str) -> str:
return piece + ("" if piece.endswith("\n") else "\n") + _CODE_FENCE
def _hard_split_point(text: str, start: int, budget: int) -> int:
"""Cut *text* *budget* characters after *start*, moved back so it splits no backtick run, escape or CRLF.
Any of these cuts would change which runs open and close code blocks.
"""
split_at = start + budget
while split_at > start and (text[split_at - 1] == "\\" or text[split_at - 1 : split_at + 1] in ("``", "\r\n")):
split_at -= 1
return split_at if split_at > start else start + budget
def _line_split_point(text: str, start: int, budget: int) -> int:
"""Where to end a message of *text* from *start* within *budget* characters, preferring a line break."""
split_at = text.rfind("\n", start, start + budget)
if split_at <= start:
return _hard_split_point(text, start, budget)
# Keep the delimiter on this chunk's tail so consecutive Discord messages
# reconstruct the original text exactly.
return split_at + 1
def _next_split(text: str, start: int, budget: int, blocks: list[_CodeBlock]) -> tuple[int, _CodeBlock | None]:
"""Where to end the message of *text* that starts at *start*, and the block open there.
*budget* is the room left after any reopened language tag.
"""
split_at = _line_split_point(text, start, budget)
block = _block_at(blocks, split_at)
if not _fence_is_carried(block):
return split_at, block
# The cut falls inside a block, which this message closes and the next one
# reopens. Take the latest line end or closing run where this message's
# block holds code after its language tag and the reopened one will too. A
# block opening on the message's last line, or a cut just before the block's
# own closing run, would leave one of them empty: Discord shows an empty
# block as plain backticks, or its language tag as the code.
end = start + budget
candidates = {index + 1 for index in range(start, end) if text[index] == "\n"}
candidates.update(run.end() for run in _CODE_FENCE_RE.finditer(text, start, end))
for candidate in sorted(candidates, reverse=True):
block = _block_at(blocks, candidate)
if not _fence_is_carried(block):
return candidate, block
holds_code = text[max(start, block.start + len(block.opener)) : candidate].strip("\r\n")
next_holds_code = block.end is None or text[candidate : block.end - len(_CODE_FENCE)].strip("\r\n")
if candidate <= end - _CODE_FENCE_CLOSE_LEN and holds_code and next_holds_code:
return candidate, block
# The block's first line in this message does not fit: cut into it.
split_at = _hard_split_point(text, start, budget - _CODE_FENCE_CLOSE_LEN)
block = _block_at(blocks, split_at)
if _fence_is_carried(block) and block.start > start and not text[block.start + len(block.opener) : split_at].strip("\r\n"):
# The cut lands in the block's opening run or language tag, or before its
# first code: end the message before the opening run instead.
return block.start, None
return split_at, block
# Bound for outbound work scheduled onto the Discord client's event loop.
# Discord API calls normally return in well under a second; anything still
# pending after this is a dead or wedged client, not a slow response.
@ -1320,23 +1454,33 @@ class DiscordChannel(Channel):
@staticmethod
def _split_text(text: str) -> list[str]:
"""Split *text* into messages within Discord's length limit.
Splits prefer line breaks. A code block that a split cuts is closed at
the end of the message and reopened with its language tag at the start
of the next, so both halves render as code. Apart from those added
fences, the messages join back to *text*.
"""
if not text:
return [""]
chunks: list[str] = []
remaining = text
while len(remaining) > _DISCORD_MAX_MESSAGE_LEN:
split_at = remaining.rfind("\n", 0, _DISCORD_MAX_MESSAGE_LEN)
if split_at <= 0:
split_at = _DISCORD_MAX_MESSAGE_LEN
blocks = _code_blocks(text)
start = 0
reopen = "" # the language tag line of a block carried into this message
while True:
budget = _DISCORD_MAX_MESSAGE_LEN - len(reopen)
if len(text) - start <= budget:
chunks.append(reopen + text[start:])
break
split_at, block = _next_split(text, start, budget, blocks)
chunk = reopen + text[start:split_at]
if _fence_is_carried(block):
chunks.append(_close_code_block(chunk))
reopen = f"{block.opener}\n"
else:
# Keep the delimiter on this chunk's tail so consecutive
# Discord messages reconstruct the original text exactly.
split_at += 1
chunks.append(remaining[:split_at])
remaining = remaining[split_at:]
if remaining:
chunks.append(remaining)
chunks.append(chunk)
reopen = ""
start = split_at
return chunks

View File

@ -203,6 +203,16 @@ the last card is clipped and marked `... (truncated)`. A retry of a partially
delivered answer resumes after the cards already sent, and a reply to any of the
cards continues the conversation.
Discord caps a message at 2,000 characters, so a longer answer is sent as
several messages, split at line breaks where possible. When a split falls inside
a code block, the message ends with closing backticks and the next one reopens
the block with its language tag, so both parts render as code. A block that
would start too close to the end of a message, before any of its code fits,
moves to the next message whole. Blocks are read the way Discord's client reads
them, not as CommonMark: a block runs from three backticks to the next three,
also when those follow the last code on its line, CRLF line endings count as
line breaks, and `~~~` fences are plain text.
For the special GitHub case (`fire_and_forget=True` channel policy), the manager calls `runs.create()` and returns once the run is `pending` — no outbound reply, because GitHub agents post via the `gh` CLI from inside their sandbox. See [GITHUB_AGENTS.md](GITHUB_AGENTS.md) for the full GitHub flow.
## Attachment delivery feedback

View File

@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import json
import logging
import re
import subprocess
import sys
import tempfile
@ -8078,6 +8079,13 @@ class TestDiscordChannel:
pytest.param("x" * 2000 + "\n" + "y" * 2000, id="newline-mid-message"),
pytest.param(("第一段\n\n" + "句" * 1990 + "\n\n最后一段") * 3, id="multibyte-paragraphs"),
pytest.param("x" * 4500, id="unbroken-run"),
pytest.param("```py\nprint(1)\n```\n" + "x" * 1990 + "\n" + "y" * 30, id="code-block-closed-before-split"),
pytest.param("use ```inline``` here " * 200, id="inline-backticks"),
pytest.param("```inline``` opens no block\n" * 150, id="code-block-closed-on-its-opening-line"),
pytest.param("```python\nprint(1)```\n\n" + "This is ordinary prose after the example.\n" * 100, id="code-block-closed-right-after-its-code"),
pytest.param("~~~js\n" + "let a = 1;\n" * 400 + "~~~", id="tildes-open-no-code-block"),
pytest.param("\\```py\n" + "not code\n" * 400, id="escaped-backticks-open-no-code-block"),
pytest.param("```" + "i" * 600 + "\n" + "code line\n" * 400 + "```", id="language-tag-too-long-to-carry"),
],
)
def test_split_text_preserves_content_within_discord_limit(self, text: str):
@ -8094,6 +8102,193 @@ class TestDiscordChannel:
assert DiscordChannel._split_text("") == [""]
assert DiscordChannel._split_text("hello\n\nworld") == ["hello\n\nworld"]
@pytest.mark.parametrize(
("text", "expected"),
[
pytest.param(
"intro\n```py\n" + "".join(f"line {i:02d} of code\n" for i in range(8)) + "```\nafter\n",
[
"intro\n```py\nline 00 of code\nline 01 of code\nline 02 of code\nline 03 of code\n```",
"```py\nline 04 of code\nline 05 of code\nline 06 of code\nline 07 of code\n```\nafter\n",
],
id="closed-and-reopened",
),
pytest.param(
"```py\n" + "".join(f"line {i:02d} of code\n" for i in range(6)) + "print(9)```\nafter\n",
[
"```py\nline 00 of code\nline 01 of code\nline 02 of code\nline 03 of code\n```",
"```py\nline 04 of code\nline 05 of code\nprint(9)```\nafter\n",
],
id="block-closing-right-after-its-last-code",
),
pytest.param(
"```py\nprint(1)```\n" + "".join(f"prose line {i:02d}\n" for i in range(8)),
[
"```py\nprint(1)```\n" + "".join(f"prose line {i:02d}\n" for i in range(4)),
"".join(f"prose line {i:02d}\n" for i in range(4, 8)),
],
id="prose-after-a-closed-block-stays-prose",
),
pytest.param(
"Run this: ```sh\n" + "echo step\n" * 12 + "```",
["Run this: ```sh\n" + "echo step\n" * 6 + "```", "```sh\n" + "echo step\n" * 6 + "```"],
id="block-opening-mid-line",
),
pytest.param(
"x" * 66 + "\n```py\n" + "code\n" * 3 + "```",
["x" * 66 + "\n", "```py\n" + "code\n" * 3 + "```"],
id="block-opening-on-the-last-line-moves-to-the-next-message",
),
pytest.param(
"```py\n" + "x" * 35 + "\n" + "x" * 34 + "\n```\nafter\n",
["```py\n" + "x" * 35 + "\n" + "x" * 34 + "\n```", "\nafter\n"],
id="closing-run-ending-at-the-limit-stays-in-the-message",
),
pytest.param(
"```py\n" + ("x" * 34 + "\n") * 2 + "\n\n```\nafter\n",
["```py\n" + "x" * 34 + "\n```", "```py\n" + "x" * 34 + "\n\n\n```\nafter\n"],
id="reopened-block-keeps-code-before-its-closing-run",
),
pytest.param(
"```\n" + "z" * 170 + "\n```",
["```\n" + "z" * 72 + "\n```", "```\n" + "z" * 72 + "\n```", "```\n" + "z" * 26 + "\n```"],
id="unbroken-code-line",
),
pytest.param(
"```py\n" + "line of code\n" * 10,
["```py\n" + "line of code\n" * 5 + "```", "```py\n" + "line of code\n" * 5],
id="unterminated-block-stays-unterminated",
),
pytest.param(
"w" * 70 + "```python\n" + "print(1)\n" * 8 + "```",
["w" * 70, "```python\n" + "print(1)\n" * 7 + "```", "```python\nprint(1)\n```"],
id="cut-in-the-language-tag-moves-the-block-to-the-next-message",
),
pytest.param(
"w" * 66 + "```python\n" + "print(1)\n" * 8 + "```",
["w" * 66, "```python\n" + "print(1)\n" * 7 + "```", "```python\nprint(1)\n```"],
id="cut-before-the-first-code-moves-the-block-to-the-next-message",
),
pytest.param(
"```py\r\n" + "line of code\r\n" * 8 + "```\r\nafter\r\n",
["```py\r\n" + "line of code\r\n" * 4 + "```", "```py\n" + "line of code\r\n" * 4 + "```\r\nafter\r\n"],
id="crlf-block-reopens-with-its-language-tag",
),
],
)
def test_split_text_closes_and_reopens_a_cut_code_block(self, monkeypatch, text: str, expected: list[str]):
"""A split inside a code block must leave both messages rendering it as code.
Without this the first message ends in an unclosed block and the second
starts with bare code, so neither renders a code block and the code is
read as markdown. Text after a closed block must stay prose.
"""
from app.channels import discord as discord_module
monkeypatch.setattr(discord_module, "_DISCORD_MAX_MESSAGE_LEN", 80)
chunks = discord_module.DiscordChannel._split_text(text)
assert chunks == expected
assert all(len(chunk) <= 80 for chunk in chunks)
@pytest.mark.parametrize(
("text", "expected"),
[
pytest.param("w" * 78 + "```code```", ["w" * 78, "```code```"], id="backtick-run"),
pytest.param("w" * 79 + "\\```code", ["w" * 79, "\\```code"], id="escape"),
pytest.param("w" * 79 + "\r\nmore", ["w" * 79, "\r\nmore"], id="crlf"),
],
)
def test_split_text_cut_inside_a_line_keeps_backtick_runs_escapes_and_crlf_whole(self, monkeypatch, text: str, expected: list[str]):
"""A cut through ```, a backslash escape or a CRLF would change which runs open a block."""
from app.channels import discord as discord_module
monkeypatch.setattr(discord_module, "_DISCORD_MAX_MESSAGE_LEN", 80)
assert discord_module.DiscordChannel._split_text(text) == expected
def test_split_text_keeps_a_long_code_block_rendering_at_discord_limit(self):
from app.channels.discord import _DISCORD_MAX_MESSAGE_LEN, DiscordChannel
code = "".join(f" result_{i} = compute_value({i}, factor=2)\n" for i in range(150))
text = "Here is the script:\n\n```python\n" + code + "```\n\nRun it with python."
chunks = DiscordChannel._split_text(text)
assert len(chunks) > 2
assert all(len(chunk) <= _DISCORD_MAX_MESSAGE_LEN for chunk in chunks)
# Every message closes the block it opens.
assert all(sum(line.startswith("```") for line in chunk.split("\n")) == 2 for chunk in chunks)
assert chunks[0].startswith("Here is the script:\n\n```python\n")
assert all(chunk.endswith("\n```") for chunk in chunks[:-1])
assert all(chunk.startswith("```python\n result_") for chunk in chunks[1:])
assert chunks[-1].endswith("```\n\nRun it with python.")
# Discord's client renders a code block from three backticks to the next
# three, with an optional language tag line; it is not CommonMark.
_DISCORD_CODE_BLOCK_RE = re.compile(r"```(?:([a-z0-9_+\-.#]+?)\n)?\n*([^\n][\s\S]*?)\n*```", re.IGNORECASE)
@classmethod
def _discord_render(cls, text: str) -> tuple[str, str, bool]:
"""(prose, code, ends inside a block) of *text* as the Discord client shows it, line breaks dropped."""
# The client's parser turns CRLF and a lone CR into LF before it parses.
text = re.sub(r"\r\n?", "\n", text)
prose, code, index = [], [], 0
while index < len(text):
if text[index] == "\\" and re.match(r"[^0-9A-Za-z\s]", text[index + 1 : index + 2]):
prose.append(text[index : index + 2])
index += 2
continue
if text.startswith("```", index):
if block := cls._DISCORD_CODE_BLOCK_RE.match(text, index):
code.append(block.group(2))
index = block.end()
continue
if "```" not in text[index + 3 :]:
tail = text[index + 3 :]
language = re.match(r"[a-z0-9_+\-.#]+?\n", tail, re.IGNORECASE)
code.append(tail[language.end() :] if language else tail)
return "".join(prose).replace("\n", ""), "".join(code).replace("\n", ""), True
prose.append(text[index])
index += 1
return "".join(prose).replace("\n", ""), "".join(code).replace("\n", ""), False
def test_split_text_with_code_blocks_keeps_prose_and_code_apart(self, monkeypatch):
"""Random replies mixing prose and code blocks render the same prose and code once split.
The expected rendering comes from Discord's code-block rule applied to
the whole reply, independently of the splitter's own parser.
"""
import random
from app.channels import discord as discord_module
limit = 120
monkeypatch.setattr(discord_module, "_DISCORD_MAX_MESSAGE_LEN", limit)
rng = random.Random(8086)
pieces = ["```", "```py\n", "```py\r\n", "x```", "\\```", "~~~\n", "````", "\n", "\n\n", "\r\n"]
for _ in range(300):
parts = []
for _ in range(rng.randint(1, 60)):
# Prose has spaces, so no prose run after backticks reads as a language tag.
parts.append(rng.choice(pieces) if rng.random() < 0.2 else "ww " * rng.randint(0, 20) + rng.choice(("\n", "\r\n")))
text = "".join(parts)
chunks = discord_module.DiscordChannel._split_text(text)
assert all(0 < len(chunk) <= limit for chunk in chunks), text
rendered = [self._discord_render(chunk) for chunk in chunks]
prose, code, ends_open = self._discord_render(text)
if not ends_open:
# Discord shows an unclosed block as plain text, so only a reply
# that closes its blocks has a rendering to keep: every message
# closes its blocks, and none moves text between prose and code.
assert not any(part[2] for part in rendered), text
assert "".join(part[0] for part in rendered) == prose, text
assert "".join(part[1] for part in rendered) == code, text
def test_stop_prevents_queued_typing_starter_from_creating_task(self):
from app.channels.discord import DiscordChannel