Skip to content

Commit e497681

Browse files
committed
fix(telegram): keep outbound timeout guard authoritative
1 parent e0a267a commit e497681

7 files changed

Lines changed: 146 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Docs: https://docs.openclaw.ai
5959
- Plugins: clarify config-selected duplicate plugin override diagnostics and document manifest schema updates for bundled-plugin forks. Fixes #8582. Thanks @sachah.
6060
- CLI backends/Claude: make live-session JSONL turn caps bounded and configurable via `reliability.outputLimits`, raising the default guard for tool-heavy Claude CLI turns while preserving memory limits. Fixes #75838. Thanks @hcordoba840.
6161
- Telegram/DMs: keep incidental `message_thread_id` reply-with-quote metadata on the flat DM session by default while preserving opt-in DM topic isolation for configured topics, `dm.threadReplies`, and `direct.<chatId>.threadReplies`. Fixes #75975. Thanks @ProjectEvolutionEVE.
62+
- Telegram/network: raise outbound text and typing Bot API request guards to 60 seconds, keep low grammY client timeouts from preempting those guards, let higher `timeoutSeconds` configs extend safe method guards, and retry timed-out typing indicators through the transport fallback without risking duplicate messages. Fixes #76013. Thanks @iaki1206.
6263
- Providers/OpenAI: resolve `keychain:<service>:<account>` `OPENAI_API_KEY` refs before creating OpenAI Realtime browser sessions or voice bridges, with a bounded cached Keychain lookup. Fixes #72120. Thanks @ctbritt.
6364
- Discord/gateway: reconnect when the gateway socket closes while waiting for the shared IDENTIFY concurrency window, instead of silently skipping IDENTIFY and leaving the bot online but unresponsive. Fixes #74617. Thanks @zeeskdr-ai.
6465
- Voice Call: add `sessionScope: "per-call"` for fresh per-call agent memory while preserving the default per-phone caller history. Fixes #45280. Thanks @pondcountry.

‎docs/channels/telegram.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -724,7 +724,7 @@ curl "https://api.telegram.org/bot<bot_token>/getUpdates"
724724
- `channels.telegram.textChunkLimit` default is 4000.
725725
- `channels.telegram.chunkMode="newline"` prefers paragraph boundaries (blank lines) before length splitting.
726726
- `channels.telegram.mediaMaxMb` (default 100) caps inbound and outbound Telegram media size.
727-
- `channels.telegram.timeoutSeconds` overrides Telegram API client timeout (if unset, grammY default applies). Long-polling bot clients clamp configured values below the 45-second `getUpdates` request guard so idle polls are not aborted before the 30-second poll window completes.
727+
- `channels.telegram.timeoutSeconds` overrides Telegram API client timeout (if unset, grammY default applies). Bot clients clamp configured values below the 60-second outbound text/typing request guard so grammY does not abort visible reply delivery before OpenClaw's transport guard and fallback can run. Long polling still uses a 45-second `getUpdates` request guard so idle polls are not abandoned indefinitely.
728728
- `channels.telegram.pollingStallThresholdMs` defaults to `120000`; tune between `30000` and `600000` only for false-positive polling-stall restarts.
729729
- group context history uses `channels.telegram.historyLimit` or `messages.groupChat.historyLimit` (default 50); `0` disables.
730730
- reply/quote/forward supplemental context is currently passed as received.
@@ -846,7 +846,7 @@ Per-account, per-group, and per-topic overrides are supported (same inheritance
846846
- authorize your sender identity (pairing and/or numeric `allowFrom`)
847847
- command authorization still applies even when group policy is `open`
848848
- `setMyCommands failed` with `BOT_COMMANDS_TOO_MUCH` means the native menu has too many entries; reduce plugin/skill/custom commands or disable native menus
849-
- `deleteMyCommands` / `setMyCommands` startup calls are bounded and retry once through Telegram's transport fallback on request timeout. Persistent network/fetch errors usually indicate DNS/HTTPS reachability issues to `api.telegram.org`
849+
- `deleteMyCommands` / `setMyCommands` startup calls and `sendChatAction` typing calls are bounded and retry once through Telegram's transport fallback on request timeout. Persistent network/fetch errors usually indicate DNS/HTTPS reachability issues to `api.telegram.org`
850850

851851
</Accordion>
852852

@@ -864,7 +864,7 @@ Per-account, per-group, and per-topic overrides are supported (same inheritance
864864
- Node 22+ + custom fetch/proxy can trigger immediate abort behavior if AbortSignal types mismatch.
865865
- Some hosts resolve `api.telegram.org` to IPv6 first; broken IPv6 egress can cause intermittent Telegram API failures.
866866
- If logs include `TypeError: fetch failed` or `Network request for 'getUpdates' failed!`, OpenClaw now retries these as recoverable network errors.
867-
- If Telegram sockets recycle on a short fixed cadence, check for a low `channels.telegram.timeoutSeconds`; long-polling bot clients clamp configured values below the `getUpdates` request guard, but older releases could abort every poll when this was set below the long-poll timeout.
867+
- If Telegram sockets recycle on a short fixed cadence, check for a low `channels.telegram.timeoutSeconds`; bot clients clamp configured values below the outbound and `getUpdates` request guards, but older releases could abort every poll or reply when this was set below those guards.
868868
- If logs include `Polling stall detected`, OpenClaw restarts polling and rebuilds the Telegram transport after 120 seconds without completed long-poll liveness by default.
869869
- `openclaw channels status --probe` and `openclaw doctor` warn when a running polling account has not completed `getUpdates` after startup grace, when a running webhook account has not completed `setWebhook` after startup grace, or when the last successful polling transport activity is stale.
870870
- Increase `channels.telegram.pollingStallThresholdMs` only when long-running `getUpdates` calls are healthy but your host still reports false polling-stall restarts. Persistent stalls usually point to proxy, DNS, IPv6, or TLS egress issues between the host and `api.telegram.org`.

‎extensions/telegram/src/bot-core.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ const TELEGRAM_TIMEOUT_FALLBACK_METHODS = new Set([
132132
"deletemycommands",
133133
"deletewebhook",
134134
"getme",
135+
"sendchataction",
135136
"setmycommands",
136137
"setwebhook",
137138
]);
@@ -154,6 +155,23 @@ function resolveTelegramClientTimeoutSeconds(params: {
154155
return Math.max(configured, Math.max(1, Math.floor(minimum)));
155156
}
156157

158+
function resolveTelegramClientTimeoutMinimumSeconds(values: readonly (number | undefined)[]) {
159+
let minimum: number | undefined;
160+
for (const value of values) {
161+
if (typeof value !== "number" || !Number.isFinite(value)) {
162+
continue;
163+
}
164+
const normalized = Math.max(1, Math.ceil(value));
165+
minimum = minimum === undefined ? normalized : Math.max(minimum, normalized);
166+
}
167+
return minimum;
168+
}
169+
170+
function resolveTelegramOutboundClientTimeoutFloorSeconds(timeoutSeconds: unknown) {
171+
const timeoutMs = resolveTelegramRequestTimeoutMs("sendmessage", timeoutSeconds);
172+
return timeoutMs === undefined ? undefined : timeoutMs / 1000;
173+
}
174+
157175
export function createTelegramBotCore(
158176
opts: TelegramBotOptions & { telegramDeps: TelegramBotDeps },
159177
): TelegramBotInstance {
@@ -214,7 +232,7 @@ export function createTelegramBotCore(
214232
// causing "signals[0] must be an instance of AbortSignal" errors).
215233
finalFetch = async (input: TelegramFetchInput, init?: TelegramFetchInit) => {
216234
const method = extractTelegramApiMethod(input);
217-
const requestTimeoutMs = resolveTelegramRequestTimeoutMs(method);
235+
const requestTimeoutMs = resolveTelegramRequestTimeoutMs(method, telegramCfg?.timeoutSeconds);
218236
const shutdownSignal = isTelegramAbortSignalLike(opts.fetchAbortSignal)
219237
? opts.fetchAbortSignal
220238
: undefined;
@@ -314,7 +332,10 @@ export function createTelegramBotCore(
314332

315333
const timeoutSeconds = resolveTelegramClientTimeoutSeconds({
316334
value: telegramCfg?.timeoutSeconds,
317-
minimum: opts.minimumClientTimeoutSeconds,
335+
minimum: resolveTelegramClientTimeoutMinimumSeconds([
336+
opts.minimumClientTimeoutSeconds,
337+
resolveTelegramOutboundClientTimeoutFloorSeconds(telegramCfg?.timeoutSeconds),
338+
]),
318339
});
319340
const apiRoot = normalizeOptionalString(telegramCfg.apiRoot);
320341
const normalizedApiRoot = apiRoot ? normalizeTelegramApiRoot(apiRoot) : undefined;

‎extensions/telegram/src/bot.create-telegram-bot.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ describe("createTelegramBot", () => {
248248
);
249249
});
250250

251-
it("honors low timeoutSeconds when no polling floor is requested", () => {
251+
it("keeps low timeoutSeconds above the outbound request guard", () => {
252252
loadConfig.mockReturnValue({
253253
channels: {
254254
telegram: { dmPolicy: "open", allowFrom: ["*"], timeoutSeconds: 10 },
@@ -258,12 +258,12 @@ describe("createTelegramBot", () => {
258258
expect(botCtorSpy).toHaveBeenCalledWith(
259259
"tok",
260260
expect.objectContaining({
261-
client: expect.objectContaining({ timeoutSeconds: 10 }),
261+
client: expect.objectContaining({ timeoutSeconds: 60 }),
262262
}),
263263
);
264264
});
265265

266-
it("keeps polling client timeout above the getUpdates request guard", () => {
266+
it("keeps polling client timeout above the outbound request guard", () => {
267267
loadConfig.mockReturnValue({
268268
channels: {
269269
telegram: { dmPolicy: "open", allowFrom: ["*"], timeoutSeconds: 10 },
@@ -273,7 +273,7 @@ describe("createTelegramBot", () => {
273273
expect(botCtorSpy).toHaveBeenCalledWith(
274274
"tok",
275275
expect.objectContaining({
276-
client: expect.objectContaining({ timeoutSeconds: 45 }),
276+
client: expect.objectContaining({ timeoutSeconds: 60 }),
277277
}),
278278
);
279279
});

‎extensions/telegram/src/bot.fetch-abort.test.ts‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,15 @@ const createTelegramBot = (opts: import("./bot.types.js").TelegramBotOptions) =>
1414
telegramDeps: telegramBotDepsForTest,
1515
});
1616

17-
function createWrappedTelegramClientFetch(proxyFetch: typeof fetch) {
17+
function createWrappedTelegramClientFetch(
18+
proxyFetch: typeof fetch,
19+
config?: import("openclaw/plugin-sdk/config-types").OpenClawConfig,
20+
) {
1821
const shutdown = new AbortController();
1922
botCtorSpy.mockClear();
2023
createTelegramBot({
2124
token: "tok",
25+
...(config ? { config } : {}),
2226
fetchAbortSignal: shutdown.signal,
2327
proxyFetch,
2428
});
@@ -111,6 +115,53 @@ describe("createTelegramBot fetch abort", () => {
111115
vi.useRealTimers();
112116
});
113117

118+
it("uses the longer outbound text timeout for sendMessage", async () => {
119+
vi.useFakeTimers();
120+
const fetchSpy = vi.fn(
121+
(_input: RequestInfo | URL, init?: RequestInit) =>
122+
new Promise<AbortSignal>((resolve) => {
123+
const signal = init?.signal as AbortSignal;
124+
signal.addEventListener("abort", () => resolve(signal), { once: true });
125+
}),
126+
);
127+
const { clientFetch } = createWrappedTelegramClientFetch(fetchSpy as unknown as typeof fetch);
128+
129+
const observedSignalPromise = clientFetch("https://api.telegram.org/bot123456:ABC/sendMessage");
130+
await vi.advanceTimersByTimeAsync(60_000);
131+
const observedSignal = (await observedSignalPromise) as AbortSignal;
132+
133+
expect(observedSignal).toBeInstanceOf(AbortSignal);
134+
expect(observedSignal.aborted).toBe(true);
135+
vi.useRealTimers();
136+
});
137+
138+
it("lets configured timeoutSeconds extend outbound method guards", async () => {
139+
vi.useFakeTimers();
140+
const fetchSpy = vi.fn(
141+
(_input: RequestInfo | URL, init?: RequestInit) =>
142+
new Promise<AbortSignal>((resolve) => {
143+
const signal = init?.signal as AbortSignal;
144+
signal.addEventListener("abort", () => resolve(signal), { once: true });
145+
}),
146+
);
147+
const { clientFetch } = createWrappedTelegramClientFetch(
148+
fetchSpy as unknown as typeof fetch,
149+
{
150+
channels: { telegram: { timeoutSeconds: 90 } },
151+
} as never,
152+
);
153+
154+
const observedSignalPromise = clientFetch(
155+
"https://api.telegram.org/bot123456:ABC/editMessageText",
156+
);
157+
await vi.advanceTimersByTimeAsync(90_000);
158+
const observedSignal = (await observedSignalPromise) as AbortSignal;
159+
160+
expect(observedSignal).toBeInstanceOf(AbortSignal);
161+
expect(observedSignal.aborted).toBe(true);
162+
vi.useRealTimers();
163+
});
164+
114165
it("retries timed-out control calls once after forcing transport fallback", async () => {
115166
vi.useFakeTimers();
116167
const forceFallback = vi.fn(() => true);
@@ -168,6 +219,33 @@ describe("createTelegramBot fetch abort", () => {
168219
},
169220
);
170221

222+
it("retries timed-out sendChatAction once after forcing transport fallback", async () => {
223+
vi.useFakeTimers();
224+
const forceFallback = vi.fn(() => true);
225+
const fetchSpy = vi
226+
.fn()
227+
.mockImplementationOnce(
228+
(_input: RequestInfo | URL, init?: RequestInit) =>
229+
new Promise((_resolve, reject) => {
230+
const signal = init?.signal as AbortSignal;
231+
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
232+
}),
233+
)
234+
.mockResolvedValueOnce({ ok: true } as Response);
235+
const { clientFetch } = createWrappedTelegramClientFetchWithTransport({
236+
fetch: fetchSpy as unknown as typeof fetch,
237+
forceFallback,
238+
});
239+
240+
const resultPromise = clientFetch("https://api.telegram.org/bot123456:ABC/sendChatAction");
241+
await vi.advanceTimersByTimeAsync(60_000);
242+
243+
await expect(resultPromise).resolves.toEqual({ ok: true });
244+
expect(forceFallback).toHaveBeenCalledWith("request-timeout");
245+
expect(fetchSpy).toHaveBeenCalledTimes(2);
246+
vi.useRealTimers();
247+
});
248+
171249
it("preserves the original fetch error when tagging cannot attach metadata", async () => {
172250
const frozenError = Object.freeze(
173251
Object.assign(new TypeError("fetch failed"), {

‎extensions/telegram/src/request-timeouts.test.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,25 @@ describe("resolveTelegramRequestTimeoutMs", () => {
1818
});
1919

2020
it("bounds outbound delivery methods", () => {
21-
expect(resolveTelegramRequestTimeoutMs("sendmessage")).toBe(20_000);
22-
expect(resolveTelegramRequestTimeoutMs("sendchataction")).toBe(10_000);
21+
expect(resolveTelegramRequestTimeoutMs("sendmessage")).toBe(60_000);
22+
expect(resolveTelegramRequestTimeoutMs("sendchataction")).toBe(60_000);
23+
expect(resolveTelegramRequestTimeoutMs("sendmessagedraft")).toBe(60_000);
2324
expect(resolveTelegramRequestTimeoutMs("editmessagetext")).toBe(15_000);
2425
expect(resolveTelegramRequestTimeoutMs("sendphoto")).toBe(30_000);
2526
});
2627

28+
it("honors higher configured timeoutSeconds except for long polling", () => {
29+
expect(resolveTelegramRequestTimeoutMs("sendmessage", 90)).toBe(90_000);
30+
expect(resolveTelegramRequestTimeoutMs("sendchataction", 90)).toBe(90_000);
31+
expect(resolveTelegramRequestTimeoutMs("editmessagetext", 90)).toBe(90_000);
32+
expect(resolveTelegramRequestTimeoutMs("getupdates", 90)).toBe(45_000);
33+
});
34+
35+
it("does not let low timeoutSeconds shorten method guards", () => {
36+
expect(resolveTelegramRequestTimeoutMs("sendmessage", 10)).toBe(60_000);
37+
expect(resolveTelegramRequestTimeoutMs("getme", 10)).toBe(15_000);
38+
});
39+
2740
it("does not assign hard timeouts to unrelated Telegram methods", () => {
2841
expect(resolveTelegramRequestTimeoutMs("answercallbackquery")).toBeUndefined();
2942
expect(resolveTelegramRequestTimeoutMs(null)).toBeUndefined();

‎extensions/telegram/src/request-timeouts.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export const TELEGRAM_GET_UPDATES_REQUEST_TIMEOUT_MS = 45_000;
2+
const TELEGRAM_OUTBOUND_TEXT_REQUEST_TIMEOUT_MS = 60_000;
23

34
const TELEGRAM_REQUEST_TIMEOUTS_MS = {
45
// Bound startup/control-plane calls so the gateway cannot report Telegram as
@@ -15,10 +16,10 @@ const TELEGRAM_REQUEST_TIMEOUTS_MS = {
1516
pinchatmessage: 15_000,
1617
sendanimation: 30_000,
1718
sendaudio: 30_000,
18-
sendchataction: 10_000,
19+
sendchataction: TELEGRAM_OUTBOUND_TEXT_REQUEST_TIMEOUT_MS,
1920
senddocument: 30_000,
20-
sendmessage: 20_000,
21-
sendmessagedraft: 20_000,
21+
sendmessage: TELEGRAM_OUTBOUND_TEXT_REQUEST_TIMEOUT_MS,
22+
sendmessagedraft: TELEGRAM_OUTBOUND_TEXT_REQUEST_TIMEOUT_MS,
2223
sendphoto: 30_000,
2324
sendvideo: 30_000,
2425
sendvoice: 30_000,
@@ -27,11 +28,26 @@ const TELEGRAM_REQUEST_TIMEOUTS_MS = {
2728
setwebhook: 15_000,
2829
} as const;
2930

30-
export function resolveTelegramRequestTimeoutMs(method: string | null): number | undefined {
31+
function resolveConfiguredTelegramRequestTimeoutMs(timeoutSeconds: unknown): number | undefined {
32+
if (typeof timeoutSeconds !== "number" || !Number.isFinite(timeoutSeconds)) {
33+
return undefined;
34+
}
35+
return Math.max(1, Math.floor(timeoutSeconds)) * 1000;
36+
}
37+
38+
export function resolveTelegramRequestTimeoutMs(
39+
method: string | null,
40+
timeoutSeconds?: unknown,
41+
): number | undefined {
3142
if (!method) {
3243
return undefined;
3344
}
34-
return TELEGRAM_REQUEST_TIMEOUTS_MS[method as keyof typeof TELEGRAM_REQUEST_TIMEOUTS_MS];
45+
const baseTimeoutMs =
46+
TELEGRAM_REQUEST_TIMEOUTS_MS[method as keyof typeof TELEGRAM_REQUEST_TIMEOUTS_MS];
47+
if (baseTimeoutMs === undefined || method === "getupdates") {
48+
return baseTimeoutMs;
49+
}
50+
return Math.max(baseTimeoutMs, resolveConfiguredTelegramRequestTimeoutMs(timeoutSeconds) ?? 0);
3551
}
3652

3753
export function resolveTelegramStartupProbeTimeoutMs(timeoutSeconds: unknown): number {

0 commit comments

Comments
 (0)