Skip to content

Commit c5488ea

Browse files
committed
fix(telegram): expose media group flush config
1 parent 52257fd commit c5488ea

10 files changed

Lines changed: 123 additions & 5 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Docs: https://docs.openclaw.ai
3030
### Fixes
3131

3232
- Gateway/usage: serve `usage.cost` and `sessions.usage` from a durable transcript aggregate cache with lock-safe background refreshes and localized stale-cache status, so large usage views avoid repeated full scans. (#76650) Thanks @Marvinthebored.
33+
- Telegram: add `channels.telegram.mediaGroupFlushMs` at the top level and per account so operators can tune album buffering instead of being stuck with the hard-coded 500ms media-group flush window. Fixes #76149. Thanks @vincentkoc.
3334
- Config/messages: coerce boolean `messages.visibleReplies` and `messages.groupChat.visibleReplies` values to the documented enum modes so an intuitive toggle no longer invalidates config and drops channel startup. Fixes #75390. Thanks @scottgl9.
3435
- Feishu: accept and honor `channels.feishu.blockStreaming` at the top level and per account, while keeping the legacy default off so Feishu cards no longer reject documented config or silently drop block replies. Fixes #75555. Thanks @vincentkoc.
3536
- Google Chat: normalize custom Google auth transport headers before google-auth/gaxios interceptors run, restoring webhook token verification when certificate retrieval expects Fetch `Headers`. Fixes #76742. Thanks @donbowman.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
c1de046645b03b1ec47ec41811b67c0e7ad5460842b54416a47757ef22b9b17e config-baseline.json
1+
df881d10bfb3d1ba0439e5984117dde70b5f7e856696f25c7f4b5c978a38f841 config-baseline.json
22
f945a060012b3e7c675fb3ea0c5f18996cdcc06c9ec6cead389e04791a529ce9 config-baseline.core.json
3-
76979aba007500abc52b970da76b6512291916739c29d6a3f4218772d1a31186 config-baseline.channel.json
3+
09a952cf734a5b4a30f760e570c0f106d54aa8e74bf439dd4d07013f9f7607e4 config-baseline.channel.json
44
245aa98aabc6c2e3c57a69e639c2fb10d84a7e1e1b3bcdadc340fa61ca998287 config-baseline.plugin.json

‎docs/channels/telegram.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,7 @@ curl "https://api.telegram.org/bot<bot_token>/getUpdates"
729729
- `channels.telegram.textChunkLimit` default is 4000.
730730
- `channels.telegram.chunkMode="newline"` prefers paragraph boundaries (blank lines) before length splitting.
731731
- `channels.telegram.mediaMaxMb` (default 100) caps inbound and outbound Telegram media size.
732+
- `channels.telegram.mediaGroupFlushMs` (default 500) controls how long Telegram albums/media groups are buffered before OpenClaw dispatches them as one inbound message. Increase it if album parts arrive late; decrease it to reduce album reply latency.
732733
- `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.
733734
- `channels.telegram.pollingStallThresholdMs` defaults to `120000`; tune between `30000` and `600000` only for false-positive polling-stall restarts.
734735
- group context history uses `channels.telegram.historyLimit` or `messages.groupChat.historyLimit` (default 50); `0` disables.
@@ -950,7 +951,7 @@ Primary reference: [Configuration reference - Telegram](/gateway/config-channels
950951
- threading/replies: `replyToMode`, `dm.threadReplies`, `direct.*.threadReplies`
951952
- streaming: `streaming` (preview), `streaming.preview.toolProgress`, `blockStreaming`
952953
- formatting/delivery: `textChunkLimit`, `chunkMode`, `linkPreview`, `responsePrefix`
953-
- media/network: `mediaMaxMb`, `timeoutSeconds`, `pollingStallThresholdMs`, `retry`, `network.autoSelectFamily`, `network.dangerouslyAllowPrivateNetwork`, `proxy`
954+
- media/network: `mediaMaxMb`, `mediaGroupFlushMs`, `timeoutSeconds`, `pollingStallThresholdMs`, `retry`, `network.autoSelectFamily`, `network.dangerouslyAllowPrivateNetwork`, `proxy`
954955
- custom API root: `apiRoot` (Bot API root only; do not include `/bot<TOKEN>`)
955956
- webhook: `webhookUrl`, `webhookSecret`, `webhookPath`, `webhookHost`
956957
- actions/capabilities: `capabilities.inlineButtons`, `actions.sendMessage|editMessage|deleteMessage|reactions|sticker`

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,10 @@ export const registerTelegramHandlers = ({
148148
typeof opts.testTimings?.mediaGroupFlushMs === "number" &&
149149
Number.isFinite(opts.testTimings.mediaGroupFlushMs)
150150
? Math.max(10, Math.floor(opts.testTimings.mediaGroupFlushMs))
151-
: MEDIA_GROUP_TIMEOUT_MS;
151+
: typeof telegramCfg.mediaGroupFlushMs === "number" &&
152+
Number.isFinite(telegramCfg.mediaGroupFlushMs)
153+
? Math.max(10, Math.floor(telegramCfg.mediaGroupFlushMs))
154+
: MEDIA_GROUP_TIMEOUT_MS;
152155

153156
const mediaGroupBuffer = new Map<string, MediaGroupEntry>();
154157
let mediaGroupProcessing: Promise<void> = Promise.resolve();

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

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,18 @@ function getChannelPostHandler() {
4545
return getOnHandler("channel_post") as (ctx: Record<string, unknown>) => Promise<void>;
4646
}
4747

48+
function getChannelPostHandlerWithRuntimeTimings() {
49+
createTelegramBot({ token: "tok" });
50+
return getOnHandler("channel_post") as (ctx: Record<string, unknown>) => Promise<void>;
51+
}
52+
4853
function resolveFlushTimer(setTimeoutSpy: ReturnType<typeof vi.spyOn>) {
54+
return resolveFlushTimerForDelay(setTimeoutSpy, TELEGRAM_TEST_TIMINGS.mediaGroupFlushMs);
55+
}
56+
57+
function resolveFlushTimerForDelay(setTimeoutSpy: ReturnType<typeof vi.spyOn>, delayMs: number) {
4958
const flushTimerCallIndex = setTimeoutSpy.mock.calls.findLastIndex(
50-
(call: Parameters<typeof setTimeout>) => call[1] === TELEGRAM_TEST_TIMINGS.mediaGroupFlushMs,
59+
(call: Parameters<typeof setTimeout>) => call[1] === delayMs,
5160
);
5261
const flushTimer =
5362
flushTimerCallIndex >= 0
@@ -104,6 +113,15 @@ async function flushChannelPostMediaGroup(setTimeoutSpy: ReturnType<typeof vi.sp
104113
await flushTimer?.();
105114
}
106115

116+
async function flushChannelPostMediaGroupForDelay(
117+
setTimeoutSpy: ReturnType<typeof vi.spyOn>,
118+
delayMs: number,
119+
) {
120+
const flushTimer = resolveFlushTimerForDelay(setTimeoutSpy, delayMs);
121+
expect(flushTimer).toBeTypeOf("function");
122+
await flushTimer?.();
123+
}
124+
107125
async function queueChannelPostAlbum(
108126
handler: ReturnType<typeof getChannelPostHandler>,
109127
params: {
@@ -181,6 +199,44 @@ describe("createTelegramBot channel_post media", () => {
181199
}
182200
});
183201

202+
it("honors configured mediaGroupFlushMs for channel_post albums", async () => {
203+
loadConfig.mockReturnValue({
204+
channels: {
205+
telegram: {
206+
groupPolicy: "open",
207+
mediaGroupFlushMs: 75,
208+
groups: {
209+
"-100777111222": {
210+
enabled: true,
211+
requireMention: false,
212+
},
213+
},
214+
},
215+
},
216+
});
217+
218+
const fetchSpy = createImageFetchSpy();
219+
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
220+
try {
221+
const handler = getChannelPostHandlerWithRuntimeTimings();
222+
await queueChannelPostAlbum(handler, {
223+
caption: "configured album",
224+
mediaGroupId: "channel-album-configured",
225+
firstMessageId: 211,
226+
secondMessageId: 212,
227+
});
228+
expect(replySpy).not.toHaveBeenCalled();
229+
await flushChannelPostMediaGroupForDelay(setTimeoutSpy, 75);
230+
231+
expect(replySpy).toHaveBeenCalledTimes(1);
232+
const payload = replySpy.mock.calls[0]?.[0] as { Body?: string };
233+
expect(payload.Body).toContain("configured album");
234+
} finally {
235+
setTimeoutSpy.mockRestore();
236+
fetchSpy.mockRestore();
237+
}
238+
});
239+
184240
it("coalesces channel_post near-limit text fragments into one message", async () => {
185241
setOpenChannelPostConfig();
186242

‎extensions/telegram/src/config-schema.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,24 @@ describe("telegram custom commands schema", () => {
6666
}
6767
});
6868

69+
it("accepts mediaGroupFlushMs overrides per account", () => {
70+
const res = TelegramConfigSchema.safeParse({
71+
mediaGroupFlushMs: 750,
72+
accounts: { ops: { mediaGroupFlushMs: 1500 } },
73+
});
74+
75+
expect(res.success).toBe(true);
76+
if (res.success) {
77+
expect(res.data.mediaGroupFlushMs).toBe(750);
78+
expect(res.data.accounts?.ops?.mediaGroupFlushMs).toBe(1500);
79+
}
80+
});
81+
82+
it("rejects mediaGroupFlushMs outside the supported flush bounds", () => {
83+
expectTelegramConfigIssue({ mediaGroupFlushMs: 9 }, "mediaGroupFlushMs");
84+
expectTelegramConfigIssue({ mediaGroupFlushMs: 60_001 }, "mediaGroupFlushMs");
85+
});
86+
6987
it("accepts DM thread reply policy overrides", () => {
7088
const res = TelegramConfigSchema.safeParse({
7189
dm: { threadReplies: "off" },

‎extensions/telegram/src/config-ui-hints.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ export const telegramChannelConfigUiHints = {
101101
label: "Telegram API Timeout (seconds)",
102102
help: "Max seconds before Telegram API requests are aborted (default: 500 per grammY).",
103103
},
104+
mediaGroupFlushMs: {
105+
label: "Telegram Media Group Flush (ms)",
106+
help: "Milliseconds to buffer Telegram albums/media groups before dispatching them as one inbound message. Default: 500.",
107+
},
104108
pollingStallThresholdMs: {
105109
label: "Telegram Polling Stall Threshold (ms)",
106110
help: "Milliseconds without completed Telegram getUpdates liveness before the polling watchdog restarts the polling runner. Default: 120000.",

‎src/config/bundled-channel-config-metadata.generated.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4172,6 +4172,9 @@ export const GENERATED_BUNDLED_CHANNEL_CONFIG_METADATA = [
41724172
type: "string",
41734173
enum: ["length", "newline"],
41744174
},
4175+
blockStreaming: {
4176+
type: "boolean",
4177+
},
41754178
blockStreamingCoalesce: {
41764179
type: "object",
41774180
properties: {
@@ -4800,6 +4803,9 @@ export const GENERATED_BUNDLED_CHANNEL_CONFIG_METADATA = [
48004803
type: "string",
48014804
enum: ["length", "newline"],
48024805
},
4806+
blockStreaming: {
4807+
type: "boolean",
4808+
},
48034809
blockStreamingCoalesce: {
48044810
type: "object",
48054811
properties: {
@@ -14128,6 +14134,13 @@ export const GENERATED_BUNDLED_CHANNEL_CONFIG_METADATA = [
1412814134
exclusiveMinimum: 0,
1412914135
maximum: 9007199254740991,
1413014136
},
14137+
mediaGroupFlushMs: {
14138+
description:
14139+
"Buffer window in milliseconds for Telegram media groups/albums before dispatching them as one inbound message. Default: 500.",
14140+
type: "integer",
14141+
minimum: 10,
14142+
maximum: 60000,
14143+
},
1413114144
pollingStallThresholdMs: {
1413214145
type: "integer",
1413314146
minimum: 30000,
@@ -15190,6 +15203,13 @@ export const GENERATED_BUNDLED_CHANNEL_CONFIG_METADATA = [
1519015203
exclusiveMinimum: 0,
1519115204
maximum: 9007199254740991,
1519215205
},
15206+
mediaGroupFlushMs: {
15207+
description:
15208+
"Buffer window in milliseconds for Telegram media groups/albums before dispatching them as one inbound message. Default: 500.",
15209+
type: "integer",
15210+
minimum: 10,
15211+
maximum: 60000,
15212+
},
1519315213
pollingStallThresholdMs: {
1519415214
type: "integer",
1519515215
minimum: 30000,
@@ -15594,6 +15614,10 @@ export const GENERATED_BUNDLED_CHANNEL_CONFIG_METADATA = [
1559415614
label: "Telegram API Timeout (seconds)",
1559515615
help: "Max seconds before Telegram API requests are aborted (default: 500 per grammY).",
1559615616
},
15617+
mediaGroupFlushMs: {
15618+
label: "Telegram Media Group Flush (ms)",
15619+
help: "Milliseconds to buffer Telegram albums/media groups before dispatching them as one inbound message. Default: 500.",
15620+
},
1559715621
pollingStallThresholdMs: {
1559815622
label: "Telegram Polling Stall Threshold (ms)",
1559915623
help: "Milliseconds without completed Telegram getUpdates liveness before the polling watchdog restarts the polling runner. Default: 120000.",

‎src/config/types.telegram.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ export type TelegramAccountConfig = {
152152
mediaMaxMb?: number;
153153
/** Telegram API client timeout in seconds (grammY ApiClientOptions). */
154154
timeoutSeconds?: number;
155+
/** Buffer window for Telegram media groups/albums before dispatching them as one inbound message. Default: 500ms. */
156+
mediaGroupFlushMs?: number;
155157
/** Telegram polling watchdog threshold in milliseconds. Default: 120000. */
156158
pollingStallThresholdMs?: number;
157159
/** Retry policy for outbound Telegram API calls. */

‎src/config/zod-schema.providers-core.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,15 @@ export const TelegramAccountSchemaBase = z
252252
streaming: ChannelPreviewStreamingConfigSchema.optional(),
253253
mediaMaxMb: z.number().positive().optional(),
254254
timeoutSeconds: z.number().int().positive().optional(),
255+
mediaGroupFlushMs: z
256+
.number()
257+
.int()
258+
.min(10)
259+
.max(60_000)
260+
.optional()
261+
.describe(
262+
"Buffer window in milliseconds for Telegram media groups/albums before dispatching them as one inbound message. Default: 500.",
263+
),
255264
pollingStallThresholdMs: z.number().int().min(30_000).max(600_000).optional(),
256265
retry: RetryConfigSchema,
257266
network: z

0 commit comments

Comments
 (0)