Skip to content

Commit 738813b

Browse files
committed
fix(telegram): add appendMode to preserve message history in streaming updates
- Add appendMode parameter to createTelegramDraftStream() - When enabled, accumulates text instead of replacing on edit - Preserves full conversation history for long-running tasks - Add setAppendMode() method for dynamic mode switching - Add comprehensive tests for append mode behavior Fixes #96306
1 parent a96418c commit 738813b

2 files changed

Lines changed: 194 additions & 3 deletions

File tree

‎extensions/telegram/src/draft-stream.test.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,4 +1016,139 @@ describe("draft stream initial message debounce", () => {
10161016
expectPreviewSend(api, "Hi");
10171017
});
10181018
});
1019+
1020+
describe("appendMode - preserve message history", () => {
1021+
it("accumulates text in append mode instead of replacing", async () => {
1022+
const api = createMockDraftApi();
1023+
const stream = createTelegramDraftStream({
1024+
api: api as unknown as Bot["api"],
1025+
chatId: 123,
1026+
appendMode: true,
1027+
throttleMs: 50, // Fast throttle for testing
1028+
});
1029+
1030+
// First update - should send new message
1031+
stream.update("Step 1: Starting...");
1032+
await stream.flush();
1033+
1034+
expect(api.sendMessage).toHaveBeenCalledTimes(1);
1035+
expectPreviewSend(api, "Step 1: Starting...");
1036+
1037+
// Second update - should edit with accumulated text
1038+
stream.update("Step 2: Processing...");
1039+
await stream.flush();
1040+
1041+
expect(api.editMessageText).toHaveBeenCalledTimes(1);
1042+
// Should contain both steps
1043+
expect(api.editMessageText).toHaveBeenCalledWith(
1044+
123,
1045+
17,
1046+
"Step 1: Starting...\nStep 2: Processing...",
1047+
);
1048+
1049+
// Third update - should continue accumulating
1050+
stream.update("Step 3: Done!");
1051+
await stream.flush();
1052+
1053+
expect(api.editMessageText).toHaveBeenCalledTimes(2);
1054+
expect(api.editMessageText).toHaveBeenLastCalledWith(
1055+
123,
1056+
17,
1057+
"Step 1: Starting...\nStep 2: Processing...\nStep 3: Done!",
1058+
);
1059+
});
1060+
1061+
it("does not accumulate text when appendMode is false (default)", async () => {
1062+
const api = createMockDraftApi();
1063+
const stream = createTelegramDraftStream({
1064+
api: api as unknown as Bot["api"],
1065+
chatId: 123,
1066+
appendMode: false, // Explicitly disabled
1067+
throttleMs: 50,
1068+
});
1069+
1070+
stream.update("Step 1");
1071+
await stream.flush();
1072+
1073+
stream.update("Step 2");
1074+
await stream.flush();
1075+
1076+
// Should only have the latest text, not accumulated
1077+
expect(api.editMessageText).toHaveBeenCalledWith(123, 17, "Step 2");
1078+
});
1079+
1080+
it("handles rich messages in append mode", async () => {
1081+
const api = createMockDraftApi();
1082+
const renderText = vi.fn((text) => ({
1083+
text: `<b>${text}</b>`,
1084+
parseMode: "HTML" as const,
1085+
}));
1086+
1087+
const stream = createTelegramDraftStream({
1088+
api: api as unknown as Bot["api"],
1089+
chatId: 123,
1090+
appendMode: true,
1091+
renderText,
1092+
throttleMs: 50,
1093+
});
1094+
1095+
stream.update("First");
1096+
await stream.flush();
1097+
1098+
stream.update("Second");
1099+
await stream.flush();
1100+
1101+
// Check that edits were called (not just sends)
1102+
expect(api.editMessageText).toHaveBeenCalled();
1103+
1104+
// Verify the second call contains both texts
1105+
const secondCallArgs = api.editMessageText.mock.calls[0];
1106+
const editText = secondCallArgs?.[2];
1107+
expect(editText).toBeDefined();
1108+
// The rendered text should contain HTML formatting
1109+
expect(editText).toMatch(/<b>/);
1110+
});
1111+
1112+
it("respects maxChars limit in append mode", async () => {
1113+
const api = createMockDraftApi();
1114+
const stream = createTelegramDraftStream({
1115+
api: api as unknown as Bot["api"],
1116+
chatId: 123,
1117+
appendMode: true,
1118+
maxChars: 50, // Small limit for testing
1119+
throttleMs: 50,
1120+
});
1121+
1122+
// Send a long message that exceeds limit
1123+
const longText = "A".repeat(60);
1124+
stream.update(longText);
1125+
await stream.flush();
1126+
1127+
// Should still send but may be truncated or split
1128+
expect(api.sendMessage).toHaveBeenCalled();
1129+
});
1130+
1131+
it("clears accumulated text on forceNewMessage()", async () => {
1132+
const api = createMockDraftApi();
1133+
const stream = createTelegramDraftStream({
1134+
api: api as unknown as Bot["api"],
1135+
chatId: 123,
1136+
appendMode: true,
1137+
throttleMs: 50,
1138+
});
1139+
1140+
stream.update("Part 1");
1141+
await stream.flush();
1142+
1143+
// Force new message - should reset accumulation
1144+
stream.forceNewMessage();
1145+
1146+
stream.update("Fresh start");
1147+
await stream.flush();
1148+
1149+
// Should send a new message, not edit
1150+
expect(api.sendMessage).toHaveBeenCalledTimes(2);
1151+
expectNthPreviewSend(api, 2, "Fresh start");
1152+
});
1153+
});
10191154
});

‎extensions/telegram/src/draft-stream.ts‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ export type TelegramDraftStream = {
5555
forceNewMessage: () => void;
5656
/** True when a preview sendMessage was attempted but the response was lost. */
5757
sendMayHaveLanded?: () => boolean;
58+
/** Append mode: accumulate text instead of replacing on edit */
59+
setAppendMode?: (append: boolean) => void;
5860
};
5961

6062
export type TelegramDraftPreview = {
@@ -188,6 +190,8 @@ export function createTelegramDraftStream(params: {
188190
onSupersededPreview?: (preview: SupersededTelegramPreview) => void;
189191
log?: (message: string) => void;
190192
warn?: (message: string) => void;
193+
/** Append mode: accumulate text instead of replacing on edit (preserves history) */
194+
appendMode?: boolean;
191195
}): TelegramDraftStream {
192196
const richMessages = params.richMessages === true;
193197
const transportLimit = richMessages ? TELEGRAM_RICH_TEXT_LIMIT : TELEGRAM_STREAM_MAX_CHARS;
@@ -218,6 +222,7 @@ export function createTelegramDraftStream(params: {
218222
}
219223
: (threadParams ?? {});
220224

225+
let appendMode = params.appendMode === true;
221226
const streamState = { stopped: false, final: false };
222227
let messageSendAttempted = false;
223228
let suspendedUntilMs = 0;
@@ -231,6 +236,7 @@ export function createTelegramDraftStream(params: {
231236
let previewRevision = 0;
232237
let generation = 0;
233238
let deliveredTextOffset = 0;
239+
let accumulatedText = ""; // For append mode: stores full text history
234240
type PreviewSendParams = {
235241
preview: TelegramDraftPreview;
236242
sendGeneration: number;
@@ -267,15 +273,38 @@ export function createTelegramDraftStream(params: {
267273
}: PreviewSendParams): Promise<boolean> => {
268274
if (typeof streamMessageId === "number") {
269275
streamVisibleSinceMs ??= Date.now();
276+
277+
// In append mode, accumulate text and edit with full history
278+
let textToEdit = preview.text;
279+
if (appendMode) {
280+
// Add separator between old and new content
281+
if (accumulatedText) {
282+
accumulatedText = accumulatedText.trimEnd();
283+
if (accumulatedText && !accumulatedText.endsWith("\n")) {
284+
accumulatedText += "\n";
285+
}
286+
textToEdit = accumulatedText + preview.text;
287+
} else {
288+
// First edit in append mode - just use the preview text
289+
textToEdit = preview.text;
290+
}
291+
}
292+
270293
if (richMessages) {
271294
await getTelegramRichRawApi(params.api).editMessageText({
272295
chat_id: chatId,
273296
message_id: streamMessageId,
274-
rich_message: preview.richMessage ?? buildTelegramRichMarkdown(preview.text),
297+
rich_message: preview.richMessage ?? buildTelegramRichMarkdown(textToEdit),
275298
});
299+
if (appendMode) {
300+
accumulatedText = textToEdit;
301+
}
276302
return true;
277303
}
278-
const transportPreview = normalizeTelegramDraftTransportPreview(preview);
304+
const transportPreview = normalizeTelegramDraftTransportPreview({
305+
...preview,
306+
text: textToEdit,
307+
});
279308
if (transportPreview.parseMode === "HTML") {
280309
try {
281310
await params.api.editMessageText(chatId, streamMessageId, transportPreview.text, {
@@ -290,6 +319,9 @@ export function createTelegramDraftStream(params: {
290319
} else {
291320
await params.api.editMessageText(chatId, streamMessageId, transportPreview.text);
292321
}
322+
if (appendMode) {
323+
accumulatedText = textToEdit;
324+
}
293325
return true;
294326
}
295327
messageSendAttempted = true;
@@ -317,10 +349,18 @@ export function createTelegramDraftStream(params: {
317349
visibleSinceMs,
318350
retain: true,
319351
});
352+
// In append mode, track the initial text even for superseded messages
353+
if (appendMode && !accumulatedText) {
354+
accumulatedText = preview.text;
355+
}
320356
return true;
321357
}
322358
streamMessageId = normalizedMessageId;
323359
streamVisibleSinceMs = visibleSinceMs;
360+
// In append mode, initialize accumulatedText on first send
361+
if (appendMode && !accumulatedText) {
362+
accumulatedText = preview.text;
363+
}
324364
return true;
325365
};
326366
const stopOversizedPreview = (payloadLength: number): false => {
@@ -554,12 +594,27 @@ export function createTelegramDraftStream(params: {
554594
resetStreamToNewMessage();
555595
};
556596

597+
const setAppendMode = (append: boolean) => {
598+
// When enabling append mode, preserve current text as the starting point
599+
if (append && !appendMode) {
600+
appendMode = true;
601+
accumulatedText = lastDeliveredText || "";
602+
} else if (!append && appendMode) {
603+
appendMode = false;
604+
// When disabling append mode, clear accumulated text
605+
accumulatedText = "";
606+
}
607+
params.log?.(`telegram stream setAppendMode(${append}) called`);
608+
};
609+
557610
const materialize = async (): Promise<number | undefined> => {
558611
await stop();
559612
return streamMessageId;
560613
};
561614

562-
params.log?.(`telegram stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
615+
params.log?.(
616+
`telegram stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs}${appendMode ? ", appendMode=true" : ""})`,
617+
);
563618

564619
return {
565620
update,
@@ -574,6 +629,7 @@ export function createTelegramDraftStream(params: {
574629
discard,
575630
materialize,
576631
forceNewMessage,
632+
setAppendMode,
577633
sendMayHaveLanded: () => messageSendAttempted && typeof streamMessageId !== "number",
578634
};
579635
}

0 commit comments

Comments
 (0)