Skip to content

Commit 94cdb6c

Browse files
fix(telegram): preserve batched reply and quote context (#121907)
Preserve reply and selected-quote metadata from later Telegram debounce and fragment-batch messages while keeping reply-chain recovery bounded. Co-authored-by: iridescentWen <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent f72001f commit 94cdb6c

7 files changed

Lines changed: 276 additions & 66 deletions

‎extensions/telegram/src/bot-handlers.inbound-buffer.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ export function createTelegramInboundBuffers({
205205
),
206206
receivedAtMs: first.receivedAtMs,
207207
ingressBuffer: "inbound-debounce",
208-
inboundDebounceMessages: entries.map((entry) => entry.msg),
208+
bufferedMessages: entries.map((entry) => entry.msg),
209209
...promptContextBoundaryOptions(
210210
latestPromptContextMinTimestampMs(
211211
...entries.map((entry) => entry.promptContextMinTimestampMs),
@@ -287,17 +287,15 @@ export function createTelegramInboundBuffers({
287287
const flushTextFragments = async (entry: TextFragmentEntry) => {
288288
try {
289289
entry.messages.sort((a, b) => a.msg.message_id - b.msg.message_id);
290+
const bufferedMessages = entry.messages.map((bufferedMessage) => bufferedMessage.msg);
290291
const first = entry.messages[0];
291292
const last = entry.messages.at(-1);
292293
if (!first || !last) {
293294
releaseDispatchDedupeClaims(entry.dispatchDedupeClaims);
294295
settleSpooledReplayParticipants(entry.spooledReplayParticipants, { kind: "skipped" });
295296
return;
296297
}
297-
const combinedTextParts = joinTelegramTextParts(
298-
entry.messages.map((bufferedMessage) => bufferedMessage.msg),
299-
"",
300-
);
298+
const combinedTextParts = joinTelegramTextParts(bufferedMessages, "");
301299
const combinedText = combinedTextParts.text;
302300
if (!combinedText.trim()) {
303301
releaseDispatchDedupeClaims(entry.dispatchDedupeClaims);
@@ -317,11 +315,10 @@ export function createTelegramInboundBuffers({
317315
storeAllowFrom: entry.storeAllowFrom,
318316
options: {
319317
messageIdOverride: String(last.msg.message_id),
320-
ambientTranscriptBody: formatTelegramAmbientTranscriptBody(
321-
entry.messages.map((bufferedMessage) => bufferedMessage.msg),
322-
),
318+
ambientTranscriptBody: formatTelegramAmbientTranscriptBody(bufferedMessages),
323319
receivedAtMs: first.receivedAtMs,
324320
ingressBuffer: "text-fragment",
321+
bufferedMessages,
325322
...promptContextBoundaryOptions(
326323
entry.promptContextMinTimestampMs,
327324
entry.promptContextAmbientWatermark,

‎extensions/telegram/src/bot-message-context.forwarded-batch.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ describe("buildTelegramMessageContext forwarded debounce batches", () => {
1818
],
1919
},
2020
options: {
21-
inboundDebounceMessages: [
21+
bufferedMessages: [
2222
{
2323
message_id: 1,
2424
date: 1_700_000_000,
@@ -64,7 +64,7 @@ describe("buildTelegramMessageContext forwarded debounce batches", () => {
6464
},
6565
},
6666
options: {
67-
inboundDebounceMessages: [
67+
bufferedMessages: [
6868
{
6969
message_id: 1,
7070
date: 1_700_000_000,
@@ -122,7 +122,7 @@ describe("buildTelegramMessageContext forwarded debounce batches", () => {
122122
topicConfig: undefined,
123123
}),
124124
options: {
125-
inboundDebounceMessages: [
125+
bufferedMessages: [
126126
{
127127
message_id: 1,
128128
date: 1_700_000_000,
@@ -171,7 +171,7 @@ describe("buildTelegramMessageContext forwarded debounce batches", () => {
171171
},
172172
allMedia: [{ path: "/tmp/photo-1.jpg", contentType: "image/jpeg", kind: "image" }],
173173
options: {
174-
inboundDebounceMessages: [
174+
bufferedMessages: [
175175
{
176176
message_id: 1,
177177
date: 1_700_000_000,
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
import { describe, expect, it } from "vitest";
2+
import { buildTelegramMessageContextForTest } from "./bot-message-context.test-harness.js";
3+
import { TELEGRAM_REPLY_CHAIN_MAX_DEPTH } from "./message-cache.js";
4+
5+
const CHAT = { id: 999, type: "private" as const, first_name: "Alice" };
6+
const SENDER = { id: 42, first_name: "Alice", is_bot: false as const };
7+
const QUOTED_LINE = "the quoted source line";
8+
// `ReplyMessage` is a Message pinned to `reply_to_message: undefined`, so the
9+
// embedded reply target cannot itself nest another one.
10+
const REPLY_TARGET = {
11+
message_id: 90,
12+
date: 1_699_999_000,
13+
chat: CHAT,
14+
text: QUOTED_LINE,
15+
from: { id: 7, first_name: "Bob", is_bot: false as const },
16+
reply_to_message: undefined,
17+
};
18+
19+
function quotingMessage(messageId: number, text: string) {
20+
return {
21+
message_id: messageId,
22+
date: 1_700_000_000 + messageId,
23+
chat: CHAT,
24+
from: SENDER,
25+
text,
26+
reply_to_message: REPLY_TARGET,
27+
quote: { text: QUOTED_LINE, position: 0 },
28+
};
29+
}
30+
31+
/** A quoting message whose reply target is unique, so none of them dedupe away. */
32+
function quotingDistinctSource(messageId: number) {
33+
const sourceText = `distinct source ${messageId}`;
34+
return {
35+
message_id: messageId,
36+
date: 1_700_000_000 + messageId,
37+
chat: CHAT,
38+
from: SENDER,
39+
text: `ask ${messageId}`,
40+
reply_to_message: { ...REPLY_TARGET, message_id: 500 + messageId, text: sourceText },
41+
quote: { text: sourceText, position: 0 },
42+
};
43+
}
44+
45+
function countReplyChainEntries(body: string): number {
46+
const block = body.match(/\[Reply chain - nearest first\]\n([\s\S]*?)\n\[\/Reply chain\]/)?.[1];
47+
if (!block) {
48+
return 0;
49+
}
50+
// Entries render as `[1. Bob id:501]` followed by their body lines.
51+
return block.split("\n").filter((line) => /^\[\d+\. /.test(line)).length;
52+
}
53+
54+
function plainMessage(messageId: number, text: string) {
55+
return { message_id: messageId, date: 1_700_000_000 + messageId, chat: CHAT, from: SENDER, text };
56+
}
57+
58+
describe("buildTelegramMessageContext reply/quote debounce batches", () => {
59+
it("preserves a quote carried by a non-first buffered message", async () => {
60+
const context = await buildTelegramMessageContextForTest({
61+
message: plainMessage(2, "plain note\nquoting note"),
62+
options: {
63+
bufferedMessages: [plainMessage(1, "plain note"), quotingMessage(2, "quoting note")],
64+
},
65+
});
66+
67+
expect(context?.ctxPayload.Body).toContain(QUOTED_LINE);
68+
});
69+
70+
it("keeps cached first-message ancestry after a quote-only follow-up", async () => {
71+
const first = quotingMessage(1, "first ask");
72+
const context = await buildTelegramMessageContextForTest({
73+
message: { ...first, text: "first ask\nfollow-up" },
74+
replyChain: [
75+
{
76+
messageId: "90",
77+
replyToId: "89",
78+
sender: "Cached Bob",
79+
senderId: "7",
80+
body: QUOTED_LINE,
81+
timestamp: 1_699_999_000_000,
82+
},
83+
],
84+
options: {
85+
bufferedMessages: [
86+
first,
87+
{
88+
...plainMessage(2, "follow-up"),
89+
quote: { text: "quote-only follow-up", position: 0 },
90+
},
91+
],
92+
},
93+
});
94+
95+
expect(context?.ctxPayload.ReplyChain).toMatchObject([
96+
{ sender: "unknown sender", body: "quote-only follow-up", isQuote: true },
97+
{
98+
messageId: "90",
99+
replyToId: "89",
100+
sender: "Cached Bob",
101+
senderId: "7",
102+
timestamp: 1_699_999_000_000,
103+
},
104+
]);
105+
});
106+
107+
it("lists a source re-quoted by two buffered messages only once", async () => {
108+
const context = await buildTelegramMessageContextForTest({
109+
message: plainMessage(3, "first ask\nsecond ask"),
110+
options: {
111+
bufferedMessages: [quotingMessage(1, "first ask"), quotingMessage(2, "second ask")],
112+
},
113+
});
114+
115+
const body = context?.ctxPayload.Body ?? "";
116+
expect(body).toContain(QUOTED_LINE);
117+
expect(body.split(QUOTED_LINE).length - 1).toBe(1);
118+
});
119+
120+
// The cap must not spend all its slots on the first message's inherited
121+
// ancestry, or it suppresses exactly the later quote this path recovers.
122+
it("keeps a later quote when the first message already has a full reply ancestry", async () => {
123+
const ancestry = Array.from({ length: TELEGRAM_REPLY_CHAIN_MAX_DEPTH }, (_, i) => ({
124+
messageId: String(900 + i),
125+
sender: "Bob",
126+
body: `ancestor ${i}`,
127+
}));
128+
const context = await buildTelegramMessageContextForTest({
129+
message: plainMessage(2, "plain note\nquoting note"),
130+
replyChain: ancestry,
131+
options: {
132+
bufferedMessages: [plainMessage(1, "plain note"), quotingMessage(2, "quoting note")],
133+
},
134+
});
135+
136+
const body = context?.ctxPayload.Body ?? "";
137+
expect(body).toContain(QUOTED_LINE);
138+
expect(countReplyChainEntries(body)).toBeLessThanOrEqual(TELEGRAM_REPLY_CHAIN_MAX_DEPTH);
139+
});
140+
141+
// A debounce window has no per-item cap of its own. Keep the nearest targets,
142+
// not the oldest messages that happened to enter the window first.
143+
it("keeps the newest batch reply targets in nearest-first order", async () => {
144+
const burst = Array.from({ length: TELEGRAM_REPLY_CHAIN_MAX_DEPTH * 2 + 2 }, (_, i) =>
145+
quotingDistinctSource(i + 1),
146+
);
147+
const context = await buildTelegramMessageContextForTest({
148+
message: plainMessage(99, burst.map((entry) => entry.text).join("\n")),
149+
options: { bufferedMessages: burst },
150+
});
151+
152+
const body = context?.ctxPayload.Body ?? "";
153+
expect(Array.from(body.matchAll(/"distinct source \d+"/g), ([source]) => source)).toEqual([
154+
'"distinct source 10"',
155+
'"distinct source 9"',
156+
'"distinct source 8"',
157+
'"distinct source 7"',
158+
]);
159+
});
160+
});

0 commit comments

Comments
 (0)