Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(chat): re-link orphan tool messages at the raw bucket write boundary (#15438)

Arvin Xua3a08c2395a6
diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.ts
index 2aa3bbd2fb8..753e12f9307 100644
--- a/src/store/chat/slices/message/actions/internals.ts
+++ b/src/store/chat/slices/message/actions/internals.ts
@@ -11,6 +11,7 @@ import { displayMessageSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
import { type MessageDispatch } from '../reducer';
import { messagesReducer } from '../reducer';
+import { reconcileAssistantToolLinks } from '../utils/reconcileTools';
const log = debug('lobe-store:message-internals');
@@ -52,12 +53,19 @@ export class MessageInternalsActionImpl {
const rawMessages = this.#get().dbMessagesMap[messagesKey] || [];
const updatedRawMessages = messagesReducer(rawMessages, payload);
- const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: updatedRawMessages };
+ // Re-link any tool row whose parent assistant lost its tools[] entry — an
+ // optimistic updateMessage{tools} on the wrong/old assistant during a step
+ // boundary can drop the link while the tool row survives, orphaning the
+ // tool bubble. Reconcile on the RAW array so the SoT stays consistent (see
+ // reconcileAssistantToolLinks).
+ const reconciled = reconcileAssistantToolLinks(updatedRawMessages);
+
+ const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: reconciled };
if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;
// parse to get display messages
- const { flatList } = parse(updatedRawMessages);
+ const { flatList } = parse(reconciled);
const nextDisplayMap = { ...this.#get().messagesMap, [messagesKey]: flatList };
this.#set({ dbMessagesMap: nextDbMap, messagesMap: nextDisplayMap }, false, {
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 7ec47d86e04..bdb7be96cae 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -10,6 +10,7 @@ import { type StoreSetter } from '@/store/types';
import { type MessageMapKeyInput } from '../../../utils/messageMapKey';
import { messageMapKey } from '../../../utils/messageMapKey';
+import { reconcileAssistantToolLinks } from '../utils/reconcileTools';
const SWR_USE_FETCH_MESSAGES = 'SWR_USE_FETCH_MESSAGES';
@@ -84,13 +85,20 @@ export class MessageQueryActionImpl {
const messagesKey = messageMapKey(ctx);
+ // Re-link any tool row whose parent assistant lost its tools[] entry before
+ // it lands in the raw bucket — a stale / out-of-order snapshot can drop the
+ // link while the tool row survives, which would orphan the tool bubble (see
+ // reconcileAssistantToolLinks). Keeps dbMessagesMap (SoT) consistent for
+ // optimistic updates, not just the parsed display.
+ const reconciled = reconcileAssistantToolLinks(messages);
+
// Get raw messages from dbMessagesMap and apply reducer
- const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: messages };
+ const nextDbMap = { ...this.#get().dbMessagesMap, [messagesKey]: reconciled };
if (isEqual(nextDbMap, this.#get().dbMessagesMap)) return;
// Parse messages using conversation-flow
- const { flatList } = parse(messages);
+ const { flatList } = parse(reconciled);
this.#set(
{
diff --git a/src/store/chat/slices/message/replaceMessages.orphanTool.regression.test.ts b/src/store/chat/slices/message/replaceMessages.orphanTool.regression.test.ts
new file mode 100644
index 00000000000..26f0e307252
--- /dev/null
+++ b/src/store/chat/slices/message/replaceMessages.orphanTool.regression.test.ts
@@ -0,0 +1,202 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import { useChatStore } from '../../store';
+
+// `replaceMessages` is pure store + conversation-flow `parse` (no service
+// calls), but importing the chat store pulls the whole slice graph, so mirror
+// the minimal service / swr / zustand stubs the sibling action tests use.
+vi.mock('@/libs/swr', async () => {
+ const actual = await vi.importActual('@/libs/swr');
+ return { ...actual, mutate: vi.fn() };
+});
+vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => Promise.resolve(new Response('mock'))),
+);
+vi.mock('zustand/traditional');
+vi.mock('@/services/message', () => ({
+ messageService: {
+ createMessage: vi.fn(),
+ getMessages: vi.fn(),
+ updateMessage: vi.fn(),
+ updateMessageError: vi.fn(),
+ },
+}));
+vi.mock('@/services/topic', () => ({ topicService: {} }));
+
+const CTX = { agentId: 'agent-1', topicId: 'topic-1' };
+const KEY = messageMapKey(CTX);
+
+const tool = (id: string, name: string) => ({
+ apiName: name,
+ arguments: '{}',
+ id,
+ identifier: name,
+ type: 'default' as const,
+});
+
+/**
+ * Real CC streaming chain from trace 20260603-205720-8ecfc841…:
+ * user → assistant#1 (2× Bash) → assistant#2 (Grep) → assistant#3 (Bash)
+ *
+ * `step2Tools` lets a later (out-of-order / SWR) snapshot drop assistant#2's
+ * `tools[]` while the Grep `role:'tool'` row + its parentId chain stay intact —
+ * the transient in-memory state that orphans the Grep bubble during streaming.
+ */
+const buildChain = (step2Tools: 'grep' | 'empty'): UIChatMessage[] =>
+ [
+ {
+ content: 'check error filtering',
+ createdAt: 1000,
+ id: 'msg-user',
+ role: 'user',
+ updatedAt: 1000,
+ },
+
+ // step 1
+ {
+ content: 'InsufficientBudgetForModel 是用户侧错误…',
+ createdAt: 2000,
+ id: 'asst-1',
+ parentId: 'msg-user',
+ role: 'assistant',
+ tools: [tool('bash-1', 'Bash'), tool('bash-2', 'Bash')],
+ updatedAt: 2000,
+ },
+ {
+ content: 'logic…',
+ createdAt: 2100,
+ id: 'bash-1',
+ parentId: 'asst-1',
+ role: 'tool',
+ tool_call_id: 'bash-1',
+ updatedAt: 2100,
+ },
+ {
+ content: 'refs…',
+ createdAt: 2200,
+ id: 'bash-2',
+ parentId: 'asst-1',
+ role: 'tool',
+ tool_call_id: 'bash-2',
+ updatedAt: 2200,
+ },
+
+ // step 2 — the fast Grep tool
+ {
+ content: 'Let me find where includeUserErrors is applied…',
+ createdAt: 3000,
+ id: 'asst-2',
+ parentId: 'bash-2',
+ role: 'assistant',
+ tools: step2Tools === 'grep' ? [tool('grep-1', 'Grep')] : [],
+ updatedAt: 3000,
+ },
+ {
+ content: 'attribution IS DISTINCT FROM user…',
+ createdAt: 3100,
+ id: 'grep-1',
+ parentId: 'asst-2',
+ role: 'tool',
+ tool_call_id: 'grep-1',
+ updatedAt: 3100,
+ },
+
+ // step 3 — chained off the Grep tool message
+ {
+ content: 'Inspect backfill classification rules',
+ createdAt: 4000,
+ id: 'asst-3',
+ parentId: 'grep-1',
+ role: 'assistant',
+ tools: [tool('bash-3', 'Bash')],
+ updatedAt: 4000,
+ },
+ {
+ content: 'rules…',
+ createdAt: 4100,
+ id: 'bash-3',
+ parentId: 'asst-3',
+ role: 'tool',
+ tool_call_id: 'bash-3',
+ updatedAt: 4100,
+ },
+ ] as UIChatMessage[];
+
+const topLevelToolIds = (result: { current: ReturnType<typeof useChatStore.getState> }) =>
+ (result.current.messagesMap[KEY] ?? []).filter((m) => m.role === 'tool').map((m) => m.id);
+
+describe('replaceMessages — hetero-agent streaming orphan tool regression', () => {
+ beforeEach(() => {
+ useChatStore.setState({ activeAgentId: 'agent-1', activeTopicId: 'topic-1' }, false);
+ });
+
+ it('groups the full CC chain when tools[] is intact (control)', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.replaceMessages(buildChain('grep'), { context: CTX });
+ });
+
+ // Whole run collapses into one assistantGroup, no stray tool bubble.
+ expect(topLevelToolIds(result)).toEqual([]);
+ expect((result.current.messagesMap[KEY] ?? []).map((m) => m.role)).toEqual([
+ 'user',
+ 'assistantGroup',
+ ]);
+ });
+
+ it('does not orphan the Grep tool when a stale snapshot drops assistant#2 tools[]', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ // 1. Consistent live state — Grep grouped under assistant#2.
+ act(() => {
+ result.current.replaceMessages(buildChain('grep'), { context: CTX });
+ });
+ expect(topLevelToolIds(result)).toEqual([]);
+
+ // 2. A later out-of-order / SWR snapshot lands assistant#2 with an empty
+ // tools[] (the "7→6 次技能调用" tools[] regression, taken to its
+ // extreme). The Grep row + parentId survive. replaceMessages must not
+ // let that regression demote Grep to a top-level orphan bubble — the
+ // exact thing the UI flags as `inspector.orphanedToolCall`.
+ act(() => {
+ result.current.replaceMessages(buildChain('empty'), { context: CTX });
+ });
+
+ expect(topLevelToolIds(result)).toEqual([]);
+ });
+
+ // Guard against over-reaching: a genuine deletion (the Grep tool ROW is gone
+ // from the snapshot, along with everything chained after it) must NOT be
+ // resurrected by the reconciliation.
+ it('does not resurrect a genuinely deleted tool (row absent from snapshot)', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.replaceMessages(buildChain('grep'), { context: CTX });
+ });
+
+ // User trimmed the conversation back to step 1 — grep row + step-3 chain
+ // are gone, and assistant#2 no longer references the (deleted) grep.
+ const trimmed = buildChain('empty').filter(
+ (m) => !['asst-3', 'bash-3', 'grep-1'].includes(m.id),
+ );
+ act(() => {
+ result.current.replaceMessages(trimmed, { context: CTX });
+ });
+
+ const ids = (result.current.messagesMap[KEY] ?? []).flatMap((m) =>
+ m.role === 'tool' ? [m.id] : [],
+ );
+ // No phantom grep anywhere — neither as an orphan nor re-linked.
+ expect(ids).toEqual([]);
+ const raw = result.current.dbMessagesMap[KEY] ?? [];
+ expect(raw.some((m) => m.id === 'grep-1')).toBe(false);
+ expect(raw.find((m) => m.id === 'asst-2')?.tools ?? []).toEqual([]);
+ });
+});
diff --git a/src/store/chat/slices/message/utils/reconcileTools.ts b/src/store/chat/slices/message/utils/reconcileTools.ts
new file mode 100644
index 00000000000..55cb116aa23
--- /dev/null
+++ b/src/store/chat/slices/message/utils/reconcileTools.ts
@@ -0,0 +1,75 @@
+import type { ChatToolPayload, UIChatMessage } from '@lobechat/types';
+
+/**
+ * Keep a raw message bucket internally consistent on the tool↔assistant link.
+ *
+ * Invariant: every present `role:'tool'` message whose `parentId` resolves to an
+ * assistant in the SAME bucket must be referenced by that assistant's `tools[]`
+ * (matching `tool_call_id`). conversation-flow groups a tool into its assistant
+ * SOLELY via `assistant.tools[].id` (parentId only finds the next assistant), so
+ * the moment an assistant's `tools[]` loses an entry whose tool row is still
+ * present, that tool falls through to a top-level `role:'tool'` bubble — the
+ * orphan the UI flags as `inspector.orphanedToolCall`.
+ *
+ * This is reachable during hetero-agent (Claude Code) streaming: a fast tool's
+ * `tool_result` + the next step's `message_start` cluster in a tiny window, so
+ * `replaceMessages` (stale / out-of-order DB snapshot) or an optimistic
+ * `internal_dispatchMessage updateMessage{tools}` can momentarily drop an
+ * assistant's `tools[]` while the tool row + parentId survive (the extreme of
+ * the "7→6 次技能调用" tools[] regression).
+ *
+ * Fixing this at the RAW bucket write boundary — not only inside `parse` — keeps
+ * `dbMessagesMap` (the Source of Truth that optimistic updates read & mutate)
+ * consistent, so every downstream consumer (display parse, next optimistic
+ * dispatch, model context) sees the tool bound to its owner.
+ *
+ * Safe by construction:
+ * - Only re-links tool rows that ARE present, so a genuine deletion (row gone)
+ * is never resurrected.
+ * - Only adds the missing entry to the assistant named by `parentId`; never
+ * removes or reorders existing entries, so legitimate additions are untouched.
+ * - Returns the SAME array reference when already consistent, so the callers'
+ * `isEqual` early-return and referential-equality checks still hold.
+ */
+export const reconcileAssistantToolLinks = (messages: UIChatMessage[]): UIChatMessage[] => {
+ const byId = new Map<string, UIChatMessage>();
+ for (const message of messages) byId.set(message.id, message);
+
+ // assistant id -> tool entries present-as-rows but missing from its tools[]
+ let missingByAssistant: Map<string, ChatToolPayload[]> | undefined;
+
+ for (const message of messages) {
+ if (message.role !== 'tool' || !message.tool_call_id || !message.parentId) continue;
+
+ const parent = byId.get(message.parentId);
+ if (!parent || parent.role !== 'assistant') continue;
+
+ const alreadyLinked = (parent.tools ?? []).some((tool) => tool.id === message.tool_call_id);
+ if (alreadyLinked) continue;
+
+ // Reconstruct the assistant's tools[] entry from the tool message's own
+ // plugin payload; `result_msg_id` points at the row itself so the UI can
+ // hydrate the result.
+ const entry = {
+ apiName: message.plugin?.apiName ?? '',
+ arguments: message.plugin?.arguments ?? '{}',
+ id: message.tool_call_id,
+ identifier: message.plugin?.identifier ?? '',
+ result_msg_id: message.id,
+ type: message.plugin?.type ?? 'default',
+ } as ChatToolPayload;
+
+ missingByAssistant ??= new Map();
+ const list = missingByAssistant.get(message.parentId);
+ if (list) list.push(entry);
+ else missingByAssistant.set(message.parentId, [entry]);
+ }
+
+ if (!missingByAssistant) return messages;
+
+ return messages.map((message) => {
+ const missing = missingByAssistant!.get(message.id);
+ if (!missing) return message;
+ return { ...message, tools: [...(message.tools ?? []), ...missing] };
+ });
+};