Files
openclaw/extensions/telegram/src/bot-message-context.dm-threads.test.ts
Peter Steinberger af3b86091f fix(telegram): preserve direct-message topic routing (#126207)
* fix(telegram): preserve direct message topic identity

* fix(telegram): break topic routing import cycle
2026-08-19 18:00:56 -07:00

526 lines
18 KiB
TypeScript

// Telegram tests cover bot message contextm threads plugin behavior.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resetTelegramTopicNameCacheForTest as resetTopicNameCacheForTest } from "./runtime.test-support.js";
type ResolveTelegramInboundBody =
typeof import("./bot-message-context.body.js").resolveTelegramInboundBody;
type TelegramInboundBodyResult = NonNullable<Awaited<ReturnType<ResolveTelegramInboundBody>>>;
type SessionRuntimeModule = typeof import("./bot-message-context.session.runtime.js");
type RecordInboundSessionFn = SessionRuntimeModule["recordInboundSession"];
type ResolveStorePathFn = SessionRuntimeModule["resolveStorePath"];
const { inboundBodyResult, recordInboundSessionMock, resolveStorePathMock } = vi.hoisted(() => {
const createInboundBodyResult = (): TelegramInboundBodyResult => ({
bodyText: "hello",
rawBody: "hello",
historyKey: undefined,
commandAuthorized: false,
effectiveWasMentioned: true,
inboundEventKind: "user_request" as const,
mentionFacts: {
canDetectMention: false,
wasMentioned: true,
explicitlyMentionedBot: false,
effectiveWasMentioned: true,
requireMention: false,
},
canDetectMention: false,
shouldBypassMention: false,
hasControlCommand: false,
stickerCacheHit: false,
locationData: undefined,
});
return {
inboundBodyResult: { value: createInboundBodyResult(), reset: createInboundBodyResult },
recordInboundSessionMock: vi.fn<RecordInboundSessionFn>(async () => undefined),
resolveStorePathMock: vi.fn<ResolveStorePathFn>(),
};
});
vi.mock("./bot-message-context.session.runtime.js", async () => {
const actual = await vi.importActual<typeof import("./bot-message-context.session.runtime.js")>(
"./bot-message-context.session.runtime.js",
);
return {
...actual,
recordInboundSession: (...args: Parameters<typeof actual.recordInboundSession>) =>
recordInboundSessionMock(...args),
resolveStorePath: (...args: Parameters<typeof actual.resolveStorePath>) =>
resolveStorePathMock(...args),
};
});
vi.mock("./bot-message-context.body.js", () => ({
resolveTelegramInboundBody: async () => inboundBodyResult.value,
}));
const { buildTelegramMessageContextForTest } =
await import("./bot-message-context.test-harness.js");
const { clearRuntimeConfigSnapshot, setRuntimeConfigSnapshot } =
await import("openclaw/plugin-sdk/runtime-config-snapshot");
let defaultSessionStoreRoot = "";
beforeEach(async () => {
defaultSessionStoreRoot = await fs.mkdtemp(
path.join(os.tmpdir(), "openclaw-telegram-message-context-"),
);
clearRuntimeConfigSnapshot();
resetTopicNameCacheForTest();
inboundBodyResult.value = inboundBodyResult.reset();
resolveStorePathMock.mockReturnValue(path.join(defaultSessionStoreRoot, "sessions.json"));
});
afterEach(async () => {
clearRuntimeConfigSnapshot();
resetTopicNameCacheForTest();
recordInboundSessionMock.mockClear();
resolveStorePathMock.mockReset();
await fs.rm(defaultSessionStoreRoot, { recursive: true, force: true });
});
describe("buildTelegramMessageContext dm thread sessions", () => {
const buildContext = async (
message: Record<string, unknown>,
params?: Pick<
Parameters<typeof buildTelegramMessageContextForTest>[0],
"cfg" | "me" | "resolveTelegramGroupConfig" | "sendChatActionHandler"
>,
) =>
await buildTelegramMessageContextForTest({
message,
...params,
});
const dmThreadMessage = {
message_id: 1,
chat: { id: 1234, type: "private" },
date: 1700000000,
text: "hello",
message_thread_id: 42,
from: { id: 42, first_name: "Alice" },
};
it("keeps DM message_thread_id on the main session when bot topics are absent", async () => {
const ctx = await buildContext(dmThreadMessage);
expect(ctx?.ctxPayload?.MessageThreadId).toBe(42);
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main");
});
it("keeps DM message_thread_id on the main session when bot topics are disabled", async () => {
const ctx = await buildContext(dmThreadMessage, {
me: { has_topics_enabled: false },
});
expect(ctx?.ctxPayload?.MessageThreadId).toBe(42);
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main");
});
it("uses thread session key when Telegram reports bot topics enabled", async () => {
const ctx = await buildContext(dmThreadMessage, {
me: { has_topics_enabled: true },
});
expect(ctx?.ctxPayload?.MessageThreadId).toBe(42);
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main:thread:1234:42");
});
it("does not use configured bot-private topics without bot topic capability", async () => {
const ctx = await buildContext(
{
...dmThreadMessage,
message_id: 3,
date: 1700000002,
},
{
resolveTelegramGroupConfig: () => ({
groupConfig: { requireTopic: true },
topicConfig: { agentId: "support" },
}),
},
);
expect(ctx?.ctxPayload?.MessageThreadId).toBe(42);
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:support:main");
});
it("uses configured bot-private topic routing once bot topic capability is present", async () => {
const ctx = await buildContext(
{
...dmThreadMessage,
message_id: 4,
date: 1700000003,
},
{
me: { has_topics_enabled: true },
resolveTelegramGroupConfig: () => ({
groupConfig: { requireTopic: true },
topicConfig: { agentId: "support" },
}),
},
);
expect(ctx?.ctxPayload?.MessageThreadId).toBe(42);
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:support:main:thread:1234:42");
});
it("uses the main session key when no thread id", async () => {
const ctx = await buildContext({
message_id: 1,
chat: { id: 1234, type: "private" },
date: 1700000000,
text: "hello",
from: { id: 42, first_name: "Alice" },
});
expect(ctx?.ctxPayload?.MessageThreadId).toBeUndefined();
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:main");
});
});
describe("buildTelegramMessageContext group sessions without forum", () => {
const buildContext = async (
message: Record<string, unknown>,
params?: Pick<
Parameters<typeof buildTelegramMessageContextForTest>[0],
"sendChatActionHandler"
>,
) =>
await buildTelegramMessageContextForTest({
message,
options: { forceWasMentioned: true },
resolveGroupActivation: () => true,
...params,
});
it("ignores message_thread_id for regular groups (not forums)", async () => {
// When someone replies to a message in a non-forum group, Telegram sends
// message_thread_id but this should NOT create a separate session
const ctx = await buildContext({
message_id: 1,
chat: { id: -1001234567890, type: "supergroup", title: "Test Group" },
date: 1700000000,
text: "@bot hello",
message_thread_id: 42, // This is a reply thread, NOT a forum topic
from: { id: 42, first_name: "Alice" },
});
if (!ctx) {
throw new Error("expected Telegram non-forum group context");
}
// Session key should NOT include :topic:42
expect(ctx.ctxPayload.SessionKey).toBe("agent:main:telegram:group:-1001234567890");
// MessageThreadId should be undefined (not a forum)
expect(ctx.ctxPayload.MessageThreadId).toBeUndefined();
});
it("round-trips channel Direct Messages topics with their distinct target marker", async () => {
const sendChatAction = vi.fn(async () => undefined);
const ctx = await buildContext(
{
message_id: 8,
chat: {
id: -1001234567890,
type: "supergroup",
title: "Channel Direct Messages",
is_direct_messages: true,
},
date: 1700000007,
text: "@bot hello",
message_thread_id: 999,
direct_messages_topic: {
topic_id: 77,
user: { id: 700, is_bot: false, first_name: "Subscriber" },
},
from: { id: 700, first_name: "Subscriber" },
},
{
sendChatActionHandler: {
sendChatAction,
isSuspended: () => false,
reset: () => {},
},
},
);
expect(ctx?.ctxPayload.MessageThreadId).toBe(77);
expect(ctx?.ctxPayload.OriginatingTo).toBe("telegram:-1001234567890:direct-topic:77");
expect(ctx?.ctxPayload.From).toBe("telegram:group:-1001234567890:direct-topic:77");
expect(ctx?.ctxPayload.SessionKey).toBe(
"agent:main:telegram:group:-1001234567890:direct-topic:77",
);
expect(ctx?.turn.record.updateLastRoute).toMatchObject({
to: "telegram:-1001234567890:direct-topic:77",
threadId: "77",
});
expect(sendChatAction).not.toHaveBeenCalled();
});
it("carries the body-layer inbound event kind instead of restamping from copied mention booleans", async () => {
inboundBodyResult.value = {
...inboundBodyResult.reset(),
effectiveWasMentioned: false,
inboundEventKind: "user_request",
mentionFacts: {
canDetectMention: true,
wasMentioned: true,
explicitlyMentionedBot: true,
mentionSource: "explicit_bot",
effectiveWasMentioned: true,
requireMention: false,
},
};
const ctx = await buildTelegramMessageContextForTest({
cfg: { messages: { groupChat: { unmentionedInbound: "room_event", mentionPatterns: [] } } },
message: {
message_id: 7,
chat: { id: -1001234567890, type: "supergroup", title: "Test Group" },
date: 1700000000,
text: "@bot hello",
entities: [{ type: "mention", offset: 0, length: "@bot".length }],
from: { id: 42, first_name: "Alice" },
},
resolveGroupActivation: () => false,
resolveGroupRequireMention: () => false,
});
expect(ctx?.ctxPayload.InboundEventKind).toBe("user_request");
expect(ctx?.ctxPayload.ExplicitlyMentionedBot).toBe(true);
});
it("keeps same session for regular group with and without message_thread_id", async () => {
const ctxWithThread = await buildContext({
message_id: 1,
chat: { id: -1001234567890, type: "supergroup", title: "Test Group" },
date: 1700000000,
text: "@bot hello",
message_thread_id: 42,
from: { id: 42, first_name: "Alice" },
});
const ctxWithoutThread = await buildContext({
message_id: 2,
chat: { id: -1001234567890, type: "supergroup", title: "Test Group" },
date: 1700000001,
text: "@bot world",
from: { id: 42, first_name: "Alice" },
});
// Both messages should use the same session key
expect(ctxWithThread?.ctxPayload?.SessionKey).toBe(ctxWithoutThread?.ctxPayload?.SessionKey);
});
it("does not add a topic-cache store lookup for non-forum group reply threads", async () => {
const resolveStorePath = vi.fn(() => "/tmp/openclaw/session-store.json");
const ctx = await buildTelegramMessageContextForTest({
message: {
message_id: 9,
chat: { id: -1001234567890, type: "supergroup", title: "Test Group" },
date: 1700000008,
text: "@bot hello",
message_thread_id: 42,
from: { id: 42, first_name: "Alice" },
},
options: { forceWasMentioned: true },
resolveGroupActivation: () => true,
sessionRuntime: { resolveStorePath },
});
expect(ctx?.isForum).toBe(false);
expect(ctx?.ctxPayload?.MessageThreadId).toBeUndefined();
expect(resolveStorePath).toHaveBeenCalledTimes(1);
});
it("uses topic session for forum groups with message_thread_id", async () => {
const ctx = await buildContext({
message_id: 1,
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
date: 1700000000,
text: "@bot hello",
message_thread_id: 99,
from: { id: 42, first_name: "Alice" },
});
// Session key SHOULD include :topic:99 for forums
expect(ctx?.ctxPayload?.SessionKey).toBe("agent:main:telegram:group:-1001234567890:topic:99");
expect(ctx?.ctxPayload?.MessageThreadId).toBe(99);
expect(ctx?.ctxPayload?.OriginatingTo).toBe("telegram:-1001234567890:topic:99");
});
it("surfaces topic name from reply_to_message forum metadata", async () => {
const ctx = await buildContext({
message_id: 3,
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
date: 1700000002,
text: "@bot hello",
message_thread_id: 99,
from: { id: 42, first_name: "Alice" },
reply_to_message: {
message_id: 2,
forum_topic_created: { name: "Deployments", icon_color: 0x6fb9f0 },
},
});
expect(ctx?.ctxPayload?.TopicName).toBe("Deployments");
});
it("handles forum messages without session runtime overrides", async () => {
const ctx = await buildTelegramMessageContextForTest({
message: {
message_id: 3,
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
date: 1700000002,
text: "@bot hello",
message_thread_id: 99,
from: { id: 42, first_name: "Alice" },
reply_to_message: {
message_id: 2,
forum_topic_created: { name: "Deployments", icon_color: 0x6fb9f0 },
},
},
options: { forceWasMentioned: true },
resolveGroupActivation: () => true,
sessionRuntime: null,
});
expect(ctx?.ctxPayload?.TopicName).toBe("Deployments");
});
it("reloads topic name from disk after cache reset", async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-telegram-topic-name-"));
const sessionStorePath = path.join(tempDir, "sessions.json");
const buildPersistedContext = async (message: Record<string, unknown>) =>
await buildTelegramMessageContextForTest({
message,
options: { forceWasMentioned: true },
resolveGroupActivation: () => true,
sessionRuntime: {
resolveStorePath: () => sessionStorePath,
},
});
try {
await buildPersistedContext({
message_id: 4,
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
date: 1700000003,
text: "@bot hello",
message_thread_id: 99,
from: { id: 42, first_name: "Alice" },
reply_to_message: {
message_id: 3,
forum_topic_created: { name: "Deployments", icon_color: 0x6fb9f0 },
},
});
resetTopicNameCacheForTest();
const ctx = await buildPersistedContext({
message_id: 5,
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
date: 1700000004,
text: "@bot again",
message_thread_id: 99,
from: { id: 42, first_name: "Alice" },
});
expect(ctx?.ctxPayload?.TopicName).toBe("Deployments");
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
resetTopicNameCacheForTest();
}
});
it("persists topic names through the default session runtime path", async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-telegram-topic-name-"));
const sessionStorePath = path.join(tempDir, "sessions.json");
resolveStorePathMock.mockReturnValue(sessionStorePath);
try {
await buildTelegramMessageContextForTest({
message: {
message_id: 6,
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
date: 1700000005,
text: "@bot hello",
message_thread_id: 99,
from: { id: 42, first_name: "Alice" },
reply_to_message: {
message_id: 5,
forum_topic_created: { name: "Deployments", icon_color: 0x6fb9f0 },
},
},
options: { forceWasMentioned: true },
resolveGroupActivation: () => true,
sessionRuntime: null,
});
resetTopicNameCacheForTest();
const ctx = await buildTelegramMessageContextForTest({
message: {
message_id: 7,
chat: { id: -1001234567890, type: "supergroup", title: "Test Forum", is_forum: true },
date: 1700000006,
text: "@bot again",
message_thread_id: 99,
from: { id: 42, first_name: "Alice" },
},
options: { forceWasMentioned: true },
resolveGroupActivation: () => true,
sessionRuntime: null,
});
expect(ctx?.ctxPayload?.TopicName).toBe("Deployments");
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
resetTopicNameCacheForTest();
}
});
});
describe("buildTelegramMessageContext direct peer routing", () => {
it("isolates dm sessions by sender id when chat id differs", async () => {
const runtimeCfg = {
agents: { defaults: { model: "anthropic/claude-opus-4-5", workspace: "/tmp/openclaw" } },
channels: { telegram: {} },
messages: { groupChat: { mentionPatterns: [] } },
session: { dmScope: "per-channel-peer" as const },
};
setRuntimeConfigSnapshot(runtimeCfg);
const baseMessage = {
chat: { id: 777777777, type: "private" as const },
date: 1700000000,
text: "hello",
};
const first = await buildTelegramMessageContextForTest({
cfg: runtimeCfg,
message: {
...baseMessage,
message_id: 1,
from: { id: 123456789, first_name: "Alice" },
},
});
const second = await buildTelegramMessageContextForTest({
cfg: runtimeCfg,
message: {
...baseMessage,
message_id: 2,
from: { id: 987654321, first_name: "Bob" },
},
});
expect(first?.ctxPayload?.SessionKey).toBe("agent:main:telegram:direct:123456789");
expect(second?.ctxPayload?.SessionKey).toBe("agent:main:telegram:direct:987654321");
});
});