Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📎 fix: Resolve useChat Tool Parts Against Live Attachments (#16960)

Marco Beretta9902a215eb32
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
index cf293107cc..856d8e92ef 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
@@ -72,6 +72,7 @@ function Harness({
messagesKey: 'new',
latestMessageId: undefined,
latestMessageDepth: undefined,
+ useLiveAttachments: () => ({}),
feedbackEnabled: false,
setMessages: () => undefined,
ask: onAsk,
diff --git a/client/src/hooks/Chat/__tests__/facade.spec.tsx b/client/src/hooks/Chat/__tests__/facade.spec.tsx
index 6965cdb82d..18539eee2f 100644
--- a/client/src/hooks/Chat/__tests__/facade.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/facade.spec.tsx
@@ -30,6 +30,9 @@ const response = (overrides: Partial<TMessage> = {}): TMessage => ({
...overrides,
});
+/** No attachment has arrived outside the message cache; one map, so every read is the same. */
+const noLiveAttachments = {};
+
const createContract = (overrides: Partial<ChatContract> = {}): ChatContract => {
const noop = jest.fn();
return {
@@ -47,6 +50,7 @@ const createContract = (overrides: Partial<ChatContract> = {}): ChatContract =>
setSiblingIdx: noop,
latestMessageId: 'user-1',
latestMessageDepth: 0,
+ useLiveAttachments: () => noLiveAttachments,
ask: jest.fn(),
regenerate: jest.fn(),
isSubmitting: false,
@@ -437,6 +441,44 @@ describe('useChat', () => {
expect(result.current.messages[1].parts[1]).toMatchObject({ state: 'input-available' });
});
+ it('resolves a tool part against an attachment that reached only the live map', () => {
+ const memoryCall = response({
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'mem-1',
+ type: 'tool_call',
+ name: 'set_memory',
+ args: '{}',
+ output: 'Memory set for key "k"',
+ progress: 1,
+ },
+ },
+ ],
+ });
+ const memoryError = {
+ conversationId: 'convo-1',
+ messageId: 'response-1',
+ toolCallId: 'mem-1',
+ type: 'memory',
+ memory: { type: 'error', key: 'k', value: 'v' },
+ } as unknown as NonNullable<TMessage['attachments']>[number];
+ const running = turn([userMessage, memoryCall], true);
+ const { result, update } = renderChat(running);
+ const userView = result.current.messages[0];
+ expect(result.current.messages[1].parts[0]).toMatchObject({ state: 'output-available' });
+
+ const live = { 'response-1': [memoryError] };
+ update({ ...running, useLiveAttachments: () => live });
+
+ expect(result.current.messages[1].parts[0]).toMatchObject({
+ type: 'tool-set_memory',
+ state: 'output-error',
+ });
+ expect(result.current.messages[0]).toBe(userView);
+ });
+
it('joins an inserted message to the conversation under the one before it', () => {
const contract = createContract();
const { result } = renderChat(contract);
diff --git a/client/src/hooks/Chat/__tests__/provider.spec.tsx b/client/src/hooks/Chat/__tests__/provider.spec.tsx
index 0687205d6a..3a3c09ef24 100644
--- a/client/src/hooks/Chat/__tests__/provider.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/provider.spec.tsx
@@ -30,6 +30,7 @@ const contract: ChatContract = {
setSiblingIdx: noop,
latestMessageId: undefined,
latestMessageDepth: undefined,
+ useLiveAttachments: () => ({}),
ask: jest.fn(),
regenerate: jest.fn(),
isSubmitting: false,
diff --git a/client/src/hooks/Chat/__tests__/transport.spec.tsx b/client/src/hooks/Chat/__tests__/transport.spec.tsx
index 8216d1cab5..431c797529 100644
--- a/client/src/hooks/Chat/__tests__/transport.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/transport.spec.tsx
@@ -4,7 +4,7 @@ import { useAtomValue, getDefaultStore } from 'jotai';
import { act, renderHook, waitFor } from '@testing-library/react';
import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { QueryKeys, ContentTypes, EModelEndpoint, request } from 'librechat-data-provider';
+import { Tools, QueryKeys, ContentTypes, EModelEndpoint, request } from 'librechat-data-provider';
import type {
TEnqueueAgentQueuedTurnRequest,
TSubmission,
@@ -664,6 +664,64 @@ describe('chat transport boundary', () => {
store.set(resumeRequestsAtom, new Set<string>());
});
+ it('resolves a tool part against an attachment streamed mid-run', async () => {
+ const fake = createFakeTransport();
+ const { result } = renderPane(fake.transport);
+ await waitFor(() => expect(statusReads()).toBe(1));
+ /** The run has a memory call whose output reads as a success; its error artifact has not
+ * arrived, and the message cache keeps no attachments until the final. */
+ const running = runningStatus();
+ running.resumeState = {
+ ...running.resumeState,
+ aggregatedContent: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'mem-1',
+ type: 'tool_call',
+ name: 'set_memory',
+ args: '{"key":"k","value":"v"}',
+ output: 'Memory set for key "k"',
+ progress: 1,
+ },
+ },
+ ],
+ } as StreamStatusResponse['resumeState'];
+ status = running;
+ await act(async () => {
+ await result.current.resumeStream();
+ });
+ await waitFor(() => expect(fake.streams).toHaveLength(1));
+ act(() =>
+ fake.streams[0].options.onEvent({
+ type: 'sync',
+ data: { sync: true, resumeState: running.resumeState, pendingEvents: [] },
+ }),
+ );
+
+ const toolPart = () =>
+ result.current.messages.find((message) => message.id === 'resp-1')?.parts[0];
+ await waitFor(() => expect(toolPart()).toMatchObject({ state: 'output-available' }));
+
+ act(() =>
+ fake.streams[0].options.onEvent({
+ type: 'attachment',
+ data: {
+ messageId: 'resp-1',
+ conversationId: 'convo-1',
+ toolCallId: 'mem-1',
+ type: Tools.memory,
+ [Tools.memory]: { type: 'error', key: 'k', value: 'v' },
+ },
+ }),
+ );
+
+ await waitFor(() =>
+ expect(toolPart()).toMatchObject({ type: 'tool-set_memory', state: 'output-error' }),
+ );
+ expect(result.current.status).not.toBe('ready');
+ });
+
it('reports a reattached stream that fails as an error', async () => {
const fake = createFakeTransport();
const { result } = renderPane(fake.transport);
diff --git a/client/src/hooks/Chat/contract.ts b/client/src/hooks/Chat/contract.ts
index 8b64ceac82..5fa7ede1d7 100644
--- a/client/src/hooks/Chat/contract.ts
+++ b/client/src/hooks/Chat/contract.ts
@@ -4,6 +4,7 @@ import type {
TPreset,
TMessage,
TModelSpec,
+ TAttachment,
RetentionMode,
TConversation,
ChatTransport,
@@ -90,6 +91,13 @@ export type ChatMessagesContract = {
latestMessageId: string | undefined;
/** Depth of the tail of the active branch, if loaded. */
latestMessageDepth: number | undefined;
+ /**
+ * Attachments delivered by message id while the message cache holds none of them yet: tool
+ * artifacts streamed mid-run and previews resolved after it. A hook, so only a caller that
+ * merges them re-renders when one arrives; stable across renders. AI SDK: the data parts a
+ * stream writes onto its message.
+ */
+ useLiveAttachments: () => Record<string, TAttachment[] | undefined>;
};
/** Sending, regenerating and continuing turns. AI SDK: `sendMessage` / `regenerate` / `status`. */
diff --git a/client/src/hooks/Chat/facade.ts b/client/src/hooks/Chat/facade.ts
index 328a7cb360..67560b2ec2 100644
--- a/client/src/hooks/Chat/facade.ts
+++ b/client/src/hooks/Chat/facade.ts
@@ -22,6 +22,7 @@ import type { ChatContract } from './contract';
import { isMemoryFailureOutput } from '~/components/Chat/Messages/Content/Parts/MemoryCall';
import { getToolMeta } from '~/components/Chat/Messages/Content/outcome';
import { useChatContext } from '~/Providers/ChatContext';
+import { mergeAttachments } from '~/utils/attachments';
import { isEmptyContentPart } from '~/utils/messages';
import { resumeRequestsAtom } from './resume';
import { mapAttachments } from '~/utils/map';
@@ -86,6 +87,7 @@ export type UseChatHelpers = {
type ToolContext = {
content: TMessage['content'];
attachments: TMessage['attachments'];
+ live: TAttachment[] | undefined;
byToolCall: Record<string, TAttachment[] | undefined>;
/** Step ids each provider tool-call id already owns, for calls that have no step yet. */
stepIdsById: Map<string, Set<string>>;
@@ -94,12 +96,18 @@ type ToolContext = {
const toolContexts = new WeakMap<TMessage, ToolContext>();
/**
- * Built once per message snapshot. The stream reuses a response object across frames and
- * replaces its `content` and `attachments` arrays, so both are checked, not only the object.
+ * Built once per message snapshot and live attachment list. The stream reuses a response object
+ * across frames and replaces its `content` and `attachments` arrays, so both are checked, not only
+ * the object. A tool's attachments reach the live list before the message cache holds them.
*/
-const getToolContext = (message: TMessage): ToolContext => {
+const getToolContext = (message: TMessage, live: TAttachment[] | undefined): ToolContext => {
const cached = toolContexts.get(message);
- if (cached && cached.content === message.content && cached.attachments === message.attachments) {
+ if (
+ cached &&
+ cached.content === message.content &&
+ cached.attachments === message.attachments &&
+ cached.live === live
+ ) {
return cached;
}
const stepIdsById = new Map<string, Set<string>>();
@@ -118,7 +126,8 @@ const getToolContext = (message: TMessage): ToolContext => {
const context: ToolContext = {
content: message.content,
attachments: message.attachments,
- byToolCall: mapAttachments(message.attachments ?? []),
+ live,
+ byToolCall: mapAttachments(mergeAttachments(message.attachments, live)),
stepIdsById,
};
toolContexts.set(message, context);
@@ -153,11 +162,10 @@ const getFailureProse = (toolCall: StoredToolCall, background: boolean) => {
* A call with no step yet is scoped away from attachments its repeated provider id's other
* steps own, as `summarizeSpan` does.
*/
-const resolveToolFailure: NonNullable<UIMappingOptions['resolveToolFailure']> = (
- toolCall,
- message,
-) => {
- const context = message ? getToolContext(message) : undefined;
+const resolveToolFailure = (
+ toolCall: StoredToolCall,
+ context: ToolContext | undefined,
+): ReturnType<NonNullable<UIMappingOptions['resolveToolFailure']>> => {
const { id, stepId } = toolCall as { id?: string; stepId?: string };
const siblingStepIds = stepId == null && id ? context?.stepIdsById.get(id) : undefined;
const meta = getToolMeta(
@@ -174,7 +182,11 @@ const resolveToolFailure: NonNullable<UIMappingOptions['resolveToolFailure']> =
return getFailureProse(toolCall, meta.background != null) ?? 'failed';
};
-const mappingOptions: UIMappingOptions = { resolveToolFailure };
+/** Mapping options that resolve a message's tool outcomes against its live attachments too. */
+const getMappingOptions = (live: TAttachment[] | undefined): UIMappingOptions => ({
+ resolveToolFailure: (toolCall, message) =>
+ resolveToolFailure(toolCall, message ? getToolContext(message, live) : undefined),
+});
/**
* Every message field a view is built from, identity and metadata included: a stream frame or a
@@ -197,28 +209,33 @@ const viewSourceKeys = [
'createdAt',
] as const;
-type CachedView = { view: UIMessage; source: Pick<TMessage, (typeof viewSourceKeys)[number]> };
+type CachedView = {
+ view: UIMessage;
+ source: Pick<TMessage, (typeof viewSourceKeys)[number]>;
+ live: TAttachment[] | undefined;
+};
const views = new WeakMap<TMessage, CachedView>();
-const isSameSource = (cached: CachedView, message: TMessage) =>
- viewSourceKeys.every((key) => cached.source[key] === message[key]);
+const isSameSource = (cached: CachedView, message: TMessage, live: TAttachment[] | undefined) =>
+ cached.live === live && viewSourceKeys.every((key) => cached.source[key] === message[key]);
/**
- * Cached per message and per snapshot of the fields a view reads: a stream frame that replaces a
- * response's content remaps that response, while untouched messages keep their views.
+ * Cached per message, per snapshot of the fields a view reads and per live attachment list: a
+ * stream frame that replaces a response's content, or an attachment that arrives for it, remaps
+ * that response, while untouched messages keep their views.
*/
-const toView = (message: TMessage) => {
+const toView = (message: TMessage, live: TAttachment[] | undefined) => {
const cached = views.get(message);
- if (cached && isSameSource(cached, message)) {
+ if (cached && isSameSource(cached, message, live)) {
return cached.view;
}
- const view = toUIMessage(message, mappingOptions);
+ const view = toUIMessage(message, getMappingOptions(live));
const source = {} as CachedView['source'];
for (const key of viewSourceKeys) {
Object.assign(source, { [key]: message[key] });
}
- views.set(message, { view, source });
+ views.set(message, { view, source, live });
return view;
};
@@ -428,11 +445,13 @@ export function useChat(): UseChatHelpers {
messagesKey,
setMessages: setStoredMessages,
latestMessageId,
+ useLiveAttachments,
isSubmitting,
ask,
regenerate: regenerateTarget,
stopGenerating,
} = useChatContext();
+ const liveAttachments = useLiveAttachments();
const { queryClient, queryHash, subscribe } = useMessagesSubscription(messagesKey);
const snapshot = useRef<{ writes: number; stored?: TMessage[] }>();
@@ -458,13 +477,13 @@ export function useChat(): UseChatHelpers {
const list: UIMessage[] = [];
let latestMessage: TMessage | undefined;
for (const message of cache.stored ?? []) {
- list.push(toView(message));
+ list.push(toView(message, liveAttachments[message.messageId]));
if (message.messageId === latestMessageId) {
latestMessage = message;
}
}
return { messages: list, latest: latestMessage };
- }, [cache, latestMessageId]);
+ }, [cache, latestMessageId, liveAttachments]);
const chatId = messagesKey || conversation?.conversationId || undefined;
const status = getChatStatus(isSubmitting, latest);
@@ -480,7 +499,10 @@ export function useChat(): UseChatHelpers {
const setMessages = useCallback(
(update: UIMessage[] | ((messages: UIMessage[]) => UIMessage[])) => {
const current = getMessages() ?? [];
- const next = typeof update === 'function' ? update(current.map(toView)) : update;
+ const next =
+ typeof update === 'function'
+ ? update(current.map((message) => toView(message, liveAttachments[message.messageId])))
+ : update;
const byId = new Map(current.map((message) => [message.messageId, message]));
const branch = getActiveBranch(byId, latestMessageId);
const conversationId = chatId === Constants.NEW_CONVO ? null : (chatId ?? null);
@@ -502,7 +524,7 @@ export function useChat(): UseChatHelpers {
});
setStoredMessages(stored);
},
- [chatId, getMessages, latestMessageId, setStoredMessages],
+ [chatId, getMessages, latestMessageId, liveAttachments, setStoredMessages],
);
return {
diff --git a/client/src/hooks/Chat/useChatHelpers.ts b/client/src/hooks/Chat/useChatHelpers.ts
index 4a01a93686..34c3d9ec21 100644
--- a/client/src/hooks/Chat/useChatHelpers.ts
+++ b/client/src/hooks/Chat/useChatHelpers.ts
@@ -18,6 +18,9 @@ import { getMessageCacheIds } from './cache';
import { useAbortCleanup } from './abort';
import store from '~/store';
+/** The live attachments map the stream and preview polling write. */
+const useLiveAttachments = () => useRecoilValue(store.messageAttachmentsMap);
+
// this to be set somewhere else
export default function useChatHelpers(index = 0, paramId?: string): ChatContract {
const clearAllSubmissions = store.useClearSubmissionState();
@@ -401,6 +404,7 @@ export default function useChatHelpers(index = 0, paramId?: string): ChatContrac
setSiblingIdx,
latestMessageId,
latestMessageDepth,
+ useLiveAttachments,
ask,
index,
regenerate,
diff --git a/client/src/hooks/Messages/useAttachments.ts b/client/src/hooks/Messages/useAttachments.ts
index a4605c3222..612453a29a 100644
--- a/client/src/hooks/Messages/useAttachments.ts
+++ b/client/src/hooks/Messages/useAttachments.ts
@@ -1,69 +1,10 @@
import { useMemo } from 'react';
import { useRecoilValue } from 'recoil';
-import type { TAttachment, TFile } from 'librechat-data-provider';
+import type { TAttachment } from 'librechat-data-provider';
import { useSearchResultsByTurn } from './useSearchResultsByTurn';
-import { attachmentIdentity } from '~/utils/media';
+import { mergeAttachments } from '~/utils/attachments';
import store from '~/store';
-function fileKeyOf(attachment: TAttachment): string | undefined {
- const { file_id, filepath } = attachment as Partial<TFile>;
- return file_id ?? filepath;
-}
-
-function toolCallIdOf(attachment: TAttachment): string | undefined {
- return (attachment as { toolCallId?: string }).toolCallId;
-}
-
-function agentIdOf(attachment: TAttachment): string | undefined {
- return (attachment as { agentId?: string }).agentId;
-}
-
-function nonFileBucketKey(attachment: TAttachment): string | undefined {
- if (fileKeyOf(attachment)) {
- return undefined;
- }
- const { type } = attachment as { type?: string };
- const toolCallId = toolCallIdOf(attachment);
- return type != null && toolCallId != null ? `${type}:${toolCallId}` : undefined;
-}
-
-/** Missing ownership is a compatibility wildcard for historical rows; two
- * known unequal owners identify distinct executions. */
-function nonFileOwnersCompatible(left: TAttachment, right: TAttachment): boolean {
- const leftAgentId = agentIdOf(left);
- const rightAgentId = agentIdOf(right);
- const leftStepId = left.stepId;
- const rightStepId = right.stepId;
- return (
- (leftAgentId == null || rightAgentId == null || leftAgentId === rightAgentId) &&
- (leftStepId == null || rightStepId == null || leftStepId === rightStepId)
- );
-}
-
-/** Stable file identity shared with the message renderer. Non-file DB/live
- * reconciliation additionally compares its producer ownership below. */
-const attachmentKey = attachmentIdentity;
-
-/**
- * Wildcard-tolerant match for the lifecycle overlay: a missing `toolCallId`
- * or `agentId` on either side matches (preview-sync records are bare
- * `{file_id, ...}`); only DISTINCT values keep same-file entries separate.
- */
-function matchesLiveEntry(db: TAttachment, live: TAttachment): boolean {
- const key = fileKeyOf(db);
- if (!key || fileKeyOf(live) !== key) {
- return false;
- }
- const dbToolCallId = toolCallIdOf(db);
- const liveToolCallId = toolCallIdOf(live);
- if (dbToolCallId != null && liveToolCallId != null && dbToolCallId !== liveToolCallId) {
- return false;
- }
- const dbAgentId = agentIdOf(db);
- const liveAgentId = agentIdOf(live);
- return dbAgentId == null || liveAgentId == null || dbAgentId === liveAgentId;
-}
-
export default function useAttachments({
messageId,
attachments,
@@ -72,81 +13,10 @@ export default function useAttachments({
attachments?: TAttachment[];
}) {
const messageAttachmentsMap = useRecoilValue(store.messageAttachmentsMap);
- const messageAttachments = useMemo<TAttachment[]>(() => {
- const live = messageAttachmentsMap[messageId ?? ''];
- if (!attachments || attachments.length === 0) {
- return live ?? [];
- }
- if (!live || live.length === 0) {
- return attachments;
- }
- /* DB-loaded attachments are the source of truth for which
- * attachments belong to this message, but live entries (from the
- * SSE handler / `useAttachmentPreviewSync` polling) carry fresher
- * lifecycle fields — `status`, `text`, `textFormat`,
- * `previewError`. Without this merge, the deferred-preview flow
- * would render "stuck pending" forever on a loaded conversation:
- * the message saved to DB at end-of-run has the immediate-persist
- * snapshot (`status: 'pending'`, `text: null`); the file record
- * itself updates to `'ready'` later, but the message's
- * `attachments` array doesn't get rewritten. Polling fetches the
- * resolved record into `messageAttachmentsMap`; merging here lets
- * `artifactTypeForAttachment` see the resolved text/textFormat
- * and route through the proper PanelArtifact card. */
- const dbKeys = new Set<string>();
- const nonFileBuckets = new Map<string, TAttachment[]>();
- const merged = attachments.map((db) => {
- const key = attachmentKey(db);
- if (!key) {
- return db;
- }
- const fileKey = fileKeyOf(db);
- if (fileKey) {
- /** Partial live file records must still be reachable by their
- * less-specific keys so an overlaid entry isn't re-appended below:
- * bare records key by file key, and agent-less records by
- * fileKey::toolCallId. */
- dbKeys.add(key);
- dbKeys.add(fileKey);
- const toolCallId = toolCallIdOf(db);
- if (toolCallId != null) {
- dbKeys.add(`${fileKey}::${toolCallId}`);
- }
- } else {
- const bucketKey = nonFileBucketKey(db);
- if (bucketKey) {
- const bucket = nonFileBuckets.get(bucketKey) ?? [];
- bucket.push(db);
- nonFileBuckets.set(bucketKey, bucket);
- }
- }
- const liveEntry = live.find((a) => matchesLiveEntry(db, a));
- return liveEntry ? ({ ...db, ...liveEntry } as TAttachment) : db;
- });
- /* Live-only entries with a stable identity are kept, not discarded: a
- * background code task's harvested files arrive via SSE anchored to a
- * message whose DB `attachments` snapshot predates them (the row is
- * patched post-finalize), so treating the DB list as exhaustive would
- * make those files vanish until a full reload. Entries whose key is
- * compatible DB file key or non-file owner are replay duplicates, while
- * entries with no stable identity at all cannot be reconciled — both are
- * dropped. */
- const liveOnly = live.filter((a) => {
- const key = attachmentKey(a);
- if (key == null) {
- return false;
- }
- if (fileKeyOf(a)) {
- return !dbKeys.has(key);
- }
- const bucketKey = nonFileBucketKey(a);
- if (!bucketKey) {
- return false;
- }
- return !nonFileBuckets.get(bucketKey)?.some((db) => nonFileOwnersCompatible(db, a));
- });
- return liveOnly.length > 0 ? [...merged, ...liveOnly] : merged;
- }, [attachments, messageAttachmentsMap, messageId]);
+ const messageAttachments = useMemo<TAttachment[]>(
+ () => mergeAttachments(attachments, messageAttachmentsMap[messageId ?? '']),
+ [attachments, messageAttachmentsMap, messageId],
+ );
const searchResults = useSearchResultsByTurn(messageAttachments);
diff --git a/client/src/utils/attachments.ts b/client/src/utils/attachments.ts
new file mode 100644
index 0000000000..ef2264d28f
--- /dev/null
+++ b/client/src/utils/attachments.ts
@@ -0,0 +1,143 @@
+import type { TAttachment, TFile } from 'librechat-data-provider';
+import { attachmentIdentity } from '~/utils/media';
+
+function fileKeyOf(attachment: TAttachment): string | undefined {
+ const { file_id, filepath } = attachment as Partial<TFile>;
+ return file_id ?? filepath;
+}
+
+function toolCallIdOf(attachment: TAttachment): string | undefined {
+ return (attachment as { toolCallId?: string }).toolCallId;
+}
+
+function agentIdOf(attachment: TAttachment): string | undefined {
+ return (attachment as { agentId?: string }).agentId;
+}
+
+function nonFileBucketKey(attachment: TAttachment): string | undefined {
+ if (fileKeyOf(attachment)) {
+ return undefined;
+ }
+ const { type } = attachment as { type?: string };
+ const toolCallId = toolCallIdOf(attachment);
+ return type != null && toolCallId != null ? `${type}:${toolCallId}` : undefined;
+}
+
+/** Missing ownership is a compatibility wildcard for historical rows; two
+ * known unequal owners identify distinct executions. */
+function nonFileOwnersCompatible(left: TAttachment, right: TAttachment): boolean {
+ const leftAgentId = agentIdOf(left);
+ const rightAgentId = agentIdOf(right);
+ const leftStepId = left.stepId;
+ const rightStepId = right.stepId;
+ return (
+ (leftAgentId == null || rightAgentId == null || leftAgentId === rightAgentId) &&
+ (leftStepId == null || rightStepId == null || leftStepId === rightStepId)
+ );
+}
+
+/** Stable file identity shared with the message renderer. Non-file DB/live
+ * reconciliation additionally compares its producer ownership below. */
+const attachmentKey = attachmentIdentity;
+
+/**
+ * Wildcard-tolerant match for the lifecycle overlay: a missing `toolCallId`
+ * or `agentId` on either side matches (preview-sync records are bare
+ * `{file_id, ...}`); only DISTINCT values keep same-file entries separate.
+ */
+function matchesLiveEntry(db: TAttachment, live: TAttachment): boolean {
+ const key = fileKeyOf(db);
+ if (!key || fileKeyOf(live) !== key) {
+ return false;
+ }
+ const dbToolCallId = toolCallIdOf(db);
+ const liveToolCallId = toolCallIdOf(live);
+ if (dbToolCallId != null && liveToolCallId != null && dbToolCallId !== liveToolCallId) {
+ return false;
+ }
+ const dbAgentId = agentIdOf(db);
+ const liveAgentId = agentIdOf(live);
+ return dbAgentId == null || liveAgentId == null || dbAgentId === liveAgentId;
+}
+
+/**
+ * A message's stored attachments reconciled with the live ones the stream and preview polling
+ * delivered for it. Returns one of its inputs unchanged when the other is empty.
+ */
+export function mergeAttachments(
+ attachments: TAttachment[] | undefined,
+ live: TAttachment[] | undefined,
+): TAttachment[] {
+ if (!attachments || attachments.length === 0) {
+ return live ?? [];
+ }
+ if (!live || live.length === 0) {
+ return attachments;
+ }
+ /* DB-loaded attachments are the source of truth for which
+ * attachments belong to this message, but live entries (from the
+ * SSE handler / `useAttachmentPreviewSync` polling) carry fresher
+ * lifecycle fields (`status`, `text`, `textFormat`,
+ * `previewError`). Without this merge, the deferred-preview flow
+ * would render "stuck pending" forever on a loaded conversation:
+ * the message saved to DB at end-of-run has the immediate-persist
+ * snapshot (`status: 'pending'`, `text: null`); the file record
+ * itself updates to `'ready'` later, but the message's
+ * `attachments` array doesn't get rewritten. Polling fetches the
+ * resolved record into `messageAttachmentsMap`; merging here lets
+ * `artifactTypeForAttachment` see the resolved text/textFormat
+ * and route through the proper PanelArtifact card. */
+ const dbKeys = new Set<string>();
+ const nonFileBuckets = new Map<string, TAttachment[]>();
+ const merged = attachments.map((db) => {
+ const key = attachmentKey(db);
+ if (!key) {
+ return db;
+ }
+ const fileKey = fileKeyOf(db);
+ if (fileKey) {
+ /** Partial live file records must still be reachable by their
+ * less-specific keys so an overlaid entry isn't re-appended below:
+ * bare records key by file key, and agent-less records by
+ * fileKey::toolCallId. */
+ dbKeys.add(key);
+ dbKeys.add(fileKey);
+ const toolCallId = toolCallIdOf(db);
+ if (toolCallId != null) {
+ dbKeys.add(`${fileKey}::${toolCallId}`);
+ }
+ } else {
+ const bucketKey = nonFileBucketKey(db);
+ if (bucketKey) {
+ const bucket = nonFileBuckets.get(bucketKey) ?? [];
+ bucket.push(db);
+ nonFileBuckets.set(bucketKey, bucket);
+ }
+ }
+ const liveEntry = live.find((a) => matchesLiveEntry(db, a));
+ return liveEntry ? ({ ...db, ...liveEntry } as TAttachment) : db;
+ });
+ /* Live-only entries with a stable identity are kept, not discarded: a
+ * background code task's harvested files arrive via SSE anchored to a
+ * message whose DB `attachments` snapshot predates them (the row is
+ * patched post-finalize), so treating the DB list as exhaustive would
+ * make those files vanish until a full reload. Entries whose key is
+ * compatible DB file key or non-file owner are replay duplicates, while
+ * entries with no stable identity at all cannot be reconciled; both are
+ * dropped. */
+ const liveOnly = live.filter((a) => {
+ const key = attachmentKey(a);
+ if (key == null) {
+ return false;
+ }
+ if (fileKeyOf(a)) {
+ return !dbKeys.has(key);
+ }
+ const bucketKey = nonFileBucketKey(a);
+ if (!bucketKey) {
+ return false;
+ }
+ return !nonFileBuckets.get(bucketKey)?.some((db) => nonFileOwnersCompatible(db, a));
+ });
+ return liveOnly.length > 0 ? [...merged, ...liveOnly] : merged;
+}
diff --git a/e2e/specs/mock/scenarios/chat-facade-live-attachments.spec.ts b/e2e/specs/mock/scenarios/chat-facade-live-attachments.spec.ts
new file mode 100644
index 0000000000..ac5b95419d
--- /dev/null
+++ b/e2e/specs/mock/scenarios/chat-facade-live-attachments.spec.ts
@@ -0,0 +1,62 @@
+import { resolve } from 'node:path';
+import { expect, test } from '@playwright/test';
+import { inOneProject, repoRoot, run } from './lint.helpers';
+
+/**
+ * No component renders through `useChat` yet, so what its caller sees is read where the hook
+ * runs: the client's jest harness, with the real chat host, stream hook and attachment handler
+ * behind a fake transport that streams the run. Each scenario runs the named tests and reads
+ * the report jest writes.
+ */
+
+type JestReport = {
+ numPassedTests: number;
+ numFailedTests: number;
+ testResults: { assertionResults: { title: string; status: string }[] }[];
+};
+
+const runJest = (specs: string[], pattern?: string) => {
+ const args = ['jest', ...specs, '--maxWorkers=2', '--json'];
+ if (pattern) {
+ args.push('-t', pattern);
+ }
+ const result = run('npx', args, { cwd: resolve(repoRoot, 'client') });
+ const start = result.stdout.indexOf('{');
+ expect(start, result.output).toBeGreaterThanOrEqual(0);
+ return { result, report: JSON.parse(result.stdout.slice(start)) as JestReport };
+};
+
+const passedTitles = (report: JestReport) =>
+ report.testResults.flatMap((file) =>
+ file.assertionResults.filter((item) => item.status === 'passed').map((item) => item.title),
+ );
+
+test.describe('useChat live attachments', () => {
+ test.beforeEach(() => inOneProject());
+
+ test('a tool part follows an attachment streamed mid-run @scenario:facade-tool-part-follows-live-attachment', () => {
+ test.setTimeout(240_000);
+ const { result, report } = runJest(
+ ['src/hooks/Chat/__tests__/transport.spec.tsx', 'src/hooks/Chat/__tests__/facade.spec.tsx'],
+ 'attachment streamed mid-run|attachment that reached only the live map',
+ );
+
+ expect(result.status, result.output).toBe(0);
+ expect(report.numFailedTests).toBe(0);
+ expect(passedTitles(report)).toEqual(
+ expect.arrayContaining([
+ 'resolves a tool part against an attachment streamed mid-run',
+ 'resolves a tool part against an attachment that reached only the live map',
+ ]),
+ );
+ });
+
+ test('the message renderer keeps reconciling stored and live attachments @scenario:message-attachments-merge-live-entries', () => {
+ test.setTimeout(240_000);
+ const { result, report } = runJest(['src/hooks/Messages/__tests__/useAttachments.spec.tsx']);
+
+ expect(result.status, result.output).toBe(0);
+ expect(report.numFailedTests).toBe(0);
+ expect(report.numPassedTests).toBeGreaterThan(0);
+ });
+});