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: Route Subagent Files Delivered After a Mid-Run Reload (#17212)

Marco Beretta54b887a1eced
diff --git a/api/server/routes/__tests__/messages-content-edit.spec.js b/api/server/routes/__tests__/messages-content-edit.spec.js
index 16bc075022..f985707624 100644
--- a/api/server/routes/__tests__/messages-content-edit.spec.js
+++ b/api/server/routes/__tests__/messages-content-edit.spec.js
@@ -9,6 +9,7 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
unescapeLaTeX: jest.fn((value) => value),
diff --git a/api/server/routes/__tests__/messages-delete.spec.js b/api/server/routes/__tests__/messages-delete.spec.js
index 6dfe494d65..ac157a4359 100644
--- a/api/server/routes/__tests__/messages-delete.spec.js
+++ b/api/server/routes/__tests__/messages-delete.spec.js
@@ -11,6 +11,7 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
createPrivateTextView: jest.fn(() => (_req, _res, next) => next()),
diff --git a/api/server/routes/__tests__/messages-feedback.spec.js b/api/server/routes/__tests__/messages-feedback.spec.js
index 0f2abc5557..4858e752ca 100644
--- a/api/server/routes/__tests__/messages-feedback.spec.js
+++ b/api/server/routes/__tests__/messages-feedback.spec.js
@@ -8,6 +8,7 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
unescapeLaTeX: jest.fn((value) => value),
diff --git a/api/server/routes/__tests__/messages-get-real-validation.spec.js b/api/server/routes/__tests__/messages-get-real-validation.spec.js
index fc2e02a21a..ba6c941432 100644
--- a/api/server/routes/__tests__/messages-get-real-validation.spec.js
+++ b/api/server/routes/__tests__/messages-get-real-validation.spec.js
@@ -23,6 +23,7 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
createPrivateTextView: jest.fn(() => (_req, _res, next) => next()),
diff --git a/api/server/routes/__tests__/messages-get.spec.js b/api/server/routes/__tests__/messages-get.spec.js
index 401b6a049f..24069625e2 100644
--- a/api/server/routes/__tests__/messages-get.spec.js
+++ b/api/server/routes/__tests__/messages-get.spec.js
@@ -53,6 +53,7 @@ jest.mock('@librechat/api', () => {
return {
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
/** The real helper, without loading the rest of the package this suite mocks around. */
diff --git a/api/server/routes/__tests__/messages-retention.spec.js b/api/server/routes/__tests__/messages-retention.spec.js
index 6aef3dbca9..28b2be82c6 100644
--- a/api/server/routes/__tests__/messages-retention.spec.js
+++ b/api/server/routes/__tests__/messages-retention.spec.js
@@ -9,6 +9,7 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
createPrivateTextView: jest.fn(() => (_req, _res, next) => next()),
diff --git a/api/server/routes/__tests__/messages-subagent-thread.spec.js b/api/server/routes/__tests__/messages-subagent-thread.spec.js
index 432eed0d7e..7d55c47897 100644
--- a/api/server/routes/__tests__/messages-subagent-thread.spec.js
+++ b/api/server/routes/__tests__/messages-subagent-thread.spec.js
@@ -8,6 +8,7 @@ jest.mock('@librechat/agents', () => ({ sleep: jest.fn() }));
jest.mock('@librechat/api', () => ({
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
withoutTraceRefs: jest.fn((message) => message),
diff --git a/api/server/routes/__tests__/messages-tool-previews.spec.js b/api/server/routes/__tests__/messages-tool-previews.spec.js
index 4d58bb9883..0043c68609 100644
--- a/api/server/routes/__tests__/messages-tool-previews.spec.js
+++ b/api/server/routes/__tests__/messages-tool-previews.spec.js
@@ -219,6 +219,41 @@ describe('tool-call previews on the message routes', () => {
expect(message.content[1].tool_call.outputTruncated).toBe(true);
});
+ const subagentCallsUrl = (convo, message, files) =>
+ `/api/messages/${convo}/${message}/subagent-calls?files=${encodeURIComponent(JSON.stringify(files))}`;
+
+ it('names the subagent child calls queried files belong to, to the owner only', async () => {
+ const url = subagentCallsUrl(conversationId, responseId, [
+ { toolCallId: 'child_1' },
+ { toolCallId: 'not-in-any-transcript' },
+ ]);
+ const owner = await request(app).get(url);
+ expect(owner.status).toBe(200);
+ expect(owner.body).toEqual({
+ parts: [{ toolCallId: 'call_sub', agentId: 'agent_a', calls: [{ id: 'child_1' }] }],
+ });
+ expect(JSON.stringify(owner.body)).not.toContain('child is reading');
+
+ expect((await request(app).get(url).set('x-user', OTHER)).status).toBe(404);
+ });
+
+ it('refuses a malformed or oversized files query', async () => {
+ const base = `/api/messages/${conversationId}/${responseId}/subagent-calls`;
+ expect((await request(app).get(base)).status).toBe(400);
+ expect((await request(app).get(`${base}?files=not-json`)).status).toBe(400);
+ expect((await request(app).get(subagentCallsUrl(conversationId, responseId, []))).status).toBe(
+ 400,
+ );
+ const many = Array.from({ length: 33 }, (_, i) => ({ toolCallId: `c${i}` }));
+ expect(
+ (await request(app).get(subagentCallsUrl(conversationId, responseId, many))).status,
+ ).toBe(400);
+ expect(
+ (await request(app).get(subagentCallsUrl(conversationId, responseId, [{ toolCallId: 7 }])))
+ .status,
+ ).toBe(400);
+ });
+
it('serves the full part to its owner and nobody else', async () => {
const url = `/api/messages/${conversationId}/${responseId}/parts/1?toolCallId=call_bash&agentId=agent_a`;
const owner = await request(app).get(url);
@@ -267,6 +302,12 @@ describe('tool-call previews on the message routes', () => {
const part = await request(app).get(partUrl());
expect(part.status).toBe(200);
expect(part.body.tool_call.output).toBe(fullOutput);
+
+ const owners = await request(app).get(
+ subagentCallsUrl(liveConversationId, 'live-response', [{ toolCallId: 'child_1' }]),
+ );
+ expect(owners.status).toBe(200);
+ expect(owners.body.parts[0].calls).toEqual([{ id: 'child_1' }]);
});
it("refuses another user's job and a job from another tenant", async () => {
diff --git a/api/server/routes/__tests__/messages-update.spec.js b/api/server/routes/__tests__/messages-update.spec.js
index 8ff14345bf..dc19ffaccd 100644
--- a/api/server/routes/__tests__/messages-update.spec.js
+++ b/api/server/routes/__tests__/messages-update.spec.js
@@ -9,6 +9,7 @@ jest.mock('@librechat/agents', () => ({
jest.mock('@librechat/api', () => ({
prepareToolCallPreviews: jest.fn(() => (messages) => Promise.resolve(messages)),
createToolCallPartHandler: jest.fn(() => (_req, res) => res.status(404).end()),
+ createSubagentAttachmentCallsHandler: jest.fn(() => (_req, res) => res.status(404).end()),
rejectToolCallPreviewWrites: (_req, _res, next) => next(),
withMessageToolCallPreviews: (_req, message) => message,
createPrivateTextView: jest.fn(() => (_req, _res, next) => next()),
diff --git a/api/server/routes/messages.js b/api/server/routes/messages.js
index eba5900a89..851f8b8dae 100644
--- a/api/server/routes/messages.js
+++ b/api/server/routes/messages.js
@@ -32,6 +32,7 @@ const {
applyForcedRetention,
prepareToolCallPreviews,
createToolCallPartHandler,
+ createSubagentAttachmentCallsHandler,
rejectToolCallPreviewWrites,
withMessageToolCallPreviews,
} = require('@librechat/api');
@@ -72,6 +73,11 @@ const readToolCallPart = createToolCallPartHandler({
validate: (req) => createMessageRequestValidation(req, { activeJobMessageRead: true }),
sendValidationResponse: (res, result) => sendValidationResponse(res, result),
});
+const readSubagentAttachmentCalls = createSubagentAttachmentCallsHandler({
+ getMessages: db.getMessages,
+ validate: (req) => createMessageRequestValidation(req, { activeJobMessageRead: true }),
+ sendValidationResponse: (res, result) => sendValidationResponse(res, result),
+});
const messageMutationMiddleware = [validateMessageReq, configMiddleware];
const storedMessageMutationMiddleware = [
validateMessageReq,
@@ -632,6 +638,7 @@ router.get('/:conversationId/:messageId', validateMessageReq, async (req, res) =
});
router.get('/:conversationId/:messageId/parts/:partIndex', readToolCallPart);
+router.get('/:conversationId/:messageId/subagent-calls', readSubagentAttachmentCalls);
router.put('/:conversationId/:messageId', messageMutationMiddleware, async (req, res) => {
try {
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index 9d528346b7..cc15fa81aa 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -2,6 +2,7 @@ import { memo, useRef, useMemo, useEffect, useCallback, useContext, Fragment } f
import { useStore } from 'jotai';
import { Constants, ContentTypes, Tools } from 'librechat-data-provider';
import type {
+ SubagentAttachmentFile,
TMessageContentParts,
SearchResultData,
TAttachment,
@@ -9,6 +10,7 @@ import type {
} from 'librechat-data-provider';
import type { ReactNode, ReactElement } from 'react';
import type { ReasoningDisclosures, ToolDisclosures } from './disclosure';
+import type { NestedCall } from '~/components/Chat/Subagents/attachments';
import type { ToolCallGroupExpansionState } from './ToolCallGroup';
import type { ActivityPhaseSegment } from '~/utils/activityLabels';
import type { MCPAppResourceOccurrence } from '~/utils/mcpApps';
@@ -16,6 +18,7 @@ import {
assignNestedAttachments,
useLiveSubagentToolCalls,
SubagentAttachmentsContext,
+ useStoredSubagentHints,
selectExactlyNestedAttachments,
selectUnclaimedAttachments,
} from '~/components/Chat/Subagents/attachments';
@@ -238,8 +241,10 @@ const collectClaimedAttachments = (
content: Array<TMessageContentParts | undefined> | undefined,
attachments: TAttachment[],
reserved: ReadonlySet<TAttachment>,
-): ReadonlySet<TAttachment> => {
+): { claimed: ReadonlySet<TAttachment>; exact: ReadonlySet<TAttachment> } => {
const claimed = new Set<TAttachment>();
+ /** Claimed by a part carrying the file's full scope, not only by a part missing some of it. */
+ const exact = new Set<TAttachment>();
const attachmentMap = mapAttachments(attachments);
const owners = buildToolCallStepOwners(content);
for (const part of content ?? []) {
@@ -253,13 +258,17 @@ const collectClaimedAttachments = (
getSiblingStepIds(part, owners),
);
for (const attachment of accepted ?? []) {
- if (reserved.has(attachment) && !carriesScopeOf(part, attachment)) {
+ const scoped = carriesScopeOf(part, attachment);
+ if (reserved.has(attachment) && !scoped) {
continue;
}
claimed.add(attachment);
+ if (scoped) {
+ exact.add(attachment);
+ }
}
}
- return claimed;
+ return { claimed, exact };
};
/** Whether the part carries every agent and step scope the attachment does. */
@@ -271,6 +280,28 @@ const carriesScopeOf = (part: TMessageContentParts, attachment: TAttachment): bo
);
};
+/**
+ * The subagent call part each tool attachment no top-level part accepts goes to, given the child
+ * calls each subagent part holds outside its stored transcript. `inDoubt` lists the files no call
+ * owns under their full scope, top-level or nested: one taken only by a call missing some of its
+ * scope may belong to a child call of a transcript the preview left out.
+ */
+const routeNestedAttachments = (
+ content: Array<TMessageContentParts | undefined> | undefined,
+ attachments: TAttachment[],
+ calls: ReadonlyMap<number, NestedCall[]>,
+) => {
+ const reserved = selectExactlyNestedAttachments(content, attachments, calls);
+ const { claimed, exact } = collectClaimedAttachments(content, attachments, reserved);
+ const unclaimed = selectUnclaimedAttachments(attachments, claimed);
+ const nested = assignNestedAttachments(content, unclaimed, calls);
+ const inDoubt = attachments.filter(
+ (attachment) =>
+ attachment.toolCallId != null && !exact.has(attachment) && !reserved.has(attachment),
+ );
+ return { nested, inDoubt };
+};
+
const PartWithContext = memo(function PartWithContext({
part,
idx,
@@ -1537,24 +1568,47 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
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]);
+ const inlineAttachments = useMemo(
+ () => partitionWorkspaceChanges(attachments).inlineAttachments,
+ [attachments],
+ );
+ const liveRouting = useMemo(
+ () => routeNestedAttachments(props.content, inlineAttachments, liveSubagentToolCalls),
+ [props.content, inlineAttachments, liveSubagentToolCalls],
+ );
+ /** A file no part owns under its full scope may belong to a child call of a previewed subagent
+ * run whose transcript was left out, such as one a background task delivered after this load. */
+ const filesInDoubt = useMemo(() => {
+ const files = new Map<string, SubagentAttachmentFile>();
+ for (const file of liveRouting.inDoubt) {
+ const { toolCallId, agentId, stepId } = file as SubagentAttachmentFile;
+ const entry = {
+ toolCallId,
+ ...(agentId != null ? { agentId } : {}),
+ ...(stepId != null ? { stepId } : {}),
+ };
+ files.set(JSON.stringify(entry), entry);
+ }
+ return [...files.keys()].sort().map((key) => files.get(key) as SubagentAttachmentFile);
+ }, [liveRouting]);
+ const storedSubagentHints = useStoredSubagentHints(
+ props.content,
+ filesInDoubt,
+ conversationId,
+ messageId,
+ );
/** 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],
- );
+ const nestedAttachments = useMemo(() => {
+ if (storedSubagentHints.size === 0) {
+ return liveRouting.nested;
+ }
+ const calls = new Map(liveSubagentToolCalls);
+ for (const [index, stored] of storedSubagentHints) {
+ calls.set(index, [...(calls.get(index) ?? []), ...stored]);
+ }
+ return routeNestedAttachments(props.content, inlineAttachments, calls).nested;
+ }, [props.content, inlineAttachments, liveRouting, liveSubagentToolCalls, storedSubagentHints]);
return (
<MessageContext.Provider value={messageContext}>
<MediaContext.Provider value={media}>
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx
index d3568986b6..93b120e779 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx
@@ -12,6 +12,11 @@ import { FOLD_GLYPH_CLASS } from '../rows';
import { litFoldPath } from '../rail';
import { Text } from '../Parts';
+/** No previewed subagent run here leaves a file in doubt, so no owner is ever asked for. */
+jest.mock('~/data-provider', () => ({
+ useSubagentAttachmentCallsQueries: () => [],
+}));
+
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, values?: Record<string | number, string>) => {
if (key === 'com_ui_ran_n_actions') {
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 88247df732..ca566a3106 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -170,6 +170,18 @@ jest.mock('../Part', () => {
};
});
+/** What the server answers when asked which subagent transcripts hold the files in doubt. */
+let mockOwners: unknown;
+const mockUseSubagentAttachmentCallsQueries = jest.fn(
+ (params: { files: unknown[] }, enabled: boolean) =>
+ params.files.length === 0 ? [] : [{ data: enabled ? mockOwners : undefined }],
+);
+jest.mock('~/data-provider', () => ({
+ useSubagentAttachmentCallsQueries: (
+ ...args: Parameters<typeof mockUseSubagentAttachmentCallsQueries>
+ ) => mockUseSubagentAttachmentCallsQueries(...args),
+}));
+
jest.mock('../ParallelContent', () => ({
/** Invokes `renderResumeAttribution` per content index like the real
* renderer does for its sequential stretches, so the wiring is testable. */
@@ -775,6 +787,134 @@ describe('ContentParts — activity phase state', () => {
);
});
+ const previewedSubagent = (id: string, extra: Record<string, unknown> = {}) => ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id,
+ name: 'subagent',
+ args: {},
+ output: 'done',
+ progress: 1,
+ subagentContentOmitted: true,
+ subagentContentParts: 1,
+ ...extra,
+ },
+ });
+ const lateFile = (toolCallId: string, filename: string, agentId?: string) =>
+ ({
+ file_id: `${filename}-id`,
+ filename,
+ filepath: `/images/${filename}`,
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ toolCallId,
+ ...(agentId != null ? { agentId } : {}),
+ }) as TAttachment;
+
+ it('asks the server which transcript holds a file a previewed subagent run delivered late', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => [{ type: 'tool-group', parts }]);
+ const content = [previewedSubagent('subagent-reloaded')] as unknown as TMessageContentParts[];
+ mockOwners = {
+ parts: [{ toolCallId: 'subagent-reloaded', calls: [{ id: 'background-child' }] }],
+ };
+ const props = { ...baseProps, conversationId: 'conversation-1', content };
+
+ const { rerender } = render(<ContentParts {...props} attachments={[]} />);
+ expect(mockUseSubagentAttachmentCallsQueries).toHaveBeenLastCalledWith(
+ { conversationId: 'conversation-1', messageId: 'msg-1', files: [] },
+ false,
+ );
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute('data-attachments', '');
+
+ rerender(
+ <ContentParts {...props} attachments={[lateFile('background-child', 'late-chart.png')]} />,
+ );
+ expect(mockUseSubagentAttachmentCallsQueries).toHaveBeenLastCalledWith(
+ {
+ conversationId: 'conversation-1',
+ messageId: 'msg-1',
+ files: [{ toolCallId: 'background-child' }],
+ },
+ true,
+ );
+ expect(screen.getByTestId('tool-call-group')).toHaveAttribute(
+ 'data-attachments',
+ 'late-chart.png',
+ );
+ mockOwners = undefined;
+ });
+
+ it('asks for a scoped late file an unscoped call reusing its id took', () => {
+ jest
+ .mocked(mapAttachments)
+ .mockImplementation(
+ jest.requireActual<typeof import('~/utils/map')>('~/utils/map').mapAttachments,
+ );
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => parts.map((part) => ({ type: 'tool-group', parts: [part] })));
+ const content = [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 'call_0', name: 'search', args: {}, output: 'top' },
+ },
+ previewedSubagent('subagent-reloaded'),
+ ] as unknown as TMessageContentParts[];
+ mockOwners = {
+ parts: [
+ { toolCallId: 'subagent-reloaded', calls: [{ id: 'call_0', agentId: 'child-agent' }] },
+ ],
+ };
+
+ render(
+ <ContentParts
+ {...baseProps}
+ conversationId="conversation-1"
+ content={content}
+ attachments={[lateFile('call_0', 'child-chart.png', 'child-agent')]}
+ />,
+ );
+ expect(mockUseSubagentAttachmentCallsQueries).toHaveBeenCalledWith(
+ expect.objectContaining({ files: [{ toolCallId: 'call_0', agentId: 'child-agent' }] }),
+ true,
+ );
+ const [topLevel, subagentGroup] = screen.getAllByTestId('tool-call-group');
+ expect(topLevel).toHaveAttribute('data-attachments', '');
+ expect(subagentGroup).toHaveAttribute('data-attachments', 'child-chart.png');
+ mockOwners = undefined;
+ });
+
+ it('asks for a scoped late file only an unscoped hint of another subagent matched', () => {
+ jest
+ .mocked(groupSequentialToolCalls)
+ .mockImplementation((parts) => parts.map((part) => ({ type: 'tool-group', parts: [part] })));
+ const content = [
+ previewedSubagent('subagent-a', { subagentAttachmentCalls: [{ id: 'shared' }] }),
+ previewedSubagent('subagent-b'),
+ ] as unknown as TMessageContentParts[];
+ mockOwners = {
+ parts: [
+ { toolCallId: 'subagent-a', calls: [{ id: 'shared' }] },
+ { toolCallId: 'subagent-b', calls: [{ id: 'shared', agentId: 'agent-b' }] },
+ ],
+ };
+
+ render(
+ <ContentParts
+ {...baseProps}
+ conversationId="conversation-1"
+ content={content}
+ attachments={[lateFile('shared', 'b-chart.png', 'agent-b')]}
+ />,
+ );
+ const [first, second] = screen.getAllByTestId('tool-call-group');
+ expect(first).toHaveAttribute('data-attachments', '');
+ expect(second).toHaveAttribute('data-attachments', 'b-chart.png');
+ mockOwners = undefined;
+ });
+
it('hoists files from a grouped subagent run that is still streaming', () => {
jest
.mocked(groupSequentialToolCalls)
diff --git a/client/src/components/Chat/Subagents/attachments.ts b/client/src/components/Chat/Subagents/attachments.ts
index 343c70b64a..fe9ccdfe00 100644
--- a/client/src/components/Chat/Subagents/attachments.ts
+++ b/client/src/components/Chat/Subagents/attachments.ts
@@ -1,7 +1,14 @@
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 {
+ Agents,
+ TAttachment,
+ FullToolCall,
+ TMessageContentParts,
+ SubagentAttachmentFile,
+ SubagentAttachmentCallsResponse,
+} from 'librechat-data-provider';
import type { SubagentContentPart } from '~/utils/subagentContent';
import {
nestedToolCallOf,
@@ -12,6 +19,7 @@ import {
rememberedSubagentChildCalls,
subagentProgressByToolCallId,
} from './state';
+import { useSubagentAttachmentCallsQueries } from '~/data-provider';
export { collectNestedCalls };
import { getPartKeyIndex } from '~/utils/messages';
@@ -252,3 +260,62 @@ export function useLiveSubagentToolCalls(
[signature],
);
}
+
+/** The identity a stored part and its cached preview share. */
+const identityOf = (toolCallId: string, stepId?: string, agentId?: string) =>
+ [toolCallId, stepId ?? '', agentId ?? ''].join('\u0000');
+
+/**
+ * Child calls of the stored transcripts of the previewed subagent calls in `content`, for the
+ * files whose owner is in doubt, keyed by the call's index in `content`. A file a background task
+ * delivers after the message loaded names a child call the cached preview never hinted; while
+ * `files` is not empty, the server is asked (in bounded batches) which transcript holds each.
+ */
+export function useStoredSubagentHints(
+ content: ReadonlyArray<TMessageContentParts | undefined> | undefined,
+ files: SubagentAttachmentFile[],
+ conversationId: string | null | undefined,
+ messageId: string,
+): ReadonlyMap<number, NestedCall[]> {
+ const previewed = useMemo(
+ () =>
+ (content ?? []).some(
+ (part) =>
+ (nestedToolCallOf(part) as FullToolCall | undefined)?.subagentContentOmitted === true,
+ ),
+ [content],
+ );
+ const results = useSubagentAttachmentCallsQueries(
+ { conversationId: conversationId ?? '', messageId, files },
+ previewed && files.length > 0 && !!conversationId && !!messageId,
+ );
+ /** A string, so the routing changes only when an answer does. */
+ const answers = JSON.stringify(results.map((result) => result.data?.parts ?? null));
+ return useMemo(() => {
+ const parts = (
+ JSON.parse(answers) as Array<SubagentAttachmentCallsResponse['parts'] | null>
+ ).flatMap((batch) => batch ?? []);
+ if (parts.length === 0 || !previewed) {
+ return NO_LIVE_CALLS;
+ }
+ const byIdentity = new Map<string, NestedCall[]>();
+ for (const entry of parts) {
+ const identity = identityOf(entry.toolCallId, entry.stepId, entry.agentId);
+ byIdentity.set(identity, [...(byIdentity.get(identity) ?? []), ...entry.calls]);
+ }
+ const byIndex = new Map<number, NestedCall[]>();
+ (content ?? []).forEach((part, index) => {
+ const toolCall = nestedToolCallOf(part) as FullToolCall | undefined;
+ if (toolCall?.subagentContentOmitted !== true || !toolCall.id) {
+ return;
+ }
+ const calls = byIdentity.get(
+ identityOf(toolCall.id, toolCall.stepId, (part as { agentId?: string }).agentId),
+ );
+ if (calls != null) {
+ byIndex.set(index, calls);
+ }
+ });
+ return byIndex.size > 0 ? byIndex : NO_LIVE_CALLS;
+ }, [answers, previewed, content]);
+}
diff --git a/client/src/data-provider/Messages/__tests__/queries.test.ts b/client/src/data-provider/Messages/__tests__/queries.test.ts
index 62c2ffb95b..f2d03217bc 100644
--- a/client/src/data-provider/Messages/__tests__/queries.test.ts
+++ b/client/src/data-provider/Messages/__tests__/queries.test.ts
@@ -1,13 +1,14 @@
import { createElement } from 'react';
import { MemoryRouter } from 'react-router-dom';
import { act, renderHook, waitFor } from '@testing-library/react';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Constants, QueryKeys, dataService } from 'librechat-data-provider';
+import { QueryClient, focusManager, QueryClientProvider } from '@tanstack/react-query';
import type { TMessage } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import {
getStableMessages,
shouldPreserveMessagesOnNotFound,
+ useSubagentAttachmentCallsQueries,
useGetMessagesByConvoId,
} from '../queries';
import { clearMessagesCache, logger } from '~/utils';
@@ -19,6 +20,7 @@ jest.mock('librechat-data-provider', () => {
dataService: {
...actual.dataService,
getMessagesByConvoId: jest.fn(),
+ getSubagentAttachmentCalls: jest.fn(),
},
};
});
@@ -638,3 +640,78 @@ describe('useGetMessagesByConvoId', () => {
unmount();
});
});
+
+describe('useSubagentAttachmentCallsQueries', () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ focusManager.setFocused(undefined);
+ });
+
+ it('asks again on focus after the read failed, and not once it answered', async () => {
+ const queryClient = new QueryClient();
+ const answer = { parts: [{ toolCallId: 'subagent', calls: [{ id: 'child' }] }] };
+ const params = {
+ conversationId: 'convo-id',
+ messageId: 'message-id',
+ files: [{ toolCallId: 'child' }],
+ };
+ /** The first read and its three retries fail; the next one succeeds. */
+ jest
+ .mocked(dataService.getSubagentAttachmentCalls)
+ .mockReset()
+ .mockRejectedValueOnce(new Error('unavailable'))
+ .mockRejectedValueOnce(new Error('unavailable'))
+ .mockRejectedValueOnce(new Error('unavailable'))
+ .mockRejectedValueOnce(new Error('unavailable'))
+ .mockResolvedValue(answer);
+ jest.useFakeTimers();
+
+ const { result, unmount } = renderHook(() => useSubagentAttachmentCallsQueries(params, true), {
+ wrapper: createWrapper(queryClient, '/c/convo-id'),
+ });
+
+ await waitFor(() => expect(result.current[0].isError).toBe(true), { timeout: 20_000 });
+ expect(dataService.getSubagentAttachmentCalls).toHaveBeenCalledTimes(4);
+ expect(dataService.getSubagentAttachmentCalls).toHaveBeenCalledWith(params);
+ act(() => {
+ focusManager.setFocused(false);
+ focusManager.setFocused(true);
+ });
+ await waitFor(() => expect(result.current[0].data).toEqual(answer));
+
+ act(() => {
+ focusManager.setFocused(false);
+ focusManager.setFocused(true);
+ });
+ expect(dataService.getSubagentAttachmentCalls).toHaveBeenCalledTimes(5);
+ unmount();
+ queryClient.clear();
+ jest.useRealTimers();
+ });
+
+ it('asks for more files than one lookup names in bounded batches', async () => {
+ const queryClient = new QueryClient();
+ jest
+ .mocked(dataService.getSubagentAttachmentCalls)
+ .mockReset()
+ .mockResolvedValue({ parts: [] });
+ const files = Array.from({ length: 40 }, (_, i) => ({ toolCallId: `child-${i}` }));
+
+ const { result, unmount } = renderHook(
+ () =>
+ useSubagentAttachmentCallsQueries(
+ { conversationId: 'convo-id', messageId: 'message-id', files },
+ true,
+ ),
+ { wrapper: createWrapper(queryClient, '/c/convo-id') },
+ );
+
+ await waitFor(() => expect(result.current.every((query) => query.isSuccess)).toBe(true));
+ const batches = jest
+ .mocked(dataService.getSubagentAttachmentCalls)
+ .mock.calls.map(([params]) => params.files.length);
+ expect(batches).toEqual([32, 8]);
+ unmount();
+ queryClient.clear();
+ });
+});
diff --git a/client/src/data-provider/Messages/queries.ts b/client/src/data-provider/Messages/queries.ts
index 760655ffcf..030c97a2cd 100644
--- a/client/src/data-provider/Messages/queries.ts
+++ b/client/src/data-provider/Messages/queries.ts
@@ -1,7 +1,7 @@
import { useLayoutEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
-import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Constants, QueryKeys, dataService } from 'librechat-data-provider';
+import { useQuery, useQueries, useQueryClient } from '@tanstack/react-query';
import type { UseQueryOptions, QueryObserverResult, QueryClient } from '@tanstack/react-query';
import type * as t from 'librechat-data-provider';
import {
@@ -125,6 +125,46 @@ export const useToolCallPartQuery = (
);
};
+/** Most files one owner lookup names; the endpoint refuses more. */
+export const SUBAGENT_ATTACHMENT_CALLS_BATCH = 32;
+
+/**
+ * The child calls of a stored message's subagent transcripts that `files` were saved under, for a
+ * client holding previews: a file that reached the message after it loaded has no hint in the
+ * cached preview. Answered from the stored transcripts, so it does not wait on the file being
+ * saved, and keyed by the files so a newer one asks again; more files than one lookup names are
+ * asked in batches. No reader is there to press retry, so a failed read retries with backoff and
+ * runs again on focus and reconnect.
+ */
+export const useSubagentAttachmentCallsQueries = (
+ params: t.SubagentAttachmentCallsParams,
+ enabled: boolean,
+): QueryObserverResult<t.SubagentAttachmentCallsResponse>[] => {
+ const { conversationId, messageId, files } = params;
+ const batches: t.SubagentAttachmentFile[][] = [];
+ for (let i = 0; i < files.length; i += SUBAGENT_ATTACHMENT_CALLS_BATCH) {
+ batches.push(files.slice(i, i + SUBAGENT_ATTACHMENT_CALLS_BATCH));
+ }
+ return useQueries({
+ queries: batches.map((batch) => ({
+ queryKey: [
+ QueryKeys.subagentAttachmentCalls,
+ conversationId,
+ messageId,
+ JSON.stringify(batch),
+ ],
+ queryFn: () =>
+ dataService.getSubagentAttachmentCalls({ conversationId, messageId, files: batch }),
+ enabled,
+ staleTime: Infinity,
+ retry: 3,
+ refetchOnMount: false,
+ refetchOnWindowFocus: true,
+ refetchOnReconnect: true,
+ })),
+ });
+};
+
function hasActiveJob(queryClient: QueryClient, id: string) {
if (!id) {
return false;
diff --git a/e2e/specs/mock/scenarios/subagent-late-files.spec.ts b/e2e/specs/mock/scenarios/subagent-late-files.spec.ts
new file mode 100644
index 0000000000..4f3e817ff5
--- /dev/null
+++ b/e2e/specs/mock/scenarios/subagent-late-files.spec.ts
@@ -0,0 +1,228 @@
+import { expect, test } from '@playwright/test';
+import { randomUUID } from 'node:crypto';
+import type { Page } from '@playwright/test';
+import type { SeedMessage } from '../db';
+import {
+ withMongo,
+ seedMessages,
+ seedConversations,
+ deleteConversations,
+ deleteMessagesByConversation,
+} from '../db';
+import { MOCK_ENDPOINTS, selectMockEndpoint, sendMessage } from '../helpers';
+import { getE2EUser } from '../../../setup/user';
+
+const NO_PARENT = '00000000-0000-0000-0000-000000000000';
+const STREAM_ROUTE = /\/api\/agents\/chat\/stream\//;
+/** 8x8 opaque PNG, enough for the browser to decode the image. */
+const PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEUlEQVR4nGO4o6aGFTEMLQkAF/tKAS/fz4YAAAAASUVORK5CYII=',
+ 'base64',
+);
+
+type LateFile = {
+ /** The child call of the subagent run the file was saved under. */
+ childCall: string;
+ /** The agent the subagent run belongs to, stamped on its part and on the file. */
+ childAgent?: string;
+ /** Whether a top-level call of the response reuses the child's provider id. */
+ reused?: boolean;
+ /** Whether the file is saved on the message before it streams; a harvest can stream it first. */
+ saved?: boolean;
+};
+
+/** A subagent's background tool can deliver its file after the conversation was loaded: the
+ * load previewed the settled subagent call before any file existed, so the preview names no
+ * child call to route it to, and only the stored transcript holds that call. The file is
+ * persisted onto the original message (as the harvest does, unless `saved` is false) and
+ * re-emitted on a later turn's live stream, the way a `check_background_task` poll delivers it. */
+async function deliverLateFile(
+ page: Page,
+ { childCall, childAgent, reused, saved = true }: LateFile,
+) {
+ const conversationId = randomUUID();
+ const userMessageId = randomUUID();
+ const messageId = randomUUID();
+ const suffix = conversationId.slice(0, 8);
+ const attachment = {
+ file_id: `${childCall}-${suffix}-file`,
+ filename: `${childCall}-${suffix}.png`,
+ filepath: `/images/e2e-subagent-late/${childCall}-${suffix}.png`,
+ type: 'image/png',
+ source: 'local',
+ bytes: PNG.length,
+ width: 8,
+ height: 8,
+ messageId,
+ conversationId,
+ toolCallId: childCall,
+ ...(childAgent != null ? { agentId: childAgent } : {}),
+ };
+ const codeCall = (output: string) => ({
+ id: childCall,
+ name: 'execute_code',
+ args: '{}',
+ output,
+ progress: 1,
+ });
+ const messages = [
+ {
+ messageId: userMessageId,
+ parentMessageId: NO_PARENT,
+ isCreatedByUser: true,
+ sender: 'User',
+ text: 'Ask the illustrator for a chart in the background.',
+ },
+ {
+ messageId,
+ parentMessageId: userMessageId,
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ text: '',
+ content: [
+ ...(reused === true
+ ? [
+ { type: 'tool_call', tool_call: codeCall('Loaded the data.') },
+ { type: 'text', text: 'Data loaded.' },
+ ]
+ : []),
+ {
+ type: 'tool_call',
+ tool_call: {
+ id: `subagent-${suffix}`,
+ name: 'subagent',
+ args: JSON.stringify({ subagent_type: 'self', description: 'Draw a chart' }),
+ output: 'The chart is rendering in the background.',
+ progress: 1,
+ subagent_content: [
+ {
+ type: 'tool_call',
+ ...(childAgent != null ? { agentId: childAgent } : {}),
+ tool_call: codeCall('Started background task bg_1.'),
+ },
+ ],
+ },
+ },
+ { type: 'text', text: 'The chart is on its way.' },
+ ],
+ },
+ ] as SeedMessage[];
+
+ await seedConversations(getE2EUser().email, [
+ { conversationId, title: 'Subagent late file', updatedAt: new Date() },
+ ]);
+ await seedMessages(getE2EUser().email, conversationId, messages);
+ await page.route('**/images/e2e-subagent-late/**', (route) =>
+ route.fulfill({ status: 200, contentType: 'image/png', body: PNG }),
+ );
+ /** Every read of this conversation's single messages or parts the client makes. */
+ const reads: string[] = [];
+ page.on('request', (request) => {
+ if (new URL(request.url()).pathname.startsWith(`/api/messages/${conversationId}/`)) {
+ reads.push(request.url());
+ }
+ });
+ const cleanup = async () => {
+ await deleteMessagesByConversation([conversationId]);
+ await deleteConversations([conversationId]);
+ };
+
+ try {
+ const loaded = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === `/api/messages/${conversationId}` &&
+ response.status() === 200,
+ );
+ await page.goto(`/c/${conversationId}`);
+ /** The load previews the subagent call with no file to hint: the shape this covers. */
+ const preview = JSON.stringify(await (await loaded).json());
+ expect(preview).toContain('"subagentContentOmitted":true');
+ expect(preview).not.toContain('subagentAttachmentCalls');
+
+ const message = page.locator(`[id="${messageId}"]`);
+ await expect(message.getByText('The chart is on its way.')).toBeVisible();
+ const image = message.getByRole('img', { name: attachment.filename, exact: true });
+ await expect(image).toHaveCount(0);
+
+ /** The background task finished: its file is saved onto the original message. */
+ if (saved) {
+ await withMongo((db) =>
+ db.collection('messages').updateOne({ messageId }, { $set: { attachments: [attachment] } }),
+ );
+ }
+
+ /** The next turn's stream re-emits that file for the original message, as a poll does. */
+ let injected = false;
+ await page.route(STREAM_ROUTE, async (route) => {
+ if (injected) {
+ await route.continue();
+ return;
+ }
+ injected = true;
+ const response = await route.fetch();
+ const body = await response.text();
+ const frame = `event: message\ndata: ${JSON.stringify({ event: 'attachment', data: attachment })}\n\n`;
+ const firstFrameEnd = body.indexOf('\n\n');
+ await route.fulfill({
+ response,
+ body:
+ firstFrameEnd < 0
+ ? frame + body
+ : body.slice(0, firstFrameEnd + 2) + frame + body.slice(firstFrameEnd + 2),
+ });
+ });
+
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ const response = await sendMessage(page, `E2E_REPLY:late-file-${suffix}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({
+ timeout: 60_000,
+ });
+ expect(injected).toBe(true);
+
+ return { message, image, reads, messageId, cleanup };
+ } catch (error) {
+ await cleanup();
+ throw error;
+ }
+}
+
+test('a file a subagent background tool delivers after the load renders under the subagent @scenario:subagent-late-background-file-renders', async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const { image, reads, messageId, cleanup } = await deliverLateFile(page, {
+ childCall: 'background-child',
+ });
+ try {
+ await expect(image).toHaveCount(1);
+ await expect(image).toBeVisible();
+ /** One owner lookup places the file; no omitted transcript is loaded. */
+ expect(reads.filter((url) => url.includes('/parts/'))).toEqual([]);
+ expect(reads.filter((url) => url.includes(`/${messageId}/subagent-calls?`))).toHaveLength(1);
+ } finally {
+ await cleanup();
+ }
+});
+
+test('a late subagent file whose id an earlier top-level call reuses renders under the subagent, even before it is saved @scenario:subagent-late-file-reused-id-routes-to-subagent', async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const { message, image, cleanup } = await deliverLateFile(page, {
+ childCall: 'call_0',
+ childAgent: 'e2e-illustrator',
+ reused: true,
+ saved: false,
+ });
+ try {
+ await expect(image).toHaveCount(1);
+ await expect(image).toBeVisible();
+ /** The reusing call renders above "Data loaded."; the subagent's files render below it. */
+ const between = await message.getByText('Data loaded.').boundingBox();
+ const imageBox = await image.boundingBox();
+ expect(between != null && imageBox != null && imageBox.y > between.y).toBe(true);
+ } finally {
+ await cleanup();
+ }
+});
diff --git a/packages/api/src/messages/parts.ts b/packages/api/src/messages/parts.ts
index 0802463116..bb5c09997b 100644
--- a/packages/api/src/messages/parts.ts
+++ b/packages/api/src/messages/parts.ts
@@ -1,11 +1,17 @@
import { ContentTypes } from 'librechat-data-provider';
import { logger, CLIENT_MESSAGE_SELECT } from '@librechat/data-schemas';
-import type { FullToolCall, ToolCallPartResponse } from 'librechat-data-provider';
+import type {
+ FullToolCall,
+ ToolCallPartResponse,
+ SubagentAttachmentCallsResponse,
+} from 'librechat-data-provider';
import type { Request, Response } from 'express';
import type {
MessageRequestValidation,
FailedMessageValidationResult,
} from '~/middleware/messageValidation';
+import type { AttachmentCallQuery } from './previews';
+import { findSubagentAttachmentCalls } from './previews';
/** Scopes a read to one message the authenticated user owns. */
export interface ToolCallPartFilter {
@@ -232,3 +238,122 @@ export function createToolCallPartHandler(
}
};
}
+
+/** Most files one owner lookup resolves, and the longest identifier it accepts. */
+const MAX_ATTACHMENT_CALL_QUERIES = 32;
+const MAX_IDENTIFIER_CHARS = 512;
+
+const boundedIdentifier = (value: unknown): string | undefined | null => {
+ const parsed = parseIdentifier(value);
+ return typeof parsed === 'string' && parsed.length > MAX_IDENTIFIER_CHARS ? null : parsed;
+};
+
+/** The `files` query: a JSON array of `{ toolCallId, agentId?, stepId? }`, or `null` if unusable. */
+function parseAttachmentCallQueries(value: unknown): AttachmentCallQuery[] | null {
+ if (typeof value !== 'string' || value.length > MAX_ATTACHMENT_CALL_QUERIES * 1_600) {
+ return null;
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ return null;
+ }
+ if (
+ !Array.isArray(parsed) ||
+ parsed.length === 0 ||
+ parsed.length > MAX_ATTACHMENT_CALL_QUERIES
+ ) {
+ return null;
+ }
+ const files: AttachmentCallQuery[] = [];
+ for (const entry of parsed) {
+ if (entry == null || typeof entry !== 'object') {
+ return null;
+ }
+ const { toolCallId, agentId, stepId } = entry as Record<string, unknown>;
+ const id = boundedIdentifier(toolCallId);
+ const agent = boundedIdentifier(agentId);
+ const step = boundedIdentifier(stepId);
+ if (id == null || agent === null || step === null) {
+ return null;
+ }
+ files.push({
+ toolCallId: id,
+ ...(agent != null ? { agentId: agent } : {}),
+ ...(step != null ? { stepId: step } : {}),
+ });
+ }
+ return files;
+}
+
+export type SubagentAttachmentCallsRequest = Request<
+ { conversationId?: string; messageId?: string },
+ SubagentAttachmentCallsResponse | { error: string },
+ unknown,
+ { files?: unknown }
+> & { user?: { id?: string; tenantId?: string | null } };
+
+export interface SubagentAttachmentCallsHandlerDeps extends ToolCallPartDeps {
+ /** The access check the part endpoint uses, active-job fallback included. */
+ validate: (req: SubagentAttachmentCallsRequest) => MessageRequestValidation;
+ sendValidationResponse: (res: Response, result: FailedMessageValidationResult) => unknown;
+}
+
+/**
+ * `GET /api/messages/:conversationId/:messageId/subagent-calls?files=[...]`, mounted behind
+ * authentication. Names, for each subagent call of the stored message, the child calls of its
+ * transcript the queried files belong to, so a client holding previews can route a file that
+ * reached the message after it loaded without fetching any transcript. Access is validated as
+ * the part endpoint does it, with the user-scoped read started alongside.
+ */
+export function createSubagentAttachmentCallsHandler(
+ deps: SubagentAttachmentCallsHandlerDeps,
+): (req: SubagentAttachmentCallsRequest, res: Response) => Promise<void> {
+ return async (req, res) => {
+ const userId = req.user?.id;
+ const { conversationId, messageId } = req.params;
+ if (!userId || !conversationId || !messageId) {
+ res.status(404).json({ error: 'Message not found' });
+ return;
+ }
+ const files = parseAttachmentCallQueries(req.query.files);
+ if (files == null) {
+ res.status(400).json({ error: 'Invalid files' });
+ return;
+ }
+ try {
+ const validation = deps.validate(req);
+ if (!validation.shouldFetchMessages) {
+ res.status(404).json({ error: 'Message not found' });
+ return;
+ }
+ const read = deps
+ .getMessages({ user: userId, conversationId, messageId }, CLIENT_MESSAGE_SELECT)
+ .then(
+ (value): SettledMessages => ({ ok: true, value }),
+ (error: unknown): SettledMessages => ({ ok: false, error }),
+ );
+ const verdict = await validation.promise;
+ if (!verdict.ok) {
+ deps.sendValidationResponse(res, verdict);
+ return;
+ }
+ const settled = await read;
+ if (!settled.ok) {
+ throw settled.error;
+ }
+ const content = settled.value?.[0]?.content;
+ if (!Array.isArray(content)) {
+ res.status(404).json({ error: 'Message not found' });
+ return;
+ }
+ res.status(200).json({ parts: findSubagentAttachmentCalls(content, files) });
+ } catch (error) {
+ logger.error('[subagentAttachmentCalls] Failed to read subagent attachment calls', error);
+ res.status(500).json({ error: 'Internal server error' });
+ }
+ };
+}
+
+type SettledMessages = { ok: true; value: StoredMessage[] | null } | { ok: false; error: unknown };
diff --git a/packages/api/src/messages/previews.spec.ts b/packages/api/src/messages/previews.spec.ts
index b1017cfc4c..fc250ce050 100644
--- a/packages/api/src/messages/previews.spec.ts
+++ b/packages/api/src/messages/previews.spec.ts
@@ -13,6 +13,7 @@ import {
withToolCallPreviews,
withMessageToolCallPreviews,
TOOL_CALL_PREVIEW_ELISION,
+ findSubagentAttachmentCalls,
} from './previews';
const limits = { outputChars: 1_024, argsChars: 1_024 };
@@ -735,3 +736,53 @@ describe('rejectToolCallPreviewWrites', () => {
expect(result.status).not.toHaveBeenCalled();
});
});
+
+describe('findSubagentAttachmentCalls', () => {
+ const call = (id: string, extra: Record<string, unknown> = {}) => ({
+ type: ContentTypes.TOOL_CALL,
+ ...extra,
+ tool_call: { id, name: 'bash_tool', args: '{}', output: 'ok', progress: 1 },
+ });
+ const subagent = (id: string, transcript: unknown[], extra: Record<string, unknown> = {}) => ({
+ type: ContentTypes.TOOL_CALL,
+ ...extra,
+ tool_call: {
+ id,
+ name: 'subagent',
+ args: '{}',
+ output: 'done',
+ progress: 1,
+ subagent_content: transcript,
+ },
+ });
+
+ it('names the subagent whose transcript holds the scoped call, not one reusing the id unscoped', () => {
+ const content = [
+ call('call_0'),
+ subagent('sub_a', [call('call_0')]),
+ subagent('sub_b', [call('call_0', { agentId: 'illustrator' })], { agentId: 'host' }),
+ ];
+ const found = findSubagentAttachmentCalls(content, [
+ { toolCallId: 'call_0', agentId: 'illustrator' },
+ ]);
+ expect(found).toEqual([
+ { toolCallId: 'sub_a', calls: [{ id: 'call_0' }] },
+ {
+ toolCallId: 'sub_b',
+ agentId: 'host',
+ calls: [{ id: 'call_0', agentId: 'illustrator' }],
+ },
+ ]);
+ });
+
+ it('walks nested runs and ignores calls no queried file names', () => {
+ const content = [
+ subagent('outer', [subagent('inner', [call('deep'), call('other')])]),
+ { type: ContentTypes.TEXT, text: 'done' },
+ ];
+ expect(findSubagentAttachmentCalls(content, [{ toolCallId: 'deep' }])).toEqual([
+ { toolCallId: 'outer', calls: [{ id: 'deep' }] },
+ ]);
+ expect(findSubagentAttachmentCalls(content, [])).toEqual([]);
+ });
+});
diff --git a/packages/api/src/messages/previews.ts b/packages/api/src/messages/previews.ts
index 687a938e07..5bb7c3dc79 100644
--- a/packages/api/src/messages/previews.ts
+++ b/packages/api/src/messages/previews.ts
@@ -276,6 +276,63 @@ function attachmentToolCallIds(message: PreviewableMessage): AttachmentScopes |
return scopes.size > 0 ? scopes : undefined;
}
+/** A file whose owner a client is resolving: the tool call it was saved under, with its scope. */
+export type AttachmentCallQuery = { toolCallId: string; agentId?: string; stepId?: string };
+
+/** A top-level subagent call and the child calls of its stored transcript the queried files name. */
+export type SubagentAttachmentCallsEntry = {
+ toolCallId: string;
+ stepId?: string;
+ agentId?: string;
+ calls: Agents.SubagentAttachmentCall[];
+};
+
+/**
+ * For each top-level subagent call in stored `content`, the child calls of its transcript that
+ * the queried files can belong to, chosen as a preview chooses `subagentAttachmentCalls`. Read
+ * from the transcript rather than the saved attachments, so a file that streamed before it was
+ * saved on the message resolves the same way.
+ */
+export function findSubagentAttachmentCalls(
+ content: unknown[],
+ files: ReadonlyArray<AttachmentCallQuery>,
+): SubagentAttachmentCallsEntry[] {
+ const wanted = new Map<string, AttachmentScope[]>();
+ for (const { toolCallId, agentId, stepId } of files) {
+ const scopes = wanted.get(toolCallId) ?? [];
+ scopes.push({ ...(agentId != null ? { agentId } : {}), ...(stepId != null ? { stepId } : {}) });
+ wanted.set(toolCallId, scopes);
+ }
+ const entries: SubagentAttachmentCallsEntry[] = [];
+ if (wanted.size === 0) {
+ return entries;
+ }
+ for (const part of content) {
+ if (!isToolCallPart(part) || !Array.isArray(part.tool_call.subagent_content)) {
+ continue;
+ }
+ const { id, stepId } = part.tool_call;
+ if (typeof id !== 'string' || id === '') {
+ continue;
+ }
+ const calls = nestedAttachmentCalls(
+ part.tool_call.subagent_content,
+ wanted,
+ runAgentId(part.tool_call),
+ );
+ if (calls.length === 0) {
+ continue;
+ }
+ entries.push({
+ toolCallId: id,
+ ...(typeof stepId === 'string' && stepId !== '' ? { stepId } : {}),
+ ...(typeof part.agentId === 'string' && part.agentId !== '' ? { agentId: part.agentId } : {}),
+ calls,
+ });
+ }
+ return entries;
+}
+
/** Cuts at `end` without splitting a surrogate pair. */
function sliceStart(text: string, end: number): string {
const code = text.charCodeAt(end - 1);
diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.ts
index 84c45ca04a..0b653f2150 100644
--- a/packages/data-provider/src/api-endpoints.ts
+++ b/packages/data-provider/src/api-endpoints.ts
@@ -76,6 +76,14 @@ export const messages = (params: q.MessagesListParams) => {
export const messagesArtifacts = (messageId: string) => `${messagesRoot}/artifact/${messageId}`;
+/** The child calls of a stored message's subagent transcripts that the given files belong to. */
+export const messageSubagentAttachmentCalls = ({
+ conversationId,
+ messageId,
+ files,
+}: q.SubagentAttachmentCallsParams) =>
+ `${messagesRoot}/${encodeURIComponent(conversationId)}/${encodeURIComponent(messageId)}/subagent-calls?files=${encodeURIComponent(JSON.stringify(files))}`;
+
/** One tool-call part of a stored message, in full. */
export const messageToolCallPart = ({
conversationId,
diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.ts
index 0e86c35f04..73e0eb1291 100644
--- a/packages/data-provider/src/data-service.ts
+++ b/packages/data-provider/src/data-service.ts
@@ -1175,6 +1175,12 @@ export function getToolCallPart(params: q.ToolCallPartParams): Promise<q.ToolCal
return request.get(endpoints.messageToolCallPart(params));
}
+export function getSubagentAttachmentCalls(
+ params: q.SubagentAttachmentCallsParams,
+): Promise<q.SubagentAttachmentCallsResponse> {
+ return request.get(endpoints.messageSubagentAttachmentCalls(params));
+}
+
export function getMessageById(conversationId: string, messageId: string): Promise<s.TMessage[]> {
return request.get(endpoints.messages({ conversationId, messageId }));
}
diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.ts
index c439d5b8b3..8c40da74fe 100644
--- a/packages/data-provider/src/keys.ts
+++ b/packages/data-provider/src/keys.ts
@@ -2,6 +2,8 @@ export enum QueryKeys {
messages = 'messages',
/* Full content of one tool-call part, fetched when its preview is not enough */
toolCallPart = 'toolCallPart',
+ /* Child calls of a message's subagent transcripts that files reaching it late belong to */
+ subagentAttachmentCalls = 'subagentAttachmentCalls',
ownerMessageTexts = 'ownerMessageTexts',
sharedMessages = 'sharedMessages',
sharedStartupConfig = 'sharedStartupConfig',
diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.ts
index c3fcfcfb1c..e2b8f4adc7 100644
--- a/packages/data-provider/src/types/queries.ts
+++ b/packages/data-provider/src/types/queries.ts
@@ -135,6 +135,25 @@ export type ToolCallPartResponse = {
tool_call: FullToolCall;
};
+/** A file whose owner a client resolves: the tool call it was saved under, with its scope. */
+export type SubagentAttachmentFile = { toolCallId: string; agentId?: string; stepId?: string };
+
+export type SubagentAttachmentCallsParams = {
+ conversationId: string;
+ messageId: string;
+ files: SubagentAttachmentFile[];
+};
+
+export type SubagentAttachmentCallsResponse = {
+ /** Each subagent call of the stored message whose transcript holds a call the files name. */
+ parts: Array<{
+ toolCallId: string;
+ stepId?: string;
+ agentId?: string;
+ calls: a.Agents.SubagentAttachmentCall[];
+ }>;
+};
+
/* Shared Links */
export type SharedMessagesResponse = Omit<s.TSharedLink, 'messages'> & {
messages: s.TMessage[];