Skip to content

Commit 4f699be

Browse files
author
jet
committed
fix(telegram): bypass grammY sequential key for interrupt/steer message delivery
- Per-message sequential keys for steer/interrupt so they bypass the debouncer and are delivered immediately without waiting for the previous message's response. - Extract resolveEffectiveQueueMode helper (shared with queue/settings.ts) to avoid duplicating the session → channel → global cascade in the Telegram hot path. - Fix stale steer+backlog comparison (normalized to steer-backlog).
1 parent d4aa967 commit 4f699be

12 files changed

Lines changed: 472 additions & 57 deletions

File tree

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { upsertChannelPairingRequest } from "openclaw/plugin-sdk/conversation-ru
66
import { enqueueSystemEvent } from "openclaw/plugin-sdk/infra-runtime";
77
import { buildModelsProviderData } from "openclaw/plugin-sdk/models-provider-runtime";
88
import { dispatchReplyWithBufferedBlockDispatcher } from "openclaw/plugin-sdk/reply-dispatch-runtime";
9+
import { isEmbeddedPiRunActiveForSessionKey } from "openclaw/plugin-sdk/reply-runtime";
910
import { listSkillCommandsForAgents } from "openclaw/plugin-sdk/skill-commands-runtime";
1011
import { loadWebMedia } from "openclaw/plugin-sdk/web-media";
1112
import { syncTelegramMenuCommands } from "./bot-native-command-menu.js";
@@ -23,6 +24,8 @@ export type TelegramBotDeps = {
2324
upsertChannelPairingRequest: typeof upsertChannelPairingRequest;
2425
enqueueSystemEvent: typeof enqueueSystemEvent;
2526
dispatchReplyWithBufferedBlockDispatcher: typeof dispatchReplyWithBufferedBlockDispatcher;
27+
/** Check whether an embedded Pi run is active for a given sessionKey. */
28+
isRunActiveForSessionKey?: (sessionKey: string) => boolean;
2629
loadWebMedia?: typeof loadWebMedia;
2730
buildModelsProviderData: typeof buildModelsProviderData;
2831
listSkillCommandsForAgents: typeof listSkillCommandsForAgents;
@@ -73,6 +76,9 @@ export const defaultTelegramBotDeps: TelegramBotDeps = {
7376
get wasSentByBot() {
7477
return wasSentByBot;
7578
},
79+
get isRunActiveForSessionKey() {
80+
return isEmbeddedPiRunActiveForSessionKey;
81+
},
7682
get resolveExecApproval() {
7783
return resolveTelegramExecApproval;
7884
},

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

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import { formatModelsAvailableHeader } from "openclaw/plugin-sdk/models-provider
2626
import { resolveAgentRoute } from "openclaw/plugin-sdk/routing";
2727
import { resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
2828
import { danger, logVerbose, warn } from "openclaw/plugin-sdk/runtime-env";
29+
import { resolveEffectiveQueueMode } from "openclaw/plugin-sdk/core";
2930
import { resolveTelegramMediaRuntimeOptions } from "./accounts.js";
3031
import { withTelegramApiErrorLogging } from "./api-logging.js";
3132
import {
@@ -97,6 +98,7 @@ import {
9798
type ProviderInfo,
9899
} from "./model-buttons.js";
99100
import { buildInlineKeyboard } from "./send.js";
101+
import { buildChatSessionCacheKey, CHAT_SESSION_CACHE_MAX } from "./sequential-key.js";
100102

101103
export const registerTelegramHandlers = ({
102104
cfg,
@@ -115,6 +117,7 @@ export const registerTelegramHandlers = ({
115117
processMessage,
116118
logger,
117119
telegramDeps = defaultTelegramBotDeps,
120+
chatSessionCache,
118121
}: RegisterTelegramHandlerParams) => {
119122
const mediaRuntimeOptions = resolveTelegramMediaRuntimeOptions({
120123
cfg,
@@ -1102,6 +1105,86 @@ export const registerTelegramHandlers = ({
11021105
debounceLane,
11031106
})
11041107
: null;
1108+
1109+
// Populate chat session cache and check for debouncer bypass.
1110+
// When an agent run is active and the queue mode needs immediate delivery
1111+
// (steer/interrupt), bypass the debouncer to avoid keyChains serialization.
1112+
if (chatSessionCache && telegramDeps.isRunActiveForSessionKey) {
1113+
const isGroup = msg.chat.type === "group" || msg.chat.type === "supergroup";
1114+
const isForum = msg.chat.is_forum === true;
1115+
try {
1116+
const sessionState = resolveTelegramSessionState({
1117+
chatId,
1118+
isGroup,
1119+
isForum,
1120+
resolvedThreadId,
1121+
messageThreadId: msg.message_thread_id,
1122+
senderId,
1123+
});
1124+
// Resolve the effective queue mode using the same cascade as
1125+
// resolveQueueSettings (session → channel → global → "collect").
1126+
// This is an intentional duplication for the hot path — the canonical
1127+
// resolveQueueSettings requires full session context params that are
1128+
// not yet available at sequentializer level.
1129+
// NOTE: Per-message inline queue directives (e.g. /interrupt as a one-off) are resolved
1130+
// later in the pipeline (resolveQueueSettings). This fast path only covers sessions that
1131+
// are already in steer/interrupt mode. One-off inline overrides still work correctly via
1132+
// the normal debouncer path — they just don't get the bypass optimization.
1133+
//
1134+
// Use live config (loadConfig) rather than the outer `cfg` snapshot so that
1135+
// runtime queue-mode changes take effect immediately without a restart.
1136+
const liveCfg = telegramDeps.loadConfig();
1137+
const effectiveMode = resolveEffectiveQueueMode({
1138+
cfg: liveCfg,
1139+
channel: "telegram",
1140+
sessionEntry: sessionState.sessionEntry,
1141+
});
1142+
const needsImmediate =
1143+
effectiveMode === "steer" ||
1144+
effectiveMode === "steer-backlog" ||
1145+
effectiveMode === "interrupt";
1146+
// For groups, key by conversation only (shared session).
1147+
// For DMs, include senderId (bridge/business-chat can route different senders differently).
1148+
const cacheSenderId = isGroup ? undefined : senderId;
1149+
const cacheKey = buildChatSessionCacheKey(chatId, conversationThreadId, cacheSenderId);
1150+
chatSessionCache.set(cacheKey, {
1151+
sessionKey: sessionState.sessionKey,
1152+
needsImmediateDelivery: needsImmediate,
1153+
});
1154+
// Evict oldest entries when cache exceeds cap (FIFO via Map insertion order).
1155+
// NOTE: Under very high fan-out (>500 distinct chats), FIFO eviction could remove an
1156+
// active session's entry before its next message arrives. In that case the bypass misses
1157+
// for one message (repopulated on the next). Acceptable for the expected bot scale;
1158+
// an LRU policy would handle this better if fan-out grows significantly.
1159+
if (chatSessionCache.size > CHAT_SESSION_CACHE_MAX) {
1160+
const firstKey = chatSessionCache.keys().next().value;
1161+
if (firstKey !== undefined) {
1162+
chatSessionCache.delete(firstKey);
1163+
}
1164+
}
1165+
1166+
// Fast path: if a run is active and mode needs immediate delivery,
1167+
// bypass the debouncer and process immediately.
1168+
if (needsImmediate && telegramDeps.isRunActiveForSessionKey(sessionState.sessionKey)) {
1169+
const replyMedia = await resolveReplyMediaForMessage(ctx, msg);
1170+
await processMessage(
1171+
ctx,
1172+
allMedia,
1173+
storeAllowFrom,
1174+
{ receivedAtMs: Date.now() },
1175+
replyMedia,
1176+
);
1177+
return;
1178+
}
1179+
} catch (err) {
1180+
// Session resolution failure is non-fatal — fall through to normal debouncer path.
1181+
// Log so misconfiguration or route failures are visible.
1182+
logger.debug(
1183+
`chat session cache: session resolution failed for chat=${chatId}: ${String(err)}`,
1184+
);
1185+
}
1186+
}
1187+
11051188
await inboundDebouncer.enqueue({
11061189
ctx,
11071190
msg,

‎extensions/telegram/src/bot-native-commands.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ export type RegisterTelegramHandlerParams = {
201201
replyMedia?: TelegramMediaRef[],
202202
) => Promise<void>;
203203
logger: ReturnType<typeof getChildLogger>;
204+
/** Chat session cache for per-message sequentializer key resolution. */
205+
chatSessionCache?: Map<string, { sessionKey: string; needsImmediateDelivery: boolean }>;
204206
};
205207

206208
export function buildTelegramNativeCommandCallbackData(commandText: string): string {

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

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,8 @@ const {
4141
useSpy,
4242
} = harness;
4343
const { resolveTelegramFetch } = await import("./fetch.js");
44-
const {
45-
createTelegramBot: createTelegramBotBase,
46-
getTelegramSequentialKey,
47-
setTelegramBotRuntimeForTest,
48-
} = await import("./bot.js");
44+
const { createTelegramBot: createTelegramBotBase, setTelegramBotRuntimeForTest } =
45+
await import("./bot.js");
4946
let createTelegramBot: (
5047
opts: Parameters<typeof import("./bot.js").createTelegramBot>[0],
5148
) => ReturnType<typeof import("./bot.js").createTelegramBot>;
@@ -204,7 +201,9 @@ describe("createTelegramBot", () => {
204201
createTelegramBot({ token: "tok" });
205202
expect(sequentializeSpy).toHaveBeenCalledTimes(1);
206203
expect(middlewareUseSpy).toHaveBeenCalledWith(sequentializeSpy.mock.results[0]?.value);
207-
expect(harness.sequentializeKey).toBe(getTelegramSequentialKey);
204+
// The key function is now wrapped to pass isRunActiveForChat options,
205+
// so we verify it's a function rather than checking reference identity.
206+
expect(typeof harness.sequentializeKey).toBe("function");
208207
});
209208

210209
it("lets /status bypass a busy Telegram topic lane", async () => {

‎extensions/telegram/src/bot.ts‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,16 @@ import { resolveTelegramTransport } from "./fetch.js";
4242
import { tagTelegramNetworkError } from "./network-errors.js";
4343
import { resolveTelegramRequestTimeoutMs } from "./request-timeouts.js";
4444
import { createTelegramSendChatActionHandler } from "./sendchataction-401-backoff.js";
45-
import { getTelegramSequentialKey } from "./sequential-key.js";
45+
import {
46+
buildChatSessionCacheKey,
47+
CHAT_SESSION_CACHE_MAX,
48+
getTelegramSequentialKey,
49+
} from "./sequential-key.js";
4650
import { createTelegramThreadBindingManager } from "./thread-bindings.js";
4751

4852
export type { TelegramBotOptions } from "./bot.types.js";
4953

50-
export { getTelegramSequentialKey };
54+
export { buildChatSessionCacheKey, CHAT_SESSION_CACHE_MAX, getTelegramSequentialKey };
5155

5256
type TelegramBotRuntime = {
5357
Bot: typeof Bot;
@@ -386,7 +390,52 @@ export function createTelegramBot(opts: TelegramBotOptions): TelegramBotInstance
386390
}
387391
});
388392

389-
bot.use(botRuntime.sequentialize(getTelegramSequentialKey));
393+
// Cache chatId:threadId[:senderId] → {sessionKey, needsImmediateDelivery} so the sequential
394+
// key middleware can check whether an embedded Pi run is active and whether the session
395+
// uses a queue mode that needs immediate delivery — without heavy session resolution per update.
396+
//
397+
// NOTE (cache population order): The sequentializer runs BEFORE the handler that populates
398+
// this cache, so the very first message in any chat always gets the default sequential key
399+
// (cache miss). This is correct by design — there can't be an active run to bypass for
400+
// until after at least one message has been handled.
401+
//
402+
// Capped at CHAT_SESSION_CACHE_MAX entries to prevent unbounded memory growth.
403+
const chatSessionCache = new Map<
404+
string,
405+
{ sessionKey: string; needsImmediateDelivery: boolean }
406+
>();
407+
408+
// Capture once to avoid re-reading the getter per update and remove non-null assertions.
409+
const isRunActiveForSessionKey = telegramDeps.isRunActiveForSessionKey;
410+
411+
bot.use(
412+
botRuntime.sequentialize((ctx) =>
413+
getTelegramSequentialKey(ctx, {
414+
isRunActiveForChat: isRunActiveForSessionKey
415+
? (chatId, threadId, senderId) => {
416+
// Try conversation-level key first (groups), then per-sender key (DMs).
417+
const convKey = buildChatSessionCacheKey(chatId, threadId);
418+
const senderKey = senderId
419+
? buildChatSessionCacheKey(chatId, threadId, senderId)
420+
: undefined;
421+
const cached =
422+
chatSessionCache.get(convKey) ??
423+
(senderKey ? chatSessionCache.get(senderKey) : undefined);
424+
if (!cached?.needsImmediateDelivery) {
425+
return false;
426+
}
427+
// When a run is active and mode needs immediate delivery, the sequentializer
428+
// returns a per-message key so multiple messages can race into runReplyAgent
429+
// in parallel. They will each try to abort and recreate the run; the retry
430+
// in agent-runner.ts mitigates the resulting ReplyOperation race, but under
431+
// rapid bursts the last arrival can still hit the user-facing "still shutting
432+
// down" message. This is better than full serialization behind the debouncer.
433+
return isRunActiveForSessionKey(cached.sessionKey);
434+
}
435+
: undefined,
436+
}),
437+
),
438+
);
390439

391440
const rawUpdateLogger = createSubsystemLogger("gateway/channels/telegram/raw-update");
392441
const MAX_RAW_UPDATE_CHARS = 8000;
@@ -618,6 +667,7 @@ export function createTelegramBot(opts: TelegramBotOptions): TelegramBotInstance
618667
processMessage,
619668
logger,
620669
telegramDeps,
670+
chatSessionCache,
621671
});
622672

623673
const originalStop = bot.stop.bind(bot);

0 commit comments

Comments
 (0)