Skip to content

Commit 77f0f40

Browse files
authored
fix(telegram): surface inbound media fetch failures (#100051)
1 parent 94ff3c6 commit 77f0f40

8 files changed

Lines changed: 359 additions & 116 deletions

‎extensions/telegram/src/bot-handlers.media.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ describe("isDurablyRetryableInboundMediaError", () => {
2222
).toBe(true);
2323
});
2424

25-
it("retries 408 and 5xx HTTP fetch failures", () => {
26-
for (const status of [408, 500, 502, 503, 504]) {
25+
it("retries 408, 429, and 5xx HTTP fetch failures", () => {
26+
for (const status of [408, 429, 500, 502, 503, 504]) {
2727
expect(
2828
isDurablyRetryableInboundMediaError(new MediaFetchError("http_error", "x", { status })),
2929
).toBe(true);
@@ -38,7 +38,7 @@ describe("isDurablyRetryableInboundMediaError", () => {
3838
}),
3939
),
4040
).toBe(false);
41-
for (const status of [400, 401, 403, 404, 429]) {
41+
for (const status of [400, 401, 403, 404]) {
4242
expect(
4343
isDurablyRetryableInboundMediaError(new MediaFetchError("http_error", "x", { status })),
4444
).toBe(false);

‎extensions/telegram/src/bot-handlers.media.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,25 @@ import type { Message } from "grammy/types";
33
import { MediaFetchError } from "openclaw/plugin-sdk/media-runtime";
44
import { isRecoverableTelegramNetworkError } from "./network-errors.js";
55

6+
const TELEGRAM_BOT_API_FILE_DOWNLOAD_LIMIT_MB = 20;
7+
8+
export class TelegramBotApiFileTooLargeError extends MediaFetchError {
9+
readonly limitMb = TELEGRAM_BOT_API_FILE_DOWNLOAD_LIMIT_MB;
10+
11+
constructor(cause: unknown) {
12+
super(
13+
"max_bytes",
14+
`Telegram Bot API cannot download files larger than ${TELEGRAM_BOT_API_FILE_DOWNLOAD_LIMIT_MB} MB`,
15+
{ cause, status: 400 },
16+
);
17+
this.name = "TelegramBotApiFileTooLargeError";
18+
}
19+
}
20+
621
export function isMediaSizeLimitError(err: unknown): boolean {
22+
if (err instanceof TelegramBotApiFileTooLargeError) {
23+
return true;
24+
}
725
const errMsg = String(err);
826
return errMsg.includes("exceeds") && errMsg.includes("MB limit");
927
}
@@ -27,7 +45,10 @@ export function isDurablyRetryableInboundMediaError(err: unknown): boolean {
2745
return false;
2846
}
2947
if (err.code === "http_error") {
30-
return typeof err.status === "number" && (err.status === 408 || err.status >= 500);
48+
return (
49+
typeof err.status === "number" &&
50+
(err.status === 408 || err.status === 429 || err.status >= 500)
51+
);
3152
}
3253
if (err.code !== "fetch_failed") {
3354
return false;

‎extensions/telegram/src/bot-handlers.runtime.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ import {
7373
isMediaSizeLimitError,
7474
isRecoverableMediaGroupError,
7575
resolveInboundMediaFileId,
76+
TelegramBotApiFileTooLargeError,
7677
} from "./bot-handlers.media.js";
7778
import type { TelegramMediaRef } from "./bot-message-context.js";
7879
import type {
@@ -220,6 +221,10 @@ export const registerTelegramHandlers = ({
220221
token: opts.token,
221222
transport: telegramTransport,
222223
});
224+
const mediaRuntimeWithAbort = {
225+
...mediaRuntimeOptions,
226+
abortSignal: opts.fetchAbortSignal,
227+
};
223228
const DEFAULT_TEXT_FRAGMENT_MAX_GAP_MS = 1500;
224229
const TELEGRAM_TEXT_FRAGMENT_START_THRESHOLD_CHARS = 4000;
225230
const TELEGRAM_TEXT_FRAGMENT_MAX_GAP_MS =
@@ -1038,7 +1043,7 @@ export const registerTelegramHandlers = ({
10381043
media = await resolveMedia({
10391044
ctx,
10401045
maxBytes: mediaMaxBytes,
1041-
...mediaRuntimeOptions,
1046+
...mediaRuntimeWithAbort,
10421047
});
10431048
} catch (mediaErr) {
10441049
if (!isRecoverableMediaGroupError(mediaErr)) {
@@ -1422,7 +1427,7 @@ export const registerTelegramHandlers = ({
14221427
getFile: async () => await bot.api.getFile(replyFileId),
14231428
},
14241429
maxBytes: mediaMaxBytes,
1425-
...mediaRuntimeOptions,
1430+
...mediaRuntimeWithAbort,
14261431
});
14271432
mediaRef = media
14281433
? {
@@ -2310,12 +2315,15 @@ export const registerTelegramHandlers = ({
23102315
media = await resolveMedia({
23112316
ctx,
23122317
maxBytes: mediaMaxBytes,
2313-
...mediaRuntimeOptions,
2318+
...mediaRuntimeWithAbort,
23142319
});
23152320
} catch (mediaErr) {
23162321
if (isMediaSizeLimitError(mediaErr)) {
23172322
if (sendOversizeWarning) {
2318-
const limitMb = Math.round(mediaMaxBytes / (1024 * 1024));
2323+
const limitMb =
2324+
mediaErr instanceof TelegramBotApiFileTooLargeError
2325+
? Math.min(mediaErr.limitMb, Math.round(mediaMaxBytes / (1024 * 1024)))
2326+
: Math.round(mediaMaxBytes / (1024 * 1024));
23192327
await withTelegramApiErrorLogging({
23202328
operation: "sendMessage",
23212329
runtime,

‎extensions/telegram/src/bot.create-telegram-bot.channel-post-media.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,84 @@ describe("createTelegramBot channel_post media", () => {
453453
}
454454
});
455455

456+
it("warns instead of dispatching a placeholder when Telegram getFile fails (#100000)", async () => {
457+
loadConfig.mockReturnValue({
458+
channels: { telegram: { dmPolicy: "open", allowFrom: ["*"] } },
459+
});
460+
sendMessageSpy.mockClear();
461+
replySpy.mockClear();
462+
463+
createTelegramBot({ token: "tok" });
464+
const handler = getOnHandler("message") as (ctx: Record<string, unknown>) => Promise<void>;
465+
466+
await handler({
467+
message: {
468+
chat: { id: 1234, type: "private" },
469+
message_id: 100000,
470+
date: 1736380800,
471+
document: { file_id: "doc-100000", file_name: "report.pdf" },
472+
from: { id: 55, is_bot: false, first_name: "u" },
473+
},
474+
me: { username: "openclaw_bot" },
475+
getFile: async () => {
476+
throw new Error("Network request for 'getFile' failed!");
477+
},
478+
});
479+
480+
await waitForMockCalls(sendMessageSpy, 1);
481+
expect(sendMessageSpy).toHaveBeenCalledWith(
482+
1234,
483+
"⚠️ Failed to download media. Please try again.",
484+
expect.objectContaining({
485+
reply_parameters: expect.objectContaining({ message_id: 100000 }),
486+
}),
487+
);
488+
expect(replySpy).not.toHaveBeenCalled();
489+
expect(saveRemoteMedia).not.toHaveBeenCalled();
490+
});
491+
492+
it.each([
493+
{ mediaMaxMb: 100, expectedLimitMb: 20 },
494+
{ mediaMaxMb: 10, expectedLimitMb: 10 },
495+
])(
496+
"reports the effective $expectedLimitMb MB limit for Telegram Bot API failures (#100000)",
497+
async ({ mediaMaxMb, expectedLimitMb }) => {
498+
loadConfig.mockReturnValue({
499+
channels: { telegram: { dmPolicy: "open", allowFrom: ["*"], mediaMaxMb } },
500+
});
501+
sendMessageSpy.mockClear();
502+
replySpy.mockClear();
503+
504+
createTelegramBot({ token: "tok" });
505+
const handler = getOnHandler("message") as (ctx: Record<string, unknown>) => Promise<void>;
506+
507+
await handler({
508+
message: {
509+
chat: { id: 1234, type: "private" },
510+
message_id: 100001,
511+
date: 1736380800,
512+
document: { file_id: "doc-100001", file_name: "large.bin" },
513+
from: { id: 55, is_bot: false, first_name: "u" },
514+
},
515+
me: { username: "openclaw_bot" },
516+
getFile: async () => {
517+
throw new Error("Bad Request: file is too big");
518+
},
519+
});
520+
521+
await waitForMockCalls(sendMessageSpy, 1);
522+
expect(sendMessageSpy).toHaveBeenCalledWith(
523+
1234,
524+
`⚠️ File too large. Maximum size is ${expectedLimitMb}MB.`,
525+
expect.objectContaining({
526+
reply_parameters: expect.objectContaining({ message_id: 100001 }),
527+
}),
528+
);
529+
expect(replySpy).not.toHaveBeenCalled();
530+
expect(saveRemoteMedia).not.toHaveBeenCalled();
531+
},
532+
);
533+
456534
it("durably retries a spooled-replay shutdown-abort document fetch without warning (#98076)", async () => {
457535
loadConfig.mockReturnValue({
458536
channels: { telegram: { dmPolicy: "open", allowFrom: ["*"] } },

0 commit comments

Comments
 (0)