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: Render Files Saved by Tools Inside a Subagent Run (#17204)

Marco Berettaf7a56e843b63
diff --git a/api/server/routes/messages.js b/api/server/routes/messages.js
index c667346acf..eba5900a89 100644
--- a/api/server/routes/messages.js
+++ b/api/server/routes/messages.js
@@ -519,11 +519,15 @@ router.post('/artifact/:messageId', configMiddleware, async (req, res) => {
});
res.status(200).json(
- withMessageToolCallPreviews(req, {
- conversationId: savedMessage.conversationId,
- content: savedMessage.content,
- text: savedMessage.text,
- }),
+ withMessageToolCallPreviews(
+ req,
+ {
+ conversationId: savedMessage.conversationId,
+ content: savedMessage.content,
+ text: savedMessage.text,
+ },
+ message.attachments,
+ ),
);
} catch (error) {
if (isContentFilterError(error)) {
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index 90e27340e1..9d528346b7 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -12,6 +12,13 @@ import type { ReasoningDisclosures, ToolDisclosures } from './disclosure';
import type { ToolCallGroupExpansionState } from './ToolCallGroup';
import type { ActivityPhaseSegment } from '~/utils/activityLabels';
import type { MCPAppResourceOccurrence } from '~/utils/mcpApps';
+import {
+ assignNestedAttachments,
+ useLiveSubagentToolCalls,
+ SubagentAttachmentsContext,
+ selectExactlyNestedAttachments,
+ selectUnclaimedAttachments,
+} from '~/components/Chat/Subagents/attachments';
import {
mapAttachments,
getPartKeyIndex,
@@ -221,6 +228,49 @@ type PartWithContextProps = {
onToolExpand?: () => void;
};
+/**
+ * Attachments a top-level part accepts under the ownership rules its own row
+ * applies. A file a subagent child call owns under its full scope (`reserved`)
+ * goes to a top-level part only when that part carries the same scope, so an
+ * unscoped call reusing the child's id cannot take it first.
+ */
+const collectClaimedAttachments = (
+ content: Array<TMessageContentParts | undefined> | undefined,
+ attachments: TAttachment[],
+ reserved: ReadonlySet<TAttachment>,
+): ReadonlySet<TAttachment> => {
+ const claimed = new Set<TAttachment>();
+ const attachmentMap = mapAttachments(attachments);
+ const owners = buildToolCallStepOwners(content);
+ for (const part of content ?? []) {
+ if (part == null) {
+ continue;
+ }
+ const accepted = filterAttachmentsForPart(
+ attachmentMap[getToolCallId(part)],
+ getPartAgentId(part),
+ getPartStepId(part),
+ getSiblingStepIds(part, owners),
+ );
+ for (const attachment of accepted ?? []) {
+ if (reserved.has(attachment) && !carriesScopeOf(part, attachment)) {
+ continue;
+ }
+ claimed.add(attachment);
+ }
+ }
+ return claimed;
+};
+
+/** Whether the part carries every agent and step scope the attachment does. */
+const carriesScopeOf = (part: TMessageContentParts, attachment: TAttachment): boolean => {
+ const { agentId, stepId } = attachment as { agentId?: string; stepId?: string };
+ return (
+ (agentId == null || getPartAgentId(part) === agentId) &&
+ (stepId == null || getPartStepId(part) === stepId)
+ );
+};
+
const PartWithContext = memo(function PartWithContext({
part,
idx,
@@ -425,15 +475,34 @@ const ContentPartsBody = memo(function ContentPartsBody({
}
return buildToolCallStepOwners(content);
}, [toolCallStepOwnersById, content]);
+ const nestedAttachments = useContext(SubagentAttachmentsContext);
+ /** Files the message gave to a subagent run; a top-level call that matches
+ * one only by a reused id does not render it as its own. */
+ const nestedFiles = useMemo(
+ () => new Set([...nestedAttachments.values()].flat()),
+ [nestedAttachments],
+ );
const attachmentsForPart = useCallback(
- (part: TMessageContentParts): TAttachment[] | undefined =>
- filterAttachmentsForPart(
+ (part: TMessageContentParts): TAttachment[] | undefined => {
+ const matched = filterAttachmentsForPart(
attachmentMap[getToolCallId(part)],
getPartAgentId(part),
getPartStepId(part),
getSiblingStepIds(part, resolvedToolCallStepOwners),
- ),
- [attachmentMap, resolvedToolCallStepOwners],
+ );
+ /** A tool run inside a subagent saves its files under the child tool
+ * call id, which only the subagent call's transcript carries. */
+ const nested = nestedAttachments.get(part);
+ const own =
+ matched == null || nestedFiles.size === 0
+ ? matched
+ : matched.filter((file) => !nestedFiles.has(file) || nested?.includes(file) === true);
+ if (nested == null) {
+ return own;
+ }
+ return own == null ? nested : [...own, ...nested.filter((file) => !own.includes(file))];
+ },
+ [attachmentMap, resolvedToolCallStepOwners, nestedAttachments, nestedFiles],
);
const disclosureStore = useStore();
const reasoningDisclosures = useContext(ReasoningDisclosureContext);
@@ -1461,6 +1530,31 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
* value at every markdown block in the message. */
const attachmentsByName = useMemo(() => buildAttachmentsByName(attachments), [attachments]);
const media = useMemo(() => ({ attachmentsByName }), [attachmentsByName]);
+ const liveSubagentToolCalls = useLiveSubagentToolCalls(
+ props.content,
+ attachments,
+ messageId,
+ props.contentIndices,
+ props.contentIndexOffset ?? 0,
+ );
+ const unclaimedAttachments = useMemo(() => {
+ const { inlineAttachments } = partitionWorkspaceChanges(attachments);
+ const reserved = selectExactlyNestedAttachments(
+ props.content,
+ inlineAttachments,
+ liveSubagentToolCalls,
+ );
+ return selectUnclaimedAttachments(
+ inlineAttachments,
+ collectClaimedAttachments(props.content, inlineAttachments, reserved),
+ );
+ }, [props.content, attachments, liveSubagentToolCalls]);
+ /** Assigned once for the whole message: the bodies an MCP App or a phase
+ * splits it into each see a slice, and must agree on every file's owner. */
+ const nestedAttachments = useMemo(
+ () => assignNestedAttachments(props.content, unclaimedAttachments, liveSubagentToolCalls),
+ [props.content, unclaimedAttachments, liveSubagentToolCalls],
+ );
return (
<MessageContext.Provider value={messageContext}>
<MediaContext.Provider value={media}>
@@ -1471,16 +1565,18 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
<Sources messageId={messageId} conversationId={conversationId || undefined} />
</SearchContext.Provider>
)}
- {appContent ?? (
- <MCPAppSuppressionContext.Provider value={suppressedAppAttachments}>
- <SoleToolContext.Provider value={undefined}>
- <ContentPartsBody
- {...props}
- resumeAuthors={props.resumeAuthors ?? messageContent.resumeAuthors}
- />
- </SoleToolContext.Provider>
- </MCPAppSuppressionContext.Provider>
- )}
+ <SubagentAttachmentsContext.Provider value={nestedAttachments}>
+ {appContent ?? (
+ <MCPAppSuppressionContext.Provider value={suppressedAppAttachments}>
+ <SoleToolContext.Provider value={undefined}>
+ <ContentPartsBody
+ {...props}
+ resumeAuthors={props.resumeAuthors ?? messageContent.resumeAuthors}
+ />
+ </SoleToolContext.Provider>
+ </MCPAppSuppressionContext.Provider>
+ )}
+ </SubagentAttachmentsContext.Provider>
</ToolDisclosureContext.Provider>
</ReasoningDisclosureContext.Provider>
</MediaContext.Provider>
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
index 57de2e7167..88247df732 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -1,13 +1,24 @@
import React from 'react';
+import { getDefaultStore } from 'jotai';
import { ContentTypes, Tools } from 'librechat-data-provider';
-import { fireEvent, render, screen } from '@testing-library/react';
-import type { TMessageContentParts, TAttachment } from 'librechat-data-provider';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import type {
+ TMessageContentParts,
+ SubagentUpdateEvent,
+ TAttachment,
+} from 'librechat-data-provider';
+import type { SubagentProgress } from '~/components/Chat/Subagents/state';
+import {
+ subagentProgressKey,
+ reduceSubagentProgress,
+ subagentProgressByToolCallId,
+} from '~/components/Chat/Subagents/state';
import { preserveStreamedContentIdentity } from '~/utils/messages';
-import { groupSequentialToolCalls } from '~/utils';
+import { mapAttachments, groupSequentialToolCalls } from '~/utils';
jest.mock('~/utils', () => ({
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
- mapAttachments: () => ({}),
+ mapAttachments: jest.fn(() => ({})),
filterAttachmentsForPart: (attachments: unknown) => attachments,
groupSequentialToolCalls: jest.fn(),
hasPendingApprovalInPart: jest.requireActual('~/utils/groupToolCalls').hasPendingApprovalInPart,
@@ -82,12 +93,15 @@ jest.mock('../ToolCallGroup', () => ({
default: ({
initialExpansionState,
onExpansionChange,
+ groupAttachments,
}: {
initialExpansionState?: { isExpanded: boolean; userOverride: boolean };
onExpansionChange?: (state: { isExpanded: boolean; userOverride: boolean }) => void;
+ groupAttachments?: TAttachment[];
}) => (
<button
data-testid="tool-call-group"
+ data-attachments={(groupAttachments ?? []).map((file) => file.filename).join(',')}
data-initial-expanded={
initialExpansionState == null ? 'unset' : String(initialExpansionState.isExpanded)
}
@@ -679,6 +693,649 @@ describe('ContentParts — activity phase state', () => {
expect(screen.getByTestId('parallel-renderer')).toHaveAttribute('data-index-offset', '1');
});
+ it('hoists files a tool saved inside a grouped subagent run onto the group', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const childImage = (subagent_content?: unknown[]) =>
+ [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'subagent-1',
+ name: 'subagent',
+ args: {},
+ output: 'done',
+ subagent_content,
+ },
+ },
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'tool-2', name: 'search', args: {}, output: 'two' },
+ },
+ ] as unknown as TMessageContentParts[];
+ const attachments = [
+ {
+ filename: 'cat.png',
+ filepath: '/images/cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'child-image',
+ },
+ ] as TAttachment[];
+ const nested = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'child-image', name: 'image_gen_oai', args: {} },
+ },
+ ];
+
+ const { rerender } = render(
+ <ContentParts {...baseProps} content={childImage(nested)} attachments={attachments} />,
+ );
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute('data-attachments', 'cat.png');
+
+ rerender(<ContentParts {...baseProps} content={childImage()} attachments={attachments} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute('data-attachments', '');
+ });
+
+ it('hoists a grouped subagent file whose transcript the server left out of the preview', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'subagent-previewed',
+ name: 'subagent',
+ args: {},
+ output: 'done',
+ progress: 1,
+ subagentContentOmitted: true,
+ subagentContentParts: 3,
+ subagentAttachmentCalls: [{ id: 'omitted-image' }],
+ },
+ },
+ ] as unknown as TMessageContentParts[];
+ const attachments = [
+ {
+ filename: 'previewed-cat.png',
+ filepath: '/images/previewed-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'omitted-image',
+ },
+ ] as TAttachment[];
+
+ render(<ContentParts {...baseProps} content={content} attachments={attachments} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'previewed-cat.png',
+ );
+ });
+
+ it('hoists files from a grouped subagent run that is still streaming', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-live', name: 'subagent', args: {} },
+ },
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'tool-2', name: 'search', args: {}, output: 'two' },
+ },
+ ] as unknown as TMessageContentParts[];
+ const attachments = [
+ {
+ filename: 'live-cat.png',
+ filepath: '/images/live-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'live-child-image',
+ },
+ ] as TAttachment[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-live', 0),
+ );
+
+ const streaming = { ...baseProps, isSubmitting: true, isLatestMessage: true };
+ const { rerender } = render(
+ <ContentParts {...streaming} content={content} attachments={attachments} />,
+ );
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute('data-attachments', '');
+ /** A streamed delta replaces the content array before the first progress update. */
+ rerender(<ContentParts {...streaming} content={[...content]} attachments={attachments} />);
+
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'live-child-image', name: 'image_gen_oai', args: '' },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ });
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'live-cat.png',
+ );
+
+ /** The bounded live activity evicts early parts as later ones arrive. */
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [{ type: ContentTypes.TEXT, text: 'later output' }],
+ } as unknown as SubagentProgress);
+ });
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'live-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('keeps a live child file routed when the message remounts after eviction', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-remount', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const attachments = [
+ {
+ filename: 'remount-cat.png',
+ filepath: '/images/remount-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'remount-child',
+ },
+ ] as TAttachment[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-remount', 0),
+ );
+ const streaming = { ...baseProps, isSubmitting: true, isLatestMessage: true };
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'remount-child', name: 'image_gen_oai', args: '' },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ });
+ const first = render(
+ <ContentParts {...streaming} content={content} attachments={attachments} />,
+ );
+ first.unmount();
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [{ type: ContentTypes.TEXT, text: 'later output' }],
+ } as unknown as SubagentProgress);
+ });
+
+ render(<ContentParts {...streaming} content={content} attachments={attachments} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'remount-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('hoists a file a settled message receives late through its subagent progress', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'subagent-settled',
+ name: 'subagent',
+ args: {},
+ output: 'done',
+ progress: 1,
+ subagentContentOmitted: true,
+ },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-settled', 0),
+ );
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'late-child', name: 'bash_tool', args: '' },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ });
+ const late = [
+ {
+ filename: 'late-report.csv',
+ filepath: '/files/late-report.csv',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'late-child',
+ },
+ ] as TAttachment[];
+
+ render(<ContentParts {...baseProps} content={content} attachments={late} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'late-report.csv',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('routes a live child file whose call was evicted before the message mounted', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-unread', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-unread', 0),
+ );
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ agentId: 'agent-unread',
+ [ContentTypes.TOOL_CALL]: { id: 'unread-child', name: 'image_gen_oai', args: '' },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ getDefaultStore().set(progressAtom, (previous) => ({
+ ...(previous as SubagentProgress),
+ contentParts: [{ type: ContentTypes.TEXT, text: 'later output' }],
+ }));
+ });
+ const files = [
+ {
+ filename: 'unread-cat.png',
+ filepath: '/images/unread-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'unread-child',
+ agentId: 'agent-unread',
+ },
+ ] as TAttachment[];
+
+ render(<ContentParts {...baseProps} content={content} attachments={files} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'unread-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('routes a live child file when one batch shows and evicts its call while mounted', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-batched', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-batched', 0),
+ );
+ const files = [
+ {
+ filename: 'batched-cat.png',
+ filepath: '/images/batched-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'batched-child',
+ },
+ ] as TAttachment[];
+ const streaming = { ...baseProps, isSubmitting: true, isLatestMessage: true };
+ const { rerender } = render(<ContentParts {...streaming} content={content} />);
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'batched-child', name: 'image_gen_oai', args: '' },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ getDefaultStore().set(progressAtom, (previous) => ({
+ ...(previous as SubagentProgress),
+ contentParts: [{ type: ContentTypes.TEXT, text: 'later output' }],
+ }));
+ });
+ rerender(<ContentParts {...streaming} content={content} attachments={files} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'batched-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('routes a child file whose call a single bounded batch evicted', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-batch', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-batch', 0),
+ );
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [{ type: ContentTypes.TEXT, text: 'after the bound' }],
+ aggregatorState: { evictedToolCalls: [{ id: 'batch-evicted' }] },
+ } as unknown as SubagentProgress);
+ });
+ const files = [
+ {
+ filename: 'batch-cat.png',
+ filepath: '/images/batch-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'batch-evicted',
+ },
+ ] as TAttachment[];
+
+ render(<ContentParts {...baseProps} content={content} attachments={files} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'batch-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('keeps the owner of a shown file past the bounded call history', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-long', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-long', 0),
+ );
+ const call = (id: string) => ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, name: 'bash_tool', args: '' },
+ });
+ const files = [
+ {
+ filename: 'early-cat.png',
+ filepath: '/images/early-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'early-image',
+ },
+ ] as TAttachment[];
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [call('early-image')],
+ } as unknown as SubagentProgress);
+ });
+ render(<ContentParts {...baseProps} content={content} attachments={files} />);
+ for (let batch = 0; batch < 6; batch++) {
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: Array.from({ length: 100 }, (_, index) => call(`later-${batch}-${index}`)),
+ } as unknown as SubagentProgress);
+ });
+ }
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'early-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('keeps a shown file owner through reduced progress that replays its eviction list', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-reduced', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-reduced', 0),
+ );
+ const runStep = (id: string, sequence: number) =>
+ ({
+ runId: 'parent-run',
+ subagentRunId: 'child-run',
+ subagentType: 'self',
+ phase: 'run_step',
+ activityEventId: `reduced-${sequence}`,
+ data: { stepDetails: { type: 'tool_calls', tool_calls: [{ id, name: 'bash_tool' }] } },
+ timestamp: '',
+ }) as unknown as SubagentUpdateEvent;
+ const files = [
+ {
+ filename: 'reduced-cat.png',
+ filepath: '/images/reduced-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'reduced-image',
+ },
+ ] as TAttachment[];
+ act(() => {
+ getDefaultStore().set(progressAtom, (previous) =>
+ reduceSubagentProgress(previous, [runStep('reduced-image', 0)]),
+ );
+ });
+ render(<ContentParts {...baseProps} content={content} attachments={files} />);
+ for (let index = 1; index <= 600; index++) {
+ act(() => {
+ getDefaultStore().set(progressAtom, (previous) =>
+ reduceSubagentProgress(previous, [runStep(`reduced-later-${index}`, index)]),
+ );
+ });
+ }
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'reduced-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('routes a file from a nested subagent run the live activity evicted', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-outer', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-outer', 0),
+ );
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'inner-subagent',
+ name: 'subagent',
+ args: '',
+ subagent_content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'inner-image', name: 'image_gen_oai' },
+ },
+ ],
+ },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ getDefaultStore().set(progressAtom, (previous) => ({
+ ...(previous as SubagentProgress),
+ contentParts: [{ type: ContentTypes.TEXT, text: 'later output' }],
+ }));
+ });
+ const files = [
+ {
+ filename: 'inner-cat.png',
+ filepath: '/images/inner-cat.png',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'inner-image',
+ },
+ ] as TAttachment[];
+
+ render(<ContentParts {...baseProps} content={content} attachments={files} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'inner-cat.png',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('reads live progress under the index a compacted part streamed at', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ streamedIndex: 1,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-compacted', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const progressAtom = subagentProgressByToolCallId(
+ subagentProgressKey('msg-1', 'subagent-compacted', 1),
+ );
+ act(() => {
+ getDefaultStore().set(progressAtom, {
+ contentParts: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'compacted-child', name: 'bash_tool', args: '' },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ });
+ const files = [
+ {
+ filename: 'compacted.csv',
+ filepath: '/files/compacted.csv',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'compacted-child',
+ },
+ ] as TAttachment[];
+
+ render(<ContentParts {...baseProps} content={content} attachments={files} />);
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'compacted.csv',
+ );
+ act(() => getDefaultStore().set(progressAtom, null));
+ });
+
+ it('keeps a scoped child file off an unscoped top-level call that reuses its id', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => parts.map((part) => ({ type: 'tool-group', parts: [part] })));
+ jest.mocked(mapAttachments).mockImplementation((files) => {
+ const map: Record<string, TAttachment[] | undefined> = {};
+ for (const file of files) {
+ if (file?.toolCallId != null) {
+ (map[file.toolCallId] ??= []).push(file);
+ }
+ }
+ return map;
+ });
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'subagent-owner',
+ name: 'subagent',
+ args: {},
+ output: 'done',
+ subagent_content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'reused-id',
+ name: 'bash_tool',
+ stepId: 'step-child',
+ },
+ },
+ ],
+ },
+ },
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'reused-id', name: 'search', args: {}, output: 'x' },
+ },
+ ] as unknown as TMessageContentParts[];
+ const files = [
+ {
+ filename: 'child.csv',
+ filepath: '/files/child.csv',
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId: 'reused-id',
+ stepId: 'step-child',
+ },
+ ] as TAttachment[];
+
+ render(<ContentParts {...baseProps} content={content} attachments={files} />);
+ const [subagentGroup, topLevelGroup] = screen.getAllByTestId('tool-call-group');
+ expect(subagentGroup).toHaveAttribute('data-attachments', 'child.csv');
+ expect(topLevelGroup).toHaveAttribute('data-attachments', '');
+ jest.mocked(mapAttachments).mockImplementation(() => ({}));
+ });
+
+ it('frees the progress member of a streaming subagent no update reached', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => parts.map((part) => ({ type: 'single', part })));
+ const key = subagentProgressKey('msg-1', 'subagent-silent', 0);
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'subagent-silent', name: 'subagent', args: {} },
+ },
+ ] as unknown as TMessageContentParts[];
+ const streaming = { ...baseProps, isSubmitting: true, isLatestMessage: true };
+ const { unmount } = render(<ContentParts {...streaming} content={content} />);
+ expect([...subagentProgressByToolCallId.getParams()]).toContain(key);
+ unmount();
+ expect([...subagentProgressByToolCallId.getParams()]).not.toContain(key);
+ });
+
it('retains a tool-group expansion override when a completed phase remounts the group', () => {
jest.mocked(groupSequentialToolCalls).mockImplementation((parts) => {
const toolParts = parts.filter(({ part }) => part.type === ContentTypes.TOOL_CALL);
diff --git a/client/src/components/Chat/Subagents/attachments.test.ts b/client/src/components/Chat/Subagents/attachments.test.ts
new file mode 100644
index 0000000000..fd8f10f16e
--- /dev/null
+++ b/client/src/components/Chat/Subagents/attachments.test.ts
@@ -0,0 +1,189 @@
+import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
+import {
+ collectNestedCalls,
+ assignNestedAttachments,
+ selectUnclaimedAttachments,
+ selectExactlyNestedAttachments,
+} from './attachments';
+
+const file = (toolCallId?: string) =>
+ ({ file_id: `file-${toolCallId}`, toolCallId }) as TAttachment;
+
+const toolCall = (id: string, fields: Record<string, unknown> = {}) =>
+ ({ type: 'tool_call', tool_call: { id, ...fields } }) as unknown as TMessageContentParts;
+
+const subagent = (id: string, subagent_content: TMessageContentParts[]) =>
+ toolCall(id, { name: 'subagent', subagent_content });
+
+const ids = (map: ReadonlyMap<unknown, TAttachment[]>, owner: TMessageContentParts) =>
+ (map.get(owner) ?? []).map((attachment) => attachment.toolCallId);
+
+describe('subagent attachments', () => {
+ it('leaves out files a top-level part accepted and files without a tool call', () => {
+ const accepted = file('direct-call');
+ const unclaimed = selectUnclaimedAttachments(
+ [accepted, file('child-call'), file(undefined)],
+ new Set([accepted]),
+ );
+ expect(unclaimed.map((attachment) => attachment.toolCallId)).toEqual(['child-call']);
+ });
+
+ it('offers a file its top-level part rejected to the subagent that ran it', () => {
+ const rejected = file('shared-id');
+ const unclaimed = selectUnclaimedAttachments([rejected], new Set());
+ const content = [subagent('subagent-call', [toolCall('shared-id')]), toolCall('shared-id')];
+ expect(ids(assignNestedAttachments(content, unclaimed, new Map()), content[0])).toEqual([
+ 'shared-id',
+ ]);
+ });
+
+ it('collects child calls with their scope through nested runs and previews', () => {
+ const scoped = {
+ type: 'tool_call',
+ agentId: 'agent-child',
+ tool_call: { id: 'grandchild-call', stepId: 'step-1' },
+ } as unknown as TMessageContentParts;
+ expect(
+ collectNestedCalls([
+ subagent('child-call', [scoped]),
+ toolCall('previewed-call', {
+ subagentAttachmentCalls: [{ id: 'omitted-call', stepId: 'step-2' }],
+ }),
+ ]),
+ ).toEqual([
+ { id: 'child-call' },
+ { id: 'grandchild-call', agentId: 'agent-child', stepId: 'step-1' },
+ { id: 'previewed-call' },
+ { id: 'omitted-call', stepId: 'step-2' },
+ ]);
+ });
+
+ it('keeps a previewed scope apart when two subagents share a child id', () => {
+ const content = [
+ toolCall('first', { subagentAttachmentCalls: [{ id: 'shared', stepId: 'step-a' }] }),
+ toolCall('second', { subagentAttachmentCalls: [{ id: 'shared', stepId: 'step-b' }] }),
+ ];
+ const fromB = { ...file('shared'), stepId: 'step-b' } as TAttachment;
+ const assigned = assignNestedAttachments(content, [fromB], new Map());
+ expect(ids(assigned, content[0])).toEqual([]);
+ expect(ids(assigned, content[1])).toEqual(['shared']);
+ });
+
+ it('routes previewed, live and stored child files, each to one owner', () => {
+ const content = [
+ subagent('first', [toolCall('shared-child')]),
+ subagent('second', [toolCall('shared-child')]),
+ toolCall('previewed', { name: 'subagent', subagentAttachmentCalls: [{ id: 'omitted' }] }),
+ toolCall('streaming', { name: 'subagent' }),
+ ];
+ const unclaimed = [file('shared-child'), file('omitted'), file('live-child'), file('other')];
+ const assigned = assignNestedAttachments(
+ content,
+ unclaimed,
+ new Map([[3, [{ id: 'live-child' }]]]),
+ );
+ expect(ids(assigned, content[0])).toEqual(['shared-child']);
+ expect(ids(assigned, content[1])).toEqual([]);
+ expect(ids(assigned, content[2])).toEqual(['omitted']);
+ expect(ids(assigned, content[3])).toEqual(['live-child']);
+ });
+
+ it('gives a child id two subagents share to the run whose step saved the file', () => {
+ const content = [
+ subagent('first', [toolCall('shared-child', { stepId: 'step-a' })]),
+ subagent('second', [toolCall('shared-child', { stepId: 'step-b' })]),
+ ];
+ const fromB = { ...file('shared-child'), stepId: 'step-b' } as TAttachment;
+ const assigned = assignNestedAttachments(content, [fromB], new Map());
+ expect(ids(assigned, content[0])).toEqual([]);
+ expect(ids(assigned, content[1])).toEqual(['shared-child']);
+ });
+
+ it('prefers the run whose call carries the file scope over one whose scope is unknown', () => {
+ const content = [
+ subagent('first', [toolCall('shared-child')]),
+ subagent('second', [toolCall('shared-child', { stepId: 'step-b' })]),
+ ];
+ const fromB = { ...file('shared-child'), stepId: 'step-b' } as TAttachment;
+ const unscoped = file('shared-child');
+ const assigned = assignNestedAttachments(content, [fromB, unscoped], new Map());
+ expect(assigned.get(content[0])).toEqual([unscoped]);
+ expect(assigned.get(content[1])).toEqual([fromB]);
+ });
+
+ it('routes child files of a stored subagent call that has no id', () => {
+ const legacy = {
+ type: 'tool_call',
+ tool_call: { name: 'subagent', subagent_content: [toolCall('legacy-child')] },
+ } as unknown as TMessageContentParts;
+ const assigned = assignNestedAttachments([legacy], [file('legacy-child')], new Map());
+ expect(ids(assigned, legacy)).toEqual(['legacy-child']);
+ });
+
+ it('reads a child call owner stored on the call when the part has none', () => {
+ expect(collectNestedCalls([toolCall('child', { agentId: 'agent-on-call' })])).toEqual([
+ { id: 'child', agentId: 'agent-on-call' },
+ ]);
+ });
+
+ it('reserves a file a child call owns under its full scope', () => {
+ const content = [subagent('runner', [toolCall('reused', { stepId: 'step-child' })])];
+ const scoped = { ...file('reused'), stepId: 'step-child' } as TAttachment;
+ const other = { ...file('reused'), stepId: 'step-other' } as TAttachment;
+ expect(selectExactlyNestedAttachments(content, [scoped, other], new Map())).toEqual(
+ new Set([scoped]),
+ );
+ });
+
+ it('collects child calls of a chain nested thousands deep', () => {
+ let deepest = toolCall('deepest-call');
+ for (let depth = 0; depth < 10_000; depth++) {
+ deepest = subagent(`level-${depth}`, [deepest]);
+ }
+ const calls = collectNestedCalls([deepest]);
+ expect(calls).toHaveLength(10_001);
+ expect(calls.at(-1)).toEqual({ id: 'deepest-call' });
+ });
+
+ it('uses the run owner for its own top-level calls only', () => {
+ expect(
+ collectNestedCalls(
+ [toolCall('own-call'), subagent('nested-run', [toolCall('nested-call')])],
+ [],
+ 'run-agent',
+ ),
+ ).toEqual([
+ { id: 'own-call', agentId: 'run-agent' },
+ { id: 'nested-run', agentId: 'run-agent' },
+ { id: 'nested-call' },
+ ]);
+ });
+
+ it('gives restored child files to the run whose stored identity owns them', () => {
+ const run = (id: string, agent: string) =>
+ toolCall(id, {
+ name: 'subagent',
+ subagentIdentity: { subagentKind: 'agent', subagentAgentId: agent },
+ subagent_content: [toolCall('shared-child')],
+ });
+ const content = [run('first', 'agent-a'), run('second', 'agent-b')];
+ const fromB = { ...file('shared-child'), agentId: 'agent-b' } as TAttachment;
+ const assigned = assignNestedAttachments(content, [fromB], new Map());
+ expect(ids(assigned, content[0])).toEqual([]);
+ expect(ids(assigned, content[1])).toEqual(['shared-child']);
+ });
+
+ it('keeps the files of two subagent calls that share an id apart', () => {
+ const content = [
+ subagent('same-id', [toolCall('first-child')]),
+ subagent('same-id', [toolCall('second-child')]),
+ ];
+ const assigned = assignNestedAttachments(
+ content,
+ [file('first-child'), file('second-child')],
+ new Map(),
+ );
+ expect(ids(assigned, content[0])).toEqual(['first-child']);
+ expect(ids(assigned, content[1])).toEqual(['second-child']);
+ });
+});
diff --git a/client/src/components/Chat/Subagents/attachments.ts b/client/src/components/Chat/Subagents/attachments.ts
new file mode 100644
index 0000000000..343c70b64a
--- /dev/null
+++ b/client/src/components/Chat/Subagents/attachments.ts
@@ -0,0 +1,254 @@
+import { createContext, useEffect, useMemo, useRef } from 'react';
+import { Constants } from 'librechat-data-provider';
+import { atom, useStore, useAtomValue } from 'jotai';
+import type { TAttachment, TMessageContentParts, Agents } from 'librechat-data-provider';
+import type { SubagentContentPart } from '~/utils/subagentContent';
+import {
+ nestedToolCallOf,
+ collectNestedCalls,
+ subagentProgressKey,
+ retainSubagentProgress,
+ rememberSubagentChildCalls,
+ rememberedSubagentChildCalls,
+ subagentProgressByToolCallId,
+} from './state';
+
+export { collectNestedCalls };
+import { getPartKeyIndex } from '~/utils/messages';
+
+type NestedPart = TMessageContentParts | SubagentContentPart | undefined;
+/** A tool call inside a subagent run, with the scope its files may carry. */
+export type NestedCall = Agents.SubagentAttachmentCall;
+
+const EMPTY: TAttachment[] = [];
+const NO_LIVE_CALLS: ReadonlyMap<number, NestedCall[]> = new Map();
+const NO_NESTED: ReadonlyMap<NestedPart, TAttachment[]> = new Map();
+
+/**
+ * The files each tool call part of the message owns through its subagent run,
+ * keyed by the part. A tool run inside a subagent saves its files under the
+ * child tool call id, which only appears inside the parent `subagent` call. The
+ * message assigns them once, so every body it splits into reads one answer.
+ */
+export const SubagentAttachmentsContext =
+ createContext<ReadonlyMap<NestedPart, TAttachment[]>>(NO_NESTED);
+
+/**
+ * The ownership rule top-level parts apply: a scope both sides carry must
+ * agree. `exact` also requires the call to carry every scope the file does, so
+ * a call whose scope is still unknown cannot take a file a scoped call owns.
+ */
+const ownsAttachment = (call: NestedCall, attachment: TAttachment, exact: boolean): boolean => {
+ const { agentId, stepId } = attachment as { agentId?: string; stepId?: string };
+ const agrees = (own: string | undefined, file: string | undefined) =>
+ file == null || (own == null ? !exact : own === file);
+ return (
+ call.id === attachment.toolCallId &&
+ agrees(call.agentId, agentId) &&
+ agrees(call.stepId, stepId)
+ );
+};
+
+/** Tool attachments that `claimed` (what the top-level parts accept) leaves out. */
+export function selectUnclaimedAttachments(
+ attachments: TAttachment[],
+ claimed: ReadonlySet<TAttachment>,
+): TAttachment[] {
+ const unclaimed = attachments.filter(
+ (attachment) => attachment.toolCallId != null && !claimed.has(attachment),
+ );
+ return unclaimed.length > 0 ? unclaimed : EMPTY;
+}
+
+/** Each tool call part of `content` with the child calls of its stored, previewed or live run. */
+function collectNestedOwners(
+ content: ReadonlyArray<NestedPart> | undefined,
+ live: ReadonlyMap<number, NestedCall[]>,
+): Array<[NestedPart, NestedCall[]]> {
+ const owners: Array<[NestedPart, NestedCall[]]> = [];
+ (content ?? []).forEach((part, index) => {
+ const toolCall = nestedToolCallOf(part);
+ if (toolCall == null) {
+ return;
+ }
+ const calls = collectNestedCalls(
+ toolCall.subagent_content,
+ [],
+ toolCall.subagentIdentity?.subagentAgentId,
+ );
+ calls.push(...(toolCall.subagentAttachmentCalls ?? []), ...(live.get(index) ?? []));
+ if (calls.length > 0) {
+ owners.push([part, calls]);
+ }
+ });
+ return owners;
+}
+
+/**
+ * Attachments a child call inside some subagent run owns under its full scope.
+ * A top-level call that only matches them by id, without that scope, must not
+ * take them first.
+ */
+export function selectExactlyNestedAttachments(
+ content: ReadonlyArray<NestedPart> | undefined,
+ attachments: TAttachment[],
+ live: ReadonlyMap<number, NestedCall[]>,
+): ReadonlySet<TAttachment> {
+ const owners = collectNestedOwners(content, live);
+ const reserved = new Set<TAttachment>();
+ if (owners.length === 0) {
+ return reserved;
+ }
+ for (const attachment of attachments) {
+ if (owners.some(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, true)))) {
+ reserved.add(attachment);
+ }
+ }
+ return reserved;
+}
+
+/**
+ * Hands each unclaimed attachment to one tool call part of the message whose
+ * transcript (stored, previewed, or streaming in `live`, keyed by content
+ * index) holds the tool call it was saved under. A part whose call matches the
+ * file's full scope is preferred over one whose scope is still unknown; within
+ * each pass the first part in message order wins, so a child id two subagents
+ * share renders the file once. The map is keyed by the part itself, so two
+ * calls sharing an id keep their own files.
+ */
+export function assignNestedAttachments(
+ content: ReadonlyArray<NestedPart> | undefined,
+ unclaimed: TAttachment[],
+ live: ReadonlyMap<number, NestedCall[]>,
+): ReadonlyMap<NestedPart, TAttachment[]> {
+ if (unclaimed.length === 0) {
+ return NO_NESTED;
+ }
+ const owners = collectNestedOwners(content, live);
+ const assigned = new Map<NestedPart, TAttachment[]>();
+ for (const attachment of unclaimed) {
+ const owner =
+ owners.find(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, true))) ??
+ owners.find(([, calls]) => calls.some((call) => ownsAttachment(call, attachment, false)));
+ if (owner == null) {
+ continue;
+ }
+ const files = assigned.get(owner[0]) ?? [];
+ files.push(attachment);
+ assigned.set(owner[0], files);
+ }
+ return assigned.size > 0 ? assigned : NO_NESTED;
+}
+
+/**
+ * Child tool calls the live progress of each subagent call in `content` holds,
+ * keyed by the call's index in `content`. Until the run is saved, and for a
+ * file a background task delivers after the message settled, those calls exist
+ * only there. The atom yields a signature string so the caller re-renders when
+ * a child call appears, not on every delta. Each member it reads is retained
+ * like a card's, so one no update ever reached is freed on unmount. Calls
+ * already seen are kept with the invocation (`rememberSubagentChildCalls`),
+ * since the bounded live activity evicts early parts before the transcript is
+ * saved.
+ */
+export function useLiveSubagentToolCalls(
+ content: ReadonlyArray<TMessageContentParts | undefined> | undefined,
+ attachments: ReadonlyArray<TAttachment> | undefined,
+ messageId: string,
+ contentIndices: ReadonlyArray<number> | undefined,
+ contentIndexOffset: number,
+): ReadonlyMap<number, NestedCall[]> {
+ /** Only calls a file of this message names matter for routing, so the
+ * signature carries those rather than the invocation's whole history. */
+ const idSignature = useMemo(
+ () =>
+ [...new Set((attachments ?? []).map((attachment) => attachment.toolCallId ?? ''))]
+ .filter(Boolean)
+ .sort()
+ .join('\u0000'),
+ [attachments],
+ );
+ /** A string, so the keys (and the atom reading them) survive the content
+ * array changing on every streamed delta. */
+ const keySignature = useMemo(() => {
+ const entries: Array<[number, string]> = [];
+ (content ?? []).forEach((part, index) => {
+ const toolCall = nestedToolCallOf(part);
+ if (toolCall?.id && toolCall.name === Constants.SUBAGENT) {
+ entries.push([
+ index,
+ subagentProgressKey(
+ messageId,
+ toolCall.id,
+ getPartKeyIndex(part, contentIndices?.[index] ?? index + contentIndexOffset),
+ ),
+ ]);
+ }
+ });
+ return entries.length === 0 ? '' : JSON.stringify(entries);
+ }, [content, messageId, contentIndices, contentIndexOffset]);
+ const keys = useMemo(
+ () => (keySignature === '' ? [] : (JSON.parse(keySignature) as Array<[number, string]>)),
+ [keySignature],
+ );
+ const store = useStore();
+ /** Retained one key at a time: releasing a key that is still read would free
+ * the member under the atom subscribed to it. */
+ const retained = useRef(new Map<string, () => void>());
+ useEffect(() => {
+ const next = new Set(keys.map(([, key]) => key));
+ for (const [key, release] of retained.current) {
+ if (!next.has(key)) {
+ release();
+ retained.current.delete(key);
+ }
+ }
+ for (const key of next) {
+ if (!retained.current.has(key)) {
+ retained.current.set(key, retainSubagentProgress(store, key));
+ }
+ }
+ }, [keys, store]);
+ useEffect(() => {
+ const held = retained.current;
+ return () => {
+ held.forEach((release) => release());
+ held.clear();
+ };
+ }, []);
+ /** Built from everything the invocation has shown, not only its current
+ * activity: a write the progress setter remembered and a later write that
+ * evicted the same call can land in one batch. */
+ const signatureAtom = useMemo(
+ () =>
+ atom((get) => {
+ const ids = new Set(idSignature === '' ? [] : idSignature.split('\u0000'));
+ const live: Array<[number, NestedCall[]]> = [];
+ for (const [index, key] of keys) {
+ const progress = get(subagentProgressByToolCallId(key));
+ const owners = rememberedSubagentChildCalls(key, ids);
+ /** The owners of this message's files are refreshed as the newest
+ * entries, so the bounded history cannot age them out while it shows. */
+ rememberSubagentChildCalls(key, owners, true);
+ rememberSubagentChildCalls(
+ key,
+ collectNestedCalls(progress?.contentParts, [], progress?.subagentAgentId),
+ );
+ const calls = rememberedSubagentChildCalls(key, ids);
+ if (calls.length > 0) {
+ live.push([index, calls]);
+ }
+ }
+ return live.length === 0 ? '' : JSON.stringify(live);
+ }),
+ [keys, idSignature],
+ );
+ const signature = useAtomValue(signatureAtom);
+ return useMemo(
+ () =>
+ signature === ''
+ ? NO_LIVE_CALLS
+ : new Map(JSON.parse(signature) as Array<[number, NestedCall[]]>),
+ [signature],
+ );
+}
diff --git a/client/src/components/Chat/Subagents/state.spec.ts b/client/src/components/Chat/Subagents/state.spec.ts
index 2296be9a61..91fa6c2442 100644
--- a/client/src/components/Chat/Subagents/state.spec.ts
+++ b/client/src/components/Chat/Subagents/state.spec.ts
@@ -3,12 +3,15 @@ import { ContentTypes } from 'librechat-data-provider';
import { act, renderHook } from '@testing-library/react';
import { createStore, Provider as JotaiProvider } from 'jotai';
import type { SubagentUpdateEvent } from 'librechat-data-provider';
+import type { SubagentProgress } from './state';
import {
closeParentSubagentProgress,
reduceSubagentProgress,
reduceSubagentReplay,
registerSubagentProgressKey,
+ rememberSubagentChildCalls,
removeSubagentProgressAtoms,
+ rememberedSubagentChildCalls,
subagentParentStreamOpenByToolCallId,
subagentProgressByToolCallId,
subagentProgressKey,
@@ -384,6 +387,61 @@ describe('reduceSubagentProgress', () => {
).toBeLessThanOrEqual(64 * 1024);
});
+ it('keeps the calls one batch evicts so their files keep an owner', () => {
+ const toolEvents = Array.from({ length: 120 }, (_, index) =>
+ update({
+ activityEventId: `evicting-tool-${index}`,
+ phase: 'run_step',
+ data: {
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: `evicting-call-${index}`, name: 'search', args: { index } }],
+ },
+ },
+ }),
+ );
+ const bounded = reduceSubagentProgress(null, toolEvents);
+ expect(bounded?.contentParts).toHaveLength(100);
+ expect(bounded?.aggregatorState.evictedToolCalls?.map((call) => call.id)).toEqual(
+ Array.from({ length: 20 }, (_, index) => `evicting-call-${index}`),
+ );
+ });
+
+ it('keeps a bounded memory of the child calls an invocation showed', () => {
+ const key = 'memory-message\u0000memory-call\u00000';
+ rememberSubagentChildCalls(
+ key,
+ Array.from({ length: 520 }, (_, index) => ({ id: `remembered-${index}` })),
+ );
+ const ids = new Set(['remembered-0', 'remembered-519']);
+ expect(rememberedSubagentChildCalls(key, ids)).toEqual([{ id: 'remembered-519' }]);
+ removeSubagentProgressAtoms(key);
+ expect(rememberedSubagentChildCalls(key, ids)).toEqual([]);
+ });
+
+ it('remembers the calls a replay segment evicted', () => {
+ const store = createStore();
+ const key = 'replay-message\u0000replay-call\u00000';
+ store.set(subagentProgressByToolCallId(key), {
+ contentParts: [],
+ aggregatorState: { evictedToolCalls: [] },
+ replaySegments: [
+ {
+ from: 0,
+ through: 1,
+ progress: {
+ contentParts: [],
+ aggregatorState: { evictedToolCalls: [{ id: 'segment-evicted' }] },
+ },
+ },
+ ],
+ } as unknown as SubagentProgress);
+ expect(rememberedSubagentChildCalls(key, new Set(['segment-evicted']))).toEqual([
+ { id: 'segment-evicted' },
+ ]);
+ removeSubagentProgressAtoms(key);
+ });
+
it('keeps only the newest bounded activity and continues folding afterward', () => {
const toolEvents = Array.from({ length: 120 }, (_, index) =>
update({
diff --git a/client/src/components/Chat/Subagents/state.ts b/client/src/components/Chat/Subagents/state.ts
index 32408157c7..4f599186e7 100644
--- a/client/src/components/Chat/Subagents/state.ts
+++ b/client/src/components/Chat/Subagents/state.ts
@@ -3,6 +3,7 @@ import { atomFamily } from 'jotai/utils';
import { atom, useAtomValue, useStore } from 'jotai';
import { ContentTypes, getToolTimingDurations } from 'librechat-data-provider';
import type {
+ Agents,
PartMetadata,
SubagentControlReceipt,
SubagentControlRequest,
@@ -99,6 +100,8 @@ const MAX_RECENT_EVENT_KEYS = 256;
const MAX_PENDING_SEQUENCE_EVENTS = 100;
const MAX_PENDING_SEQUENCE_BYTES = 128 * 1024;
const MAX_LIVE_ACTIVITY_ITEMS = 100;
+/** Evicted child calls kept per invocation for routing their files. */
+const MAX_EVICTED_TOOL_CALLS = 500;
const MAX_LIVE_ACTIVITY_BYTES = 64 * 1024;
const MAX_SINGLE_ACTIVITY_ENCODED_BYTES = MAX_LIVE_ACTIVITY_BYTES - 2;
const MAX_SINGLE_ACTIVITY_TEXT_BYTES = 60 * 1024;
@@ -205,6 +208,7 @@ const boundSingletonPart = (part: SubagentContentPart): SubagentContentPart => {
const boundContentParts = (
parts: SubagentContentPart[],
state: SubagentAggregatorState,
+ ownerAgentId?: string,
): { parts: SubagentContentPart[]; state: SubagentAggregatorState } => {
const start = Math.max(0, parts.length - MAX_LIVE_ACTIVITY_ITEMS);
let offset = parts.length;
@@ -235,6 +239,8 @@ const boundContentParts = (
part.type === ContentTypes.TOOL_CALL ? [[part.tool_call.id, index]] : [],
),
);
+ const dropped = bounded.length === 0 ? parts : parts.slice(0, offset);
+ const evicted = collectNestedCalls(dropped, [], ownerAgentId);
return {
parts: bounded,
state: {
@@ -242,6 +248,13 @@ const boundContentParts = (
openTextIdx: rebase(state.openTextIdx),
openThinkIdx: rebase(state.openThinkIdx),
toolCallIndexById,
+ ...(evicted.length === 0
+ ? {}
+ : {
+ evictedToolCalls: [...(state.evictedToolCalls ?? []), ...evicted].slice(
+ -MAX_EVICTED_TOOL_CALLS,
+ ),
+ }),
},
};
};
@@ -476,10 +489,95 @@ export const subagentControlStateByTask = atomFamily<
/** Stable identity for one subagent invocation in the parent conversation. */
export { subagentProgressKey } from '@librechat/chat';
-/** Progress state keyed by one concrete tool-call content-part occurrence. */
-export const subagentProgressByToolCallId = atomFamily((_key: string) =>
- atom<SubagentProgress | null>(null),
-);
+type NestedToolCallFields = {
+ id?: string;
+ name?: string;
+ stepId?: string;
+ agentId?: string;
+ subagentIdentity?: { subagentAgentId?: string };
+ subagent_content?: TMessageContentParts[];
+ subagentAttachmentCalls?: Agents.SubagentAttachmentCall[];
+};
+
+/** The tool call of a content part, read with the fields nested runs carry. */
+export const nestedToolCallOf = (
+ part: TMessageContentParts | SubagentContentPart | undefined,
+): NestedToolCallFields | undefined =>
+ part?.type === ContentTypes.TOOL_CALL
+ ? (part[ContentTypes.TOOL_CALL] as NestedToolCallFields | undefined)
+ : undefined;
+
+/**
+ * The tool calls of a subagent transcript, nested runs included, with their
+ * scope: the owner on the part, or on the call when the part has none, or the
+ * agent of the run the call belongs to (`ownerAgentId` for `parts` itself, the
+ * stored `subagentIdentity` of each nested run). A preview that left a
+ * transcript out names the calls its files were saved under in
+ * `subagentAttachmentCalls`.
+ */
+export function collectNestedCalls(
+ parts: ReadonlyArray<TMessageContentParts | SubagentContentPart | undefined> | undefined,
+ calls: Agents.SubagentAttachmentCall[] = [],
+ ownerAgentId?: string,
+): Agents.SubagentAttachmentCall[] {
+ /** An explicit stack, in transcript order: stored chains can nest thousands deep. Each level
+ * carries the agent of the run it belongs to, for parts that do not stamp their own. */
+ const stack: Array<
+ [ReadonlyArray<TMessageContentParts | SubagentContentPart | undefined>, number, string?]
+ > = parts == null ? [] : [[parts, 0, ownerAgentId]];
+ while (stack.length > 0) {
+ const frame = stack[stack.length - 1];
+ const [current, index, levelOwner] = frame;
+ if (index >= current.length) {
+ stack.pop();
+ continue;
+ }
+ frame[1] = index + 1;
+ const part = current[index];
+ const toolCall = nestedToolCallOf(part);
+ if (toolCall?.id) {
+ const agentId =
+ (part as { agentId?: string } | undefined)?.agentId ?? toolCall.agentId ?? levelOwner;
+ calls.push({
+ id: toolCall.id,
+ ...(agentId == null ? {} : { agentId }),
+ ...(toolCall.stepId == null ? {} : { stepId: toolCall.stepId }),
+ });
+ }
+ calls.push(...(toolCall?.subagentAttachmentCalls ?? []));
+ if (Array.isArray(toolCall?.subagent_content)) {
+ stack.push([toolCall.subagent_content, 0, toolCall.subagentIdentity?.subagentAgentId]);
+ }
+ }
+ return calls;
+}
+
+/**
+ * Progress state keyed by one concrete tool-call content-part occurrence. Every write also
+ * records the child tool calls the activity shows (`rememberSubagentChildCalls`), whether or not
+ * anything reads the member, since the bounded activity can evict a call that saved a file
+ * before a reader mounts.
+ */
+export const subagentProgressByToolCallId = atomFamily((key: string) => {
+ const progress = atom<SubagentProgress | null>(null);
+ return atom(
+ (get) => get(progress),
+ (get, set, next: SetStateAction<SubagentProgress | null>) => {
+ const value = typeof next === 'function' ? next(get(progress)) : next;
+ if (value != null) {
+ const segments = [value, ...(value.replaySegments ?? []).map(({ progress }) => progress)];
+ rememberSubagentChildCalls(
+ key,
+ segments.flatMap((segment) => [
+ ...(segment.aggregatorState?.evictedToolCalls ?? []),
+ ...collectNestedCalls(segment.contentParts, [], segment.subagentAgentId),
+ ]),
+ );
+ }
+ set(progress, value);
+ },
+ );
+});
/** Parent delivery remains authoritative until its ordered SSE close boundary. */
export const subagentParentStreamOpenByToolCallId = atomFamily((_key: string) => atom(false));
@@ -507,11 +605,57 @@ export function listRegisteredSubagentProgressKeys(): string[] {
return [...registeredSubagentProgressKeys];
}
+/**
+ * Child tool calls each invocation's live activity has shown, kept with the invocation rather
+ * than a reader: the bounded activity evicts early parts, and a reader that remounts after that
+ * still has to route the files those calls saved. Freed with the invocation's members.
+ */
+const seenSubagentChildCalls = new Map<string, Map<string, Agents.SubagentAttachmentCall>>();
+
+/**
+ * Adds `calls` to what the invocation has shown, keeping the most recent `MAX_EVICTED_TOOL_CALLS`
+ * like the eviction list it is fed from. A call already remembered keeps its place, since every
+ * write replays the eviction list; `refresh` moves the given calls to the newest end instead, for
+ * the owners of files a message shows.
+ */
+export function rememberSubagentChildCalls(
+ invocationKey: string,
+ calls: Agents.SubagentAttachmentCall[],
+ refresh = false,
+): void {
+ if (calls.length === 0) return;
+ const seen = seenSubagentChildCalls.get(invocationKey) ?? new Map();
+ for (const call of calls) {
+ const identity = [call.id, call.agentId ?? '', call.stepId ?? ''].join('\u0000');
+ if (seen.has(identity)) {
+ if (!refresh) continue;
+ seen.delete(identity);
+ }
+ seen.set(identity, call);
+ }
+ for (const identity of seen.keys()) {
+ if (seen.size <= MAX_EVICTED_TOOL_CALLS) break;
+ seen.delete(identity);
+ }
+ seenSubagentChildCalls.set(invocationKey, seen);
+}
+
+/** The remembered child calls of an invocation whose id is in `ids`. */
+export function rememberedSubagentChildCalls(
+ invocationKey: string,
+ ids: ReadonlySet<string>,
+): Agents.SubagentAttachmentCall[] {
+ const seen = seenSubagentChildCalls.get(invocationKey);
+ if (seen == null || ids.size === 0) return [];
+ return [...seen.values()].filter((call) => ids.has(call.id));
+}
+
/** Frees idle invocation members; mounted readers retain their stream identity. */
export function removeSubagentProgressAtoms(invocationKey: string): void {
if (subagentProgressReaders.has(invocationKey)) return;
subagentProgressByToolCallId.remove(invocationKey);
subagentParentStreamOpenByToolCallId.remove(invocationKey);
+ seenSubagentChildCalls.delete(invocationKey);
}
/** How many mounted readers hold each invocation's member. Removing one while
@@ -533,26 +677,29 @@ const subagentProgressReaders = new Map<string, number>();
*/
export function useSubagentProgress(invocationKey: string): SubagentProgress | null {
const store = useStore();
- useEffect(() => {
- subagentProgressReaders.set(
- invocationKey,
- (subagentProgressReaders.get(invocationKey) ?? 0) + 1,
- );
- return () => {
- const remaining = (subagentProgressReaders.get(invocationKey) ?? 1) - 1;
- if (remaining > 0) {
- subagentProgressReaders.set(invocationKey, remaining);
- return;
- }
- subagentProgressReaders.delete(invocationKey);
- if (registeredSubagentProgressKeys.has(invocationKey)) return;
- if (store.get(subagentProgressByToolCallId(invocationKey)) != null) return;
- removeSubagentProgressAtoms(invocationKey);
- };
- }, [invocationKey, store]);
+ useEffect(() => retainSubagentProgress(store, invocationKey), [invocationKey, store]);
return useAtomValue(subagentProgressByToolCallId(invocationKey));
}
+/** Counts one reader of an invocation's member; the returned release applies the rules above. */
+export function retainSubagentProgress(
+ store: ReturnType<typeof useStore>,
+ invocationKey: string,
+): () => void {
+ subagentProgressReaders.set(invocationKey, (subagentProgressReaders.get(invocationKey) ?? 0) + 1);
+ return () => {
+ const remaining = (subagentProgressReaders.get(invocationKey) ?? 1) - 1;
+ if (remaining > 0) {
+ subagentProgressReaders.set(invocationKey, remaining);
+ return;
+ }
+ subagentProgressReaders.delete(invocationKey);
+ if (registeredSubagentProgressKeys.has(invocationKey)) return;
+ if (store.get(subagentProgressByToolCallId(invocationKey)) != null) return;
+ removeSubagentProgressAtoms(invocationKey);
+ };
+}
+
const validActivitySequence = (value: number | undefined): value is number =>
Number.isSafeInteger(value) && value != null && value >= 0;
@@ -682,6 +829,7 @@ const foldAcceptedSubagentEvents = (
({ parts: contentParts, state: aggregatorState } = boundContentParts(
contentParts,
aggregatorState,
+ events[events.length - 1].subagentAgentId ?? previous?.subagentAgentId,
));
tickerState = boundTickerState(tickerState);
const last = events[events.length - 1];
@@ -955,23 +1103,27 @@ function prependSubagentReplay(
} else target = part.type === ContentTypes.TEXT ? state.openTextIdx! : state.openThinkIdx!;
indices.set(index, target);
}
- const bounded = boundContentParts(parts, {
- ...previous.aggregatorState,
- messagePhaseByStepId: inheritMessagePhases
- ? {
- ...prefix.aggregatorState.messagePhaseByStepId,
- ...previous.aggregatorState.messagePhaseByStepId,
- }
- : previous.aggregatorState.messagePhaseByStepId,
- openTextIdx:
- previous.aggregatorState.openTextIdx == null
- ? null
- : (indices.get(previous.aggregatorState.openTextIdx) ?? null),
- openThinkIdx:
- previous.aggregatorState.openThinkIdx == null
- ? null
- : (indices.get(previous.aggregatorState.openThinkIdx) ?? null),
- });
+ const bounded = boundContentParts(
+ parts,
+ {
+ ...previous.aggregatorState,
+ messagePhaseByStepId: inheritMessagePhases
+ ? {
+ ...prefix.aggregatorState.messagePhaseByStepId,
+ ...previous.aggregatorState.messagePhaseByStepId,
+ }
+ : previous.aggregatorState.messagePhaseByStepId,
+ openTextIdx:
+ previous.aggregatorState.openTextIdx == null
+ ? null
+ : (indices.get(previous.aggregatorState.openTextIdx) ?? null),
+ openThinkIdx:
+ previous.aggregatorState.openThinkIdx == null
+ ? null
+ : (indices.get(previous.aggregatorState.openThinkIdx) ?? null),
+ },
+ previous.subagentAgentId,
+ );
const offset = prefix.tickerState.lines.length;
return {
...previous,
@@ -1270,7 +1422,7 @@ function reconcileReplayTiming(
const bounded =
parts === progress.contentParts
? { parts, state: phased.state }
- : boundContentParts(parts, phased.state);
+ : boundContentParts(parts, phased.state, progress.subagentAgentId);
return {
...progress,
contentParts: bounded.parts,
diff --git a/client/src/utils/subagentContent.ts b/client/src/utils/subagentContent.ts
index 4dea780034..57321d2013 100644
--- a/client/src/utils/subagentContent.ts
+++ b/client/src/utils/subagentContent.ts
@@ -178,6 +178,11 @@ export interface SubagentAggregatorState {
idlessTextPhase?: AssistantTextPhase;
/** `tool_call.id` → its index in `contentParts` for O(1) updates. */
toolCallIndexById: Record<string, number>;
+ /**
+ * Tool calls bounding dropped from `contentParts`, with their scope, so the
+ * files they saved keep an owner after their parts are gone. Bounded too.
+ */
+ evictedToolCalls?: Array<{ id: string; agentId?: string; stepId?: string }>;
}
/** Initial empty aggregator state. */
diff --git a/e2e/specs/mock/scenarios/subagent-nested-images.spec.ts b/e2e/specs/mock/scenarios/subagent-nested-images.spec.ts
new file mode 100644
index 0000000000..26fabacde4
--- /dev/null
+++ b/e2e/specs/mock/scenarios/subagent-nested-images.spec.ts
@@ -0,0 +1,139 @@
+import { expect, test } from '@playwright/test';
+import { randomUUID } from 'node:crypto';
+import type { SeedMessage } from '../db';
+import {
+ seedMessages,
+ seedConversations,
+ deleteConversations,
+ deleteMessagesByConversation,
+} from '../db';
+import { getE2EUser } from '../../../setup/user';
+
+const NO_PARENT = '00000000-0000-0000-0000-000000000000';
+/** 8x8 opaque PNG, enough for the browser to decode the image. */
+const PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEUlEQVR4nGO4o6aGFTEMLQkAF/tKAS/fz4YAAAAASUVORK5CYII=',
+ 'base64',
+);
+
+const imageAttachment = (conversationId: string, messageId: string, toolCallId: string) => ({
+ file_id: `${toolCallId}-file`,
+ filename: `${toolCallId}.png`,
+ filepath: `/images/e2e-subagent/${toolCallId}.png`,
+ type: 'image/png',
+ source: 'local',
+ bytes: PNG.length,
+ width: 8,
+ height: 8,
+ messageId,
+ conversationId,
+ toolCallId,
+});
+
+const imageToolCall = (id: string) => ({
+ type: 'tool_call',
+ tool_call: { id, name: 'image_gen_oai', args: '{}', output: 'Image generated', progress: 1 },
+});
+
+/** The subagent's own tool calls exist only inside `subagent_content`, the shape
+ * the backend persists at save time, so the turn is seeded in that stored shape
+ * and read back through the messages route, whose previews leave the
+ * transcript out of settled subagent calls. */
+test('an image a subagent tool saved renders once under the subagent after reload @scenario:subagent-nested-tool-images-render', async ({
+ page,
+}) => {
+ const conversationId = randomUUID();
+ const userMessageId = randomUUID();
+ const messageId = randomUUID();
+ const childCall = `child-image-${conversationId.slice(0, 8)}`;
+ const grandchildCall = `grandchild-image-${conversationId.slice(0, 8)}`;
+ const directCall = `direct-image-${conversationId.slice(0, 8)}`;
+ const messages = [
+ {
+ messageId: userMessageId,
+ parentMessageId: NO_PARENT,
+ isCreatedByUser: true,
+ sender: 'User',
+ text: 'Ask the illustrator for a red cat.',
+ },
+ {
+ messageId,
+ parentMessageId: userMessageId,
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ text: '',
+ content: [
+ {
+ type: 'tool_call',
+ tool_call: {
+ id: `subagent-${conversationId.slice(0, 8)}`,
+ name: 'subagent',
+ args: JSON.stringify({ subagent_type: 'self', description: 'Draw a red cat' }),
+ output: 'The illustrator drew a red cat.',
+ progress: 1,
+ subagent_content: [
+ imageToolCall(childCall),
+ {
+ type: 'tool_call',
+ tool_call: {
+ id: `nested-subagent-${conversationId.slice(0, 8)}`,
+ name: 'subagent',
+ args: JSON.stringify({ subagent_type: 'self', description: 'Add a hat' }),
+ output: 'Added a hat.',
+ progress: 1,
+ subagent_content: [imageToolCall(grandchildCall)],
+ },
+ },
+ ],
+ },
+ },
+ imageToolCall(directCall),
+ { type: 'text', text: 'Here is the red cat.' },
+ ],
+ attachments: [
+ imageAttachment(conversationId, messageId, childCall),
+ imageAttachment(conversationId, messageId, grandchildCall),
+ imageAttachment(conversationId, messageId, directCall),
+ ],
+ },
+ ] as SeedMessage[];
+
+ await seedConversations(getE2EUser().email, [
+ { conversationId, title: 'Subagent images', updatedAt: new Date() },
+ ]);
+ await seedMessages(getE2EUser().email, conversationId, messages);
+ await page.route('**/images/e2e-subagent/**', (route) =>
+ route.fulfill({ status: 200, contentType: 'image/png', body: PNG }),
+ );
+
+ try {
+ const loaded = page.waitForResponse(
+ (response) =>
+ response.url().includes(`/api/messages/${conversationId}`) && response.status() === 200,
+ );
+ await page.goto(`/c/${conversationId}`);
+ /** The scenario is only meaningful while the route sends the subagent call
+ * as a preview: that is the default load, and the shape that omits the
+ * transcript the child tool calls live in. */
+ expect(JSON.stringify(await (await loaded).json())).toContain('"subagentContentOmitted":true');
+
+ const message = page.locator(`[id="${messageId}"]`);
+ await expect(message.getByText('Here is the red cat.')).toBeVisible();
+ for (const id of [childCall, grandchildCall, directCall]) {
+ const image = message.getByRole('img', { name: `${id}.png`, exact: true });
+ await expect(image).toHaveCount(1);
+ await expect(image).toBeVisible();
+ }
+
+ await page.reload();
+ await expect(message.getByRole('img', { name: `${childCall}.png`, exact: true })).toHaveCount(
+ 1,
+ );
+ await expect(
+ message.getByRole('img', { name: `${grandchildCall}.png`, exact: true }),
+ ).toHaveCount(1);
+ } finally {
+ await deleteMessagesByConversation([conversationId]);
+ await deleteConversations([conversationId]);
+ }
+});
diff --git a/packages/api/src/messages/previews.spec.ts b/packages/api/src/messages/previews.spec.ts
index 2975e7240f..b1017cfc4c 100644
--- a/packages/api/src/messages/previews.spec.ts
+++ b/packages/api/src/messages/previews.spec.ts
@@ -32,6 +32,9 @@ type TestToolCall = {
outputTruncated?: true;
argsTruncated?: true;
subagentContentOmitted?: true;
+ subagentAttachmentCalls?: Array<{ id: string; agentId?: string; stepId?: string }>;
+ agentId?: string;
+ subagentIdentity?: { subagentKind?: string; subagentAgentId?: string };
function?: unknown;
};
@@ -415,6 +418,113 @@ describe('previewMessagesToolCalls', () => {
expect(bigPart.tool_call.output).toHaveLength(10_000);
});
+ it('keeps the nested tool call ids an omitted transcript saved attachments under', () => {
+ const transcript = [
+ toolPart({
+ id: 'child_image',
+ stepId: 'step_child',
+ agentId: 'agent_on_call',
+ output: 'Image generated',
+ }),
+ toolPart({
+ id: 'child_subagent',
+ name: 'subagent',
+ output: 'done',
+ subagent_content: [
+ {
+ ...toolPart({ id: 'grandchild_image', output: 'Image generated' }),
+ agentId: 'agent_grandchild',
+ },
+ toolPart({ id: 'grandchild_search', output: 'found' }),
+ ],
+ }),
+ ];
+ const subagent = toolPart({
+ name: 'subagent',
+ output: 'summary',
+ subagent_content: transcript,
+ });
+ const attachments = [
+ { file_id: 'f1', toolCallId: 'child_image' },
+ { file_id: 'f2', toolCallId: 'grandchild_image' },
+ { file_id: 'f3', toolCallId: 'unrelated' },
+ ];
+ const [message] = previewMessagesToolCalls([{ content: [subagent], attachments }], limits);
+ const [part] = message.content as Array<{ tool_call: TestToolCall }>;
+ expect(part.tool_call).not.toHaveProperty('subagent_content');
+ expect(part.tool_call.subagentAttachmentCalls).toEqual(
+ expect.arrayContaining([
+ { id: 'child_image', stepId: 'step_child', agentId: 'agent_on_call' },
+ { id: 'grandchild_image', agentId: 'agent_grandchild' },
+ ]),
+ );
+ expect(part.tool_call.subagentAttachmentCalls).toHaveLength(2);
+
+ const [bare] = previewMessagesToolCalls([{ content: [subagent] }], limits);
+ const [barePart] = bare.content as Array<{ tool_call: TestToolCall }>;
+ expect(barePart.tool_call).toMatchObject({ subagentContentOmitted: true });
+ expect(barePart.tool_call).not.toHaveProperty('subagentAttachmentCalls');
+ });
+
+ it('keeps one hint per owning identity when a provider reuses a child id', () => {
+ const reused = Array.from({ length: 50 }, (_, index) =>
+ toolPart({ id: 'call_0', stepId: `step_${index}`, output: 'done' }),
+ );
+ const subagent = toolPart({ name: 'subagent', output: 'summary', subagent_content: reused });
+ const [message] = previewMessagesToolCalls(
+ [{ content: [subagent], attachments: [{ toolCallId: 'call_0', stepId: 'step_7' }] }],
+ limits,
+ );
+ const [part] = message.content as Array<{ tool_call: TestToolCall }>;
+ expect(part.tool_call.subagentAttachmentCalls).toEqual([{ id: 'call_0', stepId: 'step_7' }]);
+ });
+
+ it('keeps one hint for an unscoped attachment whatever the id reuse', () => {
+ const reused = Array.from({ length: 50 }, (_, index) =>
+ toolPart({ id: 'call_0', stepId: `step_${index}`, output: 'done' }),
+ );
+ const subagent = toolPart({ name: 'subagent', output: 'summary', subagent_content: reused });
+ const [message] = previewMessagesToolCalls(
+ [{ content: [subagent], attachments: [{ toolCallId: 'call_0' }] }],
+ limits,
+ );
+ const [part] = message.content as Array<{ tool_call: TestToolCall }>;
+ expect(part.tool_call.subagentAttachmentCalls).toHaveLength(1);
+ });
+
+ it('scopes hints to the agent a stored subagent call ran', () => {
+ const subagent = toolPart({
+ name: 'subagent',
+ output: 'summary',
+ subagentIdentity: { subagentKind: 'agent', subagentAgentId: 'agent_child' },
+ subagent_content: [toolPart({ id: 'call_0', output: 'done' })],
+ });
+ const [message] = previewMessagesToolCalls(
+ [{ content: [subagent], attachments: [{ toolCallId: 'call_0', agentId: 'agent_child' }] }],
+ limits,
+ );
+ const [part] = message.content as Array<{ tool_call: TestToolCall }>;
+ expect(part.tool_call.subagentAttachmentCalls).toEqual([
+ { id: 'call_0', agentId: 'agent_child' },
+ ]);
+ });
+
+ it('keeps hints for a mutation response that leaves its attachments out', () => {
+ const subagent = toolPart({
+ name: 'subagent',
+ output: 'summary',
+ subagent_content: [toolPart({ id: 'child_image', output: 'Image generated' })],
+ });
+ const req = { query: { toolPreviews: '1' }, config: {} } as unknown as Parameters<
+ typeof withMessageToolCallPreviews
+ >[0];
+ const response = { conversationId: 'c1', content: [subagent], text: '' };
+ const previewed = withMessageToolCallPreviews(req, response, [{ toolCallId: 'child_image' }]);
+ const [part] = previewed.content as Array<{ tool_call: TestToolCall }>;
+ expect(part.tool_call.subagentAttachmentCalls).toEqual([{ id: 'child_image' }]);
+ expect(previewed).not.toHaveProperty('attachments');
+ });
+
it('previews a call only when its identity is unique in the message', () => {
const repeated = (agentId: string) => ({
...toolPart({ id: 'call_dup', stepId: 'step_1', output: 'o'.repeat(10_000) }),
diff --git a/packages/api/src/messages/previews.ts b/packages/api/src/messages/previews.ts
index a7de540b3f..687a938e07 100644
--- a/packages/api/src/messages/previews.ts
+++ b/packages/api/src/messages/previews.ts
@@ -9,7 +9,11 @@ import {
hasToolCallPreview,
toolCallPreviewsConfigSchema,
} from 'librechat-data-provider';
-import type { TToolCallPreviewsConfig, ToolCallPreviewMarkers } from 'librechat-data-provider';
+import type {
+ Agents,
+ ToolCallPreviewMarkers,
+ TToolCallPreviewsConfig,
+} from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
import type { AppConfigUserLike, GetAppConfigOptions } from '~/app/service';
import { getAppConfigOptionsFromUser } from '~/app/service';
@@ -73,6 +77,9 @@ interface StoredToolCall extends ToolCallPreviewMarkers {
args?: unknown;
approval?: unknown;
subagent_content?: unknown;
+ subagentAttachmentCalls?: Agents.SubagentAttachmentCall[];
+ agentId?: unknown;
+ subagentIdentity?: unknown;
}
interface StoredToolCallPart {
@@ -81,9 +88,10 @@ interface StoredToolCallPart {
tool_call?: StoredToolCall;
}
-/** A message as read for a client; only `content` is inspected. */
+/** A message as read for a client; `content` is previewed and `attachments` only read. */
export interface PreviewableMessage {
content?: unknown[] | null;
+ attachments?: unknown[] | null;
/** Stamped onto each preview as `previewRevision`, so clients key fetched parts to it. */
updatedAt?: Date | string | number | null;
}
@@ -161,6 +169,113 @@ function hasPendingApproval(parts: unknown[]): boolean {
return false;
}
+/** The agent and step scope an attachment was saved with. */
+type AttachmentScope = { agentId?: string; stepId?: string };
+
+/** Each tool call id a message's attachments were saved under, with the scopes saved with it. */
+type AttachmentScopes = ReadonlyMap<string, readonly AttachmentScope[]>;
+
+/** A scope both sides carry must agree: the ownership rule the client applies. */
+const scopeAgrees = (call: AttachmentScope, file: AttachmentScope): boolean =>
+ (call.agentId == null || file.agentId == null || call.agentId === file.agentId) &&
+ (call.stepId == null || file.stepId == null || call.stepId === file.stepId);
+
+/** The agent a stored subagent call ran, from its persisted identity. */
+const runAgentId = (toolCall: StoredToolCall): string | undefined => {
+ const identity = toolCall.subagentIdentity as { subagentAgentId?: unknown } | undefined;
+ return typeof identity?.subagentAgentId === 'string' ? identity.subagentAgentId : undefined;
+};
+
+/** Whether the call carries every scope the attachment does. */
+const scopeMatches = (call: AttachmentScope, file: AttachmentScope): boolean =>
+ (file.agentId == null || call.agentId === file.agentId) &&
+ (file.stepId == null || call.stepId === file.stepId);
+
+/**
+ * Tool calls anywhere in the parts, including inside nested subagent runs, that one of the
+ * message's attachments can belong to, with the agent and step scope a client checks it against.
+ * For each attachment scope only the first call matching it exactly and the first call agreeing
+ * with it are kept (the two a client can choose between), so a reused id, or an attachment with
+ * no scope to narrow it, does not grow the hint with the transcript.
+ */
+function nestedAttachmentCalls(
+ parts: unknown[],
+ wanted: AttachmentScopes,
+ ownerAgentId?: string,
+): Agents.SubagentAttachmentCall[] {
+ const found = new Map<string, Agents.SubagentAttachmentCall>();
+ const exactFor = new Set<AttachmentScope>();
+ const agreeingFor = new Set<AttachmentScope>();
+ /** Each level carries the agent of the run it belongs to, for parts that do not stamp one. */
+ const stack: Array<[unknown[], string | undefined]> = [[parts, ownerAgentId]];
+ while (stack.length > 0) {
+ const [current, levelOwner] = stack.pop() ?? [[], undefined];
+ for (const part of current) {
+ if (!isToolCallPart(part)) {
+ continue;
+ }
+ const { id, stepId, subagent_content } = part.tool_call;
+ const scopes = typeof id === 'string' ? wanted.get(id) : undefined;
+ if (scopes != null) {
+ /** The owner is stored on the part, on the call, or on the run that holds it. */
+ const owner = part.agentId ?? part.tool_call.agentId ?? levelOwner;
+ const call: Agents.SubagentAttachmentCall = {
+ id: id as string,
+ ...(typeof owner === 'string' ? { agentId: owner } : {}),
+ ...(typeof stepId === 'string' ? { stepId } : {}),
+ };
+ let useful = false;
+ for (const scope of scopes) {
+ if (!exactFor.has(scope) && scopeMatches(call, scope)) {
+ exactFor.add(scope);
+ useful = true;
+ }
+ if (!agreeingFor.has(scope) && scopeAgrees(call, scope)) {
+ agreeingFor.add(scope);
+ useful = true;
+ }
+ }
+ const identity = [call.id, call.agentId ?? '', call.stepId ?? ''].join('\u0000');
+ if (useful && !found.has(identity)) {
+ found.set(identity, call);
+ }
+ }
+ if (Array.isArray(subagent_content)) {
+ stack.push([subagent_content, runAgentId(part.tool_call)]);
+ }
+ }
+ }
+ return [...found.values()];
+}
+
+/** The tool call ids a message's attachments were saved under, with their scopes. */
+function attachmentToolCallIds(message: PreviewableMessage): AttachmentScopes | undefined {
+ if (!Array.isArray(message.attachments) || message.attachments.length === 0) {
+ return undefined;
+ }
+ const scopes = new Map<string, AttachmentScope[]>();
+ for (const attachment of message.attachments) {
+ if (!isObject(attachment)) {
+ continue;
+ }
+ const { toolCallId, agentId, stepId } = attachment as {
+ toolCallId?: unknown;
+ agentId?: unknown;
+ stepId?: unknown;
+ };
+ if (typeof toolCallId !== 'string' || toolCallId === '') {
+ continue;
+ }
+ const entries = scopes.get(toolCallId) ?? [];
+ entries.push({
+ ...(typeof agentId === 'string' ? { agentId } : {}),
+ ...(typeof stepId === 'string' ? { stepId } : {}),
+ });
+ scopes.set(toolCallId, entries);
+ }
+ return scopes.size > 0 ? scopes : undefined;
+}
+
/** Cuts at `end` without splitting a surrogate pair. */
function sliceStart(text: string, end: number): string {
const code = text.charCodeAt(end - 1);
@@ -444,12 +559,15 @@ export function previewToolCallOutput(
/**
* Returns the tool call with long content replaced by previews, or the same object when nothing
* needed shortening. Only settled calls change: a call still waiting on output, approval or a
- * reader's answer keeps every field, since its card acts on them.
+ * reader's answer keeps every field, since its card acts on them. When the subagent transcript is
+ * left out, its tool calls that `attachmentIds` names stay on the call with their scope, so the
+ * files those calls saved still route to it before the transcript loads.
*/
export function previewToolCall<T extends StoredToolCall>(
toolCall: T,
limits: ToolCallPreviewLimits,
revision = '',
+ attachmentIds?: AttachmentScopes,
): T {
if (!isAgentToolCall(toolCall) || !isSettled(toolCall) || !hasIdentity(toolCall)) {
return toolCall;
@@ -486,6 +604,13 @@ export function previewToolCall<T extends StoredToolCall>(
delete next.subagent_content;
next.subagentContentOmitted = true;
next.subagentContentParts = (subagentContent as unknown[]).length;
+ const childCalls =
+ attachmentIds == null
+ ? []
+ : nestedAttachmentCalls(subagentContent as unknown[], attachmentIds, runAgentId(toolCall));
+ if (childCalls.length > 0) {
+ next.subagentAttachmentCalls = childCalls;
+ }
}
if (revision !== '') {
next.previewRevision = revision;
@@ -501,9 +626,10 @@ function previewToolCallSafely<T extends StoredToolCall>(
toolCall: T,
limits: ToolCallPreviewLimits,
revision: string,
+ attachmentIds?: AttachmentScopes,
): T {
try {
- return previewToolCall(toolCall, limits, revision);
+ return previewToolCall(toolCall, limits, revision, attachmentIds);
} catch (error) {
logger.warn('[toolCallPreviews] Sending a tool call in full; its preview failed', error);
return toolCall;
@@ -515,6 +641,7 @@ export function previewContentToolCalls(
content: unknown[],
limits: ToolCallPreviewLimits,
revision = '',
+ attachmentIds?: AttachmentScopes,
): unknown[] {
let result: unknown[] | undefined;
/** First index of each identity; a repeat sends both calls whole (see `toolCallIdentity`). */
@@ -537,7 +664,7 @@ export function previewContentToolCalls(
continue;
}
firstIndex.set(identity, i);
- const toolCall = previewToolCallSafely(part.tool_call, limits, revision);
+ const toolCall = previewToolCallSafely(part.tool_call, limits, revision, attachmentIds);
if (toolCall === part.tool_call) {
continue;
}
@@ -566,7 +693,12 @@ export function previewMessagesToolCalls<T extends PreviewableMessage>(
if (!Array.isArray(message?.content)) {
continue;
}
- const content = previewContentToolCalls(message.content, limits, messageRevision(message));
+ const content = previewContentToolCalls(
+ message.content,
+ limits,
+ messageRevision(message),
+ attachmentToolCallIds(message),
+ );
if (content === message.content) {
continue;
}
@@ -713,16 +845,28 @@ export function withToolCallPreviews<T extends MessagesResult>(
/**
* Previews one message a mutation returns (an artifact edit's content, a branched response), so
- * a client that asked for previews merges a bounded copy into its conversation cache.
+ * a client that asked for previews merges a bounded copy into its conversation cache. A response
+ * that leaves out the stored `attachments` passes them separately: they only decide which
+ * subagent child calls the preview keeps as hints, and are not added to the response.
*/
export function withMessageToolCallPreviews<T extends PreviewableMessage>(
req: PreviewableResultRequest,
message: T,
+ attachments?: unknown[] | null,
): T {
if (message == null || !Array.isArray(message.content)) {
return message;
}
- return withToolCallPreviews(req, { messages: [message] }).messages[0];
+ if (attachments == null || message.attachments != null) {
+ return withToolCallPreviews(req, { messages: [message] }).messages[0];
+ }
+ const withAttachments = { ...message, attachments };
+ const previewed = withToolCallPreviews(req, { messages: [withAttachments] }).messages[0];
+ if (previewed === withAttachments) {
+ return message;
+ }
+ const { attachments: _attachments, ...rest } = previewed;
+ return rest as T;
}
interface MessageWriteRequest {
diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts
index de003cb03e..40af340a87 100644
--- a/packages/data-provider/src/types/agents.ts
+++ b/packages/data-provider/src/types/agents.ts
@@ -83,6 +83,9 @@ export namespace Agents {
/**
* A call to a tool.
*/
+ /** A tool call inside a subagent transcript, with the scope its saved files may carry. */
+ export type SubagentAttachmentCall = { id: string; agentId?: string; stepId?: string };
+
export type ToolCall = {
/** Type ("tool_call") according to Assistants Tool Call Structure; optional literal
* form included to mirror langchain's ToolCall, whose `type` is optional. */
@@ -133,6 +136,10 @@ export namespace Agents {
subagentContentOmitted?: true;
/** Number of top-level parts in the omitted `subagent_content`. */
subagentContentParts?: number;
+ /** Tool calls inside the omitted `subagent_content` that the message's attachments were
+ * saved under, with their scope, so those files still route to this call before the
+ * transcript loads. */
+ subagentAttachmentCalls?: SubagentAttachmentCall[];
/** When the stored message last changed, set on previews so a client cache of the full part
* is keyed to the stored version it came from. */
previewRevision?: string;