From cb1b0eb11aec7f3fdafed1ecbf9791d1ee959b38 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 27 Jul 2026 04:47:21 +1000 Subject: [PATCH] feat(telegram): typing indicator + Markdown rendering (part of 16.6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two gaps visible in the live heyarchie bot: 1. No typing indicator. A non-command message runs a full LLM turn (seconds), during which the chat looked dead. defaultHandler now shows the typing action for the duration, refreshed every 4s since Telegram clears it after ~5s. 2. ParseMode was never set, so LLM Markdown reached users verbatim: literal **bold**, backticks, and pipe tables. helpHandler was worse -- it emitted Archie Gateway with no ParseMode, so the raw tags were shown. The SDK has no Markdown->Telegram converter (EscapeMarkdown does the inverse: it escapes text so it renders literally), and neither native parse mode helps, since Telegram's Markdown dialects use single-asterisk *bold* whereas LLMs emit **bold**. So markdownToHTML converts to the HTML subset Telegram accepts, mapping headings to , bullets to '•', and tables to
 (Telegram has no table element). Send falls back to
unformatted text if Telegram rejects the markup, so a conversion bug can
never swallow a reply.
---
 internal/channels/telegram/format.go      | 165 ++++++++++++++++++++++
 internal/channels/telegram/format_test.go |  74 ++++++++++
 internal/channels/telegram/telegram.go    | 102 ++++++++++---
 3 files changed, 320 insertions(+), 21 deletions(-)
 create mode 100644 internal/channels/telegram/format.go
 create mode 100644 internal/channels/telegram/format_test.go

diff --git a/internal/channels/telegram/format.go b/internal/channels/telegram/format.go
new file mode 100644
index 000000000..7ae65f35c
--- /dev/null
+++ b/internal/channels/telegram/format.go
@@ -0,0 +1,165 @@
+package telegram
+
+import (
+	"regexp"
+	"strings"
+)
+
+// Telegram's Bot API accepts a small HTML subset for message formatting:
+//       
 
. It has no +// notion of headings, bullets, or tables. LLM replies, however, are plain +// Markdown -- so without conversion the raw syntax (**bold**, backticks, +// pipe tables) is shown to the user verbatim. +// +// markdownToHTML converts the Markdown subset an LLM realistically emits +// into that HTML subset. It is deliberately conservative: anything it +// cannot map is escaped and passed through as literal text rather than +// guessed at, and sendMessage falls back to an unformatted send if +// Telegram still rejects the result. + +var ( + // fencedBlockRe matches ```lang\n...\n``` code fences. + fencedBlockRe = regexp.MustCompile("(?s)```([A-Za-z0-9_+-]*)\\n?(.*?)```") + // inlineCodeRe matches `code` spans. + inlineCodeRe = regexp.MustCompile("`([^`\n]+)`") + // linkRe matches [text](url). + linkRe = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)\)`) + // boldRe matches **text** and __text__. + boldRe = regexp.MustCompile(`\*\*([^*\n]+)\*\*|__([^_\n]+)__`) + // italicRe matches *text* and _text_ (after bold has been consumed). + italicRe = regexp.MustCompile(`\*([^*\n]+)\*|(?:^|[\s(])_([^_\n]+)_`) + // strikeRe matches ~~text~~. + strikeRe = regexp.MustCompile(`~~([^~\n]+)~~`) + // headingRe matches leading #, ##, ... headings. + headingRe = regexp.MustCompile(`^\s{0,3}#{1,6}\s+(.*)$`) + // bulletRe matches -, * and + list markers. + bulletRe = regexp.MustCompile(`^(\s*)[-*+]\s+(.*)$`) + // tableSepRe matches a Markdown table separator row (|---|:--:|). + tableSepRe = regexp.MustCompile(`^\s*\|?[\s:|-]*-[\s:|-]*\|?\s*$`) + // hrRe matches a horizontal rule. RE2 has no backreferences, so each + // marker character gets its own alternative rather than \1. + hrRe = regexp.MustCompile(`^\s*(?:-\s*-\s*-[-\s]*|\*\s*\*\s*\*[*\s]*|_\s*_\s*_[_\s]*)$`) +) + +// markdownToHTML converts LLM Markdown to the Telegram HTML subset. +func markdownToHTML(md string) string { + // Code content must not be touched by any inline rule, so pull fenced + // and inline code out first and re-insert after everything else. + var code []string + stash := func(s string) string { + code = append(code, s) + // \x00 cannot appear in a Telegram message, so it is a safe + // placeholder sentinel. + return "\x00" + itoa(len(code)-1) + "\x00" + } + + md = fencedBlockRe.ReplaceAllStringFunc(md, func(m string) string { + sub := fencedBlockRe.FindStringSubmatch(m) + lang, body := sub[1], strings.TrimRight(sub[2], "\n") + open := "
"
+		if lang != "" {
+			open = `
`
+		}
+		close := "
" + if lang != "" { + close = "
" + } + return stash(open + escapeHTML(body) + close) + }) + md = inlineCodeRe.ReplaceAllStringFunc(md, func(m string) string { + body := inlineCodeRe.FindStringSubmatch(m)[1] + return stash("" + escapeHTML(body) + "") + }) + + lines := strings.Split(md, "\n") + out := make([]string, 0, len(lines)) + for i := 0; i < len(lines); i++ { + line := lines[i] + + // A table needs monospace to stay aligned, and Telegram has no + // table element -- emit the whole block inside
.
+		if isTableRow(line) && i+1 < len(lines) && tableSepRe.MatchString(lines[i+1]) {
+			var block []string
+			for i < len(lines) && (isTableRow(lines[i]) || tableSepRe.MatchString(lines[i])) {
+				block = append(block, strings.TrimSpace(lines[i]))
+				i++
+			}
+			i--
+			out = append(out, "
"+escapeHTML(strings.Join(block, "\n"))+"
") + continue + } + + if hrRe.MatchString(line) { + out = append(out, "──────────") + continue + } + if m := headingRe.FindStringSubmatch(line); m != nil { + out = append(out, ""+inline(m[1])+"") + continue + } + if m := bulletRe.FindStringSubmatch(line); m != nil { + out = append(out, m[1]+"• "+inline(m[2])) + continue + } + out = append(out, inline(line)) + } + + res := strings.Join(out, "\n") + + // Re-insert code, innermost placeholder first. + for i, c := range code { + res = strings.ReplaceAll(res, "\x00"+itoa(i)+"\x00", c) + } + return res +} + +// inline applies the span-level rules to one line of already code-stripped +// text, escaping it first so user text can never inject markup. +func inline(s string) string { + s = escapeHTML(s) + s = linkRe.ReplaceAllString(s, `
$1`) + s = boldRe.ReplaceAllString(s, "$1$2") + s = strikeRe.ReplaceAllString(s, "$1") + s = italicRe.ReplaceAllStringFunc(s, func(m string) string { + sub := italicRe.FindStringSubmatch(m) + body := sub[1] + sub[2] + // Preserve the leading boundary char consumed by the _ branch. + prefix := "" + if sub[1] == "" && len(m) > 0 && m[0] != '_' { + prefix = string(m[0]) + } + return prefix + "" + body + "" + }) + return s +} + +// isTableRow reports whether a line looks like a Markdown table row. +func isTableRow(s string) bool { + t := strings.TrimSpace(s) + return strings.Count(t, "|") >= 2 +} + +// escapeHTML escapes the three characters Telegram's HTML parser treats as +// markup. Order matters: & must be escaped first. +func escapeHTML(s string) string { + s = strings.ReplaceAll(s, "&", "&") + s = strings.ReplaceAll(s, "<", "<") + s = strings.ReplaceAll(s, ">", ">") + return s +} + +// itoa is a tiny strconv.Itoa to keep the placeholder path allocation-free +// of the strconv import for such a narrow use. +func itoa(i int) string { + if i == 0 { + return "0" + } + var b [20]byte + p := len(b) + for i > 0 { + p-- + b[p] = byte('0' + i%10) + i /= 10 + } + return string(b[p:]) +} diff --git a/internal/channels/telegram/format_test.go b/internal/channels/telegram/format_test.go new file mode 100644 index 000000000..46ecaafd3 --- /dev/null +++ b/internal/channels/telegram/format_test.go @@ -0,0 +1,74 @@ +package telegram + +import "strings" + +import "testing" + +func TestMarkdownToHTML(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {name: "plain text untouched", in: "hello there", want: "hello there"}, + {name: "bold", in: "here's what I **can** do", want: "here's what I can do"}, + {name: "underscore bold", in: "__strong__", want: "strong"}, + {name: "italic", in: "*emphasis*", want: "emphasis"}, + {name: "strikethrough", in: "~~gone~~", want: "gone"}, + {name: "inline code", in: "the `/commands` system", want: "the /commands system"}, + {name: "link", in: "[docs](https://x.test)", want: `docs`}, + {name: "heading becomes bold", in: "## Capabilities", want: "Capabilities"}, + {name: "bullet becomes dot", in: "- Answer questions", want: "• Answer questions"}, + { + name: "html in user text is escaped, not injected", + in: "use & co", + want: "use <script>alert(1)</script> & co", + }, + { + name: "markdown inside code is left alone", + in: "`**not bold**`", + want: "**not bold**", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := markdownToHTML(tt.in); got != tt.want { + t.Errorf("markdownToHTML(%q)\n got: %q\nwant: %q", tt.in, got, tt.want) + } + }) + } +} + +func TestMarkdownToHTMLFencedCode(t *testing.T) { + got := markdownToHTML("run:\n```go\nfmt.Println(1 < 2)\n```") + want := "run:\n" + `
fmt.Println(1 < 2)
` + if got != want { + t.Errorf("fenced code\n got: %q\nwant: %q", got, want) + } +} + +// Telegram has no table element, so a Markdown table must become a
+// block or it arrives as unreadable pipe soup. Regression for the real
+// LLM reply that prompted this.
+func TestMarkdownToHTMLTableBecomesPre(t *testing.T) {
+	in := "| Capability | Description |\n|---|---|\n| **Code** | Write, review |"
+	got := markdownToHTML(in)
+	if !strings.HasPrefix(got, "
") || !strings.HasSuffix(got, "
") { + t.Fatalf("table not wrapped in
: %q", got)
+	}
+	if strings.Contains(got, "") {
+		t.Errorf("table interior must stay literal, got %q", got)
+	}
+}
+
+// Every emitted tag must be one Telegram actually accepts.
+func TestMarkdownToHTMLEmitsOnlySupportedTags(t *testing.T) {
+	in := "# H\n\nsome **b** and *i* and `c`\n\n- item\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n```sh\nls\n```"
+	got := markdownToHTML(in)
+	for _, bad := range []string{"

", "

    ", "
  • ", "

    ", "", "", "
    "} { + if strings.Contains(got, bad) { + t.Errorf("emitted unsupported tag %s: %q", bad, got) + } + } +} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index f4c20b188..18226e673 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -12,6 +12,7 @@ import ( "runtime/debug" "slices" "strings" + "time" "github.com/go-telegram/bot" "github.com/go-telegram/bot/models" @@ -177,7 +178,7 @@ func (g *Gateway) helpHandler() bot.HandlerFunc { return } g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, - "🤖 Archie Gateway\n\n"+ + "🤖 **Archie Gateway**\n\n"+ "/status -- Show task status\n"+ "/help -- This message\n\n"+ "Anything else: chat with the LLM (not yet wired -- coming soon).") @@ -193,6 +194,11 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { return } + // Routing a non-command message runs an LLM turn, which can take + // many seconds. Show a typing indicator for the whole wait so the + // chat doesn't look dead. + stopTyping := g.startTyping(ctx, b, msg.Chat.ID, msg.MessageThreadID) + // If it starts with / but wasn't matched by a registered // handler, it's unknown -- let the router handle it (which // will say "unrecognized"). @@ -202,6 +208,7 @@ func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { From: msg.From.Username, Text: msg.Text, }) + stopTyping() if err != nil { g.log.Error("route failed", "error", err) return @@ -238,6 +245,45 @@ func (g *Gateway) authorizedMessage(ctx context.Context, b *bot.Bot, update *mod return nil, false } +// typingRefresh is how often the typing action is re-sent. Telegram clears +// the indicator after ~5s, so it must be refreshed to stay visible for the +// length of an LLM turn. +const typingRefresh = 4 * time.Second + +// startTyping shows the "typing…" indicator and keeps it alive until the +// returned stop function is called. Errors are logged at debug level only: +// a missing typing indicator must never block or fail the actual reply. +func (g *Gateway) startTyping(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int) (stop func()) { + send := func() { + params := &bot.SendChatActionParams{ + ChatID: chatID, + Action: models.ChatActionTyping, + } + if messageThreadID != 0 { + params.MessageThreadID = messageThreadID + } + if _, err := b.SendChatAction(ctx, params); err != nil { + g.log.Debug("send chat action failed", "error", err) + } + } + + typingCtx, cancel := context.WithCancel(ctx) + send() + go func() { + ticker := time.NewTicker(typingRefresh) + defer ticker.Stop() + for { + select { + case <-typingCtx.Done(): + return + case <-ticker.C: + send() + } + } + }() + return cancel +} + func (g *Gateway) isChatAllowed(chatID int64) bool { if len(g.AllowedChatIDs) == 0 { return true @@ -249,16 +295,7 @@ func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, mes // Split long messages to stay under Telegram's 4096 character limit. const maxLen = 4000 if len(text) <= maxLen { - params := &bot.SendMessageParams{ - ChatID: chatID, - Text: text, - } - if messageThreadID != 0 { - params.MessageThreadID = messageThreadID - } - if _, err := b.SendMessage(ctx, params); err != nil { - g.log.Error("send message failed", "error", err) - } + g.send(ctx, b, chatID, messageThreadID, text, "send message failed") return } parts := splitLongMessage(text, maxLen) @@ -267,16 +304,39 @@ func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, mes if i < len(parts)-1 { partText += "\n\n_(continued...)_" } - params := &bot.SendMessageParams{ - ChatID: chatID, - Text: partText, - } - if messageThreadID != 0 { - params.MessageThreadID = messageThreadID - } - if _, err := b.SendMessage(ctx, params); err != nil { - g.log.Error("send message part failed", "error", err, "part", i) - } + g.send(ctx, b, chatID, messageThreadID, partText, "send message part failed") + } +} + +// send delivers one message, rendering Markdown as Telegram HTML. +// +// Splitting a long reply can cut an HTML tag in half, and a hand-written +// converter can always meet Markdown it maps wrongly; in both cases +// Telegram rejects the whole message with a parse error. Rather than lose +// the reply, fall back to sending the original unformatted text -- the user +// sees raw Markdown, which is what happened before formatting existed, but +// never silence. +func (g *Gateway) send(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text, errMsg string) { + params := &bot.SendMessageParams{ + ChatID: chatID, + Text: markdownToHTML(text), + ParseMode: models.ParseModeHTML, + } + if messageThreadID != 0 { + params.MessageThreadID = messageThreadID + } + if _, err := b.SendMessage(ctx, params); err == nil { + return + } else { + g.log.Warn("formatted send failed, retrying unformatted", "error", err) + } + + plain := &bot.SendMessageParams{ChatID: chatID, Text: text} + if messageThreadID != 0 { + plain.MessageThreadID = messageThreadID + } + if _, err := b.SendMessage(ctx, plain); err != nil { + g.log.Error(errMsg, "error", err) } }