@@ -19,6 +19,7 @@ import {
1919 readSessionMessagesAsync ,
2020 readSessionMessagesPageWithStatsAsync ,
2121 type ReadRecentSessionMessagesResult ,
22+ type SessionTranscriptReadScope ,
2223} from "../session-transcript-readers.js" ;
2324import 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+
207302export 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}
0 commit comments