Repository navigation
Conversation
Move changes to correct paths (extensions/telegram/src/ not src/telegram/). Modes A–E all applied to the real source files: A. deliverTextReply: inline loop with empty-chunk skip (sentAnyChunk flag), replacing sendChunkedTelegramReplyText. Buttons attach to first sent chunk (not first iteration index), guarded by messageId != null. B. sendPendingFollowUpText + sendTelegramVoiceFallbackText: same inline loop pattern with null-chunk guard and empty-HTML+text guard. C. EMPTY_TEXT_ERR_RE exported from network-errors.ts, matching both 'message text is empty' and 'text must be non-empty'. Local definitions removed from delivery.send.ts; send.ts imports from same shared source. D. sendTelegramText (delivery.send.ts): return undefined instead of throw when empty-text has no plain fallback; logVerbose both skip paths. Return type widened to Promise<number | undefined>. E. withTelegramHtmlParseFallback (send.ts): also catches empty-text errors (isTelegramEmptyTextError) and retries with plain text, matching parse-error fallback behavior. isTelegramEmptyTextError added. Inline resolveReplyToForSend + markReplyApplied replacing reply-threading import that was removed. DeliveryProgress now self-contained. Tests: update 'throws when empty' → 'silently skips'; add: - 'attaches buttons only to first sent chunk' (multi-chunk, sentAnyChunk) - 'falls back to plain text on text must be non-empty' (Mode C, delivery) - 'retries with plain text on text must be non-empty' (Mode E, send.ts) - 'retries with plain text on message text is empty' (Mode E, send.ts) Closes openclaw#37278.
sendTelegramVoiceFallbackText can return undefined when all chunks are empty (e.g. formatting-only fallback text that trims to whitespace). Previously, markReplyApplied and markDelivered were called unconditionally after the voice fallback, reporting the reply as delivered and advancing reply threading even though no Telegram message was actually sent. Fix: only call markReplyApplied/markDelivered when fallbackMessageId is non-null, indicating at least one chunk was successfully sent. Fixes #2937611198
|
Closing this PR because the author has more than 10 active PRs in this repo. Please reduce the active PR queue and reopen or resubmit once it is back under the limit. You can close your own PRs to get back under the limit. |
Greptile SummaryThis PR extends the Telegram delivery pipeline to silently skip messages that are empty or would render blank, fixing a regression where interrupted mid-reply turns sent bare The main inconsistency to be aware of: Confidence Score: 5/5
|
| if (!chunk.html?.trim() && !chunk.text?.trim()) { | ||
| logVerbose("telegram: skipping empty chunk in deliverTextReply"); | ||
| return false; |
There was a problem hiding this comment.
Pre-send guard uses AND — HTML-only whitespace tags like
<br> bypass it
The condition !chunk.html?.trim() && !chunk.text?.trim() requires both sides to be blank. A chunk carrying only chunk.html = "<br>" with chunk.text = "\n" would pass the guard ("<br>".trim() is non-empty) and reach sendTelegramText. Protection then depends on Telegram rejecting the <br> payload with the new EMPTY_TEXT_ERR_RE variants — which works, but only if Telegram rejects rather than renders it as a blank line.
The PR description explicitly calls out <br> as the triggering case, so it may be worth adding a direct check for known HTML-only whitespace-equivalent tags here (e.g. a /^(\s|<br\s*\/?>|<\/?p>|<\/?div>)*$/i guard as mentioned in the PR summary), rather than relying solely on the Telegram API rejection path.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/delivery.replies.ts
Line: 134-136
Comment:
**Pre-send guard uses AND — HTML-only whitespace tags like `<br>` bypass it**
The condition `!chunk.html?.trim() && !chunk.text?.trim()` requires *both* sides to be blank. A chunk carrying only `chunk.html = "<br>"` with `chunk.text = "\n"` would pass the guard (`"<br>".trim()` is non-empty) and reach `sendTelegramText`. Protection then depends on Telegram rejecting the `<br>` payload with the new `EMPTY_TEXT_ERR_RE` variants — which works, but only if Telegram rejects rather than renders it as a blank line.
The PR description explicitly calls out `<br>` as the triggering case, so it may be worth adding a direct check for known HTML-only whitespace-equivalent tags here (e.g. a `/^(\s|<br\s*\/?>|<\/?p>|<\/?div>)*$/i` guard as mentioned in the PR summary), rather than relying solely on the Telegram API rejection path.
How can I resolve this? If you propose a fix, please make it concise.| function resolveReplyToForSend(params: { | ||
| replyToId?: number; | ||
| replyToMode: ReplyToMode; | ||
| progress: DeliveryProgress; | ||
| }): number | undefined { | ||
| return params.replyToId && (params.replyToMode === "all" || !params.progress.hasReplied) | ||
| ? params.replyToId | ||
| : undefined; | ||
| } | ||
|
|
||
| function markReplyApplied(progress: DeliveryProgress, replyToId?: number): void { | ||
| if (replyToId && !progress.hasReplied) { | ||
| progress.hasReplied = true; | ||
| } | ||
| } |
There was a problem hiding this comment.
Duplicated helpers that are still exported from
reply-threading.ts
resolveReplyToForSend and markReplyApplied are now defined locally here with identical logic, but the originals in reply-threading.ts are still exported (and unused). Consider either re-importing the shared implementations or removing the now-dead exports from reply-threading.ts to prevent divergence over time.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/delivery.replies.ts
Line: 86-100
Comment:
**Duplicated helpers that are still exported from `reply-threading.ts`**
`resolveReplyToForSend` and `markReplyApplied` are now defined locally here with identical logic, but the originals in `reply-threading.ts` are still exported (and unused). Consider either re-importing the shared implementations or removing the now-dead exports from `reply-threading.ts` to prevent divergence over time.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
Pull request overview
This PR hardens the Telegram outbound send path against “empty” messages by broadening empty-text error detection, making empty sends no-op instead of throwing, and improving chunked reply threading so UI elements attach to the first actually delivered chunk.
Changes:
- Exported and reused a shared
EMPTY_TEXT_ERR_REto match both legacy and newer Telegram empty-text error variants. - Updated send fallbacks to treat empty-text rejections similarly to HTML parse errors, retrying as plain text (or skipping if no fallback).
- Adjusted chunked reply threading to attach
reply_markupto the first successfully sent chunk and to avoid delivery bookkeeping for skipped chunks; added/updated tests.
Reviewed changes
Copilot reviewed 7 out of 8 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| extensions/telegram/src/network-errors.ts | Adds shared EMPTY_TEXT_ERR_RE covering both Telegram empty-text error variants. |
| extensions/telegram/src/bot/delivery.send.ts | Reuses shared empty-text regex; changes empty-send behavior to log+skip and returns undefined instead of throwing. |
| extensions/telegram/src/send.ts | Extends HTML-parse fallback helper to also catch empty-text errors and retry as plain text. |
| extensions/telegram/src/bot/reply-threading.ts | Allows sendChunk to signal “skipped” via false and uses that to attach markup to the first actually sent chunk. |
| extensions/telegram/src/bot/delivery.replies.ts | Adds pre-send empty guards and treats sendTelegramText() returning undefined as “not sent” for threading/bookkeeping. |
| extensions/telegram/src/send.test.ts | Adds regression tests ensuring plain-text retry for both empty-text error variants. |
| extensions/telegram/src/bot/delivery.test.ts | Updates empty-send expectation to “skip”; adds tests around chunking/markup and empty-text variant handling. |
| .gitignore | Ignores subagent-resume-worktree. |
| // Silently skip empty chunks instead of sending a blank message that | ||
| // would trigger a Telegram API error. | ||
| if (!chunk.html?.trim() && !chunk.text?.trim()) { | ||
| logVerbose("telegram: skipping empty chunk in deliverTextReply"); | ||
| return false; |
There was a problem hiding this comment.
The empty-chunk guard only checks .trim() on the raw HTML/text strings, so it will not skip HTML-only whitespace like <br>, <p></p>, <div></div>, etc. Those strings are non-empty after .trim(), but still render as empty on Telegram and will hit the API (and rely on a 400 to no-op). Consider adding a helper that strips known whitespace-only HTML tags (and normalizes to plain text) and using it in this guard (and the similar guards in sendPendingFollowUpText / sendTelegramVoiceFallbackText).
| if (!chunk.html?.trim() && !chunk.text?.trim()) { | ||
| logVerbose("telegram: skipping empty chunk in sendPendingFollowUpText"); | ||
| return false; | ||
| } |
There was a problem hiding this comment.
This guard has the same limitation as the earlier one: .trim() won’t treat HTML-only whitespace like <br> / <p></p> as empty, so those chunks can still reach sendTelegramText and trigger a Telegram 400 before being skipped. Reuse a dedicated isHtmlWhitespaceOnly/normalization helper here to skip such chunks pre-send.
| if (!chunk || (!chunk.html?.trim() && !chunk.text?.trim())) { | ||
| logVerbose("telegram: skipping empty chunk in sendTelegramVoiceFallbackText"); | ||
| continue; | ||
| } |
There was a problem hiding this comment.
The voice-fallback loop skips only when both chunk.html and chunk.text are empty after .trim(). HTML-only whitespace like <br> / <p></p> won’t be skipped by this check, so it can still attempt an API send and rely on the empty-text rejection path. Consider using the same HTML-whitespace-only detection as the other send paths so these chunks are skipped without making a Telegram request.
| it("attaches buttons only to the first sent chunk when text spans multiple chunks", async () => { | ||
| // Verify sentAnyChunk logic: buttons attach to the first chunk that actually | ||
| // delivers, and not to any subsequent chunks. | ||
| // Use a small textLimit to force the text into multiple chunks. | ||
| const runtime = createRuntime(); | ||
| const sendMessage = vi.fn().mockResolvedValue({ message_id: 7, chat: { id: "123" } }); | ||
| const bot = createBot({ sendMessage }); | ||
|
|
||
| // "hello world" at textLimit=5 → chunks ["hello", "world"] (each ~5 chars). | ||
| await deliverWith({ | ||
| replies: [ | ||
| { | ||
| text: "hello world", | ||
| channelData: { | ||
| telegram: { | ||
| buttons: [[{ text: "Click me", callback_data: "action" }]], | ||
| }, | ||
| }, | ||
| }, | ||
| ], | ||
| runtime, | ||
| bot, | ||
| textLimit: 5, | ||
| }); | ||
|
|
||
| // Both chunks were sent | ||
| expect(sendMessage).toHaveBeenCalledTimes(2); | ||
| // reply_markup on first chunk only | ||
| const firstCall = sendMessage.mock.calls[0]; | ||
| const secondCall = sendMessage.mock.calls[1]; | ||
| expect(firstCall?.[2]).toHaveProperty("reply_markup"); | ||
| expect(secondCall?.[2]).not.toHaveProperty("reply_markup"); | ||
| }); |
There was a problem hiding this comment.
The new test name/comments suggest validating the “first actually sent chunk” behavior, but the setup ("hello world" split into two non-empty chunks) would have passed before the isFirstSentChunk change as well. To cover the regression, adjust the test so the first chunk is skipped (e.g., first chunk resolves to empty/whitespace and sendChunk returns false), then assert reply_markup is attached to the next delivered chunk.
|
Reopening — the empty-text/HTML-whitespace 400 delivery failures still happen on current main when interrupted mid-reply turns send bare |
|
Rebased onto current Because the upstream Behavior change is the same as the original PR for the specific empty-text path:
Verified that the new unit test fails on unpatched current Build proof: Trailer scan: Note: I was unable to programmatically reopen this PR via |
|
Superseded by #88810, which carries the rebased fix with a fresh proof block. GitHub refused to reopen this PR after the force-push ( |
Summary
Extends the empty-text skip guard to also catch messages containing only HTML whitespace tags (
<br>,<br/>,<p>,</p>,<div>,</div>) that would render as empty on Telegram.Root cause
When the gateway is interrupted mid-reply (active-turn-recovery), it sometimes sends
<br>as the entire message body. ThesanitizeForPlainTextfunction converts this to\n, but if the empty check runs before sanitization (or the send path bypasses normalization), the message reaches Telegram.Changes
delivery.replies.ts: AddedisHtmlWhitespaceOnly()helper and extended 3 empty-chunk guardsdelivery.test.ts: Added regression test for<br>,<br/>,\n<br>\n, etc.Supersedes closed #54167.
Tests: 34/34 passing ✅