Skip to content

The agent that grows with you

fix(desktop): stop manufacturing duplicate toolCallIds at the fold, repair poisoned cached tails

Teknium40f3e58f6de9
diff --git a/apps/desktop/src/app/chat/runtime-repository.test.ts b/apps/desktop/src/app/chat/runtime-repository.test.ts
index de7a97d39c5..f02d5cd826b 100644
--- a/apps/desktop/src/app/chat/runtime-repository.test.ts
+++ b/apps/desktop/src/app/chat/runtime-repository.test.ts
@@ -79,4 +79,108 @@ describe('useRuntimeMessageRepository', () => {
expect(windowedParents.get('a-1')).toBe(windowedParents.get('a-2'))
})
+
+ it('renames a duplicated toolCallId within one message instead of crashing useResources (#87857)', () => {
+ // The streaming path can append the same tool call twice inside ONE message
+ // (optimistic write racing the authoritative event). @assistant-ui/tap's
+ // useResources throws on duplicate resource keys, so the repository must
+ // never emit two parts of one message keyed by the same `toolCallId-<id>`.
+ const duplicated: ChatMessage = {
+ id: 'assistant-dup',
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'running…' },
+ { type: 'tool-call', toolCallId: 'call_00_DUP', toolName: 'terminal', args: {}, argsText: '' },
+ { type: 'tool-call', toolCallId: 'call_00_DUP', toolName: 'terminal', args: { done: true }, argsText: '{"done":true}' }
+ ] as ChatMessage['parts']
+ }
+
+ const { result } = renderHook(() => useRuntimeMessageRepository([text('user-1', 'user', 'go'), duplicated]))
+
+ const assistant = result.current.messages.find(item => item.message.id === 'assistant-dup')
+ expect(assistant).toBeDefined()
+
+ const toolParts = (assistant!.message.content as readonly { type: string; toolCallId?: string }[]).filter(
+ part => part.type === 'tool-call'
+ )
+ expect(toolParts).toHaveLength(2)
+ expect(new Set(toolParts.map(part => part.toolCallId)).size).toBe(2)
+
+ // And the runtime can link it end to end without throwing.
+ expect(feedToRepository(result.current).map(item => item.id)).toEqual(['user-1', 'assistant-dup'])
+ })
+
+ it('drops the carried-over copy when coalescing folds a repeated toolCallId into one message (#87857)', () => {
+ // Two individually-clean rows can share a toolCallId (structural carry-over
+ // re-attaching a cached row's calls while the same turn also exists as a
+ // committed row). Per-row that is harmless — assistant-ui's key space is
+ // per-message — but coalesceToolOnlyAssistants folds the tool-only
+ // follow-up into its predecessor, which used to manufacture the duplicate
+ // key. The fold must drop the copy the predecessor already carries while
+ // keeping the genuinely-new call.
+ const tool = (toolCallId: string): ChatMessage['parts'][number] =>
+ ({ type: 'tool-call', toolCallId, toolName: 'terminal', args: {}, argsText: '' }) as ChatMessage['parts'][number]
+
+ const committed: ChatMessage = {
+ id: 'committed-49-assistant',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'working' }, tool('call-a'), tool('call-b')] as ChatMessage['parts']
+ }
+ const streamed: ChatMessage = {
+ id: 'assistant-stream-49',
+ role: 'assistant',
+ parts: [tool('call-b'), tool('call-c')] as ChatMessage['parts']
+ }
+
+ const { result } = renderHook(() => useRuntimeMessageRepository([text('user-1', 'user', 'go'), committed, streamed]))
+
+ const assistant = result.current.messages.find(item => item.message.id === 'committed-49-assistant')
+ expect(assistant).toBeDefined()
+
+ const ids = (assistant!.message.content as readonly { type: string; toolCallId?: string }[])
+ .filter(part => part.type === 'tool-call')
+ .map(part => part.toolCallId)
+
+ // call-b appears once, call-c (genuinely new) survives the fold.
+ expect(ids).toEqual(['call-a', 'call-b', 'call-c'])
+
+ expect(feedToRepository(result.current).map(item => item.id)).toEqual(['user-1', 'committed-49-assistant'])
+ })
+
+ it('leaves a toolCallId repeated across DIFFERENT non-folded messages untouched', () => {
+ // anthropic_messages-mode providers (e.g. Kimi) number tool_use blocks per
+ // API response — `terminal_0` legitimately recurs on every turn. The key
+ // space is per-message, so cross-message repeats are NOT collisions and
+ // must never be renamed (renaming would defeat the identity cache and
+ // churn re-renders on every stream delta).
+ const turn = (n: number): ChatMessage[] => [
+ text(`user-${n}`, 'user', 'go'),
+ {
+ id: `assistant-${n}`,
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'ok' },
+ { type: 'tool-call', toolCallId: 'terminal_0', toolName: 'terminal', args: {}, argsText: '' }
+ ] as ChatMessage['parts']
+ }
+ ]
+
+ const { result } = renderHook(() => useRuntimeMessageRepository([...turn(1), ...turn(2)]))
+
+ for (const id of ['assistant-1', 'assistant-2']) {
+ const item = result.current.messages.find(entry => entry.message.id === id)
+ const ids = (item!.message.content as readonly { type: string; toolCallId?: string }[])
+ .filter(part => part.type === 'tool-call')
+ .map(part => part.toolCallId)
+
+ expect(ids).toEqual(['terminal_0'])
+ }
+
+ expect(feedToRepository(result.current).map(item => item.id)).toEqual([
+ 'user-1',
+ 'assistant-1',
+ 'user-2',
+ 'assistant-2'
+ ])
+ })
})
diff --git a/apps/desktop/src/lib/chat-runtime.test.ts b/apps/desktop/src/lib/chat-runtime.test.ts
index c4a6727a111..0da8da3f245 100644
--- a/apps/desktop/src/lib/chat-runtime.test.ts
+++ b/apps/desktop/src/lib/chat-runtime.test.ts
@@ -1,11 +1,14 @@
import { describe, expect, it } from 'vitest'
+import type { ChatMessage, ChatMessagePart } from '@/lib/chat-messages'
import type { ComposerAttachment } from '@/store/composer'
import {
attachmentDisplayText,
attachmentId,
+ coalesceToolOnlyAssistants,
coerceThinkingText,
+ createToolMergeCache,
messageCreatedAt,
optimisticAttachmentRef,
parseCommandDispatch,
@@ -251,3 +254,48 @@ describe('toRuntimeMessage timeline metadata', () => {
expect((runtime.metadata?.custom as { timelineTimestamp?: number }).timelineTimestamp).toBeUndefined()
})
})
+
+describe('coalesceToolOnlyAssistants toolCallId uniqueness', () => {
+ // Regression contract for #87857: two individually-clean assistant rows can
+ // share a toolCallId (structural carry-over re-attaching a cached row's tool
+ // calls while the same turn also exists as a committed row). Folding them
+ // used to manufacture ONE message carrying the id twice — the exact shape
+ // that makes assistant-ui's useResources throw and crash-loop the pane.
+ const tool = (toolCallId: string): ChatMessagePart =>
+ ({ type: 'tool-call', toolCallId, toolName: 'terminal', args: {} as never, argsText: '' }) as ChatMessagePart
+
+ const assistant = (id: string, parts: ChatMessagePart[]): ChatMessage =>
+ ({ id, role: 'assistant', parts }) as unknown as ChatMessage
+
+ it('drops the copy the predecessor already carries, keeps the new call', () => {
+ const merged = coalesceToolOnlyAssistants(
+ [
+ assistant('committed-49-assistant', [{ type: 'text', text: 'working' } as ChatMessagePart, tool('call-a'), tool('call-b')]),
+ assistant('assistant-stream-49', [tool('call-b'), tool('call-c')])
+ ],
+ createToolMergeCache()
+ )
+
+ expect(merged).toHaveLength(1)
+
+ const ids = merged[0].parts.filter(part => part.type === 'tool-call').map(part => (part as { toolCallId: string }).toolCallId)
+
+ expect(ids).toEqual(['call-a', 'call-b', 'call-c'])
+ })
+
+ it('folds a clean follow-up unchanged', () => {
+ const merged = coalesceToolOnlyAssistants(
+ [
+ assistant('a1', [{ type: 'text', text: 'ok' } as ChatMessagePart, tool('call-a')]),
+ assistant('a2', [tool('call-b')])
+ ],
+ createToolMergeCache()
+ )
+
+ expect(merged).toHaveLength(1)
+
+ const ids = merged[0].parts.filter(part => part.type === 'tool-call').map(part => (part as { toolCallId: string }).toolCallId)
+
+ expect(ids).toEqual(['call-a', 'call-b'])
+ })
+})
diff --git a/apps/desktop/src/lib/chat-runtime.ts b/apps/desktop/src/lib/chat-runtime.ts
index 211912dad60..98f4ff8b7f5 100644
--- a/apps/desktop/src/lib/chat-runtime.ts
+++ b/apps/desktop/src/lib/chat-runtime.ts
@@ -516,6 +516,45 @@ function isToolOnlyAssistant(message: ChatMessage): boolean {
)
}
+/**
+ * Concatenate a tool-only follow-up message's parts onto its predecessor's,
+ * dropping any incoming `tool-call` part whose `toolCallId` the predecessor
+ * already carries. A repeated id here is the SAME call re-attached (structural
+ * carry-over re-adding a cached row's tool calls, or a live-turn projection
+ * that also exists as a committed row — #87857): folding both copies into one
+ * message manufactures the duplicate key that crashes assistant-ui's
+ * `useResources`, and renaming it would render the same call twice. Genuinely
+ * new calls in the same follow-up row are preserved.
+ */
+export function concatToolPartsUnique(
+ prevParts: readonly ChatMessagePart[],
+ nextParts: readonly ChatMessagePart[]
+): ChatMessagePart[] {
+ const seen = new Set<string>()
+
+ for (const part of prevParts) {
+ if (part.type === 'tool-call' && part.toolCallId) {
+ seen.add(part.toolCallId)
+ }
+ }
+
+ const out = [...prevParts]
+
+ for (const part of nextParts) {
+ if (part.type === 'tool-call' && part.toolCallId) {
+ if (seen.has(part.toolCallId)) {
+ continue
+ }
+
+ seen.add(part.toolCallId)
+ }
+
+ out.push(part)
+ }
+
+ return out
+}
+
/**
* Fold each settled tool-only assistant message into the preceding assistant
* message so its calls join that message's tool group (and can collapse into
@@ -544,7 +583,7 @@ export function coalesceToolOnlyAssistants(messages: ChatMessage[], cache: ToolM
(latest, value) => (latest === undefined ? value : Math.max(latest, value)),
undefined
),
- parts: [...prev.parts, ...message.parts]
+ parts: concatToolPartsUnique(prev.parts, message.parts)
}
cache.set(message, { merged, parts: message.parts, prev, prevParts: prev.parts })
diff --git a/apps/desktop/src/store/transcript-tail-cache.test.ts b/apps/desktop/src/store/transcript-tail-cache.test.ts
index 6d941cd1c4c..aa6e6aad206 100644
--- a/apps/desktop/src/store/transcript-tail-cache.test.ts
+++ b/apps/desktop/src/store/transcript-tail-cache.test.ts
@@ -91,4 +91,29 @@ describe('transcript tail cache', () => {
expect(loadTranscriptTail('sess-5')).not.toBeNull()
expect(loadTranscriptTail('sess-54')).not.toBeNull()
})
+
+ it('repairs a poisoned persisted tail carrying a duplicate toolCallId (#87857)', () => {
+ // A tail written by an older build can hold one message with two tool-call
+ // parts sharing an id. This path paints DIRECTLY into the view and the same
+ // bytes are re-read every launch — without repair-on-read, an affected
+ // install crash-loops forever even after upgrading.
+ const tool = (toolCallId: string) => ({ type: 'tool-call', toolCallId, toolName: 'terminal', args: {}, argsText: '' })
+ const poisoned = {
+ messages: [{ id: 'assistant-p', role: 'assistant', parts: [tool('call-b'), tool('call-b')] }],
+ savedAt: Date.now()
+ }
+ window.localStorage.setItem('hermes.transcript-tail.v1:sess-poisoned', JSON.stringify(poisoned))
+
+ const loaded = loadTranscriptTail('sess-poisoned')
+
+ expect(loaded).toHaveLength(1)
+
+ const ids = (loaded![0].parts as { type: string; toolCallId?: string }[])
+ .filter(part => part.type === 'tool-call')
+ .map(part => part.toolCallId)
+
+ expect(ids).toHaveLength(2)
+ expect(new Set(ids).size).toBe(2)
+ expect(ids[0]).toBe('call-b')
+ })
})
diff --git a/apps/desktop/src/store/transcript-tail-cache.ts b/apps/desktop/src/store/transcript-tail-cache.ts
index 4010224d714..5a881f00be1 100644
--- a/apps/desktop/src/store/transcript-tail-cache.ts
+++ b/apps/desktop/src/store/transcript-tail-cache.ts
@@ -1,4 +1,5 @@
import type { ChatMessage } from '@/lib/chat-messages'
+import { withUniqueToolCallIdsWithinMessage } from '@/lib/chat-messages'
// ── Durable transcript-tail cache (#89206 "feels instant" layer) ────────────
// The in-memory warm cache (sessionStateByRuntimeIdRef) makes same-window
@@ -153,7 +154,13 @@ export function loadTranscriptTail(storedSessionId: string): ChatMessage[] | nul
throw new Error('empty')
}
- return parsed.messages
+ // Repair, don't just trust: a tail persisted by an older build (or by a
+ // producer bug) can carry two `tool-call` parts with one `toolCallId`
+ // inside a single message. This path paints DIRECTLY into the view, and a
+ // poisoned entry is re-read identically on every launch — the "one pane
+ // permanently broken" shape of #87857. Renaming at read keeps already-
+ // affected installs from crash-looping forever on upgraded builds.
+ return parsed.messages.map(withUniqueToolCallIdsWithinMessage)
} catch {
try {
store.removeItem(PREFIX + id)