Skip to content

Commit 4238468

Browse files
committed
fix(telegram): address ClawSweeper review findings on rich message fallback
- [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.
1 parent daf2076 commit 4238468

4 files changed

Lines changed: 133 additions & 14 deletions

File tree

‎extensions/telegram/src/network-errors.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,4 +387,13 @@ describe("isTelegramRichMessageUnsupportedError", () => {
387387
expect(isTelegramRichMessageUnsupportedError(unsupported)).toBe(true);
388388
expect(isTelegramRichMessageUnsupportedError(parseErr)).toBe(false);
389389
});
390+
391+
it("rejects bare UNSUPPORTED without message context (#pr-94405)", () => {
392+
expect(
393+
isTelegramRichMessageUnsupportedError(new Error("400: Bad Request: UNSUPPORTED_MEDIA_TYPE")),
394+
).toBe(false);
395+
expect(
396+
isTelegramRichMessageUnsupportedError(new Error("400: Bad Request: UNSUPPORTED_PARAM")),
397+
).toBe(false);
398+
});
390399
});

‎extensions/telegram/src/network-errors.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ export function isTelegramRateLimitError(err: unknown): boolean {
273273
const MESSAGE_NOT_MODIFIED_RE =
274274
/400:\s*Bad Request:\s*message is not modified|MESSAGE_NOT_MODIFIED/i;
275275
const RICH_MESSAGE_UNSUPPORTED_RE =
276-
/400:\s*Bad Request:\s*(?:this )?message\b.*\bnot supported|MESSAGE_UNSUPPORTED|UNSUPPORTED/i;
276+
/400:\s*Bad Request:\s*(?:this )?message\b.*\bnot supported|MESSAGE_UNSUPPORTED|UNSUPPORTED_MESSAGE/i;
277277
const MESSAGE_HAS_NO_TEXT_RE = /400:\s*Bad Request:\s*there is no text in the message to edit/i;
278278
const EDIT_TARGET_MISSING_RE =
279279
/400:\s*Bad Request:\s*message to edit not found|400:\s*Bad Request:\s*message can't be edited|MESSAGE_ID_INVALID/i;

‎extensions/telegram/src/send.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,34 @@ describe("sendMessageTelegram", () => {
10271027
// sendRichMessage fails (unsupported) → HTML sendMessage fails (parse error) → plain text succeeds
10281028
expect(botApi.sendMessage).toHaveBeenCalledTimes(2);
10291029
});
1030+
1031+
it("does not fall back to HTML when some rich chunks were already delivered (no duplication)", async () => {
1032+
const longText = "Hello world, this is a test message that would be chunked. ".repeat(1000);
1033+
botApi.sendMessage.mockResolvedValue({ message_id: 45, chat: { id: "123" } });
1034+
1035+
// Simulate first rich chunk succeeding, second failing with unsupported
1036+
const sendRichMock = botRawApi.sendRichMessage as ReturnType<typeof vi.fn>;
1037+
sendRichMock
1038+
.mockResolvedValueOnce({ message_id: 1, chat: { id: "123" } })
1039+
.mockRejectedValueOnce(
1040+
Object.assign(
1041+
new Error("400: Bad Request: this message is currently not supported on Telegram Web"),
1042+
{ error_code: 400 },
1043+
),
1044+
);
1045+
1046+
await expect(
1047+
sendMessageTelegram("123", longText, {
1048+
cfg: { channels: { telegram: { richMessages: true } } },
1049+
token: "tok",
1050+
}),
1051+
).rejects.toThrow(/not supported/);
1052+
1053+
// One rich chunk was sent; the second triggered unsupported error.
1054+
// Fallback should NOT have been used (would duplicate chunk 1 as HTML).
1055+
expect(sendRichMock).toHaveBeenCalledTimes(2);
1056+
expect(botApi.sendMessage).not.toHaveBeenCalled();
1057+
});
10301058
});
10311059

10321060
it.each([
@@ -3570,6 +3598,62 @@ describe("editMessageTelegram", () => {
35703598
);
35713599
expect(botRawApi.editMessageText).not.toHaveBeenCalled();
35723600
});
3601+
3602+
describe("rich edit unsupported fallback", () => {
3603+
function createRichEditUnsupportedError(
3604+
message = "400: Bad Request: this message is currently not supported on Telegram Web",
3605+
) {
3606+
return Object.assign(new Error(message), { error_code: 400 });
3607+
}
3608+
3609+
it("falls back to standard editMessageText when rich edit returns unsupported", async () => {
3610+
botApi.editMessageText.mockResolvedValue({ message_id: 1, chat: { id: "123" } });
3611+
botRawApi.editMessageText.mockRejectedValue(createRichEditUnsupportedError());
3612+
3613+
await editMessageTelegram("123", 1, "**edited**", {
3614+
token: "tok",
3615+
cfg: { channels: { telegram: { richMessages: true } } },
3616+
});
3617+
3618+
// Rich edit attempted, failed with unsupported, fell back to standard HTML edit
3619+
expect(botRawApi.editMessageText).toHaveBeenCalledTimes(1);
3620+
expect(botApi.editMessageText).toHaveBeenCalledWith("123", 1, "<b>edited</b>", {
3621+
parse_mode: "HTML",
3622+
});
3623+
});
3624+
3625+
it("does not fall back for non-unsupported rich edit errors", async () => {
3626+
botRawApi.editMessageText.mockRejectedValue(
3627+
Object.assign(new Error("400: Bad Request: can't parse entities"), { error_code: 400 }),
3628+
);
3629+
3630+
await expect(
3631+
editMessageTelegram("123", 1, "**edited**", {
3632+
token: "tok",
3633+
cfg: { channels: { telegram: { richMessages: true } } },
3634+
}),
3635+
).rejects.toThrow(/can't parse entities/);
3636+
3637+
// Rich edit was attempted, should not have fallen back to standard edit
3638+
expect(botRawApi.editMessageText).toHaveBeenCalledTimes(1);
3639+
expect(botApi.editMessageText).not.toHaveBeenCalled();
3640+
});
3641+
3642+
it("falls back for MESSAGE_UNSUPPORTED rich edit errors", async () => {
3643+
botApi.editMessageText.mockResolvedValue({ message_id: 1, chat: { id: "123" } });
3644+
botRawApi.editMessageText.mockRejectedValue(
3645+
Object.assign(new Error("400: Bad Request: MESSAGE_UNSUPPORTED"), { error_code: 400 }),
3646+
);
3647+
3648+
await editMessageTelegram("123", 1, "Hello **bold**", {
3649+
token: "tok",
3650+
cfg: { channels: { telegram: { richMessages: true } } },
3651+
});
3652+
3653+
expect(botRawApi.editMessageText).toHaveBeenCalledTimes(1);
3654+
expect(botApi.editMessageText).toHaveBeenCalled();
3655+
});
3656+
});
35733657
});
35743658

35753659
describe("sendPollTelegram", () => {

‎extensions/telegram/src/send.ts‎

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -846,12 +846,24 @@ export async function sendMessageTelegram(
846846
if (!useRichMessages) {
847847
return await sendTelegramTextChunks(buildChunkedTextPlan(rawText, context), context);
848848
}
849+
const richPlan = buildRichTextPlan(rawText);
850+
const sentCount = { value: 0 };
849851
try {
850-
return await sendTelegramRichTextChunks(buildRichTextPlan(rawText), context);
852+
return await sendTelegramRichTextChunks(richPlan, context, sentCount);
851853
} catch (err) {
852854
if (!isTelegramRichMessageUnsupportedError(err)) {
853855
throw err;
854856
}
857+
// If some rich chunks were already delivered, falling back to HTML would
858+
// duplicate visible content. Only fall back when no chunks were sent yet
859+
// (client doesn't support rich messages at all), which is the 99.9% case.
860+
if (sentCount.value > 0) {
861+
logVerbose(
862+
`telegram rich message not supported after ${sentCount.value} chunk(s) delivered; ` +
863+
`cannot fall back without duplication: ${formatErrorMessage(err)}`,
864+
);
865+
throw err;
866+
}
855867
logVerbose(
856868
`telegram rich message not supported; falling back to HTML: ${formatErrorMessage(err)}`,
857869
);
@@ -879,6 +891,7 @@ export async function sendMessageTelegram(
879891
const sendTelegramRichTextChunks = async (
880892
chunks: TelegramRichTextChunk[],
881893
context: string,
894+
sentCount?: { value: number },
882895
): Promise<{ messageId: string; chatId: string }> => {
883896
const richRawApi = getTelegramRichRawApi(api);
884897
let lastMessageId = "";
@@ -921,6 +934,9 @@ export async function sendMessageTelegram(
921934
lastChatId = String(result?.chat?.id ?? chatId);
922935
lastAcceptedParams = acceptedParams;
923936
sentChunkCount += 1;
937+
if (sentCount) {
938+
sentCount.value = sentChunkCount;
939+
}
924940
}
925941
if (lastMessageId) {
926942
logTelegramOutboundSendOk({
@@ -1629,21 +1645,31 @@ export async function editMessageTelegram(
16291645
plainCaptionParams.reply_markup = replyMarkup;
16301646
}
16311647

1632-
const performTextEdit = () => {
1648+
const performTextEdit = async () => {
16331649
if (richRawApi && richMessage) {
16341650
const richEditParams: Pick<TelegramEditRichMessageTextParams, "reply_markup"> =
16351651
replyMarkup === undefined ? {} : { reply_markup: replyMarkup };
1636-
return requestWithEditShouldLog(
1637-
() =>
1638-
richRawApi.editMessageText({
1639-
chat_id: chatId,
1640-
message_id: messageId,
1641-
rich_message: richMessage,
1642-
...richEditParams,
1643-
}),
1644-
"editMessage",
1645-
(err) => !isTelegramMessageNotModifiedError(err),
1646-
);
1652+
try {
1653+
return await requestWithEditShouldLog(
1654+
() =>
1655+
richRawApi.editMessageText({
1656+
chat_id: chatId,
1657+
message_id: messageId,
1658+
rich_message: richMessage,
1659+
...richEditParams,
1660+
}),
1661+
"editMessage",
1662+
(err) => !isTelegramMessageNotModifiedError(err),
1663+
);
1664+
} catch (err) {
1665+
if (!isTelegramRichMessageUnsupportedError(err)) {
1666+
throw err;
1667+
}
1668+
logVerbose(
1669+
`telegram edit rich message not supported; falling back to HTML edit: ${formatErrorMessage(err)}`,
1670+
);
1671+
// Fall through to regular HTML edit below.
1672+
}
16471673
}
16481674
return withTelegramHtmlParseFallback({
16491675
label: "editMessage",

0 commit comments

Comments
 (0)