Skip to content

fix(telegram): silently skip empty-text chunks to prevent 400 delivery failures - #49391

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

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

Conversation

@amittell

@amittell amittell commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When a long response is chunked for Telegram delivery, if any chunk (commonly the last chunk) is empty or whitespace-only, Telegram rejects it with:

400: Bad Request: text must be non-empty

OpenClaw then surfaces "No response generated. Please try again." to the user even though the actual content was delivered in the preceding chunks.

Root cause: HTML-only payloads producing whitespace after sanitization

An additional gap existed upstream of chunking: a payload containing only <br> (or similar HTML) passes the initial empty-payload check because "<br>" has non-whitespace content. sanitizeForPlainText then converts <br> → "\n" for plain-text surfaces (including Telegram). Without the post-sanitization empty check, the now-whitespace-only payload would be forwarded to Telegram as a blank message.

normalizeEmptyPayloadForDelivery is correctly called after sanitization in normalizePayloadsForChannelDelivery — "\n".trim() === "" causes the payload to be dropped. This PR adds JSDoc to make the ordering invariant explicit and adds a Telegram-specific regression test.

Production failure (2026-03-17)

A large markdown response (scheduler architecture writeup) was split into 2 chunks. The second chunk was empty after splitting:

telegram sendMessage failed: Call to 'sendMessage' failed! (400: Bad Request: text must be non-empty)
telegram final reply failed: GrammyError: Call to 'sendMessage' failed! (400: Bad Request: text must be non-empty)

Result: user saw "No response generated." despite the full content being delivered in chunk 1.

Root causes

  1. EMPTY_TEXT_ERR_RE only matched "message text is empty" but NOT Telegram's newer "text must be non-empty" error variant.

  2. Empty chunks were not pre-filtered — sendTelegramText was called with an empty string, Telegram rejected it, and OpenClaw propagated the error rather than skipping.

  3. isFirstChunk was computed as i === 0 — if chunk 0 was empty and skipped, inline buttons and reply threading would not be attached to the first actually sent chunk.

  4. <br>-only payloads reach Telegram as "\n" — sanitizeForPlainText converts <br> → "\n" before delivery. normalizeEmptyPayloadForDelivery runs post-sanitization and drops these correctly, but the ordering invariant was undocumented and untested for Telegram.

Changes

src/infra/outbound/deliver.ts

  • Add JSDoc to normalizeEmptyPayloadForDelivery documenting that it must be called on the sanitized payload so that <br> → "\n" conversions are caught before delivery.

src/infra/outbound/deliver.test.ts

  • Add Telegram-specific regression test: { text: "<br>" } payload on Telegram channel must be dropped (zero sendTelegram calls, empty results array). Complements the existing Signal test for the same scenario.

extensions/telegram/src/bot/delivery.send.ts

  • Extend EMPTY_TEXT_ERR_RE to match both "message text is empty" and "text must be non-empty"
  • Return undefined instead of throwing when both html and plain fallback text are empty (whitespace-only trailing chunk)
  • Return undefined instead of re-throwing when Telegram rejects with an empty-text error and there is no plain fallback
  • Change return type to Promise<number | undefined>

extensions/telegram/src/bot/reply-threading.ts

  • Add optional shouldSkipChunk predicate to sendChunkedTelegramReplyText; skipped chunks do not mark progress as delivered and do not affect the isFirstChunk calculation
  • Track sentChunkCount to determine isFirstChunk based on actually-sent chunks instead of array index

extensions/telegram/src/bot/delivery.replies.ts

  • Pass shouldSkipChunk: (chunk) => !chunk.html?.trim() && !chunk.text?.trim() to both deliverTextReply and sendPendingFollowUpText
  • Update sendTelegramVoiceFallbackText inline loop: skip empty chunks, gate button/reply attachment on first sent chunk
  • Guard firstDeliveredMessageId assignment to only set when messageId != null

extensions/telegram/src/bot/delivery.test.ts

  • Update existing "throws when both empty" test: now expects silent skip (no throw, delivered: false)
  • Add test for multi-chunk scenario where last chunk is empty (the production failure case)
  • Add test for Telegram 400 "text must be non-empty" error handling

Behaviour after fix

Scenario Before After
<br>-only payload on Telegram Forwarded as "\n" → Telegram 400 Dropped pre-delivery by post-sanitization empty check
Single empty-text reply Throws, "No response generated" Silent skip, delivered: false
Multi-chunk, last chunk empty Telegram 400 → "No response generated" Last chunk skipped, previous chunks delivered
Telegram rejects with "text must be non-empty" Error propagates Silently skipped
Telegram rejects with "message text is empty" Already handled (plain fallback or skip) Same + now also silently skips when no fallback
First chunk empty, buttons/reply threading Buttons attached to empty (failed) chunk Buttons attached to first sent chunk

Copilot AI review requested due to automatic review settings March 18, 2026 02:56
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: S labels Mar 18, 2026
@greptile-apps

greptile-apps Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a production bug where Telegram's 400: text must be non-empty error — triggered by empty trailing chunks when splitting large responses — caused the full reply to appear unsent even though earlier chunks had already been delivered successfully. The changes extend the empty-text error regex, pre-filter empty chunks via a new shouldSkipChunk predicate, fix isFirstChunk to track actually-sent chunks (not array indices), and guard firstDeliveredMessageId against undefined returns.

Key concerns:

  • Silent swallow of parse errors (delivery.send.ts lines 172–179): The new return undefined early exit lives inside the combined PARSE_ERR_RE || EMPTY_TEXT_ERR_RE branch. Before this PR, a "can't parse entities" error with no plain-text fallback would re-throw so callers could observe the failure; after, it silently returns undefined. This is an unintended side-effect — only EMPTY_TEXT_ERR_RE matches should get the silent-skip treatment.

  • Test doesn't cover the error-handling path it claims to (delivery.test.ts line 627): The "handles Telegram 400 text-must-be-non-empty" test passes { text: " " }, which is pre-filtered by shouldSkipChunk before sendTelegramText is ever called. The mockRejectedValueOnce is never triggered, so the catch-block fix in sendTelegramText is not exercised by this test.

  • Loose assertion in multi-chunk test (delivery.test.ts line 624): expect(sendMessage).toHaveBeenCalled() only confirms at least one call, but the test's purpose is to prove the empty second chunk was skipped. toHaveBeenCalledTimes(1) would make that guarantee explicit.

Confidence Score: 3/5

  • The happy-path fix is sound, but an unintended silent-swallow of parse errors and inadequate test coverage for the new error-handling branch should be addressed before merging.
  • The core bug fix (pre-filtering empty chunks and widening the regex) is correct and well-motivated. The reply-threading.ts and delivery.replies.ts changes are clean. The score is reduced because (1) the catch-block change in delivery.send.ts widens the silent-skip to cover parse-entity errors — a pre-existing category of real failures that should remain observable — and (2) the new test for the 400 error doesn't actually invoke the code path it's meant to cover, leaving the catch-block change untested.
  • extensions/telegram/src/bot/delivery.send.ts (catch-block silent-skip scope) and extensions/telegram/src/bot/delivery.test.ts (test validity for the 400 error scenario)
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/delivery.send.ts
Line: 172-179

Comment:
**Parse errors now silently swallowed when no plain fallback**

The `return undefined` path was added to handle `EMPTY_TEXT_ERR_RE` (Telegram rejecting empty text), but it also affects the `PARSE_ERR_RE` branch. Before this PR, if Telegram returned a "can't parse entities" error *and* there was no plain-text fallback, the error was re-thrown so callers could see the failure. After this change, that same scenario silently returns `undefined`, discarding the chunk without surfacing the parse error.

A concrete path where this can bite:
- A chunk where `chunk.html` is non-empty but contains malformed entities (triggering `PARSE_ERR_RE`), while `chunk.text` is an empty string (so `hasFallbackText === false`).
- The `shouldSkipChunk` predicate in `deliverTextReply` only skips when *both* are empty, so this chunk proceeds to `sendTelegramText`.
- Telegram rejects with a parse error → code now returns `undefined` instead of re-throwing.

The fix should scope the silent-skip to `EMPTY_TEXT_ERR_RE` only:

```ts
    if (PARSE_ERR_RE.test(errText) || EMPTY_TEXT_ERR_RE.test(errText)) {
      if (!hasFallbackText) {
        if (EMPTY_TEXT_ERR_RE.test(errText)) {
          // Telegram rejected the text as empty — silently skip this chunk.
          runtime.log?.(
            `telegram sendMessage skipped: Telegram rejected empty text (chat=${chatId}): ${errText}`,
          );
          return undefined;
        }
        throw err;
      }
      runtime.log?.(`telegram formatted send failed; retrying without formatting: ${errText}`);
      return await sendPlainFallback();
    }
```

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/delivery.test.ts
Line: 627-647

Comment:
**Test doesn't exercise the intended code path**

The test title says "handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk," implying it validates the `EMPTY_TEXT_ERR_RE` error-handling logic in `sendTelegramText`. However, the reply payload `{ text: "   " }` is whitespace-only, so `shouldSkipChunk` (added in this same PR) filters the chunk out in `sendChunkedTelegramReplyText` *before* `sendTelegramText` is ever called. The `mockRejectedValueOnce` on `sendMessage` is never triggered.

The test passes because of the pre-filter, not because of the new error-swallowing in the catch block. The actual regression scenario from the PR description (Telegram itself returning the 400 because our pre-check was insufficient) is untested.

To properly cover the catch-block path, the test needs a non-empty chunk whose HTML text causes Telegram to return the 400 — for example:

```ts
it("handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk", async () => {
  const runtime = createRuntime();
  const sendMessage = vi
    .fn()
    .mockRejectedValueOnce(
      new Error("Call to 'sendMessage' failed! (400: Bad Request: text must be non-empty)"),
    );
  const bot = createBot({ sendMessage });

  // ">" renders to empty HTML, which triggers the plain-fallback path in sendTelegramText.
  // Give it no plain fallback so the new EMPTY_TEXT_ERR_RE return-undefined branch fires.
  const result = await deliverReplies({
    replies: [{ text: ">" }],  // non-whitespace; not pre-filtered by shouldSkipChunk
    chatId: "123",
    token: "tok",
    runtime,
    bot,
    replyToMode: "off",
    textLimit: 4000,
  });
  // sendMessage should have been attempted (and the 400 silently swallowed)
  expect(sendMessage).toHaveBeenCalled();
  expect(result.delivered).toBe(false);
});
```

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/delivery.test.ts
Line: 610-625

Comment:
**Assertion too loose for the multi-chunk empty-last-chunk test**

The assertion only checks that `sendMessage` was called at least once, but the core claim of this test is that the empty trailing chunk is *skipped* while the non-empty chunk *is* sent. The production failure was precisely that the second (empty) chunk triggered a 400. A `toHaveBeenCalledTimes(1)` assertion would make the test actually prove both halves of that claim:

```suggestion
    // sendMessage should be called exactly once — only for the non-empty chunk.
    expect(sendMessage).toHaveBeenCalledTimes(1);
```

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

Last reviewed commit: "fix(telegram): silen..."

Comment on lines 172 to +179
const errText = formatErrorMessage(err);
if (PARSE_ERR_RE.test(errText) || EMPTY_TEXT_ERR_RE.test(errText)) {
if (!hasFallbackText) {
throw err;
// Telegram rejected the text as empty — silently skip this chunk.
runtime.log?.(
`telegram sendMessage skipped: Telegram rejected empty text (chat=${chatId}): ${errText}`,
);
return undefined;

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.

P1 Parse errors now silently swallowed when no plain fallback

The return undefined path was added to handle EMPTY_TEXT_ERR_RE (Telegram rejecting empty text), but it also affects the PARSE_ERR_RE branch. Before this PR, if Telegram returned a "can't parse entities" error and there was no plain-text fallback, the error was re-thrown so callers could see the failure. After this change, that same scenario silently returns undefined, discarding the chunk without surfacing the parse error.

A concrete path where this can bite:

  • A chunk where chunk.html is non-empty but contains malformed entities (triggering PARSE_ERR_RE), while chunk.text is an empty string (so hasFallbackText === false).
  • The shouldSkipChunk predicate in deliverTextReply only skips when both are empty, so this chunk proceeds to sendTelegramText.
  • Telegram rejects with a parse error → code now returns undefined instead of re-throwing.

The fix should scope the silent-skip to EMPTY_TEXT_ERR_RE only:

    if (PARSE_ERR_RE.test(errText) || EMPTY_TEXT_ERR_RE.test(errText)) {
      if (!hasFallbackText) {
        if (EMPTY_TEXT_ERR_RE.test(errText)) {
          // Telegram rejected the text as empty — silently skip this chunk.
          runtime.log?.(
            `telegram sendMessage skipped: Telegram rejected empty text (chat=${chatId}): ${errText}`,
          );
          return undefined;
        }
        throw err;
      }
      runtime.log?.(`telegram formatted send failed; retrying without formatting: ${errText}`);
      return await sendPlainFallback();
    }
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/delivery.send.ts
Line: 172-179

Comment:
**Parse errors now silently swallowed when no plain fallback**

The `return undefined` path was added to handle `EMPTY_TEXT_ERR_RE` (Telegram rejecting empty text), but it also affects the `PARSE_ERR_RE` branch. Before this PR, if Telegram returned a "can't parse entities" error *and* there was no plain-text fallback, the error was re-thrown so callers could see the failure. After this change, that same scenario silently returns `undefined`, discarding the chunk without surfacing the parse error.

A concrete path where this can bite:
- A chunk where `chunk.html` is non-empty but contains malformed entities (triggering `PARSE_ERR_RE`), while `chunk.text` is an empty string (so `hasFallbackText === false`).
- The `shouldSkipChunk` predicate in `deliverTextReply` only skips when *both* are empty, so this chunk proceeds to `sendTelegramText`.
- Telegram rejects with a parse error → code now returns `undefined` instead of re-throwing.

The fix should scope the silent-skip to `EMPTY_TEXT_ERR_RE` only:

```ts
    if (PARSE_ERR_RE.test(errText) || EMPTY_TEXT_ERR_RE.test(errText)) {
      if (!hasFallbackText) {
        if (EMPTY_TEXT_ERR_RE.test(errText)) {
          // Telegram rejected the text as empty — silently skip this chunk.
          runtime.log?.(
            `telegram sendMessage skipped: Telegram rejected empty text (chat=${chatId}): ${errText}`,
          );
          return undefined;
        }
        throw err;
      }
      runtime.log?.(`telegram formatted send failed; retrying without formatting: ${errText}`);
      return await sendPlainFallback();
    }
```

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

Comment on lines +627 to +647
it("handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk", async () => {
const runtime = createRuntime();
const sendMessage = vi
.fn()
.mockRejectedValueOnce(
new Error("Call to 'sendMessage' failed! (400: Bad Request: text must be non-empty)"),
);
const bot = createBot({ sendMessage });

// Should not throw — empty-text 400s are silently skipped.
const result = await deliverReplies({
replies: [{ text: " " }],
chatId: "123",
token: "tok",
runtime,
bot,
replyToMode: "off",
textLimit: 4000,
});
expect(result.delivered).toBe(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.

P1 Test doesn't exercise the intended code path

The test title says "handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk," implying it validates the EMPTY_TEXT_ERR_RE error-handling logic in sendTelegramText. However, the reply payload { text: " " } is whitespace-only, so shouldSkipChunk (added in this same PR) filters the chunk out in sendChunkedTelegramReplyText before sendTelegramText is ever called. The mockRejectedValueOnce on sendMessage is never triggered.

The test passes because of the pre-filter, not because of the new error-swallowing in the catch block. The actual regression scenario from the PR description (Telegram itself returning the 400 because our pre-check was insufficient) is untested.

To properly cover the catch-block path, the test needs a non-empty chunk whose HTML text causes Telegram to return the 400 — for example:

it("handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk", async () => {
  const runtime = createRuntime();
  const sendMessage = vi
    .fn()
    .mockRejectedValueOnce(
      new Error("Call to 'sendMessage' failed! (400: Bad Request: text must be non-empty)"),
    );
  const bot = createBot({ sendMessage });

  // ">" renders to empty HTML, which triggers the plain-fallback path in sendTelegramText.
  // Give it no plain fallback so the new EMPTY_TEXT_ERR_RE return-undefined branch fires.
  const result = await deliverReplies({
    replies: [{ text: ">" }],  // non-whitespace; not pre-filtered by shouldSkipChunk
    chatId: "123",
    token: "tok",
    runtime,
    bot,
    replyToMode: "off",
    textLimit: 4000,
  });
  // sendMessage should have been attempted (and the 400 silently swallowed)
  expect(sendMessage).toHaveBeenCalled();
  expect(result.delivered).toBe(false);
});
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/delivery.test.ts
Line: 627-647

Comment:
**Test doesn't exercise the intended code path**

The test title says "handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk," implying it validates the `EMPTY_TEXT_ERR_RE` error-handling logic in `sendTelegramText`. However, the reply payload `{ text: "   " }` is whitespace-only, so `shouldSkipChunk` (added in this same PR) filters the chunk out in `sendChunkedTelegramReplyText` *before* `sendTelegramText` is ever called. The `mockRejectedValueOnce` on `sendMessage` is never triggered.

The test passes because of the pre-filter, not because of the new error-swallowing in the catch block. The actual regression scenario from the PR description (Telegram itself returning the 400 because our pre-check was insufficient) is untested.

To properly cover the catch-block path, the test needs a non-empty chunk whose HTML text causes Telegram to return the 400 — for example:

```ts
it("handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk", async () => {
  const runtime = createRuntime();
  const sendMessage = vi
    .fn()
    .mockRejectedValueOnce(
      new Error("Call to 'sendMessage' failed! (400: Bad Request: text must be non-empty)"),
    );
  const bot = createBot({ sendMessage });

  // ">" renders to empty HTML, which triggers the plain-fallback path in sendTelegramText.
  // Give it no plain fallback so the new EMPTY_TEXT_ERR_RE return-undefined branch fires.
  const result = await deliverReplies({
    replies: [{ text: ">" }],  // non-whitespace; not pre-filtered by shouldSkipChunk
    chatId: "123",
    token: "tok",
    runtime,
    bot,
    replyToMode: "off",
    textLimit: 4000,
  });
  // sendMessage should have been attempted (and the 400 silently swallowed)
  expect(sendMessage).toHaveBeenCalled();
  expect(result.delivered).toBe(false);
});
```

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

Comment on lines +610 to +625
it("skips empty last chunk when long response splits into multiple chunks", async () => {
// Scenario: large response split into 2 chunks where the last chunk is empty/whitespace.
// Before the fix: Telegram 400 "text must be non-empty" → "No response generated."
// After the fix: empty chunk is skipped silently; first chunk delivers successfully.
const { runtime, sendMessage, bot } = createSendMessageHarness(99);
const longText = "A".repeat(3900) + "\n\n "; // ~3900 chars + trailing whitespace
await deliverWith({
replies: [{ text: longText }],
runtime,
bot,
replyToMode: "off",
textLimit: 3500,
});
// sendMessage should only be called for the non-empty chunks.
expect(sendMessage).toHaveBeenCalled();
});

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 Assertion too loose for the multi-chunk empty-last-chunk test

The assertion only checks that sendMessage was called at least once, but the core claim of this test is that the empty trailing chunk is skipped while the non-empty chunk is sent. The production failure was precisely that the second (empty) chunk triggered a 400. A toHaveBeenCalledTimes(1) assertion would make the test actually prove both halves of that claim:

Suggested change
it("skips empty last chunk when long response splits into multiple chunks", async () => {
// Scenario: large response split into 2 chunks where the last chunk is empty/whitespace.
// Before the fix: Telegram 400 "text must be non-empty" → "No response generated."
// After the fix: empty chunk is skipped silently; first chunk delivers successfully.
const { runtime, sendMessage, bot } = createSendMessageHarness(99);
const longText = "A".repeat(3900) + "\n\n "; // ~3900 chars + trailing whitespace
await deliverWith({
replies: [{ text: longText }],
runtime,
bot,
replyToMode: "off",
textLimit: 3500,
});
// sendMessage should only be called for the non-empty chunks.
expect(sendMessage).toHaveBeenCalled();
});
// sendMessage should be called exactly once — only for the non-empty chunk.
expect(sendMessage).toHaveBeenCalledTimes(1);
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/telegram/src/bot/delivery.test.ts
Line: 610-625

Comment:
**Assertion too loose for the multi-chunk empty-last-chunk test**

The assertion only checks that `sendMessage` was called at least once, but the core claim of this test is that the empty trailing chunk is *skipped* while the non-empty chunk *is* sent. The production failure was precisely that the second (empty) chunk triggered a 400. A `toHaveBeenCalledTimes(1)` assertion would make the test actually prove both halves of that claim:

```suggestion
    // sendMessage should be called exactly once — only for the non-empty chunk.
    expect(sendMessage).toHaveBeenCalledTimes(1);
```

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 pipeline to avoid Telegram 400 errors caused by empty/whitespace chunks (including markdown-rendered empty HTML), by allowing chunks to be skipped without treating them as delivered and by relaxing sendTelegramText to “skip” instead of throwing in empty-text scenarios.

Changes:

  • Add shouldSkipChunk and “first sent chunk” tracking to sendChunkedTelegramReplyText to support skipping chunks without affecting first-chunk behavior.
  • Update sendTelegramText to return undefined (and log) when both formatted and fallback text are empty or when Telegram rejects empty text without a fallback.
  • Adjust delivery logic and tests to treat empty replies as a no-op (not an error), including updated expectations around delivery status.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.

File Description
extensions/telegram/src/bot/reply-threading.ts Adds chunk-skipping support and changes first-chunk detection to be based on first chunk actually sent.
extensions/telegram/src/bot/delivery.send.ts Expands empty-text error detection and changes sendTelegramText to return number | undefined to support silent skips.
extensions/telegram/src/bot/delivery.replies.ts Wires shouldSkipChunk into threaded sending and updates “first delivered message id” tracking to handle undefined.
extensions/telegram/src/bot/delivery.test.ts Updates tests to reflect silent-skipping behavior and adds new coverage for empty-chunk scenarios.

Comment on lines +86 to +88
markReplyApplied(params.progress, replyToMessageId);
applyDelivered(params.progress);
sentChunkCount += 1;
if (replyToForChunk) {
appliedReplyTo = true;
}
sentAnyChunk = true;
Comment on lines +615 to +622
const longText = "A".repeat(3900) + "\n\n "; // ~3900 chars + trailing whitespace
await deliverWith({
replies: [{ text: longText }],
runtime,
bot,
replyToMode: "off",
textLimit: 3500,
});
Comment on lines +627 to +645
it("handles Telegram 400 text-must-be-non-empty error by silently skipping the chunk", async () => {
const runtime = createRuntime();
const sendMessage = vi
.fn()
.mockRejectedValueOnce(
new Error("Call to 'sendMessage' failed! (400: Bad Request: text must be non-empty)"),
);
const bot = createBot({ sendMessage });

// Should not throw — empty-text 400s are silently skipped.
const result = await deliverReplies({
replies: [{ text: " " }],
chatId: "123",
token: "tok",
runtime,
bot,
replyToMode: "off",
textLimit: 4000,
});
@amittell
amittell force-pushed the fix/empty-text-silent-skip-v2 branch 4 times, most recently from cda8232 to 70f219b Compare March 20, 2026 01:18
@amittell

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Addressed the parse error logging and masked chat ID in log output per the feedback. The shouldSkipChunk predicate and isFirstChunk tracking were intentional design choices to correctly handle the first-chunk-empty scenario — happy to clarify further if needed.

@amittell
amittell force-pushed the fix/empty-text-silent-skip-v2 branch from 70f219b to ee2ed25 Compare March 20, 2026 02:17
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL and removed size: S labels Mar 20, 2026
@amittell
amittell force-pushed the fix/empty-text-silent-skip-v2 branch 2 times, most recently from e792239 to ed296a5 Compare March 20, 2026 02:27
@amittell

Copy link
Copy Markdown
Contributor Author

Re: the silent undefined return — intentional by design. Previous behaviour threw 400 which surfaced as No response generated to users. The fix returns undefined (skip) while correctly NOT marking the chunk as delivered. Empty-chunk scenarios are logged at debug level for observability.

@amittell

Copy link
Copy Markdown
Contributor Author

Re: prompt injection via System: lines — the pending-inbound replay preview is already sanitized: truncated to 100 chars, newlines stripped, backticks escaped before embedding in the system event text. The sanitized preview is clearly labeled as external/untrusted in the event text.

@amittell
amittell force-pushed the fix/empty-text-silent-skip-v2 branch 2 times, most recently from 0f367a3 to ad28889 Compare March 20, 2026 03:29
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui cli CLI command changes and removed channel: telegram Channel integration: telegram agents Agent runtime and tooling labels Mar 20, 2026
@openclaw-barnacle openclaw-barnacle Bot added the channel: telegram Channel integration: telegram label Mar 21, 2026
@amittell
amittell force-pushed the fix/empty-text-silent-skip-v2 branch from f1b93da to 43a4198 Compare March 21, 2026 23:17
@openclaw-barnacle openclaw-barnacle Bot added size: S and removed gateway Gateway runtime agents Agent runtime and tooling size: XL labels Mar 21, 2026
@amittell
amittell force-pushed the fix/empty-text-silent-skip-v2 branch 10 times, most recently from f8e141b to 15fa925 Compare March 23, 2026 05:18
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M and removed size: S labels Mar 25, 2026
@amittell
amittell force-pushed the fix/empty-text-silent-skip-v2 branch from 04e62d4 to 23c39d9 Compare March 25, 2026 23:18
@openclaw-barnacle openclaw-barnacle Bot removed the docs Improvements or additions to documentation label Mar 25, 2026
…y failures

Root cause: When a long response is chunked for Telegram delivery, if a chunk
(commonly the last chunk) is empty or whitespace-only, Telegram rejects it with
'400: Bad Request: text must be non-empty'. OpenClaw then surfaces
'No response generated. Please try again.' to the user.

Changes:

extensions/telegram/src/bot/delivery.send.ts
- Extend EMPTY_TEXT_ERR_RE to also match Telegram's 'text must be non-empty'
  error variant (was only matching 'message text is empty')
- Return undefined instead of throwing when both html and plain fallback text
  are empty (whitespace-only trailing chunk scenario)
- Return undefined instead of re-throwing when Telegram rejects with
  EMPTY_TEXT_ERR_RE and there is no plain fallback (consistent behaviour)
- Change return type to Promise<number | undefined> accordingly

extensions/telegram/src/bot/reply-threading.ts
- Add optional shouldSkipChunk predicate to sendChunkedTelegramReplyText;
  skipped chunks do not mark progress as delivered and do not count toward
  the isFirstChunk calculation
- Track sentChunkCount to determine isFirstChunk based on actually-sent chunks
  instead of array index (fixes button/reply attachment when chunk 0 is empty)

extensions/telegram/src/bot/delivery.replies.ts
- Add shouldSkipChunk: (chunk) => !html?.trim() && !text?.trim() to both
  deliverTextReply and sendPendingFollowUpText call sites
- Update sendTelegramVoiceFallbackText inline loop: skip empty chunks,
  use sentAnyChunk flag (was appliedReplyTo) to gate button/reply attachment
  on the first sent chunk, not the first chunk index
- Guard firstDeliveredMessageId assignment: only set when messageId != null

extensions/telegram/src/bot/delivery.test.ts
- Update 'throws when both empty' test: now expects silent skip, not throw
- Add test for multi-chunk scenario where last chunk is empty
- Add test for Telegram 400 'text must be non-empty' error handling

Fixes the production failure observed 2026-03-17 where a large markdown
response (scheduler architecture writeup) split into 2 chunks with the
second chunk empty, triggering the 400 error and 'No response generated.'
fallback message.
…ly skips

sendTelegramText returns undefined when a chunk is silently skipped
(empty text after HTML→plain fallback). Previously, sendChunkedTelegramReplyText
would still call markDelivered and count the chunk. Fix:

- sendChunk can now return false to signal a silent skip
- sendChunkedTelegramReplyText only calls markDelivered/counts the
  chunk when sendChunk does not return false
- deliverTextReply and sendPendingFollowUpText sendChunk callbacks
  return false when sendTelegramText returns undefined
- sendTelegramVoiceFallbackText inline loop only sets sentAnyChunk
  when messageId is non-null (Aisle issue 1)
…tighten empty-text test assertion

- Mask chatId as [chatId] in all sendTelegramText log lines (Aisle Low: PII in logs)
- Restrict silent-skip to EMPTY_TEXT_ERR_RE only; PARSE_ERR_RE now re-throws when no
  plain fallback is available, restoring observable failure for callers (Greptile concern)
- Fix multi-chunk skip test to use toHaveBeenCalledTimes(1) for an explicit guarantee
  that the trailing empty chunk was skipped (Greptile: loose assertion)
… accurate split

With "A".repeat(3900) + "\n\n   " and limit 3500, the chunker produces:
  chunk1: 3500 As (sent)
  chunk2: 400 As + "\n\n   " (also non-empty → also sent)

...so sendMessage was called twice, defeating the toHaveBeenCalledTimes(1) assertion.

With "A".repeat(3500) + "\n\n   " and limit 3500, the chunker produces:
  chunk1: 3500 As (sent)
  chunk2: "   " (whitespace only → skipped by empty-text guard)

...correctly validating that trailing whitespace-only chunks are silently skipped.
…d for <br> → \n case

normalizeEmptyPayloadForDelivery is already called on the sanitized
payload in normalizePayloadsForChannelDelivery, so <br> → \n conversion
by sanitizeForPlainText is correctly caught: "\n".trim() === ""
causes the payload to be dropped before delivery.

Add explicit JSDoc to normalizeEmptyPayloadForDelivery clarifying it must
run post-sanitization, and add a Telegram-specific regression test to
lock in the behaviour (complementing the existing Signal test).

Fixes the gap where a lone <br> payload could otherwise produce a
whitespace-only Telegram message (400 error from the Bot API).

Closes openclaw#49391
@amittell

Copy link
Copy Markdown
Contributor Author

Superseded by #56620 (fix(telegram): skip empty text replies instead of crashing with GrammyError 400), merged 2026-03-28. Upstream filters whitespace-only chunks at the bot delivery fan-in, which covers the primary symptom. Closing to reduce active queue.

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

Labels

channel: telegram Channel integration: telegram size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants