The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): preserve transcript occurrences across resume and completion
BearHuddleston01d934f1d663
diff --git a/apps/desktop/src/app/contrib/hooks/completed-reply-refresh.test.tsx b/apps/desktop/src/app/contrib/hooks/completed-reply-refresh.test.tsxnew file mode 100644index 00000000000..f554c8b084a--- /dev/null+++ b/apps/desktop/src/app/contrib/hooks/completed-reply-refresh.test.tsx@@ -0,0 +1,498 @@+import { useAuiState } from '@assistant-ui/react'+import type { GatewayEvent } from '@hermes/shared'+import { useStore } from '@nanostores/react'+import { QueryClient } from '@tanstack/react-query'+import { act, cleanup, render, screen } from '@testing-library/react'+import { useCallback, useRef } from 'react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { ChatRuntimeBoundary } from '@/app/chat'+import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'+import { mergeOlderTranscriptPage } from '@/app/chat/transcript-backfill'+import { useMessageStream } from '@/app/session/hooks/use-message-stream'+import { useSessionStateCache } from '@/app/session/hooks/use-session-state-cache'+import { stubThreadEnvironment } from '@/components/assistant-ui/test-utils'+import { getLatestSessionMessages } from '@/hermes'+import { chatMessageText, toChatMessages } from '@/lib/chat-messages'+import { resetLiveSync } from '@/store/live-sync'+import {+ $busy,+ setActiveSessionId,+ setAwaitingResponse,+ setBusy,+ setMessages,+ setSelectedStoredSessionId+} from '@/store/session'+import { $sessionStates, $sessionTiles, clearAllSessionStates } from '@/store/session-states'+import { $todosBySession, clearSessionTodos, setSessionTodos } from '@/store/todos'+import type { SessionMessage } from '@/types/hermes'++import {+ hydrateStoredSessionTranscript,+ reconcileActiveTranscript,+ reconcileTileTranscripts,+ useBackgroundSync+} from './use-background-sync'++vi.mock('@/hermes', async original => ({+ ...(await original<Record<string, unknown>>()),+ getLatestSessionMessages: vi.fn()+}))++stubThreadEnvironment()++const RUNTIME = 'refresh-runtime'+const STORED = 'refresh-stored'+const FINAL = 'The completed answer must stay visible.'++const history: SessionMessage[] = [+ { id: 1, role: 'user', content: 'Earlier question', timestamp: 1 },+ { id: 2, role: 'assistant', content: 'Earlier answer', timestamp: 2 },+ { id: 3, role: 'user', content: 'Latest question', timestamp: 3 }+]++const toolRound: SessionMessage[] = [+ ...history,+ {+ id: 4,+ role: 'assistant',+ content: '',+ timestamp: 4,+ tool_calls: [+ { id: 'read-tool', type: 'function', function: { name: 'read_file', arguments: '{"path":"example.txt"}' } }+ ]+ },+ { id: 5, role: 'tool', content: 'example content', timestamp: 5, tool_call_id: 'read-tool', tool_name: 'read_file' }+]++const completeHistory: SessionMessage[] = [...toolRound, { id: 6, role: 'assistant', content: FINAL, timestamp: 6 }]+const noop = async () => undefined+let cache: ReturnType<typeof useSessionStateCache>+let stream: ReturnType<typeof useMessageStream>+let refresh: () => Promise<void>++function ObserveRuntime() {+ const messages = useAuiState(state => state.thread.messages)++ return (+ <output data-testid="runtime">+ {messages+ .map(message =>+ message.content+ .filter(part => part.type === 'text')+ .map(part => part.text)+ .join('')+ )+ .join('\n')}+ </output>+ )+}++function Harness({+ backgroundSync = false,+ tile = false,+ fallback = false+}: {+ backgroundSync?: boolean+ tile?: boolean+ fallback?: boolean+}) {+ const busyRef = useRef(false)+ const queryClient = useRef(new QueryClient()).current+ const requestSequenceRef = useRef(0)+ const signatureRef = useRef(new Map<string, string>())+ cache = useSessionStateCache({+ activeSessionId: tile ? 'other-runtime' : RUNTIME,+ selectedStoredSessionId: tile ? 'other-stored' : STORED,+ busyRef,+ setBusy,+ setAwaitingResponse,+ setMessages+ })+ const { activeSessionIdRef, selectedStoredSessionIdRef, updateSessionState } = cache++ const hydrate = useCallback(+ async (attempts = 1, storedSessionId: string | null = STORED, runtimeSessionId: string | null = RUNTIME) => {+ if (storedSessionId && runtimeSessionId) {+ await hydrateStoredSessionTranscript({+ attempts,+ storedSessionId,+ runtimeSessionId,+ storedProfile: 'default',+ updateSessionState+ })+ }+ },+ [updateSessionState]+ )++ stream = useMessageStream({+ ...cache,+ queryClient,+ hydrateFromStoredSession: fallback ? hydrate : noop,+ refreshHermesConfig: noop,+ refreshSessions: noop+ })+ refresh = useCallback(+ () =>+ tile+ ? reconcileTileTranscripts({+ requestSequenceRef,+ signatureRef,+ updateSessionState,+ tiles: [{ runtimeId: RUNTIME, storedSessionId: STORED }]+ })+ : reconcileActiveTranscript({+ activeSessionIdRef,+ selectedStoredSessionIdRef,+ updateSessionState,+ busyRef,+ requestSequenceRef,+ signatureRef,+ resolveSession: () => ({ profile: 'default' })+ }),+ [activeSessionIdRef, selectedStoredSessionIdRef, updateSessionState, tile]+ )+ useBackgroundSync({+ activeConnectionId: 'local',+ activeGatewayProfile: 'default',+ activeIsMessaging: false,+ activeSessionId: tile ? 'other-runtime' : RUNTIME,+ activeStoredSessionId: tile ? 'other-stored' : STORED,+ freshDraftReady: false,+ gatewayState: backgroundSync ? 'open' : 'closed',+ refreshActiveTranscript: refresh,+ refreshCronJobs: noop,+ refreshCurrentModel: noop,+ refreshHermesConfig: noop,+ refreshMessagingSessions: noop,+ refreshSessions: noop,+ requestGateway: async () => ({ sessions: [] }) as never,+ updateSessionState: cache.updateSessionState+ })+ const busy = useStore(PRIMARY_SESSION_VIEW.$busy)++ return (+ <ChatRuntimeBoundary+ busy={busy}+ onCancel={noop}+ onEdit={noop}+ onReload={noop}+ onThreadMessagesChange={noop}+ suppressMessages={false}+ >+ <ObserveRuntime />+ </ChatRuntimeBoundary>+ )+}++function send(type: GatewayEvent['type'], payload: GatewayEvent['payload'] = {}) {+ act(() => stream.handleGatewayEvent({ session_id: RUNTIME, type, payload }))+}++function deferredHistory() {+ let resolve!: (page: Awaited<ReturnType<typeof getLatestSessionMessages>>) => void++ const promise = new Promise<Awaited<ReturnType<typeof getLatestSessionMessages>>>(yes => {+ resolve = yes+ })++ return { promise, resolve }+}++async function finishTurn() {+ send('message.start')+ send('tool.start', { name: 'read_file', tool_id: 'read-tool', args: { path: 'example.txt' } })+ send('tool.complete', { name: 'read_file', tool_id: 'read-tool', result: 'example content' })+ send('message.delta', { text: FINAL })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(100)+ })+ send('message.complete', { text: FINAL })+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.mocked(getLatestSessionMessages).mockReset()+ setActiveSessionId(RUNTIME)+ setSelectedStoredSessionId(STORED)+})++afterEach(() => {+ cleanup()+ clearSessionTodos(RUNTIME)+ clearAllSessionStates()+ $sessionTiles.set([])+ resetLiveSync()+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ setBusy(false)+ setAwaitingResponse(false)+ setMessages([])+ localStorage.clear()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++it.each([false, true])(+ 'rejects a history read spanning a completed turn, then accepts fresh history (tile: %s)',+ async tile => {+ if (tile) {+ setActiveSessionId('other-runtime')+ setSelectedStoredSessionId('other-stored')+ $sessionTiles.set([{ runtimeId: RUNTIME, storedSessionId: STORED }])+ }++ render(<Harness tile={tile} />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))+ const delayed = deferredHistory()+ vi.mocked(getLatestSessionMessages).mockReturnValueOnce(delayed.promise)+ const pending = refresh()+ await finishTurn()+ const completed = $sessionStates.get()[RUNTIME].messages+ expect(completed.map(chatMessageText)).toContain(FINAL)++ if (!tile) {+ expect(screen.getByTestId('runtime').textContent).toContain(FINAL)+ }++ await act(async () => {+ delayed.resolve({ session_id: STORED, messages: toolRound })+ await pending+ })+ expect.soft($sessionStates.get()[RUNTIME].messages).toBe(completed)++ if (!tile) {+ expect.soft(screen.getByTestId('runtime').textContent).toContain(FINAL)+ }++ vi.mocked(getLatestSessionMessages).mockResolvedValueOnce({ session_id: STORED, messages: completeHistory })+ await act(async () => {+ await refresh()+ })+ const texts = $sessionStates.get()[RUNTIME].messages.map(chatMessageText)+ expect(texts.filter(text => text.includes(FINAL))).toHaveLength(1)+ expect(texts).toContain('Earlier answer')+ }+)++it('retries an interrupted reconnect read once on idle, even before that read returns', async () => {+ const stale = deferredHistory()+ const fresh = deferredHistory()+ vi.mocked(getLatestSessionMessages).mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise)+ render(<Harness backgroundSync />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))+ await finishTurn()+ expect.soft(getLatestSessionMessages).toHaveBeenCalledTimes(2)++ await act(async () => {+ fresh.resolve({ session_id: STORED, messages: completeHistory })+ await fresh.promise+ stale.resolve({ session_id: STORED, messages: toolRound })+ await stale.promise+ })+ expect.soft(screen.getByTestId('runtime').textContent).toContain(FINAL)+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000)+ })+ expect.soft(getLatestSessionMessages).toHaveBeenCalledTimes(2)+ const texts = $sessionStates.get()[RUNTIME].messages.map(chatMessageText)+ expect(texts.filter(text => text.includes(FINAL))).toHaveLength(1)+})++it.each([+ { tile: false, mutation: 'backfill' },+ { tile: true, mutation: 'backfill' },+ { tile: false, mutation: 'retention' },+ { tile: true, mutation: 'retention' }+])('accepts an external answer during prefix-only $mutation (tile: $tile)', async ({ tile, mutation }) => {+ if (tile) {+ setActiveSessionId('other-runtime')+ setSelectedStoredSessionId('other-stored')+ $sessionTiles.set([{ runtimeId: RUNTIME, storedSessionId: STORED }])+ }++ render(<Harness tile={tile} />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))+ const delayed = deferredHistory()+ vi.mocked(getLatestSessionMessages).mockReturnValueOnce(delayed.promise)+ const pending = refresh()+ const older = toChatMessages([{ id: 0, role: 'assistant', content: 'Backfilled answer', timestamp: 0 }])+ act(() =>+ cache.updateSessionState(+ RUNTIME,+ state => ({+ ...state,+ // Retention releases a prefix with slice; backfill prepends older rows.+ // Neither changes the existing tail nor emits a busy edge.+ messages: mutation === 'backfill' ? mergeOlderTranscriptPage(state.messages, older) : state.messages.slice(1)+ }),+ STORED+ )+ )+ await act(async () => {+ delayed.resolve({+ session_id: STORED,+ messages: [...history, { id: 4, role: 'assistant', content: 'External answer', timestamp: 4 }]+ })+ await pending+ })+ const texts = $sessionStates.get()[RUNTIME].messages.map(chatMessageText)+ expect(texts).toContain('External answer')+ expect(texts).toContain('Earlier answer')++ if (mutation === 'backfill') {+ expect(texts).toContain('Backfilled answer')+ }++ expect(getLatestSessionMessages).toHaveBeenCalledTimes(1)+})++it('rejects a read when an existing row changes even if the last row is untouched', async () => {+ render(<Harness />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))+ const delayed = deferredHistory()+ vi.mocked(getLatestSessionMessages).mockReturnValueOnce(delayed.promise)+ const pending = refresh()+ act(() =>+ cache.updateSessionState(+ RUNTIME,+ state => ({+ ...state,+ messages: state.messages.map((message, index) =>+ index === 1 ? { ...message, parts: [{ type: 'text' as const, text: 'Edited answer' }] } : message+ )+ }),+ STORED+ )+ )+ await act(async () => {+ delayed.resolve({ session_id: STORED, messages: history })+ await pending+ })+ expect($sessionStates.get()[RUNTIME].messages.map(chatMessageText)).toContain('Edited answer')+})++it('keeps the reply and retries when a complete turn fits between view animation frames', async () => {+ const stale = deferredHistory()+ vi.mocked(getLatestSessionMessages)+ .mockReturnValueOnce(stale.promise)+ .mockResolvedValue({ session_id: STORED, messages: completeHistory })+ render(<Harness backgroundSync />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))+ const busyEdges: boolean[] = []+ const unsubscribe = $busy.listen(value => busyEdges.push(value))+ await act(async () => {+ stream.handleGatewayEvent({ session_id: RUNTIME, type: 'message.start', payload: {} })+ stream.handleGatewayEvent({ session_id: RUNTIME, type: 'message.delta', payload: { text: FINAL } })+ stream.handleGatewayEvent({ session_id: RUNTIME, type: 'message.complete', payload: { text: FINAL } })+ })+ unsubscribe()+ expect(busyEdges).not.toContain(true)+ expect(screen.getByTestId('runtime').textContent).toContain(FINAL)+ expect.soft(getLatestSessionMessages).toHaveBeenCalledTimes(2)+ await act(async () => {+ stale.resolve({ session_id: STORED, messages: toolRound })+ await stale.promise+ })+ expect(screen.getByTestId('runtime').textContent).toContain(FINAL)+ expect(getLatestSessionMessages).toHaveBeenCalledTimes(2)+})++it('rejects post-turn fallback history overtaken by another completed turn, including its todo restore', async () => {+ render(<Harness fallback />)+ act(() =>+ cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history.slice(-1)) }), STORED)+ )+ const stale = deferredHistory()+ vi.mocked(getLatestSessionMessages).mockReturnValueOnce(stale.promise)+ send('message.start')+ send('message.complete')+ expect(getLatestSessionMessages).toHaveBeenCalledTimes(1)+ await finishTurn()+ act(() => setSessionTodos(RUNTIME, [{ id: 'new-todo', content: 'New turn todo', status: 'pending' }]))+ await act(async () => {+ stale.resolve({ session_id: STORED, messages: toolRound })+ await stale.promise+ })+ expect.soft(screen.getByTestId('runtime').textContent).toContain(FINAL)+ expect($todosBySession.get()[RUNTIME]).toEqual([{ id: 'new-todo', content: 'New turn todo', status: 'pending' }])+})++it('still hydrates a missing completion after a transient read failure', async () => {+ render(<Harness fallback />)+ act(() =>+ cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history.slice(-1)) }), STORED)+ )+ vi.mocked(getLatestSessionMessages)+ .mockRejectedValueOnce(new Error('transient read failure'))+ .mockResolvedValueOnce({ session_id: STORED, messages: completeHistory })+ send('message.start')+ send('message.complete')+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300)+ })+ expect(getLatestSessionMessages).toHaveBeenCalledTimes(2)+ expect(screen.getByTestId('runtime').textContent).toContain(FINAL)+})++it.each(['unmount', 'navigation'] as const)('retires an interrupted refresh on %s', async mode => {+ const stale = deferredHistory()+ vi.mocked(getLatestSessionMessages).mockReturnValueOnce(stale.promise)+ const view = render(<Harness backgroundSync />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))+ send('message.start')++ if (mode === 'unmount') {+ view.unmount()+ } else {+ act(() => {+ setActiveSessionId('other-runtime')+ setSelectedStoredSessionId('other-stored')+ })+ view.rerender(<Harness backgroundSync tile />)+ }++ await finishTurn()+ await act(async () => {+ stale.resolve({ session_id: STORED, messages: toolRound })+ await stale.promise+ })++ if (mode === 'navigation') {+ act(() => {+ setActiveSessionId(RUNTIME)+ setSelectedStoredSessionId(STORED)+ })+ view.rerender(<Harness backgroundSync />)+ await finishTurn()+ }++ expect(getLatestSessionMessages).toHaveBeenCalledTimes(1)+})++it('does not let an older finalizer retire the newest refresh observation', async () => {+ const stale = deferredHistory()+ const replacement = deferredHistory()+ vi.mocked(getLatestSessionMessages)+ .mockReturnValueOnce(stale.promise)+ .mockReturnValueOnce(replacement.promise)+ .mockResolvedValue({ session_id: STORED, messages: completeHistory })+ const view = render(<Harness backgroundSync />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))+ // Close/reopen creates a fresh scoped connect read while the old one waits.+ view.rerender(<Harness />)+ view.rerender(<Harness backgroundSync />)+ expect(getLatestSessionMessages).toHaveBeenCalledTimes(2)+ await act(async () => {+ stale.resolve({ session_id: STORED, messages: history })+ await stale.promise+ })+ await finishTurn()+ await act(async () => {+ replacement.resolve({ session_id: STORED, messages: toolRound })+ await replacement.promise+ })+ expect(getLatestSessionMessages).toHaveBeenCalledTimes(3)+ expect(screen.getByTestId('runtime').textContent).toContain(FINAL)+})diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex 27414635e76..136867a96b5 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -4,9 +4,10 @@ import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'import { preserveLocalPendingTurnMessages } from '@/app/session/hooks/use-session-actions/utils'import { getLatestSessionMessages, type ProfileScope } from '@/hermes'-import { preserveLocalAssistantErrors, sealOpenToolParts, toChatMessages } from '@/lib/chat-messages'+import { type ChatMessage, preserveLocalAssistantErrors, sealOpenToolParts, toChatMessages } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { sessionMessagesSignature } from '@/lib/session-signatures'+import { latestSessionTodos } from '@/lib/todos'import { $sidebarShowArchived } from '@/store/layout'import { $changeEventsAvailable, $cronChangeTick, $sessionsChangeTick } from '@/store/live-sync'import { $onBattery, batteryPollInterval } from '@/store/power'@@ -32,6 +33,7 @@ import {setSessionStalled} from '@/store/session-states'import { loadArchivedSessions } from '@/store/sidebar-archive'+import { clearSessionTodos, setSessionTodos, todosForHydration } from '@/store/todos'import type { ClientSessionState } from '../../types'import type { GatewayRequester } from '../types'@@ -101,6 +103,29 @@ function tileRuntimeOwnsLiveState(runtimeId: string): boolean {return Boolean(state && (state.busy || state.awaitingResponse || state.needsInput || state.turnLive))}+/** Backfill/retention may prepend or release a prefix without changing the tail. */+function transcriptChangedDuringRead(before: ChatMessage[] | undefined, after: ChatMessage[] | undefined): boolean {+ if (before === after) {+ return false+ }++ if (!before?.length || !after?.length) {+ return true+ }++ // Require the entire shorter transcript to be an unchanged suffix. Matching+ // only the last row would miss edits/tool updates earlier in the current turn.+ const overlap = Math.min(before.length, after.length)++ for (let offset = 1; offset <= overlap; offset += 1) {+ if (before[before.length - offset] !== after[after.length - offset]) {+ return true+ }+ }++ return false+}+type TileTranscriptTarget = { ownerRoute?: SessionOwnerRoute; storedSessionId: string; runtimeId?: string }/** Signature key per tile — carries the owner route so two connections/profiles@@ -184,6 +209,7 @@ export async function reconcileTileTranscripts({const profileScope = profileScopeForTranscriptSession(tile)const signatureKey = tileTranscriptSignatureKey(tile)+ const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messagestry {// Passive: a hidden tile's refresh must never cold-start its owner@@ -193,6 +219,7 @@ export async function reconcileTileTranscripts({if (requestId !== requestSequenceRef.current ||tileRuntimeOwnsLiveState(runtimeSessionId) ||+ transcriptChangedDuringRead(messagesAtRequest, $sessionStates.get()[runtimeSessionId]?.messages) ||!tileStillPresent()) {// Tile closed or superseded mid-read — discard AND prune its@@ -233,6 +260,72 @@ export async function reconcileTileTranscripts({}}+/** Best-effort post-turn fallback when the live stream did not carry an answer. */+export async function hydrateStoredSessionTranscript({+ attempts,+ storedSessionId,+ runtimeSessionId,+ storedProfile,+ updateSessionState+}: {+ attempts: number+ storedSessionId: string+ runtimeSessionId: string+ storedProfile: ProfileScope+ updateSessionState: ActiveTranscriptRefreshDeps['updateSessionState']+}): Promise<void> {+ const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messages++ const superseded = () =>+ tileRuntimeOwnsLiveState(runtimeSessionId) ||+ transcriptChangedDuringRead(messagesAtRequest, $sessionStates.get()[runtimeSessionId]?.messages)++ for (let index = 0; index < Math.max(1, attempts); index += 1) {+ if (superseded()) {+ return+ }++ try {+ const latest = await getLatestSessionMessages(storedSessionId, storedProfile)++ // This fallback belongs to the completed turn, not any subsequent turn+ // that ran during the read or retry delay. Its todo restore is stale too.+ if (superseded()) {+ return+ }++ const messages = toChatMessages(latest.messages)+ updateSessionState(+ runtimeSessionId,+ state => ({+ ...state,+ // Keep backfilled pages, un-acked optimistic input and local errors.+ messages: preserveLocalAssistantErrors(+ preserveLocalPendingTurnMessages(graftRefreshedTailOntoBackfill(messages, state.messages), state.messages),+ state.messages+ )+ }),+ storedSessionId+ )+ const restored = todosForHydration(latestSessionTodos(messages))++ if (restored) {+ setSessionTodos(runtimeSessionId, restored)+ } else {+ clearSessionTodos(runtimeSessionId)+ }++ return+ } catch {+ // Best-effort fallback when live stream payloads are empty.+ }++ if (index < attempts - 1) {+ await new Promise(resolve => window.setTimeout(resolve, 250))+ }+ }+}+/** Reconcile one persisted transcript snapshot into the currently viewed session. */export async function reconcileActiveTranscript({activeSessionIdRef,@@ -246,7 +339,7 @@ export async function reconcileActiveTranscript({const storedSessionId = selectedStoredSessionIdRef.currentconst runtimeSessionId = activeSessionIdRef.current- if (!storedSessionId || !runtimeSessionId || busyRef.current) {+ if (!storedSessionId || !runtimeSessionId || busyRef.current || tileRuntimeOwnsLiveState(runtimeSessionId)) {return}@@ -258,6 +351,9 @@ export async function reconcileActiveTranscript({const requestId = requestSequenceRef.current + 1requestSequenceRef.current = requestId+ // Busy at both endpoints can be false even though an entire turn streamed+ // while HTTP was in flight. Never let that older read replace newer text.+ const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messagestry {const profileScope: ProfileScope = profileScopeForTranscriptSession(stored)@@ -267,6 +363,8 @@ export async function reconcileActiveTranscript({if (requestId !== requestSequenceRef.current ||busyRef.current ||+ tileRuntimeOwnsLiveState(runtimeSessionId) ||+ transcriptChangedDuringRead(messagesAtRequest, $sessionStates.get()[runtimeSessionId]?.messages) ||selectedStoredSessionIdRef.current !== storedSessionId ||activeSessionIdRef.current !== runtimeSessionId) {@@ -631,8 +729,8 @@ export function useBackgroundSync({}: BackgroundSyncParams): void {const changeEventsAvailable = useStore($changeEventsAvailable)const cronChangeTick = useStore($cronChangeTick)- const activeTranscriptBusy = useStore($busy)const activeTranscriptRefreshPendingRef = useRef<string | null>(null)+ const activeTranscriptReadRef = useRef<{ sessionKey: string; preservePending: boolean } | null>(null)// Tile reconcile state (#93942 slice 1): shared sequence guard + per-tile// transcript signatures, so no-change ticks and closed tiles cost nothing.const tileRequestSequenceRef = useRef(0)@@ -654,7 +752,7 @@ export function useBackgroundSync({activeTranscriptRefreshPendingRef.current = sessionKey}- if ($busy.get()) {+ if ($busy.get() || tileRuntimeOwnsLiveState(runtimeSessionId)) {return}@@ -662,30 +760,89 @@ export function useBackgroundSync({activeTranscriptRefreshPendingRef.current = null}- let sawBusyDuringRead = false-- const unsubscribeBusy = $busy.listen(busy => {- sawBusyDuringRead ||= busy- })-+ const read = { sessionKey, preservePending }+ activeTranscriptReadRef.current = readvoid Promise.resolve(refreshActiveTranscript()).finally(() => {- unsubscribeBusy()-- // If streaming began while the read was in flight, reconciliation was- // discarded and the external event still needs one idle retry.- if (- preservePending &&- (sawBusyDuringRead || $busy.get()) &&- $activeSessionId.get() === runtimeSessionId &&- $selectedStoredSessionId.get() === storedSessionId- ) {- activeTranscriptRefreshPendingRef.current = sessionKey+ // A superseded request cannot retire the replacement's observation.+ if (activeTranscriptReadRef.current === read) {+ activeTranscriptReadRef.current = null}})},[activeSessionId, activeStoredSessionId, refreshActiveTranscript])+ // eslint-disable-next-line no-restricted-syntax -- request obligations updated by synchronous subscriptions, not mirrored atom values+ useEffect(() => {+ if (gatewayState !== 'open' || !activeSessionId || !activeStoredSessionId) {+ return+ }++ const sessionKey = `${activeStoredSessionId}:${activeSessionId}`+ let disposed = false+ let queued = false++ const isCurrent = () =>+ $activeSessionId.get() === activeSessionId && $selectedStoredSessionId.get() === activeStoredSessionId++ const isLive = () => $busy.get() || tileRuntimeOwnsLiveState(activeSessionId)++ const observe = () => {+ if (!isCurrent()) {+ return+ }++ if (isLive()) {+ const read = activeTranscriptReadRef.current++ if (read?.sessionKey === sessionKey) {+ // Queue once, before idle, even when a whole turn fits between RAFs+ // and the legacy $busy mirror never becomes true.+ activeTranscriptReadRef.current = null++ if (read.preservePending) {+ activeTranscriptRefreshPendingRef.current = sessionKey+ }+ }++ return+ }++ if (queued || activeTranscriptRefreshPendingRef.current !== sessionKey) {+ return+ }++ queued = true+ queueMicrotask(() => {+ queued = false++ // Let the canonical publication finish syncing the view before the+ // retry, and never carry it across navigation/profile/connection scope.+ if (!disposed && isCurrent() && !isLive() && activeTranscriptRefreshPendingRef.current === sessionKey) {+ requestActiveTranscriptRefresh(true)+ }+ })+ }++ const unsubscribeState = $sessionStates.listen(observe)+ const unsubscribeBusy = $busy.listen(observe)++ return () => {+ disposed = true+ unsubscribeState()+ unsubscribeBusy()+ activeTranscriptReadRef.current = null+ activeTranscriptRefreshPendingRef.current = null+ }+ }, [+ activeConnectionId,+ activeGatewayProfile,+ activeSessionId,+ activeStoredSessionId,+ gatewayState,+ requestActiveTranscriptRefresh+ ])+useEffect(() => {if (gatewayState !== 'open') {return@@ -933,23 +1090,6 @@ export function useBackgroundSync({)}, [changeEventsAvailable, cronChangeTick, gatewayState, refreshCronJobs])- // A busy transition only consumes a pending sessions.changed refresh. It- // never creates one, so an ordinary local turn going busy -> idle does not- // add a REST read. The event itself is coalesced by the list throttle above.- useEffect(() => {- if (- gatewayState !== 'open' ||- activeTranscriptBusy ||- !activeSessionId ||- !activeStoredSessionId ||- activeTranscriptRefreshPendingRef.current !== `${activeStoredSessionId}:${activeSessionId}`- ) {- return- }-- requestActiveTranscriptRefresh(true)- }, [activeSessionId, activeStoredSessionId, activeTranscriptBusy, gatewayState, requestActiveTranscriptRefresh])-// Preserve the pre-existing messaging behavior: refresh once when a// messaging transcript opens, then keep its visibility backstop. Desktop// sessions never enter this effect and therefore gain no periodic timer.diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 203fb37692f..c2da512f402 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -13,8 +13,6 @@ import { useQueryClient } from '@tanstack/react-query'import { type CSSProperties, lazy, type ReactNode, Suspense, useCallback, useEffect, useMemo, useRef } from 'react'import { useLocation, useNavigate } from 'react-router'-import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'-import { preserveLocalPendingTurnMessages } from '@/app/session/hooks/use-session-actions/utils'import { formatRefValue } from '@/components/assistant-ui/directive-text'import { BootFailureOverlay } from '@/components/boot-failure-overlay'import { ConfirmHost } from '@/components/confirm-host'@@ -38,11 +36,9 @@ import { RemoteDisplayBanner } from '@/components/remote-display-banner'import { SendDiagnosticsHost } from '@/components/send-diagnostics-dialog'import { TipHost } from '@/components/tips'import { emitGatewayEvent } from '@/contrib/events'-import { getLatestSessionMessages } from '@/hermes'import { translateNow } from '@/i18n'-import { type ChatMessage, chatMessageText, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'+import { type ChatMessage, chatMessageText } from '@/lib/chat-messages'import { isMessagingSource } from '@/lib/session-source'-import { latestSessionTodos } from '@/lib/todos'import { activateWakeIndicator } from '@/lib/wake-indicator'import { playWakeSound } from '@/lib/wake-sound'import { $billingSettingsRequest } from '@/store/billing-block'@@ -91,7 +87,6 @@ import {setMessages} from '@/store/session'import { $titlebarAppActionsSide, titlebarAppActionsClusterCounts } from '@/store/titlebar-app-actions'-import { clearSessionTodos, setSessionTodos, todosForHydration } from '@/store/todos'import { armWakeWord, stopClientCapture } from '@/store/wake-word'import { isAuxiliaryWindow, isBrowserWindow, isHudWindow } from '@/store/windows'import { useSkinCommand } from '@/themes/use-skin-command'@@ -155,6 +150,7 @@ import { UpdatesOverlay } from '../updates-overlay'import { ContribWiringContext } from './context'import {+ hydrateStoredSessionTranscript,profileScopeForTranscriptSession,reconcileActiveTranscript,resolveActiveTranscriptSession,@@ -492,48 +488,13 @@ export function ContribWiring({ children }: { children: ReactNode }) {resolveActiveTranscriptSession(storedSessionId, runtimeSessionId))- for (let index = 0; index < Math.max(1, attempts); index += 1) {- try {- const latest = await getLatestSessionMessages(storedSessionId, storedProfile)- const messages = toChatMessages(latest.messages)- updateSessionState(- runtimeSessionId,- state => ({- ...state,- // Post-turn rehydrate reads only the newest tail page — graft it- // onto any backfilled older pages instead of dropping them, and- // keep any un-acked optimistic `user-*` row, which lives nowhere- // else (a reconnect-triggered rehydrate would otherwise lose a- // message the user then has to retype). Same composition order- // as reconcileAuthoritativeChatMessages.- messages: preserveLocalAssistantErrors(- preserveLocalPendingTurnMessages(- graftRefreshedTailOntoBackfill(messages, state.messages),- state.messages- ),- state.messages- )- }),- storedSessionId- )-- const restored = todosForHydration(latestSessionTodos(messages))-- if (restored) {- setSessionTodos(runtimeSessionId, restored)- } else {- clearSessionTodos(runtimeSessionId)- }-- return- } catch {- // Best-effort fallback when live stream payloads are empty.- }-- if (index < attempts - 1) {- await new Promise(resolve => window.setTimeout(resolve, 250))- }- }+ await hydrateStoredSessionTranscript({+ attempts,+ storedSessionId,+ runtimeSessionId,+ storedProfile,+ updateSessionState+ })},[activeSessionIdRef, selectedStoredSessionIdRef, updateSessionState])diff --git a/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx b/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsxnew file mode 100644index 00000000000..4a30c2d58fc--- /dev/null+++ b/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx@@ -0,0 +1,344 @@+import type { GatewayEvent } from '@hermes/shared'+import { QueryClient } from '@tanstack/react-query'+import { act, cleanup, renderHook } from '@testing-library/react'+import { useRef } from 'react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { getLatestSessionMessages } from '@/hermes'+import { chatMessageText, toChatMessages } from '@/lib/chat-messages'+import { resetInFlightTurnJournalStateForTests } from '@/lib/inflight-turn-journal'+import { $activeGatewayProfile } from '@/store/profile'+import {+ _resetSessionOwnerHintsForTests,+ setActiveSessionId,+ setAwaitingResponse,+ setBusy,+ setConnection,+ setMessages,+ setSelectedStoredSessionId,+ setSessions+} from '@/store/session'+import { clearAllSessionStates } from '@/store/session-states'+import type { SessionMessage, SessionResumeResult } from '@/types/hermes'++import { useMessageStream } from './use-message-stream'+import { useSessionActions } from './use-session-actions'+import { useSessionStateCache } from './use-session-state-cache'++vi.mock('@/hermes', async original => ({+ ...(await original<Record<string, unknown>>()),+ getLatestSessionMessages: vi.fn()+}))+vi.mock('@/store/profile', async original => ({+ ...(await original<Record<string, unknown>>()),+ ensureGatewayProfile: vi.fn().mockResolvedValue(undefined)+}))++const storedId = 'resume-occurrences'+const runtimeId = 'resume-runtime'+const prompt = 'Inspect both phases'+const commentary = 'Checking the phase.'+const tail = 'The result is still growing.'+const noop = async () => undefined+const user: SessionMessage = { id: 1, role: 'user', content: prompt, timestamp: 1 }++function history(comments: string[]): SessionMessage[] {+ return [+ { ...user },+ ...comments.flatMap((content, index): SessionMessage[] => [+ {+ id: 2 + index * 2,+ role: 'assistant',+ content,+ timestamp: 2 + index * 2,+ tool_calls: [{ id: `call-${index}`, type: 'function', function: { name: 'read_file', arguments: '{}' } }]+ },+ { id: 3 + index * 2, role: 'tool', content: 'fixture', tool_call_id: `call-${index}`, timestamp: 3 + index * 2 }+ ])+ ]+}++function mount(snapshot: SessionResumeResult) {+ const requestGateway = vi.fn().mockResolvedValue(snapshot)++ const hook = renderHook(() => {+ const busyRef = useRef(false)+ const creatingSessionRef = useRef(false)+ const queryClient = useRef(new QueryClient()).current++ const cache = useSessionStateCache({+ activeSessionId: null,+ selectedStoredSessionId: null,+ busyRef,+ setMessages,+ setBusy,+ setAwaitingResponse+ })++ const actions = useSessionActions({+ ...cache,+ activeSessionId: null,+ selectedStoredSessionId: null,+ busyRef,+ creatingSessionRef,+ getRouteToken: () => 'A',+ getRoutedStoredSessionId: () => null,+ navigate: vi.fn(),+ requestGateway+ })++ const stream = useMessageStream({+ ...cache,+ queryClient,+ hydrateFromStoredSession: noop,+ refreshHermesConfig: noop,+ refreshSessions: noop+ })++ return { cache, actions, stream }+ })++ return { ...hook, requestGateway }+}++beforeEach(() => {+ vi.useFakeTimers()+ localStorage.clear()+ clearAllSessionStates()+ resetInFlightTurnJournalStateForTests()+ _resetSessionOwnerHintsForTests()+ $activeGatewayProfile.set('default')+ setConnection(null)+ setMessages([])+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ setBusy(false)+ setAwaitingResponse(false)+ setSessions([+ {+ id: storedId,+ title: storedId,+ source: 'desktop',+ message_count: 5,+ tool_call_count: 2,+ is_active: false,+ started_at: 1,+ last_active: 1,+ ended_at: null,+ model: null,+ preview: null,+ input_tokens: 0,+ output_tokens: 0+ }+ ])+ vi.mocked(getLatestSessionMessages).mockReset()+})+afterEach(() => {+ cleanup()+ clearAllSessionStates()+ resetInFlightTurnJournalStateForTests()+ localStorage.clear()+ setSessions([])+ setMessages([])+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ setBusy(false)+ setAwaitingResponse(false)+ vi.useRealTimers()+ vi.restoreAllMocks()+})++it.each([+ ['cold', true, 'equal'],+ ['sparse', true, 'equal'],+ ['warm', true, 'equal'],+ ['warm', false, 'equal'],+ ['warm', false, 'snapshot-ahead'],+ ['warm', false, 'local-ahead'],+ ['cold', false, 'missing-ids'],+ ['warm', false, 'delta-during-history']+] as const)(+ 'reconciles ordered tool-round occurrences, not assistant ordinals (%s, repeated: %s, %s)',+ async (cacheKind, repeated, race) => {+ // Equal commentary is intentional; the producer suppresses its second interim,+ // not its second delta. Distinct commentary exercises the other live row shape.+ const comments = [commentary, repeated ? commentary : 'Checking another phase.']++ const snapshot: SessionResumeResult = {+ session_id: runtimeId,+ resumed: storedId,+ messages: [],+ message_count: 0,+ running: true,+ inflight: {+ user: prompt,+ assistant: [...comments, race === 'local-ahead' ? tail.slice(0, 10) : tail].join('\n\n'),+ streaming: true+ }+ }++ const { result } = mount(snapshot)++ if (cacheKind !== 'cold') {+ act(() => {+ result.current.cache.activeSessionIdRef.current = runtimeId+ result.current.cache.selectedStoredSessionIdRef.current = storedId+ result.current.cache.updateSessionState(+ runtimeId,+ state => ({ ...state, messages: toChatMessages([user]) }),+ storedId+ )+ })+ }++ if (cacheKind === 'warm') {+ const send = (type: GatewayEvent['type'], payload: GatewayEvent['payload'] = {}) =>+ act(() => result.current.stream.handleGatewayEvent({ session_id: runtimeId, type, payload }))++ send('message.start')+ comments.forEach((text, index) => {+ send('message.delta', { text: `${index ? '\n\n' : ''}${text}` })++ if (!index || !repeated) {+ send('message.interim', { text, already_streamed: true })+ }++ send('tool.start', { name: 'read_file', tool_id: `call-${index}`, args: {} })+ send('tool.complete', { name: 'read_file', tool_id: `call-${index}`, result: 'fixture' })+ })+ send('message.delta', { text: `\n\n${race === 'snapshot-ahead' ? tail.slice(0, 10) : tail}` })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(150)+ })+ }++ const durable = history(comments)++ if (race === 'missing-ids') {+ durable.forEach(row => {+ delete row.id+ })+ }++ let release!: () => void++ const held = new Promise<Awaited<ReturnType<typeof getLatestSessionMessages>>>(resolve => {+ release = () => resolve({ session_id: storedId, messages: durable })+ })++ vi.mocked(getLatestSessionMessages).mockReturnValue(held)+ let pending!: Promise<void>+ await act(async () => {+ pending = result.current.actions.resumeSession(storedId, true)+ })++ if (race === 'delta-during-history') {+ expect(getLatestSessionMessages).toHaveBeenCalled()+ act(() =>+ result.current.stream.handleGatewayEvent({+ session_id: runtimeId,+ type: 'message.delta',+ payload: { text: ' More.' }+ })+ )+ await act(async () => {+ await vi.advanceTimersByTimeAsync(150)+ })+ }++ await act(async () => {+ release()+ await pending+ })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(150)+ })+ const rows = result.current.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)!.messages++ const displayed = rows+ .filter(row => row.role === 'assistant')+ .map(chatMessageText)+ .join('\n\n')+ .replace(/\s+/g, '')++ // Missing row identity cannot prove coverage: prefer a duplicate over silently+ // consuming an accepted live occurrence. The live tail must still be visible.+ if (race === 'missing-ids') {+ expect(displayed).toContain(tail.replace(/\s+/g, ''))+ } else {+ expect(displayed).toBe(+ [...comments, tail, race === 'delta-during-history' ? ' More.' : ''].join('').replace(/\s+/g, '')+ )+ }++ expect(+ rows.flatMap(row => row.parts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : [])))+ ).toEqual(comments.map((_, index) => `call-${index}`))+ }+)++it.each(['snapshot-ahead', 'history-ahead', 'unpersisted-before-correction'] as const)(+ 'uses raw producer offsets and consumes corrections by occurrence (%s)',+ async race => {+ const media = 'An artifact 📄: MEDIA:/workspace/report.pdf'+ const beforeCorrection = race === 'unpersisted-before-correction' ? '\n\nBefore the correction.' : ''+ const correction = prompt // A correction may deliberately repeat the prompt.+ const raw = [media + beforeCorrection, 'Following the correction.'].join('\n\n')++ const snapshot: SessionResumeResult = {+ session_id: runtimeId,+ resumed: storedId,+ messages: [],+ message_count: 0,+ running: true,+ inflight: {+ user: prompt,+ assistant: race === 'history-ahead' ? media : `${raw}\n\n${tail}`,+ corrections: [correction, correction],+ correction_offsets: [Array.from(media + beforeCorrection).length, Array.from(raw).length],+ streaming: true+ }+ }++ // The second accepted equal correction is not yet durable.+ const durable = history([media])+ durable.push({ id: 4, role: 'user', content: correction, display_kind: 'steer', timestamp: 4 })++ if (race === 'history-ahead') {+ durable.push({+ id: 5,+ role: 'assistant',+ content: 'Following the correction.',+ timestamp: 5,+ tool_calls: [{ id: 'later-call', type: 'function', function: { name: 'read_file', arguments: '{}' } }]+ })+ }++ vi.mocked(getLatestSessionMessages).mockResolvedValue({ session_id: storedId, messages: durable })+ const { result } = mount(snapshot)+ await act(async () => {+ await result.current.actions.resumeSession(storedId, true)+ })+ const rows = result.current.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)!.messages++ expect(rows.filter(row => row.role === 'user').map(chatMessageText)).toEqual([prompt, correction, correction])++ const texts = rows+ .filter(row => row.role === 'assistant')+ .map(chatMessageText)+ .join('\n')++ expect(texts.match(/An artifact 📄:/g)).toHaveLength(1)+ expect(texts).toContain('Following the correction.')++ if (race === 'snapshot-ahead') {+ expect(texts).toContain(tail)+ }++ if (beforeCorrection) {+ const beforeIndex = rows.findIndex(row => chatMessageText(row).includes(beforeCorrection.trim()))+ const correctionIndex = rows.findIndex(row => row.rowId === 4)+ expect(beforeIndex).toBeLessThan(correctionIndex)+ }+ }+)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.tsxnew file mode 100644index 00000000000..a43f080e873--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/completion-boundaries.test.tsx@@ -0,0 +1,266 @@+import type { GatewayEventName } from '@hermes/shared'+import { QueryClient } from '@tanstack/react-query'+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 {+ clearInFlightTurnJournal,+ readInFlightTurnJournal,+ recoverInFlightTurnJournal+} from '@/lib/inflight-turn-journal'+import { $messages, setActiveSessionId, setMessages } from '@/store/session'+import { $sessionStates } from '@/store/session-states'++import { usePromptActions } from '../use-prompt-actions'+import { useSessionStateCache } from '../use-session-state-cache'++import { useMessageStream } from './index'++const SID = 'completion-runtime'+const STORED = 'completion-stored'+const ANSWER = 'The answer is unchanged.'+const noop = async () => undefined++const requestGateway = async <T,>(method: string): Promise<T> =>+ (method === 'prompt.submit' ? { status: 'started' } : { status: 'redirected' }) as T++// Real submit/redirect, stream reducer, cache and view publication; only RPC+// acceptance and history/metadata I/O are stand-ins.+function mount() {+ const queryClient = new QueryClient()+ const hydrate = vi.fn(noop)++ const hook = renderHook(() => {+ const busyRef = useRef(false)++ const cache = useSessionStateCache({+ activeSessionId: SID,+ selectedStoredSessionId: STORED,+ busyRef,+ setAwaitingResponse: () => undefined,+ setBusy: value => {+ busyRef.current = value+ },+ setMessages+ })++ const stream = useMessageStream({+ activeSessionIdRef: cache.activeSessionIdRef,+ sessionStateByRuntimeIdRef: cache.sessionStateByRuntimeIdRef,+ updateSessionState: cache.updateSessionState,+ queryClient,+ hydrateFromStoredSession: hydrate,+ refreshHermesConfig: noop,+ refreshSessions: noop+ })++ const actions = usePromptActions({+ activeSessionId: SID,+ activeSessionIdRef: cache.activeSessionIdRef,+ branchCurrentSession: async () => true,+ busyRef,+ createBackendSessionForSend: async () => SID,+ getRoutedStoredSessionId: () => STORED,+ getRuntimeIdForStoredSession: () => SID,+ getRouteToken: () => 'completion-route',+ handleSkinCommand: () => '',+ openMemoryGraph: () => undefined,+ refreshSessions: noop,+ requestGateway,+ resumeStoredSession: noop,+ runtimeIdByStoredSessionIdRef: cache.runtimeIdByStoredSessionIdRef,+ selectedStoredSessionIdRef: cache.selectedStoredSessionIdRef,+ startFreshSessionDraft: () => undefined,+ sttEnabled: false,+ updateSessionState: cache.updateSessionState+ })++ return { cache, stream, actions }+ })++ act(() => hook.result.current.cache.ensureSessionState(SID, STORED))++ return {+ hydrate,+ state: () => hook.result.current.cache.sessionStateByRuntimeIdRef.current.get(SID)!,+ send: (type: GatewayEventName, payload: Record<string, unknown> = {}) =>+ act(() => hook.result.current.stream.handleGatewayEvent({ type, payload, session_id: SID })),+ submit: () =>+ act(async () => {+ expect(await hook.result.current.actions.submitText('Give the answer.', { attachments: [] })).toBe(true)+ }),+ redirect: () =>+ act(async () => {+ expect(await hook.result.current.actions.redirectPrompt('Revise the answer.')).toBe(true)+ }),+ update: (updater: Parameters<typeof hook.result.current.cache.updateSessionState>[1]) =>+ act(() => {+ hook.result.current.cache.updateSessionState(SID, updater)+ }),+ dispose: () => {+ hook.unmount()+ queryClient.clear()+ }+ }+}++const timeline = (messages: ChatMessage[]) => messages.map(message => [message.role, chatMessageText(message)])++const flush = () =>+ act(async () => {+ await vi.advanceTimersByTimeAsync(50)+ })++beforeEach(() => {+ vi.useFakeTimers()+ localStorage.clear()+ $sessionStates.set({})+ setMessages([])+ setActiveSessionId(SID)+})+afterEach(() => {+ cleanup()+ clearInFlightTurnJournal(STORED)+ vi.clearAllTimers()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++it.each([false, true].flatMap(previousFailure => [ANSWER, ''].map(reply => ({ previousFailure, reply }))))(+ 'keeps a new completion after a real second submit (previousFailure=$previousFailure, reply="$reply")',+ async ({ previousFailure, reply }) => {+ const h = mount()+ await h.submit()+ await h.send('message.start')+ await h.send('message.delta', { text: ANSWER })+ await h.send('message.complete', {+ text: ANSWER,+ ...(previousFailure ? { status: 'error', error: 'Interrupted provider', partial: true } : {})+ })+ const firstAnswer = h.state().messages.at(-1)!+ expect(h.hydrate).not.toHaveBeenCalled()+ await flush()+ await h.submit() // Even identical prompt text is a new occurrence.+ await h.send('message.start')+ await h.send('message.complete', { text: reply })++ const expected = [+ ['user', 'Give the answer.'],+ ['assistant', ANSWER],+ ['user', 'Give the answer.'],+ ...(reply ? [['assistant', reply]] : [])+ ]++ expect(timeline(h.state().messages)).toEqual(expected)+ expect(timeline($messages.get())).toEqual(expected)+ expect(h.state().messages.find(message => message.id === firstAnswer.id)).toEqual(firstAnswer)+ expect(h.hydrate).toHaveBeenCalledWith(3, STORED, SID)++ if (reply) {+ const ids = h.state().messages.map(message => message.id)+ await h.send('message.complete', { text: reply })+ expect(h.state().messages.map(message => message.id)).toEqual(ids)+ expect(timeline($messages.get())).toEqual(expected)+ }++ h.dispose()+ }+)++it.each([+ { before: 'Answer', after: 'Answer' },+ { before: 'Answer', after: 'Answer with details' },+ { before: 'Answer with details', after: 'Answer' },+ { before: 'Answer', after: 'Rewritten reply', previewed: true },+ { before: 'Answer', after: 'Answer with details', hidden: true },+ { before: 'Answer', after: 'Answer with details', staleStream: true }+])('keeps redirect boundaries and settles duplicates: $before → $after ($hidden, $staleStream)', async fixture => {+ const h = mount()+ await h.submit()+ await h.send('message.start')+ await h.send('message.delta', { text: fixture.before })+ await h.send('message.interim', { text: fixture.before, already_streamed: true })+ expect(timeline(h.state().messages)).toEqual([+ ['user', 'Give the answer.'],+ ['assistant', fixture.before]+ ])+ const before = h.state().messages.at(-1)!+ await flush()+ await h.redirect()++ // Visibility is not identity; a hidden user row still divides occurrences.+ // A stale stream reference must not authorize completion across that row.+ if (fixture.hidden || fixture.staleStream) {+ h.update(state => ({+ ...state,+ streamId: fixture.staleStream ? before.id : state.streamId,+ messages: fixture.hidden+ ? state.messages.map(message => (message === state.messages.at(-1) ? { ...message, hidden: true } : message))+ : state.messages+ }))+ }++ await h.send('message.complete', { text: fixture.after, response_previewed: fixture.previewed })++ const expected = [+ ['user', 'Give the answer.'],+ ['assistant', fixture.before],+ ['user', 'Revise the answer.'],+ ['assistant', fixture.after]+ ]++ expect(timeline(h.state().messages)).toEqual(expected)+ expect(h.state().messages.find(message => message.id === before.id)).toEqual(before)+ expect(h.state().messages.at(-1)?.interim).toBeFalsy()+ const ids = h.state().messages.map(message => message.id)+ await h.send('message.complete', { text: fixture.after, response_previewed: fixture.previewed })+ expect(h.state().messages.map(message => message.id)).toEqual(ids)+ expect(timeline($messages.get())).toEqual(expected)+ h.dispose()+})++it.each(['fallback', 'stream', 'tool-interim'] as const)(+ 'retires recovered metadata when completion settles the %s row',+ async path => {+ const h = mount()+ await h.submit()+ await h.send('message.start')+ await h.send('message.delta', { text: ANSWER })++ if (path === 'tool-interim') {+ await h.send('message.interim', { text: ANSWER, already_streamed: true })+ }++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1000)+ })+ expect(readInFlightTurnJournal(STORED)).not.toBeNull()+ const recovered = recoverInFlightTurnJournal(STORED, h.state().messages.slice(0, 1), { keepPending: false })+ expect(recovered.applied).toBe(true)+ const recoveredId = recovered.messages.at(-1)!.id+ h.update(state => ({+ ...state,+ busy: false,+ awaitingResponse: false,+ turnLive: false,+ streamId: path === 'stream' ? recoveredId : null,+ messages: recovered.messages+ }))+ expect(h.state().messages.at(-1)).toMatchObject({ recovered: true, pending: false })++ if (path === 'tool-interim') {+ await h.send('tool.start', { name: 'terminal', tool_id: 'after-recovery' })+ await h.send('tool.complete', { name: 'terminal', tool_id: 'after-recovery', result: 'ok' })+ }++ await h.send('message.complete', { text: ANSWER })+ expect(h.state().messages).toHaveLength(2)+ expect(h.state().messages.at(-1)).toMatchObject({ id: recoveredId, recovered: false, pending: false })+ expect(chatMessageText(h.state().messages.at(-1)!)).toBe(ANSWER)+ expect(readInFlightTurnJournal(STORED)).toBeNull()+ expect(h.state()).toMatchObject({ busy: false, awaitingResponse: false, streamId: null })+ h.dispose()+ }+)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 f4dddb07594..19b94851bd4 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@@ -37,6 +37,7 @@ import type { ClientSessionState } from '../../../types'import { collapseDuplicateFinalAfterToolInterim, type DuplicateFinalCollapse } from './collapse-duplicate-final'import { useGatewayEventHandler } from './gateway-event'import { handleServerRequest as dispatchServerRequest } from './gateway-event/server-requests'+import { currentResponseParts, mergeCurrentResponseText } from './response-parts'import { completionErrorText, delegateTaskPayloads, MAX_STREAM_FLUSH_GAP_MS, STREAM_DELTA_FLUSH_MS } from './utils'interface MessageStreamOptions {@@ -542,7 +543,16 @@ export function useMessageStream({const replaceTextPart = (parts: ChatMessagePart[]) => {const visibleText = stripGeneratedImageEchoes(authoritativeText, generatedImageEchoSources(parts)).trim()- return mergeFinalAssistantText(parts, visibleText, occurredAt)+ // A later response can share this bubble after a suppressed interim.+ // A seal arriving after its tools, without any newer text, still+ // confirms the pre-tool response (legacy/delayed seal ordering).+ const hasNewResponse = currentResponseParts(parts).some(part =>+ (part.type === 'text' || part.type === 'reasoning') && part.text.trim()+ )++ return hasNewResponse+ ? mergeCurrentResponseText(parts, visibleText, occurredAt)+ : mergeFinalAssistantText(parts, visibleText, occurredAt)}let nextMessages = state.messages@@ -635,10 +645,12 @@ export function useMessageStream({? Math.max(1, Math.round((Date.now() - state.turnStartedAt) / 1000)): undefined- const replaceTextPart = (parts: ChatMessagePart[]) => {+ const replaceTextPart = (parts: ChatMessagePart[], interim: boolean) => {const visibleFinalText = stripGeneratedImageEchoes(finalText, generatedImageEchoSources(parts)).trim()- return mergeFinalAssistantText(parts, visibleFinalText, occurredAt)+ return interim+ ? mergeFinalAssistantText(parts, visibleFinalText, occurredAt)+ : mergeCurrentResponseText(parts, visibleFinalText, occurredAt)}// Settling the final response onto a bubble makes it the turn's real@@ -650,6 +662,7 @@ export function useMessageStream({parts: completeOpenTimelineParts(message.parts, occurredAt),pending: false,interim: false,+ recovered: false,...(durationS !== undefined ? { durationS } : {}),...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})}@@ -660,7 +673,7 @@ export function useMessageStream({return {...settled,- parts: completeOpenTimelineParts(replaceTextPart(settled.parts), occurredAt),+ parts: completeOpenTimelineParts(replaceTextPart(settled.parts, Boolean(message.interim)), occurredAt),...(completionError ? { error: completionError } : {})}}@@ -683,7 +696,13 @@ export function useMessageStream({const prev = state.messageslet nextMessages = prev- const streamIndex = streamId ? prev.findIndex(message => message.id === streamId) : -1+ // A new prompt or correction starts another occurrence, even when its+ // text (or answer) repeats. Hidden user rows are boundaries too.+ const lastUserIndex = prev.findLastIndex(message => message.role === 'user')++ const streamIndex = streamId+ ? prev.findIndex((message, index) => index > lastUserIndex && message.id === streamId)+ : -1let collapsed: DuplicateFinalCollapse | null = null@@ -698,14 +717,18 @@ export function useMessageStream({collapsed?.messages ??prev.map((message, index) => (index === streamIndex ? completeMessage(message) : message))} else {- const fallbackIndex = [...prev]- .reverse()- .findIndex(message => message.role === 'assistant' && !message.hidden)+ const fallbackIndex = prev.findLastIndex(+ (message, index) => index > lastUserIndex && message.role === 'assistant' && !message.hidden+ )if (fallbackIndex >= 0) {- const index = prev.length - 1 - fallbackIndex+ const index = fallbackIndexconst existing = prev[index]- const existingText = chatMessageText(existing).trim()++ const existingText = chatMessageText({+ ...existing,+ parts: existing.interim ? existing.parts : currentResponseParts(existing.parts)+ }).trim()// The last assistant row is a sealed interim (a tool-call turn or a// verify-on-stop candidate — `message.interim` fires for BOTH, see@@ -745,11 +768,10 @@ export function useMessageStream({//// • finalContinuesInterim (prefix-either-way continuity, same// text or one a prefix of the other) is safe to settle- // flag-free: continuity can only hold for the SAME message,- // so a `message.start` reset landing between this turn's- // `message.interim` and `message.complete` must not force an- // append of a duplicate bubble (#74560). This also closes the- // non-previewed tool-call gap from #63679.+ // flag-free within this user occurrence: a `message.start`+ // reset between this turn's interim and completion must not+ // force an append of a duplicate bubble (#74560). This also+ // closes the non-previewed tool-call gap from #63679.nextMessages = prev.map((message, messageIndex) =>messageIndex === index ? completeMessage(message) : message)@@ -767,15 +789,18 @@ export function useMessageStream({// tool-call parts that never saw their completion event.nextMessages = sealOpenToolParts(nextMessages)- const hasInlineError = nextMessages.some(m => m.role === 'assistant' && m.error && !m.hidden)+ const hasInlineError = nextMessages.some(+ (m, index) => index > lastUserIndex && m.role === 'assistant' && m.error && !m.hidden+ )+const lastVisible = [...nextMessages].reverse().find(m => !m.hidden)const unresolvedUserTail = lastVisible?.role === 'user'- const sameTurnId = collapsed?.keptId ?? streamId+ const sameTurnId = collapsed?.keptId ?? (streamIndex >= 0 ? streamId : null)const sameTurnAssistant = sameTurnId? nextMessages.find(m => m.id === sameTurnId)- : [...nextMessages].reverse().find(m => m.role === 'assistant' && !m.hidden)+ : nextMessages.findLast((m, index) => index > lastUserIndex && m.role === 'assistant' && !m.hidden)const localVisibleText = sameTurnAssistant ? chatMessageText(sameTurnAssistant).trim() : ''// Having streamed the reply normally means this window owns the wholediff --git a/apps/desktop/src/app/session/hooks/use-message-stream/response-occurrences.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/response-occurrences.test.tsxnew file mode 100644index 00000000000..29ca07f9f98--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/response-occurrences.test.tsx@@ -0,0 +1,60 @@+import type { GatewayEventName } from '@hermes/shared'+import { act, cleanup } from '@testing-library/react'+import { afterEach, expect, it } from 'vitest'++import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'+import type { SessionMessage } from '@/types/hermes'++import { renderMessageStream } from './test-harness'++const text = (messages: ChatMessage[]) => messages.map(chatMessageText).join('').replace(/\s+/g, '')++afterEach(cleanup)++it.each(['interim', 'completion', 'completion without delta'])(+ 'retains earlier response occurrences in a shared tool bubble on %s',+ async boundary => {+ const sid = 'response-occurrences'+ const stream = renderMessageStream(sid)+ const send = (type: GatewayEventName, payload: Record<string, unknown> = {}) =>+ act(() => stream.handleEvent({ type, payload, session_id: sid }))+ const history: SessionMessage[] = []+ const comments = boundary === 'interim' ? ['Checking.', 'Checking.', 'Next phase.'] : ['Checking.', 'Checking.']++ await send('message.start')++ for (const [index, comment] of comments.entries()) {+ await send('message.delta', { text: `${index ? '\n\n' : ''}${comment}` })++ // The actual producer suppresses the second equal interim, not its delta.+ if (index !== 1) {+ await send('message.interim', { text: comment, already_streamed: true })+ }++ const id = `tool-${index}`+ await send('tool.start', { name: 'read_file', tool_id: id, args: {} })+ await send('tool.complete', { name: 'read_file', tool_id: id, result: 'read' })+ history.push(+ { id: index * 2 + 1, role: 'assistant', content: comment,+ tool_calls: [{ id, type: 'function', function: { name: 'read_file', arguments: '{}' } }] },+ { id: index * 2 + 2, role: 'tool', content: 'read', tool_call_id: id }+ )+ }++ if (boundary !== 'completion without delta') {+ await send('message.delta', { text: '\n\nDone.' })+ }++ await send('message.complete', { text: 'Done.' })+ history.push({ id: 20, role: 'assistant', content: 'Done.' })+ const durable = toChatMessages(history)+ expect(text(stream.state().messages)).toBe(text(durable))+ const toolIds = () => stream.state().messages.flatMap(row => row.parts.flatMap(part =>+ part.type === 'tool-call' ? [part.toolCallId] : []))+ expect(toolIds()).toEqual(comments.map((_, index) => `tool-${index}`))++ await send('message.complete', { text: 'Done.' })+ expect(text(stream.state().messages)).toBe(text(durable))+ expect(toolIds()).toEqual(comments.map((_, index) => `tool-${index}`))+ }+)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/response-parts.ts b/apps/desktop/src/app/session/hooks/use-message-stream/response-parts.tsnew file mode 100644index 00000000000..bcf3376f25d--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/response-parts.ts@@ -0,0 +1,18 @@+import { type ChatMessagePart, mergeFinalAssistantText } from '@/lib/chat-messages'++/** One live bubble may hold several model responses when an equal interim+ * callback is suppressed. The last tool round, not the bubble, bounds the+ * response that an interim/final frame is allowed to replace. */+export function currentResponseParts(parts: ChatMessagePart[]): ChatMessagePart[] {+ return parts.slice(parts.findLastIndex(part => part.type === 'tool-call') + 1)+}++export function mergeCurrentResponseText(+ parts: ChatMessagePart[],+ text: string,+ timestamp: number+): ChatMessagePart[] {+ const boundary = parts.findLastIndex(part => part.type === 'tool-call') + 1++ return [...parts.slice(0, boundary), ...mergeFinalAssistantText(parts.slice(boundary), text, timestamp)]+}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsxindex 893d8a8c5e5..2703b8bc033 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx@@ -197,15 +197,15 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outpexpect(settled.indexOf(tail!)).toBeGreaterThan(settledSteerIndex)})- it('steer with no post-steer deltas: completion settles above, bubble stays at the tail', async () => {+ it('an accepted steer bounds completion even when no post-steer delta arrived', async () => {await mountHarness()emit({ payload: {}, session_id: SID, type: 'message.start' })emit({ payload: { text: 'the whole reply already streamed' }, session_id: SID, type: 'message.delta' })await flushDeltas()- // Steer accepted during the final API call — the reply was already- // complete, so the correction becomes the NEXT turn's prompt.+ // The gateway explicitly accepts this as redirected, not queued. Equal+ // output alone cannot place its completion back above the correction.await steer('one more thing')emit({ payload: { text: 'the whole reply already streamed' }, session_id: SID, type: 'message.complete' })@@ -213,15 +213,10 @@ describe('steer mid-turn keeps arrival order (user bubble never above prior outpconst messages = states.get(SID)!.messagesconst steerIndex = messages.findIndex(message => message.role === 'user')- // The already-streamed reply settles onto its sealed bubble ABOVE the- // correction; the correction stays the tail, waiting for its own turn —- // no duplicate reply row appended below it. Load-bearing assumption: a- // completion settles the sealed pre-steer bubble in place and never- // appends/merges below the correction — if the reducer ever changes that,- // this test is the tripwire.- expect(steerIndex).toBe(messages.length - 1)+ expect(steerIndex).toBe(messages.length - 2)+ expect(messages.at(-1)?.role).toBe('assistant')expect(messages.filter(message => chatMessageText(message).includes('whole reply already streamed'))).toHaveLength(- 1+ 2)expect(messages.every(message => message.pending !== true)).toBe(true)})diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 00c1078d79a..fc195e3a45d 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -140,6 +140,7 @@ import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-rimport { sessionCreateOverrideParams, type SessionCreateOverrides, type SessionSeedMessage } from './create-overrides'import { captureDisplayHydration } from './display-hydration'+import { reconcilePersistedLiveTurn } from './persisted-live-turn'import { provisionalTranscriptPaint, transcriptRestScope } from './provisional-transcript'import { pendingClarifyToolPayload, restorePendingClarifyFromSnapshot } from './restore-pending-clarify'import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'@@ -261,8 +262,23 @@ function applyStoredUsage(stored: { input_tokens?: number | null; output_tokens?function reconcileAuthoritativeChatMessages(authoritativeMessages: ChatMessage[],previousMessages: ChatMessage[],- liveProjection?: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>+ liveProjection?: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>,+ sourceRows?: SessionMessage[]): ChatMessage[] {+ if (liveProjection && sourceRows) {+ const reconciled = reconcilePersistedLiveTurn(+ authoritativeMessages,+ previousMessages,+ sourceRows,+ liveProjection,+ (messages, previous) => reconcileAuthoritativeChatMessages(messages, previous)+ )++ if (reconciled) {+ return reconciled+ }+ }+const withLiveProjection = liveProjection? appendLiveSessionProjection(authoritativeMessages, liveProjection): authoritativeMessages@@ -278,7 +294,12 @@ function reconcileAuthoritativeMessages(previousMessages: ChatMessage[],liveProjection?: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>): ChatMessage[] {- return reconcileAuthoritativeChatMessages(toChatMessages(authoritativeMessages), previousMessages, liveProjection)+ return reconcileAuthoritativeChatMessages(+ toChatMessages(authoritativeMessages),+ previousMessages,+ liveProjection,+ authoritativeMessages+ )}// `session.create` params from the current profile + sticky-UI model/effort/fast,@@ -1453,6 +1474,7 @@ export function useSessionActions({// Reconcile its in-flight/queued tail onto the complete transcript// instead of replacing durable history while the turn is running.let acceptedPersistedDisplayTranscript = false+ let reconciledCurrentLiveTurn = falseif (persistedTranscriptPromise) {const persisted = await persistedTranscriptPromise@@ -1502,17 +1524,31 @@ export function useSessionActions({activated)- activatedMessages = reconcileAuthoritativeChatMessages(+ const currentLiveTurn = reconcilePersistedLiveTurn(persistedMessages,- previousMessages,- liveProjection+ sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)?.messages ?? previousMessages,+ persisted.messages,+ liveProjection,+ (messages, previous) => reconcileAuthoritativeChatMessages(messages, previous))++ reconciledCurrentLiveTurn = currentLiveTurn !== null+ activatedMessages =+ currentLiveTurn ??+ reconcileAuthoritativeChatMessages(+ persistedMessages,+ previousMessages,+ liveProjection,+ persisted.messages+ )}}const currentMessages = sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)?.messages- if (currentMessages) {+ // The occurrence-aware path already read the latest cache. An+ // additional identity overlay would restore its consumed tools.+ if (currentMessages && !reconciledCurrentLiveTurn) {activatedMessages = overlayConcurrentMessageChanges(activatedMessages,cachedViewState.messages,@@ -1830,7 +1866,8 @@ export function useSessionActions({const resumedMessages = reconcileAuthoritativeChatMessages(prefetchedTranscriptMessages,previousMessages,- liveProjection+ liveProjection,+ prefetchedResult?.messages)const withConcurrentChanges = overlayConcurrentMessageChanges(diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.ts b/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.tsnew file mode 100644index 00000000000..6f3fe616f23--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.ts@@ -0,0 +1,91 @@+import { assistantTextPart, type ChatMessage, chatMessageText } from '@/lib/chat-messages'++/** Whitespace normalization is for comparison only; cuts always address the original text. */+function comparable(text: string): { text: string; ends: number[] } {+ let normalized = ''+ const ends: number[] = []++ for (const match of text.matchAll(/\s+|\S/g)) {+ const value = /^\s/.test(match[0]) ? ' ' : match[0]++ if (!normalized && value === ' ') {+ continue+ }++ normalized += value+ ends.push(match.index + match[0].length)+ }++ return { text: normalized.trimEnd(), ends }+}++function textSpans(messages: ChatMessage[]) {+ let text = ''++ for (const message of messages) {+ for (const part of message.parts) {+ if (part.type !== 'text' || !part.text.trim()) {+ continue+ }++ if (text) {+ text += '\n\n'+ }++ text += part.text+ }+ }++ return { text }+}++function hasContent(message: ChatMessage): boolean {+ return Boolean(chatMessageText(message).trim() || message.parts.some(part => part.type !== 'text') || message.error)+}++/** Merge only the assistant run between two already-paired user occurrences. */+export function mergeLiveAssistantRun(projected: ChatMessage[], cached: ChatMessage[]): ChatMessage[] {+ const local = cached.filter(hasContent)++ if (!local.length) {+ return projected+ }++ if (!projected.length) {+ return local+ }++ const live = comparable(textSpans(local).text).text+ const remoteSpans = textSpans(projected)+ const remote = comparable(remoteSpans.text)+ const terminal = projected.at(-1)!++ if (terminal.error) {+ return [...local, terminal]+ }++ if (!remote.text || live.startsWith(remote.text)) {+ return local.map((message, index) =>+ index === local.length - 1 ? { ...message, pending: terminal.pending === true } : message+ )+ }++ if (remote.text.startsWith(live)) {+ const suffix = live ? remoteSpans.text.slice(remote.ends[live.length - 1]) : remoteSpans.text+ const last = local.at(-1)!++ return [+ ...local.slice(0, -1),+ {+ ...last,+ pending: terminal.pending === true,+ interim: terminal.interim,+ parts: [...last.parts, assistantTextPart(suffix)]+ }+ ]+ }++ // No evidence that one is a prefix of the other: retain both. A stale or+ // transformed snapshot is not permission to erase unseen live output.+ return [...local, ...projected]+}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts b/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.tsnew file mode 100644index 00000000000..e915be252f6--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts@@ -0,0 +1,309 @@+import { textWithoutReferenceLines } from '@/components/assistant-ui/reference-kinds'+import { assistantTextPart, type ChatMessage, chatMessageText, textPart } from '@/lib/chat-messages'+import { withoutCoveredAssistantPrefix } from '@/lib/chat-messages/coverage'+import { parseErrorSurface } from '@/lib/error-surface'+import type { SessionMessage, SessionResumeResult } from '@/types/hermes'++import { mergeLiveAssistantRun } from './live-turn-remainder'++const rowId = (row: SessionMessage) => row.row_id ?? row.id+const userText = (text: string) => textWithoutReferenceLines(text).trim()+const hasTools = (row: SessionMessage) => Array.isArray(row.tool_calls) && row.tool_calls.length > 0++const renderedText = (raw: string) => {+ const part = assistantTextPart(raw)++ return part.type === 'text' ? part.text : ''+}++interface PersistedTurn {+ prompt: ChatMessage+ start: number+ rawIntervals: string[]+ messages: ChatMessage[]+}++/** Validate the current turn's source rows against the occurrences actually painted. */+function candidateTurn(+ rows: SessionMessage[],+ messages: ChatMessage[],+ start: number,+ corrections: string[]+): PersistedTurn | null {+ const promptId = rowId(rows[start])+ const displayStart = messages.findIndex(message => message.role === 'user' && message.rowId === promptId)++ if (promptId === undefined || displayStart < 0) {+ return null+ }++ const turnMessages = messages.slice(displayStart + 1)+ const intervals: string[][] = [[]]++ for (const row of rows.slice(start + 1)) {+ if (row.role === 'user') {+ if (userText(String(row.content ?? '')) !== userText(corrections[intervals.length - 1] ?? '')) {+ return null+ }++ const id = rowId(row)++ if (id === undefined || !turnMessages.some(message => message.role === 'user' && message.rowId === id)) {+ return null+ }++ intervals.push([])+ } else if (row.role === 'assistant') {+ if (!hasTools(row) || typeof row.content !== 'string' || row.display_kind === 'hidden') {+ return null+ }++ const raw = row.content++ if (!raw.trim()) {+ continue+ }++ const id = rowId(row)++ // MEDIA rendering and folding change lengths. Only source-row provenance,+ // not equal prose elsewhere in the transcript, proves display coverage.+ if (+ id === undefined ||+ !turnMessages.some(message =>+ message.parts.some(+ part => part.type === 'text' && part.sourceRowId === id && part.text.trim() === renderedText(raw).trim()+ )+ )+ ) {+ return null+ }++ intervals.at(-1)!.push(raw)+ } else if (row.role !== 'tool') {+ return null+ }+ }++ return {+ prompt: messages[displayStart],+ start: displayStart,+ rawIntervals: intervals.map(texts => texts.join('\n\n')),+ messages: turnMessages+ }+}++function locateTurn(+ rows: SessionMessage[],+ messages: ChatMessage[],+ inflight: NonNullable<SessionResumeResult['inflight']>+): PersistedTurn | null {+ let candidate: PersistedTurn | null = null++ for (let index = rows.length - 1; index >= 0; index--) {+ const row = rows[index]++ // A final reply is an actual boundary; durable tool commentary is not.+ if (row.role === 'assistant' && !hasTools(row) && typeof row.content === 'string' && row.content.trim()) {+ break+ }++ if (+ row.role === 'user' &&+ row.display_kind !== 'steer' &&+ userText(String(row.content ?? '')) === userText(inflight.user ?? '')+ ) {+ candidate = candidateTurn(rows, messages, index, inflight.corrections ?? []) ?? candidate+ }+ }++ return candidate+}++function splitAtUsers(messages: ChatMessage[]) {+ const intervals: ChatMessage[][] = [[]]+ const users: ChatMessage[] = []++ for (const message of messages) {+ if (message.role === 'user') {+ users.push(message)+ intervals.push([])+ } else {+ intervals.at(-1)!.push(message)+ }+ }++ return { intervals, users }+}++/** Prefix races are symmetric; cuts address raw producer text, never rendered Markdown. */+function unrepresentedText(snapshot: string, stored: string): string {+ // Separators between rounds can lead an interval after a correction.+ const leading = snapshot.length - snapshot.trimStart().length+ const text = snapshot.slice(leading)+ const prefix = stored.trim()++ if (!prefix) {+ return snapshot+ }++ if (text.startsWith(prefix)) {+ return text.slice(prefix.length)+ }++ if (prefix.startsWith(text)) {+ return ''+ }++ return snapshot+}++function snapshotIntervals(inflight: NonNullable<SessionResumeResult['inflight']>): string[] {+ const text = inflight.assistant ?? ''+ const corrections = inflight.corrections ?? []+ const offsets = inflight.correction_offsets+ // Python's len() counts Unicode code points, unlike JS string offsets.+ const characters = Array.from(text)++ const usable =+ offsets?.length === corrections.length &&+ offsets.every(+ (offset, index) =>+ Number.isInteger(offset) &&+ offset >= 0 &&+ offset <= characters.length &&+ (!index || offset >= offsets[index - 1])+ )++ if (!usable) {+ return [text, ...corrections.map(() => '')]+ }++ return [...offsets, characters.length].map((end, index) =>+ characters.slice(index ? offsets[index - 1] : 0, end).join('')+ )+}++/**+ * Reconcile the anchored partial turn before role-ordinal pairing sees it.+ * Missing provenance takes the legacy path without subtracting any snapshot text.+ */+export function reconcilePersistedLiveTurn(+ messages: ChatMessage[],+ previous: ChatMessage[],+ rows: SessionMessage[],+ projection: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>,+ reconcileHistory: (messages: ChatMessage[], previous: ChatMessage[]) => ChatMessage[]+): ChatMessage[] | null {+ const inflight = projection.inflight++ if (!inflight?.user) {+ return null+ }++ const turn = locateTurn(rows, messages, inflight)++ if (!turn) {+ return null+ }++ let localStart = previous.findIndex(message => message.role === 'user' && message.rowId === turn.prompt.rowId)++ if (localStart < 0) {+ const tools = new Set(+ turn.messages.flatMap(message =>+ message.parts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : []))+ )+ )++ // Optimistic prompt rows have no durable id yet. Shared tool identity after+ // the matching prompt can anchor the turn, never the prompt text alone.+ localStart = previous.findLastIndex(+ (message, index) =>+ message.role === 'user' &&+ userText(chatMessageText(message)) === userText(chatMessageText(turn.prompt)) &&+ previous+ .slice(index + 1)+ .some(row => row.parts.some(part => part.type === 'tool-call' && tools.has(part.toolCallId)))+ )+ }++ const stored = splitAtUsers(turn.messages)+ const cached = splitAtUsers(localStart >= 0 ? previous.slice(localStart + 1) : [])+ const snapshots = snapshotIntervals(inflight)+ const corrections = inflight.corrections ?? []++ const result = reconcileHistory(+ messages.slice(0, turn.start + 1),+ localStart >= 0 ? previous.slice(0, localStart + 1) : previous+ )++ let pairedLocal = localStart >= 0+ let unpairedLocal: ChatMessage[] = []++ for (let index = 0; index < snapshots.length; index++) {+ const durable = stored.intervals[index] ?? []+ const raw = turn.rawIntervals[index] ?? ''+ // No usable correction offsets means only the complete initial prefix can+ // be proven; don't apply a later interval's normalized length to this dump.+ const text = unrepresentedText(snapshots[index], raw)++ const final = index === snapshots.length - 1+ const error = final ? inflight.error?.trim() : undefined++ const projected: ChatMessage[] =+ text.trim() || final+ ? [+ {+ id: final+ ? `assistant-stream-${projection.session_id}`+ : `inflight-assistant-segment-${index}-${projection.session_id}`,+ role: 'assistant',+ parts: text.trim() ? [assistantTextPart(text)] : [],+ pending: final && Boolean(inflight.streaming),+ ...(!final ? { interim: true } : {}),+ ...(error ? { error, errorSurface: parseErrorSurface(inflight.error_surface) ?? undefined } : {})+ }+ ]+ : []++ const local = pairedLocal ? withoutCoveredAssistantPrefix(durable, cached.intervals[index] ?? []) : []+ result.push(...durable, ...mergeLiveAssistantRun(projected, local))++ if (!final) {+ const correction = stored.users[index] ?? {+ id: `user-inflight-correction-${index}-${projection.session_id}`,+ role: 'user' as const,+ parts: [textPart(corrections[index])]+ }++ result.push(correction)++ if (+ pairedLocal &&+ (!cached.users[index] || userText(chatMessageText(cached.users[index])) !== userText(corrections[index]))+ ) {+ unpairedLocal = cached.users+ .slice(index)+ .flatMap((user, offset) => [user, ...cached.intervals[index + offset + 1]])+ pairedLocal = false+ }+ }+ }++ if (pairedLocal) {+ result.push(+ ...cached.users+ .slice(corrections.length)+ .flatMap((user, index) => [user, ...cached.intervals[corrections.length + index + 1]])+ )+ }++ result.push(...unpairedLocal)++ if (projection.queued?.user) {+ result.push({ id: `user-queued-${projection.session_id}`, role: 'user', parts: [textPart(projection.queued.user)] })+ }++ return result+}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 39b5399d98c..33287de2b7a 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@@ -1185,6 +1185,69 @@ describe('preserveLocalPendingTurnMessages', () => {])})+ it('does not keep a settled final-answer bubble already folded into the tool-round message', () => {+ const folded = {+ id: '1790016993.1043298-1-assistant',+ role: 'assistant' as const,+ parts: [+ { type: 'text' as const, text: 'I will inspect the fixture, then give the final result.' },+ { type: 'tool-call' as const, toolCallId: 'call-1', toolName: 'terminal', result: '71' },+ { type: 'text' as const, text: 'The result is 71.' }+ ]+ }++ const next = [msg('1-user', 'user', 'inspect the fixture'), folded]++ const previous = [+ msg('1-user', 'user', 'inspect the fixture'),+ { ...folded, parts: folded.parts.slice(0, 2) },+ msg('assistant-stream-placeholder', 'assistant', '', { pending: false }),+ msg('assistant-stream-final', 'assistant', 'The result is 71.', { pending: false })+ ]++ const preserved = preserveLocalPendingTurnMessages(next, previous)++ const finals = preserved.flatMap(message =>+ message.parts.filter(part => part.type === 'text' && part.text === 'The result is 71.')+ )++ expect(finals).toHaveLength(1)+ expect(preserved.map(message => message.id)).not.toContain('assistant-stream-final')+ })++ it('keeps a settled final-answer bubble the folded tool round has not absorbed', () => {+ const toolRound = {+ id: 'row-1-assistant',+ role: 'assistant' as const,+ parts: [+ { type: 'text' as const, text: 'I will inspect the fixture, then give the final result.' },+ { type: 'tool-call' as const, toolCallId: 'call-1', toolName: 'terminal', result: '71' }+ ]+ }++ const next = [msg('1-user', 'user', 'inspect the fixture'), toolRound]+ const previous = [...next, msg('assistant-stream-final', 'assistant', 'The result is 71.', { pending: false })]++ expect(preserveLocalPendingTurnMessages(next, previous).map(message => message.id)).toContain('assistant-stream-final')+ })++ it('keeps an equal final answer that belongs to a later turn history has not stored', () => {+ const folded = {+ id: 'row-1-assistant',+ role: 'assistant' as const,+ parts: [+ { type: 'text' as const, text: 'I will inspect the fixture, then give the final result.' },+ { type: 'tool-call' as const, toolCallId: 'call-1', toolName: 'terminal', result: '71' },+ { type: 'text' as const, text: 'The result is 71.' }+ ]+ }++ const next = [msg('1-user', 'user', 'first'), folded, msg('2-user', 'user', 'again')]+ const previous = [...next, msg('assistant-stream-later', 'assistant', 'The result is 71.', { pending: false })]++ expect(preserveLocalPendingTurnMessages(next, previous).map(message => message.id)).toContain('assistant-stream-later')+ })+// The whole point of replacing rather than appending: one reply on screen,// and the committed history around the live turn untouched.it('does not duplicate or rewrite committed history around the live turn', () => {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 5927244643c..99bcaa2b757 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@@ -159,6 +159,8 @@ const _chatMessageFieldsExhaustive: {} = {}const COMPARED_FIELDS = [+ 'durableComplete',+ 'recovered','asyncResult','asyncResultKind','id',@@ -222,6 +224,10 @@ export function chatPartsEquivalent(aPart: ChatMessage['parts'][number], bPart:}if (aPart.type === 'text' || aPart.type === 'reasoning') {+ if (aPart.sourceRowId !== bPart.sourceRowId) {+ return false+ }+return (aPart as { text: string }).text === (bPart as { text: string }).text}@@ -274,6 +280,8 @@ export function chatMessagesEquivalent(a: ChatMessage, b: ChatMessage): booleanif (a.id !== b.id ||a.role !== b.role ||+ a.durableComplete !== b.durableComplete ||+ a.recovered !== b.recovered ||a.pending !== b.pending ||a.error !== b.error ||// Structural compare — the descriptor arrives as a fresh object per@@ -534,6 +542,56 @@ const withAuthoritativeTurnState = (local: ChatMessage, authoritative: ChatMessareturn merged}+/** Text of the response that follows a folded tool round, not the commentary before it. */+function lastFoldedResponseText(message: ChatMessage): string {+ let afterTool = false+ let text = ''++ for (const part of message.parts) {+ if (part.type === 'tool-call') {+ afterTool = true+ text = ''++ continue+ }++ if (afterTool && part.type === 'text') {+ text = textWithoutReferenceLines(part.text).trim()+ }+ }++ return afterTool ? text : ''+}++/**+ * History folds a final answer into the preceding tool-round bubble. A live+ * stream bubble holding only that answer is the same occurrence, but full-bubble+ * equality cannot see it.+ */+function durableFoldCoversLiveResponse(messages: ChatMessage[], live: ChatMessage): boolean {+ const needle = textWithoutReferenceLines(chatMessageText(live)).trim()++ if (!needle || live.parts.some(part => part.type === 'tool-call')) {+ return false+ }++ const lastUser = messages.findLastIndex(message => message.role === 'user' && !isGatewaySystemMarker(message))++ return messages.slice(lastUser + 1).some(message => {+ if (+ message.role !== 'assistant' ||+ message.id.startsWith('assistant-stream-') ||+ message.id.startsWith('inflight-assistant-')+ ) {+ return false+ }++ const folded = lastFoldedResponseText(message)++ return folded === needle || isStrictAnswerTextExtension(folded, needle)+ })+}+export function preserveLocalPendingTurnMessages(nextMessages: ChatMessage[],previousMessages: ChatMessage[]@@ -736,6 +794,16 @@ export function preserveLocalPendingTurnMessages(}}+ const lastPreviousUser = previousMessages.findLastIndex(row => row.role === 'user' && !isGatewaySystemMarker(row))++ if (+ isPendingAssistant &&+ previousMessages.indexOf(message) > lastPreviousUser &&+ durableFoldCoversLiveResponse(nextMessages, message)+ ) {+ continue+ }+preserved.push(message)}diff --git a/apps/desktop/src/lib/chat-messages/coverage.ts b/apps/desktop/src/lib/chat-messages/coverage.tsnew file mode 100644index 00000000000..fd777464f41--- /dev/null+++ b/apps/desktop/src/lib/chat-messages/coverage.ts@@ -0,0 +1,56 @@+import type { ChatMessage, ChatMessagePart } from './types'++const normalizedText = (value: string) => value.replace(/\s+/g, ' ').trim()++function sameOccurrencePart(stored: ChatMessagePart, local: ChatMessagePart): boolean {+ if (stored.type === 'tool-call' && local.type === 'tool-call') {+ return Boolean(stored.toolCallId) && stored.toolCallId === local.toolCallId+ }++ if ((stored.type === 'text' || stored.type === 'reasoning') && local.type === stored.type) {+ return normalizedText(stored.text) === normalizedText(local.text)+ }++ return false+}++/** Subtract an ordered, tool-anchored prefix within an already matched user+ * interval. Hydration can fold several live bubbles into one durable row;+ * bubble ordinals and equal text alone cannot establish that coverage. */+export function withoutCoveredAssistantPrefix(stored: ChatMessage[], local: ChatMessage[]): ChatMessage[] {+ const parts = stored.flatMap(message => message.role === 'assistant' ? message.parts : [])+ let cursor = 0+ let anchored = false+ let stopped = false+ const remaining: ChatMessage[] = []++ for (const message of local) {+ if (stopped || message.role !== 'assistant' || message.error) {+ stopped = true+ remaining.push(message)++ continue+ }++ let consumed = 0++ for (const part of message.parts) {+ if (!parts[cursor] || !sameOccurrencePart(parts[cursor], part)) {+ break+ }++ anchored ||= part.type === 'tool-call'+ cursor += 1+ consumed += 1+ }++ if (consumed < message.parts.length) {+ stopped = true+ remaining.push(consumed ? { ...message, parts: message.parts.slice(consumed) } : message)+ }+ }++ // A coincidentally equal paragraph, without the same tool occurrence after+ // it, is insufficient evidence to remove anything.+ return anchored ? remaining : local+}diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.tsindex 1790a1b9770..fd5d695673c 100644--- a/apps/desktop/src/lib/chat-messages/hydration.ts+++ b/apps/desktop/src/lib/chat-messages/hydration.ts@@ -282,6 +282,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {}active.parts = [...active.parts, ...parts]+ active.durableComplete = falseactive.timestamp = earliestTimestamp(active.timestamp, timestamp, ...parts.map(part => part.timestamp))absorbRows(active, pendingToolRows)@@ -298,6 +299,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {id: `${pendingToolTimestamp || Date.now()}-${index}-tools`,role: 'assistant',parts: pendingToolParts,+ durableComplete: false,...(pendingToolRows > 1 ? { serverRowSpan: pendingToolRows } : {}),timestamp: pendingToolTimestamp})@@ -360,6 +362,9 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {const extractedAttachmentRefs = imageRefExtraction?.refs.length ? imageRefExtraction.refs : undefinedconst parts: ChatMessagePart[] = []+ const rowId = message.row_id ?? (typeof message.id === 'number' ? message.id : undefined)+ const sourceHasTools = Array.isArray(message.tool_calls) && message.tool_calls.length > 0+ const durableComplete = sourceHasTools ? false : rowId !== undefined ? true : undefinedconst reasoning =message.reasoning ||@@ -394,6 +399,14 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {)}+ if (rowId !== undefined) {+ for (const part of parts) {+ if (part.type === 'text') {+ part.sourceRowId = rowId+ }+ }+ }+if (!parts.length && !extractedAttachmentRefs?.length) {if (message.role !== 'assistant') {flushPendingTools(index)@@ -436,6 +449,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {if (activeAssistant && (currentHasToolCall || activeHasToolCall)) {activeAssistant.parts = [...activeAssistant.parts, ...parts]+ activeAssistant.durableComplete = durableCompleteactiveAssistant.timestamp = earliestTimestamp(activeAssistant.timestamp,message.timestamp,@@ -453,12 +467,11 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {// Gateway resume names the durable row id `row_id`; the REST transcript// prefetch ships the same messages.id as a numeric `id`. Either one lets// reactions address this exact row later.- const rowId = message.row_id ?? (typeof message.id === 'number' ? message.id : undefined)-result.push({id: `${message.timestamp || Date.now()}-${index}-${displayRole}`,role: displayRole,parts,+ ...(message.role === 'assistant' && durableComplete !== undefined ? { durableComplete } : {}),...(message.display_kind === 'async_delegation_complete' || message.display_kind === 'process_complete'? { asyncResult: asyncResultBody(displayContentForMessage(message.role, message.content || content)) }: {}),diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.tsindex 58e62ac5c33..f38966073c9 100644--- a/apps/desktop/src/lib/chat-messages/parts.ts+++ b/apps/desktop/src/lib/chat-messages/parts.ts@@ -209,35 +209,29 @@ export function collectUnspokenTurnSpeech(const normalizeWs = (value: string) => value.replace(/\s+/g, ' ').trim()/**- * Drop earlier text parts that a later text part repeats verbatim (after- * whitespace normalization). Providers that continue a turn after a tool- * call sometimes re-send the previous assistant text as the next message's- * prefix (tool_calls row, then a stop row with identical prose) — the turn- * merge then holds the same paragraph twice and everything in it renders- * twice, most visibly ::preview frames. The LAST occurrence is the- * authoritative one; keep it.+ * Collapse repeated representations of the same durable text occurrence.+ * Equal prose in different tool rounds (or without provenance) is not proof+ * of duplicate delivery and must survive hydration.*/export function dedupeRepeatedTextInParts(parts: ChatMessagePart[]): ChatMessagePart[] {- const lastByText = new Map<string, number>()+ const lastByOccurrence = new Map<string, number>()parts.forEach((part, index) => {- if (part.type === 'text') {- const key = normalizeWs(part.text)+ if (part.type === 'text' && part.sourceRowId !== undefined) {+ const key = `${part.sourceRowId}:${normalizeWs(part.text)}`- if (key) {- lastByText.set(key, index)- }+ lastByOccurrence.set(key, index)}})const dropped = parts.filter((part, index) => {- if (part.type !== 'text') {+ if (part.type !== 'text' || part.sourceRowId === undefined) {return true}- const key = normalizeWs(part.text)+ const key = `${part.sourceRowId}:${normalizeWs(part.text)}`- return !key || lastByText.get(key) === index+ return lastByOccurrence.get(key) === index})return dropped.length === parts.length ? parts : droppeddiff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.tsindex bfa3694b0f1..061b01f1551 100644--- a/apps/desktop/src/lib/chat-messages/types.ts+++ b/apps/desktop/src/lib/chat-messages/types.ts@@ -17,6 +17,8 @@ export interface TimelinePartMetadata {/** Raw streamed text behind a `text` part whose MEDIA tags are already rendered,* so the next delta re-renders from the source instead of the render. */mediaSource?: string+ /** Durable source occurrence, even when several backend rows share a bubble. */+ sourceRowId?: number}export type ChatMessagePart = Exclude<ThreadMessageLike['content'], string>[number] & TimelinePartMetadata@@ -42,6 +44,10 @@ export type ChatMessage = {* action footer so only the turn's final reply carries copy/refresh, and* the live view matches rehydration (which merges the turn into one bubble). */interim?: boolean+ /** Locally recovered output not yet represented by a durable completed reply. */+ recovered?: boolean+ /** Whether hydration reached a final assistant source row, rather than a tool round. */+ durableComplete?: boolean/** 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. */diff --git a/apps/desktop/src/lib/inflight-turn-journal.test.ts b/apps/desktop/src/lib/inflight-turn-journal.test.tsindex 8041db1059a..eba26483427 100644--- a/apps/desktop/src/lib/inflight-turn-journal.test.ts+++ b/apps/desktop/src/lib/inflight-turn-journal.test.ts@@ -671,16 +671,14 @@ describe('recoverInFlightTurnJournal', () => {// desktop as "the answer was already there, but it was inputted again".it('does not re-append committed answers when the journaled user row never persisted', () => {- // A resume projection can journal a `user-inflight-*` row that was never- // written to the DB (and may even belong to a different conversation).- // Because no base user matches it, the fold used to treat the whole tail- // as unknown and append it — duplicating the assistant answers below.+ // The prompt projection did not persist, but durable assistant identity+ // proves this exact answer is already stored. Equal text alone cannot.journalEntry([user('user-inflight-a3c2beb1', 'a stray user bubble that never persisted'),- assistant('assistant-stream-1', 'the committed answer')+ assistant('assistant-stream-1', 'the committed answer', { rowId: 42 })])- const base = [user('db-u1', 'the real prompt'), assistant('db-a1', 'the committed answer')]+ const base = [user('db-u1', 'the real prompt'), assistant('db-a1', 'the committed answer', { rowId: 42 })]const result = recoverInFlightTurnJournal('stored-1', base, { keepPending: false })expect(result.caughtUp).toBe(true)@@ -695,9 +693,9 @@ describe('recoverInFlightTurnJournal', () => {// A tail captured after a partial hydrate can end on assistant rows with// no user prompt before them. The old code appended them verbatim, so the// transcript ended with a duplicate of an answer that was already settled.- journalEntry([assistant('assistant-stream-1', 'the committed answer')])+ journalEntry([assistant('assistant-stream-1', 'the committed answer', { rowId: 42 })])- const base = [user('db-u1', 'the real prompt'), assistant('db-a1', 'the committed answer')]+ const base = [user('db-u1', 'the real prompt'), assistant('db-a1', 'the committed answer', { rowId: 42 })]const result = recoverInFlightTurnJournal('stored-1', base, { keepPending: false })expect(result.caughtUp).toBe(true)diff --git a/apps/desktop/src/lib/inflight-turn-journal.ts b/apps/desktop/src/lib/inflight-turn-journal.tsindex 31a314bb052..abe2098d94e 100644--- a/apps/desktop/src/lib/inflight-turn-journal.ts+++ b/apps/desktop/src/lib/inflight-turn-journal.ts@@ -1,4 +1,5 @@import { type ChatMessage, type ChatMessagePart, chatMessageText } from '@/lib/chat-messages'+import { withoutCoveredAssistantPrefix } from '@/lib/chat-messages/coverage'/*** Crash-survivable in-flight turn journal.@@ -140,6 +141,7 @@ function isSnapshot(value: unknown): value is InFlightTurnSnapshot {Boolean(part) &&typeof part === 'object' &&typeof part.type === 'string' &&+ (part.sourceRowId === undefined || (typeof part.sourceRowId === 'number' && Number.isFinite(part.sourceRowId))) &&(part.type !== 'text' && part.type !== 'reasoning'? part.type !== 'tool-call' ||(typeof part.toolName === 'string' &&@@ -154,6 +156,8 @@ function isSnapshot(value: unknown): value is InFlightTurnSnapshot {(message.branchGroupId === undefined || typeof message.branchGroupId === 'string') &&(message.hidden === undefined || typeof message.hidden === 'boolean') &&(message.interim === undefined || typeof message.interim === 'boolean') &&+ (message.recovered === undefined || typeof message.recovered === 'boolean') &&+ (message.durableComplete === undefined || typeof message.durableComplete === 'boolean') &&(message.attachmentRefs === undefined ||(Array.isArray(message.attachmentRefs) && message.attachmentRefs.every(ref => typeof ref === 'string'))) &&(message.rowId === undefined || (typeof message.rowId === 'number' && Number.isFinite(message.rowId)))@@ -270,6 +274,7 @@ function boundedPart(part: ChatMessagePart): ChatMessagePart | null {return {type: 'text',text: boundedString(part.text, MAX_TEXT_PART_CHARS),+ ...(part.sourceRowId === undefined ? {} : { sourceRowId: part.sourceRowId }),...(part.parentId === undefined ? {} : { parentId: boundedString(part.parentId, MAX_METADATA_CHARS) })}}@@ -362,6 +367,8 @@ function boundedMessages(messages: ChatMessage[]): ChatMessage[] | null {: { branchGroupId: boundedString(message.branchGroupId, MAX_METADATA_CHARS) }),...(message.hidden === undefined ? {} : { hidden: message.hidden }),...(message.interim === undefined ? {} : { interim: message.interim }),+ ...(message.recovered === undefined ? {} : { recovered: message.recovered }),+ ...(message.durableComplete === undefined ? {} : { durableComplete: message.durableComplete }),...(message.attachmentRefs === undefined? {}: {@@ -528,6 +535,7 @@ function userMessagesMatch(left: ChatMessage, right: ChatMessage): boolean {return (left.role === 'user' &&right.role === 'user' &&+ (left.rowId === undefined || right.rowId === undefined || left.rowId === right.rowId) &&normalizedText(chatMessageText(left)) === normalizedText(chatMessageText(right)) &&attachmentSignature(left) === attachmentSignature(right))@@ -611,7 +619,8 @@ function normalizeRecoveredTail(tail: ChatMessage[], keepPending: boolean): Chatmessage.role === 'assistant'? {...message,- pending: keepPending ? (message.pending ?? true) : false+ pending: keepPending ? (message.pending ?? true) : false,+ ...(keepPending ? {} : { recovered: true })}: { ...message, pending: false })@@ -693,10 +702,8 @@ function withoutBaseIds(rows: ChatMessage[], baseMessages: ChatMessage[]): ChatMreturn rows.filter(row => !baseIds.has(row.id))}-/** Whether every recoverable assistant row in the journal tail already exists- * as committed text in the base transcript. When true, the journal outlived- * the turn it recorded and appending it would re-render the same answers at- * the end of the transcript (the "scrambled conversation" regression). */+/** Without a matched user interval, only explicit row identity can establish+ * coverage. An older turn saying the same thing does not retire this journal. */function journalTailAlreadyCommitted(tailAssistants: ChatMessage[], baseMessages: ChatMessage[]): boolean {const recoverable = tailAssistants.filter(assistantHasRecoverableContent)@@ -704,19 +711,21 @@ function journalTailAlreadyCommitted(tailAssistants: ChatMessage[], baseMessagesreturn false}- const baseTexts = new Set(- baseMessages- .filter(message => message.role === 'assistant' && !message.hidden)- .map(message => normalizedText(chatMessageText(message)))- )-- return recoverable.every(message => {- const text = normalizedText(chatMessageText(message))+ return recoverable.every(message => baseMessages.some(base =>+ base.role === 'assistant' && !base.hidden && !isLiveProjectionRow(base) && !base.recovered &&+ (base.id === message.id || (base.rowId !== undefined && base.rowId === message.rowId)) &&+ base.error === message.error &&+ normalizedText(chatMessageText(base)) === normalizedText(chatMessageText(message)) &&+ message.parts.every(part => {+ if (part.type === 'tool-call') {+ return base.parts.some(candidate => candidate.type === 'tool-call' && Boolean(part.toolCallId) &&+ candidate.toolCallId === part.toolCallId)+ }- // Error-only rows carry no text to verify against — keep the conservative- // append path rather than risk dropping a recoverable failure.- return text.length > 0 && baseTexts.has(text)- })+ return part.type !== 'reasoning' || base.parts.some(candidate => candidate.type === 'reasoning' &&+ normalizedText(candidate.text) === normalizedText(part.text))+ })+ ))}export function mergeInFlightMessages(@@ -738,10 +747,10 @@ export function mergeInFlightMessages(return noop}- const tailUserIndex = tail.findIndex(message => message.role === 'user')+ const tailUserIndex = tail.findLastIndex(message => message.role === 'user')const tailUser = tailUserIndex >= 0 ? tail[tailUserIndex] : null- const tailAssistants = tail.slice(tailUserIndex + 1)- const lastJournalRow = tailAssistants.findLast(assistantHasRecoverableContent) ?? null+ let tailAssistants = tail.slice(tailUserIndex + 1)+ let lastJournalRow = tailAssistants.findLast(assistantHasRecoverableContent) ?? nullconst matchingUserIndex = tailUser ? baseMessages.findLastIndex(message => userMessagesMatch(message, tailUser)) : -1if (matchingUserIndex < 0) {@@ -761,29 +770,35 @@ export function mergeInFlightMessages(applied: true,caughtUp: false,messages: [...baseMessages, ...withoutBaseIds(tail, baseMessages)],- // Only a genuinely running turn keeps a live stream target. On an idle- // resume, carrying the stale streamId would keep the journal entry alive- // (persistInFlightTurnState only clears when streamId is null) and the- // same tail would be folded again on every open.+ // Recovered output stays journaled without pretending the backend is busy.streamId: options.keepPending ? streamId : null,turnStartedAt: null}}- const afterUser = baseMessages.slice(matchingUserIndex + 1)+ const nextUserIndex = baseMessages.findIndex((message, index) => index > matchingUserIndex && message.role === 'user')+ const end = nextUserIndex < 0 ? baseMessages.length : nextUserIndex+ const afterUser = baseMessages.slice(matchingUserIndex + 1, end)const completedReply = afterUser.find(- message => assistantHasRecoverableContent(message) && !isLiveProjectionRow(message)+ message => assistantHasRecoverableContent(message) && !isLiveProjectionRow(message) && !message.recovered &&+ (message.durableComplete === true || (message.durableComplete === undefined && !message.interim &&+ !message.parts.some(part => part.type === 'tool-call'))))if (completedReply) {- // The transcript already holds this turn's committed reply — the journal- // entry is stale.+ // A final reply, not merely a persisted tool round, supersedes this tail.return { ...noop, caughtUp: true }}- const projectionIndex = baseMessages.findIndex(- (message, index) => index > matchingUserIndex && message.role === 'assistant' && isLiveProjectionRow(message)+ tailAssistants = withoutCoveredAssistantPrefix(+ afterUser.filter(message => !isLiveProjectionRow(message) && !message.recovered), tailAssistants+ )+ lastJournalRow = tailAssistants.findLast(assistantHasRecoverableContent) ?? null++ const projectionIndex = baseMessages.findLastIndex(+ (message, index) => index > matchingUserIndex && index < end && message.role === 'assistant' &&+ !message.interim && isLiveProjectionRow(message))if (projectionIndex < 0) {@@ -796,11 +811,9 @@ export function mergeInFlightMessages(return {applied: true,caughtUp: false,- messages: [...baseMessages, ...withoutBaseIds(tailAssistants, baseMessages)],- // Same idle-resume rule as the other exit paths: only a running turn- // keeps the stream target alive. Carrying the stale streamId here kept- // the journal entry alive (persistInFlightTurnState only clears when- // streamId is null), so the same tail was folded again on every open.+ messages: [...baseMessages.slice(0, end), ...withoutBaseIds(tailAssistants, baseMessages), ...baseMessages.slice(end)],+ // Only a running turn keeps a stream target; recovered metadata retains+ // the journal independently until durable completion is observed.streamId: options.keepPending ? streamId : null,turnStartedAt: null}@@ -818,7 +831,7 @@ export function mergeInFlightMessages(const messages = [...baseMessages.slice(0, projectionIndex),- ...sealedRows,+ ...withoutBaseIds(sealedRows, baseMessages),merged,...baseMessages.slice(projectionIndex + 1)]@@ -827,9 +840,7 @@ export function mergeInFlightMessages(applied: true,caughtUp: false,messages,- // Same idle-resume rule as the append path: only a running turn keeps the- // stream target alive, so an idle resume clears the journal instead of- // re-folding the same tail on every open.+ // Idle recovered output must not reopen a streaming bubble.streamId: options.keepPending ? merged.id : null,turnStartedAt: null}@@ -924,7 +935,8 @@ export function persistInFlightTurnState(state: JournalableSessionState): void {return}- if (!state.busy && !state.awaitingResponse && !state.streamId) {+ if (!state.busy && !state.awaitingResponse && !state.streamId &&+ !recoverableTail(state.messages, null).some(message => message.recovered)) {clearInFlightTurnJournal(storedSessionId)returndiff --git a/apps/desktop/src/lib/transcript-occurrences.test.ts b/apps/desktop/src/lib/transcript-occurrences.test.tsnew file mode 100644index 00000000000..2a4225b4e01--- /dev/null+++ b/apps/desktop/src/lib/transcript-occurrences.test.ts@@ -0,0 +1,132 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'+import {+ mergeInFlightMessages,+ persistInFlightTurnState,+ readInFlightTurnJournal,+ recoverInFlightTurnJournal,+ resetInFlightTurnJournalStateForTests+} from '@/lib/inflight-turn-journal'+import type { SessionMessage } from '@/types/hermes'++const prompt: SessionMessage = { id: 1, role: 'user', content: 'Inspect each phase', timestamp: 1 }++const round = (id: number, text: string): SessionMessage[] => [+ {+ id,+ role: 'assistant',+ content: text,+ timestamp: id,+ tool_calls: [{ id: `tool-${id}`, type: 'function', function: { name: 'read_file', arguments: '{}' } }]+ },+ { id: id + 1, role: 'tool', content: 'result', timestamp: id + 1, tool_call_id: `tool-${id}` }+]++const assistantTexts = (rows: ChatMessage[]) => rows.filter(row => row.role === 'assistant').map(chatMessageText)++beforeEach(() => {+ vi.useFakeTimers()+ localStorage.clear()+ resetInFlightTurnJournalStateForTests()+})+afterEach(() => {+ resetInFlightTurnJournalStateForTests()+ localStorage.clear()+ vi.useRealTimers()+})++it('hydrates authored occurrences rather than deduplicating equal text across tool rounds', () => {+ const first = round(2, 'Status unchanged.')+ const second = round(4, 'Status unchanged.')+ const final: SessionMessage = { id: 6, role: 'assistant', content: 'Status unchanged.', timestamp: 6 }+ const messages = toChatMessages([prompt, ...first, ...second, final])+ const textParts = messages.flatMap(row => row.parts.filter(part => part.type === 'text'))++ expect(textParts.map(part => part.text)).toEqual(['Inspect each phase', ...Array(3).fill('Status unchanged.')])+ expect(messages.at(-1)?.durableComplete).toBe(true)+ expect(toChatMessages([prompt, ...first, ...second]).at(-1)?.durableComplete).toBe(false)+ // The same physical row is not another authored occurrence.+ expect(assistantTexts(toChatMessages([prompt, ...first, first[0]]))).toEqual(['Status unchanged.'])+})++it('recovers only the uncommitted journal suffix until the complete reply becomes durable', () => {+ const stored = toChatMessages([prompt, ...round(2, 'Checking the file.')])++ const tail: ChatMessage = {+ id: 'assistant-stream-runtime', role: 'assistant', pending: true,+ parts: [{ type: 'text', text: 'The unfinished conclusion.' }]+ }++ const state = {+ storedSessionId: 'occurrence-session', busy: true, awaitingResponse: false,+ streamId: tail.id, turnStartedAt: 1000, messages: [...stored, tail]+ }++ persistInFlightTurnState(state)+ vi.advanceTimersByTime(400)++ const first = recoverInFlightTurnJournal(state.storedSessionId, stored)+ expect(first.caughtUp).toBe(false)+ expect(assistantTexts(first.messages)).toEqual(['Checking the file.', 'The unfinished conclusion.'])+ expect(first.streamId).toBeNull()+ // Publishing idle recovered state must not delete its only persistent copy.+ persistInFlightTurnState({ ...state, messages: first.messages, busy: false, streamId: null })+ vi.advanceTimersByTime(400)+ resetInFlightTurnJournalStateForTests()+ const reopened = recoverInFlightTurnJournal(state.storedSessionId, stored)+ expect(assistantTexts(reopened.messages)).toEqual(assistantTexts(first.messages))+ expect(readInFlightTurnJournal(state.storedSessionId)).not.toBeNull()++ const completed = toChatMessages([+ prompt, ...round(2, 'Checking the file.'),+ { id: 4, role: 'assistant', content: 'The unfinished conclusion. Now complete.', timestamp: 4 }+ ])++ expect(recoverInFlightTurnJournal(state.storedSessionId, completed).caughtUp).toBe(true)+ expect(readInFlightTurnJournal(state.storedSessionId)).toBeNull()+})++it.each(['missing prompt', 'repeated prompt', 'no prompt'])('does not clear an unknown journal occurrence by global text: %s', shape => {+ const older = toChatMessages([prompt, { id: 2, role: 'assistant', content: 'Still working.', timestamp: 2 }])++ const user: ChatMessage = {+ id: 'new-user', rowId: 3, role: 'user',+ parts: [{ type: 'text', text: shape === 'repeated prompt' ? 'Inspect each phase' : 'A new question' }]+ }++ const answer: ChatMessage = {+ id: 'assistant-stream-new', role: 'assistant', pending: true,+ parts: [{ type: 'text', text: 'Still working.' }]+ }++ persistInFlightTurnState({+ storedSessionId: 'repeated-session', messages: [...(shape === 'no prompt' ? [] : [user]), answer],+ busy: true, awaitingResponse: false, streamId: answer.id, turnStartedAt: 3000+ })+ vi.advanceTimersByTime(400)+ const recovered = recoverInFlightTurnJournal('repeated-session', older)+ expect(recovered.caughtUp).toBe(false)+ expect(assistantTexts(recovered.messages)).toEqual(['Still working.', 'Still working.'])+ expect(readInFlightTurnJournal('repeated-session')).not.toBeNull()+})++it.each([true, false])('journal replay preserves sealed occurrences (live projection: %s)', hasLiveProjection => {+ const user = toChatMessages([prompt])[0]++ const sealed: ChatMessage = {+ id: 'assistant-stream-sealed', role: 'assistant', interim: true, pending: false,+ parts: [{ type: 'text', text: 'Checking.' }]+ }++ const live: ChatMessage = {+ id: 'assistant-stream-live', role: 'assistant', pending: true,+ parts: [{ type: 'text', text: 'Still working.' }]+ }++ const base = [user, sealed, live]+ const recovered = mergeInFlightMessages(hasLiveProjection ? base : base.slice(0, -1), base, { keepPending: true })+ expect(recovered.messages.map(row => row.id)).toEqual(base.map(row => row.id))+ expect(assistantTexts(recovered.messages)).toEqual(assistantTexts(base))+ expect(recovered.streamId).toBe(live.id)+})