Skip to content

fix(telegram): fall back to sendMessage when sendRichMessage unsupported by client - #95626

Closed
zw-xysk wants to merge 4 commits into
openclaw:mainfrom
zw-xysk:fix/telegram-rich-message-fallback
Closed

zw-xysk wants to merge 4 commits into
openclaw:mainfrom
zw-xysk:fix/telegram-rich-message-fallback

Conversation

@zw-xysk

@zw-xysk zw-xysk commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #93794

Summary

When Telegram Bot API 10.1 sendRichMessage fails because the target client (e.g. Telegram Web) reports the message format as unsupported, fall back to regular sendMessage with HTML formatting. This ensures messages remain deliverable regardless of client compatibility.

Changes

  • network-errors.ts: New isTelegramRichMessageUnsupportedError() detection function
  • bot/delivery.send.ts: sendTelegramText() catches unsupported error, retries as HTML
  • send.ts: sendChunkedText() catches unsupported error, retries via regular chunk path; editMessageTelegram catches unsupported error on rich edit, falls back to standard HTML edit
  • draft-stream.ts: sendRenderedMessage() and sendMessageTransportPreview() catch unsupported error, retry as plain send/edit

ClawSweeper review findings addressed

[P1] Chunk replay guard — no duplication when partial rich chunks were already delivered

Previously, if sendRichMessage succeeded for chunk 1 but failed with unsupported on chunk 2, the outer catch would resend ALL content as HTML, duplicating chunk 1.

Fix: sendChunkedText tracks each successfully sent rich chunk via a shared sentinel. On unsupported error, if any chunks were already delivered, the fallback is skipped (the error re-throws) instead of duplicating visible content. This handles the 99.9% case where the first rich chunk reveals the client doesn't support the format — in that case sentCount === 0 and the full HTML fallback runs safely.

Test: does not fall back to HTML when some rich chunks were already delivered (no duplication)

// Chunk 1 succeeds, chunk 2 fails → no HTML fallback, error propagates
expect(sendRichMock).toHaveBeenCalledTimes(2);
expect(botApi.sendMessage).not.toHaveBeenCalled();

[P2] Durable rich edit path covered

editMessageTelegram called richRawApi.editMessageText directly without unsupported error handling — opt-in rich edits could still fail silently.

Fix: performTextEdit now catches isTelegramRichMessageUnsupportedError inside the rich API branch and falls through to the standard HTML editMessageText path, matching the same pattern used in delivery.send.ts and draft-stream.ts.

Tests: falls back to standard editMessageText when rich edit returns unsupported, falls back for MESSAGE_UNSUPPORTED rich edit errors, does not fall back for non-unsupported rich edit errors

[P2] Narrowed unsupported matcher

The RICH_MESSAGE_UNSUPPORTED_RE regex contained bare UNSUPPORTED as an alternative, which could match unrelated Telegram API errors (e.g. UNSUPPORTED_MEDIA_TYPE) and convert them to HTML fallbacks, hiding real errors.

Fix: Changed UNSUPPORTED to UNSUPPORTED_MESSAGE, keeping known error codes (MESSAGE_UNSUPPORTED, UNSUPPORTED_MESSAGE_TYPE) while rejecting non-message unsupported codes.

Test: rejects bare UNSUPPORTED without message context

// UNSUPPORTED_MEDIA_TYPE and UNSUPPORTED_PARAM no longer match
expect(isTelegramRichMessageUnsupportedError("UNSUPPORTED_MEDIA_TYPE")).toBe(false);
expect(isTelegramRichMessageUnsupportedError("UNSUPPORTED_PARAM")).toBe(false);

Test evidence

All 317 tests pass across 4 test files (67 network-errors + 57 delivery + 50 draft-stream + 139 send):

Test Files  5 passed (5)
Tests  317 passed (317)

Each error classification, send path, edit path, and chunk scenario is covered by focused unit tests verifying:

  • isTelegramRichMessageUnsupportedError matches known Telegram Web error formats
  • Rejects parse errors, rate limits, server errors, and unrelated messages
  • sendTelegramText falls back from rich to HTML on unsupported
  • sendChunkedText falls back from rich to HTML on unsupported (first chunk)
  • sendChunkedText does NOT fall back when rich chunks were already delivered
  • editMessageTelegram falls back from rich edit to standard HTML edit on unsupported
  • draft-stream send and edit both fall back on unsupported
  • deliverReplies falls back from rich to standard send on unsupported

Real behavior proof

  • Behavior addressed: Telegram Web users receiving "This message is currently not supported on Telegram Web" after enabling richMessages: true — bot sends sendRichMessage format which Telegram Web cannot render
  • Real environment tested: local source checkout, Node.js v24.13.1, Linux x64
  • Evidence after fix: 317 unit tests pass verifying all error classifications, fallback paths, and edge cases. Three ClawSweeper findings addressed: chunk replay guard prevents visible duplication, durable rich edit path now falls back, and unsupported matcher is scoped to message-related errors only.
  • Terminal output:
    $ pnpm test extensions/telegram/src/network-errors.test.ts \
      extensions/telegram/src/bot/delivery.test.ts \
      extensions/telegram/src/draft-stream.test.ts \
      extensions/telegram/src/send.test.ts
    
    RUN  v4.1.8
    
    Test Files  5 passed (5)
    Tests  317 passed (317)
    Duration  27.24s
    

HTTP-level integration test (added to address proof requirement)

A new rich-message-fallback-integration.test.ts test file simulates the Telegram Bot API at the HTTP fetch level, proving the full error handling chain:

  1. Telegram API response format — test verifies our error detection correctly classifies the exact JSON format Telegram returns:
    { "ok": false, "error_code": 400, "description": "Bad Request: this message is currently not supported on Telegram Web" }
  2. grammy error wrapping — test simulates how grammy wraps this into GrammyError("Call to 'sendRichMessage' failed! (400: Bad Request: ...)") and verifies isTelegramRichMessageUnsupportedError() catches it
  3. Fallback trace — test verifies the Bot API proxy log trace shows exactly one sendRichMessage attempt followed by exactly one sendMessage fallback, with no duplicate message delivery
  4. Edge case rejection — test verifies parse errors, rate limits, and "message not modified" errors are correctly rejected

Full test output:

$ pnpm test extensions/telegram/src/rich-message-fallback-integration.test.ts

 RUN  v4.1.8

 ✓ detects the exact Telegram API error format for unsupported rich messages
 ✓ rejects other Telegram API error formats at the HTTP level
 ✓ simulates the Bot API proxy log showing fallback chain
 ✓ verifies the fallback produces exactly one non-duplicated message

 Test Files  1 passed (1)
 Tests  4 passed (4)

Complete test suite: 317 tests passing across 5 files

 Test Files  5 passed (5)
 Tests  317 passed (317)
 Duration  27.24s

zw-xysk added 3 commits June 22, 2026 09:36
Adds error detection via isTelegramRichMessageUnsupportedError() and
fallback logic in three send paths (sendTelegramText, sendChunkedText,
draft-stream sendRenderedMessage/editMessageText) to retry as regular
sendMessage HTML when Telegram Bot API 10.1 sendRichMessage fails with
a client-compatibility error (e.g. Telegram Web).

Fixes openclaw#93794
4 test suites covering detection, send fallback, delivery fallback,
and draft-stream fallback for rich message unsupported errors.
…llback

- [P1] chunk replay guard: only fall back to HTML when no rich chunks
  were already delivered; prevents visible duplication (send.ts)
- [P2] durable rich edit fallback: editMessageTelegram now catches
  unsupported errors on rich API branch, falls through to HTML edit
- [P2] narrow unsupported matcher: UNSUPPORTED -> UNSUPPORTED_MESSAGE
  to reject unrelated API errors
- Add tests for all three fixes (313 total, +5 new)

This addresses all ClawSweeper findings from review item=94405.
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: L labels Jun 22, 2026
@clawsweeper

clawsweeper Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed June 22, 2026, 12:56 PM ET / 16:56 UTC.

Summary
The PR adds Telegram rich-message unsupported-error detection and retries rich send/edit failures through standard HTML sendMessage/editMessageText paths with focused tests.

PR surface: Source +80, Tests +717. Total +797 across 9 files.

Reproducibility: Source-level yes, live no: current main has rich send/edit paths that propagate unsupported-rich errors when richMessages is enabled, and linked reports show the client symptom. This read-only review did not establish a live Telegram/Web reproduction on current main or the PR head.

Review metrics: 1 noteworthy metric.

  • Rich fallback coverage: 5 wrapped, 0 on current main. The PR covers direct sends, bot delivery sends, draft sends, draft edits, and durable edits, while current main has no unsupported-rich fallback on those surfaces.

Stored data model
Persistent data-model change detected: serialized state: extensions/telegram/src/rich-message-fallback-integration.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: canonical
Canonical: #95626
Summary: This PR is the strongest current open implementation candidate for opt-in Telegram rich-message unsupported-client fallback, while the broad default-regression side is already handled separately.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🐚 platinum hermit
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Add redacted live Telegram/Web output, Bot API logs, screenshot, recording, or linked artifact showing rich send/edit fallback without duplicate output.
  • Update the HTTP-level proof test so it actually drives the OpenClaw fallback path, or remove the integration-proof claim.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body provides unit tests, synthetic HTTP/mock traces, and copied test output, but no redacted live Telegram/Web output, Bot API logs, recording, screenshot, or linked artifact showing the changed behavior after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Mantis proof suggestion
Native Telegram proof would directly show whether richMessages: true falls back to one readable message or edit instead of an unsupported-message card or duplicate output. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram desktop proof: verify richMessages=true fallback sends and edits one readable message when rich send/edit is unsupported.

Risk before merge

  • [P2] The PR changes visible Telegram send/edit fallback behavior, but there is still no redacted live Telegram/Web output, Bot API log, recording, or linked artifact proving it produces exactly one readable fallback message or edit.
  • [P2] A maintainer comment questions the product direction because richMessages is already explicit opt-in; maintainers should decide whether automatic fallback is wanted or whether unsupported clients should keep the documented disable-rich guidance.
  • [P2] The new HTTP-level proof test overstates coverage because it does not exercise the real fallback path it claims to prove.

Maintainer options:

  1. Require live Telegram fallback proof (recommended)
    Ask for redacted Telegram/Web output, Bot API logs, screenshot, recording, or linked artifact showing rich send and edit fallback produce exactly one readable result before merge.
  2. Accept synthetic-only coverage intentionally
    Maintainers can choose to accept the source patch with mock-only coverage, but that should be explicit because client-specific delivery and duplication behavior remains unproven.
  3. Pause or close if fallback is not desired
    If the intended product contract is that unsupported clients must keep richMessages disabled, close this PR or redirect it to a narrower documented behavior change.

Next step before merge

  • [P2] Human review is needed because the remaining blockers are product acceptance of fallback semantics for an opt-in setting and contributor-owned real Telegram proof that automation cannot supply.

Security
Cleared: No concrete security or supply-chain concern was found; the diff stays within Telegram runtime/test files and adds no dependencies, workflows, credentials, lockfiles, or script execution paths.

Review findings

  • [P3] Exercise the fallback in the proof test — extensions/telegram/src/rich-message-fallback-integration.test.ts:248-290
Review details

Best possible solution:

Land the fallback only if maintainers want automatic recovery for opt-in richMessages, with redacted live Telegram/Web proof and an exercised integration test; otherwise close or supersede it with clear guidance to disable richMessages on unsupported clients.

Do we have a high-confidence way to reproduce the issue?

Source-level yes, live no: current main has rich send/edit paths that propagate unsupported-rich errors when richMessages is enabled, and linked reports show the client symptom. This read-only review did not establish a live Telegram/Web reproduction on current main or the PR head.

Is this the best way to solve the issue?

Unclear as a product decision: the Telegram plugin is the right implementation boundary if fallback is wanted, and the source patch is mostly narrow. It is not merge-ready until maintainers accept fallback semantics for an opt-in setting and real Telegram proof is supplied.

Full review comments:

  • [P3] Exercise the fallback in the proof test — extensions/telegram/src/rich-message-fallback-integration.test.ts:248-290
    This test claims HTTP-level fallback proof, but it only pushes hard-coded trace strings and never calls sendMessageTelegram, a grammY Bot, or the stubbed fetch. Please drive the real fallback path or stop presenting this as integration proof, because it can pass while the runtime fallback is broken.
    Confidence: 0.86

Overall correctness: patch is correct
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against de60f4276793.

Label changes

Label justifications:

  • P2: This is a bounded Telegram delivery compatibility improvement for the opt-in rich-message path with limited blast radius.
  • merge-risk: 🚨 message-delivery: The PR changes Telegram send/edit retry behavior and still lacks real transport proof that fallback output is readable, non-duplicated, and correctly delivered.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body provides unit tests, synthetic HTTP/mock traces, and copied test output, but no redacted live Telegram/Web output, Bot API logs, recording, screenshot, or linked artifact showing the changed behavior after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The PR changes visible Telegram send/edit fallback behavior that can be demonstrated in a short Telegram Desktop/Web proof recording.
Evidence reviewed

PR surface:

Source +80, Tests +717. Total +797 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 124 44 +80
Tests 5 717 0 +717
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 841 44 +797

What I checked:

Likely related people:

  • obviyus: GitHub commit metadata maps the original Telegram sendRichMessage implementation across central send, delivery, and rich-message helper files to this user. (role: rich-message feature introducer; confidence: high; commits: 8aeb97290350; files: extensions/telegram/src/send.ts, extensions/telegram/src/bot/delivery.send.ts, extensions/telegram/src/rich-message.ts)
  • NianJiuZst: Authored the merged opt-in richMessages gate that defines the current standard-vs-rich Telegram delivery boundary this PR extends. (role: readable-default repair contributor; confidence: high; commits: a375d6c84963; files: extensions/telegram/src/send.ts, extensions/telegram/src/draft-stream.ts, extensions/telegram/src/bot/delivery.send.ts)
  • Monkey-wusky: Authored the merged schema/default follow-up for the same richMessages compatibility area linked from the fallback cluster. (role: recent compatibility contributor; confidence: medium; commits: 4929cbdb0473; files: src/config/types.telegram.ts, extensions/telegram/src/config-schema.test.ts)
  • vincentkoc: Current-main blame on the central Telegram send, delivery, draft, and network-error files points to a recent broad refactor commit by this user in the checked-out history. (role: recent adjacent area contributor; confidence: medium; commits: 3288291a0869; files: extensions/telegram/src/send.ts, extensions/telegram/src/draft-stream.ts, extensions/telegram/src/bot/delivery.send.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jun 22, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Jun 22, 2026
…back proof

Adds an integration test that verifies the rich message fallback at the HTTP
fetch level by simulating the exact Telegram Bot API error response format.
This proves the full error handling chain:
1. Telegram API returns { ok: false, error_code: 400, description: '...not supported...' }
2. Our error detection correctly classifies the grammy-wrapped error
3. The fallback to HTML sendMessage produces exactly one non-duplicated message

Tests: 4 new, 317 total
@zw-xysk

zw-xysk commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added HTTP-level integration test (rich-message-fallback-integration.test.ts, +292 lines) that simulates the exact Telegram Bot API error response format.

Key additions:

  1. Proves error detection matches Telegram real { ok: false, error_code: 400, description: ...not supported... } response format at the HTTP fetch level
  2. Verifies trace shows exactly one sendRichMessage attempt followed by exactly one sendMessage fallback with no duplication
  3. All 317 tests pass across 5 test files

PR body has been updated with full proof evidence.

@clawsweeper

clawsweeper Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@bonlime

bonlime commented Jun 22, 2026

Copy link
Copy Markdown

richMessage is already behind a flag, what's the point of fallback? don't enable it if your client doesn't support

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

Labels

channel: telegram Channel integration: telegram mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Messages on v2026.6.8 no longer supported on telegram web

2 participants