Skip to content

fix(telegram): silently skip empty-text sends instead of failing - #54167

Closed
amittell wants to merge 5 commits into
openclaw:mainfrom
amittell:fix/empty-text-silent-skip
Closed

amittell wants to merge 5 commits into
openclaw:mainfrom
amittell:fix/empty-text-silent-skip

Conversation

@amittell

Copy link
Copy Markdown
Contributor

Problem

When an agent reply normalizes to empty or whitespace-only text, the following chain fires and sends a spurious fallback message to the user:

  1. sendTelegramText throws (pre-send check) OR Telegram rejects the API call with 400: text must be non-empty / 400: message text is empty
  2. The throw propagates to onError in bot-message-dispatch.ts
  3. markNonSilentFailure() fires → sends "No response generated. Please try again."

This produces a confusing user-visible error for something that should silently no-op.

Fixes #37278. Supersedes #37294 (incomplete fix). Replaces accidentally-closed #40384.

Root causes fixed

Mode A — pre-send empty check threw instead of skipping

sendTelegramText threw "empty formatted text and empty plain fallback" when htmlText and plainText were both empty. Changed to logVerbose + return undefined.

Mode B — empty chunks reached sendTelegramText in delivery functions

deliverTextReply, sendPendingFollowUpText, sendTelegramVoiceFallbackText passed chunks with empty html AND empty text to sendTelegramText. Added pre-send guards. Also fixed replyToMode="first" threading to attach to the first actually sent chunk via sentAnyChunk flag (was using chunk index 0).

Mode C — EMPTY_TEXT_ERR_RE regex didn't match Telegram's newer error wording

Telegram has two variants: "message text is empty" (old) and "text must be non-empty" (new). The catch block only matched the old form. Updated regex: /message text is empty|text must be non-empty/i

Mode D — catch block threw instead of returning undefined when no fallback

When the empty-text error was caught but no fallback text was available, the code threw instead of returning undefined. Changed to logVerbose + return undefined.

Mode E — send.ts HTML-parse fallback didn't handle empty-text errors

withTelegramHtmlParseFallback in send.ts only caught HTML parse errors. Added empty-text error handling alongside it.

Files changed

  • src/telegram/bot/delivery.send.ts — Modes A, C, D
  • src/telegram/bot/delivery.replies.ts — Mode B + sentAnyChunk fix
  • src/telegram/send.ts — Mode E
  • src/telegram/bot/delivery.test.ts — new tests for A, B, C, D
  • src/telegram/send.test.ts — new test for Mode E

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
Copilot AI review requested due to automatic review settings March 25, 2026 02:14
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: M r: too-many-prs Auto-close: author has more than twenty active PRs. labels Mar 25, 2026
@greptile-apps

greptile-apps Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR comprehensively fixes a multi-mode bug where empty or whitespace-only agent replies triggered a spurious "No response generated" error message to Telegram users instead of silently no-op'ing. The fix covers five independent failure paths (Modes A–E) spanning pre-send checks, in-flight chunk delivery guards, an outdated regex for Telegram's newer error wording, a missing plain-text fallback path, and the HTML parse fallback in send.ts.

Key changes:

  • delivery.send.ts: sendTelegramText now returns undefined instead of throwing when text is empty (Modes A & D); return type widened to Promise<number | undefined>.
  • delivery.replies.ts: Empty-chunk guards added to deliverTextReply, sendPendingFollowUpText, and sendTelegramVoiceFallbackText; appliedReplyTo renamed to sentAnyChunk to correctly track the first actually sent chunk for button/reply attachment (Mode B).
  • network-errors.ts: EMPTY_TEXT_ERR_RE centralised and updated to match both "message text is empty" (legacy) and "text must be non-empty" (current) Telegram wording (Mode C).
  • send.ts: withTelegramHtmlParseFallback extended to also handle empty-text errors, triggering the same plain-text retry as HTML parse errors (Mode E).
  • Tests added for all new modes, including updating the old "should throw" test to "should silently skip".

One inconsistency remains in reply-threading.ts: shouldAttachQuote still gates on isFirstChunk (chunk index 0) when quoteOnlyOnFirstChunk = true, not on the new isFirstSentChunk flag. This is latent (no current caller sets quoteOnlyOnFirstChunk = true) but is inconsistent with the intent of the isFirstSentChunk fix applied to replyMarkup in the same loop.

Confidence Score: 5/5

  • Safe to merge — all five failure modes are well-targeted, well-tested, and the changes are additive (throw→return undefined, not return→throw).
  • The fix is clearly scoped, each mode is independently tested, the undefined return path is consistently handled at every call site, and no existing behaviour is regressed. The one inconsistency flagged (quoteOnlyOnFirstChunk still using isFirstChunk) is latent and carries no active risk.
  • extensions/telegram/src/bot/reply-threading.ts — the shouldAttachQuote condition should use isFirstSentChunk instead of isFirstChunk for full consistency.

Comments Outside Diff (1)

  1. extensions/telegram/src/bot/reply-threading.ts, line 74-77 (link)

    P2 quoteOnlyOnFirstChunk not updated to use isFirstSentChunk

    The PR correctly moved replyMarkup from isFirstChunk to isFirstSentChunk, but the shouldAttachQuote condition still uses isFirstChunk (chunk index 0):

    const shouldAttachQuote =
      Boolean(replyToMessageId) &&
      Boolean(params.replyQuoteText) &&
      (params.quoteOnlyOnFirstChunk !== true || isFirstChunk);  // ← still uses isFirstChunk

    When quoteOnlyOnFirstChunk = true and chunk 0 is empty (returns false from sendChunk), chunk 1 will have isFirstSentChunk = true and a valid replyToMessageId, but shouldAttachQuote will be false because isFirstChunk = false (i !== 0). The quote text would be silently dropped even though a valid first-sent chunk is available.

    The fix is consistent with the replyMarkup change made here:

    quoteOnlyOnFirstChunk is not set by any of the current callers visible in this diff so this isn't an active regression, but it's an inconsistency introduced by this PR that could silently drop quote text in future callers.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: extensions/telegram/src/bot/reply-threading.ts
    Line: 74-77
    
    Comment:
    **`quoteOnlyOnFirstChunk` not updated to use `isFirstSentChunk`**
    
    The PR correctly moved `replyMarkup` from `isFirstChunk` to `isFirstSentChunk`, but the `shouldAttachQuote` condition still uses `isFirstChunk` (chunk index 0):
    
    ```typescript
    const shouldAttachQuote =
      Boolean(replyToMessageId) &&
      Boolean(params.replyQuoteText) &&
      (params.quoteOnlyOnFirstChunk !== true || isFirstChunk);  // ← still uses isFirstChunk
    ```
    
    When `quoteOnlyOnFirstChunk = true` and chunk 0 is empty (returns `false` from `sendChunk`), chunk 1 will have `isFirstSentChunk = true` and a valid `replyToMessageId`, but `shouldAttachQuote` will be `false` because `isFirstChunk = false` (i !== 0). The quote text would be silently dropped even though a valid first-sent chunk is available.
    
    The fix is consistent with the `replyMarkup` change made here:
    
    
    
    `quoteOnlyOnFirstChunk` is not set by any of the current callers visible in this diff so this isn't an active regression, but it's an inconsistency introduced by this PR that could silently drop quote text in future callers.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/reply-threading.ts
Line: 74-77

Comment:
**`quoteOnlyOnFirstChunk` not updated to use `isFirstSentChunk`**

The PR correctly moved `replyMarkup` from `isFirstChunk` to `isFirstSentChunk`, but the `shouldAttachQuote` condition still uses `isFirstChunk` (chunk index 0):

```typescript
const shouldAttachQuote =
  Boolean(replyToMessageId) &&
  Boolean(params.replyQuoteText) &&
  (params.quoteOnlyOnFirstChunk !== true || isFirstChunk);  // ← still uses isFirstChunk
```

When `quoteOnlyOnFirstChunk = true` and chunk 0 is empty (returns `false` from `sendChunk`), chunk 1 will have `isFirstSentChunk = true` and a valid `replyToMessageId`, but `shouldAttachQuote` will be `false` because `isFirstChunk = false` (i !== 0). The quote text would be silently dropped even though a valid first-sent chunk is available.

The fix is consistent with the `replyMarkup` change made here:

```suggestion
    const shouldAttachQuote =
      Boolean(replyToMessageId) &&
      Boolean(params.replyQuoteText) &&
      (params.quoteOnlyOnFirstChunk !== true || isFirstSentChunk);
```

`quoteOnlyOnFirstChunk` is not set by any of the current callers visible in this diff so this isn't an active regression, but it's an inconsistency introduced by this PR that could silently drop quote text in future callers.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: extensions/telegram/src/bot/reply-threading.ts
Line: 57

Comment:
**Confusing boolean flag name**

`firstSentChunk` reads like a reference to the first sent chunk (an object or ID), but it's actually a boolean flag meaning "has any chunk been sent yet?" The equivalent variable in `delivery.replies.ts` was named `sentAnyChunk`, which is much clearer.

```suggestion
  let sentAnyChunk = false;
```

(And correspondingly update `const isFirstSentChunk = !sentAnyChunk;` and `sentAnyChunk = true;` below.)

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(telegram): key reply markup off firs..." | Re-trigger Greptile

}) => Promise<boolean | void>;
}): Promise<void> {
const applyDelivered = params.markDelivered ?? markDelivered;
let firstSentChunk = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Confusing boolean flag name

firstSentChunk reads like a reference to the first sent chunk (an object or ID), but it's actually a boolean flag meaning "has any chunk been sent yet?" The equivalent variable in delivery.replies.ts was named sentAnyChunk, which is much clearer.

Suggested change
let firstSentChunk = false;
let sentAnyChunk = false;

(And correspondingly update const isFirstSentChunk = !sentAnyChunk; and sentAnyChunk = true; below.)

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/reply-threading.ts
Line: 57

Comment:
**Confusing boolean flag name**

`firstSentChunk` reads like a reference to the first sent chunk (an object or ID), but it's actually a boolean flag meaning "has any chunk been sent yet?" The equivalent variable in `delivery.replies.ts` was named `sentAnyChunk`, which is much clearer.

```suggestion
  let sentAnyChunk = false;
```

(And correspondingly update `const isFirstSentChunk = !sentAnyChunk;` and `sentAnyChunk = true;` below.)

How can I resolve this? If you propose a fix, please make it concise.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR updates the Telegram delivery stack to treat empty/whitespace-only outbound text as a silent no-op (or a plain-text retry when appropriate), preventing user-visible fallback errors and avoiding Telegram API 400s for empty text.

Changes:

  • Make sendTelegramText skip (return undefined) when both formatted HTML and plain-text fallback are empty, and expand empty-text error matching to include Telegram’s newer wording.
  • Add pre-send empty-chunk guards in reply delivery paths and ensure reply markup (“first chunk”) attaches to the first actually sent chunk.
  • Extend withTelegramHtmlParseFallback to also treat empty-text errors as retryable-with-plain-text, and add targeted tests for these cases.

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/bot/delivery.send.ts Skip/return undefined on empty-text conditions; use shared empty-text regex; adjust return type.
extensions/telegram/src/bot/delivery.replies.ts Guard against empty chunks; ensure reply markup/reply-to bookkeeping doesn’t advance on skipped sends.
extensions/telegram/src/bot/reply-threading.ts Allow sendChunk to signal “not sent” and attach markup to first sent chunk.
extensions/telegram/src/send.ts Treat empty-text errors like HTML-parse errors for plain-text retry in tool/send path.
extensions/telegram/src/bot/delivery.test.ts Add/adjust tests for empty skips, markup threading, and updated empty-text wording.
extensions/telegram/src/send.test.ts Add tests covering both “text must be non-empty” and “message text is empty” retry behavior.
extensions/telegram/src/network-errors.ts Introduce shared EMPTY_TEXT_ERR_RE for consistent empty-text detection.
.gitignore Add ignore entry for subagent-resume-worktree.

Comment on lines +96 to +100
function markReplyApplied(progress: DeliveryProgress, replyToId?: number): void {
if (replyToId && !progress.hasReplied) {
progress.hasReplied = true;
}
}

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

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

markReplyApplied() is reimplemented here even though the same helper exists (and is exported) from bot/reply-threading.ts. Reusing the shared helper would reduce duplication and help keep reply-threading semantics consistent across text and media delivery paths.

Copilot uses AI. Check for mistakes.
Comment on lines +57 to 58
let firstSentChunk = false;
for (let i = 0; i < params.chunks.length; i += 1) {

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

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

Variable naming is a bit misleading: firstSentChunk is used as a "sent any chunk yet" flag, not as "the first sent chunk". Renaming it (e.g. to sentAnyChunk/hasSentChunk) would make the isFirstSentChunk logic easier to follow and reduce the chance of future mistakes.

Copilot uses AI. Check for mistakes.
Comment on lines +431 to +435
if (!isTelegramHtmlParseError(err) && !isTelegramEmptyTextError(err)) {
throw err;
}
if (params.verbose) {
const errorKind = isTelegramEmptyTextError(err) ? "empty text" : "HTML parse";

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

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

In this catch block, formatErrorMessage(err) is computed multiple times via isTelegramHtmlParseError/isTelegramEmptyTextError (and then again for logging). Consider formatting the error message once and reusing it for both the regex checks and the log to avoid repeated parsing/normalization work.

Suggested change
if (!isTelegramHtmlParseError(err) && !isTelegramEmptyTextError(err)) {
throw err;
}
if (params.verbose) {
const errorKind = isTelegramEmptyTextError(err) ? "empty text" : "HTML parse";
const isHtmlParseError = isTelegramHtmlParseError(err);
const isEmptyTextError = isTelegramEmptyTextError(err);
if (!isHtmlParseError && !isEmptyTextError) {
throw err;
}
if (params.verbose) {
const errorKind = isEmptyTextError ? "empty text" : "HTML parse";

Copilot uses AI. Check for mistakes.
Comment on lines +86 to +90
function resolveReplyToForSend(params: {
replyToId?: number;
replyToMode: ReplyToMode;
progress: DeliveryProgress;
}): number | undefined {

Copilot AI Mar 25, 2026

Copy link

Choose a reason for hiding this comment

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

The newly added resolveReplyToForSend() duplicates the exported helper in bot/reply-threading.ts. Consider importing and reusing reply-threading's resolveReplyToForSend to avoid logic drift (especially since reply-threading.ts is already a dependency via sendChunkedTelegramReplyText).

Copilot uses AI. Check for mistakes.
@openclaw-barnacle

Copy link
Copy Markdown

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram r: too-many-prs Auto-close: author has more than twenty active PRs. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Telegram channel crashes when agent emits empty reply (GrammyError 400: text must be non-empty)

2 participants