Skip to content

Commit 42f1627

Browse files
committed
fix(telegram): trust dm topic silent replies
1 parent fc5ffed commit 42f1627

10 files changed

Lines changed: 211 additions & 19 deletions

‎extensions/telegram/src/bot-message-dispatch.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3032,6 +3032,54 @@ describe("dispatchTelegramMessage draft streaming", () => {
30323032
expect(deliverReplies).not.toHaveBeenCalled();
30333033
});
30343034

3035+
it("passes trusted DM-topic silent-reply context into buffered dispatch", async () => {
3036+
const draftStream = createDraftStream(999);
3037+
createTelegramDraftStream.mockReturnValue(draftStream);
3038+
dispatchReplyWithBufferedBlockDispatcher.mockResolvedValue({
3039+
queuedFinal: false,
3040+
});
3041+
3042+
await dispatchWithContext({
3043+
context: createContext({
3044+
ctxPayload: {
3045+
SessionKey: "agent:main:telegram:direct:123:thread:123:777",
3046+
} as unknown as TelegramMessageContext["ctxPayload"],
3047+
}),
3048+
cfg: {
3049+
agents: {
3050+
defaults: {
3051+
silentReply: {
3052+
direct: "disallow",
3053+
group: "allow",
3054+
internal: "allow",
3055+
},
3056+
silentReplyRewrite: {
3057+
direct: true,
3058+
},
3059+
},
3060+
},
3061+
} as unknown as OpenClawConfig,
3062+
});
3063+
3064+
expect(dispatchReplyWithBufferedBlockDispatcher).toHaveBeenCalledWith(
3065+
expect.objectContaining({
3066+
ctx: expect.objectContaining({
3067+
SessionKey: "agent:main:telegram:direct:123:thread:123:777",
3068+
TrustedThreadSessionKey: true,
3069+
}),
3070+
dispatcherOptions: expect.objectContaining({
3071+
silentReplyContext: expect.objectContaining({
3072+
sessionKey: "agent:main:telegram:direct:123:thread:123:777",
3073+
surface: "telegram",
3074+
conversationType: "internal",
3075+
trustThreadSessionKey: true,
3076+
}),
3077+
}),
3078+
}),
3079+
);
3080+
expect(deliverReplies).not.toHaveBeenCalled();
3081+
});
3082+
30353083
it("rewrites no-visible-response DM thread turns when the thread suffix is mismatched", async () => {
30363084
const draftStream = createDraftStream(999);
30373085
createTelegramDraftStream.mockReturnValue(draftStream);

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

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,18 @@ export const dispatchTelegramMessage = async ({
671671
};
672672
const silentErrorReplies = telegramCfg.silentErrorReplies === true;
673673
const isDmTopic = !isGroup && threadSpec.scope === "dm" && threadSpec.id != null;
674+
const policySessionKey =
675+
ctxPayload.CommandSource === "native"
676+
? (ctxPayload.CommandTargetSessionKey ?? ctxPayload.SessionKey)
677+
: ctxPayload.SessionKey;
678+
const trustPolicyThreadSessionKey = isTrustedTelegramPolicyThreadSessionKey({
679+
sessionKey: policySessionKey,
680+
chatId,
681+
thread: threadSpec,
682+
});
683+
const dispatchCtxPayload = trustPolicyThreadSessionKey
684+
? { ...ctxPayload, TrustedThreadSessionKey: true }
685+
: ctxPayload;
674686
let queuedFinal = false;
675687
let hadErrorReplyFailureOrSkip = false;
676688
let isFirstTurnInSession = false;
@@ -870,10 +882,21 @@ export const dispatchTelegramMessage = async ({
870882
record: context.turn.record,
871883
runDispatch: () =>
872884
telegramDeps.dispatchReplyWithBufferedBlockDispatcher({
873-
ctx: ctxPayload,
885+
ctx: dispatchCtxPayload,
874886
cfg,
875887
dispatcherOptions: {
876888
...replyPipeline,
889+
...(trustPolicyThreadSessionKey
890+
? {
891+
silentReplyContext: {
892+
cfg,
893+
sessionKey: policySessionKey,
894+
surface: "telegram",
895+
conversationType: "internal" as const,
896+
trustThreadSessionKey: true,
897+
},
898+
}
899+
: {}),
877900
beforeDeliver: async (payload) => payload,
878901
deliver: async (payload, info) => {
879902
if (isDispatchSuperseded()) {
@@ -1308,15 +1331,6 @@ export const dispatchTelegramMessage = async ({
13081331
}
13091332

13101333
if (!queuedFinal && !sentFallback && !dispatchError && !deliverySummary.delivered) {
1311-
const policySessionKey =
1312-
ctxPayload.CommandSource === "native"
1313-
? (ctxPayload.CommandTargetSessionKey ?? ctxPayload.SessionKey)
1314-
: ctxPayload.SessionKey;
1315-
const trustPolicyThreadSessionKey = isTrustedTelegramPolicyThreadSessionKey({
1316-
sessionKey: policySessionKey,
1317-
chatId,
1318-
thread: threadSpec,
1319-
});
13201334
const silentReplyFallback = projectOutboundPayloadPlanForDelivery(
13211335
createOutboundPayloadPlan([{ text: "NO_REPLY" }], {
13221336
cfg,

‎src/auto-reply/dispatch.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,42 @@ describe("withReplyDispatcher", () => {
349349
);
350350
});
351351

352+
it("uses provider-verified thread trust for silent-reply dispatcher context", async () => {
353+
hoisted.createReplyDispatcherWithTypingMock.mockReturnValueOnce({
354+
dispatcher: createDispatcher([]),
355+
replyOptions: {},
356+
markDispatchIdle: vi.fn(),
357+
markRunComplete: vi.fn(),
358+
});
359+
hoisted.dispatchReplyFromConfigMock.mockResolvedValueOnce({ text: "ok" });
360+
361+
await dispatchInboundMessageWithBufferedDispatcher({
362+
ctx: buildTestCtx({
363+
SessionKey: "agent:test:telegram:direct:123:thread:123:42",
364+
MessageThreadId: "42",
365+
TrustedThreadSessionKey: true,
366+
ChatType: "direct",
367+
Surface: "telegram",
368+
}),
369+
cfg: {} as OpenClawConfig,
370+
dispatcherOptions: {
371+
deliver: async () => undefined,
372+
},
373+
replyResolver: async () => ({ text: "ok" }),
374+
});
375+
376+
expect(hoisted.createReplyDispatcherWithTypingMock).toHaveBeenCalledWith(
377+
expect.objectContaining({
378+
silentReplyContext: expect.objectContaining({
379+
sessionKey: "agent:test:telegram:direct:123:thread:123:42",
380+
surface: "telegram",
381+
conversationType: "internal",
382+
trustThreadSessionKey: true,
383+
}),
384+
}),
385+
);
386+
});
387+
352388
it("does not copy source conversation type onto cross-session native silent-reply targets", async () => {
353389
hoisted.createReplyDispatcherWithTypingMock.mockReturnValueOnce({
354390
dispatcher: createDispatcher([]),

‎src/auto-reply/dispatch.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,11 @@ function resolveDispatcherSilentReplyContext(
4040
finalized.CommandTargetSessionKey !== finalized.SessionKey;
4141
const hasTrustedThreadSessionKey =
4242
!isNativeCrossSession &&
43-
isTrustedStructuredThreadSessionKey({
44-
sessionKey: policySessionKey,
45-
threadId: finalized.MessageThreadId,
46-
});
43+
(finalized.TrustedThreadSessionKey === true ||
44+
isTrustedStructuredThreadSessionKey({
45+
sessionKey: policySessionKey,
46+
threadId: finalized.MessageThreadId,
47+
}));
4748
const chatType = normalizeChatType(finalized.ChatType);
4849
const conversationType: SilentReplyConversationType | undefined = isNativeCrossSession
4950
? undefined

‎src/auto-reply/reply/dispatch-from-config.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1287,6 +1287,40 @@ describe("dispatchReplyFromConfig", () => {
12871287
);
12881288
});
12891289

1290+
it("routes provider-verified chat-scoped thread replies with internal policy context", async () => {
1291+
setNoAbort();
1292+
mocks.routeReply.mockClear();
1293+
const cfg = emptyConfig;
1294+
const dispatcher = createDispatcher();
1295+
const ctx = buildTestCtx({
1296+
Provider: "webchat",
1297+
Surface: "webchat",
1298+
OriginatingChannel: "telegram",
1299+
OriginatingTo: "telegram:123",
1300+
ExplicitDeliverRoute: true,
1301+
MessageThreadId: "42",
1302+
TrustedThreadSessionKey: true,
1303+
SessionKey: "agent:main:telegram:direct:123:thread:123:42",
1304+
});
1305+
1306+
const replyResolver = async (
1307+
_ctx: MsgContext,
1308+
_opts?: GetReplyOptions,
1309+
_cfg?: OpenClawConfig,
1310+
) => ({ text: "hi" }) satisfies ReplyPayload;
1311+
await dispatchReplyFromConfig({ ctx, cfg, dispatcher, replyResolver });
1312+
1313+
expect(dispatcher.sendFinalReply).not.toHaveBeenCalled();
1314+
expect(mocks.routeReply).toHaveBeenCalledWith(
1315+
expect.objectContaining({
1316+
channel: "telegram",
1317+
policyConversationType: "internal",
1318+
policySessionKey: "agent:main:telegram:direct:123:thread:123:42",
1319+
to: "telegram:123",
1320+
}),
1321+
);
1322+
});
1323+
12901324
it("routes mismatched threaded replies with parent direct policy context", async () => {
12911325
setNoAbort();
12921326
mocks.routeReply.mockClear();

‎src/auto-reply/reply/dispatch-from-config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ const resolveRoutedPolicyConversationType = (
202202
return undefined;
203203
}
204204
if (
205+
ctx.TrustedThreadSessionKey === true ||
205206
isTrustedStructuredThreadSessionKey({
206207
sessionKey: ctx.SessionKey,
207208
threadId: ctx.MessageThreadId,

‎src/auto-reply/reply/get-reply-run.exec-hint.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,16 @@ describe("resolvePromptSilentReplyConversationType", () => {
9292
}),
9393
}),
9494
).toBe("internal");
95+
expect(
96+
resolvePromptSilentReplyConversationType({
97+
ctx: buildGetReplyCtx({
98+
ChatType: "direct",
99+
MessageThreadId: "300118",
100+
TrustedThreadSessionKey: true,
101+
SessionKey: "agent:main:telegram:direct:435427284:thread:435427284:300118",
102+
}),
103+
}),
104+
).toBe("internal");
95105
expect(
96106
resolvePromptSilentReplyConversationType({
97107
ctx: buildGetReplyGroupCtx({

‎src/auto-reply/reply/get-reply-run.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,12 @@ type ExecOverrides = Pick<ExecToolDefaults, "host" | "security" | "ask" | "node"
8080
export function resolvePromptSilentReplyConversationType(params: {
8181
ctx: Pick<
8282
MsgContext,
83-
"ChatType" | "CommandSource" | "CommandTargetSessionKey" | "MessageThreadId" | "SessionKey"
83+
| "ChatType"
84+
| "CommandSource"
85+
| "CommandTargetSessionKey"
86+
| "MessageThreadId"
87+
| "SessionKey"
88+
| "TrustedThreadSessionKey"
8489
>;
8590
inboundSessionKey?: string;
8691
}): SilentReplyConversationType | undefined {
@@ -93,6 +98,7 @@ export function resolvePromptSilentReplyConversationType(params: {
9398
return undefined;
9499
}
95100
if (
101+
params.ctx.TrustedThreadSessionKey === true ||
96102
isTrustedStructuredThreadSessionKey({
97103
sessionKey: sourceSessionKey,
98104
threadId: params.ctx.MessageThreadId,
@@ -419,15 +425,18 @@ export async function runPreparedReply(
419425
ctx: promptSessionCtx,
420426
inboundSessionKey: ctx.SessionKey,
421427
});
428+
const hasTrustedThreadSessionKey =
429+
promptSessionCtx.TrustedThreadSessionKey === true ||
430+
isTrustedStructuredThreadSessionKey({
431+
sessionKey: runtimePolicySessionKey,
432+
threadId: promptSessionCtx.MessageThreadId,
433+
});
422434
const silentReplySettings = resolveSilentReplySettings({
423435
cfg,
424436
sessionKey: runtimePolicySessionKey,
425437
surface: promptSessionCtx.Surface ?? promptSessionCtx.Provider,
426438
conversationType: silentReplyConversationType,
427-
trustThreadSessionKey: isTrustedStructuredThreadSessionKey({
428-
sessionKey: runtimePolicySessionKey,
429-
threadId: promptSessionCtx.MessageThreadId,
430-
}),
439+
trustThreadSessionKey: hasTrustedThreadSessionKey,
431440
});
432441
const useFastReplyRuntime = shouldUseReplyFastTestRuntime({
433442
cfg,

‎src/auto-reply/reply/reply-flow.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,39 @@ describe("createReplyDispatcher", () => {
117117
expect(deliver).not.toHaveBeenCalled();
118118
});
119119

120+
it("drops exact NO_REPLY final payloads for trusted chat-scoped thread sessions", async () => {
121+
const deliver = vi.fn().mockResolvedValue(undefined);
122+
const cfg: OpenClawConfig = {
123+
agents: {
124+
defaults: {
125+
silentReply: {
126+
direct: "disallow",
127+
group: "allow",
128+
internal: "allow",
129+
},
130+
silentReplyRewrite: {
131+
direct: true,
132+
},
133+
},
134+
},
135+
};
136+
const dispatcher = createReplyDispatcher({
137+
deliver,
138+
silentReplyContext: {
139+
cfg,
140+
sessionKey: "agent:main:telegram:direct:123:thread:123:42",
141+
surface: "telegram",
142+
conversationType: "internal",
143+
trustThreadSessionKey: true,
144+
},
145+
});
146+
147+
expect(dispatcher.sendFinalReply({ text: SILENT_REPLY_TOKEN })).toBe(false);
148+
149+
await dispatcher.waitForIdle();
150+
expect(deliver).not.toHaveBeenCalled();
151+
});
152+
120153
it("strips heartbeat tokens and applies responsePrefix", async () => {
121154
const deliver = vi.fn().mockResolvedValue(undefined);
122155
const onHeartbeatStrip = vi.fn();

‎src/auto-reply/templating.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,12 @@ export type MsgContext = {
202202
ForceSenderIsOwnerFalse?: boolean;
203203
/** Thread identifier (Telegram topic id or Matrix thread event id). */
204204
MessageThreadId?: string | number;
205+
/**
206+
* Trusted runtime assertion that the structured thread suffix in SessionKey
207+
* refers to this provider turn. Use when the provider's canonical
208+
* MessageThreadId differs from the session-key suffix shape.
209+
*/
210+
TrustedThreadSessionKey?: boolean;
205211
/** Platform-native channel/conversation id (e.g. Slack DM channel "D…" id). */
206212
NativeChannelId?: string;
207213
/** Stable provider-native direct-peer id when a DM room/user mapping must survive later writes. */

0 commit comments

Comments
 (0)