The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): the store releases paged-through history instead of holding it for the window's lifetime (#77311)
kshitijk4poor14b432744574
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 85822116dbb..4bba263587a 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -80,6 +80,7 @@ import {transcriptBackfillAvailable} from './transcript-backfill'import { advanceSessionTranscriptWindow, type SessionWindowMemo } from './transcript-window'+import { useTranscriptRetention } from './use-transcript-retention'interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {gateway: HermesGateway | null@@ -325,6 +326,17 @@ export function ChatRuntimeBoundary({}, [messages, windowPages])const currentMessages = history.page?.messages ?? windowedMessages+ // Release the store's paged-through history (persisted rows older than the+ // window) instead of retaining it for the window's lifetime (#77311). A+ // static history page is not the live store, and neither is a suppressed+ // transcript, so both opt out.+ useTranscriptRetention({+ anchorId: windowed ? windowedMessages[0]?.id ?? null : null,+ enabled: !suppressMessages && !history.page,+ profile: tailProfile,+ runtimeId,+ storedSessionId: storedId+ })const runtimeMessageRepository = useRuntimeMessageRepository(currentMessages)// Subscribed (not read imperatively) so the "Show earlier" affordance// appears/retires as tail hydrations and backfill pages record their state.diff --git a/apps/desktop/src/app/chat/transcript-retention.test.ts b/apps/desktop/src/app/chat/transcript-retention.test.tsnew file mode 100644index 00000000000..9ce1fc0a504--- /dev/null+++ b/apps/desktop/src/app/chat/transcript-retention.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from 'vitest'++import type { ChatMessage } from '@/lib/chat-messages'+import { messageStoreWeight, RENDER_WEIGHT_CHARS } from '@/lib/render-weight'++import { boundRetainedTranscript, TRANSCRIPT_RETAIN_SLACK } from './transcript-retention'++interface RowOptions {+ group?: string+ /** Persisted rows carry the store's only durable handle back to the backend. */+ persisted?: boolean+ textUnits?: number+}++const row = (index: number, options: RowOptions = {}): ChatMessage => {+ const { group, persisted = true, textUnits = 1 } = options++ return {+ ...(group ? { branchGroupId: group } : {}),+ id: `m${index}`,+ parts: [{ type: 'text', text: 'x'.repeat(RENDER_WEIGHT_CHARS * textUnits) }],+ role: 'assistant',+ ...(persisted ? { rowId: index + 1 } : {})+ }+}++const transcript = (count: number, each: (index: number) => ChatMessage = index => row(index)): ChatMessage[] =>+ Array.from({ length: count }, (_, index) => each(index))++/** Rows the slack buys behind the window, at the weight every `heavy` row carries. */+const slackRows = (sample: ChatMessage): number =>+ Math.ceil(TRANSCRIPT_RETAIN_SLACK / messageStoreWeight(sample.parts))++const heavy = (index: number) => row(index, { textUnits: 100 })++describe('boundRetainedTranscript', () => {+ it('releases the persisted rows older than the window and its slack', () => {+ const messages = transcript(60, heavy)+ const anchor = messages[40].id+ const keep = slackRows(messages[40])++ const retention = boundRetainedTranscript(messages, anchor)++ expect(retention.releasedRows).toBe(40 - keep)+ expect(retention.messages[0].id).toBe(`m${40 - keep}`)+ expect(retention.retainedPersistedRows).toBe(messages.length - retention.releasedRows)+ expect(retention.messages).toHaveLength(messages.length - retention.releasedRows)+ })++ it('keeps a fixed amount of history behind the window, however long the session is', () => {+ const short = transcript(60, heavy)+ const long = transcript(600, heavy)+ const shortRetention = boundRetainedTranscript(short, short[40].id)+ const longRetention = boundRetainedTranscript(long, long[560].id)++ const behind = (retention: typeof shortRetention, anchorId: string) =>+ retention.messages.findIndex(message => message.id === anchorId)++ // The window itself holds different amounts here; what must not grow with+ // the session is the history retained BEHIND it.+ expect(behind(longRetention, long[560].id)).toBe(behind(shortRetention, short[40].id))+ expect(behind(longRetention, long[560].id)).toBeLessThanOrEqual(slackRows(long[560]))++ // ...and the longer session releases proportionally more rows.+ expect(longRetention.releasedRows).toBeGreaterThan(shortRetention.releasedRows)+ expect(longRetention.messages.length).toBeLessThan(long.length / 2)+ })++ it('leaves the transcript whole when a released row cannot be fetched back', () => {+ // Rows 27-29 were never persisted: releasing the prefix around them would+ // drop content nothing can restore, so nothing is released at all.+ const messages = transcript(60, index =>+ index >= 27 && index <= 29 ? row(index, { persisted: false, textUnits: 100 }) : heavy(index)+ )++ const retention = boundRetainedTranscript(messages, messages[40].id)++ expect(retention.messages).toBe(messages)+ expect(retention.releasedRows).toBe(0)+ })++ it('does not split an assistant branch group', () => {+ // The slack boundary lands inside one three-message branch group; keeping+ // the whole group is what stops a branch being re-parented onto a fork+ // point that is no longer in the store.+ const messages = transcript(60, index => row(index, { group: index >= 26 && index <= 28 ? 'g1' : undefined, textUnits: 100 }))+ const keep = slackRows(messages[40])++ const retention = boundRetainedTranscript(messages, messages[40].id)++ expect(40 - keep).toBeGreaterThan(25)+ expect(40 - keep).toBeLessThanOrEqual(28)+ expect(retention.messages.filter(message => message.branchGroupId === 'g1')).toHaveLength(3)+ expect(retention.messages[0].id).toBe('m26')+ })++ it('returns the store array untouched when nothing precedes the window', () => {+ const messages = transcript(30, heavy)++ for (const anchor of [null, messages[0].id]) {+ const retention = boundRetainedTranscript(messages, anchor)++ expect(retention.messages).toBe(messages)+ expect(retention.releasedRows).toBe(0)+ expect(retention.retainedPersistedRows).toBe(30)+ }+ })++ it('returns the store array untouched when the retained rows carry no durable id', () => {+ // Offset bookkeeping is measured from persisted rows; without one in the+ // retained slice there is nothing to re-fetch against.+ const messages = transcript(30, index => row(index, { persisted: index >= 20, textUnits: 100 }))++ const retention = boundRetainedTranscript(messages, messages[25].id)++ expect(retention.messages).toBe(messages)+ expect(retention.releasedRows).toBe(0)+ })+})diff --git a/apps/desktop/src/app/chat/transcript-retention.ts b/apps/desktop/src/app/chat/transcript-retention.tsnew file mode 100644index 00000000000..03e13219c33--- /dev/null+++ b/apps/desktop/src/app/chat/transcript-retention.ts@@ -0,0 +1,134 @@+/**+ * BOUND THE RETAINED TRANSCRIPT — release paged-through history from the store.+ *+ * `transcript-window` bounds what REACHES assistant-ui, but the session store+ * underneath it keeps every message it ever materialized: the tail hydration,+ * every page "Show earlier" fetched, and every turn this window streamed. A+ * long-lived window therefore grows with session content forever — measured as+ * the renderer's dominant footprint on #77311 — and the payload is what costs:+ * `ChatMessage.parts` carries the rendered tool output, file previews, diffs and+ * images for each of those rows.+ *+ * The rows in question are already off the user's screen (older than the+ * window's own start) and already on the backend (they are persisted with a+ * `rowId`), so holding them is pure duplication. This module decides the cut:+ * keep the live window plus one weight page of slack so a single "Show earlier"+ * still pages through memory, and release everything older. Re-hydration is the+ * existing older-page backfill — the caller rewinds the session's+ * `transcript-tail` bookkeeping so `expandWindow` fetches the released rows+ * again instead of treating the transcript as fully materialized+ * (see app/chat/transcript-backfill).+ *+ * Invariants:+ * - Never inside the window: the cut starts at the window's first message.+ * - Never splits an assistant branch group (same reason the window cut does+ * not: a group without its fork point is re-parented).+ * - Never drops a row without a durable `rowId` — an unpersisted row cannot be+ * fetched back, so releasing it would lose content for good.+ * - Returns the input array by reference when nothing is released, so React+ * trees are not re-rendered for a no-op.+ */++import type { ChatMessage } from '@/lib/chat-messages'+import { messageStoreWeight } from '@/lib/render-weight'++import { alignToBranchGroup, TRANSCRIPT_WINDOW_BUDGET } from './transcript-window'++/**+ * Weight of already-paged-through history kept behind the live window.+ *+ * One window page: enough that the first "Show earlier" of a session pages+ * through memory (and the backfill it may then start is prefetched by the same+ * click), while the retained payload stays proportional to the window instead+ * of to the session's length.+ */+export const TRANSCRIPT_RETAIN_SLACK = TRANSCRIPT_WINDOW_BUDGET++export interface TranscriptRetention {+ /** Transcript to keep in the store; identical to the input when nothing was+ * released. */+ messages: ChatMessage[]+ /** Rows released this pass. 0 means nothing was older than the retained+ * window and slack. */+ releasedRows: number+ /** Persisted rows still retained, counted from the newest. This is the+ * `transcript-tail` offset the next older REST page starts at — the backend+ * pages by persisted rows, so it is counted in the same currency. */+ retainedPersistedRows: number+}++function persistedRowCount(messages: readonly ChatMessage[]): number {+ let count = 0++ for (const message of messages) {+ if (message.rowId !== undefined) {+ count += 1+ }+ }++ return count+}++/**+ * How much of `messages` the store must keep, given the live window's first+ * message. Pure: the caller owns applying it (store write + tail rewind).+ */+export function boundRetainedTranscript(+ messages: readonly ChatMessage[],+ windowAnchorId: null | string+): TranscriptRetention {+ const keepEverything: TranscriptRetention = {+ messages: messages as ChatMessage[],+ releasedRows: 0,+ retainedPersistedRows: persistedRowCount(messages)+ }++ if (windowAnchorId === null || messages.length === 0) {+ return keepEverything+ }++ const anchor = messages.findIndex(message => message.id === windowAnchorId)++ // The window already starts at the oldest row the store holds.+ if (anchor <= 0) {+ return keepEverything+ }++ // Spend the slack walking back from the window, so paging history stays a+ // memory read for one more page.+ let boundary = anchor+ let slackLeft = TRANSCRIPT_RETAIN_SLACK++ while (boundary > 0 && slackLeft > 0) {+ boundary -= 1+ slackLeft -= messageStoreWeight(messages[boundary].parts)+ }++ boundary = alignToBranchGroup(messages, boundary)++ // A released row must be fetchable again, so every row being released has to+ // carry its durable id. A prefix holding a never-persisted row (an in-memory+ // row the backend never wrote) is left whole rather than released in part:+ // the older-page fetch is a row offset from the newest, and a prefix that+ // cannot be re-fetched in full would leave a hole in the middle.+ for (let i = 0; i < boundary; i += 1) {+ if (messages[i].rowId === undefined) {+ return keepEverything+ }+ }++ if (boundary <= 0) {+ return keepEverything+ }++ const retained = messages.slice(boundary)+ const retainedPersistedRows = persistedRowCount(retained)++ // Offset bookkeeping is measured from persisted rows. Without one in the+ // retained slice there is no anchor to re-fetch against — keep everything.+ if (retainedPersistedRows === 0) {+ return keepEverything+ }++ return { messages: retained, releasedRows: boundary, retainedPersistedRows }+}diff --git a/apps/desktop/src/app/chat/use-transcript-retention.test.tsx b/apps/desktop/src/app/chat/use-transcript-retention.test.tsxnew file mode 100644index 00000000000..d113065f534--- /dev/null+++ b/apps/desktop/src/app/chat/use-transcript-retention.test.tsx@@ -0,0 +1,216 @@+import { act, render } from '@testing-library/react'+import { atom } from 'nanostores'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { stubThreadEnvironment } from '@/components/assistant-ui/test-utils'+import { type TranscriptWindowValue, useTranscriptWindow } from '@/components/assistant-ui/thread/transcript-window'+import type * as HermesApi from '@/hermes'+import type { ChatMessage } from '@/lib/chat-messages'+import { RENDER_WEIGHT_CHARS } from '@/lib/render-weight'+import type * as SessionStates from '@/store/session-states'+import { $transcriptTailBySessionId, recordTranscriptTail } from '@/store/transcript-tail'++import { PRIMARY_SESSION_VIEW, SessionViewProvider } from './session-view'+import { _resetTranscriptBackfillForTests } from './transcript-backfill'+import { useTranscriptRetention } from './use-transcript-retention'++import { ChatRuntimeBoundary } from '.'++vi.mock('@/hermes', async importOriginal => ({+ ...(await importOriginal<typeof HermesApi>()),+ getOlderSessionMessages: vi.fn()+}))+vi.mock('@/store/session-states', async importOriginal => ({+ ...(await importOriginal<typeof SessionStates>()),+ sessionTileDelegate: vi.fn()+}))+const { getOlderSessionMessages } = await import('@/hermes')+const { sessionTileDelegate } = await import('@/store/session-states')+stubThreadEnvironment()++/** A persisted row heavy enough that a dozen of them fill one window page. */+const row = (index: number): ChatMessage => ({+ id: `m${index}`,+ parts: [{ type: 'text', text: 'x'.repeat(RENDER_WEIGHT_CHARS * 100) }],+ role: 'assistant',+ rowId: index + 1+})++const HYDRATED_ROWS = 120++function sessionView(messages: ChatMessage[]) {+ const $messages = atom(messages)++ return {+ $messages,+ view: {+ ...PRIMARY_SESSION_VIEW,+ $messages,+ // A held reference is not needed; the view only reads these.+ $runtimeId: atom<string | null>('runtime'),+ $storedId: atom<string | null>('stored')+ }+ }+}++function mountBoundary(view: ReturnType<typeof sessionView>['view'], onWindow: (value: TranscriptWindowValue) => void) {+ function Observe() {+ onWindow(useTranscriptWindow())++ return null+ }++ render(+ <SessionViewProvider value={view}>+ <ChatRuntimeBoundary+ busy={false}+ onCancel={() => {}}+ onEdit={async () => {}}+ onReload={async () => {}}+ onThreadMessagesChange={() => {}}+ suppressMessages={false}+ >+ <Observe />+ </ChatRuntimeBoundary>+ </SessionViewProvider>+ )+}++beforeEach(() => {+ $transcriptTailBySessionId.set({})+ _resetTranscriptBackfillForTests()+ vi.mocked(getOlderSessionMessages).mockReset()+})++describe('useTranscriptRetention — the store releases paged-through history', () => {+ it('drops the rows older than the live window, then fetches them back on "Show earlier"', async () => {+ const { $messages, view } = sessionView(Array.from({ length: 60 }, (_, index) => row(index)))++ recordTranscriptTail('stored', {+ messages: Array.from({ length: HYDRATED_ROWS }, (_, index) => ({ id: index, role: 'user', content: 'tail' })),+ pagination: { limit: HYDRATED_ROWS, offset: 0, order: 'latest', returned: HYDRATED_ROWS }+ })++ let state = { messages: $messages.get() }+ vi.mocked(sessionTileDelegate).mockReturnValue({+ updateSession: (_id: string, update: (previous: { messages: ChatMessage[] }) => { messages: ChatMessage[] }) => {+ state = update(state)++ if (state.messages !== $messages.get()) {+ $messages.set(state.messages)+ }++ return state+ }+ } as never)++ let window!: TranscriptWindowValue++ mountBoundary(view, value => (window = value))++ // The window cuts the transcript; everything older than it plus one page of+ // slack is released, and the released rows stay reachable over REST.+ const released = 60 - state.messages.length+ // Where the rewind points the next older page: the retained prefix.+ const rewoundOffset = state.messages.length++ expect(released).toBeGreaterThan(1)+ expect($messages.get()).toHaveLength(state.messages.length)+ expect($transcriptTailBySessionId.get().stored).toMatchObject({+ nextOffset: state.messages.length,+ possiblyTruncated: true+ })++ // The first "Show earlier" pages the retained store; the second one — with+ // the in-memory transcript fully materialized — fetches REST.+ vi.mocked(getOlderSessionMessages).mockResolvedValue({+ messages: Array.from({ length: released }, (_, index) => ({+ id: index + 1,+ content: 'restored',+ role: 'user',+ timestamp: index+ })),+ pagination: { limit: HYDRATED_ROWS, offset: rewoundOffset, order: 'latest', returned: released },+ session_id: 'stored'+ } as never)++ // Each click first pages what the store still retains; once that is fully+ // materialized the click that follows fetches the released rows over REST.+ for (let click = 0; click < 8 && vi.mocked(getOlderSessionMessages).mock.calls.length === 0; click += 1) {+ await act(async () => {+ expect(await window.expandWindow()).toBe(true)+ })+ }++ // Re-hydration read the released rows back from exactly where the rewind+ // said they were.+ expect(vi.mocked(getOlderSessionMessages)).toHaveBeenCalledTimes(1)+ expect(vi.mocked(getOlderSessionMessages).mock.calls[0][2]).toBe(rewoundOffset)++ // ...and the released history is back in chronological order.+ expect($messages.get()).toHaveLength(60)+ })++ it('leaves a transcript that fits its window alone', () => {+ const { $messages, view } = sessionView([row(0), row(1)])+ const updateSession = vi.fn()++ vi.mocked(sessionTileDelegate).mockReturnValue({ updateSession } as never)+ mountBoundary(view, () => {})++ expect(updateSession).not.toHaveBeenCalled()+ expect($messages.get()).toHaveLength(2)+ })++ it('does not release anything for a session with no recorded page route', () => {+ const { $messages, view } = sessionView(Array.from({ length: 60 }, (_, index) => row(index)))+ let state = { messages: $messages.get() }++ vi.mocked(sessionTileDelegate).mockReturnValue({+ updateSession: (_id: string, update: (previous: typeof state) => typeof state) => (state = update(state))+ } as never)+ mountBoundary(view, () => {})++ // `beforeEach` left the tail store empty: nothing can fetch released rows,+ // so they stay.+ expect(state.messages).toHaveLength(60)+ })+})++describe('useTranscriptRetention — direct', () => {+ it('releases on the anchor it is given, and only when the anchor moves', () => {+ const messages = Array.from({ length: 60 }, (_, index) => row(index))+ let state = { messages }+ const updateSession = vi.fn((_id: string, update: (previous: typeof state) => typeof state) => {+ state = update(state)++ return state+ })++ vi.mocked(sessionTileDelegate).mockReturnValue({ updateSession } as never)+ recordTranscriptTail('stored', {+ messages: [],+ pagination: { limit: HYDRATED_ROWS, offset: 0, order: 'latest', returned: HYDRATED_ROWS }+ })++ const { rerender } = render(<Harness anchorId={null} enabled runtimeId="runtime" storedSessionId="stored" />)++ expect(updateSession).not.toHaveBeenCalled()+ expect(state.messages).toHaveLength(60)++ rerender(<Harness anchorId="m48" enabled runtimeId="runtime" storedSessionId="stored" />)++ expect(updateSession).toHaveBeenCalledTimes(1)+ expect(state.messages.length).toBeLessThan(60)+ expect($transcriptTailBySessionId.get().stored).toMatchObject({+ nextOffset: state.messages.length,+ possiblyTruncated: true+ })+ })+})++function Harness(props: Parameters<typeof useTranscriptRetention>[0]) {+ useTranscriptRetention(props)++ return null+}diff --git a/apps/desktop/src/app/chat/use-transcript-retention.ts b/apps/desktop/src/app/chat/use-transcript-retention.tsnew file mode 100644index 00000000000..48d7f9fda92--- /dev/null+++ b/apps/desktop/src/app/chat/use-transcript-retention.ts@@ -0,0 +1,67 @@+import { useEffect, useRef } from 'react'++import { sessionTileDelegate } from '@/store/session-states'+import { rewindTranscriptTail, type TranscriptProfileScope } from '@/store/transcript-tail'++import { boundRetainedTranscript } from './transcript-retention'++interface TranscriptRetentionOptions {+ /** First message of the live window; null while the window covers the whole+ * in-memory transcript (nothing to release). */+ anchorId: null | string+ /** False for a static history page or a suppressed transcript — neither is+ * the live session store this hook bounds. */+ enabled: boolean+ profile?: TranscriptProfileScope+ runtimeId: null | string+ storedSessionId: null | string+}++/**+ * Release the store's paged-through history once it is off the live window.+ *+ * Runs when the window's own cut moves — the only moment the set of rows older+ * than the window changes (streaming grows the tail, "Show earlier" prepends, a+ * re-cut moves the anchor) — so the weight walk never happens per token.+ *+ * The released rows are persisted and stay on the backend, so this is a cache+ * eviction, not data loss: the tail bookkeeping is rewound first (the fetch+ * route must exist before anything is dropped) and the next "Show earlier"+ * fetches them back through the existing older-page backfill.+ *+ * The cut is computed inside the store updater, from the array it is about to+ * replace: a view snapshot can be a flush behind the store, and writing a+ * trimmed version of it back would drop the newest rows of a live turn.+ */+export function useTranscriptRetention({+ anchorId,+ enabled,+ profile,+ runtimeId,+ storedSessionId+}: TranscriptRetentionOptions): void {+ const profileRef = useRef(profile)+ profileRef.current = profile++ useEffect(() => {+ if (!enabled || !runtimeId || !storedSessionId || anchorId === null) {+ return+ }++ sessionTileDelegate()?.updateSession(runtimeId, state => {+ const retention = boundRetainedTranscript(state.messages, anchorId)++ if (retention.releasedRows === 0) {+ return state+ }++ // Nothing may be released until the rows are fetchable again: no tail+ // entry means no recorded route to page them back from.+ if (!rewindTranscriptTail(storedSessionId, retention.retainedPersistedRows, profileRef.current)) {+ return state+ }++ return { ...state, messages: retention.messages }+ })+ }, [anchorId, enabled, runtimeId, storedSessionId])+}diff --git a/apps/desktop/src/store/transcript-tail.test.ts b/apps/desktop/src/store/transcript-tail.test.tsindex 0aafeb279c1..9432792ae1b 100644--- a/apps/desktop/src/store/transcript-tail.test.ts+++ b/apps/desktop/src/store/transcript-tail.test.ts@@ -1,6 +1,11 @@import { beforeEach, describe, expect, it } from 'vitest'-import { $transcriptTailBySessionId, clearTranscriptTailPaging, recordTranscriptTail } from './transcript-tail'+import {+ $transcriptTailBySessionId,+ clearTranscriptTailPaging,+ recordTranscriptTail,+ rewindTranscriptTail+} from './transcript-tail'const page = (count: number, limit = 10) => ({messages: Array.from({ length: count }, (_, i) => ({ id: `m${i}` })),@@ -62,3 +67,41 @@ describe('recordTranscriptTail no-op suppression', () => {expect($transcriptTailBySessionId.get()['other-0']).toBeUndefined()})})++describe('rewindTranscriptTail', () => {+ beforeEach(() => {+ $transcriptTailBySessionId.set({})+ })++ it('points the next older page at the retained prefix', () => {+ recordTranscriptTail('s1', page(10))++ expect(rewindTranscriptTail('s1', 4)).toBe(true)+ expect($transcriptTailBySessionId.get().s1).toMatchObject({ nextOffset: 4, possiblyTruncated: true })+ })++ it('keeps a rewind on the same route the tail was hydrated with', () => {+ recordTranscriptTail('s1', page(10), { connectionId: 'c1', profile: 'work' }, { connectionId: 'c1', profile: 'work' })++ expect(rewindTranscriptTail('s1', 4, { connectionId: 'c1', profile: 'work' })).toBe(true)++ const entry = $transcriptTailBySessionId.get()[JSON.stringify(['c1', 'work', 's1'])]++ expect(entry).toMatchObject({ nextOffset: 4, possiblyTruncated: true })+ expect(entry.profile).toEqual({ connectionId: 'c1', profile: 'work' })+ })++ it('refuses to rewind a session with no recorded page route', () => {+ // No entry means no route to fetch a page from: the caller must keep its+ // rows rather than release history nothing can bring back.+ expect(rewindTranscriptTail('unknown', 4)).toBe(false)+ expect($transcriptTailBySessionId.get()).toEqual({})+ })++ it('refuses an ambiguous rewind when the session has several owner scopes', () => {+ recordTranscriptTail('s1', page(10), { connectionId: 'c1', profile: 'work' }, { connectionId: 'c1', profile: 'work' })+ recordTranscriptTail('s1', page(10), { connectionId: 'c2', profile: 'work' }, { connectionId: 'c2', profile: 'work' })++ expect(rewindTranscriptTail('s1', 4)).toBe(false)+ })+})diff --git a/apps/desktop/src/store/transcript-tail.ts b/apps/desktop/src/store/transcript-tail.tsindex 74c8394f62b..f0df8f415bf 100644--- a/apps/desktop/src/store/transcript-tail.ts+++ b/apps/desktop/src/store/transcript-tail.ts@@ -180,6 +180,50 @@ export function recordTranscriptBackfillPage(setTranscriptTailEntry(key, tailStateFromPage(page, previous.profile))}+/**+ * Re-arm the older-page fetch after in-store history was released.+ *+ * `boundRetainedTranscript` (app/chat/transcript-retention) drops rows that are+ * older than the live window once they are persisted — but they stay reachable+ * only while the transcript still reports older rows as fetchable. Point the+ * entry at the retained prefix so the next "Show earlier" fetches them back+ * instead of treating the in-memory store as the whole transcript.+ *+ * Returns false when the session has no entry: without one there is no route+ * recorded to fetch a page from, so the caller must keep its rows rather than+ * release history nothing can bring back.+ */+export function rewindTranscriptTail(+ storedSessionId: string,+ retainedRows: number,+ profile?: TranscriptProfileScope+): boolean {+ if (!storedSessionId || retainedRows < 0) {+ return false+ }++ const current = $transcriptTailBySessionId.get()++ const selected: Array<[string, TranscriptTailState | undefined]> =+ profile === undefined+ ? matchingTailEntries(storedSessionId)+ : [[transcriptTailKey(storedSessionId, profile), current[transcriptTailKey(storedSessionId, profile)]]]++ if (selected.length !== 1 || !selected[0][1]) {+ return false+ }++ const [key, previous] = selected[0]++ setTranscriptTailEntry(key, {+ nextOffset: retainedRows,+ possiblyTruncated: true,+ profile: previous.profile+ })++ return true+}+export function transcriptTailState(storedSessionId: null | string | undefined,profile?: TranscriptProfileScope