fix: unify telegram thread handling

This commit is contained in:
Ayaan Zaidi
2026-02-02 08:53:42 +05:30
committed by Ayaan Zaidi
parent 5020bfa2a9
commit 19b8416a81
10 changed files with 151 additions and 46 deletions

View File

@@ -51,7 +51,7 @@ import {
describeReplyTarget,
extractTelegramLocation,
hasBotMention,
resolveTelegramForumThreadId,
resolveTelegramThreadSpec,
} from "./bot/helpers.js";
type TelegramMediaRef = {
@@ -158,11 +158,13 @@ export const buildTelegramMessageContext = async ({
const isGroup = msg.chat.type === "group" || msg.chat.type === "supergroup";
const messageThreadId = (msg as { message_thread_id?: number }).message_thread_id;
const isForum = (msg.chat as { is_forum?: boolean }).is_forum === true;
const resolvedThreadId = resolveTelegramForumThreadId({
const threadSpec = resolveTelegramThreadSpec({
isGroup,
isForum,
messageThreadId,
});
const replyThreadId = isGroup ? resolvedThreadId : messageThreadId;
const resolvedThreadId = threadSpec.scope === "forum" ? threadSpec.id : undefined;
const replyThreadId = threadSpec.id;
const { groupConfig, topicConfig } = resolveTelegramGroupConfig(chatId, resolvedThreadId);
const peerId = isGroup ? buildTelegramGroupPeerId(chatId, resolvedThreadId) : String(chatId);
const route = resolveAgentRoute({
@@ -175,8 +177,8 @@ export const buildTelegramMessageContext = async ({
},
});
const baseSessionKey = route.sessionKey;
// DMs: use raw messageThreadId for thread sessions (not resolvedThreadId which is for forums)
const dmThreadId = !isGroup ? messageThreadId : undefined;
// DMs: use raw messageThreadId for thread sessions (not forum topic ids)
const dmThreadId = threadSpec.scope === "dm" ? threadSpec.id : undefined;
const threadKeys =
dmThreadId != null
? resolveThreadSessionKeys({ baseSessionKey, threadId: String(dmThreadId) })
@@ -621,8 +623,8 @@ export const buildTelegramMessageContext = async ({
Sticker: allMedia[0]?.stickerMetadata,
...(locationData ? toLocationContext(locationData) : undefined),
CommandAuthorized: commandAuthorized,
// For groups: use resolvedThreadId (forum topics only); for DMs: use raw messageThreadId
MessageThreadId: isGroup ? resolvedThreadId : messageThreadId,
// For groups: use resolved forum topic id; for DMs: use raw messageThreadId
MessageThreadId: threadSpec.id,
IsForum: isForum,
// Originating channel for reply routing.
OriginatingChannel: "telegram" as const,
@@ -675,6 +677,7 @@ export const buildTelegramMessageContext = async ({
chatId,
isGroup,
resolvedThreadId,
threadSpec,
replyThreadId,
isForum,
historyKey,