Skip to content

Commit 5e13f45

Browse files
aspalaginsteipete
andauthored
fix(telegram): preserve forward origins in debounce batches (#108985)
* fix(telegram): preserve forward origins in debounce batches * fix(telegram): deliver batched forward origins to agent * refactor(telegram): keep debounce forward cleanup local Co-authored-by: Arseniy Palagin <[email protected]> --------- Co-authored-by: Arseniy Palagin <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent f977649 commit 5e13f45

5 files changed

Lines changed: 335 additions & 21 deletions

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,12 +134,16 @@ export function createTelegramInboundDebounceRuntime(
134134
settleSpooledReplayParticipants(participants, { kind: "skipped" });
135135
return;
136136
}
137+
// Single entries return above with their original message and structured forward metadata.
137138
const first = expectDefined(entries.at(0), "multi-entry Telegram debounce batch");
138-
const syntheticMessage = buildSyntheticTextMessage({
139-
base: first.msg,
140-
text: combinedText,
141-
date: last.msg.date ?? first.msg.date,
142-
});
139+
const syntheticMessage = {
140+
...buildSyntheticTextMessage({
141+
base: first.msg,
142+
text: combinedText,
143+
date: last.msg.date ?? first.msg.date,
144+
}),
145+
forward_origin: undefined,
146+
};
143147
const result = await processMessageWithReplyChain({
144148
ctx: buildSyntheticContext(first.ctx, syntheticMessage),
145149
msg: syntheticMessage,
@@ -152,6 +156,7 @@ export function createTelegramInboundDebounceRuntime(
152156
),
153157
receivedAtMs: first.receivedAtMs,
154158
ingressBuffer: "inbound-debounce",
159+
inboundDebounceMessages: entries.map((entry) => entry.msg),
155160
...promptContextBoundaryOptions(
156161
latestPromptContextMinTimestampMs(
157162
...entries.map((entry) => entry.promptContextMinTimestampMs),
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import { describe, expect, it } from "vitest";
2+
import { buildTelegramMessageContextForTest } from "./bot-message-context.test-harness.js";
3+
4+
describe("buildTelegramMessageContext forwarded debounce batches", () => {
5+
it("keeps ordinary text plain while attributing only the forwarded segment", async () => {
6+
const chat = { id: 999, type: "private" as const, first_name: "Alice" };
7+
const sender = { id: 42, first_name: "Alice", is_bot: false };
8+
const context = await buildTelegramMessageContextForTest({
9+
message: {
10+
message_id: 2,
11+
chat,
12+
from: sender,
13+
text: "ordinary note\nforwarded note",
14+
forward_origin: {
15+
type: "hidden_user",
16+
sender_user_name: "Wrong inherited origin",
17+
date: 400,
18+
},
19+
},
20+
options: {
21+
inboundDebounceMessages: [
22+
{
23+
message_id: 1,
24+
date: 1_700_000_000,
25+
chat,
26+
from: sender,
27+
text: "ordinary note",
28+
},
29+
{
30+
message_id: 2,
31+
date: 1_700_000_001,
32+
chat,
33+
from: sender,
34+
text: "forwarded note",
35+
forward_origin: {
36+
type: "hidden_user",
37+
sender_user_name: "Original B",
38+
date: 500,
39+
},
40+
},
41+
],
42+
},
43+
});
44+
45+
const payload = context?.ctxPayload;
46+
expect(payload?.Body).toMatch(
47+
/ordinary note\n\[Forwarded from Original B[^\]]*\]\nforwarded note/,
48+
);
49+
expect(payload?.Body).not.toContain("Wrong inherited origin");
50+
expect(payload?.BodyForAgent).toMatch(
51+
/ordinary note\n\[Forwarded from Original B[^\]]*\]\nforwarded note/,
52+
);
53+
expect(payload?.ForwardedFrom).toBeUndefined();
54+
});
55+
56+
it("redacts a debounced forward origin denied by group context visibility", async () => {
57+
const chat = { id: -1007, type: "group" as const, title: "Ops" };
58+
const sender = { id: 1, first_name: "Allowed", is_bot: false };
59+
const context = await buildTelegramMessageContextForTest({
60+
message: {
61+
message_id: 2,
62+
chat,
63+
from: sender,
64+
text: "ordinary note\nprivate forwarded note",
65+
},
66+
cfg: {
67+
channels: {
68+
telegram: {
69+
groupPolicy: "allowlist",
70+
contextVisibility: "allowlist",
71+
},
72+
},
73+
},
74+
resolveTelegramGroupConfig: () => ({
75+
groupConfig: { requireMention: false, allowFrom: ["1"] },
76+
topicConfig: undefined,
77+
}),
78+
options: {
79+
inboundDebounceMessages: [
80+
{
81+
message_id: 1,
82+
date: 1_700_000_000,
83+
chat,
84+
from: sender,
85+
text: "ordinary note",
86+
},
87+
{
88+
message_id: 2,
89+
date: 1_700_000_001,
90+
chat,
91+
from: sender,
92+
text: "private forwarded note",
93+
forward_origin: {
94+
type: "user",
95+
sender_user: {
96+
id: 999,
97+
first_name: "Hidden",
98+
is_bot: false,
99+
},
100+
date: 500,
101+
},
102+
},
103+
],
104+
},
105+
});
106+
107+
const payload = context?.ctxPayload;
108+
expect(payload?.Body).toContain("ordinary note\nprivate forwarded note");
109+
expect(payload?.Body).not.toContain("[Forwarded from");
110+
expect(payload?.Body).not.toContain("Hidden");
111+
expect(payload?.BodyForAgent).toBe("ordinary note\nprivate forwarded note");
112+
expect(payload?.ForwardedFrom).toBeUndefined();
113+
});
114+
115+
it("keeps mixed text and forwarded media segments ordered", async () => {
116+
const chat = { id: 999, type: "private" as const, first_name: "Alice" };
117+
const sender = { id: 42, first_name: "Alice", is_bot: false };
118+
const photo = [{ file_id: "photo-1", file_unique_id: "unique-1", width: 1, height: 1 }];
119+
const context = await buildTelegramMessageContextForTest({
120+
message: {
121+
message_id: 2,
122+
chat,
123+
from: sender,
124+
text: "ordinary note",
125+
},
126+
allMedia: [{ path: "/tmp/photo-1.jpg", contentType: "image/jpeg" }],
127+
options: {
128+
inboundDebounceMessages: [
129+
{
130+
message_id: 1,
131+
date: 1_700_000_000,
132+
chat,
133+
from: sender,
134+
text: "ordinary note",
135+
},
136+
{
137+
message_id: 2,
138+
date: 1_700_000_001,
139+
chat,
140+
from: sender,
141+
photo,
142+
forward_origin: {
143+
type: "hidden_user",
144+
sender_user_name: "Original B",
145+
date: 500,
146+
},
147+
},
148+
],
149+
},
150+
});
151+
152+
const expectedBody = /ordinary note\n\[Forwarded from Original B[^\]]*\]\n<media:image>/;
153+
expect(context?.ctxPayload.Body).toMatch(expectedBody);
154+
expect(context?.ctxPayload.BodyForAgent).toMatch(expectedBody);
155+
expect(context?.ctxPayload.CommandBody).toBe("ordinary note");
156+
});
157+
});

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

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ import {
4444
buildTelegramGroupFrom,
4545
buildTelegramInboundOriginTarget,
4646
describeReplyTarget,
47+
getTelegramTextParts,
4748
normalizeForwardedContext,
49+
resolveTelegramMediaPlaceholder,
4850
type TelegramReplyTarget,
4951
type TelegramThreadSpec,
5052
} from "./bot/helpers.js";
@@ -148,8 +150,19 @@ function stripReplyChainForwarded(entry: TelegramReplyChainEntry): TelegramReply
148150
return withoutForwarded;
149151
}
150152

153+
function formatTelegramForwardedMessageBody(params: {
154+
body: string;
155+
forwardedFrom?: string;
156+
forwardedDate?: number;
157+
}): string {
158+
const forwardedAt = timestampMsToIsoString(params.forwardedDate);
159+
const forwardPrefix = params.forwardedFrom
160+
? `[Forwarded from ${params.forwardedFrom}${forwardedAt ? ` at ${forwardedAt}` : ""}]`
161+
: undefined;
162+
return [forwardPrefix, params.body].filter(Boolean).join("\n");
163+
}
164+
151165
function formatReplyChainEntry(entry: TelegramReplyChainEntry, index: number): string {
152-
const forwardedAt = timestampMsToIsoString(entry.forwardedDate);
153166
const mediaPath = entry.mediaPath ? resolveTelegramPromptMediaPath(entry.mediaPath) : undefined;
154167
const labels = [
155168
`${index + 1}. ${entry.sender ?? "unknown sender"}`,
@@ -158,10 +171,11 @@ function formatReplyChainEntry(entry: TelegramReplyChainEntry, index: number): s
158171
entry.timestamp ? timestampMsToIsoString(entry.timestamp) : undefined,
159172
].filter(Boolean);
160173
const bodyLines = [
161-
entry.forwardedFrom
162-
? `[Forwarded from ${entry.forwardedFrom}${forwardedAt ? ` at ${forwardedAt}` : ""}]`
163-
: undefined,
164-
entry.isQuote && entry.body ? `"${entry.body}"` : entry.body,
174+
formatTelegramForwardedMessageBody({
175+
body: entry.isQuote && entry.body ? `"${entry.body}"` : (entry.body ?? ""),
176+
forwardedFrom: entry.forwardedFrom,
177+
forwardedDate: entry.forwardedDate,
178+
}),
165179
entry.mediaType ? `<media:${entry.mediaType}>` : undefined,
166180
mediaPath ? `[media_path:${mediaPath}]` : undefined,
167181
entry.mediaRef ? `[media_ref:${entry.mediaRef}]` : undefined,
@@ -261,7 +275,8 @@ export async function buildTelegramInboundContextPayload(params: {
261275
sessionRuntime: sessionRuntimeOverride,
262276
} = params;
263277
const replyTarget = describeReplyTarget(msg);
264-
const forwardOrigin = normalizeForwardedContext(msg);
278+
const hasMultiMessageDebounceBatch = (options?.inboundDebounceMessages?.length ?? 0) > 1;
279+
const forwardOrigin = hasMultiMessageDebounceBatch ? null : normalizeForwardedContext(msg);
265280
const contextVisibilityMode = resolveChannelContextVisibilityMode({
266281
cfg,
267282
channel: "telegram",
@@ -354,20 +369,48 @@ export async function buildTelegramInboundContextPayload(params: {
354369
return [includeForwarded ? visibleEntry : stripReplyChainForwarded(visibleEntry)];
355370
});
356371
const visibleForwardOrigin = includeForwardOrigin ? forwardOrigin : null;
357-
const visibleForwardOriginAt = timestampMsToIsoString(
358-
visibleForwardOrigin?.date ? visibleForwardOrigin.date * 1000 : undefined,
359-
);
372+
const inboundDebounceBodySegments = hasMultiMessageDebounceBatch
373+
? options?.inboundDebounceMessages?.flatMap((debouncedMessage) => {
374+
const segmentBody =
375+
getTelegramTextParts(debouncedMessage).text ||
376+
resolveTelegramMediaPlaceholder(debouncedMessage);
377+
if (!segmentBody) {
378+
return [];
379+
}
380+
const debouncedForwardOrigin = normalizeForwardedContext(debouncedMessage);
381+
const visibleDebouncedForwardOrigin =
382+
debouncedForwardOrigin &&
383+
shouldIncludeGroupSupplementalContext({
384+
kind: "forwarded",
385+
senderId: debouncedForwardOrigin.fromId,
386+
senderUsername: debouncedForwardOrigin.fromUsername,
387+
})
388+
? debouncedForwardOrigin
389+
: null;
390+
return [
391+
formatTelegramForwardedMessageBody({
392+
body: segmentBody,
393+
forwardedFrom: visibleDebouncedForwardOrigin?.from,
394+
forwardedDate: visibleDebouncedForwardOrigin?.date
395+
? visibleDebouncedForwardOrigin.date * 1000
396+
: undefined,
397+
}),
398+
];
399+
})
400+
: undefined;
401+
const visibleBodyText = inboundDebounceBodySegments?.length
402+
? inboundDebounceBodySegments.join("\n")
403+
: formatTelegramForwardedMessageBody({
404+
body: bodyText,
405+
forwardedFrom: visibleForwardOrigin?.from,
406+
forwardedDate: visibleForwardOrigin?.date ? visibleForwardOrigin.date * 1000 : undefined,
407+
});
360408
const replySuffix =
361409
visibleReplyChain.length > 0
362410
? `\n\n[Reply chain - nearest first]\n${visibleReplyChain
363411
.map(formatReplyChainEntry)
364412
.join("\n")}\n[/Reply chain]`
365413
: "";
366-
const forwardPrefix = visibleForwardOrigin
367-
? `[Forwarded from ${visibleForwardOrigin.from}${
368-
visibleForwardOriginAt ? ` at ${visibleForwardOriginAt}` : ""
369-
}]\n`
370-
: "";
371414
const groupLabel = isGroup ? buildGroupLabel(msg, chatId, resolvedThreadId) : undefined;
372415
const senderName = buildSenderName(msg);
373416
const conversationLabel = isGroup
@@ -415,7 +458,7 @@ export async function buildTelegramInboundContextPayload(params: {
415458
channel: "Telegram",
416459
from: conversationLabel,
417460
timestamp: msg.date ? msg.date * 1000 : undefined,
418-
body: `${forwardPrefix}${bodyText}${replySuffix}`,
461+
body: `${visibleBodyText}${replySuffix}`,
419462
chatType: isGroup ? "group" : "direct",
420463
sender: {
421464
name: senderName,
@@ -524,7 +567,7 @@ export async function buildTelegramInboundContextPayload(params: {
524567
inboundEventKind,
525568
body,
526569
rawBody,
527-
bodyForAgent: bodyText,
570+
bodyForAgent: hasMultiMessageDebounceBatch ? visibleBodyText : bodyText,
528571
commandBody,
529572
inboundHistory,
530573
sourceModality: msg.voice ? "voice" : undefined,

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Telegram type declarations define plugin contracts.
22
import type { Bot } from "grammy";
3+
import type { Message } from "grammy/types";
34
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
45
import type {
56
DmPolicy,
@@ -29,6 +30,7 @@ export type TelegramMessageContextOptions = {
2930
promptContextMinTimestampMs?: number;
3031
promptContextAmbientWatermark?: TelegramAmbientTranscriptWatermark;
3132
ambientTranscriptBody?: string;
33+
inboundDebounceMessages?: readonly Message[];
3234
spooledReplay?: boolean;
3335
/** Use an attempt-local participant so an outer retry loop owns final spool settlement. */
3436
isolateSpooledReplaySettlement?: boolean;

0 commit comments

Comments
 (0)