fix(telegram): keep Markdown headings/lists as blocks and strip Markdown on plain fallback

- insert blank lines around ATX headings and list blocks so Telegram does not
  collapse them into the surrounding paragraph
- leave the SDK's compact triple-backtick tool fences unstyled (do not re-space)
- strip Markdown syntax when the rich send/edit falls back to plain, so the
  user never sees raw '#', '**', backticks or link brackets
- log telegramRenderVersion + mode on every outgoing message
This commit is contained in:
sam committed 2026-08-27 23:33:24 +00:00
1 parent 365297a4cb
commit ab8583e1f9
3 files changed
+221 -7

No files matched your search

+4 -4
View File
@@ -702,7 +702,7 @@ func (l *liveReply) finalText(reply string) string {
func (l *liveReply) open(ctx context.Context, body string) {
params := &bot.SendRichMessageParams{
ChatID: l.chatID,
RichMessage: models.InputRichMessage{Markdown: body},
RichMessage: models.InputRichMessage{Markdown: telegramMarkdown(body)},
}
if l.messageThreadID != 0 {
params.MessageThreadID = l.messageThreadID
@@ -710,7 +710,7 @@ func (l *liveReply) open(ctx context.Context, body string) {
msg, err := l.b.SendRichMessage(ctx, params)
if err != nil {
l.g.log.Debug("live reply rich send failed, retrying unformatted", "error", err)
plain := &bot.SendMessageParams{ChatID: l.chatID, Text: body}
plain := &bot.SendMessageParams{ChatID: l.chatID, Text: telegramPlainText(body)}
if l.messageThreadID != 0 {
plain.MessageThreadID = l.messageThreadID
}
@@ -737,7 +737,7 @@ func (l *liveReply) edit(ctx context.Context, messageID int, body string) error
_, richErr := l.b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: l.chatID,
MessageID: messageID,
RichMessage: &models.InputRichMessage{Markdown: body},
RichMessage: &models.InputRichMessage{Markdown: telegramMarkdown(body)},
})
if richErr == nil {
return nil
@@ -747,7 +747,7 @@ func (l *liveReply) edit(ctx context.Context, messageID int, body string) error
if _, plainErr := l.b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: l.chatID,
MessageID: messageID,
Text: body,
Text: telegramPlainText(body),
}); plainErr != nil {
l.g.log.Debug("live reply edit failed", "error", plainErr)
return errors.Join(
+136 -3
View File
@@ -900,6 +900,136 @@ func markdownCodeDelimiterAt(text string, position int) (string, bool) {
return delimiter, delimiter != ""
}
// telegramRenderVersion identifies the renderer applied to outgoing Telegram
// messages. It is included in the per-send log line so an old deployment
// cannot be mistaken for the current code when diagnosing rendering
// differences.
const telegramRenderVersion = "rich-markdown-v2"
var (
// atxHeadingLine matches an ATX heading (one to six # then whitespace or EOL).
atxHeadingLine = regexp.MustCompile(`^#{1,6}(?:[ ]|$)`)
// listItemLine matches a Markdown unordered or ordered list item.
listItemLine = regexp.MustCompile(`^[ ]*(?:[-*+]|[0-9]+[.)])[ ]+`)
// inlineLink matches [label](url).
inlineLink = regexp.MustCompile(`\[([^\]]*)\]\(([^)]+)\)`)
// Emphasis/code delimiters stripped by telegramPlainText, longest first.
strikeMarkdown = regexp.MustCompile(`~~(.+?)~~`)
boldMarkdown = regexp.MustCompile(`\*\*(.+?)\*\*`)
underlineMarkdown = regexp.MustCompile(`__(.+?)__`)
italicMarkdown = regexp.MustCompile(`\*(.+?)\*`)
italicUnderscore = regexp.MustCompile(`_(.+?)_`)
inlineCodeMarkdown = regexp.MustCompile("`([^`]*)`")
)
// renderTelegramMarkdown prepares text for Telegram's rich Markdown renderer:
// it preserves bare-URL paragraph boundaries and inserts blank lines around
// block-level constructs (headings, lists, fenced code) that Telegram's
// Markdown semantics would otherwise collapse into the surrounding paragraph.
func renderTelegramMarkdown(text string) string {
return telegramMarkdown(normalizeTelegramText(text))
}
// renderTelegramPlain prepares readable plain text for the fallback send that
// runs when a server rejects the rich message: it strips Markdown syntax so the
// user does not see raw "#", "**", backticks or link brackets.
func renderTelegramPlain(text string) string {
return telegramPlainText(normalizeTelegramText(text))
}
// telegramMarkdown inserts a blank line before and after block-level Markdown
// constructs that Telegram's renderer would otherwise collapse into the
// surrounding paragraph. It is idempotent. Fenced code blocks are deliberately
// left untouched: the SDK's tool block already emits compact triple-backtick
// fences on their own lines, and adding blank lines around them would break that
// layout without fixing any reported collapse.
func telegramMarkdown(text string) string {
if text == "" {
return text
}
lines := strings.Split(text, "\n")
out := make([]string, 0, len(lines)*2)
var prev string
for i := 0; i < len(lines); i++ {
line := lines[i]
trimmed := strings.TrimSpace(line)
if atxHeadingLine.MatchString(trimmed) {
if prev != "" {
out = append(out, "")
}
out = append(out, line)
prev = line
if i+1 < len(lines) {
next := strings.TrimSpace(lines[i+1])
if next != "" && !atxHeadingLine.MatchString(next) && !listItemLine.MatchString(next) {
out = append(out, "")
prev = ""
}
}
continue
}
if listItemLine.MatchString(trimmed) {
if prev != "" {
out = append(out, "")
}
j := i
for j < len(lines) && listItemLine.MatchString(strings.TrimSpace(lines[j])) {
out = append(out, lines[j])
prev = lines[j]
j++
}
if j < len(lines) && strings.TrimSpace(lines[j]) != "" {
out = append(out, "")
prev = ""
}
i = j - 1
continue
}
out = append(out, line)
prev = line
}
return strings.Join(out, "\n")
}
// telegramPlainText converts Markdown into readable plain text for the
// unformatted fallback: fenced code blocks keep their content (the fence lines
// are dropped), ATX heading markers are removed, links become "label (url)",
// and emphasis/code delimiters are stripped while their text is kept.
func telegramPlainText(text string) string {
if text == "" {
return text
}
lines := strings.Split(text, "\n")
out := make([]string, 0, len(lines))
inFence := false
for _, line := range lines {
if strings.HasPrefix(strings.TrimSpace(line), "```") {
inFence = !inFence
continue
}
if inFence {
out = append(out, line)
continue
}
out = append(out, plainLine(line))
}
return strings.Join(out, "\n")
}
// plainLine strips one non-fence line's Markdown syntax.
func plainLine(line string) string {
text := atxHeadingLine.ReplaceAllString(line, "")
text = inlineLink.ReplaceAllString(text, "$1 ($2)")
text = strikeMarkdown.ReplaceAllString(text, "$1")
text = boldMarkdown.ReplaceAllString(text, "$1")
text = underlineMarkdown.ReplaceAllString(text, "$1")
text = italicMarkdown.ReplaceAllString(text, "$1")
text = italicUnderscore.ReplaceAllString(text, "$1")
text = inlineCodeMarkdown.ReplaceAllString(text, "$1")
return text
}
func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) {
text = normalizeTelegramText(text)
if utf8.RuneCountInString(text) <= messageMaxLen {
@@ -928,26 +1058,29 @@ func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, mes
// treated as "unsupported" rather than fatal: fall back to a plain send so
// the user still receives the reply, unformatted, instead of silence.
func (g *Gateway) send(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text, errMsg string) {
text = normalizeTelegramText(text)
normalized := normalizeTelegramText(text)
rich := &bot.SendRichMessageParams{
ChatID: chatID,
RichMessage: models.InputRichMessage{Markdown: text},
RichMessage: models.InputRichMessage{Markdown: telegramMarkdown(normalized)},
}
if messageThreadID != 0 {
rich.MessageThreadID = messageThreadID
}
if _, err := b.SendRichMessage(ctx, rich); err == nil {
g.log.Debug("telegram message sent", "renderer", telegramRenderVersion, "mode", "rich")
return
} else {
g.log.Warn("rich send failed, retrying unformatted", "error", err)
}
plain := &bot.SendMessageParams{ChatID: chatID, Text: text}
plain := &bot.SendMessageParams{ChatID: chatID, Text: telegramPlainText(normalized)}
if messageThreadID != 0 {
plain.MessageThreadID = messageThreadID
}
if _, err := b.SendMessage(ctx, plain); err != nil {
g.log.Error(errMsg, "error", err)
} else {
g.log.Warn("telegram message sent via plain fallback", "renderer", telegramRenderVersion, "mode", "plain")
}
}
@@ -915,3 +915,84 @@ func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) {
t.Error("launch() started long polling without dropping pending updates")
}
}
func TestRenderTelegramMarkdownBlocksHeadings(t *testing.T) {
// The exact report: a heading immediately after prose, no blank line,
// collapses into one paragraph under Telegram's Markdown semantics.
input := "rely on checkbox text alone.\n### Add a \"dangerous configuration\" review guard"
out := renderTelegramMarkdown(input)
if strings.Contains(out, "alone.\n### ") {
t.Fatalf("heading not separated from prose:\n%s", out)
}
if !strings.Contains(out, "alone.\n\n### Add a \"dangerous configuration\" review guard") {
t.Fatalf("expected a blank line before the heading, got:\n%s", out)
}
}
func TestRenderTelegramMarkdownBlocksLists(t *testing.T) {
input := "text\n- one\n- two\nmore"
out := renderTelegramMarkdown(input)
if !strings.Contains(out, "text\n\n- one\n- two\n\nmore") {
t.Fatalf("list block not separated, got:\n%s", out)
}
ordered := "intro\n1. first\n2. second\nafter"
outOrdered := renderTelegramMarkdown(ordered)
if !strings.Contains(outOrdered, "intro\n\n1. first\n2. second\n\nafter") {
t.Fatalf("ordered list block not separated, got:\n%s", outOrdered)
}
}
func TestRenderTelegramMarkdownLeavesFencesCompact(t *testing.T) {
// The SDK's tool block emits ````` text ```` fences tight against the tool
// line; those must not be re-spaced (that is what keeps a noisy tool turn
// compact). Only headings and lists get explicit block boundaries.
input := "🔧 shell — done\n```text\nexit 0\n```\ndone"
out := renderTelegramMarkdown(input)
if !strings.Contains(out, "done\n```text\nexit 0\n```\ndone") {
t.Fatalf("fence re-spaced; tool block must stay compact, got:\n%s", out)
}
}
func TestRenderTelegramMarkdownIsIdempotent(t *testing.T) {
input := "text\n### heading\n- item\n```\ncode\n```\nmore"
once := renderTelegramMarkdown(input)
twice := renderTelegramMarkdown(once)
if once != twice {
t.Fatalf("renderer is not idempotent:\nonce:\n%s\n\ntwice:\n%s", once, twice)
}
}
func TestRenderTelegramPlainStripsMarkdown(t *testing.T) {
input := "## Heading\n**bold** and *italic* and `code` and [a link](https://example.com)"
out := renderTelegramPlain(input)
if strings.Contains(out, "##") || strings.Contains(out, "**") ||
strings.Contains(out, "`") || strings.Contains(out, "](https://example.com)") {
t.Fatalf("plain fallback left raw Markdown artifacts:\n%s", out)
}
if !strings.Contains(out, "Heading") || !strings.Contains(out, "bold") ||
!strings.Contains(out, "italic") || !strings.Contains(out, "code") ||
!strings.Contains(out, "a link (https://example.com)") {
t.Fatalf("plain fallback lost content:\n%s", out)
}
}
func TestRenderTelegramPlainKeepsFenceContent(t *testing.T) {
input := "before\n```\nfunc main() {}\n```\nafter"
out := renderTelegramPlain(input)
if strings.Contains(out, "```") {
t.Fatalf("plain fallback kept fence markers:\n%s", out)
}
if !strings.Contains(out, "func main() {}") {
t.Fatalf("plain fallback dropped fenced code content:\n%s", out)
}
}
func TestRenderTelegramPlainKeepsListsAndBlockquotes(t *testing.T) {
input := "- item one\n- item two\n> a blockquote"
out := renderTelegramPlain(input)
if !strings.Contains(out, "- item one") || !strings.Contains(out, "- item two") ||
!strings.Contains(out, "> a blockquote") {
t.Fatalf("plain fallback dropped list/blockquote text:\n%s", out)
}
}