The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): reconcile a late tool completion with the bubble that owns it
liuhao1024fef05a894007
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 1d0dcf07308..d82bbfc60af 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@@ -15,6 +15,7 @@ import {reasoningPart,renderMediaTags,sealOpenToolParts,+ toolCallOwnerMessageId,upsertToolPart} from '@/lib/chat-messages'import type { ErrorSurface } from '@/lib/error-surface'@@ -93,6 +94,11 @@ export function useMessageStream({seed: () => ChatMessagePart[],opts: {pending?: (message: ChatMessage) => boolean+ // Resolve the message an event should mutate by payload identity+ // rather than by the current stream position. A late `tool.complete`+ // that crosses an interim/settle boundary must attach to the bubble+ // that still owns the call, wherever that bubble now sits.+ eventTarget?: (state: ClientSessionState) => string | null} = {},occurredAt = Date.now() / 1000) => {@@ -106,7 +112,8 @@ export function useMessageStream({return state}- const streamId = state.streamId ?? nextStreamMessageId('assistant-stream')+ const reconciledId = opts.eventTarget?.(state) ?? null+ const streamId = reconciledId ?? state.streamId ?? nextStreamMessageId('assistant-stream')const groupId = state.pendingBranchGroup ?? undefinedconst prev = state.messageslet nextMessages: ChatMessage[]@@ -138,7 +145,11 @@ export function useMessageStream({return {...state,messages: nextMessages,- streamId,+ // 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,sawAssistantPayload: true,awaitingResponse: false}@@ -486,7 +497,16 @@ export function useMessageStream({sessionId,parts => dedupeGeneratedImageEchoesInParts(upsertToolPart(parts, payload, phase, occurredAt)),() => upsertToolPart([], payload, phase, occurredAt),- { pending: m => phase !== 'complete' || (m.pending ?? false) },+ {+ pending: m => phase !== 'complete' || (m.pending ?? false),+ // A completion 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)+ },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.tsxnew file mode 100644index 00000000000..fcada785e3b--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/late-tool-complete.test.tsx@@ -0,0 +1,118 @@+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('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.' })+ // 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' })+ ])+ })++ 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/lib/chat-messages/index.ts b/apps/desktop/src/lib/chat-messages/index.tsindex 24dbe4c3690..7777224c46f 100644--- a/apps/desktop/src/lib/chat-messages/index.ts+++ b/apps/desktop/src/lib/chat-messages/index.ts@@ -20,6 +20,7 @@ export {sealOpenToolParts,settlePendingClarifyToolCall,stripPendingClarifyProjectionForCache,+ toolCallOwnerMessageId,upsertToolPart,withUniqueToolCallIdsWithinMessage} from './tool-parts'diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.tsindex f0fc7b9fe7a..c547c1b4683 100644--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts@@ -374,6 +374,43 @@ export interface SettledClarifyProjection {streamId: string | null}+/**+ * Find the message that owns a tool call, by its stable call id, anywhere in+ * the transcript — not just in the currently-streaming bubble.+ *+ * Interim commentary and turn settles seal the streaming bubble and drop the+ * stream id while a long-running tool is still executing. When the completion+ * finally arrives it must reconcile with the part that already exists (and,+ * 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.+ */+export function toolCallOwnerMessageId(+ messages: ChatMessage[],+ payload: GatewayEventPayload | undefined+): string | null {+ const stableId = toolId(payload)++ if (!stableId) {+ return null+ }++ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) {+ const message = messages[messageIndex]++ for (const part of message.parts) {+ if (part.type === 'tool-call' && part.toolCallId === stableId) {+ return message.id+ }+ }+ }++ return null+}+interface PendingClarifyLocation {messageIndex: numberpartIndex: number