Skip to content

The agent that grows with you

fix(desktop): never route a tool event onto a finished row from an earlier turn

teknium132cf330f2027
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-complete.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-complete.test.tsx
deleted file mode 100644
index d8c798ae754..00000000000
--- a/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-complete.test.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import type { GatewayEventName } from '@hermes/shared'
-import { act, cleanup } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-
-import { type MessageStreamHarness, renderMessageStream } from './test-harness'
-
-const SID = 'late-tool-complete-session'
-
-let stream: MessageStreamHarness
-
-const event = (type: GatewayEventName, timestamp: number, payload: Record<string, unknown> = {}) =>
- act(() => stream.handleEvent({ payload: { ...payload, timestamp }, session_id: SID, type }))
-
-const toolParts = () =>
- (stream.state(SID).messages ?? []).flatMap(message => message.parts.filter(part => part.type === 'tool-call'))
-
-describe('late tool completions across interim boundaries', () => {
- beforeEach(async () => {
- stream = renderMessageStream(SID)
- })
-
- afterEach(() => {
- cleanup()
- vi.restoreAllMocks()
- })
-
- it('attaches a late completion to the sealed bubble that owns the call', () => {
- event('message.start', 100)
- event('message.delta', 101, { text: 'Scraping the page.' })
- event('tool.start', 102, { args: { url: 'https://example.test' }, name: 'browser', tool_id: 'call-late-1' })
- // Interim commentary seals the streaming bubble while the browser scrape
- // keeps running (minutes in practice). streamId drops; the tool part is
- // sealed with completedAt and no result.
- event('message.interim', 103, { text: 'Scraping the page.' })
- event('tool.complete', 260.5, { name: 'browser', result: 'ok', tool_id: 'call-late-1' })
-
- const assistants = (stream.state(SID).messages ?? []).filter(message => message.role === 'assistant')
-
- expect(assistants).toHaveLength(1)
- // The sealed part got the result instead of staying "Result unavailable"...
- expect(assistants[0].parts).toEqual([
- expect.objectContaining({ completedAt: 102, type: 'text' }),
- expect.objectContaining({ result: 'ok', toolCallId: 'call-late-1', type: 'tool-call' })
- ])
-
- // ...and no duplicate row was seeded into a fresh bubble.
- expect(toolParts()).toHaveLength(1)
- })
-
- it('seeds a fresh bubble for a completion with no owner', () => {
- event('message.start', 400)
- event('message.interim', 401, { text: 'Sealed.' })
- // A completion whose tool.start never arrived (reconnect gap): no part
- // owns the id, so it seeds a bubble as before instead of vanishing.
- event('tool.complete', 402, { name: 'grep', result: 'match', tool_id: 'call-fresh-1' })
-
- const assistants = (stream.state(SID).messages ?? []).filter(message => message.role === 'assistant')
-
- expect(assistants).toHaveLength(2)
- expect(assistants[1].parts).toEqual([
- expect.objectContaining({ result: 'match', toolCallId: 'call-fresh-1', type: 'tool-call' })
- ])
- })
-})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-events.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-events.test.tsx
new file mode 100644
index 00000000000..74daeb17c97
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-events.test.tsx
@@ -0,0 +1,119 @@
+import type { GatewayEventName } from '@hermes/shared'
+// Tool events route to the bubble that owns the call id, not to whatever is
+// streaming now. A result that lands AFTER its part was sealed (interim
+// commentary, mid-turn user insert, turn settle) must re-attach to that part
+// instead of seeding a duplicate row under "Result unavailable" (#113035) —
+// but a call id that repeats across turns (llama.cpp emits one constant id)
+// must never be routed back onto a finished row from an earlier turn.
+import { act, cleanup } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+
+import { appendMidTurnUserMessage } from '@/app/session/hooks/use-prompt-actions/rewind'
+
+import { type MessageStreamHarness, renderMessageStream } from './test-harness'
+
+const SID = 'late-tool-events-session'
+
+let stream: MessageStreamHarness
+
+const event = (type: GatewayEventName, timestamp: number, payload: Record<string, unknown> = {}) =>
+ act(() => stream.handleEvent({ payload: { ...payload, timestamp }, session_id: SID, type }))
+
+const toolRows = (toolCallId: string) =>
+ (stream.state(SID).messages ?? []).flatMap((message, messageIndex) =>
+ message.parts.flatMap(part =>
+ part.type === 'tool-call' && part.toolCallId === toolCallId ? [{ messageIndex, part }] : []
+ )
+ )
+
+describe('tool events for a part that already exists on a sealed message', () => {
+ beforeEach(() => {
+ stream = renderMessageStream(SID)
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('attaches a late completion to the sealed bubble that owns the call', () => {
+ event('message.start', 100)
+ event('message.delta', 101, { text: 'Scraping the page.' })
+ event('tool.start', 102, { args: { url: 'https://example.test' }, name: 'browser', tool_id: 'call-late-1' })
+ // Interim commentary seals the streaming bubble while the browser scrape
+ // keeps running (minutes in practice). streamId drops; the tool part is
+ // sealed with completedAt and no result.
+ event('message.interim', 103, { text: 'Scraping the page.' })
+ event('tool.complete', 260.5, { name: 'browser', result: 'ok', tool_id: 'call-late-1' })
+
+ const state = stream.state(SID)
+ const assistants = (state.messages ?? []).filter(message => message.role === 'assistant')
+
+ // The sealed part got the result instead of staying "Result unavailable"
+ // and no duplicate row was seeded into a fresh bubble.
+ expect(assistants).toHaveLength(1)
+ expect(assistants[0].parts).toEqual([
+ expect.objectContaining({ completedAt: 102, type: 'text' }),
+ expect.objectContaining({ result: 'ok', toolCallId: 'call-late-1', type: 'tool-call' })
+ ])
+ expect(toolRows('call-late-1')).toHaveLength(1)
+ // The late completion does not re-open a stream bubble.
+ expect(state.streamId).toBeNull()
+ })
+
+ it('keeps one live row when the user types mid-turn and the running tool then completes', () => {
+ event('message.start', 300)
+ event('tool.start', 301, { args: { command: 'timeout 120 debug share' }, name: 'terminal', tool_id: 'call_02' })
+
+ // Mid-turn user insert (steer): the desktop seals the live bubble and
+ // clears streamId so the next assistant output lands below the user row.
+ act(() => {
+ stream.states.set(
+ SID,
+ appendMidTurnUserMessage(stream.state(SID), {
+ id: 'user-steer',
+ role: 'user',
+ parts: [{ type: 'text', text: 'also check the log' }],
+ timestamp: 302
+ })
+ )
+ })
+
+ // A running-phase event for the same call (progress/replay) must update
+ // the existing row, not seed a second live row under the user message.
+ event('tool.start', 303, { args: { command: 'timeout 120 debug share' }, name: 'terminal', tool_id: 'call_02' })
+
+ const running = toolRows('call_02')
+ expect(running).toHaveLength(1)
+ expect(running[0].messageIndex).toBe(0)
+ expect((running[0].part as { completedAt?: number }).completedAt).toBeUndefined()
+
+ event('tool.complete', 304, { name: 'terminal', result: 'shared', tool_id: 'call_02' })
+
+ const found = toolRows('call_02')
+ expect(found).toHaveLength(1)
+ expect(found[0].messageIndex).toBe(0)
+ expect(found[0].part).toMatchObject({ result: 'shared', type: 'tool-call' })
+ // user row stays the tail: no phantom assistant bubble was appended.
+ expect(stream.state(SID).messages.at(-1)?.id).toBe('user-steer')
+ })
+
+ it('draws a reused tool_call_id from a later turn as its own row, not over the finished one', () => {
+ event('message.start', 400)
+ event('tool.start', 401, { args: { command: 'echo step1' }, name: 'terminal', tool_id: 'call_const' })
+ event('tool.complete', 402, { name: 'terminal', result: 'step 1 output', tool_id: 'call_const' })
+ event('message.complete', 403, { text: 'first' })
+
+ // Same id in the next turn: a finished part is never the owner of a new
+ // running event, so this call lands in the live bubble.
+ event('message.start', 500)
+ event('tool.start', 501, { args: { command: 'echo step2' }, name: 'terminal', tool_id: 'call_const' })
+ event('tool.complete', 502, { name: 'terminal', result: 'step 2 output', tool_id: 'call_const' })
+ event('message.complete', 503, { text: 'second' })
+
+ const rows = toolRows('call_const')
+ expect(rows).toHaveLength(2)
+ expect(rows[0].part).toMatchObject({ args: { command: 'echo step1' }, result: 'step 1 output' })
+ expect(rows[1].part).toMatchObject({ args: { command: 'echo step2' }, result: 'step 2 output' })
+ expect(rows[1].messageIndex).toBeGreaterThan(rows[0].messageIndex)
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-result.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-result.test.tsx
deleted file mode 100644
index ad2830c23b5..00000000000
--- a/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-result.test.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import type { GatewayEvent } from '@hermes/shared'
-// A tool result that lands AFTER its part was sealed (turn settled without the
-// completion, or the user typed mid-turn and the live bubble was closed) must
-// re-attach to the part that already carries its tool_call_id. Seeding a new
-// bubble instead leaves the original row on "Result unavailable" while a
-// duplicate row for the same call shows below it (#113035).
-import { act, cleanup } from '@testing-library/react'
-import { afterEach, describe, expect, it } from 'vitest'
-
-import { appendMidTurnUserMessage } from '@/app/session/hooks/use-prompt-actions/rewind'
-import type { ChatMessage } from '@/lib/chat-messages'
-
-import { renderMessageStream } from './test-harness'
-
-const SID = 'late-tool-result-session'
-
-const emit = (stream: ReturnType<typeof renderMessageStream>, event: GatewayEvent) =>
- act(() => stream.handleEvent(event))
-
-function toolParts(messages: ChatMessage[], toolCallId: string) {
- return messages.flatMap((message, messageIndex) =>
- message.parts.flatMap(part =>
- part.type === 'tool-call' && part.toolCallId === toolCallId ? [{ messageIndex, part }] : []
- )
- )
-}
-
-describe('tool events for a part that already exists on a settled message', () => {
- afterEach(() => {
- cleanup()
- })
-
- it('re-attaches a tool.complete that arrives after message.complete sealed the part', () => {
- const stream = renderMessageStream(SID)
-
- emit(stream, { session_id: SID, type: 'message.start', payload: {} })
- emit(stream, {
- payload: { args: { command: 'sleep 90' }, name: 'terminal', tool_id: 'call_01' },
- session_id: SID,
- type: 'tool.start'
- })
- // The turn settles before the completion frame reaches this window.
- emit(stream, { payload: { text: 'done' }, session_id: SID, type: 'message.complete' })
-
- const sealed = toolParts(stream.state().messages, 'call_01')
- expect(sealed).toHaveLength(1)
- expect(sealed[0].part).toMatchObject({ type: 'tool-call' })
-
- emit(stream, {
- payload: { name: 'terminal', result: 'ok', tool_id: 'call_01' },
- session_id: SID,
- type: 'tool.complete'
- })
-
- const state = stream.state()
- const found = toolParts(state.messages, 'call_01')
-
- // One row for one call, on the message that owned it, with the result.
- expect(found).toHaveLength(1)
- expect(found[0].messageIndex).toBe(sealed[0].messageIndex)
- expect(found[0].part).toMatchObject({ result: 'ok', type: 'tool-call' })
- expect(state.messages.filter(m => m.role === 'assistant')).toHaveLength(1)
- // The late completion does not re-open a stream bubble.
- expect(state.streamId).toBeNull()
- })
-
- it('keeps one live row when the user types mid-turn and the running tool then completes', () => {
- const stream = renderMessageStream(SID)
-
- emit(stream, { session_id: SID, type: 'message.start', payload: {} })
- emit(stream, {
- payload: { args: { command: 'timeout 120 debug share' }, name: 'terminal', tool_id: 'call_02' },
- session_id: SID,
- type: 'tool.start'
- })
-
- // Mid-turn user insert (steer): the desktop seals the live bubble and
- // clears streamId so the next assistant output lands below the user row.
- act(() => {
- const current = stream.state()
- stream.states.set(
- SID,
- appendMidTurnUserMessage(current, {
- id: 'user-steer',
- role: 'user',
- parts: [{ type: 'text', text: 'also check the log' }],
- timestamp: Date.now() / 1000
- })
- )
- })
-
- // A running-phase event for the same call (progress/replay) must update
- // the existing row, not seed a second live row under the user message.
- emit(stream, {
- payload: { args: { command: 'timeout 120 debug share' }, name: 'terminal', tool_id: 'call_02' },
- session_id: SID,
- type: 'tool.start'
- })
-
- const running = toolParts(stream.state().messages, 'call_02')
- expect(running).toHaveLength(1)
- expect(running[0].messageIndex).toBe(0)
- expect(running[0].part).toMatchObject({ type: 'tool-call' })
- expect((running[0].part as { completedAt?: number }).completedAt).toBeUndefined()
-
- emit(stream, {
- payload: { name: 'terminal', result: 'shared', tool_id: 'call_02' },
- session_id: SID,
- type: 'tool.complete'
- })
-
- const state = stream.state()
- const found = toolParts(state.messages, 'call_02')
-
- expect(found).toHaveLength(1)
- expect(found[0].messageIndex).toBe(0)
- expect(found[0].part).toMatchObject({ result: 'shared', type: 'tool-call' })
- // user row stays the tail: no phantom assistant bubble was appended.
- expect(state.messages.at(-1)?.id).toBe('user-steer')
- })
-})
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index d65f549428e..f5f5b22afc8 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -391,9 +391,16 @@ export interface SettledClarifyProjection {
* sealed with `completedAt` but no `result`, renders as "Result unavailable"),
* instead of seeding a fresh bubble with a duplicate row (#113035).
*
- * Newest-first: interim boundaries append bubbles, so the owner of an
- * in-flight call is the most recent message that carries the id. Idempotent
- * for duplicate completions — `upsertToolPart` overwrites the same part.
+ * Only an UNRESOLVED part (never completed: no `result` key, sealed or not)
+ * can own an event. Tool call ids are not unique across turns — llama.cpp
+ * emits one constant id for every call and Hermes' own deterministic ids
+ * repeat — so a part that already carries its completion is a finished call
+ * from an earlier turn, not the owner of the new one. Routing to it would
+ * draw the new call over the old row and leave the live turn empty.
+ *
+ * Newest-first among unresolved parts: interim boundaries append bubbles, so
+ * the owner of an in-flight call is the most recent message that carries the
+ * id without a result.
*/
export function toolCallOwnerMessageId(
messages: ChatMessage[],
@@ -409,7 +416,7 @@ export function toolCallOwnerMessageId(
const message = messages[messageIndex]
for (const part of message.parts) {
- if (part.type === 'tool-call' && part.toolCallId === stableId) {
+ if (part.type === 'tool-call' && part.toolCallId === stableId && !Object.hasOwn(part, 'result')) {
return message.id
}
}