Skip to content

The agent that grows with you

fix(desktop): reconcile failed tails without erasing later replies

brooklyn!10225745533b
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
index a4b53115a02..e7d2a7096e3 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
@@ -640,6 +640,37 @@ describe('active transcript refresh', () => {
})
describe('reconcileActiveTranscript', () => {
+ it('keeps one failed assistant bubble when refresh rebuilds the same tail turn under a new id', async () => {
+ const fixture = makeRefresh()
+ fixture.state.messages = [
+ {
+ id: 'optimistic-user',
+ parts: [{ text: 'question', type: 'text' }],
+ role: 'user'
+ },
+ {
+ error: 'connection lost after completion',
+ errorSurface: { code: 'transport_lost', layer: 'streaming', retryable: true },
+ id: 'assistant-live-before-refresh',
+ parts: [{ text: 'answer', type: 'text' }],
+ role: 'assistant'
+ }
+ ]
+ vi.mocked(getLatestSessionMessages).mockResolvedValue(transcript('answer') as never)
+
+ await fixture.refresh()
+
+ const messages = fixture.states.get(ACTIVE_RUNTIME_ID)?.messages ?? []
+ const assistants = messages.filter(message => message.role === 'assistant')
+
+ expect(assistants).toHaveLength(1)
+ expect(assistants[0]).toMatchObject({
+ error: 'connection lost after completion',
+ errorSurface: { code: 'transport_lost', layer: 'streaming', retryable: true },
+ pending: false
+ })
+ })
+
it('resolves and hydrates a messaging session from the messaging sessions store', async () => {
setSessionOwnerHint(ACTIVE_STORED_ID, {
connectionId: 'stale-messaging-owner',
diff --git a/apps/desktop/src/lib/chat-messages/reconciliation.test.ts b/apps/desktop/src/lib/chat-messages/reconciliation.test.ts
new file mode 100644
index 00000000000..71b6439dfa2
--- /dev/null
+++ b/apps/desktop/src/lib/chat-messages/reconciliation.test.ts
@@ -0,0 +1,59 @@
+import { expect, it } from 'vitest'
+
+import { type ChatMessage, preserveLocalAssistantErrors, textPart, toChatMessages } from './index'
+
+const row = (id: string, role: 'user' | 'assistant', text: string, extra: Partial<ChatMessage> = {}): ChatMessage => ({
+ id, role, parts: [textPart(text)], ...extra
+})
+
+it('reconciles only the represented failed tail, retaining its structured error and omitted segments', () => {
+ const hydrated = toChatMessages([
+ { role: 'user', content: 'read it', timestamp: 1 },
+ { role: 'assistant', content: '', timestamp: 2, tool_calls: [{ id: 'call', function: { name: 'read_file', arguments: '{"path":"README.md"}' } }] },
+ { role: 'tool', tool_call_id: 'call', tool_name: 'read_file', content: 'contents', timestamp: 3 },
+ { role: 'assistant', content: 'Done.', timestamp: 4 }
+ ])
+
+ const storedAssistant = hydrated.find(message => message.role === 'assistant')!
+
+ const failed = row('local-failure', 'assistant', 'Done.', {
+ parts: storedAssistant.parts,
+ error: 'connection lost after completion',
+ errorSurface: { code: 'transport_lost', layer: 'streaming', retryable: true }
+ })
+
+ for (const id of [failed.id, storedAssistant.id]) {
+ const merged = preserveLocalAssistantErrors(hydrated, [row('local-user', 'user', 'read it'), { ...failed, id }])
+ expect(merged.filter(message => message.role === 'assistant')).toHaveLength(1)
+ expect(merged.at(-1)).toMatchObject({ id: storedAssistant.id, error: failed.error, errorSurface: failed.errorSurface, pending: false })
+ }
+
+ const user = row('user', 'user', 'read it')
+ const earlier = row('earlier', 'assistant', 'Done.')
+ const laterUser = row('later-user', 'user', 'read it')
+
+ const cases: { name: string; stored: ChatMessage[]; local: ChatMessage[] }[] = [
+ { name: 'omitted continuation', stored: [user, earlier], local: [user, earlier, row('hidden', 'user', 'Continue.', { hidden: true }), failed] },
+ { name: 'older failed segment', stored: [user, earlier], local: [user, failed, earlier] },
+ { name: 'repeated prompt', stored: [user, earlier], local: [user, earlier, laterUser, failed] },
+ { name: 'older identical text', stored: [user, earlier, laterUser], local: [user, earlier, laterUser, failed] },
+ { name: 'different attachments', stored: [{ ...user, attachmentRefs: ['a.png'] }, earlier], local: [{ ...user, attachmentRefs: ['b.png'] }, failed] },
+ { name: 'different durable row', stored: [user, { ...earlier, rowId: 10 }], local: [user, { ...failed, rowId: 20 }] },
+ { name: 'reused tool id across turns', stored: [user, storedAssistant, laterUser], local: [user, storedAssistant, laterUser, failed] }
+ ]
+
+ for (const fixture of cases) {
+ const merged = preserveLocalAssistantErrors(fixture.stored, fixture.local)
+ expect(merged.find(message => message.id === failed.id)?.error, fixture.name).toBe(failed.error)
+
+ for (const stored of fixture.stored.filter(message => message.role === 'assistant')) {
+ expect(merged.find(message => message.id === stored.id)?.error, fixture.name).toBeUndefined()
+ }
+ }
+
+ const current = [user, row('earlier-live', 'assistant', 'First.'), failed]
+ const stored = [user, row('earlier-stored', 'assistant', 'First.'), earlier]
+ const merged = preserveLocalAssistantErrors(stored, current)
+ expect(merged.map(message => message.id)).toEqual(stored.map(message => message.id))
+ expect(merged.at(-1)).toMatchObject({ error: failed.error, errorSurface: failed.errorSurface })
+})
diff --git a/apps/desktop/src/lib/chat-messages/reconciliation.ts b/apps/desktop/src/lib/chat-messages/reconciliation.ts
index 7d14446af2e..6e6f98310da 100644
--- a/apps/desktop/src/lib/chat-messages/reconciliation.ts
+++ b/apps/desktop/src/lib/chat-messages/reconciliation.ts
@@ -40,6 +40,65 @@ const assistantTimelineMatch = (stored: ChatMessage, local: ChatMessage) => {
return Boolean(storedText) && storedText === normalizedTimelineText(local)
}
+const userTurnMatch = (stored: ChatMessage, local: ChatMessage) =>
+ stored.role === 'user' &&
+ local.role === 'user' &&
+ normalizedTimelineText(stored) === normalizedTimelineText(local) &&
+ (stored.attachmentRefs ?? []).join('\n') === (local.attachmentRefs ?? []).join('\n')
+
+/**
+ * Find the hydrated assistant representing a local failed tail turn.
+ *
+ * Text and provider tool-call ids are not globally unique, so the match is
+ * deliberately anchored to the last visible user turn on both timelines.
+ */
+const tailTurnAssistantMatchIndex = (
+ storedMessages: ChatMessage[],
+ localMessages: ChatMessage[],
+ localAssistantIndex: number
+) => {
+ if (
+ localMessages
+ .slice(localAssistantIndex + 1)
+ .some(message => (message.role === 'user' || message.role === 'assistant') && !message.hidden)
+ ) {
+ return -1
+ }
+
+ const visibleUser = (message: ChatMessage) => message.role === 'user' && !message.hidden
+ const visibleAssistant = (message: ChatMessage) => message.role === 'assistant' && !message.hidden
+ const localUserIndex = localMessages.findLastIndex(visibleUser)
+ const storedUserIndex = storedMessages.findLastIndex(visibleUser)
+
+ if (
+ localUserIndex < 0 ||
+ storedUserIndex < 0 ||
+ localMessages.filter(visibleUser).length !== storedMessages.filter(visibleUser).length ||
+ !userTurnMatch(storedMessages[storedUserIndex], localMessages[localUserIndex])
+ ) {
+ return -1
+ }
+
+ const localAssistants = localMessages.slice(localUserIndex + 1).filter(visibleAssistant)
+ const storedAssistants = storedMessages.slice(storedUserIndex + 1).filter(visibleAssistant)
+
+ // A hidden directive can produce another assistant under the same visible
+ // user. Match the whole segment sequence, never an earlier equivalent reply.
+ if (
+ localAssistants.length !== storedAssistants.length ||
+ !storedAssistants.every((stored, index) => {
+ const local = localAssistants[index]
+ const sameRow = stored.rowId === undefined || local.rowId === undefined || stored.rowId === local.rowId
+
+ return sameRow && assistantTimelineMatch(stored, local)
+ })
+ ) {
+ return -1
+ }
+
+ return storedMessages.findLastIndex(visibleAssistant)
+}
+
const timelinePartMatch = (stored: ChatMessagePart, local: ChatMessagePart) => {
if (stored.type !== local.type) {
return false
@@ -139,6 +198,7 @@ export function preserveLocalAssistantErrors(
return {
...message,
error: local.error,
+ ...(local.errorSurface ? { errorSurface: local.errorSurface } : {}),
pending: false
}
})
@@ -162,6 +222,19 @@ export function preserveLocalAssistantErrors(
continue
}
+ const hydratedAssistantIndex = tailTurnAssistantMatchIndex(mergedNextMessages, currentMessages, index)
+
+ if (hydratedAssistantIndex !== -1) {
+ mergedNextMessages[hydratedAssistantIndex] = {
+ ...mergedNextMessages[hydratedAssistantIndex],
+ error: message.error,
+ ...(message.errorSurface ? { errorSurface: message.errorSurface } : {}),
+ pending: false
+ }
+
+ continue
+ }
+
preserveIds.add(message.id)
for (let probe = index - 1; probe >= 0; probe -= 1) {