The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): reconcile refreshed transcripts by acknowledged occurrence
brooklyn!a87310a3432d
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 2a77e18d248..9a10d3e641f 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@@ -4,7 +4,7 @@ import { act, cleanup, renderHook } from '@testing-library/react'import { useRef } from 'react'import { afterEach, beforeEach, expect, it, vi } from 'vitest'-import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'+import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'import {clearInFlightTurnJournal,readInFlightTurnJournal,@@ -15,6 +15,7 @@ import { $sessionStates } from '@/store/session-states'import { usePromptActions } from '../use-prompt-actions'import { useSessionStateCache } from '../use-session-state-cache'+import { reconcileDurableHistory } from '../use-session-actions/utils'import { useMessageStream } from './index'@@ -28,7 +29,7 @@ const requestGateway = async <T,>(method: string): Promise<T> =>// Real submit/redirect, stream reducer, cache and view publication; only RPC// acceptance and history/metadata I/O are stand-ins.-function mount() {+function mount(rpc = requestGateway) {const queryClient = new QueryClient()const hydrate = vi.fn(noop)@@ -68,7 +69,7 @@ function mount() {handleSkinCommand: () => '',openMemoryGraph: () => undefined,refreshSessions: noop,- requestGateway,+ requestGateway: rpc,resumeStoredSession: noop,runtimeIdByStoredSessionIdRef: cache.runtimeIdByStoredSessionIdRef,selectedStoredSessionIdRef: cache.selectedStoredSessionIdRef,@@ -106,6 +107,71 @@ function mount() {}}+it('binds a late submit acknowledgement to its exact optimistic prompt without reviving the turn', async () => {+ const laterUser: ChatMessage = { id: 'later-user', role: 'user', parts: [{ type: 'text', text: 'Give the answer.' }] }+ const h = mount(async <T,>(): Promise<T> => {+ await h.send('message.start')+ await h.send('message.delta', { text: ANSWER })+ await h.send('message.complete', { text: ANSWER })+ h.update(state => ({ ...state, messages: [...state.messages, laterUser], needsInput: true }))+ await flush()+ return { status: 'started', user_row_id: 71 } as T+ })++ await h.submit()+ await flush()++ expect(h.state().messages[0].rowId).toBe(71)+ expect($messages.get()[0].rowId).toBe(71)+ expect(h.state().messages.at(-1)).toBe(laterUser)+ expect(h.state()).toMatchObject({ busy: false, awaitingResponse: false, needsInput: true, streamId: null })+ h.dispose()+})++it.each([true, false, undefined])(+ 'keeps the final occurrence receipt (complete=%s) before a queued prompt',+ async complete => {+ const h = mount()+ await h.submit()+ await h.send('message.start')+ await h.send('message.delta', { text: ANSWER })+ await flush()+ const assistantId = h.state().streamId+ const queued: ChatMessage = { id: `user-queued-${SID}`, role: 'user', parts: [{ type: 'text', text: 'Next' }] }+ h.update(state => ({ ...state, messages: [...state.messages, queued] }))+ const receipt =+ complete === undefined+ ? undefined+ : {+ row_ids: [71, 72, 73],+ user_row_id: 71,+ final_assistant_row_id: 73,+ complete+ }++ await h.send('message.complete', { text: ANSWER, persisted_turn: receipt })++ const settled = h.state().messages.find(message => message.id === assistantId)!+ expect(settled.pending).toBe(false)+ expect(settled.rowId).toBe(receipt?.final_assistant_row_id)+ expect(settled.parts.findLast(part => part.type === 'text')?.sourceRowId).toBe(receipt?.final_assistant_row_id)+ expect(settled.durableComplete === true).toBe(complete === true)+ expect(settled.persistedTurn).toEqual(receipt)+ expect(h.state().messages.at(-1)).toBe(queued)++ if (complete === true) {+ const latestPage = toChatMessages([{ id: 73, role: 'assistant', content: ANSWER }])+ h.update(state => ({ ...state, messages: reconcileDurableHistory(latestPage, state.messages) }))+ await flush()+ expect(timeline($messages.get())).toEqual([+ ['assistant', ANSWER],+ ['user', 'Next']+ ])+ }+ 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/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.tsindex a1fc314e0ce..910b0b87851 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts@@ -350,7 +350,14 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {}: undefined- completeAssistantMessage(sessionId, finalText, payload?.response_previewed, failure, occurredAt)+ completeAssistantMessage(+ sessionId,+ finalText,+ payload?.response_previewed,+ failure,+ occurredAt,+ payload?.persisted_turn+ )// Onboarding's first build: between turns is the only moment Setup may// put a check-in into that session (no-op everywhere else).diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.tsindex 575e1565e14..d5e6217b676 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/types.ts@@ -1,4 +1,4 @@-import type { GatewayEvent } from '@hermes/shared'+import type { GatewayEvent, PersistedTurn } from '@hermes/shared'import type { QueryClient } from '@tanstack/react-query'import type { MutableRefObject } from 'react'@@ -20,7 +20,8 @@ export interface GatewayEventDeps {text: string,responsePreviewed?: boolean,failure?: { error: string; partial: boolean },- occurredAt?: number+ occurredAt?: number,+ persistedTurn?: PersistedTurn | null) => voidfailAssistantMessage: (sessionId: string,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 df1aa0db935..b6bffb47a87 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@@ -1,3 +1,4 @@+import type { PersistedTurn } from '@hermes/shared'import type { QueryClient } from '@tanstack/react-query'import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'@@ -606,7 +607,8 @@ export function useMessageStream({text: string,responsePreviewed?: boolean,failure?: { error: string; partial: boolean; surface?: ErrorSurface | null },- occurredAt = Date.now() / 1000+ occurredAt = Date.now() / 1000,+ persistedTurn?: PersistedTurn | null) => {let shouldHydrate = false@@ -655,6 +657,28 @@ export function useMessageStream({: mergeCurrentResponseText(parts, visibleFinalText, occurredAt)}+ const withPersistedIdentity = (message: ChatMessage): ChatMessage => {+ const finalRowId = persistedTurn?.final_assistant_row_id+ const hasFinalRow = typeof finalRowId === 'number' && Number.isSafeInteger(finalRowId) && finalRowId > 0+ const finalPartIndex = message.parts.findLastIndex(part => part.type === 'text')++ return {+ ...message,+ durableComplete: persistedTurn?.complete === true,+ persistedTurn: persistedTurn ?? undefined,+ // A folded bubble can already address its first source row. Keep+ // that address and bind the final response's exact source as well.+ ...(hasFinalRow+ ? {+ rowId: message.rowId ?? finalRowId,+ parts: message.parts.map((part, index) =>+ index === finalPartIndex ? { ...part, sourceRowId: finalRowId } : part+ )+ }+ : {})+ }+ }+// Settling the final response onto a bubble makes it the turn's real// reply — clear `interim` so it regains the action footer.const completeMessage = (message: ChatMessage): ChatMessage => {@@ -670,30 +694,35 @@ export function useMessageStream({}if (completionError && !keepFailedPartialText) {- return { ...settled, error: completionError, parts: settled.parts.filter(part => part.type !== 'text') }+ return withPersistedIdentity({+ ...settled,+ error: completionError,+ parts: settled.parts.filter(part => part.type !== 'text')+ })}- return {+ return withPersistedIdentity({...settled,parts: completeOpenTimelineParts(replaceTextPart(settled.parts, Boolean(message.interim)), occurredAt),...(completionError ? { error: completionError } : {})- }+ })}- const newAssistantFromCompletion = (): ChatMessage => ({- id: `assistant-${Date.now()}`,- role: 'assistant',- parts:- completionError && !keepFailedPartialText- ? []- : [{ ...assistantTextPart(finalText, occurredAt), completedAt: occurredAt }],- timestamp: occurredAt,- completedAt: occurredAt,- branchGroupId: state.pendingBranchGroup ?? undefined,- ...(durationS !== undefined ? { durationS } : {}),- ...(completionError && { error: completionError }),- ...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})- })+ const newAssistantFromCompletion = (): ChatMessage =>+ withPersistedIdentity({+ id: `assistant-${Date.now()}`,+ role: 'assistant',+ parts:+ completionError && !keepFailedPartialText+ ? []+ : [{ ...assistantTextPart(finalText, occurredAt), completedAt: occurredAt }],+ timestamp: occurredAt,+ completedAt: occurredAt,+ branchGroupId: state.pendingBranchGroup ?? undefined,+ ...(durationS !== undefined ? { durationS } : {}),+ ...(completionError && { error: completionError }),+ ...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})+ })const prev = state.messageslet nextMessages = prevdiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 5f82402114f..7c2a00bc0c3 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -1,3 +1,4 @@+import type { PromptSubmitResult } from '@hermes/shared'import { type MutableRefObject, useCallback } from 'react'import { PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'@@ -793,12 +794,16 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {try {const recoverStoredSessionId = targetStoredSessionId ?? selectedStoredSessionIdRef.current- await withSessionNotFoundResume(+ const submitted = await withSessionNotFoundResume(sessionId,recoverStoredSessionId,liveId =>withSessionBusyRetry(() =>- requestGateway('prompt.submit', submitParams(liveId), PROMPT_SUBMIT_REQUEST_TIMEOUT_MS)+ requestGateway<PromptSubmitResult>(+ 'prompt.submit',+ submitParams(liveId),+ PROMPT_SUBMIT_REQUEST_TIMEOUT_MS+ )),{requestGateway,@@ -827,6 +832,26 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {// instead of erroring out and losing the session binding.{ alsoTimeout: true })++ const rowId = submitted.result?.user_row_id++ if (typeof rowId === 'number' && Number.isSafeInteger(rowId) && rowId > 0) {+ // The worker may finish before this acknowledgement arrives. Bind+ // only this send's optimistic occurrence; never reset live state or+ // assume the newest user row still belongs to this RPC.+ updateSessionState(submitted.sessionId, state => {+ const index = state.messages.findIndex(message => message.id === optimisticId && message.role === 'user')++ if (index < 0 || state.messages[index].rowId === rowId) {+ return state+ }++ return {+ ...state,+ messages: state.messages.map((message, i) => (i === index ? { ...message, rowId } : message))+ }+ })+ }} catch (firstErr) {if (firstErr instanceof SessionRecoveryAborted) {console.warn('[submit-drift-abort]', firstErr.reason, { phase: 'post-resume-retry' })diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/pending-turn-identity.ts b/apps/desktop/src/app/session/hooks/use-session-actions/pending-turn-identity.tsnew file mode 100644index 00000000000..486b2a8c48e--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/pending-turn-identity.ts@@ -0,0 +1,78 @@+import type { ChatMessage } from '@/lib/chat-messages'+import { isLiveTailReplyId } from '@/lib/spoken-reply'++/** A hydrated bubble can contain several source rows, including the final reply. */+export function transcriptRowIds(message: ChatMessage): number[] {+ const ids = message.parts.flatMap(part => (part.sourceRowId !== undefined ? [part.sourceRowId] : []))++ return message.rowId === undefined ? ids : [message.rowId, ...ids]+}++/** Unknown identity is not a match, but remains eligible for legacy live projection. */+export function conflictingTranscriptIdentity(local: ChatMessage, authoritative: ChatMessage): boolean {+ const localIds = transcriptRowIds(local)+ const authoritativeIds = transcriptRowIds(authoritative)++ return Boolean(localIds.length && authoritativeIds.length && !localIds.some(id => authoritativeIds.includes(id)))+}++export function persistedTurnsEquivalent(a: ChatMessage['persistedTurn'], b: ChatMessage['persistedTurn']): boolean {+ return (+ a === b ||+ Boolean(+ a &&+ b &&+ a.complete === b.complete &&+ a.user_row_id === b.user_row_id &&+ a.final_assistant_row_id === b.final_assistant_row_id &&+ a.row_ids.length === b.row_ids.length &&+ a.row_ids.every((id, index) => id === b.row_ids[index])+ )+ )+}++/** Locate an acknowledged boundary on BOTH windows. Prose and clocks are not identity. */+export function acknowledgedTranscriptBoundary(next: ChatMessage[], previous: ChatMessage[]) {+ const byId = new Map(next.map((message, index) => [message.id, index]))+ const byRow = new Map<number, number>()++ next.forEach((message, index) => {+ for (const id of transcriptRowIds(message)) {+ byRow.set(id, index)+ }+ })++ for (let localIndex = previous.length - 1; localIndex >= 0; localIndex -= 1) {+ const local = previous[localIndex]++ if (local.role === 'assistant' && (local.pending || local.interim || local.persistedTurn?.complete === false)) {+ continue+ }++ // A live bubble can still hold unpersisted segments alongside a committed+ // source. Only the terminal receipt proves the whole bubble is covered.+ if (isLiveTailReplyId(local.id) && local.durableComplete !== true) {+ continue+ }++ const finalRowId = local.persistedTurn?.final_assistant_row_id ?? local.rowId+ const storedIndex = finalRowId !== undefined ? byRow.get(finalRowId) : byId.get(local.id)++ if (storedIndex === undefined) {+ continue+ }++ const authoritative = next[storedIndex]++ if (+ authoritative.role === local.role &&+ !authoritative.pending &&+ !authoritative.interim &&+ !conflictingTranscriptIdentity(local, authoritative)+ ) {+ return { localIndex, storedIndex }+ }+ }++ return { localIndex: -1, storedIndex: -1 }+}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.tsindex 660f4ad4298..bd7fb827565 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { textWithoutReferenceLines, WIRE_REFERENCE_KINDS } from '@/components/assistant-ui/reference-kinds'-import { type ChatMessage, type ChatMessagePart, chatMessageText } from '@/lib/chat-messages'+import { type ChatMessage, type ChatMessagePart, chatMessageText, textPart } from '@/lib/chat-messages'import { $approvalModes, approvalModeForProfile } from '@/store/approval-mode'import { $desktopOnboarding, consumePendingCredentialWarning } from '@/store/onboarding'import { $activeGatewayProfile } from '@/store/profile'@@ -726,6 +726,42 @@ describe('reconcileResumeMessages', () => {})describe('preserveLocalPendingTurnMessages', () => {+ it('does not append acknowledged local history after a shifted newest page', () => {+ const previous = [+ msg('user-first', 'user', 'Original request', { timestamp: 1 }),+ msg('assistant-stream-first', 'assistant', 'Working.', { pending: false, timestamp: 2 }),+ msg('user-followup', 'user', 'Follow-up request', { timestamp: 3 }),+ msg('assistant-stream-final', 'assistant', 'Completed.', { pending: false, rowId: 30, durableComplete: true })+ ]++ const answer = msg('stored-answer', 'assistant', 'Completed.', { rowId: 30, timestamp: 5 })++ const folded = { ...answer, rowId: 20, parts: [{ ...textPart('Completed.'), sourceRowId: 30 }] }+ for (const next of [[answer], [msg('stored-followup', 'user', 'Follow-up request'), answer], [folded]]) {+ expect(preserveLocalPendingTurnMessages(next, previous)).toEqual(next)+ }++ const unacknowledged = msg('user-new', 'user', 'A new request', { timestamp: 6 })+ expect(preserveLocalPendingTurnMessages([answer], [...previous, unacknowledged])).toEqual([answer, unacknowledged])+ })++ it('keeps a newer equal reply and its prompt until that occurrence is persisted', () => {+ const previousAnswer = msg('stored-answer', 'assistant', 'Completed.', { rowId: 10 })+ const prompt = msg('user-new', 'user', 'Repeat the check', { rowId: 11 })+ const reply = msg('assistant-stream-new', 'assistant', 'Completed.', { pending: false, rowId: 12 })+ reply.parts.push({ type: 'reasoning', text: 'Reasoning only from the new occurrence.' })+ expect(reconcileResumeMessages([previousAnswer], [prompt, reply])).toEqual([previousAnswer])++ // Neither equal prose nor missing clocks can make a different persisted+ // occurrence acknowledge this one, even when the older row left the cache.+ for (const previous of [+ [previousAnswer, prompt, reply],+ [prompt, reply]+ ]) {+ expect(preserveLocalPendingTurnMessages([previousAnswer], previous)).toEqual([previousAnswer, prompt, reply])+ }+ })+it('keeps an optimistic user turn and pending assistant when the server projection is behind', () => {const next = [msg('1-user', 'user', 'first'), msg('2-assistant', 'assistant', 'first answer')]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.tsindex 81d34b4b8d6..7d517c2908d 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@@ -58,6 +58,12 @@ import { reportBackendContract, reportInstallMethodWarning } from '@/store/updatimport type { SessionCreateResponse, SessionInfo, SessionResumeResult, SessionRuntimeInfo } from '@/types/hermes'import type { ClientSessionState } from '../../../types'+import {+ acknowledgedTranscriptBoundary,+ conflictingTranscriptIdentity,+ persistedTurnsEquivalent,+ transcriptRowIds+} from './pending-turn-identity'function withAppendedText(message: ChatMessage, suffix: string): ChatMessage {let appended = false@@ -146,11 +152,11 @@ function preserveStructuralParts(message: ChatMessage, previous: ChatMessage): C// ships one), these fail tsc until someone explicitly classifies it.//// COMPARED: fields whose change must trigger a re-render (setMessages).+// Durable identity changes must publish too: view-side refresh reconciliation+// must see an acknowledgement even when its visible text is unchanged.// IGNORED: fields that are intentionally not compared — display-only metadata// or reference identity the runtime already guarantees.-// 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//@@ -162,6 +168,8 @@ const _chatMessageFieldsExhaustive: {} = {}const COMPARED_FIELDS = [+ 'rowId',+ 'persistedTurn','durableComplete','recovered','asyncResult',@@ -184,7 +192,7 @@ const COMPARED_FIELDS = ['durationS'] as const-const IGNORED_FIELDS = ['attachmentRefs', 'parts', 'rowId', 'serverRowSpan'] as const+const IGNORED_FIELDS = ['attachmentRefs', 'parts', '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.@@ -282,6 +290,8 @@ export function chatReactionsEquivalent(a: ChatMessage['reactions'], b: ChatMessexport function chatMessagesEquivalent(a: ChatMessage, b: ChatMessage): boolean {if (a.id !== b.id ||+ a.rowId !== b.rowId ||+ !persistedTurnsEquivalent(a.persistedTurn, b.persistedTurn) ||a.role !== b.role ||a.durableComplete !== b.durableComplete ||a.recovered !== b.recovered ||@@ -368,7 +378,7 @@ export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMesconst previous = previousByRoleOrdinal.get(`${message.role}:${ordinal}`)- if (!previous) {+ if (!previous || conflictingTranscriptIdentity(previous, message)) {return message}@@ -608,10 +618,14 @@ export function preserveLocalPendingTurnMessages(return nextMessages}+ const acknowledged = acknowledgedTranscriptBoundary(nextMessages, previousMessages)+ const remainingNext = nextMessages.slice(acknowledged.storedIndex + 1)+ const acknowledgedTurn = nextMessages.slice(Math.max(0, acknowledged.storedIndex))+ const lastStoredRowId = nextMessages.reduce((last, message) => Math.max(last, ...transcriptRowIds(message)), 0)const nextByRoleOrdinal = new Map<string, ChatMessage>()const nextRoleCounts = new Map<ChatMessage['role'], number>()- for (const message of nextMessages) {+ for (const message of remainingNext) {if (isGatewaySystemMarker(message)) {continue}@@ -637,7 +651,7 @@ export function preserveLocalPendingTurnMessages(const liveOptimisticUsers = new Set<ChatMessage>()if (newestOptimisticUser) {- for (let index = previousMessages.indexOf(newestOptimisticUser); index >= 0; index -= 1) {+ for (let index = previousMessages.indexOf(newestOptimisticUser); index > acknowledged.localIndex; index -= 1) {const candidate = previousMessages[index]if (candidate.role === 'user' && candidate.id.startsWith('user-')) {@@ -658,18 +672,26 @@ export function preserveLocalPendingTurnMessages(}}- const latestAuthoritativeUser = [...nextMessages].reverse().find(message => message.role === 'user')+ const latestAuthoritativeUser = [...remainingNext].reverse().find(message => message.role === 'user')const preserved: ChatMessage[] = []// Authoritative id → richer local pending row. Replacing (not appending)// avoids painting both the empty inflight shell and the full stream bubble.const replacements = new Map<string, ChatMessage>()const lastPreviousUser = previousMessages.findLastIndex(row => row.role === 'user' && !isGatewaySystemMarker(row))+ let crossedUserBoundary = false- for (const message of previousMessages) {- if (isGatewaySystemMarker(message)) {+ for (const [index, message] of previousMessages.entries()) {+ if (index <= acknowledged.localIndex || isGatewaySystemMarker(message)) {continue}+ crossedUserBoundary ||= message.role === 'user' || message.role === 'system'+ // A second segment of the acknowledged turn can still be folded into its+ // final row. A new prompt closes that ownership; identical later replies+ // must not be consumed by the already-acknowledged prefix.+ const candidates = (crossedUserBoundary ? remainingNext : acknowledgedTurn).filter(+ candidate => !conflictingTranscriptIdentity(message, candidate)+ )const ordinal = previousRoleCounts.get(message.role) ?? 0previousRoleCounts.set(message.role, ordinal + 1)@@ -700,16 +722,25 @@ export function preserveLocalPendingTurnMessages(continue}+ // The submit receipt already proved this row was saved. If the newest+ // page has advanced beyond it, its absence is pagination, not unsent input.+ if (isOptimisticUser && message.rowId !== undefined && message.rowId <= lastStoredRowId) {+ continue+ }+if (isOptimisticUser &&latestAuthoritativeUser &&+ !conflictingTranscriptIdentity(message, latestAuthoritativeUser) &&textWithoutReferenceLines(chatMessageText(latestAuthoritativeUser)) ===textWithoutReferenceLines(chatMessageText(message))) {continue}- const authoritative = nextByRoleOrdinal.get(`${message.role}:${ordinal}`)+ const ordinalMatch = nextByRoleOrdinal.get(`${message.role}:${ordinal}`)+ const authoritative =+ ordinalMatch && !conflictingTranscriptIdentity(message, ordinalMatch) ? ordinalMatch : undefined// A settled stream row (`pending: false` after message.complete) whose reply// the authoritative transcript already carries under its committed id is@@ -720,7 +751,7 @@ export function preserveLocalPendingTurnMessages(if (isPendingAssistant &&message.pending !== true &&- nextMessages.some(+ candidates.some(candidate =>candidate.role === 'assistant' &&textWithoutReferenceLines(chatMessageText(candidate)) === textWithoutReferenceLines(chatMessageText(message))@@ -770,7 +801,7 @@ export function preserveLocalPendingTurnMessages(if (isPendingAssistant) {const nextText = textWithoutReferenceLines(chatMessageText(message))- const committedMatch = nextMessages.find(+ const committedMatch = candidates.find(candidate =>candidate.role === 'assistant' &&!isLiveTailRow(candidate) &&@@ -782,7 +813,7 @@ export function preserveLocalPendingTurnMessages(continue}- const committedPrefix = nextMessages.find(+ const committedPrefix = candidates.find(candidate =>candidate.role === 'assistant' &&!isLiveTailRow(candidate) &&@@ -806,7 +837,7 @@ export function preserveLocalPendingTurnMessages(if (isPendingAssistant &&previousMessages.indexOf(message) > lastPreviousUser &&- durableFoldCoversLiveResponse(nextMessages, message)+ durableFoldCoversLiveResponse(candidates, message)) {continue}diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.tsindex d95bfc734ce..f59d83fd781 100644--- a/apps/desktop/src/lib/chat-messages/types.ts+++ b/apps/desktop/src/lib/chat-messages/types.ts@@ -1,5 +1,5 @@import type { ThreadMessageLike } from '@assistant-ui/react'-import { type BillingBlock, type ToolLabel } from '@hermes/shared'+import { type BillingBlock, type PersistedTurn, type ToolLabel } from '@hermes/shared'import type { ErrorSurface } from '@/lib/error-surface'import type { ToolResultMetadata } from '@/lib/tool-result-metadata'@@ -48,6 +48,8 @@ export type ChatMessage = {recovered?: boolean/** Whether hydration reached a final assistant source row, rather than a tool round. */durableComplete?: boolean+ /** Exact gateway receipt; whole-turn coverage is never inferred from prose. */+ persistedTurn?: PersistedTurn/** Whole-turn wall-clock seconds (message.start → message.complete),* stamped by the desktop when it watched the turn run. Absent for* messages hydrated from history — the backend doesn't persist it. */@@ -202,6 +204,7 @@ export type GatewayEventPayload = {// message.complete — signals the final text was already previewed via// interim_assistant_callback, so the UI can settle instead of duplicating.response_previewed?: boolean+ persisted_turn?: PersistedTurn | null// message.complete — history-commit note the gateway surfaced instead of dropping.warning?: string// message.complete with status "error" — `text` is streamed partial output