Skip to content

The agent that grows with you

fix(desktop): route running tool events by call id too and unseal the owning row

teknium16cdca684c3c2
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.ts
index d82bbfc60af..3377c4c1ac2 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
@@ -114,6 +114,11 @@ export function useMessageStream({
const reconciledId = opts.eventTarget?.(state) ?? null
const streamId = reconciledId ?? state.streamId ?? nextStreamMessageId('assistant-stream')
+ // The event landed on a bubble that is NOT the live stream (sealed
+ // by interim commentary, a mid-turn user message, or turn settle).
+ // It is a patch to history: the bubble keeps its own pending bit
+ // and the turn's stream bookkeeping is neither consulted nor changed.
+ const patchesSealedBubble = reconciledId !== null && reconciledId !== state.streamId
const groupId = state.pendingBranchGroup ?? undefined
const prev = state.messages
let nextMessages: ChatMessage[]
@@ -136,20 +141,23 @@ export function useMessageStream({
? {
...m,
parts: transform(m.parts, m),
- pending: opts.pending ? opts.pending(m) : true
+ pending: patchesSealedBubble ? (m.pending ?? false) : opts.pending ? opts.pending(m) : true
}
: m
)
}
+ if (patchesSealedBubble) {
+ // Later deltas must not append into the bubble the late event
+ // just updated, and a late event from an earlier phase must not
+ // clear the wait state of the turn now in flight.
+ return { ...state, messages: nextMessages }
+ }
+
return {
...state,
messages: nextMessages,
- // A reconciled target keeps the stream bookkeeping untouched:
- // the live stream (if any) keeps its own id, and a sealed one
- // stays sealed — later deltas must not append into the bubble
- // the late event just updated.
- streamId: reconciledId ? state.streamId : streamId,
+ streamId,
sawAssistantPayload: true,
awaitingResponse: false
}
@@ -499,13 +507,15 @@ export function useMessageStream({
() => upsertToolPart([], payload, phase, occurredAt),
{
pending: m => phase !== 'complete' || (m.pending ?? false),
- // A completion belongs to the bubble that owns the call, not to
+ // A tool event belongs to the bubble that owns the call, not to
// whatever is streaming now. Long tools (browser scrapes run
- // minutes) outlive the interim commentary boundary that seals
- // their bubble: without this lookup the completion seeds a new
- // bubble with a duplicate row while the sealed one keeps reading
- // "Result unavailable" forever (#113035).
- eventTarget: state => (phase === 'complete' ? toolCallOwnerMessageId(state.messages, payload) : null)
+ // minutes) outlive the boundary that seals their bubble (interim
+ // commentary, a message typed mid-turn, turn settle): without this
+ // lookup a completion seeds a new bubble with a duplicate row while
+ // the sealed one keeps reading "Result unavailable", and a running
+ // event for the same id seeds a second live row with its own timer
+ // under the user's message (#113035). Both phases route by id.
+ eventTarget: state => toolCallOwnerMessageId(state.messages, payload)
},
occurredAt
)
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
index fcada785e3b..d8c798ae754 100644
--- 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
@@ -47,46 +47,6 @@ describe('late tool completions across interim boundaries', () => {
expect(toolParts()).toHaveLength(1)
})
- it('keeps the sealed bubble sealed after reconciling', () => {
- event('message.start', 200)
- event('tool.start', 201, { args: {}, name: 'browser', tool_id: 'call-late-2' })
- event('message.interim', 202, { text: 'Working on it.' })
- event('tool.complete', 203, { name: 'browser', result: 'ok', tool_id: 'call-late-2' })
-
- // The reconciliation must not reopen the stream onto the sealed bubble:
- // a later turn still seeds the next bubble instead of appending into it.
- event('message.delta', 204, { text: 'Follow-up text.' })
- event('message.complete', 205, { text: 'Follow-up text.' })
-
- const assistants = (stream.state(SID).messages ?? []).filter(message => message.role === 'assistant')
-
- expect(assistants).toHaveLength(2)
- expect(assistants[0]).toMatchObject({ completedAt: 202, interim: true })
- expect(
- assistants[0].parts.some(part => part.type === 'tool-call' && 'result' in part && part.result === 'ok')
- ).toBe(true)
- expect(assistants[1]).toMatchObject({ completedAt: 205 })
- expect(assistants[1].parts.map(part => part.type)).toEqual(['text'])
- })
-
- it('reconciles into the owning bubble even while a new bubble streams', () => {
- event('message.start', 300)
- event('tool.start', 301, { args: {}, name: 'browser', tool_id: 'call-late-3' })
- event('message.interim', 302, { text: 'Still scraping.' })
- // The turn continues after the boundary: a new bubble opens and streams.
- event('message.delta', 303, { text: 'Meanwhile.' })
- // The long tool finishes — its completion must land in the FIRST bubble.
- event('tool.complete', 304, { name: 'browser', result: 'done', tool_id: 'call-late-3' })
-
- const assistants = (stream.state(SID).messages ?? []).filter(message => message.role === 'assistant')
-
- expect(assistants).toHaveLength(2)
- expect(assistants[0].parts.map(part => part.type)).toEqual(['tool-call', 'text'])
- expect(assistants[0].parts[0]).toMatchObject({ result: 'done', toolCallId: 'call-late-3', type: 'tool-call' })
- // The streaming bubble keeps only its text — no duplicate tool row.
- expect(assistants[1].parts.map(part => part.type)).toEqual(['text'])
- })
-
it('seeds a fresh bubble for a completion with no owner', () => {
event('message.start', 400)
event('message.interim', 401, { text: 'Sealed.' })
@@ -101,18 +61,4 @@ describe('late tool completions across interim boundaries', () => {
expect.objectContaining({ result: 'match', toolCallId: 'call-fresh-1', type: 'tool-call' })
])
})
-
- it('does not move a completion away from the live stream when it owns the call', () => {
- event('message.start', 500)
- event('tool.start', 501, { args: {}, name: 'terminal', tool_id: 'call-live-1' })
- event('tool.complete', 502, { name: 'terminal', result: 'ok', tool_id: 'call-live-1' })
- event('message.complete', 503, { text: 'Done.' })
-
- const assistants = (stream.state(SID).messages ?? []).filter(message => message.role === 'assistant')
-
- // Unchanged single-bubble behaviour for the plain in-stream case.
- expect(assistants).toHaveLength(1)
- expect(assistants[0].parts.map(part => part.type)).toEqual(['tool-call', 'text'])
- expect(assistants[0].parts[0]).toMatchObject({ result: 'ok' })
- })
})
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
new file mode 100644
index 00000000000..ad2830c23b5
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-result.test.tsx
@@ -0,0 +1,121 @@
+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 c547c1b4683..d65f549428e 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -357,6 +357,13 @@ export function upsertToolPart(
if (index === -1) {
next.push(base)
+ } else if (phase === 'running' && prev?.type === 'tool-call' && prev.completedAt !== undefined && prev.result === undefined) {
+ // A settle-time seal (interim boundary, mid-turn user message, lost
+ // completion) closed this call without a result. A running event for the
+ // same id says the tool is still executing, so the row goes live again
+ // instead of reading "Result unavailable" over a ticking sibling.
+ const { completedAt: _completedAt, ...unsealed } = next[index] as Extract<ChatMessagePart, { type: 'tool-call' }>
+ next[index] = { ...unsealed, ...base }
} else {
next[index] = { ...next[index], ...base }
}