Skip to content

Commit 7db2551

Browse files
committed
fix: keep Telegram DM thread IDs on flat sessions
1 parent f727fbc commit 7db2551

15 files changed

Lines changed: 264 additions & 28 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ Docs: https://docs.openclaw.ai
5656
- Control UI/Talk: allow the OpenAI Realtime WebRTC offer endpoint through the Control UI CSP, configure browser sessions with explicit VAD/transcription input settings, and surface OpenAI realtime error/lifecycle events instead of leaving Talk stuck as live with no diagnostic. Fixes #73427.
5757
- Plugins: clarify config-selected duplicate plugin override diagnostics and document manifest schema updates for bundled-plugin forks. Fixes #8582. Thanks @sachah.
5858
- 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.
59-
- 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. Fixes #75975. Thanks @ProjectEvolutionEVE.
59+
- 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.
6060
- 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.
6161
- 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.
6262
- Voice Call: add `sessionScope: "per-call"` for fresh per-call agent memory while preserving the default per-phone caller history. Fixes #45280. Thanks @pondcountry.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
ba41e5775c361dba63fec0441f943106d8cd0cb0f10c10fee36becc1555d5059 config-baseline.json
1+
7d12cd37e835641b78986fa909208e34990a51b0cfe71480ecbd073db4576a0a config-baseline.json
22
7b1716d578d22e5b4388f56140b50d326f61327b760f8c580bdd9b971335fb85 config-baseline.core.json
3-
74632b512b6470a155652c7d15b9e430738a05df3b5a85dca16cc4d84dcea764 config-baseline.channel.json
3+
a2a949a99f5cc5960d4d7ae0159b6b48c4d6b1f813be67cda196457ab2f88034 config-baseline.channel.json
44
fffe0e74eab92a88c3c57952a70bc932438ce3a7f5f9982688437f2cdaee0bcb config-baseline.plugin.json

‎docs/channels/telegram.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ curl "https://api.telegram.org/bot<bot_token>/getUpdates"
260260
- Routing is deterministic: Telegram inbound replies back to Telegram (the model does not pick channels).
261261
- Inbound messages normalize into the shared channel envelope with reply metadata and media placeholders.
262262
- Group sessions are isolated by group ID. Forum topics append `:topic:<threadId>` to keep topics isolated.
263-
- DM messages can carry `message_thread_id`; OpenClaw preserves the thread ID for replies but keeps DMs on the flat session by default. Configure `channels.telegram.direct.<chatId>.threadReplies: "inbound"` or `requireTopic: true` when you intentionally want DM topic session isolation.
263+
- DM messages can carry `message_thread_id`; OpenClaw preserves the thread ID for replies but keeps DMs on the flat session by default. Configure `channels.telegram.dm.threadReplies: "inbound"`, `channels.telegram.direct.<chatId>.threadReplies: "inbound"`, `requireTopic: true`, or a matching topic config when you intentionally want DM topic session isolation.
264264
- Long polling uses grammY runner with per-chat/per-thread sequencing. Overall runner sink concurrency uses `agents.defaults.maxConcurrent`.
265265
- Long polling is guarded inside each gateway process so only one active poller can use a bot token at a time. If you still see `getUpdates` 409 conflicts, another OpenClaw gateway, script, or external poller is likely using the same token.
266266
- Long-polling watchdog restarts trigger after 120 seconds without completed `getUpdates` liveness by default. Increase `channels.telegram.pollingStallThresholdMs` only if your deployment still sees false polling-stall restarts during long-running work. The value is in milliseconds and is allowed from `30000` to `600000`; per-account overrides are supported.
@@ -542,7 +542,7 @@ curl "https://api.telegram.org/bot<bot_token>/getUpdates"
542542

543543
**Thread-bound ACP spawn from chat**: `/acp spawn <agent> --thread here|auto` binds the current topic to a new ACP session; follow-ups route there directly. OpenClaw pins the spawn confirmation in-topic. Requires `channels.telegram.threadBindings.spawnSessions` to remain enabled (default: `true`).
544544

545-
Template context exposes `MessageThreadId` and `IsForum`. DM chats with `message_thread_id` keep DM routing and reply metadata; they only use thread-aware session keys when the DM is configured with `threadReplies: "inbound"`, `threadReplies: "always"`, `requireTopic: true`, or a matching topic config.
545+
Template context exposes `MessageThreadId` and `IsForum`. DM chats with `message_thread_id` keep DM routing and reply metadata on flat sessions by default; they only use thread-aware session keys when configured with `threadReplies: "inbound"`, `threadReplies: "always"`, `requireTopic: true`, or a matching topic config. Use top-level `channels.telegram.dm.threadReplies` for the account default, or `direct.<chatId>.threadReplies` for one DM.
546546

547547
</Accordion>
548548

@@ -941,7 +941,7 @@ Primary reference: [Configuration reference - Telegram](/gateway/config-channels
941941
- access control: `dmPolicy`, `allowFrom`, `groupPolicy`, `groupAllowFrom`, `groups`, `groups.*.topics.*`, top-level `bindings[]` (`type: "acp"`)
942942
- exec approvals: `execApprovals`, `accounts.*.execApprovals`
943943
- command/menu: `commands.native`, `commands.nativeSkills`, `customCommands`
944-
- threading/replies: `replyToMode`
944+
- threading/replies: `replyToMode`, `dm.threadReplies`, `direct.*.threadReplies`
945945
- streaming: `streaming` (preview), `streaming.preview.toolProgress`, `blockStreaming`
946946
- formatting/delivery: `textChunkLimit`, `chunkMode`, `linkPreview`, `responsePrefix`
947947
- media/network: `mediaMaxMb`, `timeoutSeconds`, `pollingStallThresholdMs`, `retry`, `network.autoSelectFamily`, `network.dangerouslyAllowPrivateNetwork`, `proxy`

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

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import {
3434
resolveSessionStoreEntry,
3535
updateSessionStore,
3636
} from "openclaw/plugin-sdk/session-store-runtime";
37-
import { resolveTelegramMediaRuntimeOptions } from "./accounts.js";
37+
import { resolveTelegramAccount, resolveTelegramMediaRuntimeOptions } from "./accounts.js";
3838
import { withTelegramApiErrorLogging } from "./api-logging.js";
3939
import {
4040
isSenderAllowed,
@@ -329,6 +329,12 @@ export const registerTelegramHandlers = ({
329329
const directConfig = !params.isGroup
330330
? (groupConfig as TelegramDirectConfig | undefined)
331331
: undefined;
332+
let accountConfig = telegramCfg;
333+
try {
334+
accountConfig = resolveTelegramAccount({ cfg: runtimeCfg, accountId }).config;
335+
} catch {
336+
// Keep the startup snapshot when live config is temporarily unavailable.
337+
}
332338
const { route } = resolveTelegramConversationRoute({
333339
cfg: runtimeCfg,
334340
accountId,
@@ -346,9 +352,11 @@ export const registerTelegramHandlers = ({
346352
isGroup: params.isGroup,
347353
senderId: params.senderId,
348354
});
349-
const threadKeys = shouldUseTelegramDmThreadSession({ dmThreadId, directConfig, topicConfig })
350-
? resolveThreadSessionKeys({ baseSessionKey, threadId: `${params.chatId}:${dmThreadId}` })
351-
: null;
355+
const threadKeys =
356+
shouldUseTelegramDmThreadSession({ dmThreadId, accountConfig, directConfig, topicConfig }) &&
357+
dmThreadId != null
358+
? resolveThreadSessionKeys({ baseSessionKey, threadId: `${params.chatId}:${dmThreadId}` })
359+
: null;
352360
const sessionKey = threadKeys?.sessionKey ?? baseSessionKey;
353361
const storePath = telegramDeps.resolveStorePath(runtimeCfg.session?.store, {
354362
agentId: route.agentId,

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

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ describe("buildTelegramMessageContext dm thread sessions", () => {
6363
message: Record<string, unknown>,
6464
params?: Pick<
6565
Parameters<typeof buildTelegramMessageContextForTest>[0],
66-
"resolveTelegramGroupConfig"
66+
"cfg" | "resolveTelegramGroupConfig"
6767
>,
6868
) =>
6969
await buildTelegramMessageContextForTest({
@@ -109,6 +109,75 @@ describe("buildTelegramMessageContext dm thread sessions", () => {
109109
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main:thread:1234:42");
110110
});
111111

112+
it("uses thread session key for DM topics when dm.threadReplies is inbound", async () => {
113+
const ctx = await buildContext(
114+
{
115+
message_id: 1,
116+
chat: { id: 1234, type: "private" },
117+
date: 1700000000,
118+
text: "hello",
119+
message_thread_id: 42,
120+
from: { id: 42, first_name: "Alice" },
121+
},
122+
{
123+
cfg: {
124+
agents: {
125+
defaults: { model: "anthropic/claude-opus-4-5", workspace: "/tmp/openclaw" },
126+
},
127+
channels: {
128+
telegram: {
129+
dmPolicy: "open",
130+
allowFrom: ["*"],
131+
dm: { threadReplies: "inbound" },
132+
},
133+
},
134+
messages: { groupChat: { mentionPatterns: [] } },
135+
},
136+
},
137+
);
138+
139+
expect(ctx).not.toBeNull();
140+
expect(ctx?.ctxPayload?.MessageThreadId).toBe(42);
141+
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main:thread:1234:42");
142+
});
143+
144+
it("lets direct chat config opt one DM back into thread session keys", async () => {
145+
const cfg = {
146+
agents: { defaults: { model: "anthropic/claude-opus-4-5", workspace: "/tmp/openclaw" } },
147+
channels: {
148+
telegram: {
149+
dmPolicy: "open",
150+
allowFrom: ["*"],
151+
direct: {
152+
"1234": {
153+
threadReplies: "inbound",
154+
},
155+
},
156+
},
157+
},
158+
messages: { groupChat: { mentionPatterns: [] } },
159+
};
160+
const ctx = await buildTelegramMessageContextForTest({
161+
cfg,
162+
message: {
163+
message_id: 1,
164+
chat: { id: 1234, type: "private" },
165+
date: 1700000000,
166+
text: "hello",
167+
message_thread_id: 42,
168+
from: { id: 42, first_name: "Alice" },
169+
},
170+
resolveTelegramGroupConfig: () => ({
171+
groupConfig: { threadReplies: "inbound" },
172+
topicConfig: undefined,
173+
}),
174+
});
175+
176+
expect(ctx).not.toBeNull();
177+
expect(ctx?.ctxPayload?.MessageThreadId).toBe(42);
178+
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main:thread:1234:42");
179+
});
180+
112181
it("uses the main session key when no thread id", async () => {
113182
const ctx = await buildContext({
114183
message_id: 2,

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

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import type { TelegramDirectConfig, TelegramGroupConfig } from "openclaw/plugin-
88
import { deriveLastRoutePolicy } from "openclaw/plugin-sdk/routing";
99
import { normalizeAccountId, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
1010
import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
11-
import { resolveDefaultTelegramAccountId } from "./accounts.js";
11+
import { mergeTelegramAccountConfig, resolveDefaultTelegramAccountId } from "./accounts.js";
1212
import { withTelegramApiErrorLogging } from "./api-logging.js";
1313
import { firstDefined, normalizeAllowFrom, normalizeDmAllowFromWithStore } from "./bot-access.js";
1414
import { resolveTelegramInboundBody } from "./bot-message-context.body.js";
@@ -225,6 +225,7 @@ export const buildTelegramMessageContext = async ({
225225
const freshCfg =
226226
loadFreshConfig?.() ??
227227
(runtime?.getRuntimeConfig ?? (await loadTelegramMessageContextRuntime()).getRuntimeConfig)();
228+
const telegramCfg = mergeTelegramAccountConfig(freshCfg, account.accountId);
228229
let { route, configuredBinding, configuredBindingSessionKey } = resolveTelegramConversationRoute({
229230
cfg: freshCfg,
230231
accountId: account.accountId,
@@ -384,12 +385,14 @@ export const buildTelegramMessageContext = async ({
384385
});
385386
const useDmThreadSession = shouldUseTelegramDmThreadSession({
386387
dmThreadId,
388+
accountConfig: telegramCfg,
387389
directConfig,
388390
topicConfig,
389391
});
390-
const threadKeys = useDmThreadSession
391-
? resolveThreadSessionKeys({ baseSessionKey, threadId: `${chatId}:${dmThreadId}` })
392-
: null;
392+
const threadKeys =
393+
useDmThreadSession && dmThreadId != null
394+
? resolveThreadSessionKeys({ baseSessionKey, threadId: `${chatId}:${dmThreadId}` })
395+
: null;
393396
const sessionKey = threadKeys?.sessionKey ?? baseSessionKey;
394397
route = {
395398
...route,

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

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -888,16 +888,21 @@ export const registerTelegramNativeCommands = ({
888888
senderId,
889889
});
890890
const dmThreadId = threadSpec.scope === "dm" ? threadSpec.id : undefined;
891-
const threadKeys = shouldUseTelegramDmThreadSession({
892-
dmThreadId,
893-
directConfig: !isGroup ? (groupConfig as TelegramDirectConfig | undefined) : undefined,
894-
topicConfig,
895-
})
896-
? (await resolveNativeCommandRuntime()).resolveThreadSessionKeys({
897-
baseSessionKey,
898-
threadId: `${chatId}:${dmThreadId}`,
899-
})
900-
: null;
891+
const directConfig = !isGroup
892+
? (groupConfig as TelegramDirectConfig | undefined)
893+
: undefined;
894+
const threadKeys =
895+
shouldUseTelegramDmThreadSession({
896+
dmThreadId,
897+
accountConfig: runtimeTelegramCfg,
898+
directConfig,
899+
topicConfig,
900+
}) && dmThreadId != null
901+
? (await resolveNativeCommandRuntime()).resolveThreadSessionKeys({
902+
baseSessionKey,
903+
threadId: `${chatId}:${dmThreadId}`,
904+
})
905+
: null;
901906
cachedTargetSessionKey = threadKeys?.sessionKey ?? baseSessionKey;
902907
return cachedTargetSessionKey;
903908
};

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import type { Chat, Message } from "@grammyjs/types";
22
import { formatLocationText } from "openclaw/plugin-sdk/channel-inbound";
33
import type {
4+
TelegramAccountConfig,
45
TelegramDirectConfig,
56
TelegramGroupConfig,
7+
TelegramDmThreadReplies,
68
TelegramTopicConfig,
79
} from "openclaw/plugin-sdk/config-types";
810
import { readChannelAllowFromStore } from "openclaw/plugin-sdk/conversation-runtime";
@@ -75,6 +77,36 @@ export type TelegramThreadSpec = {
7577
scope: "dm" | "forum" | "none";
7678
};
7779

80+
function normalizeTelegramDmThreadReplies(value: unknown): TelegramDmThreadReplies | undefined {
81+
return value === "off" || value === "inbound" || value === "always" ? value : undefined;
82+
}
83+
84+
export function resolveTelegramDmThreadReplies(params: {
85+
accountConfig?: TelegramAccountConfig;
86+
directConfig?: TelegramDirectConfig;
87+
}): TelegramDmThreadReplies {
88+
return (
89+
normalizeTelegramDmThreadReplies(params.directConfig?.threadReplies) ??
90+
normalizeTelegramDmThreadReplies(params.accountConfig?.dm?.threadReplies) ??
91+
"off"
92+
);
93+
}
94+
95+
export function shouldUseTelegramDmThreadSession(params: {
96+
dmThreadId?: number;
97+
accountConfig?: TelegramAccountConfig;
98+
directConfig?: TelegramDirectConfig;
99+
topicConfig?: TelegramTopicConfig;
100+
}): boolean {
101+
if (params.dmThreadId == null) {
102+
return false;
103+
}
104+
if (params.directConfig?.requireTopic === true || params.topicConfig) {
105+
return true;
106+
}
107+
return resolveTelegramDmThreadReplies(params) !== "off";
108+
}
109+
78110
export function extractTelegramForumFlag(value: unknown): boolean | undefined {
79111
if (!value || typeof value !== "object" || !("is_forum" in value)) {
80112
return undefined;

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

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

69+
it("accepts DM thread reply policy overrides", () => {
70+
const res = TelegramConfigSchema.safeParse({
71+
dm: { threadReplies: "off" },
72+
direct: {
73+
"123456789": {
74+
threadReplies: "inbound",
75+
},
76+
},
77+
accounts: {
78+
ops: {
79+
dm: { threadReplies: "always" },
80+
},
81+
},
82+
});
83+
84+
expect(res.success).toBe(true);
85+
if (res.success) {
86+
expect(res.data.dm?.threadReplies).toBe("off");
87+
expect(res.data.direct?.["123456789"]?.threadReplies).toBe("inbound");
88+
expect(res.data.accounts?.ops?.dm?.threadReplies).toBe("always");
89+
}
90+
});
91+
92+
it("rejects unknown DM thread reply policy values", () => {
93+
expectTelegramConfigIssue({ dm: { threadReplies: "first" } }, "dm.threadReplies");
94+
expectTelegramConfigIssue(
95+
{
96+
direct: {
97+
"123456789": {
98+
threadReplies: "first",
99+
},
100+
},
101+
},
102+
"direct.123456789.threadReplies",
103+
);
104+
});
105+
69106
it("rejects pollingStallThresholdMs outside the watchdog bounds", () => {
70107
expectTelegramConfigIssue({ pollingStallThresholdMs: 29_999 }, "pollingStallThresholdMs");
71108
expectTelegramConfigIssue({ pollingStallThresholdMs: 600_001 }, "pollingStallThresholdMs");

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ export const telegramChannelConfigUiHints = {
1717
label: "Telegram DM Policy",
1818
help: 'Direct message access control ("pairing" recommended). "open" requires channels.telegram.allowFrom=["*"].',
1919
},
20+
"dm.threadReplies": {
21+
label: "Telegram DM Thread Replies",
22+
help: 'Controls whether Telegram DMs with message_thread_id use flat sessions ("off", default) or thread-scoped sessions ("inbound" or "always"). Thread IDs are still preserved for replies when sessions stay flat.',
23+
},
24+
"direct.*.threadReplies": {
25+
label: "Telegram Per-DM Thread Replies",
26+
help: 'Per-DM override for message_thread_id session threading. Use "inbound" only when a specific direct chat intentionally uses Telegram DM topics as separate sessions.',
27+
},
2028
configWrites: {
2129
label: "Telegram Config Writes",
2230
help: "Allow Telegram to write config in response to channel events/commands (default: true).",

0 commit comments

Comments
 (0)