Skip to content

fix(telegram): deliver long answers whole, keep code blocks intact, survive rate limits - #157

Merged
royosherove merged 9 commits into
mainfrom
fix/telegram-rendering
Nov 21, 2026
Merged

royosherove merged 9 commits into
mainfrom
fix/telegram-rendering

Conversation

@royosherove

@royosherove royosherove commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Why

Four defects in how agent output reaches Telegram, each reproduced with a failing test before it was fixed.

  1. Text was dropped at the 4096-character limit. The markdown was split at 3800 source characters, converted, and then cut with truncateHtmlSafe. HTML escaping and tags can push a chunk past the limit, so the cut removed text. An 11,000-character answer with a 140-line code block lost code lines on both the posting and the streaming path.
  2. A code block split across messages rendered as prose, with literal fences and its contents re-interpreted as markdown.
  3. A rate limit (HTTP 429) during streaming left the final message truncated. After one failed edit the throttle stopped applying, every later delta retried at once, and the final-edit failure was swallowed.
  4. The converter mangled common model output: 2 * 3 * 4, * bullets with emphasis, __init__, mis-nested emphasis, \* escapes, and formatting inside table cells.

What changes

  • Splitting measures the result. splitMarkdownForTelegram splits the source so each chunk's rendered HTML fits. Nothing is truncated. A fenced block that spans chunks is closed at the end of one and reopened with the same opening line in the next; a table repeats its header. A single line longer than the limit is hard-split, never dropped. Surrogate pairs and entities are not cut.
  • Streaming commits at exact source offsets, at the last line break whose rendered prefix fits, so each bubble starts on a line boundary and the bubbles together are the whole text.
  • Rate limits are obeyed. A 429 records when editing may resume; failed attempts count for the throttle. The final edit waits (30 s at most) and retries, and if it still fails the undelivered text is posted as a new message. The edit interval is 1100 ms in private chats and 3100 ms in groups, the Chat SDK's own floors.
  • Emphasis is paired by CommonMark delimiter rules instead of regexes, with backslash escapes, so the output is always well-formed HTML. Table cells are read as inline markdown and emitted as plain text (Telegram's <pre> may not contain other entities); links in cells are repeated under the table.

Behaviour changes to know

  • A single word in double underscores (__init__) stays literal; __two words__ is still bold. The two cannot be told apart otherwise.
  • An unclosed code fence renders as code to the end of the text, so code shows as code while it streams.
  • The end of a stream can wait up to 30 s for a rate limit to lift.
  • \. in prose loses its backslash, a consequence of honouring escapes.

Verification

  • npm test: 882 passing on this branch (with main merged in). npm run typecheck: clean.
  • A seeded property test runs 400 generated documents at Telegram's limit and 150 at smaller limits: every chunk's rendered HTML fits, removing the added fence lines and joining the chunks gives back the source exactly, and every chunk has balanced fences.
  • Delivery tests post and stream generated documents through a fake Telegram, including through rate limits, with an injected clock.
  • Not verified against real Telegram: how often 1100 ms edits draw a 429.

After the independent review (see the outcome comment below): an answer waits up to 90 s for rate limits and Telegram is never called inside a wait it asked for; a quiet stream shows its text when the next edit is due; no chunk is sent without visible text; the fake Telegram in the tests refuses what Telegram refuses.

…res 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 <pre>, 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.
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.
Telegram's <pre> 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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T20:08:01.615934Z 6c1278d New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 78e4772cab

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/transports/telegram/html.ts Resolved
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).
@royosherove

Copy link
Copy Markdown
Member Author

Independent review: outcome

A second reviewer read the branch and probed it with its own fuzzers and a stricter fake of the Bot API. No blockers; every should-fix finding is fixed, each with a test that fails on the code as it was.

# Finding Outcome
1 A rate limit longer than 30 s dropped one chunk and delivered the ones after it; the retry after the 30 s was made inside Telegram's wait Fixed. An answer waits up to 90 s in total. 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 is held back, later chunks are not sent, and the loss is logged once with its size
2 Streamed table rows after a message boundary rendered as raw pipes without a header Fixed. A cut before a half-written row is inside the table, so the next message repeats the header
3 Text sat unsent while the stream was quiet (a tool running) Fixed. A timer shows it when the next edit is due
4 A code block whose first line is too long produced a message of bare fences Fixed. No chunk without visible text: the cut goes inside the long line. The same rule covers blank lines before a long line
5 The thread used for boot, cron and sub-agent notices treated a refused call as success Fixed. It throws, so the retry after a rate limit and the plain-text fallback apply
6 Table cells beyond the header's column count were dropped Fixed
7 CR LF line endings; bold before punctuation (**Note:**text, CJK) Fixed
7 **bold **, a closing fence followed by text, \. in prose Left as CommonMark has them
8 Final edit not paced; edits that only change trailing whitespace Fixed
9 Stream failure lost the tail since the last edit; unused truncateHtmlSafe Fixed; helper removed
9 Lines of thousands of > or -, a 4,090-character table header, an edit whose response was lost Not fixed, recorded in futureplans/next-phase.md
10 The test fake accepted what Telegram refuses Fixed. It now refuses empty text, HTML it cannot parse, more than 4096 visible characters and unchanged edits. Tables are checked for content

Two of my own fixes were wrong at first and the reviewer's fuzzers caught them before the push: treating a half-written row as a row in the converter made very wide tables unsplittable, and a chunk could consist of a line break alone. Both have tests now.

Also added: a stream piece that ends in the middle of a surrogate pair is not sent until the other half arrives.

Still not handled, and listed in the plan: Telegram's limit on formatted spans per message (unverified), the growing per-piece cost of very long one-character streams, and telling the owner in chat when a rate limit made roundhouse give up on part of an answer.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 901a97ae07

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/transports/telegram/html.ts Resolved
Comment thread src/transports/telegram/html.ts Resolved
… 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.
@royosherove
royosherove merged commit de05f06 into main Nov 21, 2026
1 check passed
@royosherove
royosherove deleted the fix/telegram-rendering branch November 21, 2026 20:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant