The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): bind every user bubble of a turn to the receipt's stored rows
Teknium5db9c8ee7654
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/completion-boundaries.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/completion-boundaries.test.tsxindex ede73c9cd7d..a9ac492be6b 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/completion-boundaries.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/completion-boundaries.test.tsx@@ -181,10 +181,12 @@ it.each([true, false, undefined])()// The session authority acknowledges a queued admission before the prompt row-// exists, so the optimistic prompt has no row id until the completion receipt-// names it. A stored page read after the turn must replace that bubble, not-// paint the prompt a second time beside its stored copy.-it('binds the optimistic prompt to the receipt row when the submit acknowledgement named none', async () => {+// exists, and writes a steer's row mid-turn, so no submit acknowledgement names+// them. The completion receipt does; a stored page read after the turn must+// replace those bubbles, not paint each prompt a second time beside its row.+const submissionIdOf = (h: ReturnType<typeof mount>) => h.state().messages[0].id.replace(/^user-/, '')++it('binds the sent prompt to the receipt row named by its submission', async () => {const h = mount()await h.submit()expect(h.state().messages[0].rowId).toBeUndefined()@@ -192,7 +194,10 @@ it('binds the optimistic prompt to the receipt row when the submit acknowledgemeawait h.send('message.delta', { text: ANSWER })await h.send('message.complete', {text: ANSWER,- persisted_turn: { row_ids: [71, 72], user_row_id: 71, final_assistant_row_id: 72, complete: true }+ persisted_turn: {+ row_ids: [71, 72], user_row_id: 71, user_row_ids: [71], final_assistant_row_id: 72, complete: true,+ submission_id: submissionIdOf(h)+ }})const latestPage = toChatMessages([@@ -200,7 +205,6 @@ it('binds the optimistic prompt to the receipt row when the submit acknowledgeme{ id: 72, role: 'assistant', content: ANSWER }])- // The switch-back read grafts the stored page onto the window by row id.expect(timeline(graftRefreshedTailOntoBackfill(latestPage, h.state().messages))).toEqual([['user', 'Give the answer.'],['assistant', ANSWER]@@ -208,6 +212,49 @@ it('binds the optimistic prompt to the receipt row when the submit acknowledgemeh.dispose()})+it('binds the prompt and the steer of a turn whose receipt is not complete', async () => {+ const h = mount()+ await h.submit()+ await h.send('message.start')+ await h.send('message.delta', { text: 'Partial' })+ await flush()+ await h.redirect()+ await h.send('message.delta', { text: ' then revised.' })+ await h.send('message.complete', {+ text: 'Revised.',+ persisted_turn: {+ row_ids: [71, 72, 73, 74], user_row_id: 71, user_row_ids: [71, 73], final_assistant_row_id: 74,+ complete: false, submission_id: submissionIdOf(h)+ }+ })++ expect(h.state().messages.filter(m => m.role === 'user').map(m => m.rowId)).toEqual([71, 73])+ h.dispose()+})++it('binds a viewer that never sent the turn only when it shows exactly the receipt rows', async () => {+ const h = mount()++ const earlier = toChatMessages([+ { id: 60, role: 'user', content: 'Earlier.' },+ { id: 61, role: 'assistant', content: 'Before.' }+ ])++ h.update(state => ({ ...state, messages: [...earlier, { id: 'user-peer', role: 'user', parts: [{ type: 'text', text: 'Give the answer.' }] }] }))+ await h.send('message.start')+ await h.send('message.delta', { text: ANSWER })+ await h.send('message.complete', {+ text: ANSWER,+ persisted_turn: {+ row_ids: [71, 72], user_row_id: 71, user_row_ids: [71], final_assistant_row_id: 72, complete: true,+ submission_id: 'sent-from-another-window'+ }+ })++ expect(h.state().messages.find(m => m.id === 'user-peer')?.rowId).toBe(71)+ h.dispose()+})+const timeline = (messages: ChatMessage[]) => messages.map(message => [message.role, chatMessageText(message)])const flush = () =>diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.tsindex 68234a42b1b..5730ee918df 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts@@ -48,39 +48,10 @@ import {import { useGatewayEventHandler } from './gateway-event'import { handleServerRequest as dispatchServerRequest } from './gateway-event/server-requests'import { extendInterruptedReply } from './interrupted-reply'+import { bindReceiptUserRows } from './receipt-user-rows'import { currentResponseParts, mergeCurrentResponseText } from './response-parts'import { completionErrorText, delegateTaskPayloads, MAX_STREAM_FLUSH_GAP_MS, STREAM_DELTA_FLUSH_MS } from './utils'-/**- * A complete receipt names the turn's one stored prompt row. A host whose- * submit acknowledgement cannot name it (the session authority queues the turn- * and writes the row when it runs) leaves the optimistic prompt without a row- * id; bind it here so a transcript read keyed on stored rows (switch-back,- * peer refresh) replaces that bubble instead of painting the prompt twice.- */-function bindReceiptPrompt(- messages: ChatMessage[],- promptIndex: number,- persistedTurn: PersistedTurn | null | undefined-): ChatMessage[] {- const rowId = persistedTurn?.complete === true ? persistedTurn.user_row_id : undefined- const prompt = messages[promptIndex]-- if (- typeof rowId !== 'number' ||- !Number.isSafeInteger(rowId) ||- rowId <= 0 ||- prompt?.role !== 'user' ||- prompt.rowId !== undefined ||- !prompt.id.startsWith('user-') ||- prompt.id.startsWith('user-queued-')- ) {- return messages- }-- return messages.map((message, index) => (index === promptIndex ? { ...message, rowId } : message))-}-interface MessageStreamOptions {activeGatewayProfile?: stringactiveSessionIdRef: MutableRefObject<string | null>@@ -1066,7 +1037,7 @@ export function useMessageStream({// degraded websocket leaves its tool row spinning forever. The turn is// provably done here — nothing can still be running — so seal any// tool-call parts that never saw their completion event.- nextMessages = bindReceiptPrompt(sealOpenToolParts(nextMessages), lastUserIndex, persistedTurn)+ nextMessages = bindReceiptUserRows(sealOpenToolParts(nextMessages), persistedTurn)const hasInlineError = nextMessages.some((m, index) => index > lastUserIndex && m.role === 'assistant' && m.error && !m.hiddendiff --git a/apps/desktop/src/app/session/hooks/use-message-stream/receipt-user-rows.ts b/apps/desktop/src/app/session/hooks/use-message-stream/receipt-user-rows.tsnew file mode 100644index 00000000000..404093d40e6--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/receipt-user-rows.ts@@ -0,0 +1,94 @@+import type { PersistedTurn } from '@hermes/shared'++import { transcriptRowIds } from '@/app/session/hooks/use-session-actions/pending-turn-identity'+import type { ChatMessage } from '@/lib/chat-messages'++const isRowId = (value: unknown): value is number =>+ typeof value === 'number' && Number.isSafeInteger(value) && value > 0++/** The receipt's stored user rows in turn order (prompt first, then each steer/redirect row). */+function receiptUserRowIds(receipt: PersistedTurn): number[] {+ const listed = receipt.user_row_ids++ if (Array.isArray(listed) && listed.length && listed.every(isRowId)) {+ return listed+ }++ // A host that lists no user rows still names the prompt; on its own that is the+ // whole set only when the receipt vouches for the entire turn.+ return isRowId(receipt.user_row_id) && receipt.complete === true ? [receipt.user_row_id] : []+}++const isTurnUserBubble = (message: ChatMessage) =>+ message.role === 'user' && !message.hidden && !message.id.startsWith('user-queued-')++/**+ * Give the turn's on-screen user bubbles the stored row ids its completion+ * receipt names. A host that queues the turn (the session authority) writes the+ * prompt row only when the turn runs, and a steer/redirect row is written+ * mid-turn, so no submit acknowledgement can carry them. Without a row id, a+ * later transcript read keyed on stored rows (switch-back graft, peer refresh)+ * keeps the optimistic bubble beside its stored copy and paints the prompt twice.+ *+ * Pairing is positional within the turn and never by text:+ * - the turn starts at the sender's own optimistic prompt (`user-<submission_id>`);+ * - a window that did not send it (another window, a queued follow-up) starts+ * after the last row that belongs to an earlier turn, and binds only when it+ * shows exactly the receipt's user rows;+ * - a bubble that already carries a different row id means the pairing is+ * wrong, and nothing is bound.+ */+export function bindReceiptUserRows(messages: ChatMessage[], receipt: PersistedTurn | null | undefined): ChatMessage[] {+ const ids = receipt ? receiptUserRowIds(receipt) : []++ if (!receipt || !ids.length) {+ return messages+ }++ const anchor =+ typeof receipt.submission_id === 'string' && receipt.submission_id+ ? messages.findIndex(message => message.role === 'user' && message.id === `user-${receipt.submission_id}`)+ : -1++ const turnRows = new Set(receipt.row_ids)++ const start =+ anchor >= 0+ ? anchor+ : messages.findLastIndex(message => {+ const rows = transcriptRowIds(message)++ return rows.length > 0 && !rows.some(id => turnRows.has(id))+ }) + 1++ const candidates = messages.flatMap((message, index) => (index >= start && isTurnUserBubble(message) ? [index] : []))++ // Unanchored, a missing bubble makes every later pairing ambiguous. Anchored,+ // the prompt is still certain even when a later bubble is absent.+ const paired =+ anchor >= 0 ? (candidates.length >= ids.length ? ids.length : 1) : candidates.length === ids.length ? ids.length : 0++ const binding = new Map<number, number>()++ for (let i = 0; i < paired; i += 1) {+ const current = messages[candidates[i]].rowId++ if (current !== undefined && current !== ids[i]) {+ return messages+ }++ if (current === undefined) {+ binding.set(candidates[i], ids[i])+ }+ }++ if (!binding.size) {+ return messages+ }++ return messages.map((message, index) => {+ const rowId = binding.get(index)++ return rowId === undefined ? message : { ...message, rowId }+ })+}