Skip to content

Commit dc3eef6

Browse files
fix(telegram): rotate preamble only on a fresh resume, not every tool boundary
The eager tool-boundary rotation re-rendered the full cumulative snapshot into a new bubble at EVERY tool boundary, so multi-tool turns produced a staircase of duplicated messages (S1, S1+S2, S1+S2+S3). Partials are full cumulative snapshots (no delta), so each rotation after a reset re-printed everything. Defer the rotation to the next answer event (flag set at onToolStart) and rotate ONLY when the resumed snapshot does NOT continue the already-streamed text (a genuine preamble->answer transition; the fresh text is itself the un-shown delta). Ordinary continuation across multiple tool boundaries keeps editing one bubble — no staircase, no superset re-render. Compare against lastAnswerPartialText (not the send-lagged lastDeliveredText) so fast timing classifies correctly. Keeps the single preamble->tool->resume guarantee and the below-debounce no-spurious gate. Adds a staircase regression test (no sent message may be a superset re-render of another) that catches this class offline.
1 parent 8beba4e commit dc3eef6

2 files changed

Lines changed: 88 additions & 26 deletions

File tree

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

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4903,9 +4903,11 @@ describe("dispatchTelegramMessage draft streaming", () => {
49034903
const realDraft =
49044904
await vi.importActual<typeof import("./draft-stream.js")>("./draft-stream.js");
49054905
let nextMessageId = 500;
4906-
const sendRichMessage = vi.fn(async (_params: { rich_message?: { markdown?: string } }) => ({
4907-
message_id: nextMessageId++,
4908-
}));
4906+
const sendRichMessage = vi.fn(
4907+
async (_params: { rich_message?: { markdown?: string; html?: string } }) => ({
4908+
message_id: nextMessageId++,
4909+
}),
4910+
);
49094911
const editRichMessageText = vi.fn(async () => true);
49104912
const bot = {
49114913
api: {
@@ -4998,5 +5000,44 @@ describe("dispatchTelegramMessage draft streaming", () => {
49985000
spuriousPreamble: sentTexts.includes(SHORT),
49995001
}).toEqual({ sends: 1, edits: 0, spuriousPreamble: false });
50005002
});
5003+
5004+
// Regression for the eager-rotation staircase: a multi-tool turn streams
5005+
// cumulative full-snapshot partials with a tool boundary between each segment.
5006+
// No distinct sent message may be a superset re-render (prefix) of another —
5007+
// each tool boundary must NOT open a fresh bubble that re-prints prior content.
5008+
it("does not staircase: no sent message re-renders a previous one (multi-tool turn)", async () => {
5009+
const { bot, sendRichMessage } = await setupRealDraftStream();
5010+
dispatchReplyWithBufferedBlockDispatcher.mockImplementation(
5011+
async ({ dispatcherOptions, replyOptions }) => {
5012+
await replyOptions?.onAssistantMessageStart?.();
5013+
let cumulative = "";
5014+
for (let i = 0; i < 3; i += 1) {
5015+
const seg = `Segment ${i + 1}: distinct answer content number ${i + 1} here.`;
5016+
cumulative = cumulative ? `${cumulative} ${seg}` : seg;
5017+
await replyOptions?.onPartialReply?.({ text: cumulative });
5018+
if (i < 2) {
5019+
await replyOptions?.onToolStart?.({ name: "read_file", phase: "start" });
5020+
}
5021+
}
5022+
await dispatcherOptions.deliver({ text: cumulative }, { kind: "final" });
5023+
return { queuedFinal: true };
5024+
},
5025+
);
5026+
5027+
await dispatchWithContext({ context: createContext(), bot });
5028+
5029+
const sent = sendRichMessage.mock.calls.map(
5030+
(c) => c[0]?.rich_message?.html ?? c[0]?.rich_message?.markdown ?? "",
5031+
);
5032+
const supersetPairs: Array<[string, string]> = [];
5033+
for (let i = 0; i < sent.length; i += 1) {
5034+
for (let j = 0; j < sent.length; j += 1) {
5035+
if (i !== j && sent[j].length > sent[i].length && sent[j].startsWith(sent[i])) {
5036+
supersetPairs.push([sent[i], sent[j]]);
5037+
}
5038+
}
5039+
}
5040+
expect(supersetPairs).toEqual([]);
5041+
});
50015042
});
50025043
});

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

Lines changed: 44 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1183,25 +1183,27 @@ export const dispatchTelegramMessage = async ({
11831183
}
11841184
await rotateLaneForNewMessage(answerLane);
11851185
};
1186-
// A streamed answer preamble stays mutable until finalized. When a tool starts
1187-
// mid-stream and tool progress is suppressed (so prepareAnswerLaneForToolProgress
1188-
// never rotated), the post-tool answer text would keep editing the preamble
1189-
// bubble. Rotate on INTENT — a preamble partial was emitted (hasStreamedMessage)
1190-
// — not on send-ack. Under fast live timing the preamble's Bot API send is still
1191-
// in flight when the tool boundary fires, so its message id is not back yet;
1192-
// gating on stream.messageId() being a number (as a prior fix did) let the post-tool
1193-
// text edit the preamble bubble. rotateAnswerLaneForNewMessage -> rotateLaneForNewMessage
1194-
// awaits the in-flight send (loop.flush awaits the in-flight promise) before
1195-
// forceNewMessage(), so the preamble is always committed to its own message and the
1196-
// resumed text starts a fresh one. Defer to the tool-progress path when it already
1197-
// owns the rotation; skip when no preamble was emitted.
1198-
//
1199-
// Gate on send-dispatched, not just hasStreamedMessage: a preamble shorter than the
1200-
// preview debounce (minInitialChars) is suppressed and never sent. Rotating it here
1201-
// would stop()->flush it into a spurious standalone message. Rotate only when the
1202-
// send has landed (messageId is a number) or is in flight (sendMayHaveLanded); a
1203-
// never-attempted preamble stays pending so the resumed text remains one message.
1204-
const rotateInFlightAnswerPreambleForToolBoundary = async () => {
1186+
// A streamed answer preamble stays mutable until finalized. When a tool runs
1187+
// mid-stream and the answer resumes, decide rotation by comparing the resumed
1188+
// snapshot to what is already on screen:
1189+
// - FRESH resume (snapshot does NOT continue the shown text): a genuine
1190+
// preamble->answer transition. Rotate ONCE so the preamble is preserved (the
1191+
// original bug). The fresh snapshot is itself the un-shown delta — never a
1192+
// superset of the previous bubble.
1193+
// - CONTINUATION (snapshot starts with the shown text): ordinary streaming
1194+
// growth, including MULTIPLE tool boundaries in one turn. Do NOT rotate — keep
1195+
// editing the one bubble (no staircase, no cumulative re-render).
1196+
// The decision is deferred to the next answer event (flag set at onToolStart)
1197+
// because the resumed text is unknown at the boundary. Gate on send-dispatched so
1198+
// a below-debounce never-sent preamble (minInitialChars-suppressed) is not flushed
1199+
// into a spurious standalone message: rotate only when the send has landed
1200+
// (messageId) or is in flight (sendMayHaveLanded).
1201+
let toolBoundaryRotationPending = false;
1202+
const rotateAnswerLaneForFreshResume = async (resumedText: string): Promise<void> => {
1203+
if (!toolBoundaryRotationPending) {
1204+
return;
1205+
}
1206+
toolBoundaryRotationPending = false;
12051207
if (activeAnswerDraftIsToolProgressOnly) {
12061208
return;
12071209
}
@@ -1214,6 +1216,14 @@ export const dispatchTelegramMessage = async ({
12141216
if (!sendDispatched) {
12151217
return;
12161218
}
1219+
// Compare against lastAnswerPartialText (the cumulative we last streamed), not
1220+
// stream.lastDeliveredText(): under fast timing the send is still in flight and
1221+
// lastDeliveredText() lags (empty), which would misclassify a continuation as
1222+
// fresh and re-staircase.
1223+
const shownText = lastAnswerPartialText.trimEnd();
1224+
if (shownText && resumedText.trimEnd().startsWith(shownText)) {
1225+
return;
1226+
}
12171227
await rotateAnswerLaneForNewMessage();
12181228
};
12191229
const rotateAnswerLaneAfterToolProgress = async () => {
@@ -1395,6 +1405,10 @@ export const dispatchTelegramMessage = async ({
13951405
const split = splitTextIntoLaneSegments(update, isReasoning);
13961406
for (const segment of split.segments) {
13971407
if (segment.lane === "answer") {
1408+
const resumed = resolveDraftPartialText(lastAnswerPartialText, segment.update);
1409+
if (resumed) {
1410+
await rotateAnswerLaneForFreshResume(resumed);
1411+
}
13981412
await prepareAnswerLaneForText();
13991413
}
14001414
if (segment.lane === "reasoning") {
@@ -2355,6 +2369,10 @@ export const dispatchTelegramMessage = async ({
23552369
enqueueDraftLaneEvent(async () => {
23562370
reasoningStepState.resetForNextStep();
23572371
finalAnswerDelivered = false;
2372+
// A genuine new assistant message owns its own rotation here;
2373+
// drop any deferred tool-boundary rotation so it does not
2374+
// double-fire on the next partial.
2375+
toolBoundaryRotationPending = false;
23582376
if (streamMode !== "progress") {
23592377
resetProgressDraftState();
23602378
}
@@ -2406,10 +2424,13 @@ export const dispatchTelegramMessage = async ({
24062424
await statusReactionController.setTool(toolName);
24072425
}
24082426
await progressPromise;
2409-
// Ordered after pending preamble partials so the rotation
2410-
// sees the streamed message; no-op when progress already
2411-
// rotated or nothing was sent.
2412-
await enqueueDraftLaneEvent(rotateInFlightAnswerPreambleForToolBoundary);
2427+
// Defer the preamble->answer rotation to the next answer event so
2428+
// we can tell a fresh resume (rotate, preserve preamble) from an
2429+
// ordinary cumulative continuation across multiple tool boundaries
2430+
// (do not rotate -> no staircase). Ordered after pending partials.
2431+
await enqueueDraftLaneEvent(async () => {
2432+
toolBoundaryRotationPending = true;
2433+
});
24132434
},
24142435
onItemEvent: async (payload) => {
24152436
if (payload.kind === "preamble") {

0 commit comments

Comments
 (0)