Skip to content

Commit 71cf5cf

Browse files
fix(gateway): keep chat history visible past a silent raw tail (#121337)
The bounded raw tail window that chat.history reads can be filled entirely by records that project to nothing (tool traffic, hidden memory-flush prompts, dropped silent turns, or one oversized record). The first page then came back empty even though the branch still held visible turns, and every snapshot client rebuilds destructively from that page, so the TUI wiped a conversation the transcript still had. Scan older transcript chunks when the first page projects to no display rows, bounded in records and bytes so a pathological transcript cannot turn the tail read into a full scan, project each chunk beside the newer records it borders so paired rows survive a chunk boundary, and report the scanned record count so older paging still resumes strictly before the served page.
1 parent 97bd54d commit 71cf5cf

2 files changed

Lines changed: 210 additions & 24 deletions

File tree

‎src/gateway/server-methods/chat-history-pages.ts‎

Lines changed: 129 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
readSessionMessagesAsync,
2020
readSessionMessagesPageWithStatsAsync,
2121
type ReadRecentSessionMessagesResult,
22+
type SessionTranscriptReadScope,
2223
} from "../session-transcript-readers.js";
2324
import type { loadSessionEntry } from "../session-utils.js";
2425

@@ -204,6 +205,100 @@ function dropLocalHistoryOverreadContextMessage(
204205
return [...messages.slice(0, index), ...messages.slice(index + 1)];
205206
}
206207

208+
// A silent tail can outrun the bounded raw window: tool traffic, hidden
209+
// memory-flush prompts, and dropped silent turns all consume raw records
210+
// without producing a display row, so the newest window can project to nothing
211+
// while visible history is still on the branch. Snapshot clients rebuild
212+
// destructively from a first page, so returning that empty page erases a
213+
// rendered conversation the transcript still holds. Scan older pages until a
214+
// display row appears, bounded so a pathological transcript cannot turn the
215+
// tail read into a full scan.
216+
const SILENT_CHAT_HISTORY_TAIL_SCAN_MAX_MESSAGES = 8_000;
217+
// Chunk size stays independent of the requested display limit: a `limit: 1`
218+
// request must not turn the scan into one transcript read per raw record. Pages
219+
// are contiguous and released between iterations, and the chunk stays below the
220+
// record count an explicit offset page already materializes, so peak scan memory
221+
// never exceeds what one ordinary history page costs. A byte-budgeted read is
222+
// deliberately not used here: it drops oversized records from the middle of a
223+
// window, which would punch holes in the cursor and hide the oversized-message
224+
// placeholder the handler would otherwise render. Accepted tradeoff: a chunk is
225+
// materialized before its bytes can be counted, so the walk can overshoot its
226+
// budget by one page. That page is smaller than the one every explicit offset
227+
// request already reads, and closing the gap would need a stop-at-budget
228+
// contiguous reader that does not exist yet.
229+
const SILENT_CHAT_HISTORY_TAIL_SCAN_CHUNK_MESSAGES = 100;
230+
231+
/** Keeps a first history page displayable by scanning past an all-silent raw tail. */
232+
async function resolveDisplayableChatHistoryTail(params: {
233+
entry: ReturnType<typeof loadSessionEntry>["entry"];
234+
readScope: SessionTranscriptReadScope;
235+
effectiveMaxChars: number;
236+
max: number;
237+
maxBytes: number;
238+
projected: unknown[];
239+
rawMessages: unknown[];
240+
rawPageMessages: number;
241+
totalMessages: number;
242+
}): Promise<{ messages: unknown[]; rawPageMessages: number }> {
243+
const unchanged = { messages: params.projected, rawPageMessages: params.rawPageMessages };
244+
if (params.projected.length > 0 || params.totalMessages <= params.rawPageMessages) {
245+
return unchanged;
246+
}
247+
const sessionStartedAt =
248+
typeof params.entry?.sessionStartedAt === "number" ? params.entry.sessionStartedAt : undefined;
249+
const scanLimit = params.rawPageMessages + SILENT_CHAT_HISTORY_TAIL_SCAN_MAX_MESSAGES;
250+
let scanned = params.rawPageMessages;
251+
// Record count alone does not bound a walk over large tool results, and the
252+
// reader cannot bound it either: a byte-budgeted page skips an oversized
253+
// record mid-window, which would strand it and its placeholder. Budget the
254+
// whole walk instead, at the payload one history response may already return.
255+
let scannedBytes = 0;
256+
// Projection pairs records across turns (message-tool sends and their
257+
// results, turn boundaries), so each chunk is projected together with the
258+
// already-read newer records it borders. Only the neighbour is carried, which
259+
// keeps the working set at two chunks plus the tail window.
260+
let newerRawMessages = params.rawMessages;
261+
while (scanned < params.totalMessages && scanned < scanLimit) {
262+
const page = await readSessionMessagesPageWithStatsAsync(params.readScope, {
263+
offset: scanned,
264+
maxMessages: SILENT_CHAT_HISTORY_TAIL_SCAN_CHUNK_MESSAGES + 1,
265+
allowResetArchiveFallback: true,
266+
});
267+
if (page.messages.length === 0) {
268+
return unchanged;
269+
}
270+
// The extra oldest record only supplies pair-filter and turn-boundary
271+
// context. Without it a chunk boundary between a stale announce and its
272+
// reply would leak the reply that the tail read hides. Each chunk's context
273+
// record is the newest record of the next chunk, so this one overread also
274+
// covers every junction the walk creates, including tail-to-first-chunk.
275+
const contextMessage =
276+
page.messages.length > SILENT_CHAT_HISTORY_TAIL_SCAN_CHUNK_MESSAGES
277+
? page.messages[0]
278+
: undefined;
279+
scanned += page.messages.length - (contextMessage === undefined ? 0 : 1);
280+
const chunkMessages = dropLocalHistoryOverreadContextMessage(
281+
dropPreSessionStartAnnouncePairs(page.messages, sessionStartedAt),
282+
contextMessage,
283+
);
284+
const projected = projectRecentChatDisplayMessages([...chunkMessages, ...newerRawMessages], {
285+
maxChars: params.effectiveMaxChars,
286+
maxMessages: params.max,
287+
resolveCurrentUserProfileDisplay,
288+
turnBoundaryPending: isHeartbeatHistoryTurnBoundaryMessage(contextMessage),
289+
});
290+
if (projected.length > 0) {
291+
return { messages: projected, rawPageMessages: scanned };
292+
}
293+
scannedBytes += Buffer.byteLength(JSON.stringify(page.messages), "utf8");
294+
if (scannedBytes >= params.maxBytes) {
295+
return unchanged;
296+
}
297+
newerRawMessages = chunkMessages;
298+
}
299+
return unchanged;
300+
}
301+
207302
export async function readChatHistoryPage(params: {
208303
entry: ReturnType<typeof loadSessionEntry>["entry"];
209304
provider: string | undefined;
@@ -338,23 +433,35 @@ export async function readChatHistoryPage(params: {
338433
: isTailPage
339434
? projected
340435
: capOffsetChatHistoryProjectedMessages(projected, max);
341-
const normalized = augmentChatHistoryWithCanvasBlocks(windowed);
342436
if (messageId) {
343437
// Numeric offsets do not encode the selected historical transcript source.
344-
return { messages: normalized };
438+
return { messages: augmentChatHistoryWithCanvasBlocks(windowed) };
345439
}
440+
const tail = isTailPage
441+
? await resolveDisplayableChatHistoryTail({
442+
entry,
443+
readScope,
444+
effectiveMaxChars,
445+
max,
446+
maxBytes: maxHistoryBytes,
447+
projected: windowed,
448+
rawMessages: recencyFilteredMessages,
449+
rawPageMessages,
450+
totalMessages: readPage.totalMessages,
451+
})
452+
: { messages: windowed, rawPageMessages };
346453
return {
347454
...(isTailPage
348455
? {
349456
activeLeafEntryId: resolveChatHistoryActiveLeafEntryId(readPage),
350457
}
351458
: {}),
352-
messages: normalized,
459+
messages: augmentChatHistoryWithCanvasBlocks(tail.messages),
353460
responseOffset: pageOffset,
354461
pagination: {
355462
offset: pageOffset,
356463
totalMessages: readPage.totalMessages,
357-
rawPageMessages,
464+
rawPageMessages: tail.rawPageMessages,
358465
},
359466
};
360467
}
@@ -447,18 +554,29 @@ export async function readChatHistoryPage(params: {
447554
resolveCurrentUserProfileDisplay,
448555
turnBoundaryPending,
449556
});
557+
const tail = await resolveDisplayableChatHistoryTail({
558+
entry,
559+
readScope,
560+
effectiveMaxChars,
561+
max,
562+
maxBytes: maxHistoryBytes,
563+
projected: displayMessages,
564+
rawMessages: recencyFilteredMessages,
565+
// The extra record supplies pair-filter context; it was not returned and
566+
// must remain reachable by the next strictly-older page.
567+
rawPageMessages: Math.min(
568+
rawHistoryWindow.maxMessages,
569+
Math.max(readPage.messages.length, readPage.totalMessages > 0 ? 1 : 0),
570+
),
571+
totalMessages: readPage.totalMessages,
572+
});
450573
return {
451574
activeLeafEntryId,
452-
messages: augmentChatHistoryWithCanvasBlocks(displayMessages),
575+
messages: augmentChatHistoryWithCanvasBlocks(tail.messages),
453576
pagination: {
454577
offset: 0,
455578
totalMessages: readPage.totalMessages,
456-
// The extra record supplies pair-filter context; it was not returned and
457-
// must remain reachable by the next strictly-older page.
458-
rawPageMessages: Math.min(
459-
rawHistoryWindow.maxMessages,
460-
Math.max(readPage.messages.length, readPage.totalMessages > 0 ? 1 : 0),
461-
),
579+
rawPageMessages: tail.rawPageMessages,
462580
},
463581
};
464582
}

‎src/gateway/server.chat.gateway-server-chat-b.test.ts‎

Lines changed: 81 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5269,7 +5269,7 @@ describe("gateway server chat", () => {
52695269
});
52705270
});
52715271

5272-
test("chat.history advances past an oversized newest record when the tail parses empty", async () => {
5272+
test("chat.history serves older history past an oversized newest record", async () => {
52735273
await withGatewayChatHarness(async ({ ws, createSessionDir }) => {
52745274
await prepareMainHistoryHarness({ ws, createSessionDir });
52755275
const historyMaxBytes = getMaxChatHistoryMessagesBytes();
@@ -5289,18 +5289,9 @@ describe("gateway server chat", () => {
52895289
hasMore?: boolean;
52905290
}>(ws, "chat.history", makeMainSessionParams({ limit: 1 }));
52915291
expect(firstPage.ok).toBe(true);
5292-
expect(firstPage.payload?.messages).toEqual([]);
5293-
expect(firstPage.payload?.hasMore).toBe(true);
5294-
expect(firstPage.payload?.nextOffset).toBe(1);
5295-
5296-
const olderPage = await rpcReq<{ messages?: unknown[]; hasMore?: boolean }>(
5297-
ws,
5298-
"chat.history",
5299-
makeMainSessionParams({ limit: 1, offset: firstPage.payload?.nextOffset }),
5300-
);
5301-
expect(olderPage.ok).toBe(true);
5302-
expect(JSON.stringify(olderPage.payload?.messages)).toContain("reachable older message");
5303-
expect(olderPage.payload?.hasMore).toBe(false);
5292+
expect(JSON.stringify(firstPage.payload?.messages)).toContain("reachable older message");
5293+
expect(firstPage.payload?.hasMore).toBe(false);
5294+
expect(firstPage.payload?.nextOffset).toBeUndefined();
53045295
});
53055296
});
53065297

@@ -5810,6 +5801,83 @@ describe("gateway server chat", () => {
58105801
});
58115802
});
58125803

5804+
// A silent tail longer than the bounded raw window used to project to an empty
5805+
// first page while the branch still held visible turns, and snapshot clients
5806+
// erase their rendered conversation when that page comes back empty.
5807+
test.each([
5808+
{ name: "tail request", params: { limit: 2, maxChars: 100 } },
5809+
{ name: "explicit first page", params: { limit: 2, maxChars: 100, offset: 0 } },
5810+
])(
5811+
"chat.history recovers visible history when the raw tail window is entirely silent ($name)",
5812+
async ({ params }) => {
5813+
await withGatewayChatHarness(async ({ ws, createSessionDir }) => {
5814+
await prepareMainHistoryHarness({ ws, createSessionDir });
5815+
// limit 2 reads at most 2 * 20 + 20 raw records, so 80 silent records
5816+
// push every visible turn out of the tail window.
5817+
const silentTail = Array.from({ length: 80 }, (_, index) =>
5818+
createTextTranscriptEvent("assistant", "NO_REPLY", {
5819+
timestamp: Date.now() + index + 2,
5820+
}),
5821+
);
5822+
await writeMainSessionTranscript([
5823+
createTextTranscriptEvent("user", "visible question", { timestamp: Date.now() }),
5824+
createTextTranscriptEvent("assistant", "visible answer", { timestamp: Date.now() + 1 }),
5825+
...silentTail,
5826+
]);
5827+
5828+
const page = await rpcReq<{ messages?: unknown[]; hasMore?: boolean }>(
5829+
ws,
5830+
"chat.history",
5831+
makeMainSessionParams(params),
5832+
);
5833+
expect(page.ok).toBe(true);
5834+
expect(JSON.stringify(page.payload?.messages)).toContain("visible question");
5835+
expect(JSON.stringify(page.payload?.messages)).toContain("visible answer");
5836+
expect(JSON.stringify(page.payload?.messages)).not.toContain("NO_REPLY");
5837+
expect(page.payload?.hasMore).toBe(false);
5838+
});
5839+
},
5840+
);
5841+
5842+
test("chat.history overreads context while scanning past a silent tail", async () => {
5843+
await withGatewayChatHarness(async ({ ws, createSessionDir }) => {
5844+
await prepareMainHistoryHarness({ ws, createSessionDir });
5845+
const sessionStartedAt = Date.now();
5846+
await writeSessionStore({
5847+
entries: {
5848+
main: { sessionId: "sess-main", updatedAt: Date.now(), sessionStartedAt },
5849+
},
5850+
});
5851+
// limit 2 reads a 60-record tail, and the scan then walks 100-record
5852+
// chunks, so record 239 of 400 is the first chunk's context boundary.
5853+
const silent = (index: number, count: number) =>
5854+
Array.from({ length: count }, (_, offset) =>
5855+
createTextTranscriptEvent("assistant", "NO_REPLY", {
5856+
timestamp: sessionStartedAt + index + offset,
5857+
}),
5858+
);
5859+
await writeMainSessionTranscript([
5860+
createTextTranscriptEvent("user", "oldest visible question", {
5861+
timestamp: sessionStartedAt + 1,
5862+
}),
5863+
...silent(2, 238),
5864+
createTextTranscriptEvent("user", "stale announce", {
5865+
timestamp: sessionStartedAt - 2_000,
5866+
message: { provenance: { kind: "inter_session", sourceTool: "subagent_announce" } },
5867+
}),
5868+
createTextTranscriptEvent("assistant", "stale announce reply", {
5869+
timestamp: sessionStartedAt - 1_000,
5870+
}),
5871+
...silent(300, 159),
5872+
]);
5873+
5874+
const messages = await fetchHistoryMessages(ws, { limit: 2, maxChars: 100 });
5875+
const serialized = JSON.stringify(messages);
5876+
expect(serialized).toContain("oldest visible question");
5877+
expect(serialized).not.toContain("stale announce reply");
5878+
});
5879+
});
5880+
58135881
test("chat.history returns retryable unavailable while a dirty projection rebuilds", async () => {
58145882
await withGatewayChatHarness(async ({ ws, createSessionDir }) => {
58155883
const sessionDir = await prepareMainHistoryHarness({ ws, createSessionDir });

0 commit comments

Comments
 (0)