Skip to content

Commit 08d926d

Browse files
authored
fix(telegram): recognize current-source message targets (#126625)
Recognize raw, provider-qualified, and topic-qualified Telegram targets as the same current source when their semantic identities match. Prevent successful final message-tool sends from continuing into duplicate replies. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent f20c6da commit 08d926d

4 files changed

Lines changed: 192 additions & 10 deletions

File tree

‎extensions/telegram/src/channel.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,11 @@ import {
7575
} from "./group-policy.js";
7676
import { resolveTelegramInlineButtonsScope } from "./inline-buttons.js";
7777
import * as monitorModule from "./monitor.js";
78-
import { looksLikeTelegramTargetId, normalizeTelegramMessagingTarget } from "./normalize.js";
78+
import {
79+
looksLikeTelegramTargetId,
80+
normalizeTelegramMessagingTarget,
81+
telegramMessagingTargetsMatch,
82+
} from "./normalize.js";
7983
import { createTelegramOutboundAdapter } from "./outbound-adapter.js";
8084
import { parseTelegramThreadId } from "./outbound-params.js";
8185
import { releaseStoppedTelegramPollingLease } from "./polling-lease.js";
@@ -1280,6 +1284,12 @@ export const telegramPlugin = createChatChannelPlugin({
12801284
},
12811285
security: telegramSecurityAdapter,
12821286
threading: {
1287+
matchesToolContextTarget: ({ target, toolContext }) => {
1288+
return [toolContext.currentMessagingTarget, toolContext.currentChannelId].some(
1289+
(currentTarget) =>
1290+
currentTarget != null && telegramMessagingTargetsMatch(target, currentTarget),
1291+
);
1292+
},
12831293
resolveReplyToMode: ({ cfg, accountId }) =>
12841294
resolveTelegramConfigAccessorAccount({ cfg, accountId }).config.replyToMode ?? "off",
12851295
buildToolContext: (params) => buildTelegramThreadingToolContext(params),

‎extensions/telegram/src/normalize.ts‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,27 +15,39 @@ function normalizeTelegramTargetBody(raw: string): string | undefined {
1515
return undefined;
1616
}
1717

18-
const parsed = parseTelegramTarget(trimmed);
19-
const normalizedChatId = normalizeTelegramLookupTarget(parsed.chatId);
20-
if (!normalizedChatId) {
18+
const identity = resolveTelegramTargetIdentity(trimmed);
19+
if (!identity) {
2120
return undefined;
2221
}
2322

2423
const keepLegacyGroupPrefix = /^group:/i.test(prefixStripped);
2524
const hasTopicSuffix = /:topic:\d+$/i.test(prefixStripped);
26-
const chatSegment = keepLegacyGroupPrefix ? `group:${normalizedChatId}` : normalizedChatId;
27-
if (parsed.directMessagesTopicId != null) {
28-
return `${chatSegment}:direct-topic:${parsed.directMessagesTopicId}`;
25+
const chatSegment = keepLegacyGroupPrefix ? `group:${identity.chatId}` : identity.chatId;
26+
if (identity.directMessagesTopicId != null) {
27+
return `${chatSegment}:direct-topic:${identity.directMessagesTopicId}`;
2928
}
30-
if (parsed.messageThreadId == null) {
29+
if (identity.messageThreadId == null) {
3130
return chatSegment;
3231
}
3332
const threadSuffix = hasTopicSuffix
34-
? `:topic:${parsed.messageThreadId}`
35-
: `:${parsed.messageThreadId}`;
33+
? `:topic:${identity.messageThreadId}`
34+
: `:${identity.messageThreadId}`;
3635
return `${chatSegment}${threadSuffix}`;
3736
}
3837

38+
function resolveTelegramTargetIdentity(raw: string) {
39+
const parsed = parseTelegramTarget(raw);
40+
const chatId = normalizeTelegramLookupTarget(parsed.chatId);
41+
if (!chatId) {
42+
return undefined;
43+
}
44+
return {
45+
chatId: normalizeLowercaseStringOrEmpty(chatId),
46+
messageThreadId: parsed.messageThreadId,
47+
directMessagesTopicId: parsed.directMessagesTopicId,
48+
};
49+
}
50+
3951
export function normalizeTelegramMessagingTarget(raw: string): string | undefined {
4052
const normalizedBody = normalizeTelegramTargetBody(raw);
4153
if (!normalizedBody) {
@@ -47,3 +59,15 @@ export function normalizeTelegramMessagingTarget(raw: string): string | undefine
4759
export function looksLikeTelegramTargetId(raw: string): boolean {
4860
return normalizeTelegramTargetBody(raw) !== undefined;
4961
}
62+
63+
export function telegramMessagingTargetsMatch(target: string, currentTarget: string): boolean {
64+
const targetIdentity = resolveTelegramTargetIdentity(target);
65+
const currentIdentity = resolveTelegramTargetIdentity(currentTarget);
66+
return (
67+
targetIdentity !== undefined &&
68+
currentIdentity !== undefined &&
69+
targetIdentity.chatId === currentIdentity.chatId &&
70+
targetIdentity.messageThreadId === currentIdentity.messageThreadId &&
71+
targetIdentity.directMessagesTopicId === currentIdentity.directMessagesTopicId
72+
);
73+
}

‎extensions/telegram/src/threading-tool-context.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@ vi.mock("openclaw/plugin-sdk/secret-file-runtime", async (importOriginal) => ({
1515
tryReadSecretFileSync: tryReadSecretFileSyncMock,
1616
}));
1717

18+
function requireTelegramToolContextTargetMatcher() {
19+
const matchesToolContextTarget = telegramPlugin.threading?.matchesToolContextTarget;
20+
if (!matchesToolContextTarget) {
21+
throw new Error("Telegram tool context target matcher is unavailable");
22+
}
23+
return matchesToolContextTarget;
24+
}
25+
1826
describe("telegramPlugin reply threading", () => {
1927
it.each([
2028
{
@@ -60,6 +68,42 @@ describe("telegramPlugin reply threading", () => {
6068
expect(resolveReplyToMode({ cfg, accountId: "sut" })).toBe(expected);
6169
expect(tryReadSecretFileSyncMock).not.toHaveBeenCalled();
6270
});
71+
72+
it.each([
73+
{ target: "-100123", currentChannelId: "telegram:-100123", expected: true },
74+
{ target: "telegram:-100123", currentChannelId: "-100123", expected: true },
75+
{
76+
target: "-100123:topic:77",
77+
currentChannelId: "telegram:-100123:77",
78+
expected: true,
79+
},
80+
{
81+
target: "-100123:direct-topic:77",
82+
currentChannelId: "telegram:-100123:direct-topic:77",
83+
expected: true,
84+
},
85+
{
86+
target: "-100123:topic:77",
87+
currentChannelId: "telegram:-100123:direct-topic:77",
88+
expected: false,
89+
},
90+
{
91+
target: "-100123:topic:77",
92+
currentChannelId: "telegram:-100123:topic:78",
93+
expected: false,
94+
},
95+
{ target: "-100456", currentChannelId: "telegram:-100123", expected: false },
96+
])(
97+
"matches canonical target $target against current channel $currentChannelId",
98+
({ target, currentChannelId, expected }) => {
99+
expect(
100+
requireTelegramToolContextTargetMatcher()({
101+
target,
102+
toolContext: { currentChannelId },
103+
}),
104+
).toBe(expected);
105+
},
106+
);
63107
});
64108

65109
describe("buildTelegramThreadingToolContext", () => {

‎src/infra/outbound/message-action-execution.source-reply.test.ts‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Covers core message-action send fallback, TTS application, and durable send
22
// policy after plugin preparation is absent.
33
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import type { ChannelPlugin } from "../../channels/plugins/types.public.js";
45
import type { OpenClawConfig } from "../../config/config.js";
56
import { setActivePluginRegistry } from "../../plugins/runtime.js";
67
import { createOutboundTestPlugin, createTestRegistry } from "../../test-utils/channel-plugins.js";
@@ -22,6 +23,14 @@ const slackConfig = {
2223
},
2324
} as OpenClawConfig;
2425

26+
const telegramConfig = {
27+
channels: {
28+
telegram: {
29+
enabled: true,
30+
},
31+
},
32+
} as OpenClawConfig;
33+
2534
function registerSlackTextPlugin(accountIds: string[] = ["default"]) {
2635
const sendText = vi.fn().mockResolvedValue({
2736
channel: "slack",
@@ -54,6 +63,41 @@ function registerSlackTextPlugin(accountIds: string[] = ["default"]) {
5463
return sendText;
5564
}
5665

66+
function registerTelegramTextPlugin(
67+
matchesToolContextTarget: NonNullable<
68+
NonNullable<ChannelPlugin["threading"]>["matchesToolContextTarget"]
69+
>,
70+
) {
71+
setActivePluginRegistry(
72+
createTestRegistry([
73+
{
74+
pluginId: "telegram",
75+
source: "test",
76+
plugin: {
77+
...createOutboundTestPlugin({
78+
id: "telegram",
79+
messaging: { targetResolver: { looksLikeId: () => true } },
80+
outbound: {
81+
deliveryMode: "direct",
82+
sendText: vi.fn().mockResolvedValue({
83+
channel: "telegram",
84+
messageId: "m1",
85+
chatId: "-100123",
86+
}),
87+
},
88+
}),
89+
config: {
90+
listAccountIds: () => ["default"],
91+
resolveAccount: () => ({ enabled: true }),
92+
isConfigured: () => true,
93+
},
94+
threading: { matchesToolContextTarget },
95+
},
96+
},
97+
]),
98+
);
99+
}
100+
57101
describe("runMessageAction core send routing", () => {
58102
afterEach(() => {
59103
setActivePluginRegistry(createTestRegistry([]));
@@ -123,6 +167,66 @@ describe("runMessageAction core send routing", () => {
123167
expect(result.payload).toMatchObject({ sourceReplyRoute: "current-source" });
124168
});
125169

170+
it.each([
171+
{
172+
name: "an equivalent raw current-chat target",
173+
target: "-100123",
174+
currentChannelId: "telegram:-100123",
175+
matcherResult: true,
176+
expectedRoute: "current-source",
177+
},
178+
{
179+
name: "a different chat",
180+
target: "-100456",
181+
currentChannelId: "telegram:-100123",
182+
matcherResult: false,
183+
expectedRoute: undefined,
184+
},
185+
{
186+
name: "a different topic",
187+
target: "-100123:topic:78",
188+
currentChannelId: "telegram:-100123:topic:77",
189+
matcherResult: false,
190+
expectedRoute: undefined,
191+
},
192+
])("uses the Telegram target matcher for $name", async (testCase) => {
193+
const matchesToolContextTarget = vi.fn(() => testCase.matcherResult);
194+
registerTelegramTextPlugin(matchesToolContextTarget);
195+
196+
const toolContext = {
197+
currentChannelProvider: "telegram",
198+
currentChannelId: testCase.currentChannelId,
199+
currentSourceTurnId: "source-turn-1",
200+
};
201+
const result = await runMessageAction({
202+
cfg: telegramConfig,
203+
action: "send",
204+
params: {
205+
channel: "telegram",
206+
target: testCase.target,
207+
message: "visible source reply",
208+
},
209+
toolContext,
210+
messageActionAuthorization: {
211+
requesterAccountId: "default",
212+
toolContext,
213+
},
214+
sessionKey: `agent:main:telegram:group:${testCase.currentChannelId}`,
215+
defaultAccountId: "default",
216+
sourceReplyDeliveryMode: "message_tool_only",
217+
dryRun: false,
218+
});
219+
220+
expect(result.kind).toBe("send");
221+
expect((result.payload as { sourceReplyRoute?: unknown }).sourceReplyRoute).toBe(
222+
testCase.expectedRoute,
223+
);
224+
expect(matchesToolContextTarget).toHaveBeenCalledWith({
225+
target: testCase.target,
226+
toolContext,
227+
});
228+
});
229+
126230
it("does not mark a message-scoped reply that enters a new thread as current-source", async () => {
127231
registerSlackTextPlugin();
128232

0 commit comments

Comments
 (0)