Skip to content

Commit af3b860

Browse files
authored
fix(telegram): preserve direct-message topic routing (#126207)
* fix(telegram): preserve direct message topic identity * fix(telegram): break topic routing import cycle
1 parent 41009e7 commit af3b860

43 files changed

Lines changed: 527 additions & 366 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎extensions/telegram/src/bot-handlers.callback-actions.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { Message } from "grammy/types";
22
import { questionGatewayRuntime } from "openclaw/plugin-sdk/question-gateway-runtime";
33
import type { RegisterTelegramHandlerParams } from "./bot-handlers.types.js";
4-
import { buildTelegramThreadParams, resolveTelegramMessageThreadSpec } from "./bot/helpers.js";
4+
import { buildTelegramThreadParams, type TelegramThreadSpec } from "./bot/helpers.js";
55
import type { TelegramQuestionCallback } from "./question-callback-data.js";
66
import { buildInlineKeyboard } from "./send.js";
77

@@ -44,9 +44,9 @@ export interface TelegramCallbackMessageActions {
4444
export function createTelegramCallbackMessageActions(params: {
4545
bot: RegisterTelegramHandlerParams["bot"];
4646
callbackMessage: Message;
47-
isForum: boolean;
47+
threadSpec: TelegramThreadSpec;
4848
}): TelegramCallbackMessageActions {
49-
const { bot, callbackMessage, isForum } = params;
49+
const { bot, callbackMessage, threadSpec } = params;
5050
const callbackBusinessParams =
5151
callbackMessage.business_connection_id !== undefined
5252
? { business_connection_id: callbackMessage.business_connection_id }
@@ -89,9 +89,7 @@ export function createTelegramCallbackMessageActions(params: {
8989
};
9090

9191
const replyToCallbackChat = async (text: string, replyParams?: TelegramCallbackReplyParams) => {
92-
const threadParams = buildTelegramThreadParams(
93-
resolveTelegramMessageThreadSpec(callbackMessage, isForum),
94-
);
92+
const threadParams = buildTelegramThreadParams(threadSpec);
9593
const mergedParams =
9694
callbackBusinessParams || threadParams || replyParams
9795
? { ...replyParams, ...callbackBusinessParams, ...threadParams }

‎extensions/telegram/src/bot-handlers.callback-router.ts‎

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import {
6767
parseTelegramQuestionCallbackData,
6868
} from "./question-callback-data.js";
6969
import { buildInlineKeyboard } from "./send.js";
70+
import { buildTelegramConversationId } from "./topic-conversation.js";
7071

7172
export function createTelegramCallbackRouter({
7273
params: {
@@ -175,7 +176,6 @@ export function createTelegramCallbackRouter({
175176
return;
176177
}
177178

178-
const messageThreadId = callbackMessage.message_thread_id;
179179
const isForum = await resolveTelegramForumFlag({
180180
chatId,
181181
chatType: callbackMessage.chat.type,
@@ -193,7 +193,8 @@ export function createTelegramCallbackRouter({
193193
senderId,
194194
threadSpec: resolveTelegramMessageThreadSpec(callbackMessage, isForum),
195195
});
196-
const { resolvedThreadId, dmThreadId, storeAllowFrom, groupConfig } = eventAuthContext;
196+
const threadSpec = eventAuthContext.threadSpec;
197+
const { dmThreadId, storeAllowFrom, groupConfig } = eventAuthContext;
197198
const requireTopic = (groupConfig as { requireTopic?: boolean } | undefined)?.requireTopic;
198199
if (!isGroup && requireTopic === true && dmThreadId == null) {
199200
logVerbose(
@@ -204,7 +205,7 @@ export function createTelegramCallbackRouter({
204205
const actions = createTelegramCallbackMessageActions({
205206
bot,
206207
callbackMessage,
207-
isForum,
208+
threadSpec,
208209
});
209210
const clearRoutedCallbackButtons = async () => {
210211
try {
@@ -262,9 +263,8 @@ export function createTelegramCallbackRouter({
262263
return;
263264
}
264265

265-
const callbackThreadId = resolvedThreadId ?? dmThreadId;
266-
const callbackConversationId =
267-
callbackThreadId != null ? `${chatId}:topic:${callbackThreadId}` : String(chatId);
266+
const callbackConversationId = buildTelegramConversationId({ chatId, thread: threadSpec });
267+
const callbackThreadId = threadSpec.id;
268268
const runtimeCfg = telegramDeps.getRuntimeConfig();
269269
const approvalRuntime = createTelegramCallbackApprovalRuntime({
270270
accountId,
@@ -344,9 +344,7 @@ export function createTelegramCallbackRouter({
344344
ctx,
345345
chatId,
346346
isGroup,
347-
isForum,
348-
messageThreadId,
349-
resolvedThreadId,
347+
threadSpec,
350348
senderId,
351349
runtimeCfg,
352350
telegramDeps,
@@ -375,6 +373,7 @@ export function createTelegramCallbackRouter({
375373
allMedia: [],
376374
storeAllowFrom,
377375
options: {
376+
threadSpec,
378377
...(nativeCallbackCommand ? { commandSource: "native" as const } : {}),
379378
forceWasMentioned: true,
380379
messageIdOverride: callback.id,
@@ -416,9 +415,7 @@ async function handleTelegramModelCallback(params: {
416415
ctx: Pick<TelegramContext, "me">;
417416
chatId: number;
418417
isGroup: boolean;
419-
isForum: boolean;
420-
messageThreadId?: number;
421-
resolvedThreadId?: number;
418+
threadSpec: ReturnType<typeof resolveTelegramMessageThreadSpec>;
422419
senderId: string;
423420
runtimeCfg: OpenClawConfig;
424421
telegramDeps: RegisterTelegramHandlerParams["telegramDeps"];
@@ -431,9 +428,7 @@ async function handleTelegramModelCallback(params: {
431428
ctx,
432429
chatId,
433430
isGroup,
434-
isForum,
435-
messageThreadId,
436-
resolvedThreadId,
431+
threadSpec,
437432
senderId,
438433
runtimeCfg,
439434
telegramDeps,
@@ -465,9 +460,7 @@ async function handleTelegramModelCallback(params: {
465460
messageRuntime.resolveTelegramSessionState({
466461
chatId,
467462
isGroup,
468-
isForum,
469-
messageThreadId,
470-
resolvedThreadId,
463+
threadSpec,
471464
botHasTopicsEnabled: resolveTelegramBotHasTopicsEnabled(ctx.me),
472465
senderId,
473466
runtimeCfg,
@@ -514,9 +507,7 @@ async function handleTelegramModelCallback(params: {
514507
const session = messageRuntime.resolveTelegramSessionState({
515508
chatId,
516509
isGroup,
517-
isForum,
518-
messageThreadId,
519-
resolvedThreadId,
510+
threadSpec,
520511
botHasTopicsEnabled: resolveTelegramBotHasTopicsEnabled(ctx.me),
521512
senderId,
522513
runtimeCfg,

‎extensions/telegram/src/bot-handlers.debounce-key.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Telegram plugin module implements bot handlersebounce key behavior.
2+
import { buildTelegramGroupPeerId, type TelegramThreadSpec } from "./bot/helpers.js";
23
export function buildTelegramInboundDebounceKey(params: {
34
accountId?: string | null;
45
conversationKey: string;
@@ -11,9 +12,7 @@ export function buildTelegramInboundDebounceKey(params: {
1112

1213
export function buildTelegramInboundDebounceConversationKey(params: {
1314
chatId: number | string;
14-
threadId?: number | null;
15+
threadSpec: TelegramThreadSpec;
1516
}): string {
16-
return params.threadId != null
17-
? `${params.chatId}:topic:${params.threadId}`
18-
: String(params.chatId);
17+
return buildTelegramGroupPeerId(params.chatId, params.threadSpec);
1918
}

‎extensions/telegram/src/bot-handlers.event-bindings.ts‎

Lines changed: 10 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import type { ChatMember, ReactionTypeEmoji } from "grammy/types";
22
import { resolveChannelConfigWrites } from "openclaw/plugin-sdk/channel-config-helpers";
33
import { mutateConfigFile } from "openclaw/plugin-sdk/config-mutation";
4-
import { resolveAgentRoute } from "openclaw/plugin-sdk/routing";
54
import { danger, logVerbose, warn } from "openclaw/plugin-sdk/runtime-env";
65
import { resolveTelegramAccount } from "./accounts.js";
76
import type { TelegramHandlerAuthorization } from "./bot-handlers.inbound-authorization.js";
@@ -11,12 +10,7 @@ import {
1110
isTelegramSpooledReplayUpdate,
1211
recordTelegramMessageProcessingResult,
1312
} from "./bot-processing-outcome.js";
14-
import {
15-
buildTelegramGroupPeerId,
16-
buildTelegramParentPeer,
17-
resolveTelegramThreadSpec,
18-
type TelegramThreadSpec,
19-
} from "./bot/helpers.js";
13+
import { resolveTelegramThreadSpec, type TelegramThreadSpec } from "./bot/helpers.js";
2014
import { resolveTelegramConversationRoute } from "./conversation-route.js";
2115
import { migrateTelegramGroupConfig } from "./group-migration.js";
2216
import { getPreparedTelegramPollAnswer } from "./poll-answer-context.js";
@@ -180,34 +174,15 @@ export function createTelegramEventBindings({
180174
}
181175
}
182176

183-
const resolvedThreadId = eventAuthContext.resolvedThreadId;
184-
let sessionKey: string;
185-
if (recoveredThreadSpec) {
186-
// Scoped topics must retain topic agents and conversation bindings.
187-
sessionKey = resolveTelegramConversationRoute({
188-
cfg: eventAuthContext.cfg,
189-
accountId,
190-
chatId,
191-
isGroup,
192-
resolvedThreadId,
193-
replyThreadId: recoveredThreadSpec.id,
194-
senderId,
195-
topicAgentId: eventAuthContext.topicConfig?.agentId,
196-
}).route.sessionKey;
197-
} else {
198-
// Direct chats and non-forum groups retain their established peer route.
199-
const peerId = isGroup
200-
? buildTelegramGroupPeerId(chatId, resolvedThreadId)
201-
: String(chatId);
202-
const parentPeer = buildTelegramParentPeer({ isGroup, resolvedThreadId, chatId });
203-
sessionKey = resolveAgentRoute({
204-
cfg: eventAuthContext.cfg,
205-
channel: "telegram",
206-
accountId,
207-
peer: { kind: isGroup ? "group" : "direct", id: peerId },
208-
parentPeer,
209-
}).sessionKey;
210-
}
177+
const sessionKey = resolveTelegramConversationRoute({
178+
cfg: eventAuthContext.cfg,
179+
accountId,
180+
chatId,
181+
isGroup,
182+
threadSpec: recoveredThreadSpec ?? eventAuthContext.threadSpec,
183+
senderId,
184+
topicAgentId: eventAuthContext.topicConfig?.agentId,
185+
}).route.sessionKey;
211186

212187
const senderName = user
213188
? [user.first_name, user.last_name].filter(Boolean).join(" ").trim() || user.username

‎extensions/telegram/src/bot-handlers.inbound-authorization.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ export function createTelegramHandlerAuthorization({
301301
accountId,
302302
chatId,
303303
isGroup,
304-
resolvedThreadId: context.resolvedThreadId,
304+
threadSpec: context.threadSpec,
305305
senderId,
306306
senderUsername,
307307
}).isAuthorizedSender;

‎extensions/telegram/src/bot-handlers.inbound-buffer.provenance.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ describe("Telegram inbound provenance buffering", () => {
7272
receivedAtMs: index + 1,
7373
debounceKey: "telegram:default:42:42:default",
7474
debounceLane: "default",
75+
threadSpec: { scope: "none" },
7576
dispatchDedupeClaims: [],
7677
channelIngressResolvers: [channelIngressResolver],
7778
});

‎extensions/telegram/src/bot-handlers.inbound-buffer.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
buildTelegramThreadParams,
2020
getTelegramTextParts,
2121
joinTelegramTextParts,
22-
resolveTelegramMessageThreadSpec,
22+
type TelegramThreadSpec,
2323
} from "./bot/helpers.js";
2424
import type { TelegramContext } from "./bot/types.js";
2525
import type { TelegramMessageDispatchReplayClaim } from "./message-dispatch-dedupe.js";
@@ -35,7 +35,7 @@ export type TelegramDebounceEntry = {
3535
debounceKey: string | null;
3636
debounceLane: TelegramDebounceLane;
3737
botUsername?: string;
38-
threadId?: number;
38+
threadSpec: TelegramThreadSpec;
3939
promptContextMinTimestampMs?: number;
4040
promptContextAmbientWatermark?: TelegramAmbientTranscriptWatermark;
4141
dispatchDedupeClaims: TelegramMessageDispatchReplayClaim[];
@@ -47,6 +47,7 @@ type TextFragmentEntry = {
4747
key: string;
4848
storeAllowFrom: string[];
4949
messages: Array<{ msg: Message; ctx: TelegramContext; receivedAtMs: number }>;
50+
threadSpec: TelegramThreadSpec;
5051
promptContextMinTimestampMs?: number;
5152
promptContextAmbientWatermark?: TelegramAmbientTranscriptWatermark;
5253
dispatchDedupeClaims: TelegramMessageDispatchReplayClaim[];
@@ -59,8 +60,7 @@ type TelegramTextFragmentInput = {
5960
ctx: TelegramContext;
6061
msg: Message;
6162
chatId: number;
62-
resolvedThreadId?: number;
63-
dmThreadId?: number;
63+
threadSpec: TelegramThreadSpec;
6464
storeAllowFrom: string[];
6565
isAbortControlMessage: boolean;
6666
isAuthorizedAbortControlMessage: () => Promise<boolean>;
@@ -164,6 +164,7 @@ export function createTelegramInboundBuffers({
164164
options: {
165165
receivedAtMs: last.receivedAtMs,
166166
ingressBuffer: "inbound-debounce",
167+
threadSpec: last.threadSpec,
167168
...promptContextBoundaryOptions(
168169
last.promptContextMinTimestampMs,
169170
last.promptContextAmbientWatermark,
@@ -212,6 +213,7 @@ export function createTelegramInboundBuffers({
212213
),
213214
receivedAtMs: first.receivedAtMs,
214215
ingressBuffer: "inbound-debounce",
216+
threadSpec: first.threadSpec,
215217
bufferedMessages: entries.map((entry) => entry.msg),
216218
...promptContextBoundaryOptions(
217219
latestPromptContextMinTimestampMs(
@@ -253,10 +255,7 @@ export function createTelegramInboundBuffers({
253255
}
254256
const chatId = items[0]?.msg.chat.id;
255257
if (chatId != null) {
256-
const firstMessage = items[0]?.msg;
257-
const threadParams = firstMessage
258-
? buildTelegramThreadParams(resolveTelegramMessageThreadSpec(firstMessage))
259-
: undefined;
258+
const threadParams = buildTelegramThreadParams(items[0]?.threadSpec);
260259
void bot.api
261260
.sendMessage(
262261
chatId,
@@ -326,6 +325,7 @@ export function createTelegramInboundBuffers({
326325
ambientTranscriptBody: formatTelegramAmbientTranscriptBody(bufferedMessages),
327326
receivedAtMs: first.receivedAtMs,
328327
ingressBuffer: "text-fragment",
328+
threadSpec: entry.threadSpec,
329329
bufferedMessages,
330330
...promptContextBoundaryOptions(
331331
entry.promptContextMinTimestampMs,
@@ -366,8 +366,7 @@ export function createTelegramInboundBuffers({
366366
(entity) => entity.type === "bot_command" && entity.offset === 0,
367367
);
368368
const senderId = params.msg.from?.id != null ? String(params.msg.from.id) : "unknown";
369-
const threadId = params.resolvedThreadId ?? params.dmThreadId;
370-
const key = `text:${params.chatId}:${threadId ?? "main"}:${senderId}`;
369+
const key = `text:${params.chatId}:${params.threadSpec.scope}:${params.threadSpec.id ?? "main"}:${senderId}`;
371370
if (text && !isCommand && !params.isAbortControlMessage) {
372371
const nowMs = Date.now();
373372
const existing = textBuffer.get(key);
@@ -416,6 +415,7 @@ export function createTelegramInboundBuffers({
416415
const entry: TextFragmentEntry = {
417416
key,
418417
storeAllowFrom: params.storeAllowFrom,
418+
threadSpec: params.threadSpec,
419419
messages: [{ msg: params.msg, ctx: params.ctx, receivedAtMs: nowMs }],
420420
dispatchDedupeClaims: params.dispatchDedupeClaims,
421421
spooledReplayParticipants: participant ? [participant] : [],

0 commit comments

Comments
 (0)