Skip to content

The agent that grows with you

refactor(desktop): share the tail-entry lookup, and plan nothing when nothing is released

kshitijk4poor71a0ce913cf0
diff --git a/apps/desktop/src/app/chat/transcript-retention.test.ts b/apps/desktop/src/app/chat/transcript-retention.test.ts
index 9ce1fc0a504..3a423105b48 100644
--- a/apps/desktop/src/app/chat/transcript-retention.test.ts
+++ b/apps/desktop/src/app/chat/transcript-retention.test.ts
@@ -3,7 +3,7 @@ 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'
+import { boundRetainedTranscript, TRANSCRIPT_RETAIN_BUDGET } from './transcript-retention'
interface RowOptions {
group?: string
@@ -29,17 +29,31 @@ const transcript = (count: number, each: (index: number) => ChatMessage = 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))
+ Math.ceil(TRANSCRIPT_RETAIN_BUDGET / messageStoreWeight(sample.parts))
const heavy = (index: number) => row(index, { textUnits: 100 })
+/** The release path, or a failure naming the anchor that was expected to release. */
+const released = (messages: readonly ChatMessage[], anchorId: null | string) => {
+ const retention = boundRetainedTranscript(messages, anchorId)
+
+ if (!retention.released) {
+ throw new Error(`expected a release for anchor ${String(anchorId)}`)
+ }
+
+ return retention
+}
+
+const untouched = (messages: readonly ChatMessage[], anchorId: null | string) =>
+ boundRetainedTranscript(messages, anchorId)
+
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)
+ const retention = released(messages, anchor)
expect(retention.releasedRows).toBe(40 - keep)
expect(retention.messages[0].id).toBe(`m${40 - keep}`)
@@ -50,10 +64,10 @@ describe('boundRetainedTranscript', () => {
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 shortRetention = released(short, short[40].id)
+ const longRetention = released(long, long[560].id)
- const behind = (retention: typeof shortRetention, anchorId: string) =>
+ const behind = (retention: ReturnType<typeof released>, anchorId: string) =>
retention.messages.findIndex(message => message.id === anchorId)
// The window itself holds different amounts here; what must not grow with
@@ -73,20 +87,20 @@ describe('boundRetainedTranscript', () => {
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)
+ expect(untouched(messages, messages[40].id)).toEqual({ released: false })
})
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 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)
+ const retention = released(messages, messages[40].id)
expect(40 - keep).toBeGreaterThan(25)
expect(40 - keep).toBeLessThanOrEqual(28)
@@ -94,26 +108,41 @@ describe('boundRetainedTranscript', () => {
expect(retention.messages[0].id).toBe('m26')
})
- it('returns the store array untouched when nothing precedes the window', () => {
+ it('releases nothing 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)
+ expect(untouched(messages, anchor)).toEqual({ released: false })
}
})
- it('returns the store array untouched when the retained rows carry no durable id', () => {
+ it('releases nothing 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(untouched(messages, messages[25].id)).toEqual({ released: false })
+ })
+
+ it('does no work when there is nothing to release', () => {
+ // A re-cut of an untouched transcript must stay cheap: the released:false
+ // path must not walk the weights of a long array.
+ let reads = 0
+
+ const messages = transcript(20, index => {
+ const base = heavy(index)
+
+ return Object.defineProperty({ ...base }, 'parts', {
+ enumerable: true,
+ get: () => {
+ reads += 1
+
+ return base.parts
+ }
+ }) as ChatMessage
+ })
- expect(retention.messages).toBe(messages)
- expect(retention.releasedRows).toBe(0)
+ expect(untouched(messages, messages[0].id)).toEqual({ released: false })
+ expect(reads).toBe(0)
})
})
diff --git a/apps/desktop/src/app/chat/transcript-retention.ts b/apps/desktop/src/app/chat/transcript-retention.ts
index 03e13219c33..0420ebaec52 100644
--- a/apps/desktop/src/app/chat/transcript-retention.ts
+++ b/apps/desktop/src/app/chat/transcript-retention.ts
@@ -25,8 +25,9 @@
* 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.
+ * - Reports `released: false` and does no work (no weight walk, no row count)
+ * when there is nothing to release, so a re-cut of an untouched transcript
+ * stays cheap.
*/
import type { ChatMessage } from '@/lib/chat-messages'
@@ -35,27 +36,32 @@ 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.
+ * 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.
*
- * 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.
+ * Distinct from `TRANSCRIPT_WINDOW_SLACK`, which is the re-cut hysteresis.
*/
-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
-}
+export const TRANSCRIPT_RETAIN_BUDGET = TRANSCRIPT_WINDOW_BUDGET
+
+export type TranscriptRetention =
+ | { released: false }
+ | {
+ released: true
+ /** Transcript to keep in the store; everything before it was released. */
+ messages: ChatMessage[]
+ /** Rows released this pass. */
+ 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
+ }
+
+const NOTHING_RELEASED: TranscriptRetention = { released: false }
function persistedRowCount(messages: readonly ChatMessage[]): number {
let count = 0
@@ -77,27 +83,21 @@ 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
+ return NOTHING_RELEASED
}
const anchor = messages.findIndex(message => message.id === windowAnchorId)
// The window already starts at the oldest row the store holds.
if (anchor <= 0) {
- return keepEverything
+ return NOTHING_RELEASED
}
// 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
+ let slackLeft = TRANSCRIPT_RETAIN_BUDGET
while (boundary > 0 && slackLeft > 0) {
boundary -= 1
@@ -106,6 +106,10 @@ export function boundRetainedTranscript(
boundary = alignToBranchGroup(messages, boundary)
+ if (boundary <= 0) {
+ return NOTHING_RELEASED
+ }
+
// 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:
@@ -113,22 +117,18 @@ export function boundRetainedTranscript(
// 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
+ return NOTHING_RELEASED
}
}
- 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 NOTHING_RELEASED
}
- return { messages: retained, releasedRows: boundary, retainedPersistedRows }
+ return { messages: retained, releasedRows: boundary, released: true, retainedPersistedRows }
}
diff --git a/apps/desktop/src/app/chat/use-transcript-retention.test.tsx b/apps/desktop/src/app/chat/use-transcript-retention.test.tsx
index d113065f534..6ebb70e93ae 100644
--- a/apps/desktop/src/app/chat/use-transcript-retention.test.tsx
+++ b/apps/desktop/src/app/chat/use-transcript-retention.test.tsx
@@ -166,13 +166,16 @@ describe('useTranscriptRetention — the store releases paged-through history',
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)
+ const updateSession = vi.fn(
+ (_id: string, update: (previous: typeof state) => typeof state) => (state = update(state))
+ )
+
+ vi.mocked(sessionTileDelegate).mockReturnValue({ updateSession } as never)
mountBoundary(view, () => {})
// `beforeEach` left the tail store empty: nothing can fetch released rows,
- // so they stay.
+ // so the plan is never even computed and they stay.
+ expect(updateSession).not.toHaveBeenCalled()
expect(state.messages).toHaveLength(60)
})
})
@@ -181,6 +184,7 @@ 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)
diff --git a/apps/desktop/src/app/chat/use-transcript-retention.ts b/apps/desktop/src/app/chat/use-transcript-retention.ts
index 48d7f9fda92..352bb402937 100644
--- a/apps/desktop/src/app/chat/use-transcript-retention.ts
+++ b/apps/desktop/src/app/chat/use-transcript-retention.ts
@@ -1,7 +1,7 @@
-import { useEffect, useRef } from 'react'
+import { useEffect } from 'react'
import { sessionTileDelegate } from '@/store/session-states'
-import { rewindTranscriptTail, type TranscriptProfileScope } from '@/store/transcript-tail'
+import { rewindTranscriptTail, type TranscriptProfileScope, transcriptTailState } from '@/store/transcript-tail'
import { boundRetainedTranscript } from './transcript-retention'
@@ -32,6 +32,10 @@ interface TranscriptRetentionOptions {
* 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.
+ *
+ * `profile` must be referentially stable across renders (the chat view memoizes
+ * it): it is a dependency here, and the rewind has to address the same route
+ * the render resolved.
*/
export function useTranscriptRetention({
anchorId,
@@ -40,28 +44,31 @@ export function useTranscriptRetention({
runtimeId,
storedSessionId
}: TranscriptRetentionOptions): void {
- const profileRef = useRef(profile)
- profileRef.current = profile
-
useEffect(() => {
if (!enabled || !runtimeId || !storedSessionId || anchorId === null) {
return
}
+ // Cheap pre-check: with no recorded tail entry there is no route to fetch
+ // released rows back from, so the plan below would be discarded anyway.
+ // The rewind inside the updater stays the authoritative arbiter.
+ if (!transcriptTailState(storedSessionId, profile)) {
+ return
+ }
+
sessionTileDelegate()?.updateSession(runtimeId, state => {
const retention = boundRetainedTranscript(state.messages, anchorId)
- if (retention.releasedRows === 0) {
+ if (!retention.released) {
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)) {
+ // Nothing may be released until the rows are fetchable again.
+ if (!rewindTranscriptTail(storedSessionId, retention.retainedPersistedRows, profile)) {
return state
}
return { ...state, messages: retention.messages }
})
- }, [anchorId, enabled, runtimeId, storedSessionId])
+ }, [anchorId, enabled, profile, runtimeId, storedSessionId])
}
diff --git a/apps/desktop/src/store/transcript-tail.ts b/apps/desktop/src/store/transcript-tail.ts
index f0df8f415bf..f1674bd6f66 100644
--- a/apps/desktop/src/store/transcript-tail.ts
+++ b/apps/desktop/src/store/transcript-tail.ts
@@ -84,6 +84,32 @@ function matchingTailEntries(storedSessionId: string): Array<[string, Transcript
})
}
+/**
+ * Resolve the single tail entry an address refers to, returning its key too.
+ *
+ * `undefined` when the address is ambiguous (two scopes recorded for one stored
+ * session, no profile to disambiguate) or absent. Callers that page or rewind
+ * must then leave the transcript alone: a route that cannot be addressed
+ * exactly is a route that cannot be fetched from.
+ */
+function resolveTailEntry(
+ storedSessionId: string,
+ profile?: TranscriptProfileScope
+): [key: string, state: TranscriptTailState] | undefined {
+ const current = $transcriptTailBySessionId.get()
+
+ if (profile !== undefined) {
+ const key = transcriptTailKey(storedSessionId, profile)
+ const state = current[key]
+
+ return state ? [key, state] : undefined
+ }
+
+ const matches = matchingTailEntries(storedSessionId)
+
+ return matches.length === 1 ? matches[0] : undefined
+}
+
function tailStateFromPage(page: TailPage, profile?: TranscriptProfileScope): TranscriptTailState {
const pagination = page.pagination
@@ -160,24 +186,13 @@ export function recordTranscriptBackfillPage(
page: TailPage,
profile?: TranscriptProfileScope
): void {
- const current = $transcriptTailBySessionId.get()
+ const entry = resolveTailEntry(storedSessionId, profile)
- const selected: Array<[string, TranscriptTailState | undefined]> =
- profile === undefined
- ? matchingTailEntries(storedSessionId)
- : [[transcriptTailKey(storedSessionId, profile), current[transcriptTailKey(storedSessionId, profile)]]]
-
- if (selected.length !== 1) {
- return
- }
-
- const [key, previous] = selected[0]
-
- if (!previous) {
+ if (!entry) {
return
}
- setTranscriptTailEntry(key, tailStateFromPage(page, previous.profile))
+ setTranscriptTailEntry(entry[0], tailStateFromPage(page, entry[1].profile))
}
/**
@@ -202,23 +217,16 @@ export function rewindTranscriptTail(
return false
}
- const current = $transcriptTailBySessionId.get()
+ const entry = resolveTailEntry(storedSessionId, profile)
- const selected: Array<[string, TranscriptTailState | undefined]> =
- profile === undefined
- ? matchingTailEntries(storedSessionId)
- : [[transcriptTailKey(storedSessionId, profile), current[transcriptTailKey(storedSessionId, profile)]]]
-
- if (selected.length !== 1 || !selected[0][1]) {
+ if (!entry) {
return false
}
- const [key, previous] = selected[0]
-
- setTranscriptTailEntry(key, {
+ setTranscriptTailEntry(entry[0], {
nextOffset: retainedRows,
possiblyTruncated: true,
- profile: previous.profile
+ profile: entry[1].profile
})
return true
@@ -232,13 +240,7 @@ export function transcriptTailState(
return undefined
}
- if (profile !== undefined) {
- return $transcriptTailBySessionId.get()[transcriptTailKey(storedSessionId, profile)]
- }
-
- const matches = matchingTailEntries(storedSessionId)
-
- return matches.length === 1 ? matches[0][1] : undefined
+ return resolveTailEntry(storedSessionId, profile)?.[1]
}
/** Drops the LRU order as well as the atom. */