From ac8df6989ff63d8d2ba52454c997fa9981b48aac Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:19:17 +0200 Subject: [PATCH 1/8] telegram: fix emphasis and table rendering, add a splitter that measures rendered HTML The Markdown to Telegram HTML converter mangled common model output, and there was no way to split a long answer without breaking it. Converter (markdownToTelegramHtml): - Emphasis is paired by the CommonMark delimiter rules instead of regexes. A delimiter needs a non-space character on its inside edge, `_` needs a word boundary on its outside edge, and backslash escapes are honoured. `2 * 3 * 4`, `* item` bullets, `snake_case_name` and `\*x\*` stay literal. Mis-nested markers (`**bold _both** tail_`) come out as well-formed HTML instead of crossed tags. - A single word in double underscores (`__init__`, `__main__`) stays literal. It cannot be told apart from `__bold__`, which therefore is no longer bold; `__two words__` still is. - `2*3*4` and `2**10` between numbers stay literal. - Code fences are read line by line. A block ends only on a line of backticks, so backticks inside a code line no longer end it; a longer fence can hold a shorter one; a fence that is never closed runs to the end of the text, so a code block renders as code while it streams. - Inline code can use more than one backtick. - Table cells get inline formatting and a `|` inside inline code or after a backslash no longer splits the cell. Telegram shows neither bold nor links inside
, so each link in a cell is repeated under the table. Splitter (new): splitMarkdownForTelegram, takeMarkdownChunk and resumeMarkdownAt split the markdown source so that each chunk's rendered HTML, and its source, fit one Telegram message. A chunk ends at the last line break that fits. A code block that spans chunks is closed and reopened with the same opening line; a table repeats its header. A single line too long for a message is cut inside the line, at a space if there is one, never inside a surrogate pair. Chunks record the source range they cover, so concatenating them gives back the text exactly. splitMessage is unchanged except that it no longer cuts a surrogate pair. --- src/transports/telegram/format.ts | 958 ++++++++++++++++++++++++++---- src/util.ts | 8 + test/telegram-doc-generator.ts | 148 +++++ test/telegram-format.test.ts | 170 +++++- test/telegram-split.test.ts | 354 +++++++++++ test/telegram-test-helpers.ts | 158 +++++ test/unit.test.ts | 10 + 7 files changed, 1674 insertions(+), 132 deletions(-) create mode 100644 test/telegram-doc-generator.ts create mode 100644 test/telegram-split.test.ts create mode 100644 test/telegram-test-helpers.ts diff --git a/src/transports/telegram/format.ts b/src/transports/telegram/format.ts index 3732008..dc87bd9 100644 --- a/src/transports/telegram/format.ts +++ b/src/transports/telegram/format.ts @@ -1,5 +1,6 @@ /** - * telegram-format.ts — Convert markdown to Telegram-compatible HTML + * telegram-format.ts — Convert markdown to Telegram-compatible HTML, and split + * markdown into pieces whose HTML fits one Telegram message. * * Telegram's Bot API supports a subset of HTML: * , , ,,,, ,@@ -7,17 +8,24 @@ * This converter handles common agent output patterns: * - Headers (#, ##, ###) → bold text * - ***bold italic*** → text - * - **bold** / __bold__ → + * - **bold** / __bold phrase__ → * - *italic* / _italic_ → * - ~~strikethrough~~ →* - `inline code` →"); +/** The first chunk of a text, as returned by `takeMarkdownChunk` */ +export interface TakenChunk { + /** How many characters of the body this chunk covers */ + length: number; + prefix: string; + suffix: string; + text: string; + html: string; + /** The prefix the text after this chunk needs */ + nextPrefix: string; +} - // Strikethrough: ~~text~~ - processed = processed.replace(/~~(.+?)~~/g, "* - ```code blocks``` →* - [text](url) → text (supports parens in URLs) + * - Tables → abox with aligned columns * - Bullet/numbered lists preserved as-is * - HTML entities escaped (&, <, >) + * + * Emphasis follows the CommonMark delimiter rules, so `2 * 3 * 4`, `* item` + * bullets, `snake_case` and mis-nested markers stay literal instead of + * turning into tags. Whatever comes out is well-formed: every tag is closed + * in the order it was opened. */ -import { randomBytes } from "node:crypto"; +/** The longest text Telegram accepts in one message, in UTF-16 code units */ +export const TELEGRAM_MESSAGE_LIMIT = 4096; /** Escape HTML special characters */ function escapeHtml(text: string): string { @@ -55,28 +63,12 @@ function matchLink(str: string, startIdx: number): { full: string; text: string; return { full: str.slice(startIdx, i + 1), text, url, end: i + 1 }; } -/** Extract all markdown links with balanced-paren URL support */ -function extractLinks(str: string, cb: (text: string, url: string) => string): string { - let result = ""; - let i = 0; - while (i < str.length) { - if (str[i] === "[") { - const link = matchLink(str, i); - if (link) { - result += cb(link.text, link.url); - i = link.end; - continue; - } - } - result += str[i]; - i++; - } - return result; -} - /** * Truncate HTML safely — avoids cutting inside tags. * Finds the last '>' before the limit, or falls back to the limit itself. + * + * Message delivery does not use this: it drops text. Long answers are split + * with `splitMarkdownForTelegram` instead. */ export function truncateHtmlSafe(html: string, limit: number): string { if (html.length <= limit) return html; @@ -93,30 +85,369 @@ export function truncateHtmlSafe(html: string, limit: number): string { return html.slice(0, safeEnd) + "..."; } +// ── Inline formatting ───────────────────────────────── + +/** A run of `*`, `_` or `~~` that may open or close emphasis */ +interface Delimiter { + type: "delim"; + ch: "*" | "_" | "~"; + /** Characters of the run not yet used by a match */ + count: number; + /** Length of the run as written */ + length: number; + canOpen: boolean; + canClose: boolean; +} + +type InlineNode = + | { type: "text"; text: string } + | { type: "code"; text: string } + | { type: "link"; href: string; children: InlineNode[] } + | { type: "tag"; tag: "b" | "i" | "s"; children: InlineNode[] } + | Delimiter; + +/** ASCII punctuation: the characters a backslash can escape */ +const ESCAPABLE = /[!-/:-@[-`{-~]/; +const PUNCTUATION = /[\p{P}\p{S}]/u; +const WORD_CHAR = /[\p{L}\p{N}_]/u; +const ASCII_DIGIT = /[0-9]/; +const SAFE_URL = /^(?:https?:\/\/|mailto:)/i; /** - * Convert a markdown table into a-wrapped, column-aligned monospace table. - * Parses the header row, skips the separator row, and pads all columns to uniform width. + * A name wrapped in double underscores, like `__init__` or `__FILE__`. + * Models write these far more often than they write `__bold__`, so a single + * word in double underscores stays literal. `__two words__` is still bold. */ -function formatTable(tableMd: string): string { - const lines = tableMd.trim().split("\n"); - if (lines.length < 2) return `${escapeHtml(tableMd)}`; +const DUNDER_NAME = /__[\p{L}\p{N}]+(?:_+[\p{L}\p{N}]+)*__(?![\p{L}\p{N}_])/uy; + +/** The character before index `i`, or a space at the start of the line */ +function charBefore(s: string, i: number): string { + if (i <= 0) return " "; + const low = s.charCodeAt(i - 1); + if (low >= 0xdc00 && low <= 0xdfff && i >= 2) { + const high = s.charCodeAt(i - 2); + if (high >= 0xd800 && high <= 0xdbff) return s.slice(i - 2, i); + } + return s[i - 1]; +} - // Parse rows: split by | and trim each cell - const parseRow = (line: string): string[] => - line.replace(/^\|/, "").replace(/\|$/, "").split("|").map(c => c.trim()); +/** The character at index `i`, or a space at the end of the line */ +function charAt(s: string, i: number): string { + return i >= s.length ? " " : String.fromCodePoint(s.codePointAt(i)!); +} - const headerCells = parseRow(lines[0]); - // lines[1] is the separator row (|---|---|) — skip it - const dataRows = lines.slice(2).map(parseRow); - const colCount = headerCells.length; +function runLength(s: string, i: number, ch: string): number { + let n = 0; + while (s[i + n] === ch) n++; + return n; +} - // Normalize rows to exactly colCount columns - const normalize = (cells: string[]): string[] => - Array.from({ length: colCount }, (_, i) => cells[i] ?? ""); +/** Index of the next run of exactly `n` backticks at or after `from`, or -1 */ +function findBacktickRun(s: string, from: number, n: number): number { + let i = s.indexOf("`", from); + while (i !== -1) { + const len = runLength(s, i, "`"); + if (len === n) return i; + i = s.indexOf("`", i + len); + } + return -1; +} + +/** + * Decide whether a delimiter run can open or close emphasis (CommonMark's + * flanking rules). A delimiter needs a non-space character on its inside + * edge, and `_` also needs a word boundary on its outside edge. Returns null + * for a run that can do neither: it is plain text. + */ +function delimiterAt(src: string, i: number, n: number, ch: "*" | "_" | "~"): Delimiter | null { + const prev = charBefore(src, i); + const next = charAt(src, i + n); + const prevSpace = /\s/.test(prev); + const nextSpace = /\s/.test(next); + let canOpen: boolean; + let canClose: boolean; + if (ch === "~") { + canOpen = !nextSpace; + canClose = !prevSpace; + } else { + const prevPunct = PUNCTUATION.test(prev); + const nextPunct = PUNCTUATION.test(next); + const leftFlanking = !nextSpace && (!nextPunct || prevSpace || prevPunct); + const rightFlanking = !prevSpace && (!prevPunct || nextSpace || nextPunct); + if (ch === "_") { + canOpen = leftFlanking && (!rightFlanking || prevPunct); + canClose = rightFlanking && (!leftFlanking || nextPunct); + } else { + // `2*3*4` and `2**10` are arithmetic, not emphasis. + const arithmetic = ASCII_DIGIT.test(prev) && ASCII_DIGIT.test(next); + canOpen = leftFlanking && !arithmetic; + canClose = rightFlanking && !arithmetic; + } + } + return canOpen || canClose ? { type: "delim", ch, count: n, length: n, canOpen, canClose } : null; +} + +/** Text of a code span: one space of padding on each side is not part of it */ +function codeSpanText(raw: string): string { + return raw.length > 2 && raw.startsWith(" ") && raw.endsWith(" ") && raw.trim() !== "" ? raw.slice(1, -1) : raw; +} + +/** + * Parse one line of markdown into inline nodes. Code spans and links are + * taken out first, so nothing inside them is read as formatting. + */ +function parseInline(src: string, allowLinks = true): InlineNode[] { + const nodes: InlineNode[] = []; + let text = ""; + const flush = () => { + if (text) nodes.push({ type: "text", text }); + text = ""; + }; + + let i = 0; + while (i < src.length) { + const c = src[i]; - const rawHeader = normalize(headerCells); - const rawDataRows = dataRows.map(normalize); - const allRows = [rawHeader, ...rawDataRows]; + if (c === "\\" && i + 1 < src.length && ESCAPABLE.test(src[i + 1])) { + text += src[i + 1]; + i += 2; + continue; + } + + if (c === "`") { + const n = runLength(src, i, "`"); + const close = findBacktickRun(src, i + n, n); + if (close === -1) { + text += src.slice(i, i + n); + } else { + flush(); + nodes.push({ type: "code", text: codeSpanText(src.slice(i + n, close)) }); + } + i = close === -1 ? i + n : close + n; + continue; + } + + if (c === "[" && allowLinks) { + const link = matchLink(src, i); + if (link) { + flush(); + const url = link.url.trim(); + const children = parseInline(link.text, false); + if (SAFE_URL.test(url)) { + nodes.push({ type: "link", href: url, children }); + } else { + // Unsafe or relative URL — render as text + nodes.push(...children, { type: "text", text: ` (${url})` }); + } + i = link.end; + continue; + } + } + + if (c === "*" || c === "_" || c === "~") { + const n = runLength(src, i, c); + if (c === "_" && n === 2 && !WORD_CHAR.test(charBefore(src, i))) { + DUNDER_NAME.lastIndex = i; + const name = DUNDER_NAME.exec(src); + if (name) { + text += name[0]; + i += name[0].length; + continue; + } + } + const delimiter = c === "~" && n !== 2 ? null : delimiterAt(src, i, n, c); + if (delimiter) { + flush(); + nodes.push(delimiter); + } else { + text += src.slice(i, i + n); + } + i += n; + continue; + } + + text += c; + i++; + } + flush(); + return resolveEmphasis(nodes); +} + +/** + * Pair delimiter runs into , andnodes (CommonMark's "process + * emphasis"). A closer takes the nearest opener of its kind; delimiters left + * between the two stay literal, so the result is always properly nested. + */ +function resolveEmphasis(nodes: InlineNode[]): InlineNode[] { + /** Indexes into `nodes` of delimiters that can still open */ + const openers: number[] = []; + let k = 0; + while (k < nodes.length) { + const closer = nodes[k]; + if (closer.type !== "delim") { + k++; + continue; + } + let matched = false; + if (closer.canClose) { + for (let s = openers.length - 1; s >= 0; s--) { + const at = openers[s]; + const opener = nodes[at] as Delimiter; + if (opener.ch !== closer.ch) continue; + // CommonMark's rule of three: `*a**b*` does not pair the `**` with a `*`. + if ( + closer.ch !== "~" && + (opener.canClose || closer.canOpen) && + (opener.length + closer.length) % 3 === 0 && + !(opener.length % 3 === 0 && closer.length % 3 === 0) + ) { + continue; + } + // Two characters make bold, one makes italic. Odd runs on both sides + // (`***x***`) spend one first, so italic ends up inside bold. + const bothOdd = opener.count % 2 === 1 && closer.count % 2 === 1; + const use = closer.ch === "~" || (opener.count >= 2 && closer.count >= 2 && !bothOdd) ? 2 : 1; + const tag = closer.ch === "~" ? "s" : use === 2 ? "b" : "i"; + const children = nodes.slice(at + 1, k); + opener.count -= use; + closer.count -= use; + const keepOpener = opener.count > 0; + const keepCloser = closer.count > 0; + const from = keepOpener ? at + 1 : at; + nodes.splice(from, k - from + (keepCloser ? 0 : 1), { type: "tag", tag, children }); + openers.length = keepOpener ? s + 1 : s; + // A closer with characters left is looked at again; it now sits right after the new tag. + k = from + 1; + matched = true; + break; + } + } + if (!matched) { + if (closer.canOpen) openers.push(k); + k++; + } + } + return nodes; +} + +/** + * Render inline nodes as Telegram HTML. + * + * `open` holds the tags already open around these nodes, so `# **Title**` + * does not nest in . With `footnotes`, a link renders as its text only + * and its tag is collected there: Telegram ignores links inside"); - // _text_ only at word boundaries (avoid matching snake_case) - processed = processed.replace(/(?$1. + */ +function renderInlineNodes(nodes: InlineNode[], open: ReadonlySet, footnotes?: string[]): string { + let html = ""; + for (const node of nodes) { + switch (node.type) { + case "text": + html += escapeHtml(node.text); + break; + case "delim": + html += escapeHtml(node.ch.repeat(node.count)); + break; + case "code": + html += ` ${escapeHtml(node.text)}`; + break; + case "link": { + const inner = renderInlineNodes(node.children, open) || escapeHtml(node.href); + const anchor = `${inner}`; + if (footnotes) { + if (!footnotes.includes(anchor)) footnotes.push(anchor); + html += inner; + } else { + html += anchor; + } + break; + } + case "tag": { + if (open.has(node.tag)) { + html += renderInlineNodes(node.children, open, footnotes); + } else { + const inner = renderInlineNodes(node.children, new Set(open).add(node.tag), footnotes); + html += `<${node.tag}>${inner}${node.tag}>`; + } + break; + } + } + } + return html; +} + +/** The text a reader sees for these nodes, without any markup */ +function inlineText(nodes: InlineNode[]): string { + let text = ""; + for (const node of nodes) { + if (node.type === "text" || node.type === "code") text += node.text; + else if (node.type === "delim") text += node.ch.repeat(node.count); + else text += inlineText(node.children); + } + return text; +} + +const NO_OPEN_TAGS: ReadonlySet= new Set(); +const INSIDE_BOLD: ReadonlySet = new Set(["b"]); + +/** Render one line that is not part of a code block or a table */ +function renderTextLine(line: string): string { + // Horizontal rules: --- or *** + if (/^[-*]{3,}$/.test(line)) return "───────────────"; + + // Headers: # text → text (Telegram has no header tags) + const header = /^#{1,6}\s+(.+)$/.exec(line); + if (header) return `${renderInlineNodes(parseInline(header[1]), INSIDE_BOLD)}`; + + // Blockquotes: > text + const quote = /^>\s?(.+)$/.exec(line); + if (quote) return ` ${renderInlineNodes(parseInline(quote[1]), NO_OPEN_TAGS)}`; + + return renderInlineNodes(parseInline(line), NO_OPEN_TAGS); +} + +// ── Tables ──────────────────────────────────────────── + +/** + * Split a table row into trimmed cells. A `|` inside inline code or after a + * backslash belongs to the cell. + */ +function splitTableRow(line: string): string[] { + const row = line.replace(/^\|/, "").replace(/\|$/, ""); + const cells: string[] = []; + let start = 0; + let i = 0; + while (i < row.length) { + const c = row[i]; + if (c === "\\" && i + 1 < row.length) { + i += 2; + } else if (c === "`") { + const n = runLength(row, i, "`"); + const close = findBacktickRun(row, i + n, n); + i = close === -1 ? i + n : close + n; + } else if (c === "|") { + cells.push(row.slice(start, i).trim()); + start = ++i; + } else { + i++; + } + } + cells.push(row.slice(start).trim()); + return cells; +} + +/** + * Convert a markdown table into a-wrapped, column-aligned monospace table. + * `lines` are the header row, the separator row and the data rows. All columns + * are padded to a uniform width. + * + * Cells get inline formatting: the markers are gone and the text is tagged. + * Telegram does not show bold, italics or links inside, so a cell reads + * as clean text, and each link is repeated under the table where it works. + */ +function formatTable(lines: string[]): string { + const headerCells = splitTableRow(lines[0]); + // lines[1] is the separator row (|---|---|) — skip it + const dataRows = lines.slice(2).map(splitTableRow); + const colCount = headerCells.length; // Display width of a single Unicode code point in a monospace font. // Emoji and CJK characters typically occupy 2 columns. @@ -177,134 +508,501 @@ function formatTable(tableMd: string): string { return w; }; - // Calculate max *display* width for each column (on unescaped text, - // since Telegram renders entities back to their visual form in) + /** Links found in cells, as tags, in order of appearance */ + const links: string[] = []; + + // A cell as it is emitted, with the display width of what the reader sees + // (Telegram renders entities back to their visual form in). + const toCell = (raw: string): { html: string; width: number } => { + const nodes = parseInline(raw); + return { html: renderInlineNodes(nodes, NO_OPEN_TAGS, links), width: displayWidth(inlineText(nodes)) }; + }; + + // Normalize rows to exactly colCount columns + const normalize = (cells: string[]) => + Array.from({ length: colCount }, (_, i) => toCell(cells[i] ?? "")); + + const header = normalize(headerCells); + const body = dataRows.map(normalize); + const allRows = [header, ...body]; + + // Calculate max *display* width for each column const colWidths: number[] = []; for (let c = 0; c < colCount; c++) { let max = 0; for (const row of allRows) { - max = Math.max(max, displayWidth(row[c])); + max = Math.max(max, row[c].width); } colWidths.push(max); } - // Pad an escaped cell so it visually aligns to `width` display columns. + // Pad a cell so it visually aligns to `width` display columns. // Spaces are 1 display column each, so we add (target - actual) spaces. - const padCell = (rawText: string, width: number): string => { - const escaped = escapeHtml(rawText); - const dw = displayWidth(rawText); - return escaped + " ".repeat(Math.max(0, width - dw)); - }; + const padCell = (cell: { html: string; width: number }, width: number): string => + cell.html + " ".repeat(Math.max(0, width - cell.width)); // Build formatted rows - const formatRow = (cells: string[]): string => + const formatRow = (cells: Array<{ html: string; width: number }>): string => "│ " + cells.map((cell, i) => padCell(cell, colWidths[i])).join(" │ ") + " │"; const separator = "├─" + colWidths.map(w => "─".repeat(w)).join("─┼─") + "─┤"; const topBorder = "┌─" + colWidths.map(w => "─".repeat(w)).join("─┬─") + "─┐"; const bottomBorder = "└─" + colWidths.map(w => "─".repeat(w)).join("─┴─") + "─┘"; - // Cells are escaped inside padCell; box-drawing chars are HTML-safe. + // Cells are escaped when rendered; box-drawing chars are HTML-safe. const result = [ topBorder, - formatRow(rawHeader), + formatRow(header), separator, - ...rawDataRows.map(formatRow), + ...body.map(formatRow), bottomBorder, ].join("\n"); - return `${result}`; + return [`${result}`, ...links].join("\n"); +} + +// ── Block structure ─────────────────────────────────── + +/** An opening code fence */ +interface Fence { + /** The opening line as written, e.g. "```ts" */ + line: string; + indent: string; + /** Number of backticks */ + ticks: number; +} + +interface TableHead { + head: string; + sep: string; +} + +type LineKind = "text" | "fence-open" | "fence-body" | "fence-close" | "table-head" | "table-sep" | "table-row"; + +interface Line { + /** Offset of the first character */ + start: number; + /** Offset of the line's newline, or the end of the text */ + end: number; + text: string; + kind: LineKind; + /** The fence this line opens, sits in or closes */ + fence?: Fence; + /** The table this line belongs to */ + table?: TableHead; +} + +/** + * A fence line longer than this is ordinary text. It keeps the line that + * reopens a split code block short next to the message limit. + */ +const MAX_FENCE_LINE = 200; +const FENCE_OPEN = /^([ \t]*)(`{3,})[^`]*$/; +const FENCE_CLOSE = /^[ \t]*(`{3,})\s*$/; +const TABLE_ROW = /^\|.+\|$/; +const TABLE_SEPARATOR = /^\|[-| :]+\|$/; + +function matchFenceOpen(line: string): Fence | null { + if (line.length > MAX_FENCE_LINE) return null; + const m = FENCE_OPEN.exec(line); + return m ? { line, indent: m[1], ticks: m[2].length } : null; +} + +function isFenceClose(line: string, fence: Fence): boolean { + if (line.length > MAX_FENCE_LINE) return false; + const m = FENCE_CLOSE.exec(line); + return m !== null && m[1].length >= fence.ticks; +} + +/** + * Split markdown into lines and say what each one is. This is the one place + * that decides where code blocks and tables start and end; the converter and + * the splitter both read it, so they cannot disagree. + * + * A code block opens on a line of three or more backticks (after optional + * indentation, followed by an optional info string) and closes on a line of + * at least as many backticks and nothing else. One that is never closed runs + * to the end of the text. + */ +function scanLines(md: string): Line[] { + const lines: Line[] = []; + for (let start = 0; ; ) { + const newline = md.indexOf("\n", start); + const end = newline === -1 ? md.length : newline; + lines.push({ start, end, text: md.slice(start, end), kind: "text" }); + if (newline === -1) break; + start = newline + 1; + } + + let fence: Fence | null = null; + let table: TableHead | null = null; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (fence) { + line.fence = fence; + line.kind = isFenceClose(line.text, fence) ? "fence-close" : "fence-body"; + if (line.kind === "fence-close") fence = null; + continue; + } + fence = matchFenceOpen(line.text); + if (fence) { + line.kind = "fence-open"; + line.fence = fence; + table = null; + continue; + } + if (table && TABLE_ROW.test(line.text)) { + line.kind = "table-row"; + line.table = table; + continue; + } + table = null; + // A table is a header row, a separator row and at least one data row. + if ( + i + 2 < lines.length && + TABLE_ROW.test(line.text) && + TABLE_SEPARATOR.test(lines[i + 1].text) && + TABLE_ROW.test(lines[i + 2].text) + ) { + table = { head: line.text, sep: lines[i + 1].text }; + line.kind = "table-head"; + line.table = table; + lines[i + 1].kind = "table-sep"; + lines[i + 1].table = table; + i++; + } + } + return lines; } /** * Convert markdown text to Telegram-compatible HTML. - * Handles code blocks first (to avoid processing markdown inside them), - * then processes inline formatting. + * Code blocks and tables are handled as blocks, so markdown inside them is + * never processed; every other line gets inline formatting. */ export function markdownToTelegramHtml(md: string): string { - // Generate unique sentinel per call to prevent spoofing - const sentinel = randomBytes(8).toString("hex"); - const S = (kind: string, idx: number) => `\x00${sentinel}_${kind}_${idx}\x00`; - const RE = (kind: string) => new RegExp(`\\x00${sentinel}_${kind}_(\\d+)\\x00`, "g"); - - // Extract fenced code blocks first to protect their contents - // (must happen before table extraction to avoid nestedtags) - const codeBlocks: string[] = []; - let processed = md.replace(/```(\w*)\n?([\s\S]*?)```/g, (_match, _lang, code) => { - const idx = codeBlocks.length; - codeBlocks.push(`${escapeHtml(code.replace(/\n$/, ""))}`); - return S("CB", idx); - }); - - // Extract markdown tables (now safe — code blocks are already sentinelled out) - const tables: string[] = []; - processed = processed.replace( - /(?:^|\n)(\|.+\|\n\|[-| :]+\|\n(?:\|.+\|(?:\n|$))+)/g, - (match) => { - const idx = tables.length; - const leadingNewline = match.startsWith("\n") ? "\n" : ""; - const trailingNewline = match.endsWith("\n") ? "\n" : ""; - const tableContent = match.replace(/^\n/, "").replace(/\n$/, ""); - tables.push(formatTable(tableContent)); - return leadingNewline + S("TB", idx) + trailingNewline; - }, - ); - - // Extract inline code to protect contents - const inlineCodes: string[] = []; - processed = processed.replace(/`([^`\n]+)`/g, (_match, code) => { - const idx = inlineCodes.length; - inlineCodes.push(`${escapeHtml(code)}`); - return S("IC", idx); - }); - - // Extract links before HTML-escaping (URLs contain &, = etc. that must be escaped once) - const links: string[] = []; - processed = extractLinks(processed, (text, url) => { - const trimmedUrl = url.trim(); - if (/^https?:\/\//i.test(trimmedUrl) || /^mailto:/i.test(trimmedUrl)) { - const idx = links.length; - links.push(`${escapeHtml(text)}`); - return S("LK", idx); + const lines = scanLines(md); + const out: string[] = []; + let i = 0; + while (i < lines.length) { + const line = lines[i]; + + if (line.kind === "fence-open") { + const code: string[] = []; + let j = i + 1; + while (j < lines.length && lines[j].kind === "fence-body") { + code.push(lines[j].text); + j++; + } + const closed = j < lines.length; + // An open block that ends with a newline has no last empty line yet. + if (!closed && code.length > 0 && code[code.length - 1] === "") code.pop(); + out.push(`${escapeHtml(code.join("\n"))}`); + i = closed ? j + 1 : j; + continue; } - // Unsafe or relative URL — render as text (will be escaped below) - return `${text} (${trimmedUrl})`; - }); - // Now escape HTML in the rest - processed = escapeHtml(processed); + if (line.kind === "table-head") { + let j = i; + while (j < lines.length && lines[j].table === line.table) j++; + out.push(formatTable(lines.slice(i, j).map((l) => l.text))); + i = j; + continue; + } - // Headers: # text → text (Telegram has no header tags) - processed = processed.replace(/^#{1,6}\s+(.+)$/gm, "$1"); + out.push(renderTextLine(line.text)); + i++; + } - // Bold+italic: ***text*** → text (must come before ** and *) - processed = processed.replace(/\*\*\*(.+?)\*\*\*/g, "$1"); + // Merge adjacent blockquotes + return out.join("\n").replace(/<\/blockquote>\n/g, "\n"); +} - // Bold: **text** or __text__ - processed = processed.replace(/\*\*(.+?)\*\*/g, "$1"); - processed = processed.replace(/__(.+?)__/g, "$1"); +// ── Splitting ───────────────────────────────────────── + +/** One message's worth of markdown */ +export interface MarkdownChunk { + /** Where this chunk's source starts in the text given to the splitter */ + start: number; + /** Where it ends. Chunks follow each other without gaps or overlaps. */ + end: number; + /** + * Lines the splitter put before the source: the fence that reopens a code + * block, or the header of a table, that the previous chunk ended inside. + * Empty when the chunk starts outside both. The first chunk has the prefix + * the caller passed in. + */ + prefix: string; + /** The fence the splitter put after the source to close a code block, or "" */ + suffix: string; + /** `prefix + source + suffix`: the markdown `html` was rendered from */ + text: string; + /** `text` as Telegram HTML, no longer than the limit */ + html: string; +} - // Italic: *text* (not part of **) - processed = processed.replace(/(?$1$1"); +/** What surrounds a position: the code block or table it is inside, if any */ +interface BlockContext { + fence?: Fence; + table?: TableHead; +} - // Blockquotes: > text (after HTML escaping, > becomes >) - processed = processed.replace(/^>\s?(.+)$/gm, "$1"); - // Merge adjacent blockquotes - processed = processed.replace(/<\/blockquote>\n/g, "\n"); +/** The line that contains `offset` (the later one, at a line start) */ +function lineIndexAt(lines: Line[], offset: number): number { + let lo = 0; + let hi = lines.length - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if (lines[mid].start <= offset) lo = mid; + else hi = mid - 1; + } + return lo; +} - // Horizontal rules: --- or *** - processed = processed.replace(/^[-*]{3,}$/gm, "───────────────"); +/** The block a cut at `offset` would fall inside */ +function contextAt(lines: Line[], offset: number): BlockContext { + const line = lines[lineIndexAt(lines, offset)]; + if (offset === line.start) { + if (line.kind === "fence-body" || line.kind === "fence-close") return { fence: line.fence }; + if (line.kind === "table-row") return { table: line.table }; + return {}; + } + if (line.kind === "fence-open" || line.kind === "fence-body") return { fence: line.fence }; + return {}; +} + +function contextPrefix(context: BlockContext): string { + if (context.fence) return `${context.fence.line}\n`; + if (context.table) return `${context.table.head}\n${context.table.sep}\n`; + return ""; +} - // Restore placeholders - processed = processed.replace(RE("LK"), (_match, idx) => links[parseInt(idx, 10)]); - processed = processed.replace(RE("IC"), (_match, idx) => inlineCodes[parseInt(idx, 10)]); - processed = processed.replace(RE("CB"), (_match, idx) => codeBlocks[parseInt(idx, 10)]); - processed = processed.replace(RE("TB"), (_match, idx) => tables[parseInt(idx, 10)]); +/** + * True for a line start that makes a poor place to cut: it would leave an + * empty code block or a table header without rows on one side. + */ +function isAwkwardCut(lines: Line[], index: number, base: number): boolean { + const line = lines[index]; + const before = lines[index - 1]; + if (line.kind === "fence-close" || line.kind === "table-sep") return true; + if (before.start < base) return false; + return before.kind === "fence-open" || before.kind === "table-sep"; +} - return processed; +/** A line start that the converter reads as a quote, a header or a rule */ +const BLOCK_MARKER = /^(?:>|#{1,6}\s|[-*]{3,}$)/; + +/** How far a cut inside a line may move back to avoid changing what the rest means */ +const MAX_CUT_BACKOFF = 64; + +function isSurrogatePairAt(s: string, i: number): boolean { + if (i <= 0 || i >= s.length) return false; + const high = s.charCodeAt(i - 1); + const low = s.charCodeAt(i); + return high >= 0xd800 && high <= 0xdbff && low >= 0xdc00 && low <= 0xdfff; +} + +/** + * Take the first message's worth of `body`. + * + * `prefix` is what the body continues from: "" at the start of a text, + * otherwise the `nextPrefix` of the chunk before it (or the prefix from + * `resumeMarkdownAt`). It is rendered in front of the body and counts + * towards the limit. The chunk ends at the + * last line break whose rendered HTML still fits `limit`, so nothing is + * truncated and the rest starts on a new line. Its markdown source fits the + * limit too, since that is what is sent when Telegram refuses the HTML. + * + * A chunk that ends inside a code block gets a closing fence, and the rest + * reopens the block with the same opening line. A chunk that ends inside a + * table makes the rest repeat the table's header. + * + * A single line too long for one message is cut inside the line, at a space + * if there is one, and never between the halves of a surrogate pair. + */ +export function takeMarkdownChunk(prefix: string, body: string, limit = TELEGRAM_MESSAGE_LIMIT): TakenChunk { + // Look no further than one message can reach, plus the lines needed to + // tell what the last line in reach is. + let reach = body.length; + if (body.length > limit) { + reach = limit; + for (let n = 0; n < 3 && reach < body.length; n++) { + const newline = body.indexOf("\n", reach); + reach = newline === -1 ? body.length : newline + 1; + } + } + const doc = prefix + body.slice(0, reach); + const base = prefix.length; + const lines = scanLines(doc); + + /** The chunk that ends at `end`, or null if it does not fit (unless forced) */ + const chunkTo = (end: number, force = false): TakenChunk | null => { + const context = contextAt(lines, end); + const fence = context.fence; + const suffix = fence ? (doc[end - 1] === "\n" ? "" : "\n") + fence.indent + "`".repeat(fence.ticks) : ""; + const text = doc.slice(0, end) + suffix; + if (text.length > limit && !force) return null; + const html = markdownToTelegramHtml(text); + if (html.length > limit && !force) return null; + return { length: end - base, prefix, suffix, text, html, nextPrefix: contextPrefix(context) }; + }; + + if (reach === body.length) { + const whole = chunkTo(doc.length); + if (whole) return whole; + } + + // Cut at a line break: the last one that fits. + const first = lineIndexAt(lines, base); + let lo = first + 1; + let hi = lines.length - 1; + let best = -1; + let bestChunk: TakenChunk | null = null; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + const chunk = chunkTo(lines[mid].start); + if (chunk) { + best = mid; + bestChunk = chunk; + lo = mid + 1; + } else { + hi = mid - 1; + } + } + if (bestChunk) { + for (let index = best; index > first && index > best - 4; index--) { + if (isAwkwardCut(lines, index, base)) continue; + const chunk = index === best ? bestChunk : chunkTo(lines[index].start); + if (chunk) return chunk; + } + return bestChunk; + } + + // The first line alone is too long: cut inside it. + const line = lines[first]; + let cut = -1; + lo = base + 1; + hi = Math.min(line.end, base + limit); + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if (chunkTo(mid)) { + cut = mid; + lo = mid + 1; + } else { + hi = mid - 1; + } + } + if (cut === -1) { + // Not even one character fits beside the prefix. Move forward anyway. + cut = base + 1; + } else if (cut < line.end) { + for (let at = cut; at > base + ((cut - base) >> 1); at--) { + if (doc[at - 1] === " " || doc[at - 1] === "\t") { + cut = at; + break; + } + } + } + + // The rest of the line starts the next message. Back off a little if it + // would mean something there that it does not mean here: a fence, or a + // block marker that would swallow its first characters. + const fence = line.kind === "fence-body" ? line.fence! : null; + const changesMeaning = (at: number): boolean => { + if (line.kind === "fence-open" || line.kind === "fence-close") return false; + const head = doc.slice(line.start, at); + const tail = doc.slice(at, line.end); + if (fence) return isFenceClose(head, fence) || isFenceClose(tail, fence); + return matchFenceOpen(head) !== null || matchFenceOpen(tail) !== null || BLOCK_MARKER.test(tail); + }; + const unsafe = (at: number) => isSurrogatePairAt(doc, at) || changesMeaning(at); + const preferred = cut; + for (let n = 0; n < MAX_CUT_BACKOFF && cut > base + 1 && unsafe(cut); n++) cut--; + if (unsafe(cut)) { + cut = preferred; + if (isSurrogatePairAt(doc, cut)) cut += cut > base + 1 ? -1 : 1; + } + + return chunkTo(cut, true)!; +} + +/** + * Split markdown into chunks that each render to at most `limit` characters + * of Telegram HTML. Nothing is dropped: the chunks' source ranges cover the + * text exactly, and a code block or table that spans chunks is reopened in + * each one (see `MarkdownChunk.prefix` and `suffix`). + * + * `prefix` is for text that continues from something already delivered: the + * `nextPrefix` of an earlier chunk, or what `resumeMarkdownAt` returned. + */ +export function splitMarkdownForTelegram( + markdown: string, + limit = TELEGRAM_MESSAGE_LIMIT, + prefix = "", +): MarkdownChunk[] { + const chunks: MarkdownChunk[] = []; + let pos = 0; + while (pos < markdown.length) { + const taken = takeMarkdownChunk(prefix, markdown.slice(pos), limit); + chunks.push({ + start: pos, + end: pos + taken.length, + prefix: taken.prefix, + suffix: taken.suffix, + text: taken.text, + html: taken.html, + }); + pos += taken.length; + prefix = taken.nextPrefix; + } + return chunks; +} + +/** + * Find where to continue a text that was delivered only up to `offset`. + * + * `prefix` and `body` are as in `takeMarkdownChunk`. Returns the offset to + * continue from and the prefix that text needs, for `splitMarkdownForTelegram`. + * Usually that is `offset` itself, with the fence or table header of the + * block it is in. The exceptions keep the rest from being misread: + * - Inside an opening fence line: continue after the line; the prefix + * reopens the block. + * - At or inside a closing fence line: continue after the line. + * - Inside a line whose remainder would read as a quote, a header, a rule + * or a fence: the prefix is a backslash, which keeps it literal. + * - Inside a code line whose remainder would read as the closing fence: + * continue a few characters earlier, repeating them. + */ +export function resumeMarkdownAt(prefix: string, body: string, offset: number): { offset: number; prefix: string } { + const doc = prefix + body; + const lines = scanLines(doc); + const at = prefix.length + offset; + const line = lines[lineIndexAt(lines, at)]; + const afterLine = Math.min(line.end + 1, doc.length) - prefix.length; + if (line.kind === "fence-close") return { offset: afterLine, prefix: "" }; + if (line.kind === "fence-open" && at > line.start) return { offset: afterLine, prefix: `${line.fence!.line}\n` }; + const context = contextAt(lines, at); + if (at > line.start) { + if (context.fence) { + // The whole line is not a closing fence, so this stops at its start at the latest. + let from = at; + while (isFenceClose(doc.slice(from, line.end), context.fence)) from--; + return { offset: from - prefix.length, prefix: contextPrefix(context) }; + } + const rest = doc.slice(at, line.end); + if (matchFenceOpen(rest) !== null || BLOCK_MARKER.test(rest)) return { offset, prefix: "\\" }; + } + return { offset, prefix: contextPrefix(context) }; } diff --git a/src/util.ts b/src/util.ts index 366e5da..15ed074 100644 --- a/src/util.ts +++ b/src/util.ts @@ -15,6 +15,10 @@ export const DEBUG_STREAM = process.env.ROUNDHOUSE_DEBUG_STREAM === "1"; /** * Split a long message into chunks that fit within maxLen. * Prefers splitting at newline boundaries. + * + * This knows nothing about markdown: a cut can land inside a code block. + * Telegram output is split with `splitMarkdownForTelegram` + * (src/transports/telegram/format.ts) instead, which reopens the block. */ export function splitMessage(text: string, maxLen: number): string[] { if (maxLen <= 0) throw new Error(`splitMessage: maxLen must be > 0, got ${maxLen}`); @@ -28,6 +32,10 @@ export function splitMessage(text: string, maxLen: number): string[] { } let splitAt = remaining.lastIndexOf("\n", maxLen); if (splitAt < maxLen / 2) splitAt = maxLen; + // Keep the two halves of a surrogate pair (an emoji) together. + const before = remaining.charCodeAt(splitAt - 1); + const after = remaining.charCodeAt(splitAt); + if (splitAt > 1 && before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) splitAt--; chunks.push(remaining.slice(0, splitAt)); // If we split at a newline, consume it so next chunk doesn't start with \n if (splitAt < remaining.length && remaining[splitAt] === "\n") { diff --git a/test/telegram-doc-generator.ts b/test/telegram-doc-generator.ts new file mode 100644 index 0000000..8198bfb --- /dev/null +++ b/test/telegram-doc-generator.ts @@ -0,0 +1,148 @@ +/** + * Seeded generator of markdown documents for the Telegram splitting and + * delivery tests: prose, lists, quotes, code blocks with and without info + * strings, tables, lines too long for one message, HTML-special characters + * and emoji. The same seed always gives the same document. + */ + +/** Small seeded generator (mulberry32) */ +export function rng(seed: number) { + let a = seed >>> 0; + const next = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + const int = (min: number, max: number) => min + Math.floor(next() * (max - min + 1)); + const pick =(items: readonly T[]): T => items[int(0, items.length - 1)]; + return { next, int, pick, chance: (p: number) => next() < p }; +} +export type Rng = ReturnType ; + +const PROSE_WORDS = [ + "the", "cache", "is", "rebuilt", "when", "a < b", "x > y", "R&D", " ", "&", "Map ", + "**bold**", "*italic*", "_also italic_", "`inline `", "~~gone~~", "[link](https://example.com/a?b=1&c=2)", + "snake_case_name", "__init__", "2 * 3", "\\*escaped\\*", "😀", "👨👩👧", "日本語", "naïve", "é", "—", "100%", + "path/to/file.ts", "(see below)", "\"quoted\"", "it's", "a|b", "`a|b`", "#hash", "> not a quote", "...", +]; +/** Prose without inline markup, but with everything else that needs care */ +const PLAIN_WORDS = [ + "the", "cache", "is", "rebuilt", "when", "a < b", "x > y", "R&D", "", "&", "Map ", + "snake_case_name", "😀", "👨👩👧", "日本語", "naïve", "—", "100%", "path/to/file.ts", "(see below)", + "\"quoted\"", "it's", "a|b", "#hash", "> not a quote", "# not a header", "...", +]; +const CODE_WORDS = [ + "const", "x", "=", " ", "&&", "||", "a < b", "=>", "`tpl`", "\"```\"", "__x__", "**kw", "*args", "😀", + "Map>", "// comment & more", "|", "# not a header", "[i](j)", "\\n", " ", +]; +const FENCE_INFO = ["", "ts", "python", "bash", "json", "diff", "c++", "ts title=\"a.ts\""]; + +/** Each code line carries this, so a test can tell code from prose in the output */ +export const CODE_MARK = "ⓒ"; +/** Each prose line carries this */ +export const PROSE_MARK = "ⓟ"; + +function words(r: Rng, pool: readonly string[], count: number): string { + return Array.from({ length: count }, () => r.pick(pool)).join(" "); +} + +function genProse(r: Rng, pool: readonly string[]): string { + const lines = Array.from({ length: r.int(1, 4) }, () => `${PROSE_MARK} ${words(r, pool, r.int(3, 40))}`); + return lines.join(r.chance(0.5) ? "\n" : "\n\n"); +} + +function genList(r: Rng, pool: readonly string[]): string { + const bullet = r.pick(["- ", "* ", "1. ", " * "]); + return Array.from({ length: r.int(2, 12) }, () => `${bullet}${PROSE_MARK} ${words(r, pool, r.int(1, 10))}`).join("\n"); +} + +function genHeaderOrQuote(r: Rng, pool: readonly string[]): string { + const lead = r.pick(["# ", "## ", "### ", "> ", "> "]); + return `${lead}${PROSE_MARK} ${words(r, pool, r.int(1, 8))}`; +} + +function genFence(r: Rng, lineCount: number): string { + const ticks = r.chance(0.15) ? "````" : "```"; + const indent = r.chance(0.15) ? " " : ""; + const lines: string[] = []; + for (let i = 0; i < lineCount; i++) { + if (r.chance(0.06)) lines.push(""); + else if (ticks === "````" && r.chance(0.05)) lines.push(`${indent}\`\`\``); + else lines.push(`${indent}${CODE_MARK} ${words(r, CODE_WORDS, r.int(1, 14))}`); + } + return `${indent}${ticks}${r.pick(FENCE_INFO)}\n${lines.join("\n")}\n${indent}${ticks}`; +} + +function genTable(r: Rng, rowCount: number): string { + const cols = r.int(2, 4); + const cell = () => r.pick(["ok", "a & b", " ", "**x**", "`a|b`", "😀", "日本", "value " + r.int(0, 9999), "[l](https://e.com/x)"]); + const row = () => `| ${Array.from({ length: cols }, cell).join(" | ")} |`; + const head = `| ${Array.from({ length: cols }, (_, i) => `H${i}`).join(" | ")} |`; + const sep = `|${Array.from({ length: cols }, () => "---").join("|")}|`; + return [head, sep, ...Array.from({ length: rowCount }, row)].join("\n"); +} + +/** One line too long for a message */ +function genLongLine(r: Rng): string { + const unit = r.pick(["word ", "x", "<&>", "😀", "ab😀 ", "日本語", "a&b ", "long_snake_name "]); + const target = r.int(3000, 9000); + return `${PROSE_MARK} ` + unit.repeat(Math.ceil(target / unit.length)); +} + +function genLongCodeLine(r: Rng, withFenceLookalikes: boolean): string { + const unit = r.pick(["x", "<&>", "😀", "ab cd ", "a && b || ", withFenceLookalikes ? "``` " : "`` "]); + const target = r.int(3000, 9000); + const line = `${CODE_MARK} ` + unit.repeat(Math.ceil(target / unit.length)); + return "```" + r.pick(FENCE_INFO) + "\n" + line + "\nafter the long line " + CODE_MARK + "\n```"; +} + +/** + * What a generated document contains: + * - "full": everything. + * - "no-tables": no tables. A table split in two repeats its header, so + * what the reader sees is not simply the whole document cut in pieces. + * - "plain-prose": no tables, rules or inline markup either. For tests + * where a message stops in the middle of a line: half an emphasis shows + * its markers, which the whole document would not, and a code line that + * ends like a closing fence has a few characters sent twice. + */ +export type DocumentKind = "full" | "no-tables" | "plain-prose"; + +export function genDocument(seed: number, kind: DocumentKind): string { + const r = rng(seed); + const pool = kind === "plain-prose" ? PLAIN_WORDS : PROSE_WORDS; + const blocks: string[] = []; + const blockCount = r.int(1, 14); + for (let i = 0; i < blockCount; i++) { + const roll = r.next(); + if (roll < 0.3) blocks.push(genProse(r, pool)); + else if (roll < 0.4) blocks.push(genList(r, pool)); + else if (roll < 0.5) blocks.push(genHeaderOrQuote(r, pool)); + else if (roll < 0.7) blocks.push(genFence(r, r.int(0, 25))); + else if (roll < 0.78) blocks.push(genFence(r, r.int(60, 220))); + else if (roll < 0.84) blocks.push(genLongLine(r)); + else if (roll < 0.88) blocks.push(genLongCodeLine(r, kind !== "plain-prose")); + else if (roll < 0.9 && kind !== "plain-prose") blocks.push("---"); + else if (kind === "full") blocks.push(genTable(r, r.chance(0.3) ? r.int(40, 150) : r.int(1, 8))); + else blocks.push(genProse(r, pool)); + } + let md = ""; + for (const block of blocks) md += block + (r.chance(0.7) ? "\n\n" : "\n"); + return r.chance(0.5) ? md : md.trimEnd(); +} + +/** Everything a reader sees, without line breaks (a cut may add or remove one) */ +export function flat(visible: string[]): string { + return visible.join("").replace(/\n/g, ""); +} + +/** Where two strings first differ, with some context, or null if they are equal */ +export function firstDifference(got: string, want: string): string | null { + if (got === want) return null; + let i = 0; + while (i < got.length && got[i] === want[i]) i++; + const show = (s: string) => JSON.stringify(s.slice(Math.max(0, i - 40), i + 40)); + return `at ${i}: got ${show(got)}, want ${show(want)}`; +} diff --git a/test/telegram-format.test.ts b/test/telegram-format.test.ts index 465e4cc..36b21a2 100644 --- a/test/telegram-format.test.ts +++ b/test/telegram-format.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from "vitest"; import { markdownToTelegramHtml, truncateHtmlSafe } from "../src/transports/telegram/format"; +import { telegramHtmlProblem, htmlToVisible } from "./telegram-test-helpers"; describe("markdownToTelegramHtml", () => { it("escapes HTML entities", () => { @@ -16,8 +17,14 @@ describe("markdownToTelegramHtml", () => { expect(markdownToTelegramHtml("hello **world**")).toBe("hello world"); }); - it("converts __bold__", () => { - expect(markdownToTelegramHtml("hello __world__")).toBe("hello world"); + it("converts a __bold phrase__", () => { + expect(markdownToTelegramHtml("hello __big world__")).toBe("hello big world"); + }); + + it("leaves a single __word__ literal", () => { + // This used to be bold. It cannot be told apart from `__init__` or + // `__main__`, which models write far more often and which must stay literal. + expect(markdownToTelegramHtml("hello __world__")).toBe("hello __world__"); }); it("converts *italic*", () => { @@ -294,6 +301,165 @@ describe("markdownToTelegramHtml", () => { }); }); +// Model output the converter used to mangle. Each case was seen in a real answer. +describe("markdownToTelegramHtml — emphasis and tables in model output", () => { + it("leaves arithmetic with spaced asterisks alone", () => { + expect(markdownToTelegramHtml("2 * 3 * 4")).toBe("2 * 3 * 4"); + expect(markdownToTelegramHtml("so a * b = c * d here")).toBe("so a * b = c * d here"); + }); + + it("leaves unspaced arithmetic between numbers alone", () => { + expect(markdownToTelegramHtml("2*3*4 and 2**10")).toBe("2*3*4 and 2**10"); + }); + + it("renders a `* ` bullet with emphasis inside as a bullet with italics", () => { + expect(markdownToTelegramHtml("* a *b* c")).toBe("* a b c"); + }); + + it("renders a whole `* ` list", () => { + const md = "* one\n* two *em* x\n* **three**\n * nested `code`"; + expect(markdownToTelegramHtml(md)).toBe("* one\n* two em x\n* three\n * nested code"); + }); + + it("keeps __init__ and other double-underscore names literal", () => { + expect(markdownToTelegramHtml("__init__")).toBe("__init__"); + expect(markdownToTelegramHtml("call __init__ first")).toBe("call __init__ first"); + expect(markdownToTelegramHtml("see __init__.py and obj.__class__.__name__")).toBe("see __init__.py and obj.__class__.__name__"); + expect(markdownToTelegramHtml('if __name__ == "__main__":')).toBe('if __name__ == "__main__":'); + }); + + it("keeps snake_case_name literal in prose", () => { + expect(markdownToTelegramHtml("set snake_case_name and _private_field_name here")).toBe( + "set snake_case_name and _private_field_name here", + ); + }); + + it("still renders a multi-word __bold phrase__ and _italic_", () => { + expect(markdownToTelegramHtml("a __bold phrase__ and _italic_ word")).toBe("a bold phrase and italic word"); + }); + + it("degrades mis-nested emphasis to valid HTML", () => { + const html = markdownToTelegramHtml("**bold _both** tail_"); + expect(telegramHtmlProblem(html)).toBeNull(); + expect(html).toBe("bold _both tail_"); + }); + + it("renders backslash-escaped asterisks literally", () => { + expect(markdownToTelegramHtml("\\*not emphasis\\*")).toBe("*not emphasis*"); + expect(markdownToTelegramHtml("snake\\_case and \\_x\\_")).toBe("snake_case and _x_"); + expect(markdownToTelegramHtml("a \\`not code\\` b")).toBe("a `not code` b"); + }); + + it("does not open emphasis on a delimiter followed by a space", () => { + expect(markdownToTelegramHtml("a ** b ** c")).toBe("a ** b ** c"); + expect(markdownToTelegramHtml("use *args and **kwargs")).toBe("use *args and **kwargs"); + expect(markdownToTelegramHtml("match *.ts and *.js")).toBe("match *.ts and *.js"); + }); + + it("keeps bold working next to punctuation and code", () => { + expect(markdownToTelegramHtml("**Note**: done.")).toBe("Note: done."); + expect(markdownToTelegramHtml("(**x**)")).toBe("(x)"); + expect(markdownToTelegramHtml("**`code`** and *`it`*")).toBe("codeandit"); + expect(markdownToTelegramHtml("**a *b* c**")).toBe("a b c"); + }); + + it("does not treat markdown inside inline code as formatting", () => { + expect(markdownToTelegramHtml("`**x** _y_ [z](https://e.com)`")).toBe("**x** _y_ [z](https://e.com)"); + }); + + it("formats table cells and keeps the box layout", () => { + const md = [ + "| Name | Notes |", + "|------|-------|", + "| **x** | `a|b` |", + "| [link](https://example.com/p?a=1&b=2) | *it* and ~~old~~ |", + ].join("\n"); + const html = markdownToTelegramHtml(md); + + expect(telegramHtmlProblem(html)).toBeNull(); + expect(html).toContain("x"); + expect(html).toContain("a|b"); + expect(html).toContain('link'); + expect(html).toContain("it"); + expect(html).toContain("old"); + // No markdown markers are left in the cells. + expect(html).not.toContain("**"); + expect(html).not.toContain("`"); + expect(html).not.toContain("]("); + + // Still one box: 6 lines, every row with two cells, all rows the same visible width. + const box = html.match(/([\s\S]*?)<\/pre>/)![1]; + const rows = htmlToVisible(box).split("\n"); + expect(rows.length).toBe(6); + for (const row of [rows[1], rows[3], rows[4]]) { + expect(row.split("│").length - 1).toBe(3); + expect(row.length).toBe(rows[0].length); + } + expect(rows[3]).toBe("│ x │ a|b │"); + expect(rows[4]).toBe("│ link │ it and old │"); + }); + + it("repeats a table cell's link under the table, where Telegram makes it clickable", () => { + const md = "| Doc | Where |\n|---|---|\n| guide | [here](https://example.com/guide) |\n| api | [here](https://example.com/api) |\nafter"; + const html = markdownToTelegramHtml(md); + expect(html.endsWith( + '\nhere\nhere\nafter', + )).toBe(true); + // Inside the box the cell shows the link text only. + expect(html.match(/([\s\S]*?)<\/pre>/)![1]).not.toContain(" { + const html = markdownToTelegramHtml("| A | B |\n|---|---|\n| x \\| y | z |"); + const rows = htmlToVisible(html.match(/([\s\S]*?)<\/pre>/)![1]).split("\n"); + expect(rows[3]).toContain("x | y"); + expect(rows[3].split("│").length - 1).toBe(3); + }); + + it("emits well-formed HTML for awkward emphasis", () => { + const cases = [ + "**bold _both** tail_", + "*a **b* c**", + "~~s **b~~ c**", + "_a *b_ c*", + "**unclosed", + "*a* **b** ***c*** ****d****", + "# **Title** with `code` and [l](https://e.com)", + "> quote with **bold _mix** tail_", + "[**bold** link](https://e.com) and [bad](ftp://x)\n\nOutro")).toBe(true); + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("reopens an indented or longer fence exactly as it was written", () => { + const code = Array.from({ length: 150 }, (_, i) => ` row ${i} ${"z".repeat(40)}`); + const md = "1. Step\n ````yaml title\n" + code.join("\n") + "\n ````\n2. Next"; + const chunks = splitMarkdownForTelegram(md); + + expect(chunks.length).toBeGreaterThan(1); + expect(chunks[0].suffix).toBe(" ````"); + expect(chunks[1].prefix).toBe(" ````yaml title\n"); + for (const c of chunks) { + expect(outsidePre(c.html)).not.toContain("row "); + expect(c.html).not.toContain("`"); + } + }); + + it("does not leave an empty code block on either side of a cut", () => { + // The block's opening line is the last line that fits the first message. + const before = Array.from({ length: 45 }, (_, i) => `para ${i} ${"p".repeat(80)}`).join("\n"); + const code = Array.from({ length: 60 }, (_, i) => `code ${i} ${"c".repeat(80)}`).join("\n"); + const md = before + "\n```js\n" + code + "\n```\nend"; + const chunks = splitMarkdownForTelegram(md); + + for (const c of chunks) { + expect(c.html).not.toContain(""); + expect(c.html).not.toContain("& more", + "a < b **c > d** & e", + "***", + "* * *", + "_ _ _", + "** **", + ]; + for (const md of cases) { + expect(telegramHtmlProblem(markdownToTelegramHtml(md)), md).toBeNull(); + } + }); +}); + +describe("markdownToTelegramHtml — fenced code", () => { + it("renders a fence that is still open as a code block", () => { + expect(markdownToTelegramHtml("```ts\nconst a = __x__;")).toBe(" const a = __x__;"); + }); + + it("does not end a block on backticks inside a code line", () => { + const md = "```js\nconst fence = \"```\";\nconst b = 2;\n```\nafter"; + expect(markdownToTelegramHtml(md)).toBe('const fence = "```";\nconst b = 2;\nafter'); + }); + + it("lets a longer fence hold a shorter one", () => { + const md = "````md\n```js\nx\n```\n````"; + expect(markdownToTelegramHtml(md)).toBe("```js\nx\n```"); + }); + + it("renders a fence indented under a list item, keeping the code as written", () => { + const md = "1. Run:\n ```bash\n npm test\n ```\n2. Done"; + expect(markdownToTelegramHtml(md)).toBe("1. Run:\nnpm test\n2. Done"); + }); +}); + describe("truncateHtmlSafe", () => { it("returns short html unchanged", () => { expect(truncateHtmlSafe("hello", 100)).toBe("hello"); diff --git a/test/telegram-split.test.ts b/test/telegram-split.test.ts new file mode 100644 index 0000000..9756020 --- /dev/null +++ b/test/telegram-split.test.ts @@ -0,0 +1,354 @@ +/** + * test/telegram-split.test.ts — splitting markdown into Telegram messages. + * + * The splitter must never lose a character, never produce a message longer + * than Telegram accepts, and keep a code block a code block in every message + * it spans. The last block checks those properties on a few hundred generated + * documents; the generator (telegram-doc-generator.ts) is seeded, so a + * failure names the seed that reproduces it. + */ + +import { describe, it, expect } from "vitest"; +import { + TELEGRAM_MESSAGE_LIMIT, + markdownToTelegramHtml, + resumeMarkdownAt, + splitMarkdownForTelegram, + takeMarkdownChunk, + type MarkdownChunk, +} from "../src/transports/telegram/format"; +import { htmlToVisible, outsidePre, telegramHtmlProblem } from "./telegram-test-helpers"; +import { CODE_MARK, PROSE_MARK, genDocument } from "./telegram-doc-generator"; + +const LIMIT = TELEGRAM_MESSAGE_LIMIT; + +/** The source each chunk covers, in order */ +function sources(md: string, chunks: MarkdownChunk[]): string[] { + return chunks.map((c) => md.slice(c.start, c.end)); +} + +describe("splitMarkdownForTelegram", () => { + it("returns one chunk for a short text, with nothing added", () => { + const chunks = splitMarkdownForTelegram("**hello** world"); + expect(chunks).toEqual([ + { start: 0, end: 15, prefix: "", suffix: "", text: "**hello** world", html: "hello world" }, + ]); + }); + + it("returns no chunks for an empty text", () => { + expect(splitMarkdownForTelegram("")).toEqual([]); + }); + + it("measures the rendered HTML, not the source", () => { + // 3,900 source characters that render to 15,600. + const md = Array.from({ length: 100 }, () => "<".repeat(39)).join("\n"); + const chunks = splitMarkdownForTelegram(md); + expect(chunks.length).toBeGreaterThanOrEqual(4); + for (const c of chunks) expect(c.html.length).toBeLessThanOrEqual(LIMIT); + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("keeps the markdown source within the limit too, for the plain-text fallback", () => { + // 6,000 source characters that render to 3,000. + const md = "\\*".repeat(3000); + const chunks = splitMarkdownForTelegram(md); + expect(chunks.length).toBe(2); + for (const c of chunks) expect(c.text.length).toBeLessThanOrEqual(LIMIT); + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("cuts at a line break and keeps the newline with the earlier chunk", () => { + const lines = Array.from({ length: 200 }, (_, i) => `line ${i} ${"x".repeat(40)}`); + const md = lines.join("\n"); + const chunks = splitMarkdownForTelegram(md); + expect(chunks.length).toBeGreaterThan(1); + for (const c of chunks.slice(0, -1)) expect(md[c.end - 1]).toBe("\n"); + for (const c of chunks.slice(1)) expect(md.slice(c.start).startsWith("line ")).toBe(true); + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("closes a code block at the end of a chunk and reopens it with the same info string", () => { + const code = Array.from({ length: 200 }, (_, i) => `const v${i} = compute(${i}); // ${"y".repeat(20)}`); + const md = "Intro\n\n```ts\n" + code.join("\n") + "\n```\n\nOutro"; + const chunks = splitMarkdownForTelegram(md); + + expect(chunks.length).toBeGreaterThanOrEqual(3); + expect(chunks[0].prefix).toBe(""); + expect(chunks[0].suffix).toBe("```"); + for (const c of chunks.slice(1, -1)) { + expect(c.prefix).toBe("```ts\n"); + expect(c.suffix).toBe("```"); + expect(c.html.startsWith("const v")).toBe(true); + expect(c.html.endsWith("")).toBe(true); + } + const last = chunks[chunks.length - 1]; + expect(last.prefix).toBe("```ts\n"); + expect(last.suffix).toBe(""); + expect(last.html.endsWith("\n"); + } + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("repeats a table's header when the table spans chunks", () => { + const rows = Array.from({ length: 120 }, (_, i) => `| item ${i} | ${"v".repeat(30)} |`); + const md = "| Name | Value |\n|------|-------|\n" + rows.join("\n"); + const chunks = splitMarkdownForTelegram(md); + + expect(chunks.length).toBeGreaterThan(1); + for (const c of chunks.slice(1)) { + expect(c.prefix).toBe("| Name | Value |\n|------|-------|\n"); + } + for (const c of chunks) { + expect(c.html.startsWith("┌")).toBe(true); + expect(c.html).toContain("│ Name "); + expect(c.html).not.toContain("|"); + } + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("cuts a line that is too long at a space", () => { + const md = Array.from({ length: 1200 }, (_, i) => `word${i}`).join(" "); + const chunks = splitMarkdownForTelegram(md); + + expect(chunks.length).toBeGreaterThan(1); + for (const c of chunks.slice(0, -1)) expect(md[c.end - 1]).toBe(" "); + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("cuts a line without spaces wherever it has to, but never inside a surrogate pair", () => { + const md = "😀".repeat(3000) + "a" + "😀".repeat(3000); + const chunks = splitMarkdownForTelegram(md); + + expect(chunks.length).toBeGreaterThanOrEqual(3); + for (const source of sources(md, chunks)) { + expect(source.isWellFormed()).toBe(true); + } + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("never cuts an HTML entity", () => { + const md = "&<>".repeat(3000); + const chunks = splitMarkdownForTelegram(md); + + for (const c of chunks) { + expect(c.html.length).toBeLessThanOrEqual(LIMIT); + expect(telegramHtmlProblem(c.html)).toBeNull(); + } + expect(chunks.map((c) => htmlToVisible(c.html)).join("")).toBe(md); + }); + + it("does not let a piece of a long code line read as the closing fence", () => { + // Cut at a space, the tail of this line would be "```". + const line = "x".repeat(4050) + " ```"; + const md = "```\n" + line + "\nstill code\n```\nprose"; + const chunks = splitMarkdownForTelegram(md); + + for (const c of chunks) expect(outsidePre(c.html)).not.toContain("still code"); + expect(chunks[chunks.length - 1].html.endsWith("\nprose")).toBe(true); + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("does not let a piece of a long prose line read as an opening fence", () => { + const line = "x".repeat(4050) + " ```js"; + const md = line + "\nstill prose"; + const chunks = splitMarkdownForTelegram(md); + + for (const c of chunks) expect(c.html).not.toContain(""); + expect(sources(md, chunks).join("")).toBe(md); + }); + + it("continues inside a code block when given the block's opening line as prefix", () => { + const chunks = splitMarkdownForTelegram("b = 2\n```\nafter", LIMIT, "```py\n"); + expect(chunks.length).toBe(1); + expect(chunks[0].html).toBe("b = 2\nafter"); + }); + + it("works with a small limit", () => { + const md = "Intro line\n```sh\n" + Array.from({ length: 30 }, (_, i) => `echo ${i}`).join("\n") + "\n```\nDone"; + const chunks = splitMarkdownForTelegram(md, 80); + for (const c of chunks) { + expect(c.html.length).toBeLessThanOrEqual(80); + expect(outsidePre(c.html)).not.toContain("echo"); + } + expect(sources(md, chunks).join("")).toBe(md); + }); +}); + +describe("takeMarkdownChunk", () => { + it("takes the whole body when it fits", () => { + const taken = takeMarkdownChunk("", "hello"); + expect(taken).toEqual({ length: 5, prefix: "", suffix: "", text: "hello", html: "hello", nextPrefix: "" }); + }); + + it("closes a code block the body leaves open", () => { + const taken = takeMarkdownChunk("", "```ts\nconst a = 1;"); + expect(taken.suffix).toBe("\n```"); + expect(taken.html).toBe("const a = 1;"); + expect(taken.nextPrefix).toBe("```ts\n"); + }); + + it("says what the rest of the text needs in front of it", () => { + const body = "```ts\n" + Array.from({ length: 200 }, (_, i) => `line ${i} ${"q".repeat(30)}`).join("\n"); + const taken = takeMarkdownChunk("", body); + expect(taken.length).toBeLessThan(body.length); + expect(body[taken.length - 1]).toBe("\n"); + expect(taken.nextPrefix).toBe("```ts\n"); + + const next = takeMarkdownChunk(taken.nextPrefix, body.slice(taken.length)); + expect(next.html.startsWith("line ")).toBe(true); + }); +}); + +describe("resumeMarkdownAt", () => { + const body = "intro\n```ts\nconst a = 1;\nconst b = 2;\n```\nend"; + + it("continues prose where it stopped", () => { + expect(resumeMarkdownAt("", body, 3)).toEqual({ offset: 3, prefix: "" }); + }); + + it("reopens the code block when it stopped inside one", () => { + const at = body.indexOf("const b"); + expect(resumeMarkdownAt("", body, at)).toEqual({ offset: at, prefix: "```ts\n" }); + expect(resumeMarkdownAt("", body, at + 4)).toEqual({ offset: at + 4, prefix: "```ts\n" }); + }); + + it("starts after an opening fence it stopped inside", () => { + const at = body.indexOf("```ts") + 2; + expect(resumeMarkdownAt("", body, at)).toEqual({ offset: body.indexOf("const a"), prefix: "```ts\n" }); + }); + + it("skips the closing fence it stopped at", () => { + const at = body.indexOf("```\nend"); + expect(resumeMarkdownAt("", body, at)).toEqual({ offset: body.indexOf("end"), prefix: "" }); + }); + + it("takes the prefix into account", () => { + expect(resumeMarkdownAt("```py\n", "x = 1\ny = 2\n```\nz", 6)).toEqual({ offset: 6, prefix: "```py\n" }); + }); + + it("keeps the rest of a line literal when it would read as a quote, header, rule or fence", () => { + for (const rest of ["> b", "# b", "---", "```js"]) { + const text = `a ${rest}\nnext`; + const resume = resumeMarkdownAt("", text, 2); + expect(resume).toEqual({ offset: 2, prefix: "\\" }); + const [chunk] = splitMarkdownForTelegram(text.slice(resume.offset), LIMIT, resume.prefix); + expect(htmlToVisible(chunk.html)).toBe(`${rest}\nnext`); + } + }); + + it("steps back inside a code line whose rest would read as the closing fence", () => { + const code = "```\nx = 1 ```\ny = 2\n```"; + const at = code.indexOf(" ```") + 1; + const resume = resumeMarkdownAt("", code, at); + expect(resume).toEqual({ offset: code.indexOf("1 ```"), prefix: "```\n" }); + const [chunk] = splitMarkdownForTelegram(code.slice(resume.offset), LIMIT, resume.prefix); + expect(chunk.html).toBe("1 ```\ny = 2"); + }); +}); + +// ── Generated documents ─────────────────────────────── + +/** True if every code fence in `md` that opens also closes (checked independently of the converter) */ +function fencesBalanced(md: string): boolean { + let open: number | null = null; + for (const line of md.split("\n")) { + if (open === null) { + const m = /^[ \t]*(`{3,})[^`]*$/.exec(line); + if (m) open = m[1].length; + } else { + const m = /^[ \t]*(`{3,})\s*$/.exec(line); + if (m && m[1].length >= open) open = null; + } + } + return open === null; +} + +/** Check one split against the properties. Returns the first problem, or null. */ +function splitProblem(md: string, chunks: MarkdownChunk[], limit: number): string | null { + let pos = 0; + for (const [i, c] of chunks.entries()) { + const at = `chunk ${i} of ${chunks.length}`; + if (c.start !== pos) return `${at} starts at ${c.start}, expected ${pos}`; + if (c.end <= c.start) return `${at} is empty`; + pos = c.end; + const source = md.slice(c.start, c.end); + if (c.text !== c.prefix + source + c.suffix) return `${at}: text is not prefix + source + suffix`; + if (c.html !== markdownToTelegramHtml(c.text)) return `${at}: html is not the rendering of text`; + if (c.html.length > limit) return `${at}: html is ${c.html.length} long`; + if (c.text.length > limit) return `${at}: text is ${c.text.length} long`; + if (!source.isWellFormed()) return `${at}: source cuts a surrogate pair`; + if (!fencesBalanced(c.text)) return `${at}: unbalanced fences`; + const problem = telegramHtmlProblem(c.html); + if (problem) return `${at}: ${problem}`; + if (outsidePre(c.html).includes(CODE_MARK)) return `${at}: code outside a code block`; + const blocks = c.html.match(/[\s\S]*?<\/pre>/g) ?? []; + if (blocks.some((block) => block.includes(PROSE_MARK))) return `${at}: prose inside a code block`; + } + if (pos !== md.length) return `chunks end at ${pos}, text is ${md.length} long`; + if (sources(md, chunks).join("") !== md) return "concatenated sources differ from the text"; + return null; +} + +describe("splitMarkdownForTelegram — generated documents", () => { + it("holds its properties for 400 documents at Telegram's limit", () => { + for (let seed = 1; seed <= 400; seed++) { + const md = genDocument(seed, "full"); + const chunks = splitMarkdownForTelegram(md); + expect(splitProblem(md, chunks, LIMIT), `seed ${seed}`).toBeNull(); + } + }); + + it("holds its properties for 150 documents at smaller limits", () => { + for (let seed = 1001; seed <= 1150; seed++) { + const limit = [600, 1000, 2500][seed % 3]; + const md = genDocument(seed, "full"); + const chunks = splitMarkdownForTelegram(md, limit); + expect(splitProblem(md, chunks, limit), `seed ${seed}, limit ${limit}`).toBeNull(); + } + }); + + it("covers what it claims to: long documents, split code blocks, split tables, hard cuts", () => { + let split = 0, reopenedFence = 0, repeatedTable = 0, hardCut = 0, longest = 0; + for (let seed = 1; seed <= 400; seed++) { + const md = genDocument(seed, "full"); + const chunks = splitMarkdownForTelegram(md); + longest = Math.max(longest, md.length); + if (chunks.length > 1) split++; + if (chunks.some((c) => c.prefix.startsWith("```") || c.prefix.startsWith(" ```"))) reopenedFence++; + if (chunks.some((c) => c.prefix.startsWith("|"))) repeatedTable++; + if (chunks.slice(0, -1).some((c) => md[c.end - 1] !== "\n")) hardCut++; + } + expect(split).toBeGreaterThan(250); + expect(reopenedFence).toBeGreaterThan(100); + expect(repeatedTable).toBeGreaterThan(20); + expect(hardCut).toBeGreaterThan(100); + expect(longest).toBeGreaterThan(30_000); + }); +}); diff --git a/test/telegram-test-helpers.ts b/test/telegram-test-helpers.ts new file mode 100644 index 0000000..c7944f2 --- /dev/null +++ b/test/telegram-test-helpers.ts @@ -0,0 +1,158 @@ +/** + * Shared doubles for the Telegram rendering and delivery tests. + * + * `fakeTelegram` stands in for a Chat SDK thread backed by the Telegram + * adapter. It records every Bot API call and keeps what each message would + * show after its edits, so a test can assert on what the reader ends up with. + */ + +export const TELEGRAM_LIMIT = 4096; + +export interface TelegramCall { + method: string; + payload: any; + /** Clock value when the call was made (0 without a clock) */ + at: number; + /** True when the fake rejected the call */ + failed: boolean; +} + +export interface FakeTelegram { + id: string; + adapter: { telegramFetch: (method: string, payload: any) => Promise}; + calls: TelegramCall[]; + /** Final content of each message, in the order the messages were created */ + messages: () => Array<{ id: number; text: string; html: boolean }>; + /** What a reader sees: every message's visible text, in order */ + visible: () => string[]; +} + +export interface FakeTelegramOptions { + chatId?: string; + /** Return an error to reject the call (after it is recorded) */ + fail?: (call: TelegramCall, index: number) => unknown; + /** Clock used to stamp calls */ + now?: () => number; +} + +export function fakeTelegram(opts: FakeTelegramOptions = {}): FakeTelegram { + const chatId = opts.chatId ?? "12345"; + const calls: TelegramCall[] = []; + const state = new Map (); + let nextId = 1; + + const telegramFetch = async (method: string, payload: any) => { + const call: TelegramCall = { method, payload, at: opts.now?.() ?? 0, failed: false }; + calls.push(call); + const err = opts.fail?.(call, calls.length - 1); + if (err) { + call.failed = true; + throw err; + } + const html = payload.parse_mode === "HTML"; + if (method === "sendMessage") { + const id = nextId++; + state.set(id, { text: payload.text, html }); + return { message_id: id, chat: { id: Number(chatId) } }; + } + if (method === "editMessageText") { + state.set(payload.message_id, { text: payload.text, html }); + return true; + } + return true; + }; + + const messages = () => [...state.entries()].map(([id, m]) => ({ id, ...m })); + + return { + id: `telegram:${chatId}`, + adapter: { telegramFetch }, + calls, + messages, + visible: () => messages().map((m) => (m.html ? htmlToVisible(m.text) : m.text)), + }; +} + +/** The error the Telegram adapter throws on HTTP 429 */ +export function rateLimitError(retryAfterSeconds?: number): Error { + const err = new Error(`Rate limited by telegram, retry after ${retryAfterSeconds}s`) as Error & { retryAfter?: number }; + err.name = "AdapterRateLimitError"; + err.retryAfter = retryAfterSeconds; + return err; +} + +/** A clock and a sleep that only moves that clock */ +export function fakeClock(start = 1_000_000) { + let t = start; + const sleeps: number[] = []; + return { + now: () => t, + advance: (ms: number) => { t += ms; }, + sleep: async (ms: number) => { sleeps.push(ms); t += ms; }, + sleeps, + }; +} + +/** Strip Telegram HTML down to the text a reader sees */ +export function htmlToVisible(html: string): string { + return html + .replace(/<[^>]+>/g, "") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/&/g, "&"); +} + +/** The parts of an HTML message that are not inside a block */ +export function outsidePre(html: string): string { + return html.replace(/[\s\S]*?<\/pre>/g, ""); +} + +/** + * Check that a string is well-formed for Telegram's HTML subset: only the + * tags Telegram accepts, properly nested and closed, and no bare `<`, `>` + * or `&`. Returns a description of the first problem, or null. + */ +export function telegramHtmlProblem(html: string): string | null { + const allowed = new Set(["b", "i", "u", "s", "code", "pre", "a", "blockquote"]); + const stack: string[] = []; + const re = /<(\/?)([a-zA-Z]+)((?:\s+[a-zA-Z-]+="[^"<>]*")*)>|[<>]|&(?!(?:amp|lt|gt|quot);)/g; + let m: RegExpExecArray | null; + while ((m = re.exec(html))) { + if (m[2] === undefined) return `bare "${m[0]}" at ${m.index}`; + const tag = m[2]; + if (!allowed.has(tag)) return `tag <${tag}> is not in Telegram's subset`; + if (m[1]) { + const open = stack.pop(); + if (open !== tag) return `${tag}> at ${m.index} closes <${open ?? "nothing"}>`; + } else { + stack.push(tag); + } + } + return stack.length ? `unclosed <${stack[stack.length - 1]}>` : null; +} + +/** Yield the text in pieces of `size` characters, calling `tick` before each */ +export async function* inPieces(text: string, size: number, tick?: () => void): AsyncIterable{ + for (let i = 0; i < text.length; i += size) { + tick?.(); + yield text.slice(i, i + size); + } +} + +/** + * An answer like the one that lost lines: prose, then a long code block + * whose lines grow when HTML-escaped, then prose. + */ +export function longAnswerWithCode(codeLines = 140): { markdown: string; code: string[] } { + const code: string[] = []; + for (let i = 1; i <= codeLines; i++) { + code.push(` const cache${i}: Map > = new Map(); // entry ${i} & its `); + } + const intro = Array.from({ length: 6 }, (_, i) => + `Paragraph ${i + 1}: the registry keeps one cache per tenant and rebuilds it lazily, so a cold start costs a full scan.`, + ).join("\n\n"); + const outro = "That is the whole change. **Run the migration** before deploying, then check `cache_hits` in the dashboard."; + const markdown = `${intro}\n\n\`\`\`ts\n${code.join("\n")}\n\`\`\`\n\n${outro}\n`; + return { markdown, code }; +} diff --git a/test/unit.test.ts b/test/unit.test.ts index efeb671..6620676 100644 --- a/test/unit.test.ts +++ b/test/unit.test.ts @@ -59,6 +59,16 @@ describe("splitMessage", () => { expect(chunks).toEqual(["a", "b", "c"]); }); + it("does not cut a surrogate pair in half", () => { + const text = "ab" + "😀".repeat(10); + for (const maxLen of [3, 4, 5, 7]) { + const chunks = splitMessage(text, maxLen); + expect(chunks.join("")).toBe(text); + expect(chunks.every((c) => c.length <= maxLen)).toBe(true); + expect(chunks.every((c) => c.isWellFormed())).toBe(true); + } + }); + it("does not infinite loop on leading newline with small maxLen", () => { const text = "\nhello world"; const chunks = splitMessage(text, 5); From 5a3b58e088c4a1fa6af33b091076110221c5c951 Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:20:17 +0200 Subject: [PATCH 2/8] telegram: stop dropping text at the message limit and after a rate limit Three ways an answer reached Telegram incomplete: 1. Text was cut at 4096 characters. The markdown was split at 3800 source characters, converted, and the HTML truncated to fit; escaping and tags push a chunk past the limit, so lines were silently dropped. The stream committed a prefix by a ratio estimate, lost lines and started the next message mid-line. Now the markdown is split so that each chunk's rendered HTML fits, and nothing is truncated. The stream closes a message at the last line break that fits and continues the next one from that exact offset. 2. A code block split across messages rendered as prose, because the converter needs both fences in one chunk. The splitter closes the block at the end of a chunk and reopens it with the same opening line. A line longer than the limit inside a block is cut inside the line. 3. After one HTTP 429 during streaming, every later delta retried at once (the throttle only counted successful edits) and the final edit failed silently, leaving the message at whatever it showed. Now a rate limit is recorded and nothing is sent before Telegram's retry-after has passed; the throttle counts failed attempts too. The last edit of a message waits for the retry-after, 30 seconds at most, and tries again. If the message still cannot be edited, the text it does not show is posted as a new message. Posting waits out a rate limit the same way instead of dropping the message. Edits are spaced 1100 ms apart (was 600), and 3100 ms in groups: the Chat SDK adapter's own floors. An edit Telegram refuses as "message is not modified" counts as delivered instead of falling back to plain text. postTelegramHtml and handleTelegramHtmlStream take an optional clock and sleep, so tests do not wait. --- src/transports/telegram/html.ts | 448 ++++++++++++++++++++---------- test/telegram-delivery.test.ts | 464 ++++++++++++++++++++++++++++++++ 2 files changed, 765 insertions(+), 147 deletions(-) create mode 100644 test/telegram-delivery.test.ts diff --git a/src/transports/telegram/html.ts b/src/transports/telegram/html.ts index 1b17dea..177451f 100644 --- a/src/transports/telegram/html.ts +++ b/src/transports/telegram/html.ts @@ -6,16 +6,51 @@ * * Chat SDK remains responsible for: incoming messages, subscriptions, * typing indicators, command handling, authorization, message history. + * + * Two rules hold for everything sent from here: + * - Nothing is truncated. A text too long for one message is split in its + * markdown source, so that each piece renders within Telegram's limit. + * - A rate limit (HTTP 429) is waited out, not ignored. */ -import { markdownToTelegramHtml, truncateHtmlSafe } from "./format"; -import { splitMessage } from "../../util"; +import { + TELEGRAM_MESSAGE_LIMIT, + markdownToTelegramHtml, + resumeMarkdownAt, + splitMarkdownForTelegram, + takeMarkdownChunk, + type TakenChunk, +} from "./format"; + +/** + * Shortest time between two updates of a streaming message in a private + * chat (ms). The Chat SDK's Telegram adapter uses the same floor; editing + * faster earns a 429. + */ +export const STREAM_EDIT_INTERVAL_MS = 1100; -/** Max Telegram message length */ -const TELEGRAM_LIMIT = 4096; +/** + * The same for groups and channels, where Telegram allows a bot about 20 + * messages a minute. Also the Chat SDK's floor. + */ +export const STREAM_EDIT_INTERVAL_GROUP_MS = 3100; -/** Streaming edit interval (ms) */ -const STREAM_EDIT_INTERVAL_MS = 600; +/** Longest time spent waiting out rate limits for one call that must get through (ms) */ +export const MAX_RATE_LIMIT_WAIT_MS = 30_000; + +/** Tries for one call that must get through */ +const MAX_DELIVERY_ATTEMPTS = 4; + +/** Wait used when Telegram reports a rate limit without a retry-after (ms) */ +const DEFAULT_RETRY_AFTER_MS = 1000; + +/** The clock and the sleep used for pacing. Tests replace them. */ +export interface TelegramDeliveryOptions { + /** Current time in ms. Defaults to `Date.now`. */ + now?: () => number; + /** Wait for `ms`. Defaults to a timer. */ + sleep?: (ms: number) => Promise ; +} /** Check if a Chat SDK thread is backed by the Telegram adapter */ export function isTelegramThread(thread: any): boolean { @@ -48,199 +83,318 @@ function basePayload(chatId: string, messageThreadId?: number) { }; } -/** Send one HTML message, falling back to plain text on parse error */ +/** + * How long Telegram asked us to wait, in ms, or null if `err` is not a rate + * limit. The adapter throws `AdapterRateLimitError` with `retryAfter` in + * seconds; that class lives in a package we do not depend on, so it is + * recognised by shape. + */ +export function rateLimitDelayMs(err: unknown): number | null { + if (!err || typeof err !== "object") return null; + const { retryAfter, name } = err as { retryAfter?: unknown; name?: unknown }; + if (typeof retryAfter === "number" && Number.isFinite(retryAfter)) { + return retryAfter > 0 ? retryAfter * 1000 : DEFAULT_RETRY_AFTER_MS; + } + return name === "AdapterRateLimitError" ? DEFAULT_RETRY_AFTER_MS : null; +} + +/** Telegram refuses an edit that would not change the message. The message is as wanted. */ +function isNotModified(err: unknown): boolean { + return /message is not modified/i.test(String((err as Error | undefined)?.message ?? "")); +} + +/** Remembers when Telegram will accept calls again, and waits for it */ +class RateLimiter { + readonly now: () => number; + private readonly sleep: (ms: number) => Promise ; + /** Time before which Telegram asked for no more calls */ + private blockedUntil = 0; + + constructor(options: TelegramDeliveryOptions) { + this.now = options.now ?? Date.now; + this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + } + + /** Record a rate limit. Returns false if `err` is some other error. */ + note(err: unknown): boolean { + const delay = rateLimitDelayMs(err); + if (delay === null) return false; + this.blockedUntil = Math.max(this.blockedUntil, this.now() + delay); + return true; + } + + blocked(): boolean { + return this.now() < this.blockedUntil; + } + + /** + * Make a call that must get through. Waits until Telegram accepts calls + * again, and after a rate limit waits and tries again, for at most + * `MAX_RATE_LIMIT_WAIT_MS` in total. Throws the last error after that, and + * any error that is not a rate limit at once. + */ + async deliver (call: () => Promise ): Promise { + let budget = MAX_RATE_LIMIT_WAIT_MS; + for (let attempt = 1; ; attempt++) { + const wait = Math.min(this.blockedUntil - this.now(), budget); + if (wait > 0) { + await this.sleep(wait); + budget -= wait; + } + try { + const result = await call(); + this.blockedUntil = 0; + return result; + } catch (err) { + if (!this.note(err) || budget <= 0 || attempt >= MAX_DELIVERY_ATTEMPTS) throw err; + } + } + } +} + +/** + * Send one HTML message, falling back to plain text on parse error. + * A rate limit is waited out (see `RateLimiter.deliver`). + */ async function sendHtmlOrPlain( + limiter: RateLimiter, adapter: any, chatId: string, messageThreadId: number | undefined, html: string, plainFallback: string, ): Promise { - try { - await adapter.telegramFetch("sendMessage", { - ...basePayload(chatId, messageThreadId), - text: html, - parse_mode: "HTML", - }); - } catch { - try { - await adapter.telegramFetch("sendMessage", { + const send = (text: string, parseMode?: "HTML") => + limiter.deliver(() => + adapter.telegramFetch("sendMessage", { ...basePayload(chatId, messageThreadId), - text: plainFallback, - }); - } catch (err) { - console.error(`[roundhouse] Telegram sendMessage failed:`, (err as Error).message); - } + text, + ...(parseMode && { parse_mode: parseMode }), + }), + ); + const giveUp = (err: unknown) => + console.error( + `[roundhouse] Telegram sendMessage failed, ${plainFallback.length} characters not delivered:`, + (err as Error).message, + ); + try { + await send(html, "HTML"); + return; + } catch (err) { + // Still rate limited after waiting: plain text would be refused as well. + if (rateLimitDelayMs(err) !== null) return giveUp(err); + } + try { + await send(plainFallback); + } catch (err) { + giveUp(err); } } /** * Post markdown as Telegram HTML, with chunking and fallback. - * Splits markdown into chunks before conversion so each chunk's HTML stays within limits. + * The markdown is split so that each chunk's HTML fits one message; a code + * block that spans chunks is closed and reopened, so it stays a code block. */ -export async function postTelegramHtml(thread: any, markdown: string): Promise { +export async function postTelegramHtml( + thread: any, + markdown: string, + options: TelegramDeliveryOptions = {}, +): Promise { const { chatId, messageThreadId } = parseTelegramThreadId(thread.id); + const limiter = new RateLimiter(options); + await postChunks(limiter, thread.adapter, chatId, messageThreadId, markdown, ""); +} - // Split before conversion — HTML expansion is usually modest - for (const chunk of splitMessage(markdown, 3800)) { - const html = markdownToTelegramHtml(chunk); - const safeHtml = truncateHtmlSafe(html, TELEGRAM_LIMIT); - await sendHtmlOrPlain(thread.adapter, chatId, messageThreadId, safeHtml, chunk); +/** Post `markdown` as one message per chunk. `prefix` is as in `takeMarkdownChunk`. */ +async function postChunks( + limiter: RateLimiter, + adapter: any, + chatId: string, + messageThreadId: number | undefined, + markdown: string, + prefix: string, +): Promise { + for (const chunk of splitMarkdownForTelegram(markdown, TELEGRAM_MESSAGE_LIMIT, prefix)) { + // Telegram refuses a message with nothing to show. + if (!markdown.slice(chunk.start, chunk.end).trim()) continue; + await sendHtmlOrPlain(limiter, adapter, chatId, messageThreadId, chunk.html, chunk.text); } } /** * Stream agent text as Telegram HTML using sendMessage + editMessageText. * - * For responses under 4096 chars: single message with progressive edits. - * For longer responses: finalize current message and start new ones via postTelegramHtml. + * The text grows in one message ("bubble") that is edited as it arrives, at + * most once per `STREAM_EDIT_INTERVAL_MS` (`STREAM_EDIT_INTERVAL_GROUP_MS` + * in a group). When it no longer fits one + * message, the bubble is closed at the last line break that fits and the + * text after it starts the next bubble, so the bubbles together hold the + * whole text and each starts on a new line. + * + * An update in the middle of the stream may be skipped or refused; the next + * one makes up for it. The last update of a bubble may not: after a rate + * limit it is tried again once Telegram allows, and if the bubble still + * cannot be edited, the text it does not show is posted as a new message. */ export async function handleTelegramHtmlStream( thread: any, stream: AsyncIterable , + options: TelegramDeliveryOptions = {}, ): Promise { const { chatId, messageThreadId } = parseTelegramThreadId(thread.id); + const limiter = new RateLimiter(options); + const base = basePayload(chatId, messageThreadId); + // Groups and channels have negative chat ids. + const editInterval = chatId.startsWith("-") ? STREAM_EDIT_INTERVAL_GROUP_MS : STREAM_EDIT_INTERVAL_MS; let accumulated = ""; + /** Source offset up to which the text is in closed bubbles */ + let committed = 0; + /** What the open bubble continues from: see `takeMarkdownChunk` */ + let prefix = ""; + /** The open bubble's message, once Telegram has accepted one */ let messageId: number | null = null; - let lastEditContent = ""; - let lastEditTime = 0; - /** Content already committed to sent messages (for overflow handling) */ - let committedLength = 0; + /** The text Telegram last accepted for the open bubble */ + let shown = ""; + /** Source offset up to which the open bubble shows the text */ + let shownEnd = 0; + /** When Telegram was last called for the open bubble, whether or not it worked */ + let lastAttemptAt = Number.NEGATIVE_INFINITY; + + /** The source of the open bubble */ + const body = () => accumulated.slice(committed); - const sendInitial = async (html: string): Promise => { + const send = async (text: string, html: boolean): Promise => { const result = await thread.adapter.telegramFetch("sendMessage", { - ...basePayload(chatId, messageThreadId), - text: html, - parse_mode: "HTML", + ...base, + text, + ...(html && { parse_mode: "HTML" }), }); return result.message_id; }; - const editMessage = async (html: string): Promise => { - if (!messageId || html === lastEditContent) return true; + const edit = (text: string, html: boolean): Promise => + thread.adapter.telegramFetch("editMessageText", { + ...base, + message_id: messageId, + text, + ...(html && { parse_mode: "HTML" }), + }); + + /** The open bubble as HTML, or null when it has outgrown one message */ + const renderOpen = (): string | null => { + const text = prefix + body(); + if (text.length > TELEGRAM_MESSAGE_LIMIT) return null; + const html = markdownToTelegramHtml(text); + return html.length > TELEGRAM_MESSAGE_LIMIT ? null : html; + }; + + /** Show the open bubble's current text, if it is time for an update */ + const updateBubble = async (html: string): Promise => { + if (!body().trim() || !html.trim()) return; + if (messageId !== null && html === shown) return; + if (limiter.blocked() || limiter.now() - lastAttemptAt < editInterval) return; try { - await thread.adapter.telegramFetch("editMessageText", { - ...basePayload(chatId, messageThreadId), - message_id: messageId, - text: html, - parse_mode: "HTML", - }); - lastEditContent = html; - lastEditTime = Date.now(); - return true; - } catch { - // Telegram may reject if content hasn't changed or HTML is temporarily invalid - return false; + if (messageId === null) messageId = await send(html, true); + else await edit(html, true); + shown = html; + shownEnd = accumulated.length; + } catch (err) { + // After a rate limit the next update waits for Telegram. A refused edit + // is left to the next update too: the HTML of a half-written answer can + // be invalid, and Telegram refuses an edit that changes nothing. + if (!limiter.note(err) && messageId === null) { + // Telegram refused the HTML: open the bubble with the markdown source. + const plain = prefix + body(); + try { + messageId = await send(plain, false); + shown = plain; + shownEnd = accumulated.length; + } catch (plainErr) { + if (!limiter.note(plainErr)) { + console.error(`[roundhouse] Telegram stream initial send failed:`, (plainErr as Error).message); + } + } + } + } finally { + lastAttemptAt = limiter.now(); } }; - /** Get the current uncommitted portion of accumulated text */ - const currentText = () => accumulated.slice(committedLength); - - const renderCurrent = (): string => { - return markdownToTelegramHtml(currentText()); + /** Make the open bubble show `html`. Returns false if Telegram would not take it. */ + const finalEdit = async (html: string, plain: string): Promise => { + try { + await limiter.deliver(() => edit(html, true)); + return true; + } catch (err) { + if (isNotModified(err)) return true; + if (rateLimitDelayMs(err) !== null) return false; + } + // Telegram refused the HTML: show the markdown source instead. + try { + await limiter.deliver(() => edit(plain, false)); + return true; + } catch (err) { + return isNotModified(err); + } }; /** - * Check if current content exceeds the Telegram limit. - * If so, finalize the current message and start overflow handling. + * Close the open bubble with `chunk` as its final content, and start the + * next one after it. This is the update that has to arrive. */ - const handleOverflow = async (): Promise => { - const html = renderCurrent(); - if (html.length <= TELEGRAM_LIMIT) return; - - // Finalize current streaming message with tag-safe truncation - if (messageId) { - const truncated = truncateHtmlSafe(html, TELEGRAM_LIMIT); - await editMessage(truncated); - // Estimate how many source chars were consumed using the expansion ratio - const sourceLen = currentText().length; - const ratio = sourceLen > 0 ? html.length / sourceLen : 1; - const consumed = Math.min(sourceLen, Math.floor((TELEGRAM_LIMIT - 10) / Math.max(ratio, 1))); - committedLength += consumed; - messageId = null; - lastEditContent = ""; - } - }; - - for await (const chunk of stream) { - accumulated += chunk; - - if (!messageId) { - // First chunk (or after overflow) — send initial message - const html = renderCurrent(); - if (html.trim()) { - const safeHtml = truncateHtmlSafe(html, TELEGRAM_LIMIT); - try { - messageId = await sendInitial(safeHtml); - lastEditContent = safeHtml; - lastEditTime = Date.now(); - } catch { - try { - const result = await thread.adapter.telegramFetch("sendMessage", { - ...basePayload(chatId, messageThreadId), - text: currentText(), - }); - messageId = result.message_id; - lastEditContent = currentText(); - lastEditTime = Date.now(); - } catch (err) { - console.error(`[roundhouse] Telegram stream initial send failed:`, (err as Error).message); + const closeBubble = async (chunk: TakenChunk): Promise => { + let end = committed + chunk.length; + let nextPrefix = chunk.nextPrefix; + const source = accumulated.slice(committed, end); + if (messageId === null) { + // Nothing of this bubble is on screen yet: post it whole. + if (source.trim()) { + await sendHtmlOrPlain(limiter, thread.adapter, chatId, messageThreadId, chunk.html, chunk.text); + lastAttemptAt = limiter.now(); + } + } else if (chunk.html !== shown) { + if (!(await finalEdit(chunk.html, chunk.text))) { + // The bubble is stuck showing the text up to `shownEnd`. + const shownLength = shownEnd - committed; + if (shownLength < chunk.length) { + // Post the part of the chunk it does not show. + const resume = resumeMarkdownAt(prefix, source, shownLength); + const rest = source.slice(resume.offset); + if (rest.trim()) { + await postChunks(limiter, thread.adapter, chatId, messageThreadId, rest, resume.prefix); } + } else { + // It shows more than the chunk: the start of a line that belongs + // to the next bubble. Let the next bubble continue after it. + const resume = resumeMarkdownAt(prefix, body(), shownLength); + end = committed + resume.offset; + nextPrefix = resume.prefix; } } - continue; + lastAttemptAt = limiter.now(); } + committed = end; + prefix = nextPrefix; + messageId = null; + shown = ""; + shownEnd = end; + }; - // Check for overflow before editing - await handleOverflow(); - - // Throttled edit (only if we still have an active message) - if (messageId) { - const now = Date.now(); - if (now - lastEditTime >= STREAM_EDIT_INTERVAL_MS) { - const html = renderCurrent(); - const safeHtml = truncateHtmlSafe(html, TELEGRAM_LIMIT); - await editMessage(safeHtml); - } + for await (const piece of stream) { + accumulated += piece; + let html = renderOpen(); + while (html === null) { + await closeBubble(takeMarkdownChunk(prefix, body())); + html = renderOpen(); } + await updateBubble(html); } - // Final: handle any remaining content - const remaining = currentText(); - if (!remaining.trim()) return; - - if (messageId) { - // Try final edit - const finalHtml = renderCurrent(); - if (finalHtml.length <= TELEGRAM_LIMIT) { - const ok = await editMessage(finalHtml); - if (!ok) { - // Fallback to plain text edit - try { - await thread.adapter.telegramFetch("editMessageText", { - ...basePayload(chatId, messageThreadId), - message_id: messageId, - text: remaining, - }); - } catch { /* at least some content was sent */ } - } - } else { - // Content exceeds limit — finalize current message and post remainder - const truncated = truncateHtmlSafe(finalHtml, TELEGRAM_LIMIT); - await editMessage(truncated); - // Estimate consumed source chars using expansion ratio - const remLen = remaining.length; - const ratio = remLen > 0 ? finalHtml.length / remLen : 1; - const overflowStart = Math.min(remLen, Math.floor((TELEGRAM_LIMIT - 10) / Math.max(ratio, 1))); - const overflow = remaining.slice(overflowStart); - if (overflow.trim()) { - await postTelegramHtml(thread, overflow); - } - } - } else { - // No active message — post everything remaining - await postTelegramHtml(thread, remaining); + // Final: whatever the open bubble holds. It fits one message, unless + // closing a code block that is still open pushes it over. + while (body().trim()) { + await closeBubble(takeMarkdownChunk(prefix, body())); } } diff --git a/test/telegram-delivery.test.ts b/test/telegram-delivery.test.ts new file mode 100644 index 0000000..eca9f55 --- /dev/null +++ b/test/telegram-delivery.test.ts @@ -0,0 +1,464 @@ +/** + * test/telegram-delivery.test.ts — what reaches Telegram, end to end. + * + * The first three blocks each reproduce a defect seen in production: + * 1. text dropped at the 4096-character limit (posting and streaming) + * 2. a code block split across messages rendering as prose + * 3. a rate limit (HTTP 429) during streaming leaving the message truncated + * + * The last block posts and streams a few hundred generated documents and + * checks that the reader ends up with every character of each. The + * generator is seeded, so a failure names the seed that reproduces it. + */ + +import { describe, it, expect, vi, afterEach } from "vitest"; +import { markdownToTelegramHtml } from "../src/transports/telegram/format"; +import { postTelegramHtml, handleTelegramHtmlStream } from "../src/transports/telegram/html"; +import { + TELEGRAM_LIMIT, + fakeTelegram, + fakeClock, + rateLimitError, + htmlToVisible, + inPieces, + longAnswerWithCode, + outsidePre, + telegramHtmlProblem, +} from "./telegram-test-helpers"; +import { CODE_MARK, firstDifference, flat, genDocument, rng, type Rng } from "./telegram-doc-generator"; + +const LIMIT = TELEGRAM_LIMIT; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** How many times `needle` occurs in `haystack` */ +function count(haystack: string, needle: string): number { + return haystack.split(needle).length - 1; +} + +// ── 1. Nothing is dropped at the 4096-character limit ────────────────── + +describe("no text is dropped at Telegram's message limit", () => { + it("posting an 11,000-character answer with a 140-line code block delivers every code line", async () => { + const { markdown, code } = longAnswerWithCode(); + expect(markdown.length).toBeGreaterThan(11_000); + const t = fakeTelegram(); + + await postTelegramHtml(t, markdown); + + for (const call of t.calls) { + expect(call.payload.text.length).toBeLessThanOrEqual(TELEGRAM_LIMIT); + } + const seen = t.visible().join("\n"); + const missing = code.filter((line) => count(seen, line) !== 1); + expect(missing).toEqual([]); + expect(seen).toContain("Paragraph 6:"); + expect(seen).toContain("Run the migration before deploying"); + }); + + it("posting never ends a message with a truncation marker", async () => { + const { markdown } = longAnswerWithCode(); + const t = fakeTelegram(); + + await postTelegramHtml(t, markdown); + + for (const m of t.messages()) { + expect(m.text.endsWith("...")).toBe(false); + expect(telegramHtmlProblem(m.text)).toBeNull(); + } + }); + + it("streaming the same answer delivers every code line, each bubble starting on a line boundary", async () => { + const { markdown, code } = longAnswerWithCode(); + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now }); + + await handleTelegramHtmlStream(t, inPieces(markdown, 37, () => clock.advance(40)), clock); + + const bubbles = t.visible(); + expect(bubbles.length).toBeGreaterThanOrEqual(3); + for (const m of t.messages()) { + expect(m.text.length).toBeLessThanOrEqual(TELEGRAM_LIMIT); + } + const seen = bubbles.join("\n"); + const missing = code.filter((line) => count(seen, line) !== 1); + expect(missing).toEqual([]); + + // Every bubble after the first starts with a whole source line. + const sourceLines = new Set(markdown.split("\n")); + for (const bubble of bubbles.slice(1)) { + const firstLine = bubble.replace(/^\n+/, "").split("\n")[0]; + expect(sourceLines.has(firstLine), `bubble starts mid-line: ${JSON.stringify(firstLine)}`).toBe(true); + } + }); + + it("streaming one very long line delivers every character", async () => { + const words = Array.from({ length: 1500 }, (_, i) => `w${i}`); + const line = words.join(" "); + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now }); + + await handleTelegramHtmlStream(t, inPieces(line, 500, () => clock.advance(40)), clock); + + expect(t.visible().join("")).toBe(line); + }); +}); + +// ── 2. A code block split across messages stays a code block ─────────── + +describe("a code block split across messages", () => { + const codeOnlyInPre = (html: string) => { + expect(html).not.toContain("```"); + expect(outsidePre(html)).not.toContain("const cache"); + }; + + it("renders as a code block in every message when posted", async () => { + const { markdown } = longAnswerWithCode(); + const t = fakeTelegram(); + + await postTelegramHtml(t, markdown); + + expect(t.messages().length).toBeGreaterThanOrEqual(3); + for (const m of t.messages()) { + expect(m.html).toBe(true); + codeOnlyInPre(m.text); + } + }); + + it("renders as a code block in every bubble when streamed", async () => { + const { markdown } = longAnswerWithCode(); + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now }); + + await handleTelegramHtmlStream(t, inPieces(markdown, 53, () => clock.advance(40)), clock); + + for (const m of t.messages()) { + expect(m.html).toBe(true); + codeOnlyInPre(m.text); + } + }); + + it("keeps markdown inside the code literal after the split", async () => { + const code = Array.from({ length: 150 }, (_, i) => `def __x__(self): return self.__dict__ # row ${i} *not* **bold**`); + const markdown = "```python\n" + code.join("\n") + "\n```"; + const t = fakeTelegram(); + + await postTelegramHtml(t, markdown); + + expect(t.messages().length).toBeGreaterThanOrEqual(2); + for (const m of t.messages()) { + expect(m.text).not.toMatch(/|/); + expect(m.text.startsWith(" ")).toBe(true); + expect(m.text.trimEnd().endsWith("")).toBe(true); + } + expect(t.visible().join("\n")).toBe(code.join("\n")); + }); + + it("hard-splits a single line longer than the limit inside a fence instead of dropping it", async () => { + const longLine = "x&".repeat(1400); // 7000 characters, 16,800 once escaped + const markdown = "```\n" + longLine + "\n```"; + const t = fakeTelegram(); + + await postTelegramHtml(t, markdown); + + for (const m of t.messages()) { + expect(m.text.length).toBeLessThanOrEqual(TELEGRAM_LIMIT); + expect(m.text.startsWith(" ")).toBe(true); + expect(telegramHtmlProblem(m.text)).toBeNull(); + } + expect(t.visible().join("")).toBe(longLine); + }); +}); + +// ── 3. A rate limit during streaming does not truncate the message ───── + +describe("a Telegram rate limit (HTTP 429) during streaming", () => { + const text = "Hello there. " + Array.from({ length: 60 }, (_, i) => `Sentence number ${i} of the answer.`).join(" "); + + it("still delivers the final text once the retry-after has passed", async () => { + const clock = fakeClock(); + let blockedUntil = 0; + const t = fakeTelegram({ + now: clock.now, + fail: (call, index) => { + // The first call is accepted. The second is rejected with retry_after 20 s, + // and so is anything else sent before those 20 s are over. + if (index === 1) blockedUntil = clock.now() + 20_000; + return index >= 1 && clock.now() < blockedUntil ? rateLimitError(20) : null; + }, + }); + vi.spyOn(console, "error").mockImplementation(() => {}); + + await handleTelegramHtmlStream(t, inPieces(text, 6, () => clock.advance(100)), clock); + + expect(t.visible()).toEqual([text]); + }); + + it("does not edit again before the retry-after has passed", async () => { + const clock = fakeClock(); + let blockedUntil = 0; + const t = fakeTelegram({ + now: clock.now, + fail: (call, index) => { + if (index === 1) blockedUntil = clock.now() + 20_000; + return index >= 1 && clock.now() < blockedUntil ? rateLimitError(20) : null; + }, + }); + + await handleTelegramHtmlStream(t, inPieces(text, 6, () => clock.advance(100)), clock); + + // One rejected call tells us about the limit. Nothing else is sent until it lifts. + expect(t.calls.filter((c) => c.failed).length).toBe(1); + const afterLimit = t.calls.slice(2); + for (const call of afterLimit) { + expect(call.at).toBeGreaterThanOrEqual(blockedUntil); + } + }); + + it("waits at most 30 seconds for the final edit, then posts the rest as a new message", async () => { + const clock = fakeClock(); + // Edits are rejected for good; new messages are accepted. + const t = fakeTelegram({ + now: clock.now, + fail: (call) => (call.method === "editMessageText" ? rateLimitError(600) : null), + }); + vi.spyOn(console, "error").mockImplementation(() => {}); + + await handleTelegramHtmlStream(t, inPieces(text, 6, () => clock.advance(100)), clock); + + expect(clock.sleeps.length).toBeGreaterThan(0); + expect(Math.max(...clock.sleeps)).toBeLessThanOrEqual(30_000); + // The first bubble kept what it had; the rest arrived in a second message. + const bubbles = t.visible(); + expect(bubbles.length).toBe(2); + expect(bubbles[0]).toBe("Hello "); + expect(bubbles.join("")).toBe(text); + }); + + it("keeps throttling edits after one fails for another reason", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ + now: clock.now, + fail: (call) => + call.method === "editMessageText" && call.payload.parse_mode === "HTML" + ? new Error("Bad Request: can't parse entities") + : null, + }); + + // One piece every 100 ms. + const streamMs = Math.ceil(text.length / 12) * 100; + await handleTelegramHtmlStream(t, inPieces(text, 12, () => clock.advance(100)), clock); + + const htmlEdits = t.calls.filter((c) => c.method === "editMessageText" && c.payload.parse_mode === "HTML"); + // At most one attempt per 1.1 s, plus the final one. Before the fix every piece was an attempt. + expect(htmlEdits.length).toBeGreaterThan(3); + expect(htmlEdits.length).toBeLessThanOrEqual(Math.floor(streamMs / 1100) + 1); + for (let i = 1; i < htmlEdits.length - 1; i++) { + expect(htmlEdits[i].at - htmlEdits[i - 1].at).toBeGreaterThanOrEqual(1100); + } + // The final edit fell back to plain text, so the whole answer is there. + expect(t.visible()).toEqual([text]); + }); + + it("delivers the answer when the very first send is rate limited", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ + now: clock.now, + fail: (_call, index) => (index === 0 ? rateLimitError(3) : null), + }); + + await handleTelegramHtmlStream(t, inPieces(text, 6, () => clock.advance(100)), clock); + + expect(t.visible()).toEqual([text]); + // The second attempt waited for the 3 seconds Telegram asked for. + expect(t.calls[1].at - t.calls[0].at).toBeGreaterThanOrEqual(3000); + }); + + it("retries a rate-limited post instead of dropping the message", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ + now: clock.now, + fail: (_call, index) => (index === 0 ? rateLimitError(4) : null), + }); + + await postTelegramHtml(t, "**hello** world", clock); + + expect(clock.sleeps).toEqual([4000]); + expect(t.messages().map((m) => m.text)).toEqual(["hello world"]); + }); + + it("edits no more often than every 1100 ms while streaming", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now }); + + await handleTelegramHtmlStream(t, inPieces(text, 6, () => clock.advance(100)), clock); + + const edits = t.calls.filter((c) => c.method === "editMessageText"); + expect(edits.length).toBeGreaterThan(3); + // The last edit is the final one and is not throttled. + for (let i = 1; i < edits.length - 1; i++) { + expect(edits[i].at - edits[i - 1].at).toBeGreaterThanOrEqual(1100); + } + expect(t.visible()).toEqual([text]); + }); + + it("edits no more often than every 3100 ms in a group", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now, chatId: "-1001234567890" }); + + await handleTelegramHtmlStream(t, inPieces(text, 6, () => clock.advance(100)), clock); + + const edits = t.calls.filter((c) => c.method === "editMessageText"); + expect(edits.length).toBeGreaterThan(3); + for (let i = 1; i < edits.length - 1; i++) { + expect(edits[i].at - edits[i - 1].at).toBeGreaterThanOrEqual(3100); + } + expect(t.calls[0].payload.chat_id).toBe("-1001234567890"); + expect(t.visible()).toEqual([text]); + }); +}); + +describe("the last edit of a streamed message", () => { + it("counts as delivered when Telegram says the message is not modified", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ + now: clock.now, + fail: (call) => + call.method === "editMessageText" + ? new Error("Bad Request: message is not modified: specified new message content and reply markup are exactly the same") + : null, + }); + + // The second piece only adds a line break, which Telegram trims. + await handleTelegramHtmlStream(t, inPieces("**done**\n", 8, () => clock.advance(10)), clock); + + // No plain-text edit and no second message. + expect(t.calls.map((c) => c.method)).toEqual(["sendMessage", "editMessageText"]); + expect(t.messages()).toEqual([{ id: 1, text: "done", html: true }]); + }); + + it("closes a code block the answer left open", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now }); + + await handleTelegramHtmlStream(t, inPieces("Run:\n```sh\nnpm test", 5, () => clock.advance(10)), clock); + + expect(t.messages().map((m) => m.text)).toEqual(["Run:\nnpm test"]); + }); +}); + +// ── Generated documents ─────────────────────────────── + +describe("delivery of generated documents", () => { + it("delivers every visible character when posting 150 documents", async () => { + for (let seed = 2001; seed <= 2150; seed++) { + const md = genDocument(seed, "no-tables"); + const t = fakeTelegram(); + await postTelegramHtml(t, md); + + for (const m of t.messages()) { + expect(m.html, `seed ${seed}`).toBe(true); + expect(m.text.length, `seed ${seed}`).toBeLessThanOrEqual(LIMIT); + } + const whole = htmlToVisible(markdownToTelegramHtml(md)).replace(/\n/g, ""); + expect(firstDifference(flat(t.visible()), whole), `seed ${seed}`).toBeNull(); + } + }); + + /** The document as a model would stream it: mostly small pieces, now and then a big one */ + async function* streamed(md: string, r: Rng, clock: ReturnType): AsyncIterable { + for (let i = 0; i < md.length; ) { + const size = r.chance(0.05) ? r.int(2000, 12000) : r.int(1, 400); + clock.advance(r.int(10, 900)); + yield md.slice(i, i + size); + i += size; + } + } + + const expectValidBubbles = (t: ReturnType , seed: number) => { + for (const m of t.messages()) { + expect(m.html, `seed ${seed}`).toBe(true); + expect(m.text.length, `seed ${seed}`).toBeLessThanOrEqual(LIMIT); + expect(telegramHtmlProblem(m.text), `seed ${seed}`).toBeNull(); + expect(outsidePre(m.text).includes(CODE_MARK), `seed ${seed}: code outside a code block`).toBe(false); + } + }; + + it("delivers every visible character when streaming 80 documents", async () => { + for (let seed = 3001; seed <= 3080; seed++) { + const md = genDocument(seed, "no-tables"); + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now }); + + await handleTelegramHtmlStream(t, streamed(md, rng(seed), clock), clock); + + expectValidBubbles(t, seed); + const whole = htmlToVisible(markdownToTelegramHtml(md)).replace(/\n/g, ""); + expect(firstDifference(flat(t.visible()), whole), `seed ${seed}`).toBeNull(); + } + }); + + it("delivers every visible character when streaming 80 documents through rate limits", async () => { + let limited = 0; + for (let seed = 4001; seed <= 4080; seed++) { + const md = genDocument(seed, "no-tables"); + const clock = fakeClock(); + const r = rng(seed * 7); + // Now and then Telegram answers 429 and refuses everything for up to 25 seconds. + let blockedUntil = 0; + const t = fakeTelegram({ + now: clock.now, + fail: () => { + const now = clock.now(); + if (now >= blockedUntil + 60_000 && r.chance(0.15)) { + blockedUntil = now + r.int(1, 25) * 1000; + limited++; + } + return now < blockedUntil ? rateLimitError(Math.ceil((blockedUntil - now) / 1000)) : null; + }, + }); + + await handleTelegramHtmlStream(t, streamed(md, rng(seed), clock), clock); + + expectValidBubbles(t, seed); + const whole = htmlToVisible(markdownToTelegramHtml(md)).replace(/\n/g, ""); + expect(firstDifference(flat(t.visible()), whole), `seed ${seed}`).toBeNull(); + } + expect(limited).toBeGreaterThan(40); + }); + + it("delivers every visible character when some bubbles can never be edited", async () => { + let stuck = 0; + for (let seed = 5001; seed <= 5080; seed++) { + const md = genDocument(seed, "plain-prose"); + const clock = fakeClock(); + const r = rng(seed * 11); + // Every edit of an unlucky message is refused with a retry-after longer than we wait. + const unlucky = new Map (); + const t = fakeTelegram({ + now: clock.now, + fail: (call) => { + if (call.method !== "editMessageText") return null; + const id = call.payload.message_id as number; + if (!unlucky.has(id)) unlucky.set(id, r.chance(0.4)); + return unlucky.get(id) ? rateLimitError(120) : null; + }, + }); + + await handleTelegramHtmlStream(t, streamed(md, rng(seed), clock), clock); + + stuck += [...unlucky.values()].filter(Boolean).length; + for (const m of t.messages()) { + expect(m.text.length, `seed ${seed}`).toBeLessThanOrEqual(LIMIT); + expect(telegramHtmlProblem(m.text), `seed ${seed}`).toBeNull(); + } + // A bubble stuck in the middle of a fence line shows a few of its backticks. + const strip = (s: string) => s.replace(/[`\n]/g, ""); + const whole = strip(htmlToVisible(markdownToTelegramHtml(md))); + expect(firstDifference(strip(t.visible().join("")), whole), `seed ${seed}`).toBeNull(); + } + expect(stuck).toBeGreaterThan(40); + }); +}); From 78e4772cab54ce5a3bdbcb8336c8e94bb2c14864 Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:23:13 +0200 Subject: [PATCH 3/8] telegram: emit plain text inside table boxes Telegram's may not contain other entities, and a message it refuses falls back to raw markdown for the whole chunk. Cells are read as inline markdown, so the markers are gone, but nothing is tagged inside the box. Links are still repeated under the table. --- src/transports/telegram/format.ts | 17 +++++++++++------ test/telegram-format.test.ts | 13 ++++++++----- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/transports/telegram/format.ts b/src/transports/telegram/format.ts index dc87bd9..c8d17ef 100644 --- a/src/transports/telegram/format.ts +++ b/src/transports/telegram/format.ts @@ -439,9 +439,9 @@ function splitTableRow(line: string): string[] { * `lines` are the header row, the separator row and the data rows. All columns * are padded to a uniform width. * - * Cells get inline formatting: the markers are gone and the text is tagged. - * Telegram does not show bold, italics or links inside, so a cell reads - * as clean text, and each link is repeated under the table where it works. + * Cells are read as inline markdown and emitted as plain text: the markers are + * gone and nothing is tagged, becausemay not contain other entities. + * Each link is repeated under the table, where it works. */ function formatTable(lines: string[]): string { const headerCells = splitTableRow(lines[0]); @@ -511,11 +511,16 @@ function formatTable(lines: string[]): string { /** Links found in cells, as tags, in order of appearance */ const links: string[] = []; - // A cell as it is emitted, with the display width of what the reader sees - // (Telegram renders entities back to their visual form in). + // A cell as it is emitted: its text with the markdown markers removed, and + // no tags. Telegram's rule is thatand some more text pa...'); + it("keeps the cells of a row that has more of them than the header", () => { + const html = markdownToTelegramHtml("| Command | What |\n|---|---|\n| cat x | grep y | finds y |"); + expect(html).toContain("│ cat x │ grep y │ finds y │"); + expect(html).toContain("│ Command │ What │ │"); }); }); diff --git a/test/telegram-split.test.ts b/test/telegram-split.test.ts index 9756020..27a9a9a 100644 --- a/test/telegram-split.test.ts +++ b/test/telegram-split.test.ts @@ -16,6 +16,7 @@ import { splitMarkdownForTelegram, takeMarkdownChunk, type MarkdownChunk, + hasVisibleText, } from "../src/transports/telegram/format"; import { htmlToVisible, outsidePre, telegramHtmlProblem } from "./telegram-test-helpers"; import { CODE_MARK, PROSE_MARK, genDocument } from "./telegram-doc-generator"; @@ -352,3 +353,54 @@ describe("splitMarkdownForTelegram — generated documents", () => { expect(longest).toBeGreaterThan(30_000); }); }); + +describe("splitMarkdownForTelegram — found in review", () => { + const shows = (md: string) => splitMarkdownForTelegram(md).map((c) => hasVisibleText(c.html)); + + it("never makes a message of a code fence alone when the block's first line is too long", () => { + const md = "Here is the file:\n\n```json\n" + '{"k":"' + "x".repeat(5000) + '"}' + "\n```\nDone."; + const chunks = splitMarkdownForTelegram(md); + expect(chunks.map((c) => hasVisibleText(c.html))).toEqual([true, true, true]); + expect(chunks.map((c) => md.slice(c.start, c.end)).join("")).toBe(md); + for (const c of chunks) expect(c.html.length).toBeLessThanOrEqual(TELEGRAM_MESSAGE_LIMIT); + }); + + it("never makes a message of blank lines alone before a line that is too long", () => { + expect(shows("\n" + "x".repeat(5000))).toEqual([true, true]); + expect(shows("intro\n\n\n" + "x".repeat(9000)).every(Boolean)).toBe(true); + }); + + it("still splits a table that is too wide to box in one message", () => { + const cells = (text: (i: number) => string) => "| " + Array.from({ length: 30 }, (_, i) => text(i)).join(" | ") + " |"; + const md = [ + cells((i) => `Column number ${i} with a long title`), + "|" + "---|".repeat(30), + ...[1, 2, 3].map((n) => cells((i) => `value ${n}-${i}`)), + ].join("\n"); + + const chunks = splitMarkdownForTelegram(md); + + // A handful of messages, not one per character. + expect(chunks.length).toBeLessThanOrEqual(6); + expect(chunks.map((c) => md.slice(c.start, c.end)).join("")).toBe(md); + for (const c of chunks) { + expect(c.html.length).toBeLessThanOrEqual(TELEGRAM_MESSAGE_LIMIT); + expect(hasVisibleText(c.html)).toBe(true); + } + }); + + it("knows a cut before a half-written row is inside the table", () => { + const prose = Array.from({ length: 60 }, (_, i) => `Line ${i} of prose with some words to fill the line up nicely.`).join("\n"); + const head = "| Name | Value |\n|------|-------|\n"; + const rows = "| item 0 | 0 |\n| item 1 | 7 |\n"; + // The text so far ends in the middle of a row, as it does while streaming, + // and that row is what no longer fits. + const halfRow = "| item 2 | " + "y".repeat(400); + const body = `${prose}\n\n${head}${rows}${halfRow}`; + + const taken = takeMarkdownChunk("", body); + + expect(body.slice(taken.length)).toBe(halfRow); + expect(taken.nextPrefix).toBe(head); + }); +}); diff --git a/test/telegram-synthetic-thread.test.ts b/test/telegram-synthetic-thread.test.ts new file mode 100644 index 0000000..095c4a5 --- /dev/null +++ b/test/telegram-synthetic-thread.test.ts @@ -0,0 +1,82 @@ +/** + * test/telegram-synthetic-thread.test.ts — the thread roundhouse builds for + * messages that do not answer an incoming one (boot notice, cron results, + * sub-agent reports). It calls the Bot API itself. + * + * A refused call used to return null, which the delivery code took for + * success: no retry after a rate limit, no plain-text fallback, no log line. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { TelegramAdapter } from "../src/transports/telegram/telegram-adapter"; + +const realFetch = globalThis.fetch; +const realToken = process.env.TELEGRAM_BOT_TOKEN; + +type Reply = { status: number; body: unknown }; +let replies: Reply[]; +let requests: Array<{ method: string; payload: any }>; + +beforeEach(() => { + process.env.TELEGRAM_BOT_TOKEN = "123456:TEST-TOKEN-NOT-REAL"; + replies = []; + requests = []; + globalThis.fetch = (async (url: string, init: { body: string }) => { + requests.push({ method: String(url).split("/").pop()!, payload: JSON.parse(init.body) }); + const reply = replies.shift() ?? { status: 200, body: { ok: true, result: { message_id: requests.length } } }; + return new Response(JSON.stringify(reply.body), { status: reply.status }); + }) as any; + vi.spyOn(console, "error").mockImplementation(() => {}); +}); + +afterEach(() => { + globalThis.fetch = realFetch; + if (realToken === undefined) delete process.env.TELEGRAM_BOT_TOKEN; + else process.env.TELEGRAM_BOT_TOKEN = realToken; + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe("a thread created for a notice", () => { + it("falls back to plain text when Telegram refuses the HTML", async () => { + replies.push({ status: 400, body: { ok: false, error_code: 400, description: "Bad Request: can't parse entities" } }); + const thread = new TelegramAdapter().createThread(42); + + await thread.post("**hello** world"); + + expect(requests.map((r) => [r.method, r.payload.parse_mode, r.payload.text])).toEqual([ + ["sendMessage", "HTML", "hello world"], + ["sendMessage", undefined, "**hello** world"], + ]); + }); + + it("waits and sends again after a rate limit", async () => { + vi.useFakeTimers(); + replies.push({ + status: 429, + body: { ok: false, error_code: 429, description: "Too Many Requests: retry after 3", parameters: { retry_after: 3 } }, + }); + const thread = new TelegramAdapter().createThread(42); + + const posted = thread.post("hello"); + await vi.advanceTimersByTimeAsync(2900); + expect(requests).toHaveLength(1); + await vi.advanceTimersByTimeAsync(200); + await posted; + + expect(requests.map((r) => r.payload.text)).toEqual(["hello", "hello"]); + }); + + it("says so in the log when Telegram refuses the message for good", async () => { + const refusal = { status: 403, body: { ok: false, error_code: 403, description: "Forbidden: bot was blocked by the user" } }; + replies.push(refusal, refusal); + const thread = new TelegramAdapter().createThread(42); + + await thread.post("hello"); + + const logged = vi.mocked(console.error).mock.calls.map((c) => c.join(" ")).join("\n"); + expect(logged).toContain("5 characters not delivered"); + expect(logged).toContain("bot was blocked by the user"); + expect(logged).not.toContain("TEST-TOKEN"); + }); +}); diff --git a/test/telegram-test-helpers.ts b/test/telegram-test-helpers.ts index c7944f2..c0e5ae3 100644 --- a/test/telegram-test-helpers.ts +++ b/test/telegram-test-helpers.ts @@ -4,6 +4,10 @@ * `fakeTelegram` stands in for a Chat SDK thread backed by the Telegram * adapter. It records every Bot API call and keeps what each message would * show after its edits, so a test can assert on what the reader ends up with. + * + * Like Telegram, it refuses a message with nothing to show, one that shows + * more than 4096 characters, HTML it cannot parse, and an edit that changes + * nothing. */ export const TELEGRAM_LIMIT = 4096; @@ -50,12 +54,28 @@ export function fakeTelegram(opts: FakeTelegramOptions = {}): FakeTelegram { throw err; } const html = payload.parse_mode === "HTML"; + const refuse = (message: string): never => { + call.failed = true; + throw new Error(`Bad Request: ${message}`); + }; + if (method === "sendMessage" || method === "editMessageText") { + const text = payload.text as string; + const problem = html ? telegramHtmlProblem(text) : null; + if (problem) refuse(`can't parse entities: ${problem}`); + const visible = html ? htmlToVisible(text) : text; + if (!visible.trim()) refuse("message text is empty"); + if (visible.length > TELEGRAM_LIMIT) refuse("message is too long"); + } if (method === "sendMessage") { const id = nextId++; state.set(id, { text: payload.text, html }); return { message_id: id, chat: { id: Number(chatId) } }; } if (method === "editMessageText") { + const current = state.get(payload.message_id); + if (current && current.html === html && current.text.trimEnd() === payload.text.trimEnd()) { + refuse("message is not modified: specified new message content and reply markup are exactly the same"); + } state.set(payload.message_id, { text: payload.text, html }); return true; } From 79d720c2f4a9cbf1971551148c9fb1d6836e60db Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:23:16 +0200 Subject: [PATCH 6/8] docs: Telegram delivery rules for agents, and what the review left open --- CLAUDE.md | 6 ++++++ futureplans/next-phase.md | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index f88211e..aefbc2b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,6 +33,12 @@ Roundhouse is a chat-gateway between chat platforms (via Vercel Chat SDK) and a - `turn_end` / `agent_end` → flush so the next turn starts a fresh message If `promptStream` is missing, `agent.prompt()` is called and the full text is split/posted via `postWithFallback` (markdown-first, plaintext fallback). +**Telegram answers are sent by roundhouse, not by the Chat SDK** (`src/transports/telegram/html.ts` and `format.ts`; the SDK's posting uses Telegram's legacy Markdown mode). What holds there: +- **Nothing is truncated.** A long answer is cut in its markdown source (`splitMarkdownForTelegram`, `takeMarkdownChunk`) so that each chunk's HTML fits one message; a code block or table that spans chunks is reopened in the next one. `scanLines` is the one place that decides where code blocks and tables are, and the converter and the splitter both read it. No chunk is without visible text: Telegram refuses an empty message, and the refusal sends the plain-text fallback, which shows raw fences. +- **Telegram is never called inside a wait it asked for** (`RateLimiter`). A 429 is waited out, up to `MAX_RATE_LIMIT_WAIT_MS` per answer; a wait longer than what is left is not started and the loss is logged. Sends and edits have separate waits, because Telegram refuses edits of one message for minutes while it still takes a new message. After a chunk that is held back, later chunks are not sent. +- **Streaming** edits one message at most every `STREAM_EDIT_INTERVAL_MS` (longer in groups). An edit in the middle may be skipped; a timer makes up for it when the stream goes quiet (a tool is running). The last edit of a message must arrive: if it cannot, the text the message does not show is posted as a new message. +- **The fake in `test/telegram-test-helpers.ts` refuses what Telegram refuses** (empty text, HTML it cannot parse, more than 4096 visible characters, an edit that changes nothing). Keep it that strict: a lenient fake is how an empty code block and raw table rows got through. The generated-document tests are seeded; a failure names the seed. + **Pi adapter nuance — wait for idle, not for `prompt()`.** `src/agents/pi/pi-adapter.ts` targets pi 1.x (`@earendil-works/pi-coding-agent`, pinned to the exact version in `package.json`). Since pi 1.0, `session.prompt()` resolves only after the run has settled: retries, compaction, follow-ups queued by `agent_end` handlers and the `agent_settled` handlers are all inside it. A run an extension starts *after* that (`pi.sendMessage(..., { triggerTurn: true })` while idle) is not, so `runPromptAndFollowUps` then loops on the public `session.isIdle` / `session.waitForIdle()` before the caller unsubscribes. Unsubscribe earlier and Telegram shows a review bubble followed by silence. Do not reintroduce the pre-1.0 workarounds (awaiting the private `_agentEventQueue`, calling `agent.continue()` by hand): that field is gone and the session drains its own queues. **Pi adapter nuance — "still working" notices come from events.** `promptStream` emits `draining` when a new low-level run (`agent_start`) begins after one already ended (`agent_end` with `willRetry: false`) inside the same prompt, and `drain_complete` on `agent_settled`. A retry is not a new run for this purpose. diff --git a/futureplans/next-phase.md b/futureplans/next-phase.md index f4314f0..c23bb23 100644 --- a/futureplans/next-phase.md +++ b/futureplans/next-phase.md @@ -133,6 +133,14 @@ Belongs with A1. - **A turn whose answer was delivered but which is still in post-turn work** (memory finalize, flush) when the gateway stops is reported as unfinished at the next start. - **Expired OAuth credentials** produce pi's "Run '/login x'" text in chat, which is not a roundhouse command. - **Hard cuts** of a single line longer than Telegram's limit can land inside inline markup, so both halves show the markers literally. Nothing is lost. +- **Telegram delivery, left from the review of the rendering fix:** + - A message with more than 100 formatted spans may exceed Telegram's entity limit (recalled, not verified); the splitter counts characters only. + - A line of several thousand `>` or `-` characters loses a few of them or turns into rules, and a table header of about 4,090 characters produces one chunk over the limit. + - An edit that Telegram applied but whose response was lost is posted again as a new message. + - A stream of one-character pieces costs more per piece as the answer grows; a 1M-character answer streamed that way is slow. + - A rate limit longer than 90 s per answer drops the rest of that answer with a log line; the owner is not told in chat. + - Tilde fences (`~~~`) are not read as code blocks, and a closing fence followed by text on the same line does not close the block (as in CommonMark). + - `telegramFetch` is called without a timeout of its own. - **Slack pairing** has no one-time code: the first user whose display name matches is paired. Slack users are admitted by id only, but the pairing step is the weak link. - **`roundhouse setup` and `roundhouse update`** install unpinned software: latest npm packages, a skills repository at its default branch, and the uv installer piped to a shell. - **The CI workflow does not run the typecheck.** Adding it needs a token with the `workflow` scope. From 901a97ae07b91048b9f680b712382a205e9537c7 Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:37:52 +0200 Subject: [PATCH 7/8] telegram: do not send half an emoji when a stream piece ends inside one --- src/transports/telegram/html.ts | 9 +++++++++ test/telegram-delivery.test.ts | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/transports/telegram/html.ts b/src/transports/telegram/html.ts index fc20982..266db4d 100644 --- a/src/transports/telegram/html.ts +++ b/src/transports/telegram/html.ts @@ -211,6 +211,12 @@ function stillRateLimited(waitMs: number): Error { return Object.assign(new Error(`Telegram asked for a wait of ${seconds} s`), { retryAfter: seconds }); } +/** True if the text ends with the first half of a surrogate pair */ +function endsInHalfCharacter(text: string): boolean { + const last = text.charCodeAt(text.length - 1); + return last >= 0xd800 && last <= 0xdbff; +} + /** Two texts Telegram shows the same way: it drops whitespace at the end of a message */ function sameText(a: string, b: string): boolean { return a === b || a.trimEnd() === b.trimEnd(); @@ -528,6 +534,9 @@ export async function handleTelegramHtmlStream( next = null; if (result.done) break; accumulated += result.value; + // Half of a character that takes two code units: Telegram refuses it. + // The other half comes with the next piece. + if (endsInHalfCharacter(accumulated)) continue; let html = renderOpen(); while (html === null) { await closeBubble(takeMarkdownChunk(prefix, body())); diff --git a/test/telegram-delivery.test.ts b/test/telegram-delivery.test.ts index 7448ec6..21c4ef7 100644 --- a/test/telegram-delivery.test.ts +++ b/test/telegram-delivery.test.ts @@ -461,6 +461,25 @@ describe("the last edit of a streamed message", () => { expect(edits[1].at - edits[0].at).toBeGreaterThanOrEqual(1100); }); + it("does not send half an emoji when a piece ends in the middle of one", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ now: clock.now }); + const text = "Done 😀 and more text after it."; + const half = text.indexOf("😀") + 1; + async function* pieces() { + yield text.slice(0, 3); + clock.advance(1200); + yield text.slice(3, half); // ends with the first half of the emoji + clock.advance(1200); + yield text.slice(half); + } + + await handleTelegramHtmlStream(t, pieces(), clock); + + for (const call of t.calls) expect(call.payload.text.isWellFormed(), call.payload.text).toBe(true); + expect(t.visible()).toEqual([text]); + }); + it("delivers what arrived when the stream fails, then reports the failure", async () => { const clock = fakeClock(); const t = fakeTelegram({ now: clock.now }); From 6c1278d46d9ccad0838eff94344baf401f7e9a81 Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:59:50 +0200 Subject: [PATCH 8/8] telegram: stop a streamed answer after a part that a rate limit holds back Posted answers already stopped at the first chunk that was held back; a streamed one went on with the next bubble once Telegram accepted messages again, so the reader got the answer with a hole in it. Now nothing is sent after the part that was held back, the stream is read to its end, and the loss is logged once with its size. --- src/transports/telegram/html.ts | 42 +++++++++++++++-------- test/telegram-delivery.test.ts | 59 +++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 14 deletions(-) diff --git a/src/transports/telegram/html.ts b/src/transports/telegram/html.ts index 266db4d..b1423d9 100644 --- a/src/transports/telegram/html.ts +++ b/src/transports/telegram/html.ts @@ -276,14 +276,16 @@ export async function postTelegramHtml( ): Promisecannot contain other entities, and + // a message it refuses falls back to raw markdown for the whole chunk, so + // nothing but text goes inside the box. Rendering the cell is still done, + // for its side effect of collecting the links. const toCell = (raw: string): { html: string; width: number } => { const nodes = parseInline(raw); - return { html: renderInlineNodes(nodes, NO_OPEN_TAGS, links), width: displayWidth(inlineText(nodes)) }; + renderInlineNodes(nodes, NO_OPEN_TAGS, links); + const text = inlineText(nodes); + return { html: escapeHtml(text), width: displayWidth(text) }; }; // Normalize rows to exactly colCount columns diff --git a/test/telegram-format.test.ts b/test/telegram-format.test.ts index 36b21a2..ae32083 100644 --- a/test/telegram-format.test.ts +++ b/test/telegram-format.test.ts @@ -367,7 +367,7 @@ describe("markdownToTelegramHtml — emphasis and tables in model output", () => expect(markdownToTelegramHtml("`**x** _y_ [z](https://e.com)`")).toBe("**x** _y_ [z](https://e.com)"); }); - it("formats table cells and keeps the box layout", () => { + it("reads table cells as inline markdown, emits them as plain text, and keeps the box layout", () => { const md = [ "| Name | Notes |", "|------|-------|", @@ -377,11 +377,14 @@ describe("markdownToTelegramHtml — emphasis and tables in model output", () => const html = markdownToTelegramHtml(md); expect(telegramHtmlProblem(html)).toBeNull(); - expect(html).toContain("x"); - expect(html).toContain("a|b"); + // The link works under the table; inside the box there is text only, + // because Telegram'smay not contain other entities. expect(html).toContain('link'); - expect(html).toContain("it"); - expect(html).toContain("old"); + const inside = html.match(/([\s\S]*?)<\/pre>/)![1]; + expect(inside).not.toMatch(/<\/?(b|i|s|u|code|a)\b/); + expect(inside).toContain("x"); + expect(inside).toContain("a|b"); + expect(inside).toContain("it and old"); // No markdown markers are left in the cells. expect(html).not.toContain("**"); expect(html).not.toContain("`"); From 234f5b8b0fae3b901d67e70a75537e6c6eff4de9 Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:56:36 +0200 Subject: [PATCH 4/8] telegram: do not repeat a rate-limited call inside the wait Telegram asked for --- src/transports/telegram/html.ts | 33 +++++++++++++++++++++++---------- test/telegram-delivery.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/src/transports/telegram/html.ts b/src/transports/telegram/html.ts index 177451f..1649190 100644 --- a/src/transports/telegram/html.ts +++ b/src/transports/telegram/html.ts @@ -128,25 +128,38 @@ class RateLimiter { } /** - * Make a call that must get through. Waits until Telegram accepts calls - * again, and after a rate limit waits and tries again, for at most - * `MAX_RATE_LIMIT_WAIT_MS` in total. Throws the last error after that, and - * any error that is not a rate limit at once. + * Make a call that must get through, waiting for at most + * `MAX_RATE_LIMIT_WAIT_MS` in total. + * + * Blocked by an earlier call: wait for it, up to the budget, then try. This + * call can be accepted where that one was not (Telegram refuses edits of one + * message for minutes and still takes a new message). + * + * Refused itself: wait as long as Telegram said and try again. If that is + * longer than the budget left, throw without another try: the same call + * inside its own wait is refused again and can lengthen the wait. + * + * Any error that is not a rate limit is thrown at once. */ async deliver(call: () => Promise ): Promise { let budget = MAX_RATE_LIMIT_WAIT_MS; + const pause = async (ms: number) => { + if (ms <= 0) return; + await this.sleep(ms); + budget -= ms; + }; + await pause(Math.min(this.blockedUntil - this.now(), budget)); for (let attempt = 1; ; attempt++) { - const wait = Math.min(this.blockedUntil - this.now(), budget); - if (wait > 0) { - await this.sleep(wait); - budget -= wait; - } try { const result = await call(); this.blockedUntil = 0; return result; } catch (err) { - if (!this.note(err) || budget <= 0 || attempt >= MAX_DELIVERY_ATTEMPTS) throw err; + const delay = rateLimitDelayMs(err); + if (delay === null) throw err; + this.note(err); + if (delay > budget || attempt >= MAX_DELIVERY_ATTEMPTS) throw err; + await pause(delay); } } } diff --git a/test/telegram-delivery.test.ts b/test/telegram-delivery.test.ts index eca9f55..c363ed1 100644 --- a/test/telegram-delivery.test.ts +++ b/test/telegram-delivery.test.ts @@ -289,6 +289,29 @@ describe("a Telegram rate limit (HTTP 429) during streaming", () => { expect(t.messages().map((m) => m.text)).toEqual(["hello world"]); }); + it("does not call Telegram again before a wait longer than its patience has run out", async () => { + const clock = fakeClock(); + const t = fakeTelegram({ + now: clock.now, + fail: (_call, index) => (index === 0 ? rateLimitError(60) : null), + }); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + + await postTelegramHtml(t, "**hello** world", clock); + + // One call, refused for 60 s. A second call inside that minute would be + // refused as well and can lengthen the wait, so none is made. + expect(t.calls).toHaveLength(1); + expect(clock.sleeps).toEqual([]); + expect(errors.mock.calls.map((c) => String(c[0])).join("\n")).toMatch(/not delivered/); + errors.mockRestore(); + + // Once the minute is over the next message goes out, without a wait. + clock.advance(60_000); + await postTelegramHtml(t, "later", clock); + expect(t.messages().map((m) => m.text)).toEqual(["later"]); + }); + it("edits no more often than every 1100 ms while streaming", async () => { const clock = fakeClock(); const t = fakeTelegram({ now: clock.now }); From 86939fd4ee3be8031c2b25a6e78ad0f279d91de9 Mon Sep 17 00:00:00 2001 From: royosherove <575051+royosherove@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:21:47 +0200 Subject: [PATCH 5/8] telegram: fix what the review found in delivery, splitting and rendering Delivery - A rate limit is waited out for up to 90 s per answer (was 30 s per call). Telegram is never called inside a wait it asked for. Sends and edits keep separate waits, and the wait for sends is remembered per chat. - After a chunk that a rate limit holds back, later chunks are not sent; the loss is logged once with its size. - A stream that goes quiet shows the text it has when the next edit is due, instead of when the next piece arrives. - The final edit keeps the same distance from the previous one as any other. - No edit for a change that is only trailing whitespace. - A stream that fails still delivers what arrived. - The thread used for boot, cron and sub-agent notices throws when Telegram refuses a call, so retries and the plain-text fallback apply to it too. Splitting - No chunk without visible text: a code block whose first line is too long is cut inside that line, and blank lines before a long line stay with it. - A cut before a half-written table row (streaming) repeats the header. Rendering - Lines ending in CR LF. - Bold next to punctuation with a letter after it (`**Note:**text`, CJK). - Table rows with more cells than the header keep them. Tests: the fake Telegram now refuses what Telegram refuses (empty text, bad HTML, over-long text, unchanged edits). --- src/transports/telegram/format.ts | 88 +++--- src/transports/telegram/html.ts | 282 ++++++++++++++----- src/transports/telegram/telegram-adapter.ts | 17 +- test/telegram-delivery.test.ts | 287 +++++++++++++++++++- test/telegram-format.test.ts | 39 +-- test/telegram-split.test.ts | 52 ++++ test/telegram-synthetic-thread.test.ts | 82 ++++++ test/telegram-test-helpers.ts | 20 ++ 8 files changed, 726 insertions(+), 141 deletions(-) create mode 100644 test/telegram-synthetic-thread.test.ts diff --git a/src/transports/telegram/format.ts b/src/transports/telegram/format.ts index c8d17ef..0416dc4 100644 --- a/src/transports/telegram/format.ts +++ b/src/transports/telegram/format.ts @@ -63,28 +63,6 @@ function matchLink(str: string, startIdx: number): { full: string; text: string; return { full: str.slice(startIdx, i + 1), text, url, end: i + 1 }; } -/** - * Truncate HTML safely — avoids cutting inside tags. - * Finds the last '>' before the limit, or falls back to the limit itself. - * - * Message delivery does not use this: it drops text. Long answers are split - * with `splitMarkdownForTelegram` instead. - */ -export function truncateHtmlSafe(html: string, limit: number): string { - if (html.length <= limit) return html; - if (limit <= 3) return "..."; - const cutoff = limit - 3; // room for "..." - // Find the last '>' at or before cutoff to avoid splitting a tag - let safeEnd = cutoff; - for (let i = cutoff - 1; i >= Math.max(0, cutoff - 200); i--) { - if (html[i] === ">") { - safeEnd = i + 1; - break; - } - } - return html.slice(0, safeEnd) + "..."; -} - // ── Inline formatting ───────────────────────────────── /** A run of `*`, `_` or `~~` that may open or close emphasis */ @@ -179,8 +157,12 @@ function delimiterAt(src: string, i: number, n: number, ch: "*" | "_" | "~"): De } else { // `2*3*4` and `2**10` are arithmetic, not emphasis. const arithmetic = ASCII_DIGIT.test(prev) && ASCII_DIGIT.test(next); - canOpen = leftFlanking && !arithmetic; - canClose = rightFlanking && !arithmetic; + // Bold needs only a non-space character on its inside edge. CommonMark's + // punctuation rule would leave `**Note:**text` and `**注意:**这是重点` + // literal, and models write both (text without spaces has no other way). + const bold = n >= 2; + canOpen = (bold ? !nextSpace : leftFlanking) && !arithmetic; + canClose = (bold ? !prevSpace : rightFlanking) && !arithmetic; } } return canOpen || canClose ? { type: "delim", ch, count: n, length: n, canOpen, canClose } : null; @@ -447,7 +429,9 @@ function formatTable(lines: string[]): string { const headerCells = splitTableRow(lines[0]); // lines[1] is the separator row (|---|---|) — skip it const dataRows = lines.slice(2).map(splitTableRow); - const colCount = headerCells.length; + // As many columns as the widest row: a row with more cells than the header + // keeps them. + const colCount = Math.max(headerCells.length, ...dataRows.map((row) => row.length)); // Display width of a single Unicode code point in a monospace font. // Emoji and CJK characters typically occupy 2 columns. @@ -628,17 +612,28 @@ function isFenceClose(line: string, fence: Fence): boolean { * indentation, followed by an optional info string) and closes on a line of * at least as many backticks and nothing else. One that is never closed runs * to the end of the text. + * + * `openLastRow` is for text that is still being written: a last line that + * starts with `|` inside a table is then a row that has not got its closing + * `|` yet. The splitter uses it to know that a cut before that line is inside + * the table. The converter does not: it renders such a line as text. */ -function scanLines(md: string): Line[] { +function scanLines(md: string, openLastRow = false): Line[] { const lines: Line[] = []; for (let start = 0; ; ) { const newline = md.indexOf("\n", start); const end = newline === -1 ? md.length : newline; - lines.push({ start, end, text: md.slice(start, end), kind: "text" }); + // A line ending of CR LF: the CR is not part of the line's text. + const textEnd = end > start && md.charCodeAt(end - 1) === 13 ? end - 1 : end; + lines.push({ start, end, text: md.slice(start, textEnd), kind: "text" }); if (newline === -1) break; start = newline + 1; } + /** A row that continues the open table */ + const isRow = (i: number): boolean => + TABLE_ROW.test(lines[i].text) || (openLastRow && i === lines.length - 1 && lines[i].text.startsWith("|")); + let fence: Fence | null = null; let table: TableHead | null = null; for (let i = 0; i < lines.length; i++) { @@ -656,7 +651,7 @@ function scanLines(md: string): Line[] { table = null; continue; } - if (table && TABLE_ROW.test(line.text)) { + if (table && isRow(i)) { line.kind = "table-row"; line.table = table; continue; @@ -723,6 +718,14 @@ export function markdownToTelegramHtml(md: string): string { return out.join("\n").replace(/<\/blockquote>\n /g, "\n"); } +/** + * True if Telegram HTML has something to show. Telegram refuses a message + * that has none, such as an empty code block. + */ +export function hasVisibleText(html: string): boolean { + return html.replace(/<[^>]*>/g, "").trim() !== ""; +} + // ── Splitting ───────────────────────────────────────── /** One message's worth of markdown */ @@ -850,7 +853,8 @@ export function takeMarkdownChunk(prefix: string, body: string, limit = TELEGRAM } const doc = prefix + body.slice(0, reach); const base = prefix.length; - const lines = scanLines(doc); + // The end of the body may be the middle of a row (a stream). + const lines = scanLines(doc, reach === body.length); /** The chunk that ends at `end`, or null if it does not fit (unless forced) */ const chunkTo = (end: number, force = false): TakenChunk | null => { @@ -890,15 +894,20 @@ export function takeMarkdownChunk(prefix: string, body: string, limit = TELEGRAM for (let index = best; index > first && index > best - 4; index--) { if (isAwkwardCut(lines, index, base)) continue; const chunk = index === best ? bestChunk : chunkTo(lines[index].start); - if (chunk) return chunk; + if (chunk && hasVisibleText(chunk.html)) return chunk; } - return bestChunk; + // Every cut near the end is awkward. Take the last one, unless the chunk + // would show nothing: blank lines, or a fence line and its closing fence + // when the first line of a code block is too long. Telegram refuses such + // a message, so cut inside the line after it instead. + if (hasVisibleText(bestChunk.html)) return bestChunk; } - // The first line alone is too long: cut inside it. - const line = lines[first]; + // One line alone is too long: cut inside it. + const line = lines[bestChunk ? best : first]; + const floor = Math.max(line.start, base); let cut = -1; - lo = base + 1; + lo = floor + 1; hi = Math.min(line.end, base + limit); while (lo <= hi) { const mid = (lo + hi) >> 1; @@ -910,10 +919,11 @@ export function takeMarkdownChunk(prefix: string, body: string, limit = TELEGRAM } } if (cut === -1) { + if (bestChunk) return bestChunk; // Not even one character fits beside the prefix. Move forward anyway. - cut = base + 1; + cut = floor + 1; } else if (cut < line.end) { - for (let at = cut; at > base + ((cut - base) >> 1); at--) { + for (let at = cut; at > floor + ((cut - floor) >> 1); at--) { if (doc[at - 1] === " " || doc[at - 1] === "\t") { cut = at; break; @@ -934,10 +944,10 @@ export function takeMarkdownChunk(prefix: string, body: string, limit = TELEGRAM }; const unsafe = (at: number) => isSurrogatePairAt(doc, at) || changesMeaning(at); const preferred = cut; - for (let n = 0; n < MAX_CUT_BACKOFF && cut > base + 1 && unsafe(cut); n++) cut--; + for (let n = 0; n < MAX_CUT_BACKOFF && cut > floor + 1 && unsafe(cut); n++) cut--; if (unsafe(cut)) { cut = preferred; - if (isSurrogatePairAt(doc, cut)) cut += cut > base + 1 ? -1 : 1; + if (isSurrogatePairAt(doc, cut)) cut += cut > floor + 1 ? -1 : 1; } return chunkTo(cut, true)!; @@ -992,7 +1002,7 @@ export function splitMarkdownForTelegram( */ export function resumeMarkdownAt(prefix: string, body: string, offset: number): { offset: number; prefix: string } { const doc = prefix + body; - const lines = scanLines(doc); + const lines = scanLines(doc, true); const at = prefix.length + offset; const line = lines[lineIndexAt(lines, at)]; const afterLine = Math.min(line.end + 1, doc.length) - prefix.length; diff --git a/src/transports/telegram/html.ts b/src/transports/telegram/html.ts index 1649190..fc20982 100644 --- a/src/transports/telegram/html.ts +++ b/src/transports/telegram/html.ts @@ -10,11 +10,14 @@ * Two rules hold for everything sent from here: * - Nothing is truncated. A text too long for one message is split in its * markdown source, so that each piece renders within Telegram's limit. - * - A rate limit (HTTP 429) is waited out, not ignored. + * - A rate limit (HTTP 429) is waited out, not ignored, for up to + * `MAX_RATE_LIMIT_WAIT_MS` per answer. Telegram is never called inside a + * wait it asked for. */ import { TELEGRAM_MESSAGE_LIMIT, + hasVisibleText, markdownToTelegramHtml, resumeMarkdownAt, splitMarkdownForTelegram, @@ -35,8 +38,12 @@ export const STREAM_EDIT_INTERVAL_MS = 1100; */ export const STREAM_EDIT_INTERVAL_GROUP_MS = 3100; -/** Longest time spent waiting out rate limits for one call that must get through (ms) */ -export const MAX_RATE_LIMIT_WAIT_MS = 30_000; +/** + * Longest time one answer (one post, or one stream) spends waiting out rate + * limits (ms). A wait that does not fit in what is left is not started: the + * text is reported as not delivered instead. + */ +export const MAX_RATE_LIMIT_WAIT_MS = 90_000; /** Tries for one call that must get through */ const MAX_DELIVERY_ATTEMPTS = 4; @@ -103,68 +110,114 @@ function isNotModified(err: unknown): boolean { return /message is not modified/i.test(String((err as Error | undefined)?.message ?? "")); } -/** Remembers when Telegram will accept calls again, and waits for it */ +/** A new message, or an edit of a message already sent */ +type CallKind = "send" | "edit"; + +/** + * Per adapter and chat: the time before which Telegram refuses new messages. + * Kept across answers, so the next answer to the same chat knows about a wait + * that is still running. + */ +const sendBlocks = new WeakMap{ const { chatId, messageThreadId } = parseTelegramThreadId(thread.id); const limiter = new RateLimiter(options, thread.adapter, chatId); - await postChunks(limiter, thread.adapter, chatId, messageThreadId, markdown, ""); + const heldBack = await postChunks(limiter, thread.adapter, chatId, messageThreadId, markdown, ""); + if (heldBack > 0) reportHeldBack(limiter, heldBack); } /** * Post `markdown` as one message per chunk. `prefix` is as in `takeMarkdownChunk`. * * Stops at the first chunk a rate limit keeps back: the chunks after it would - * arrive without it. What was not sent is logged once. + * arrive without it. Returns how many characters, counted from the end of + * `markdown`, were not sent for that reason (0 if none). */ async function postChunks( limiter: RateLimiter, @@ -292,18 +294,16 @@ async function postChunks( messageThreadId: number | undefined, markdown: string, prefix: string, -): Promise { +): Promise { const chunks = splitMarkdownForTelegram(markdown, TELEGRAM_MESSAGE_LIMIT, prefix); for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; // Telegram refuses a message with nothing to show. if (!hasVisibleText(chunk.html)) continue; const outcome = await sendHtmlOrPlain(limiter, adapter, chatId, messageThreadId, chunk.html, chunk.text); - if (outcome === "rate-limited") { - reportHeldBack(limiter, markdown.length - chunk.start); - return; - } + if (outcome === "rate-limited") return markdown.length - chunk.start; } + return 0; } /** Log text that a rate limit kept from being sent */ @@ -311,7 +311,8 @@ function reportHeldBack(limiter: RateLimiter, characters: number): void { const wait = Math.max(0, Math.ceil((limiter.until("send") - limiter.now()) / 1000)); console.error( `[roundhouse] Telegram rate limit: ${characters} characters not delivered. ` + - `Telegram asked for a wait of ${wait} s, more than is left of the ${MAX_RATE_LIMIT_WAIT_MS / 1000} s an answer waits.`, + (wait > 0 ? `Telegram asks for another ${wait} s; an ` : "An ") + + `answer waits ${MAX_RATE_LIMIT_WAIT_MS / 1000} s in total.`, ); } @@ -332,6 +333,10 @@ function reportHeldBack(limiter: RateLimiter, characters: number): void { * again once Telegram allows, and if the bubble still cannot be edited, the * text it does not show is posted as a new message. * + * Once a rate limit has held back part of the answer (see `RateLimiter`), + * nothing after that part is sent: it would arrive with a gap. The stream is + * still read to its end, and what was not sent is logged once. + * * If the stream itself fails, what has arrived is still delivered, and the * error is thrown afterwards. */ @@ -363,6 +368,8 @@ export async function handleTelegramHtmlStream( let latest = ""; /** A text Telegram refused for the open bubble for another reason than a rate limit */ let refused: string | null = null; + /** Source offset from which a rate limit held the text back, or -1. Nothing is sent after it. */ + let heldBackFrom = -1; /** The source of the open bubble */ const body = () => accumulated.slice(committed); @@ -397,7 +404,10 @@ export async function handleTelegramHtmlStream( /** True if the open bubble has text that is not on screen and is worth trying */ const updatePending = (): boolean => - hasVisibleText(latest) && latest !== refused && (messageId === null || !sameText(latest, shown)); + heldBackFrom === -1 && + hasVisibleText(latest) && + latest !== refused && + (messageId === null || !sameText(latest, shown)); /** The earliest time an update of the open bubble may be tried */ const updateDueAt = (): number => Math.max(lastAttemptAt + editInterval, limiter.until(updateKind())); @@ -469,7 +479,7 @@ export async function handleTelegramHtmlStream( // Nothing of this bubble is on screen yet: post it whole. if (hasVisibleText(chunk.html)) { const outcome = await sendHtmlOrPlain(limiter, thread.adapter, chatId, messageThreadId, chunk.html, chunk.text); - if (outcome === "rate-limited") reportHeldBack(limiter, source.length); + if (outcome === "rate-limited") heldBackFrom = committed; lastAttemptAt = limiter.now(); } } else if (!sameText(chunk.html, shown)) { @@ -481,7 +491,8 @@ export async function handleTelegramHtmlStream( const resume = resumeMarkdownAt(prefix, source, shownLength); const rest = source.slice(resume.offset); if (rest.trim()) { - await postChunks(limiter, thread.adapter, chatId, messageThreadId, rest, resume.prefix); + const heldBack = await postChunks(limiter, thread.adapter, chatId, messageThreadId, rest, resume.prefix); + if (heldBack > 0) heldBackFrom = end - heldBack; } } else { // It shows more than the chunk: the start of a line that belongs @@ -534,15 +545,17 @@ export async function handleTelegramHtmlStream( next = null; if (result.done) break; accumulated += result.value; + // Nothing more is sent after a part that was held back. + if (heldBackFrom !== -1) continue; // Half of a character that takes two code units: Telegram refuses it. // The other half comes with the next piece. if (endsInHalfCharacter(accumulated)) continue; let html = renderOpen(); - while (html === null) { + while (html === null && heldBackFrom === -1) { await closeBubble(takeMarkdownChunk(prefix, body())); html = renderOpen(); } - await updateBubble(html); + if (html !== null) await updateBubble(html); } } catch (err) { failed = true; @@ -551,8 +564,9 @@ export async function handleTelegramHtmlStream( // Final: whatever the open bubble holds. It fits one message, unless // closing a code block that is still open pushes it over. - while (body().trim()) { + while (heldBackFrom === -1 && body().trim()) { await closeBubble(takeMarkdownChunk(prefix, body())); } + if (heldBackFrom !== -1) reportHeldBack(limiter, accumulated.length - heldBackFrom); if (failed) throw failure; } diff --git a/test/telegram-delivery.test.ts b/test/telegram-delivery.test.ts index 21c4ef7..a841068 100644 --- a/test/telegram-delivery.test.ts +++ b/test/telegram-delivery.test.ts @@ -362,6 +362,39 @@ describe("a Telegram rate limit (HTTP 429) during streaming", () => { expect(t.visible()[0]).toBe(answer.slice(0, answer.length - lost)); }); + it("stops a streamed answer after a part that a rate limit holds back", async () => { + const clock = fakeClock(); + let sends = 0; + const t = fakeTelegram({ + now: clock.now, + // The message that would open the second bubble is refused for ten minutes. + fail: (call) => (call.method === "sendMessage" && ++sends === 2 ? rateLimitError(600) : null), + }); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + const all = lines(0, 220); + const answer = all.join("\n"); + async function* pieces() { + for (let i = 0; i < all.length; i++) { + // The second bubble fills up while the limit is on. Then the stream + // pauses for longer than the limit lasts, and goes on. + clock.advance(i === 170 ? 700_000 : 50); + yield all[i] + (i < all.length - 1 ? "\n" : ""); + } + } + + await handleTelegramHtmlStream(t, pieces(), clock); + + // The first bubble arrived. The second was held back, so the third is not + // sent either, although Telegram would take it by then: it would follow + // the first with a hole in between. + expect(t.messages()).toHaveLength(1); + expect(t.calls.filter((c) => c.failed)).toHaveLength(1); + expect(errors).toHaveBeenCalledTimes(1); + const lost = Number(/(\d+) characters not delivered/.exec(String(errors.mock.calls[0][0]))?.[1]); + expect(lost).toBeGreaterThan(8000); + expect(t.visible()[0].trimEnd()).toBe(answer.slice(0, answer.length - lost).trimEnd()); + }); + it("waits 90 seconds for one answer in total, not for each message", async () => { const clock = fakeClock(); // Every message is refused once, with a wait of 40 seconds. @@ -570,6 +603,32 @@ describe("a stream that goes quiet", () => { await vi.advanceTimersByTimeAsync(60_000); await delivery; }); + + it("does not keep the answer waiting for a rate limit once the stream has ended", async () => { + vi.useFakeTimers(); + const t = fakeTelegram({ + now: Date.now, + fail: (call) => (call.method === "editMessageText" ? rateLimitError(600) : null), + }); + const pause = (ms: number) => new Promise ((resolve) => setTimeout(resolve, ms)); + async function* pieces() { + yield "One."; + await pause(1200); + yield " Two."; // this edit is refused for ten minutes + await pause(2000); + } + const started = Date.now(); + let finishedAfter = -1; + + const delivery = handleTelegramHtmlStream(t, pieces()).then(() => { finishedAfter = Date.now() - started; }); + await vi.advanceTimersByTimeAsync(10_000); + await delivery; + + // Done when the stream was, not ten minutes later, and no timer is left behind. + expect(finishedAfter).toBeLessThanOrEqual(3300); + expect(vi.getTimerCount()).toBe(0); + expect(t.visible().join("")).toBe("One. Two."); + }); }); describe("a table that is being streamed when a message fills up", () => {