🧩 fix: Render Nested MCP Apps Under Standalone Subagent Calls (#17211)

* fix: Render Nested MCP Apps Under a Standalone Subagent Call

* fix: Hoist Subagent Run Apps Beside Their Row With Message-Wide Ordinals
This commit is contained in:
Marco Beretta 2026-10-18 11:51:25 +02:00 • committed by GitHub
parent 54b887a1ec
commit bb69bcfe34
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 440 additions and 51 deletions

View file

@ -139,6 +139,7 @@ const buildToolCallStepOwners = (
const collectMessageContent = (
content: Array<TMessageContentParts | undefined> | undefined,
attachments: TAttachment[] | undefined,
nested: Pick<ReadonlyMap<TMessageContentParts, TAttachment[]>, 'get'>,
contentIndexOffset = 0,
contentIndices?: ReadonlyArray<number>,
): {
@ -169,7 +170,10 @@ const collectMessageContent = (
getPartStepId(part),
getSiblingStepIds(part, ownersByToolCallId),
);
for (const attachment of routed ?? []) {
/** A subagent's child-call Apps render beside the subagent row, like its
* own, so regrouping the row while it streams never remounts them. */
const owned = nested.get(part);
for (const attachment of owned == null ? (routed ?? []) : [...(routed ?? []), ...owned]) {
if (
attachment.type === Tools.ui_resources &&
!collected.has(attachment) &&
@ -1430,15 +1434,64 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
previousIdentity.isSubmitting = isSubmitting;
}
const appRenderScope = appRenderIdentity.current!.scope;
const liveSubagentToolCalls = useLiveSubagentToolCalls(
props.content,
attachments,
messageId,
props.contentIndices,
props.contentIndexOffset ?? 0,
);
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(() => {
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]);
const messageContent = useMemo(
() =>
collectMessageContent(
props.content,
attachments,
nestedAttachments,
props.contentIndexOffset,
props.contentIndices,
),
[props.content, attachments, props.contentIndexOffset, props.contentIndices],
[props.content, attachments, nestedAttachments, props.contentIndexOffset, props.contentIndices],
);
const suppressedAppAttachments = useMemo<ReadonlySet<TAttachment>>(
() => new Set(messageContent.attachments),
@ -1561,54 +1614,6 @@ 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 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(() => {
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}>

View file

@ -26,6 +26,7 @@ import { MessageContext } from '~/Providers/MessageContext';
import { useShareContext } from '~/Providers/ShareContext';
import MessageIcon from '~/components/Share/MessageIcon';
import { parseSubagentBackgroundHandle } from './handle';
import { MCPAppViews } from '~/components/MCPUIResource';
import { isError } from '../ToolOutput/OutputRenderer';
import { useToolPreparation } from '../preparation';
import { useAgentsMapContext } from '~/Providers';
@ -525,7 +526,10 @@ export default function SubagentCall({
</button>
{!hideAttachments && attachments && attachments.length > 0 && (
<AttachmentGroup attachments={attachments} />
<>
<AttachmentGroup attachments={attachments} />
<MCPAppViews attachments={attachments} />
</>
)}
</>
);

View file

@ -5,6 +5,7 @@ import { MemoryRouter } from 'react-router-dom';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type {
PartMetadata,
TAttachment,
SubagentIdentity,
SubagentUpdateEvent,
ParentSubagentSummary,
@ -63,6 +64,12 @@ jest.mock('../Attachment', () => ({
),
}));
jest.mock('~/components/MCPUIResource', () => ({
MCPAppViews: ({ attachments }: { attachments?: unknown[] }) => (
<div data-testid="app-views">{JSON.stringify(attachments)}</div>
),
}));
jest.mock('lucide-react', () => ({
// eslint-disable-next-line i18next/no-literal-string
ChevronRight: () => <span aria-hidden="true">chevron</span>,
@ -731,6 +738,44 @@ describe('SubagentCall', () => {
expect(screen.getByRole('button', { name: 'Ran agent' })).toBeDisabled();
});
/** A tool inside the run saves its MCP App under the child call id, so the
* standalone card is the only row that can show it. */
it('renders the MCP Apps its run produced beside its files', () => {
const app = {
type: 'ui_resources',
toolCallId: 'child-app-call',
ui_resources: [{ uri: 'ui://e2e/app', toolName: 'show_app', serverName: 'e2e-app' }],
} as unknown as TAttachment;
const tree = (hideAttachments: boolean) => (
<MemoryRouter>
<RecoilRoot>
<MessageContext.Provider
value={{
conversationId: 'parent-conversation',
messageId: 'parent',
isExpanded: false,
}}
>
<SubagentCall
toolCallId="app-call"
initialProgress={1}
args={{ subagent_type: 'self', description: 'Show the app.' }}
output="Shown."
attachments={[app]}
hideAttachments={hideAttachments}
/>
</MessageContext.Provider>
</RecoilRoot>
</MemoryRouter>
);
const rendered = render(tree(false));
expect(JSON.parse(screen.getByTestId('app-views').textContent ?? '')).toEqual([app]);
rendered.rerender(tree(true));
expect(screen.queryByTestId('app-views')).toBeNull();
});
it('keeps model-authored lookalike output on the foreground adapter', () => {
const output = JSON.stringify({
background_task_id: 'task-1',

View file

@ -59,9 +59,11 @@ jest.mock('~/components/MCPUIResource', () => {
MCPAppViews: ({
attachments,
resources,
ordinalStart = 1,
}: {
attachments?: TAttachment[];
resources?: MCPAppResourceOccurrence[];
ordinalStart?: number;
}) => {
const suppressed = ReactActual.useContext(MCPAppSuppressionContext);
const selectedAttachments =
@ -78,6 +80,7 @@ jest.mock('~/components/MCPUIResource', () => {
return (
<div
data-testid="mcp-app-attachments"
data-ordinal={ordinalStart}
data-owners={visible
.map((attachment) => {
const owned = attachment as TAttachment & { agentId?: string; stepId?: string };
@ -170,6 +173,23 @@ jest.mock('../Parts', () => ({
MemoryCall: ({ attachments }: { attachments?: TAttachment[] }) => (
<div data-testid="memory-call" data-count={attachments?.length ?? 0} />
),
/** Mirrors the card: it offers its run's Apps only while it shows attachments. */
SubagentCall: ({
attachments,
hideAttachments,
}: {
attachments?: TAttachment[];
hideAttachments?: boolean;
}) => {
const { MCPAppViews } = jest.requireMock<typeof import('~/components/MCPUIResource')>(
'~/components/MCPUIResource',
);
return (
<div data-testid="subagent-call">
{!hideAttachments && <MCPAppViews attachments={attachments} />}
</div>
);
},
}));
jest.mock('~/components/Web/Sources', () => ({
@ -875,6 +895,71 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {
expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);
});
const makeSubagentCall = (id: string, childId: string): TMessageContentParts =>
({
type: ContentTypes.TOOL_CALL,
[ContentTypes.TOOL_CALL]: {
id,
name: Constants.SUBAGENT,
args: '{}',
output: 'Shown.',
subagent_content: [
{
type: ContentTypes.TOOL_CALL,
[ContentTypes.TOOL_CALL]: {
id: childId,
name: `show_app${MCP_DELIMITER}demo`,
args: '{}',
output: 'shown',
},
},
],
},
}) as unknown as TMessageContentParts;
it('keeps a subagent run App mounted while its row is regrouped', () => {
const subagent = makeSubagentCall('call_subagent', 'child_app');
const otherCall = makeMcpToolCall('call_other');
const frame = (content: TMessageContentParts[]) => (
<RecoilRoot>
<ContentParts
{...baseProps}
content={content}
attachments={[appAttachment('child_app')]}
messageId="response_"
conversationId="conversation-1"
isLatestMessage
/>
</RecoilRoot>
);
const { rerender } = render(frame([subagent]));
const appView = screen.getByTestId('mcp-app-attachments');
expect(appView).toHaveAttribute('data-owners', 'none/none/child_app');
/** An adjacent call moves the subagent row into a tool group. */
rerender(frame([subagent, otherCall]));
expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);
/** A phase marker then claims both calls. */
rerender(frame([subagent, otherCall, makePhasePart(0, 2, 'Showed the app')]));
expect(screen.getByTestId('mcp-app-attachments')).toBe(appView);
});
it('numbers subagent run Apps across the message', () => {
renderContentParts({
...baseProps,
content: [
makeSubagentCall('call_first', 'child_first'),
makeTextPart('between the runs'),
makeSubagentCall('call_second', 'child_second'),
],
attachments: [appAttachment('child_first'), appAttachment('child_second')],
});
expect(
screen.getAllByTestId('mcp-app-attachments').map((view) => view.dataset.ordinal),
).toEqual(['1', '2']);
});
it('retains an existing resource when another App is inserted into its tool result', () => {
const call = makeMcpToolCall('call_app', true, 'step-1', 'agent-a');
const resource = (resourceId: string) => ({

View file

@ -0,0 +1,250 @@
import { expect, test } from '@playwright/test';
import { randomUUID } from 'node:crypto';
import type { Page } from '@playwright/test';
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';
const appAttachment = (
conversationId: string,
messageId: string,
toolCallId: string,
toolName = toolCallId,
) => ({
type: 'ui_resources',
messageId,
conversationId,
toolCallId,
ui_resources: [
{
uri: `ui://e2e-app/${toolCallId}`,
mimeType: 'text/html;profile=mcp-app',
text: '<p>app</p>',
toolName,
serverName: 'e2e-app',
},
],
});
const appToolCall = (id: string) => ({
type: 'tool_call',
tool_call: { id, name: 'show_app_mcp_e2e-app', args: '{}', output: 'Shown', progress: 1 },
});
/** The harness enables MCP Apps only in its dedicated fixture profile, so each test sets
* the deployment policy in the startup config the client reads. */
async function setMCPAppsPolicy(page: Page, enabled: boolean) {
await page.route('**/api/config', async (route) => {
const response = await route.fetch();
const config = (await response.json()) as { mcpApps?: Record<string, unknown> };
await route.fulfill({
response,
json: { ...config, mcpApps: { ...config.mcpApps, enabled, legacyHtmlEnabled: true } },
});
});
}
async function seedTurn() {
const conversationId = randomUUID();
const userMessageId = randomUUID();
const messageId = randomUUID();
const suffix = conversationId.slice(0, 8);
const calls = {
child: `child-app-${suffix}`,
grandchild: `grandchild-app-${suffix}`,
direct: `direct-app-${suffix}`,
};
const messages = [
{
messageId: userMessageId,
parentMessageId: NO_PARENT,
isCreatedByUser: true,
sender: 'User',
text: 'Ask the helper to open the dashboard.',
},
{
messageId,
parentMessageId: userMessageId,
isCreatedByUser: false,
sender: 'Assistant',
text: '',
content: [
{
type: 'tool_call',
tool_call: {
id: `subagent-${suffix}`,
name: 'subagent',
args: JSON.stringify({ subagent_type: 'self', description: 'Open the dashboard' }),
output: 'The helper opened the dashboard.',
progress: 1,
subagent_content: [
appToolCall(calls.child),
{
type: 'tool_call',
tool_call: {
id: `nested-subagent-${suffix}`,
name: 'subagent',
args: JSON.stringify({ subagent_type: 'self', description: 'Open the chart' }),
output: 'Opened the chart.',
progress: 1,
subagent_content: [appToolCall(calls.grandchild)],
},
},
],
},
},
{ type: 'text', text: 'The helper is done.' },
appToolCall(calls.direct),
{ type: 'text', text: 'Here is the dashboard.' },
],
attachments: Object.values(calls).map((id) => appAttachment(conversationId, messageId, id)),
},
] as SeedMessage[];
await seedConversations(getE2EUser().email, [
{ conversationId, title: 'Subagent MCP Apps', updatedAt: new Date() },
]);
await seedMessages(getE2EUser().email, conversationId, messages);
return { conversationId, messageId, calls };
}
/** Two standalone subagent runs, kept apart by prose, whose tools each open the same App. */
async function seedSeparateRuns() {
const conversationId = randomUUID();
const userMessageId = randomUUID();
const messageId = randomUUID();
const suffix = conversationId.slice(0, 8);
const children = [`first-app-${suffix}`, `second-app-${suffix}`];
const run = (index: number) => ({
type: 'tool_call',
tool_call: {
id: `subagent-${index}-${suffix}`,
name: 'subagent',
args: JSON.stringify({ subagent_type: 'self', description: `Open dashboard ${index}` }),
output: `Opened dashboard ${index}.`,
progress: 1,
subagent_content: [appToolCall(children[index])],
},
});
const messages = [
{
messageId: userMessageId,
parentMessageId: NO_PARENT,
isCreatedByUser: true,
sender: 'User',
text: 'Open both dashboards.',
},
{
messageId,
parentMessageId: userMessageId,
isCreatedByUser: false,
sender: 'Assistant',
text: '',
content: [
run(0),
{ type: 'text', text: 'The first dashboard is open.' },
run(1),
{ type: 'text', text: 'Both dashboards are open.' },
],
attachments: children.map((id) =>
appAttachment(conversationId, messageId, id, 'show_dashboard'),
),
},
] as SeedMessage[];
await seedConversations(getE2EUser().email, [
{ conversationId, title: 'Separate subagent Apps', updatedAt: new Date() },
]);
await seedMessages(getE2EUser().email, conversationId, messages);
return { conversationId, messageId };
}
async function openTurn(page: Page, conversationId: string) {
const loaded = page.waitForResponse(
(response) =>
response.url().includes(`/api/messages/${conversationId}`) && response.status() === 200,
);
await page.goto(`/c/${conversationId}`);
/** Only meaningful while the route sends the subagent call as a preview, the
* default load, which omits the transcript the child tool calls live in. */
expect(JSON.stringify(await (await loaded).json())).toContain('"subagentContentOmitted":true');
}
/** 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. */
test('an MCP App a subagent tool produced renders once under the standalone subagent @scenario:subagent-nested-mcp-apps-render', async ({
page,
}) => {
const { conversationId, messageId, calls } = await seedTurn();
await setMCPAppsPolicy(page, true);
try {
await openTurn(page, conversationId);
const message = page.locator(`[id="${messageId}"]`);
await expect(message.getByText('Here is the dashboard.')).toBeVisible();
for (const id of Object.values(calls)) {
const view = message.locator(`[data-mcp-app-view="${id}"]`);
await expect(view).toHaveCount(1);
await expect(view.getByRole('button', { name: new RegExp(id) })).toBeVisible();
}
await page.reload();
for (const id of [calls.child, calls.grandchild]) {
await expect(message.locator(`[data-mcp-app-view="${id}"]`)).toHaveCount(1);
}
} finally {
await deleteMessagesByConversation([conversationId]);
await deleteConversations([conversationId]);
}
});
test('a subagent MCP App stays hidden while the deployment disables MCP Apps @scenario:subagent-nested-mcp-apps-policy-off', async ({
page,
}) => {
const { conversationId, messageId } = await seedTurn();
await setMCPAppsPolicy(page, false);
try {
await openTurn(page, conversationId);
const message = page.locator(`[id="${messageId}"]`);
await expect(message.getByText('Here is the dashboard.')).toBeVisible();
await expect(message.getByText('The helper is done.')).toBeVisible();
await expect(message.locator('[data-mcp-app-view]')).toHaveCount(0);
} finally {
await deleteMessagesByConversation([conversationId]);
await deleteConversations([conversationId]);
}
});
test('the same App opened by two separate subagent runs gets a distinct control name for each @scenario:subagent-nested-mcp-apps-distinct-names', async ({
page,
}) => {
const { conversationId, messageId } = await seedSeparateRuns();
await setMCPAppsPolicy(page, true);
try {
await openTurn(page, conversationId);
const message = page.locator(`[id="${messageId}"]`);
await expect(message.getByText('Both dashboards are open.')).toBeVisible();
await expect(message.locator('[data-mcp-app-view="show_dashboard"]')).toHaveCount(2);
for (const ordinal of [1, 2]) {
await expect(
message.getByRole('button', {
name: `Open app: show_dashboard (${ordinal})`,
exact: true,
}),
).toBeVisible();
}
} finally {
await deleteMessagesByConversation([conversationId]);
await deleteConversations([conversationId]);
}
});