Skip to content

The agent that grows with you

fix(desktop): count released transcript rows in backend rows

kshitijk4poor3f985c84cd14
diff --git a/apps/desktop/src/app/chat/transcript-retention.test.ts b/apps/desktop/src/app/chat/transcript-retention.test.ts
index 79bd3fe10db..9306b977da9 100644
--- a/apps/desktop/src/app/chat/transcript-retention.test.ts
+++ b/apps/desktop/src/app/chat/transcript-retention.test.ts
@@ -7,20 +7,23 @@ import { boundRetainedTranscript, TRANSCRIPT_RETAIN_BUDGET } from './transcript-
interface RowOptions {
group?: string
- /** Persisted rows carry the store's only durable handle back to the backend. */
- persisted?: boolean
+ /** Backend rows this message folds (the hydration fold merges tool rows). */
+ span?: number
+ /** A row still in flight: no backend row yet, so it can never be released. */
+ pendingRow?: boolean
textUnits?: number
}
const row = (index: number, options: RowOptions = {}): ChatMessage => {
- const { group, persisted = true, textUnits = 1 } = options
+ const { group, pendingRow = false, span, 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 } : {})
+ ...(pendingRow ? { pending: true } : { rowId: index + 1 }),
+ ...(span ? { serverRowSpan: span } : {})
}
}
@@ -79,11 +82,11 @@ describe('boundRetainedTranscript', () => {
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.
+ it('leaves the transcript whole when a released row is still in flight', () => {
+ // Rows 27-29 are in flight: releasing the prefix around them would drop
+ // content no fetch can restore.
const messages = transcript(60, index =>
- index >= 27 && index <= 29 ? row(index, { persisted: false, textUnits: 100 }) : heavy(index)
+ index >= 27 && index <= 29 ? row(index, { pendingRow: true, textUnits: 100 }) : heavy(index)
)
expect(untouched(messages, messages[40].id)).toEqual({ released: false })
@@ -115,15 +118,27 @@ describe('boundRetainedTranscript', () => {
}
})
- it('releases nothing when a row older than the window cannot be fetched back', () => {
- // Rows 0-19 were never persisted. The older-page fetch is a row offset from
- // the newest, so a prefix holding an unpersisted row cannot be re-fetched in
- // full — the transcript is left whole rather than released in part.
- const messages = transcript(30, index => row(index, { persisted: index >= 20, textUnits: 100 }))
+ it('releases nothing when a row older than the window is still in flight', () => {
+ // Rows 0-19 were never persisted. Releasing them would drop content nothing
+ // can fetch back, so the transcript is left whole rather than released in
+ // part.
+ const messages = transcript(30, index => row(index, { pendingRow: index < 20, textUnits: 100 }))
expect(untouched(messages, messages[25].id)).toEqual({ released: false })
})
+ it('reports the released rows in backend rows, not messages', () => {
+ // A tool-heavy turn folds its tool rows into one message: the older-page
+ // offset the caller rewinds is counted in those backend rows.
+ const messages = transcript(60, index => row(index, { span: 11, textUnits: 100 }))
+ const keep = slackRows(messages[40])
+
+ const retention = released(messages, messages[40].id)
+
+ expect(retention.releasedRows).toBe(40 - keep)
+ expect(retention.releasedServerRows).toBe((40 - keep) * 11)
+ })
+
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.
diff --git a/apps/desktop/src/app/chat/transcript-retention.ts b/apps/desktop/src/app/chat/transcript-retention.ts
index 2fd14053cf7..39f596da4e4 100644
--- a/apps/desktop/src/app/chat/transcript-retention.ts
+++ b/apps/desktop/src/app/chat/transcript-retention.ts
@@ -52,15 +52,33 @@ export type TranscriptRetention =
released: true
/** Transcript to keep in the store; everything before it was released. */
messages: ChatMessage[]
- /** Rows released this pass. Every one of them is persisted, so the
- * caller can subtract them from the session's older-page offset — the
- * offset the backend itself reported, which the release must stay in the
- * currency of (the backend pages display history, not raw store rows). */
+ /** Messages released this pass. */
releasedRows: number
+ /** Backend rows those messages covered — the `transcript-tail` older-page
+ * offset is counted in backend rows, so this is what the caller rewinds
+ * it by. The hydration fold merges a turn's tool rows into one message,
+ * so this is usually larger than `releasedRows`. */
+ releasedServerRows: number
}
const NOTHING_RELEASED: TranscriptRetention = { released: false }
+/**
+ * Backend rows the slice covers. The hydration fold merges a turn's tool rows
+ * into the assistant message they belong to, so a message is not one backend
+ * row; the older-page offset is counted in backend rows, so the released rows
+ * have to be converted before the offset can be rewound.
+ */
+function serverRowCount(messages: readonly ChatMessage[], end: number): number {
+ let rows = 0
+
+ for (let i = 0; i < end; i += 1) {
+ rows += messages[i].serverRowSpan ?? 1
+ }
+
+ return rows
+}
+
/**
* 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).
@@ -96,18 +114,20 @@ export function boundRetainedTranscript(
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:
- // 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.
+ // Nothing in flight may be released: a `pending` row has no backend row yet,
+ // so it cannot be fetched back and dropping it would lose content outright.
for (let i = 0; i < boundary; i += 1) {
- if (messages[i].rowId === undefined) {
+ if (messages[i].pending) {
return NOTHING_RELEASED
}
}
const retained = messages.slice(boundary)
- return { messages: retained, releasedRows: boundary, released: true }
+ return {
+ messages: retained,
+ releasedRows: boundary,
+ releasedServerRows: serverRowCount(messages, boundary),
+ released: true
+ }
}
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 e81305f7922..e5cf3beb8bc 100644
--- a/apps/desktop/src/app/chat/use-transcript-retention.test.tsx
+++ b/apps/desktop/src/app/chat/use-transcript-retention.test.tsx
@@ -28,15 +28,20 @@ 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. */
+/** A persisted row heavy enough that a dozen of them fill one window page.
+ * `serverRowSpan` models the hydration fold: each message stands for three
+ * backend rows, so the rewind has to convert. */
const row = (index: number): ChatMessage => ({
id: `m${index}`,
parts: [{ type: 'text', text: 'x'.repeat(RENDER_WEIGHT_CHARS * 100) }],
role: 'assistant',
- rowId: index + 1
+ rowId: index + 1,
+ serverRowSpan: 3
})
const HYDRATED_ROWS = 120
+/** Backend rows each store message stands for (see `serverRowSpan` above). */
+const SERVER_ROWS_PER_MESSAGE = 3
function sessionView(messages: ChatMessage[]) {
const $messages = atom(messages)
@@ -112,8 +117,8 @@ describe('useTranscriptRetention — the store releases paged-through history',
// 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 hydrated offset minus the
- // rows the store gave up.
- const rewoundOffset = HYDRATED_ROWS - released
+ // BACKEND rows the store gave up (three per message here).
+ const rewoundOffset = HYDRATED_ROWS - released * SERVER_ROWS_PER_MESSAGE
expect(released).toBeGreaterThan(1)
expect($messages.get()).toHaveLength(state.messages.length)
@@ -208,7 +213,7 @@ describe('useTranscriptRetention — direct', () => {
expect(updateSession).toHaveBeenCalledTimes(1)
expect(state.messages.length).toBeLessThan(60)
expect($transcriptTailBySessionId.get().stored).toMatchObject({
- nextOffset: HYDRATED_ROWS - (60 - state.messages.length),
+ nextOffset: HYDRATED_ROWS - (60 - state.messages.length) * SERVER_ROWS_PER_MESSAGE,
possiblyTruncated: true
})
})
diff --git a/apps/desktop/src/app/chat/use-transcript-retention.ts b/apps/desktop/src/app/chat/use-transcript-retention.ts
index 8dc2ebd7f72..b892efafcdb 100644
--- a/apps/desktop/src/app/chat/use-transcript-retention.ts
+++ b/apps/desktop/src/app/chat/use-transcript-retention.ts
@@ -64,7 +64,7 @@ export function useTranscriptRetention({
}
// Nothing may be released until the rows are fetchable again.
- if (!rewindTranscriptTail(storedSessionId, retention.releasedRows, profile)) {
+ if (!rewindTranscriptTail(storedSessionId, retention.releasedServerRows, profile)) {
return state
}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index 91c0b9f1d8d..b3241281367 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -148,6 +148,8 @@ function preserveStructuralParts(message: ChatMessage, previous: ChatMessage): C
// timestamp — presentation-only (sort/age display), never affects transcript equality
// attachmentRefs — composer-side metadata; already reconciled in reconcileResumeMessages
// rowId — durable backend identity; stable for a given row, never changes what's painted
+// serverRowSpan — backend rows the folded message covers; the older-page offset
+// accounting reads it, the transcript never paints it
//
// If your new field affects what the user sees in the transcript, add it to
// COMPARED. If it's metadata that shouldn't trigger a re-render, add it to
@@ -177,7 +179,7 @@ const COMPARED_FIELDS = [
'durationS'
] as const
-const IGNORED_FIELDS = ['attachmentRefs', 'parts', 'rowId'] as const
+const IGNORED_FIELDS = ['attachmentRefs', 'parts', 'rowId', 'serverRowSpan'] as const
// Compile-time check: every ChatMessagePart discriminant must be handled by
// chatPartsEquivalent. If @assistant-ui adds a new part type, this fails tsc.
diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.ts
index 5bac8a4fd33..defba040555 100644
--- a/apps/desktop/src/lib/chat-messages.test.ts
+++ b/apps/desktop/src/lib/chat-messages.test.ts
@@ -1534,3 +1534,30 @@ describe('sealOpenToolParts', () => {
expect(sealOpenToolParts(messages)).toBe(messages)
})
})
+
+describe('toChatMessages backend-row accounting', () => {
+ it('reports the backend rows a folded turn stands for', () => {
+ // The older-page offset (transcript-tail) is counted in BACKEND rows, and
+ // this fold is what makes a message not one row: one assistant row plus its
+ // tool rows, plus a second assistant row that merges into the same bubble.
+ const messages = toChatMessages([
+ {
+ role: 'assistant',
+ content: 'Running the checks.',
+ timestamp: 1,
+ tool_calls: [{ id: 'tc', function: { name: 'terminal', arguments: '{}' } }]
+ },
+ { role: 'tool', tool_call_id: 'tc', content: 'ok', timestamp: 2 },
+ { role: 'assistant', content: 'Done.', timestamp: 3 }
+ ])
+
+ expect(messages).toHaveLength(1)
+ expect(messages[0].serverRowSpan).toBe(3)
+
+ // A row that stands for one backend row carries no span at all.
+ const plain = toChatMessages([{ role: 'user', content: 'hi', timestamp: 1 }])
+
+ expect(plain).toHaveLength(1)
+ expect(plain[0]).not.toHaveProperty('serverRowSpan')
+ })
+})
diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.ts
index 59e539130f8..a1380148e28 100644
--- a/apps/desktop/src/lib/chat-messages/hydration.ts
+++ b/apps/desktop/src/lib/chat-messages/hydration.ts
@@ -242,11 +242,24 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
const result: ChatMessage[] = []
let pendingToolParts: ChatMessagePart[] = []
let pendingToolTimestamp: number | undefined
+ // Backend rows the pending batch stands for. The fold merges a turn's tool
+ // rows into one message, and the store's older-page offset is counted in
+ // backend rows, so the folded message has to report how many it covers
+ // (see ChatMessage.serverRowSpan).
+ let pendingToolRows = 0
let activeAssistantIndex: null | number = null
const clearPendingTools = () => {
pendingToolParts = []
pendingToolTimestamp = undefined
+ pendingToolRows = 0
+ }
+
+ /** Attribute `rows` backend rows to a folded message (absent field means one). */
+ const absorbRows = (message: ChatMessage | undefined, rows: number) => {
+ if (message && rows > 0) {
+ message.serverRowSpan = (message.serverRowSpan ?? 1) + rows
+ }
}
const earliestTimestamp = (...values: (number | undefined)[]) => {
@@ -270,6 +283,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
active.parts = [...active.parts, ...parts]
active.timestamp = earliestTimestamp(active.timestamp, timestamp, ...parts.map(part => part.timestamp))
+ absorbRows(active, pendingToolRows)
return true
}
@@ -284,6 +298,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
id: `${pendingToolTimestamp || Date.now()}-${index}-tools`,
role: 'assistant',
parts: pendingToolParts,
+ ...(pendingToolRows > 1 ? { serverRowSpan: pendingToolRows } : {}),
timestamp: pendingToolTimestamp
})
activeAssistantIndex = result.length - 1
@@ -298,6 +313,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
if (updatedPendingToolParts) {
pendingToolParts = updatedPendingToolParts
+ pendingToolRows += 1
return
}
@@ -308,6 +324,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
pendingToolParts = [...pendingToolParts, storedToolMessagePart(message, index)]
pendingToolTimestamp ??= message.timestamp
+ pendingToolRows += 1
return
}
@@ -392,14 +409,18 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
if (isToolOnlyAssistant) {
pendingToolParts = [...pendingToolParts, ...parts]
pendingToolTimestamp ??= message.timestamp
+ pendingToolRows += 1
return
}
+ let pendingAbsorbedRows = 0
+
if (message.role === 'assistant') {
if (pendingToolParts.length) {
if (!appendPartsToActiveAssistant(pendingToolParts, message.timestamp ?? pendingToolTimestamp)) {
parts.unshift(...pendingToolParts)
+ pendingAbsorbedRows = pendingToolRows
}
clearPendingTools()
@@ -420,6 +441,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
message.timestamp,
...parts.map(part => part.timestamp)
)
+ absorbRows(activeAssistant, 1)
return
}
@@ -443,6 +465,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
...(message.display_kind === 'process_complete' ? { asyncResultKind: 'process' as const } : {}),
timestamp: earliestTimestamp(message.timestamp, ...parts.map(part => part.timestamp)),
...(rowId !== undefined ? { rowId } : {}),
+ ...(pendingAbsorbedRows > 1 ? { serverRowSpan: pendingAbsorbedRows } : {}),
...(reactions.length ? { reactions } : {}),
...(extractedAttachmentRefs ? { attachmentRefs: extractedAttachmentRefs } : {})
})
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index f5f5b22afc8..2fdaaa21198 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -808,7 +808,7 @@ export function applyStoredToolResult(messages: ChatMessage[], toolMessage: Sess
result: parseStoredToolResult(content),
isError: false
} as ChatMessagePart
- messages[i] = { ...message, parts }
+ messages[i] = { ...message, parts, serverRowSpan: (message.serverRowSpan ?? 1) + 1 }
return true
}
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 54e4c18629f..bfa3694b0f1 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -50,6 +50,12 @@ export type ChatMessage = {
attachmentRefs?: string[]
/** Durable backend `messages.id`. Absent until the row is persisted. */
rowId?: number
+ /** Backend transcript rows this message represents — the hydration fold
+ * merges a turn's tool rows into the assistant message they belong to, so a
+ * message is not one backend row. The older-page offset (transcript-tail) is
+ * counted in backend rows, so anything that rewinds that offset must convert
+ * through this. Absent means one row. */
+ serverRowSpan?: number
/** Emoji reactions on this message — one per author (see MessageReaction). */
reactions?: MessageReaction[]
}
diff --git a/apps/desktop/src/store/transcript-tail.ts b/apps/desktop/src/store/transcript-tail.ts
index 39559ccd0ae..22a059ee6c0 100644
--- a/apps/desktop/src/store/transcript-tail.ts
+++ b/apps/desktop/src/store/transcript-tail.ts
@@ -205,12 +205,14 @@ export function recordTranscriptBackfillPage(
* back instead of treating the in-memory store as the whole transcript.
*
* The offset is decremented RELATIVE to what the backend reported, never
- * recomputed from the store's own row count: the backend pages display history
- * (`include_compacted` reads are grouped by display order, and inactive rows are
- * not counted), so a locally counted row total is not guaranteed to be the same
- * unit. Subtracting from the backend's own number can only overlap a page that
- * is already in memory — which the merge dedupes — where an over-counted
- * absolute offset would skip rows the reader can then never reach.
+ * recomputed from the store's own row count, and it is decremented by BACKEND
+ * rows: the hydration fold merges a turn's tool rows into the assistant message
+ * they belong to (`ChatMessage.serverRowSpan` carries how many), and the backend
+ * pages display history (an `include_compacted` read is grouped by display
+ * order; inactive rows are not counted). Subtracting from the backend's own
+ * number can only overlap a page that is already in memory — which the merge
+ * dedupes — where an over-counted absolute offset would skip rows the reader
+ * can then never reach.
*
* 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
@@ -218,10 +220,10 @@ export function recordTranscriptBackfillPage(
*/
export function rewindTranscriptTail(
storedSessionId: string,
- releasedRows: number,
+ releasedServerRows: number,
profile?: TranscriptProfileScope
): boolean {
- if (!storedSessionId || releasedRows <= 0) {
+ if (!storedSessionId || releasedServerRows <= 0) {
return false
}
@@ -232,7 +234,7 @@ export function rewindTranscriptTail(
}
setTranscriptTailEntry(entry[0], {
- nextOffset: Math.max(0, entry[1].nextOffset - releasedRows),
+ nextOffset: Math.max(0, entry[1].nextOffset - releasedServerRows),
possiblyTruncated: true,
profile: entry[1].profile
})