mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-21 07:23:11 +00:00
🫸 fix: Gate MCP App Views and Actions on User Intent (#16297)
* 🫸 fix: Gate MCP App Views and Actions on User Intent
* 🧪 ci: Run MCP Apps Browser Checks on Repository Bot PRs
* 🧲 test: Open App Before Checking Tool-Call Frames
* 🔎 fix: Wait for Stable App Views in Restored Browser Tests
* 🧪 test: Trace Grouped App View Activation in Browser CI
* 🧪 test: Diagnose Grouped App Click Propagation
* 🧪 test: Distinguish Native and React App Click Delivery
* 🧪 test: Inspect Grouped App Button Hit Target
* 🎟️ test: Open Grouped App Views After Scrolling Into Place
* 🧯 fix: Revoke App Approval Before Teardown Handshake
* 🫸 fix: Configure App Limits and Suspend Denied Actions
* 🧾 test: Expect Configured MCP App Limits in API Suites
* 🧱 fix: Isolate Approved App Messages From Composer Drafts
* 🛟 fix: Suspend Aborted App Actions and Restore View Focus
* 🦮 fix: Preserve Focus on App-Initiated Teardown
* 🧳 fix: Exclude Draft Agent State From App Messages
* 🧭 test: Preserve Legacy Null File Overrides
* 🧰 fix: Retain Selected MCP Tools Across App Messages
* 🧾 fix: Acknowledge Accepted App Turns and Disclose Selected Tools
---------
Co-authored-by: Lia <lia@librechat.ai>
(cherry picked from commit 6866732a88)
Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/16297
This commit is contained in:
parent
b0783e8085
commit
e396ea9c7b
27 changed files with 1595 additions and 94 deletions
16
.github/workflows/playwright-mock.yml
vendored
16
.github/workflows/playwright-mock.yml
vendored
|
|
@ -165,7 +165,8 @@ jobs:
|
|||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
github.event.pull_request != null &&
|
||||
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association)))
|
||||
(contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository)))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
# Separate runners isolate each shard's user, MongoDB, Redis and fixture state.
|
||||
|
|
@ -413,7 +414,8 @@ jobs:
|
|||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
github.event.pull_request != null &&
|
||||
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association)))
|
||||
(contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository)))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
|
|
@ -564,7 +566,8 @@ jobs:
|
|||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
github.event.pull_request != null &&
|
||||
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association))
|
||||
(contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
|
|
@ -599,8 +602,8 @@ jobs:
|
|||
- name: Verify Chrome is present
|
||||
run: google-chrome --version
|
||||
|
||||
- name: Check MCP Apps result gating
|
||||
run: node --test e2e/mcp-apps/results.test.mjs
|
||||
- name: Check MCP Apps result gating and same-repository PR eligibility
|
||||
run: node --test e2e/mcp-apps/results.test.mjs e2e/mcp-apps/workflow.test.mjs
|
||||
|
||||
- name: Check real SDK server fixture
|
||||
run: node --test e2e/mcp-apps/server.test.mjs
|
||||
|
|
@ -643,7 +646,8 @@ jobs:
|
|||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
github.event.pull_request != null &&
|
||||
contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association)))
|
||||
(contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) ||
|
||||
github.event.pull_request.head.repo.full_name == github.repository)))
|
||||
needs: [codegraph_select, e2e_shards, mcp_tool_list_changed, mcp_apps]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
|
|
|||
|
|
@ -408,6 +408,8 @@ describe('GET /api/config', () => {
|
|||
cspLimits: { maxSourcesPerDirective: 32, maxSerializedLength: 4096 },
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -420,6 +422,8 @@ describe('GET /api/config', () => {
|
|||
maxSourcesPerDirective: 64,
|
||||
maxSerializedLength: 8192,
|
||||
maxAdmissionRequestsPerMinute: 480,
|
||||
maxActiveViews: 7,
|
||||
maxActionPreviewChars: 32768,
|
||||
},
|
||||
});
|
||||
const response = await request(createApp(mockUser)).get('/api/config');
|
||||
|
|
@ -430,6 +434,8 @@ describe('GET /api/config', () => {
|
|||
cspLimits: { maxSourcesPerDirective: 64, maxSerializedLength: 8192 },
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 480,
|
||||
maxActiveViews: 7,
|
||||
maxActionPreviewChars: 32768,
|
||||
sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -47,6 +47,8 @@ const defaultMCPAppsPolicy = {
|
|||
enabled: false,
|
||||
legacyHtmlEnabled: true,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -324,6 +324,8 @@ router.get('/', async function (req, res) {
|
|||
appConfig?.mcpAppSandbox?.maxPersistedAppBytes,
|
||||
appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,
|
||||
appConfig?.mcpAppSandbox?.url,
|
||||
appConfig?.mcpAppSandbox?.maxActiveViews,
|
||||
appConfig?.mcpAppSandbox?.maxActionPreviewChars,
|
||||
),
|
||||
...(codeEnvironmentMoveVersion != null ? { codeEnvironmentMoveVersion } : {}),
|
||||
...(cloudFront ? { cloudFront } : {}),
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ const defaultMCPAppsPolicy = {
|
|||
enabled: false,
|
||||
legacyHtmlEnabled: true,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -157,6 +157,8 @@ describe('initializeMCPs', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
@ -180,6 +182,8 @@ describe('initializeMCPs', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
@ -202,6 +206,8 @@ describe('initializeMCPs', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
@ -214,6 +220,8 @@ describe('initializeMCPs', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
},
|
||||
],
|
||||
[
|
||||
|
|
@ -223,6 +231,8 @@ describe('initializeMCPs', () => {
|
|||
legacyHtmlEnabled: false,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
},
|
||||
],
|
||||
])('normalizes the startup MCP Apps policy for apps=%s', async (apps, expected) => {
|
||||
|
|
@ -250,6 +260,8 @@ describe('initializeMCPs', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 480,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',
|
||||
});
|
||||
});
|
||||
|
|
@ -288,6 +300,8 @@ describe('initializeMCPs', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: 1048576,
|
||||
maxAdmissionRequestsPerMinute: 240,
|
||||
maxActiveViews: 3,
|
||||
maxActionPreviewChars: 16384,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,17 +1,37 @@
|
|||
import { createContext, useContext, useMemo } from 'react';
|
||||
import { createContext, useCallback, useContext, useMemo } from 'react';
|
||||
import { atom, createStore, useAtomValue } from 'jotai';
|
||||
import {
|
||||
DEFAULT_MCP_APPS_POLICY,
|
||||
DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
MAX_MCP_APP_ACTIVE_VIEWS,
|
||||
MAX_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
resolveMCPAppCspLimits,
|
||||
type TMCPAppsPolicy,
|
||||
type TStartupConfig,
|
||||
} from 'librechat-data-provider';
|
||||
|
||||
/** One store per host provider; never share capacity across conversations or signed-in users. */
|
||||
const activeAppViewsAtom = atom<ReadonlySet<string>>(new Set<string>());
|
||||
|
||||
function validLimit(value: unknown, fallback: number, max: number): number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 && value <= max
|
||||
? value
|
||||
: fallback;
|
||||
}
|
||||
|
||||
type MCPAppsHostContextValue = {
|
||||
reserveView: (key: string) => boolean;
|
||||
releaseView: (key: string) => void;
|
||||
activeViewStore: ReturnType<typeof createStore>;
|
||||
policy: Readonly<TMCPAppsPolicy>;
|
||||
userId?: string;
|
||||
};
|
||||
|
||||
const DEFAULT_MCP_APPS_HOST: MCPAppsHostContextValue = {
|
||||
reserveView: () => false,
|
||||
releaseView: () => undefined,
|
||||
activeViewStore: createStore(),
|
||||
policy: DEFAULT_MCP_APPS_POLICY,
|
||||
};
|
||||
|
||||
|
|
@ -29,7 +49,20 @@ function getPublishedPolicy(
|
|||
) {
|
||||
return DEFAULT_MCP_APPS_POLICY;
|
||||
}
|
||||
return { ...policy, cspLimits: resolveMCPAppCspLimits(policy.cspLimits) };
|
||||
return {
|
||||
...policy,
|
||||
cspLimits: resolveMCPAppCspLimits(policy.cspLimits),
|
||||
maxActiveViews: validLimit(
|
||||
policy.maxActiveViews,
|
||||
DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
MAX_MCP_APP_ACTIVE_VIEWS,
|
||||
),
|
||||
maxActionPreviewChars: validLimit(
|
||||
policy.maxActionPreviewChars,
|
||||
DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
MAX_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function MCPAppsPolicyProvider({
|
||||
|
|
@ -44,10 +77,32 @@ export function MCPAppsPolicyProvider({
|
|||
userId?: string;
|
||||
}) {
|
||||
const policy = useMemo(() => getPublishedPolicy(startupConfig, ready), [ready, startupConfig]);
|
||||
const activeViewStore = useMemo(() => createStore(), []);
|
||||
const reserveView = useCallback(
|
||||
(key: string) => {
|
||||
const active = activeViewStore.get(activeAppViewsAtom);
|
||||
if (active.has(key)) return true;
|
||||
if (active.size >= (policy.maxActiveViews ?? DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS)) return false;
|
||||
activeViewStore.set(activeAppViewsAtom, new Set(active).add(key));
|
||||
return true;
|
||||
},
|
||||
[activeViewStore, policy.maxActiveViews],
|
||||
);
|
||||
const releaseView = useCallback(
|
||||
(key: string) => {
|
||||
const active = activeViewStore.get(activeAppViewsAtom);
|
||||
if (active.has(key)) {
|
||||
const next = new Set(active);
|
||||
next.delete(key);
|
||||
activeViewStore.set(activeAppViewsAtom, next);
|
||||
}
|
||||
},
|
||||
[activeViewStore],
|
||||
);
|
||||
const authenticatedUserId = typeof userId === 'string' && userId.trim() ? userId : undefined;
|
||||
const value = useMemo(
|
||||
() => ({ policy, userId: authenticatedUserId }),
|
||||
[authenticatedUserId, policy],
|
||||
() => ({ policy, userId: authenticatedUserId, reserveView, releaseView, activeViewStore }),
|
||||
[authenticatedUserId, policy, reserveView, releaseView, activeViewStore],
|
||||
);
|
||||
|
||||
return <MCPAppsPolicyContext.Provider value={value}>{children}</MCPAppsPolicyContext.Provider>;
|
||||
|
|
@ -60,3 +115,12 @@ export function useMCPAppsPolicy(): Readonly<TMCPAppsPolicy> {
|
|||
export function useMCPAppsHost(): MCPAppsHostContextValue {
|
||||
return useContext(MCPAppsPolicyContext);
|
||||
}
|
||||
|
||||
/** Subscribe only a capacity notice, not every historical placeholder, to shared View changes. */
|
||||
export function useMCPAppViewAtCapacity(): boolean {
|
||||
const { activeViewStore, policy } = useMCPAppsHost();
|
||||
return (
|
||||
useAtomValue(activeAppViewsAtom, { store: activeViewStore }).size >=
|
||||
(policy.maxActiveViews ?? DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS)
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import React from 'react';
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { TStartupConfig } from 'librechat-data-provider';
|
||||
|
|
@ -21,8 +22,11 @@ function LimitsProbe() {
|
|||
}
|
||||
|
||||
function SandboxPolicyProbe() {
|
||||
const { sandboxUrl, maxAdmissionRequestsPerMinute } = useMCPAppsPolicy();
|
||||
return <output>{`${sandboxUrl ?? 'none'}:${maxAdmissionRequestsPerMinute ?? 'none'}`}</output>;
|
||||
const { sandboxUrl, maxAdmissionRequestsPerMinute, maxActiveViews, maxActionPreviewChars } =
|
||||
useMCPAppsPolicy();
|
||||
return (
|
||||
<output>{`${sandboxUrl ?? 'none'}:${maxAdmissionRequestsPerMinute ?? 'none'}:${maxActiveViews ?? 'none'}:${maxActionPreviewChars ?? 'none'}`}</output>
|
||||
);
|
||||
}
|
||||
|
||||
function CachedPolicyProvider({ children }: { children: React.ReactNode }) {
|
||||
|
|
@ -103,6 +107,8 @@ describe('MCPAppsPolicyProvider', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',
|
||||
maxAdmissionRequestsPerMinute: 480,
|
||||
maxActiveViews: 7,
|
||||
maxActionPreviewChars: 32768,
|
||||
},
|
||||
} as TStartupConfig
|
||||
}
|
||||
|
|
@ -113,10 +119,64 @@ describe('MCPAppsPolicyProvider', () => {
|
|||
);
|
||||
|
||||
expect(
|
||||
screen.getByText('https://mcp-sandbox.example.com/api/mcp/sandbox:480'),
|
||||
screen.getByText('https://mcp-sandbox.example.com/api/mcp/sandbox:480:7:32768'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back to bounded policy values when a published startup payload is malformed', () => {
|
||||
render(
|
||||
<MCPAppsPolicyProvider
|
||||
ready
|
||||
startupConfig={
|
||||
{
|
||||
mcpApps: {
|
||||
enabled: true,
|
||||
legacyHtmlEnabled: true,
|
||||
maxActiveViews: Infinity,
|
||||
maxActionPreviewChars: 0,
|
||||
},
|
||||
} as TStartupConfig
|
||||
}
|
||||
>
|
||||
<SandboxPolicyProbe />
|
||||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
expect(screen.getByText('none:none:3:16384')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps App capacity in an isolated per-host Jotai store', () => {
|
||||
function Reserve({ label }: { label: string }) {
|
||||
const { reserveView } = useMCPAppsHost();
|
||||
const [accepted, setAccepted] = React.useState(false);
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => setAccepted(reserveView(label))}>{label}</button>
|
||||
<output>{`${label}:${accepted}`}</output>
|
||||
</>
|
||||
);
|
||||
}
|
||||
const config = {
|
||||
mcpApps: { enabled: true, legacyHtmlEnabled: true, maxActiveViews: 1 },
|
||||
} as TStartupConfig;
|
||||
render(
|
||||
<>
|
||||
<MCPAppsPolicyProvider ready userId="alice" startupConfig={config}>
|
||||
<Reserve label="first" />
|
||||
</MCPAppsPolicyProvider>
|
||||
<MCPAppsPolicyProvider ready userId="bob" startupConfig={config}>
|
||||
<Reserve label="second" />
|
||||
</MCPAppsPolicyProvider>
|
||||
</>,
|
||||
);
|
||||
// Each provider owns its own capacity; the other user's View remains independent.
|
||||
act(() => {
|
||||
screen.getByRole('button', { name: 'first' }).click();
|
||||
screen.getByRole('button', { name: 'second' }).click();
|
||||
});
|
||||
expect(screen.getByText('first:true')).toBeInTheDocument();
|
||||
expect(screen.getByText('second:true')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('tracks the startup cache without exposing pending, missing, or malformed policy', async () => {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
render(
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage })
|
|||
/**
|
||||
* Empty overrides are authoritative: a recovery prompt is not the user's next
|
||||
* compose, so `ask` must not attach or drain files, skills, or quotes already
|
||||
* staged in the composer.
|
||||
* staged in the composer. The agent and MCP server selection remains in scope.
|
||||
*/
|
||||
const recover = (text: string) =>
|
||||
chat?.ask({ text }, { overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] });
|
||||
|
|
@ -66,7 +66,7 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage })
|
|||
<div
|
||||
role="group"
|
||||
aria-labelledby={titleId}
|
||||
className="relative my-2 flex w-full flex-col rounded-xl border border-border-light bg-surface-secondary p-3"
|
||||
className="border-border-light bg-surface-secondary relative my-2 flex w-full flex-col rounded-xl border p-3"
|
||||
>
|
||||
<TooltipAnchor
|
||||
description={localize('com_ui_tool_call_limit_dismiss')}
|
||||
|
|
@ -77,7 +77,7 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage })
|
|||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label={localize('com_ui_tool_call_limit_dismiss')}
|
||||
className="absolute right-1.5 top-1.5 text-text-secondary focus-visible:ring-inset focus-visible:ring-offset-0"
|
||||
className="text-text-secondary absolute top-1.5 right-1.5 focus-visible:ring-offset-0 focus-visible:ring-inset"
|
||||
onClick={() => setDismissed(true)}
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden="true" />
|
||||
|
|
@ -86,12 +86,12 @@ export default function ToolCallLimitNotice({ message }: { message: TMessage })
|
|||
/>
|
||||
<p
|
||||
id={titleId}
|
||||
className="flex min-w-0 items-center gap-2 pr-8 text-sm font-medium text-text-primary"
|
||||
className="text-text-primary flex min-w-0 items-center gap-2 pr-8 text-sm font-medium"
|
||||
>
|
||||
<Gauge className="h-4 w-4 shrink-0 text-text-secondary" aria-hidden="true" />
|
||||
<Gauge className="text-text-secondary h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
{localize('com_ui_tool_call_limit_title')}
|
||||
</p>
|
||||
<p className="mb-3 mt-1 text-sm text-text-secondary">
|
||||
<p className="text-text-secondary mt-1 mb-3 text-sm">
|
||||
{localize('com_ui_tool_call_limit_body')}
|
||||
</p>
|
||||
{canAct && (
|
||||
|
|
|
|||
|
|
@ -91,14 +91,33 @@ jest.mock('../Parts', () => ({
|
|||
),
|
||||
}));
|
||||
|
||||
jest.mock('@librechat/client', () => ({
|
||||
Button: ({ children, onClick, ...props }: any) => (
|
||||
<button onClick={onClick} {...props}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
Spinner: (props: React.HTMLAttributes<HTMLSpanElement>) => <span {...props} />,
|
||||
}));
|
||||
jest.mock('@librechat/client', () => {
|
||||
const DialogPart = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;
|
||||
const DialogButton = ({
|
||||
children,
|
||||
onClick,
|
||||
}: {
|
||||
children?: React.ReactNode;
|
||||
onClick?: () => void;
|
||||
}) => <button onClick={onClick}>{children}</button>;
|
||||
return {
|
||||
Button: ({ children, onClick, ...props }: any) => (
|
||||
<button onClick={onClick} {...props}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
Spinner: (props: React.HTMLAttributes<HTMLSpanElement>) => <span {...props} />,
|
||||
AlertDialog: ({ children, open }: { children?: React.ReactNode; open: boolean }) =>
|
||||
open ? <div>{children}</div> : null,
|
||||
AlertDialogContent: DialogPart,
|
||||
AlertDialogHeader: DialogPart,
|
||||
AlertDialogTitle: DialogPart,
|
||||
AlertDialogDescription: DialogPart,
|
||||
AlertDialogFooter: DialogPart,
|
||||
AlertDialogAction: DialogButton,
|
||||
AlertDialogCancel: DialogButton,
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('lucide-react', () => ({
|
||||
ChevronDown: () => <span>{'ChevronDown'}</span>,
|
||||
|
|
@ -325,8 +344,9 @@ describe('ToolCall', () => {
|
|||
/>,
|
||||
);
|
||||
|
||||
// A server-bound inline resource renders through the sandbox bridge (not bare srcDoc),
|
||||
// so its App.connect handshake receives tool input/results.
|
||||
// Stored results do not run App code until the viewer explicitly opens the App.
|
||||
expect(container.querySelector('iframe[data-sandbox-url]')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
const iframe = container.querySelector('iframe[data-sandbox-url]');
|
||||
expect(iframe).toBeInTheDocument();
|
||||
const { useAppBridge } = jest.requireMock('~/hooks/MCP') as { useAppBridge: jest.Mock };
|
||||
|
|
@ -399,6 +419,8 @@ describe('ToolCall', () => {
|
|||
</MCPAppsPolicyProvider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
expect(container.querySelector('iframe[data-sandbox-url]')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
expect(container.querySelector('iframe[data-sandbox-url]')).toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
|
|
|
|||
|
|
@ -71,7 +71,11 @@ describe('ToolCallLimitNotice', () => {
|
|||
expect(ask).toHaveBeenCalledTimes(1);
|
||||
expect(ask).toHaveBeenCalledWith(
|
||||
{ text: TRANSLATIONS.com_ui_tool_call_limit_continue_prompt },
|
||||
{ overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] },
|
||||
{
|
||||
overrideFiles: [],
|
||||
overrideManualSkills: [],
|
||||
overrideQuotes: [],
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -85,7 +89,11 @@ describe('ToolCallLimitNotice', () => {
|
|||
|
||||
expect(ask).toHaveBeenCalledWith(
|
||||
{ text: TRANSLATIONS.com_ui_tool_call_limit_answer_prompt },
|
||||
{ overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] },
|
||||
{
|
||||
overrideFiles: [],
|
||||
overrideManualSkills: [],
|
||||
overrideQuotes: [],
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,31 @@
|
|||
import React, { useMemo } from 'react';
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { Button } from '@librechat/client';
|
||||
import type { TAttachment, UIResource } from 'librechat-data-provider';
|
||||
import { useMCPAppsHost } from '~/Providers/MCPAppsPolicyContext';
|
||||
import { selectToolCallUIResources } from '~/utils/mcpApps';
|
||||
import { useMCPAppsHost, useMCPAppViewAtCapacity } from '~/Providers/MCPAppsPolicyContext';
|
||||
import { selectToolCallUIResources, getInlineResourceHtml } from '~/utils/mcpApps';
|
||||
import { useIsMessagesViewReadOnly } from '~/Providers/MessagesViewContext';
|
||||
import { MCPAppApproval, useMCPAppApproval } from '~/hooks/MCP/approval';
|
||||
import { useAppBridge, useMCPAppFrame } from '~/hooks/MCP';
|
||||
import { MCPAppFrame } from './MCPAppFrame';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
const DEFAULT_APP_VIEW_HEIGHT = 320;
|
||||
|
||||
function CapacityNotice() {
|
||||
const localize = useLocalize();
|
||||
return useMCPAppViewAtCapacity() ? (
|
||||
<span role="alert">{localize('com_ui_mcp_app_at_capacity')}</span>
|
||||
) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attachments rendered by a stable ancestor. Presentation components may still receive those
|
||||
* attachments for files, search rows, and outcome metadata; only their duplicate App view stands
|
||||
|
|
@ -15,46 +33,198 @@ const DEFAULT_APP_VIEW_HEIGHT = 320;
|
|||
*/
|
||||
export const MCPAppSuppressionContext = React.createContext<ReadonlySet<TAttachment> | null>(null);
|
||||
|
||||
const MCPAppView = React.memo(function MCPAppView({
|
||||
function ActiveMCPAppView({
|
||||
app,
|
||||
userId,
|
||||
close,
|
||||
closeButtonRef,
|
||||
openButtonRef,
|
||||
ordinal,
|
||||
}: {
|
||||
app: UIResource;
|
||||
userId: string;
|
||||
close: (restoreFocus?: boolean) => void;
|
||||
closeButtonRef: React.RefObject<HTMLButtonElement>;
|
||||
openButtonRef: React.RefObject<HTMLButtonElement>;
|
||||
ordinal: number;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const approval = useMCPAppApproval();
|
||||
const frame = useMCPAppFrame(app, {
|
||||
defaultHeight: DEFAULT_APP_VIEW_HEIGHT,
|
||||
toolArgs: app.toolArgs,
|
||||
});
|
||||
|
||||
useAppBridge({
|
||||
iframeRef: frame.iframeRef,
|
||||
resource: app,
|
||||
toolArgs: frame.toolArgs,
|
||||
toolResult: frame.toolResult,
|
||||
userId,
|
||||
onRequestAction: approval.request,
|
||||
onCancelAction: approval.cancel,
|
||||
attempt: frame.attempt,
|
||||
active: frame.active,
|
||||
onSizeChanged: frame.onSizeChanged,
|
||||
onLoaded: frame.onLoaded,
|
||||
onTeardown: frame.onTeardown,
|
||||
onTeardown: () => {
|
||||
// A peer can tear down while the user is in its frame or approval dialog. Restore
|
||||
// their place without stealing focus if they have already moved elsewhere.
|
||||
const focusedInView =
|
||||
closeButtonRef.current?.parentElement?.contains(document.activeElement) ?? false;
|
||||
const focusedInApproval =
|
||||
approval.pending !== null &&
|
||||
document.activeElement?.closest('[role="alertdialog"]') != null;
|
||||
approval.cancel();
|
||||
close(focusedInView || focusedInApproval);
|
||||
},
|
||||
onFailed: frame.onFailed,
|
||||
});
|
||||
|
||||
if (frame.status === 'tornDown') {
|
||||
return null;
|
||||
}
|
||||
let body: React.ReactNode = null;
|
||||
if (frame.kind === 'unavailable') {
|
||||
return (
|
||||
body = (
|
||||
<div className="border-border-light bg-surface-secondary text-text-secondary my-2 flex items-center gap-2 rounded-lg border px-4 py-3 text-sm">
|
||||
{localize('com_ui_mcp_app_shared_unavailable')}
|
||||
</div>
|
||||
);
|
||||
} else if (frame.status !== 'tornDown') {
|
||||
body = (
|
||||
<div className="relative my-2 overflow-hidden" style={{ height: frame.height }}>
|
||||
<MCPAppFrame frame={frame} resource={app} spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
ref={closeButtonRef}
|
||||
onClick={() => close()}
|
||||
aria-label={localize('com_ui_mcp_app_close_named', { 0: app.toolName, 1: String(ordinal) })}
|
||||
>
|
||||
{localize('com_ui_mcp_app_close')}
|
||||
</Button>
|
||||
{body}
|
||||
<MCPAppApproval
|
||||
action={approval.pending}
|
||||
approve={approval.approve}
|
||||
cancel={approval.cancel}
|
||||
close={() => {
|
||||
approval.cancel();
|
||||
close();
|
||||
}}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
// The dialog has no persistent trigger. Return focus to the host View control.
|
||||
(openButtonRef.current ?? closeButtonRef.current)?.focus();
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const MCPAppView = React.memo(function MCPAppView({
|
||||
app,
|
||||
userId,
|
||||
ordinal,
|
||||
}: {
|
||||
app: UIResource;
|
||||
userId: string;
|
||||
ordinal: number;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const { reserveView, releaseView } = useMCPAppsHost();
|
||||
const readOnly = useIsMessagesViewReadOnly();
|
||||
const unavailable = readOnly && !getInlineResourceHtml(app);
|
||||
const viewKey = useId();
|
||||
const [opened, setOpened] = useState(false);
|
||||
const [atCapacity, setAtCapacity] = useState(false);
|
||||
const openButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const closeButtonRef = useRef<HTMLButtonElement>(null);
|
||||
const focusAfterTransition = useRef<'open' | 'close' | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const target = focusAfterTransition.current;
|
||||
if (!target) return;
|
||||
const button = target === 'open' ? openButtonRef.current : closeButtonRef.current;
|
||||
if (button) {
|
||||
focusAfterTransition.current = null;
|
||||
button.focus();
|
||||
}
|
||||
}, [opened]);
|
||||
useEffect(() => {
|
||||
if (unavailable) {
|
||||
releaseView(viewKey);
|
||||
setOpened(false);
|
||||
}
|
||||
}, [unavailable, releaseView, viewKey]);
|
||||
const close = useCallback(
|
||||
(restoreFocus = true) => {
|
||||
focusAfterTransition.current = restoreFocus ? 'open' : null;
|
||||
releaseView(viewKey);
|
||||
setOpened(false);
|
||||
setAtCapacity(false);
|
||||
},
|
||||
[releaseView, viewKey],
|
||||
);
|
||||
useEffect(
|
||||
() => () => {
|
||||
releaseView(viewKey);
|
||||
},
|
||||
[releaseView, viewKey],
|
||||
);
|
||||
const open = () => {
|
||||
if (unavailable) return;
|
||||
const reserved = reserveView(viewKey);
|
||||
if (!reserved) {
|
||||
setAtCapacity(true);
|
||||
return;
|
||||
}
|
||||
focusAfterTransition.current = 'close';
|
||||
setAtCapacity(false);
|
||||
setOpened(true);
|
||||
};
|
||||
if (unavailable) {
|
||||
return (
|
||||
<div
|
||||
className="border-border-light bg-surface-secondary text-text-secondary my-2 rounded-lg border px-4 py-3 text-sm"
|
||||
data-mcp-app-view={app.toolName}
|
||||
>
|
||||
{localize('com_ui_mcp_app_shared_unavailable')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="relative my-2 overflow-hidden" style={{ height: frame.height }}>
|
||||
<MCPAppFrame frame={frame} resource={app} spinner />
|
||||
<div className="my-2" data-mcp-app-view={app.toolName}>
|
||||
{opened ? (
|
||||
<ActiveMCPAppView
|
||||
app={app}
|
||||
userId={userId}
|
||||
close={close}
|
||||
closeButtonRef={closeButtonRef}
|
||||
openButtonRef={openButtonRef}
|
||||
ordinal={ordinal}
|
||||
/>
|
||||
) : (
|
||||
<div className="border-border-light bg-surface-secondary text-text-secondary flex min-h-16 items-center gap-3 rounded-lg border px-4 py-3 text-sm">
|
||||
<span className="min-w-0 flex-1 truncate">{app.toolName}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
ref={openButtonRef}
|
||||
onClick={open}
|
||||
aria-label={localize('com_ui_mcp_app_open_named', {
|
||||
0: app.toolName,
|
||||
1: String(ordinal),
|
||||
})}
|
||||
>
|
||||
{localize('com_ui_mcp_app_open')}
|
||||
</Button>
|
||||
{atCapacity && <CapacityNotice />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
|
@ -77,8 +247,13 @@ export function MCPAppViews({ attachments }: { attachments?: TAttachment[] }) {
|
|||
|
||||
return (
|
||||
<>
|
||||
{apps.map(({ key, resource }) => (
|
||||
<MCPAppView key={JSON.stringify([userId, key])} app={resource} userId={userId} />
|
||||
{apps.map(({ key, resource }, index) => (
|
||||
<MCPAppView
|
||||
key={JSON.stringify([userId, key])}
|
||||
app={resource}
|
||||
userId={userId}
|
||||
ordinal={index + 1}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { Tools } from 'librechat-data-provider';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { TAttachment, TStartupConfig, UIResource } from 'librechat-data-provider';
|
||||
import type { MCPAppFrameState } from '~/hooks/MCP';
|
||||
import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext';
|
||||
|
|
@ -8,8 +8,13 @@ import { MCPAppSuppressionContext, MCPAppViews } from '../MCPAppViews';
|
|||
import { useAppBridge, useMCPAppFrame } from '~/hooks/MCP';
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string, values?: Record<number, string>) =>
|
||||
key === 'com_ui_mcp_app_frame_title' ? `MCP App: ${values?.[0] ?? ''}` : key,
|
||||
useLocalize: () => (key: string, values?: Record<number, string>) => {
|
||||
if (key === 'com_ui_mcp_app_frame_title') return `MCP App: ${values?.[0] ?? ''}`;
|
||||
if (key === 'com_ui_mcp_app_open_named' || key === 'com_ui_mcp_app_close_named') {
|
||||
return `${key} ${values?.[0]} (${values?.[1]})`;
|
||||
}
|
||||
return key;
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks/MCP', () => ({
|
||||
|
|
@ -31,6 +36,7 @@ function app(overrides: Partial<UIResource>): UIResource {
|
|||
mimeType: 'text/html;profile=mcp-app',
|
||||
toolName: 'show_app',
|
||||
serverName: 'demo',
|
||||
text: '<p>view</p>',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
|
@ -121,6 +127,9 @@ describe('MCPAppViews', () => {
|
|||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
|
||||
expect(container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(0);
|
||||
expect(mockUseAppBridge).not.toHaveBeenCalled();
|
||||
screen.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ }).forEach(fireEvent.click);
|
||||
expect(container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(2);
|
||||
expect(mockUseAppBridge).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
|
|
@ -148,6 +157,136 @@ describe('MCPAppViews', () => {
|
|||
);
|
||||
});
|
||||
|
||||
it('gives duplicate App buttons distinct accessible names', () => {
|
||||
const attachments = [
|
||||
attachment({ toolCallId: 'dup', agentId: 'agent', stepId: 'step' }, [
|
||||
app({ resourceId: 'one' }),
|
||||
app({ resourceId: 'two' }),
|
||||
]),
|
||||
];
|
||||
const view = render(
|
||||
<MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">
|
||||
<MCPAppViews attachments={attachments} />
|
||||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
const buttons = view.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ });
|
||||
expect(buttons).toHaveLength(2);
|
||||
expect(buttons[0]).toHaveAccessibleName('com_ui_mcp_app_open_named show_app (1)');
|
||||
expect(buttons[1]).toHaveAccessibleName('com_ui_mcp_app_open_named show_app (2)');
|
||||
fireEvent.click(buttons[0]);
|
||||
expect(view.getByRole('button', { name: /com_ui_mcp_app_close_named/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('applies the published limit to all Views and clears failed capacity notices on release', () => {
|
||||
const config = {
|
||||
mcpApps: { enabled: true, legacyHtmlEnabled: true, maxActiveViews: 1 },
|
||||
} as TStartupConfig;
|
||||
const attachments = [
|
||||
attachment({ toolCallId: 'bounded', agentId: 'agent', stepId: 'step' }, [
|
||||
app({ resourceId: 'first' }),
|
||||
app({ resourceId: 'second' }),
|
||||
]),
|
||||
];
|
||||
const view = render(
|
||||
<MCPAppsPolicyProvider startupConfig={config} ready userId="user-1">
|
||||
<MCPAppViews attachments={attachments} />
|
||||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
const buttons = view.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ });
|
||||
fireEvent.click(buttons[0]);
|
||||
fireEvent.click(buttons[1]);
|
||||
expect(view.getByRole('alert')).toHaveTextContent('com_ui_mcp_app_at_capacity');
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_close_named/ }));
|
||||
expect(view.queryByRole('alert')).not.toBeInTheDocument();
|
||||
fireEvent.click(view.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ })[1]);
|
||||
expect(view.container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('returns keyboard focus to the replacement App control without stealing focus on peer teardown', () => {
|
||||
const attachments = [
|
||||
attachment({ toolCallId: 'focus', agentId: 'agent', stepId: 'step' }, [app({})]),
|
||||
];
|
||||
const view = render(
|
||||
<MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">
|
||||
<MCPAppViews attachments={attachments} />
|
||||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
const open = view.getByRole('button', { name: /com_ui_mcp_app_open_named/ });
|
||||
open.focus();
|
||||
fireEvent.click(open);
|
||||
const close = view.getByRole('button', { name: /com_ui_mcp_app_close_named/ });
|
||||
expect(close).toHaveFocus();
|
||||
fireEvent.click(close);
|
||||
expect(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ })).toHaveFocus();
|
||||
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
view.getByRole('button', { name: /com_ui_mcp_app_close_named/ }).focus();
|
||||
act(() => {
|
||||
mockUseAppBridge.mock.calls.at(-1)?.[0].onTeardown?.();
|
||||
});
|
||||
expect(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ })).toHaveFocus();
|
||||
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
const unrelated = document.createElement('button');
|
||||
document.body.appendChild(unrelated);
|
||||
unrelated.focus();
|
||||
act(() => {
|
||||
mockUseAppBridge.mock.calls.at(-1)?.[0].onTeardown?.();
|
||||
});
|
||||
expect(unrelated).toHaveFocus();
|
||||
expect(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ })).toBeInTheDocument();
|
||||
unrelated.remove();
|
||||
});
|
||||
|
||||
it('does not reserve capacity or mount a bridge for a read-only URI-only App', () => {
|
||||
const config = {
|
||||
mcpApps: { enabled: true, legacyHtmlEnabled: true, maxActiveViews: 1 },
|
||||
} as TStartupConfig;
|
||||
const attachments = [
|
||||
attachment({ toolCallId: 'read-only', agentId: 'agent', stepId: 'step' }, [
|
||||
app({ text: undefined, resourceId: 'uri-only' }),
|
||||
app({ resourceId: 'inline' }),
|
||||
]),
|
||||
];
|
||||
const view = render(
|
||||
<MCPAppsPolicyProvider startupConfig={config} ready userId="user-1">
|
||||
<MCPAppViews attachments={attachments} />
|
||||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
expect(view.getByText('com_ui_mcp_app_shared_unavailable')).toBeInTheDocument();
|
||||
expect(mockUseMCPAppFrame).not.toHaveBeenCalled();
|
||||
expect(view.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ })).toHaveLength(1);
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
expect(view.container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('limits simultaneous live bridges and releases the slot on close', () => {
|
||||
const attachments = [
|
||||
attachment(
|
||||
{ toolCallId: 'batch', agentId: 'agent', stepId: 'step' },
|
||||
Array.from({ length: 4 }, (_, i) => app({ resourceId: `r${i}`, toolName: `tool${i}` })),
|
||||
),
|
||||
];
|
||||
const view = render(
|
||||
<MCPAppsPolicyProvider startupConfig={enabledConfig} ready userId="user-1">
|
||||
<MCPAppViews attachments={attachments} />
|
||||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
expect(mockUseAppBridge).not.toHaveBeenCalled();
|
||||
view
|
||||
.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ })
|
||||
.slice(0, 3)
|
||||
.forEach(fireEvent.click);
|
||||
expect(view.container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(3);
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
expect(view.getByRole('alert')).toHaveTextContent('com_ui_mcp_app_at_capacity');
|
||||
expect(view.container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(3);
|
||||
fireEvent.click(view.getAllByRole('button', { name: /com_ui_mcp_app_close_named/ })[0]);
|
||||
expect(view.container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(2);
|
||||
fireEvent.click(view.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ }).at(-1)!);
|
||||
expect(view.container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('keeps legitimate same-owner and same-resource occurrences distinct', () => {
|
||||
const attachments = [
|
||||
attachment({ toolCallId: 'call-0', agentId: 'agent-alpha', stepId: 'step-alpha' }, [
|
||||
|
|
@ -162,6 +301,9 @@ describe('MCPAppViews', () => {
|
|||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
|
||||
expect(container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(0);
|
||||
expect(mockUseAppBridge).not.toHaveBeenCalled();
|
||||
screen.getAllByRole('button', { name: /com_ui_mcp_app_open_named/ }).forEach(fireEvent.click);
|
||||
expect(container.querySelectorAll('iframe[data-sandbox-url]')).toHaveLength(2);
|
||||
expect(mockUseAppBridge.mock.calls.map(([params]) => params.toolArgs)).toEqual([
|
||||
{ occurrence: 'first' },
|
||||
|
|
@ -194,6 +336,8 @@ describe('MCPAppViews', () => {
|
|||
</MCPAppsPolicyProvider>
|
||||
);
|
||||
const view = render(renderViews([targetAttachment]));
|
||||
expect(view.queryByTitle('MCP App: target')).not.toBeInTheDocument();
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
const targetFrame = view.getByTitle('MCP App: target');
|
||||
|
||||
view.rerender(renderViews([unrelatedAttachment, targetAttachment]));
|
||||
|
|
@ -227,6 +371,8 @@ describe('MCPAppViews', () => {
|
|||
);
|
||||
|
||||
expect(view.queryByTitle('MCP App: owned')).not.toBeInTheDocument();
|
||||
expect(view.queryByTitle('MCP App: nested')).not.toBeInTheDocument();
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
expect(view.getByTitle('MCP App: nested')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
|
@ -249,6 +395,8 @@ describe('MCPAppViews', () => {
|
|||
<MCPAppViews attachments={attachments} />
|
||||
</MCPAppsPolicyProvider>,
|
||||
);
|
||||
expect(view.queryByTitle('MCP App: compact')).not.toBeInTheDocument();
|
||||
fireEvent.click(view.getByRole('button', { name: /com_ui_mcp_app_open_named/ }));
|
||||
const container = view.getByTitle('MCP App: compact').parentElement;
|
||||
|
||||
expect(container).toHaveStyle({ height: `${height}px` });
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import type {
|
|||
TConversation,
|
||||
TMessage,
|
||||
TSubmission,
|
||||
TEphemeralAgent,
|
||||
} from 'librechat-data-provider';
|
||||
import { activeUsageResponseIdFamily, pendingUsageFamily } from '~/store/usage';
|
||||
import { revealedQueuedTurnFamily } from '~/store/steer';
|
||||
|
|
@ -16,7 +17,7 @@ import { isPasteSubmitted } from '~/utils';
|
|||
const mockNavigate = jest.fn();
|
||||
const mockSetShowStopButton = jest.fn();
|
||||
const mockSetIsSubmitting = jest.fn();
|
||||
const mockGetEphemeralAgent = jest.fn(() => null);
|
||||
const mockGetEphemeralAgent = jest.fn((): TEphemeralAgent | null => null);
|
||||
const mockSetFilesToDelete = jest.fn();
|
||||
const mockGetSender = jest.fn(() => 'Assistant');
|
||||
const mockGetExpiry = jest.fn(() => 'expiry-key');
|
||||
|
|
@ -523,6 +524,9 @@ describe('useChatFunctions ask attachments', () => {
|
|||
jest.clearAllMocks();
|
||||
mockGetQueryData.mockReturnValue({});
|
||||
});
|
||||
afterEach(() => {
|
||||
mockGetEphemeralAgent.mockReturnValue(null);
|
||||
});
|
||||
|
||||
/** The server titles an attachment-only turn from the submitted filenames
|
||||
* (getAttachmentTitleText), so the fresh-file mapping must carry them. */
|
||||
|
|
@ -567,6 +571,141 @@ describe('useChatFunctions ask attachments', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('keeps the next composer file staged when a text-only App message uses empty overrides', () => {
|
||||
const setMessages = jest.fn();
|
||||
const setSubmission = jest.fn();
|
||||
const setFiles = jest.fn();
|
||||
const files = new Map([
|
||||
[
|
||||
'app-next-draft-file',
|
||||
{
|
||||
file_id: 'app-next-draft-file',
|
||||
filepath: '/uploads/app-next-draft-file',
|
||||
filename: 'private-next-message.pdf',
|
||||
type: 'application/pdf',
|
||||
},
|
||||
],
|
||||
]) as unknown as Parameters<typeof useChatFunctions>[0]['files'];
|
||||
const { result } = renderHook(() =>
|
||||
useChatFunctions({
|
||||
isSubmitting: false,
|
||||
latestMessage: null,
|
||||
conversation: conversation(Constants.NEW_CONVO as string),
|
||||
getMessages: () => [],
|
||||
setMessages,
|
||||
setSubmission,
|
||||
files,
|
||||
setFiles,
|
||||
}),
|
||||
);
|
||||
const selectedConversationTools: TEphemeralAgent = {
|
||||
skills: true,
|
||||
mcp: ['selected-server'],
|
||||
};
|
||||
mockGetEphemeralAgent.mockReturnValue(selectedConversationTools);
|
||||
|
||||
act(() => {
|
||||
result.current.ask(
|
||||
{ text: 'approved App message' },
|
||||
{
|
||||
overrideFiles: [],
|
||||
overrideManualSkills: [],
|
||||
overrideQuotes: [],
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
|
||||
expect(submission.userMessage.text).toBe('approved App message');
|
||||
expect(submission.userMessage.files).toBeUndefined();
|
||||
expect(submission.userMessage.manualSkills).toBeUndefined();
|
||||
expect(submission.userMessage.quotes).toBeUndefined();
|
||||
expect(submission.ephemeralAgent).toEqual(selectedConversationTools);
|
||||
expect(mockGetEphemeralAgent).toHaveBeenCalledTimes(1);
|
||||
expect(files?.has('app-next-draft-file')).toBe(true);
|
||||
expect(setFiles).not.toHaveBeenCalled();
|
||||
expect(isPasteSubmitted('app-next-draft-file')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a blank text-only App turn even when the composer contains a staged file', () => {
|
||||
const setSubmission = jest.fn();
|
||||
const files = new Map([
|
||||
['staged-file', { file_id: 'staged-file', filename: 'private-draft.pdf' }],
|
||||
]) as unknown as Parameters<typeof useChatFunctions>[0]['files'];
|
||||
const { result } = renderHook(() =>
|
||||
useChatFunctions({
|
||||
isSubmitting: false,
|
||||
latestMessage: null,
|
||||
conversation: conversation(Constants.NEW_CONVO as string),
|
||||
getMessages: () => [],
|
||||
setMessages: jest.fn(),
|
||||
setSubmission,
|
||||
files,
|
||||
setFiles: jest.fn(),
|
||||
}),
|
||||
);
|
||||
let accepted: ReturnType<typeof result.current.ask>;
|
||||
act(() => {
|
||||
accepted = result.current.ask(
|
||||
{ text: ' ' },
|
||||
{
|
||||
overrideFiles: [],
|
||||
overrideManualSkills: [],
|
||||
overrideQuotes: [],
|
||||
},
|
||||
);
|
||||
});
|
||||
expect(accepted!).toBe(false);
|
||||
expect(setSubmission).not.toHaveBeenCalled();
|
||||
expect(files?.has('staged-file')).toBe(true);
|
||||
});
|
||||
|
||||
it('treats a legacy null file override as an ordinary staged-file submission', () => {
|
||||
const files = new Map([
|
||||
['legacy-draft-file', { file_id: 'legacy-draft-file', filename: 'draft.pdf' }],
|
||||
]) as unknown as Parameters<typeof useChatFunctions>[0]['files'];
|
||||
const setSubmission = jest.fn();
|
||||
const { result } = renderHook(() =>
|
||||
useChatFunctions({
|
||||
isSubmitting: false,
|
||||
latestMessage: null,
|
||||
conversation: conversation(Constants.NEW_CONVO as string),
|
||||
getMessages: () => [],
|
||||
setMessages: jest.fn(),
|
||||
setSubmission,
|
||||
files,
|
||||
setFiles: jest.fn(),
|
||||
}),
|
||||
);
|
||||
act(() => {
|
||||
result.current.ask(
|
||||
{ text: '' },
|
||||
{
|
||||
overrideFiles: null as unknown as NonNullable<
|
||||
Parameters<typeof result.current.ask>[1]
|
||||
>['overrideFiles'],
|
||||
},
|
||||
);
|
||||
});
|
||||
expect(setSubmission).toHaveBeenCalledTimes(1);
|
||||
expect((setSubmission.mock.calls[0][0] as TSubmission).userMessage.files).toEqual([
|
||||
expect.objectContaining({ file_id: 'legacy-draft-file' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('still uses a staged ephemeral agent for an ordinary composer submission', () => {
|
||||
const stagedAgent: TEphemeralAgent = { skills: true, mcp: ['selected-tool'] };
|
||||
mockGetEphemeralAgent.mockReturnValue(stagedAgent);
|
||||
const { result, setSubmission } = renderAsk([], 'conversation-1');
|
||||
act(() => {
|
||||
result.current.ask({ text: 'normal user draft' });
|
||||
});
|
||||
expect(mockGetEphemeralAgent).toHaveBeenCalledTimes(1);
|
||||
expect((setSubmission.mock.calls.at(-1)?.[0] as TSubmission).ephemeralAgent).toEqual(
|
||||
stagedAgent,
|
||||
);
|
||||
});
|
||||
|
||||
it('marks files consumed through overrideFiles as submitted', () => {
|
||||
const overrideFiles = [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -318,12 +318,12 @@ export default function useChatFunctions({
|
|||
text = text.trim();
|
||||
/**
|
||||
* Attached files make an otherwise empty draft submittable, e.g. replying
|
||||
* to an agent that asked for a document upload. Replayed turns (regenerate,
|
||||
* or save-and-submit carrying `overrideFiles`) reuse stored attachments that
|
||||
* aren't in the compose `files` map, so count those too and never re-block a
|
||||
* regenerate of an already-validated file-only turn.
|
||||
* to an agent that asked for a document upload. When a caller supplies
|
||||
* `overrideFiles`, that array is authoritative, even when empty. A text-only
|
||||
* App action must not become submittable just because the user has staged
|
||||
* a file for a different, unsent composer message.
|
||||
*/
|
||||
const replayFileCount = overrideFiles?.length ?? 0;
|
||||
const availableFileCount = overrideFiles == null ? (files?.size ?? 0) : overrideFiles.length;
|
||||
/** A compaction sends no text: it replays the branch, like a regenerate,
|
||||
* with the response placeholder parented onto the leaf. */
|
||||
const regenerateShaped = isRegenerate || compact;
|
||||
|
|
@ -331,7 +331,7 @@ export default function useChatFunctions({
|
|||
!!isSubmitting ||
|
||||
jotaiStore.get(revealedQueuedTurnFamily(immutableConversation?.conversationId ?? '')) !=
|
||||
null ||
|
||||
(!regenerateShaped && !isSubmittableMessage(text, (files?.size ?? 0) + replayFileCount))
|
||||
(!regenerateShaped && !isSubmittableMessage(text, availableFileCount))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
185
client/src/hooks/MCP/__tests__/approval.spec.tsx
Normal file
185
client/src/hooks/MCP/__tests__/approval.spec.tsx
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
import React from 'react';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MCPAppApproval, useMCPAppApproval } from '../approval';
|
||||
|
||||
jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
|
||||
|
||||
const action = {
|
||||
kind: 'tool' as const,
|
||||
serverName: 'fixture',
|
||||
toolName: 'remove',
|
||||
argumentsText: '{"id":"1"}',
|
||||
};
|
||||
|
||||
function Harness({
|
||||
onReady,
|
||||
onClose,
|
||||
}: {
|
||||
onReady: (approval: ReturnType<typeof useMCPAppApproval>) => void;
|
||||
onClose?: () => void;
|
||||
}) {
|
||||
const approval = useMCPAppApproval();
|
||||
onReady(approval);
|
||||
return (
|
||||
<MCPAppApproval
|
||||
action={approval.pending}
|
||||
approve={approval.approve}
|
||||
cancel={approval.cancel}
|
||||
close={
|
||||
onClose
|
||||
? () => {
|
||||
approval.cancel();
|
||||
onClose();
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
test('requires a host click before approving the exact tool request', async () => {
|
||||
let approval!: ReturnType<typeof useMCPAppApproval>;
|
||||
const view = render(<Harness onReady={(value) => (approval = value)} />);
|
||||
let result!: Promise<boolean>;
|
||||
const controller = new AbortController();
|
||||
act(() => {
|
||||
result = approval.request(action, controller.signal);
|
||||
});
|
||||
expect(screen.getByRole('alertdialog')).toHaveTextContent('fixture / remove');
|
||||
expect(screen.getByRole('alertdialog')).toHaveTextContent('{"id":"1"}');
|
||||
expect(screen.getByRole('alertdialog')).not.toHaveTextContent(
|
||||
'com_ui_mcp_app_message_tool_context',
|
||||
);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_mcp_app_run_tool' }));
|
||||
});
|
||||
await expect(result).resolves.toBe(true);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
test('discloses conversation tool context before an App-authored chat turn is approved', async () => {
|
||||
let approval!: ReturnType<typeof useMCPAppApproval>;
|
||||
const view = render(<Harness onReady={(value) => (approval = value)} />);
|
||||
let result!: Promise<boolean>;
|
||||
act(() => {
|
||||
result = approval.request(
|
||||
{ kind: 'message', serverName: 'fixture', text: 'continue' },
|
||||
new AbortController().signal,
|
||||
);
|
||||
});
|
||||
expect(screen.getByRole('alertdialog')).toHaveTextContent('com_ui_mcp_app_message_tool_context');
|
||||
act(() => approval.cancel());
|
||||
await expect(result).resolves.toBe(false);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
test('rejects simultaneous App requests and lets the user deny the first', async () => {
|
||||
let approval!: ReturnType<typeof useMCPAppApproval>;
|
||||
const view = render(<Harness onReady={(value) => (approval = value)} />);
|
||||
let first!: Promise<boolean>;
|
||||
act(() => {
|
||||
first = approval.request(action, new AbortController().signal);
|
||||
});
|
||||
await expect(
|
||||
approval.request(
|
||||
{ kind: 'message', serverName: 'fixture', text: 'next' },
|
||||
new AbortController().signal,
|
||||
),
|
||||
).resolves.toBe(false);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_cancel' }));
|
||||
});
|
||||
await expect(first).resolves.toBe(false);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
test('denying once suppresses repeated prompts until the View is reopened', async () => {
|
||||
let approval!: ReturnType<typeof useMCPAppApproval>;
|
||||
const view = render(<Harness onReady={(value) => (approval = value)} />);
|
||||
let first!: Promise<boolean>;
|
||||
act(() => {
|
||||
first = approval.request(action, new AbortController().signal);
|
||||
});
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_cancel' }));
|
||||
});
|
||||
await expect(first).resolves.toBe(false);
|
||||
for (let i = 0; i < 100; i++) {
|
||||
await expect(approval.request(action, new AbortController().signal)).resolves.toBe(false);
|
||||
}
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
|
||||
view.unmount();
|
||||
let reopened!: ReturnType<typeof useMCPAppApproval>;
|
||||
const next = render(<Harness onReady={(value) => (reopened = value)} />);
|
||||
let fresh!: Promise<boolean>;
|
||||
act(() => {
|
||||
fresh = reopened.request(action, new AbortController().signal);
|
||||
});
|
||||
expect(screen.getByRole('alertdialog')).toBeInTheDocument();
|
||||
act(() => {
|
||||
reopened.cancel();
|
||||
});
|
||||
await expect(fresh).resolves.toBe(false);
|
||||
next.unmount();
|
||||
});
|
||||
|
||||
test('the host Stop app control denies the current action and closes its View', async () => {
|
||||
let approval!: ReturnType<typeof useMCPAppApproval>;
|
||||
const onClose = jest.fn();
|
||||
const view = render(<Harness onReady={(value) => (approval = value)} onClose={onClose} />);
|
||||
let pending!: Promise<boolean>;
|
||||
act(() => {
|
||||
pending = approval.request(action, new AbortController().signal);
|
||||
});
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_mcp_app_stop' }));
|
||||
});
|
||||
await expect(pending).resolves.toBe(false);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
await expect(approval.request(action, new AbortController().signal)).resolves.toBe(false);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
test('an App-aborted displayed request suspends future prompts until the View is reopened', async () => {
|
||||
let approval!: ReturnType<typeof useMCPAppApproval>;
|
||||
const view = render(<Harness onReady={(value) => (approval = value)} />);
|
||||
const controller = new AbortController();
|
||||
let first!: Promise<boolean>;
|
||||
act(() => {
|
||||
first = approval.request(action, controller.signal);
|
||||
});
|
||||
expect(screen.getByRole('alertdialog')).toBeInTheDocument();
|
||||
act(() => controller.abort());
|
||||
await expect(first).resolves.toBe(false);
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
|
||||
for (let i = 0; i < 100; i++) {
|
||||
await expect(approval.request(action, new AbortController().signal)).resolves.toBe(false);
|
||||
}
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
|
||||
view.unmount();
|
||||
|
||||
let reopened!: ReturnType<typeof useMCPAppApproval>;
|
||||
const next = render(<Harness onReady={(value) => (reopened = value)} />);
|
||||
let fresh!: Promise<boolean>;
|
||||
act(() => {
|
||||
fresh = reopened.request(action, new AbortController().signal);
|
||||
});
|
||||
expect(screen.getByRole('alertdialog')).toBeInTheDocument();
|
||||
next.unmount();
|
||||
await expect(fresh).resolves.toBe(false);
|
||||
});
|
||||
|
||||
test('an already aborted request does not suspend a fresh View', async () => {
|
||||
let approval!: ReturnType<typeof useMCPAppApproval>;
|
||||
const view = render(<Harness onReady={(value) => (approval = value)} />);
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
await expect(approval.request(action, aborted.signal)).resolves.toBe(false);
|
||||
let pending!: Promise<boolean>;
|
||||
act(() => {
|
||||
pending = approval.request(action, new AbortController().signal);
|
||||
});
|
||||
expect(screen.getByRole('alertdialog')).toBeInTheDocument();
|
||||
view.unmount();
|
||||
await expect(pending).resolves.toBe(false);
|
||||
});
|
||||
|
|
@ -24,6 +24,7 @@ type RequestHandler = (
|
|||
extra: ReturnType<typeof requestExtra>,
|
||||
) => Promise<unknown>;
|
||||
const mockAsk = jest.fn();
|
||||
const mockApproveAction = jest.fn();
|
||||
|
||||
class FakeAppBridge {
|
||||
static instances: FakeAppBridge[] = [];
|
||||
|
|
@ -130,6 +131,8 @@ jest.mock('~/hooks', () => ({
|
|||
key === 'com_ui_mcp_app_frame_title' ? `MCP App: ${values?.[0] ?? ''}` : key,
|
||||
}));
|
||||
|
||||
const mockPreviewLimit = jest.fn((): number | undefined => undefined);
|
||||
|
||||
jest.mock('~/Providers', () => ({
|
||||
useOptionalMessagesOperations: () => ({ ask: mockAsk }),
|
||||
useIsMessagesViewReadOnly: jest.fn(() => false),
|
||||
|
|
@ -137,6 +140,7 @@ jest.mock('~/Providers', () => ({
|
|||
enabled: true,
|
||||
legacyHtmlEnabled: true,
|
||||
cspLimits: { maxSourcesPerDirective: 32, maxSerializedLength: 4096 },
|
||||
maxActionPreviewChars: mockPreviewLimit(),
|
||||
}),
|
||||
}));
|
||||
|
||||
|
|
@ -201,7 +205,12 @@ function BridgeFrameHarness({ resource, userId }: { resource: UIResource; userId
|
|||
function mountBridge(
|
||||
resource: UIResource,
|
||||
client: QueryClient,
|
||||
callbacks: { onFailed?: () => void; onTeardown?: () => void; userId?: string } = {},
|
||||
callbacks: {
|
||||
onFailed?: () => void;
|
||||
onTeardown?: () => void;
|
||||
userId?: string;
|
||||
withoutApproval?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.setAttribute('data-sandbox-url', SANDBOX_URL);
|
||||
|
|
@ -220,6 +229,7 @@ function mountBridge(
|
|||
toolArgs: { q: 1 },
|
||||
toolResult: { content: [] },
|
||||
userId: callbacks.userId,
|
||||
onRequestAction: callbacks.withoutApproval ? undefined : mockApproveAction,
|
||||
attempt: 0,
|
||||
onSizeChanged: jest.fn(),
|
||||
onLoaded: jest.fn(),
|
||||
|
|
@ -252,6 +262,8 @@ describe('useAppBridge', () => {
|
|||
);
|
||||
mockReadOnly.mockReturnValue(false);
|
||||
mockAsk.mockReset();
|
||||
mockApproveAction.mockReset().mockResolvedValue(true);
|
||||
mockPreviewLimit.mockReturnValue(undefined);
|
||||
mockFetchHtml.mockResolvedValue({ html: '<p>app</p>' });
|
||||
mockValidateBinding.mockResolvedValue();
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
|
|
@ -938,6 +950,21 @@ describe('useAppBridge', () => {
|
|||
expect(openSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses an otherwise allowed link after View disposal', async () => {
|
||||
mockFetchHtml.mockResolvedValue({
|
||||
html: '<p>app</p>',
|
||||
csp: { connectDomains: ['https://api.example.com'] },
|
||||
});
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const bridge = latest();
|
||||
view.unmount();
|
||||
await expect(
|
||||
bridge.onopenlink?.({ url: 'https://api.example.com/x' }, requestExtra()),
|
||||
).resolves.toEqual({ isError: true });
|
||||
expect(openSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports cancellation and thrown browser failures', async () => {
|
||||
mockFetchHtml.mockResolvedValue({
|
||||
html: '<p>app</p>',
|
||||
|
|
@ -980,16 +1007,215 @@ describe('useAppBridge', () => {
|
|||
'binding-demo',
|
||||
'next',
|
||||
{ q: 2 },
|
||||
extra.signal,
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
expect(mockReadResource).toHaveBeenCalledWith(
|
||||
'demo',
|
||||
'binding-demo',
|
||||
'ui://detail',
|
||||
extra.signal,
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
expect(mockListResources).toHaveBeenCalledWith('demo', 'binding-demo', 'a', extra.signal);
|
||||
expect(mockListTemplates).toHaveBeenCalledWith('demo', 'binding-demo', 'b', extra.signal);
|
||||
expect(mockListResources).toHaveBeenCalledWith(
|
||||
'demo',
|
||||
'binding-demo',
|
||||
'a',
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
expect(mockListTemplates).toHaveBeenCalledWith(
|
||||
'demo',
|
||||
'binding-demo',
|
||||
'b',
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
});
|
||||
|
||||
it('aborts active resource operations and denies new requests after View disposal', async () => {
|
||||
mockReadResource.mockResolvedValue({ contents: [] });
|
||||
mockListResources.mockResolvedValue({ resources: [] });
|
||||
mockListTemplates.mockResolvedValue({ resourceTemplates: [] });
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const bridge = latest();
|
||||
await bridge.onreadresource?.({ uri: 'ui://detail' }, requestExtra());
|
||||
await bridge.onlistresources?.({ cursor: 'a' }, requestExtra());
|
||||
await bridge.onlistresourcetemplates?.({ cursor: 'b' }, requestExtra());
|
||||
const readSignal = mockReadResource.mock.calls[0][3];
|
||||
const resourcesSignal = mockListResources.mock.calls[0][3];
|
||||
const templatesSignal = mockListTemplates.mock.calls[0][3];
|
||||
expect(readSignal?.aborted).toBe(false);
|
||||
view.unmount();
|
||||
expect(readSignal?.aborted).toBe(true);
|
||||
expect(resourcesSignal?.aborted).toBe(true);
|
||||
expect(templatesSignal?.aborted).toBe(true);
|
||||
await expect(
|
||||
bridge.onreadresource?.({ uri: 'ui://detail' }, requestExtra()),
|
||||
).rejects.toMatchObject({ name: 'AbortError' });
|
||||
await expect(bridge.onlistresources?.({ cursor: 'a' }, requestExtra())).rejects.toMatchObject(
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
await expect(
|
||||
bridge.onlistresourcetemplates?.({ cursor: 'b' }, requestExtra()),
|
||||
).rejects.toMatchObject({ name: 'AbortError' });
|
||||
expect(mockReadResource).toHaveBeenCalledTimes(1);
|
||||
expect(mockListResources).toHaveBeenCalledTimes(1);
|
||||
expect(mockListTemplates).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('denies App tool and message actions without a host approval control', async () => {
|
||||
const view = mountBridge(makeResource(), client, { withoutApproval: true });
|
||||
await flush();
|
||||
// A caller outside an active host View has no approval authority.
|
||||
const bridge = latest();
|
||||
expect(await bridge.oncalltool?.({ name: 'next', arguments: {} }, requestExtra())).toEqual({
|
||||
content: [],
|
||||
isError: true,
|
||||
});
|
||||
expect(
|
||||
await bridge.onmessage?.({ content: [{ type: 'text', text: 'submit' }] }, requestExtra()),
|
||||
).toEqual({ isError: true });
|
||||
expect(mockApproveAction).not.toHaveBeenCalled();
|
||||
expect(mockCallTool).not.toHaveBeenCalled();
|
||||
expect(mockAsk).not.toHaveBeenCalled();
|
||||
view.view.unmount();
|
||||
});
|
||||
|
||||
it('submits only approved App text without draining staged composer context', async () => {
|
||||
let grant: ((allowed: boolean) => void) | undefined;
|
||||
mockApproveAction.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
grant = resolve;
|
||||
}),
|
||||
);
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const pending = latest().onmessage?.(
|
||||
{
|
||||
content: [
|
||||
{ type: 'text', text: 'approved' },
|
||||
{ type: 'text', text: 'message' },
|
||||
],
|
||||
},
|
||||
requestExtra(),
|
||||
);
|
||||
await flush();
|
||||
expect(mockApproveAction).toHaveBeenCalledWith(
|
||||
{ kind: 'message', serverName: 'demo', text: 'approved\nmessage' },
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
expect(mockAsk).not.toHaveBeenCalled();
|
||||
grant?.(true);
|
||||
await expect(pending).resolves.toEqual({});
|
||||
expect(mockAsk).toHaveBeenCalledTimes(1);
|
||||
expect(mockAsk).toHaveBeenCalledWith(
|
||||
{ text: 'approved\nmessage' },
|
||||
{ overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] },
|
||||
);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it('acknowledges an accepted turn even when the App aborts immediately afterward', async () => {
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const controller = new AbortController();
|
||||
mockAsk.mockImplementationOnce(() => {
|
||||
controller.abort();
|
||||
return undefined;
|
||||
});
|
||||
const result = await latest().onmessage?.(
|
||||
{ content: [{ type: 'text', text: 'approved turn' }] },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(mockApproveAction).toHaveBeenCalledTimes(1);
|
||||
expect(mockAsk).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({});
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it('does not ask for approval for a whitespace-only App message', async () => {
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const result = await latest().onmessage?.(
|
||||
{ content: [{ type: 'text', text: ' ' }] },
|
||||
requestExtra(),
|
||||
);
|
||||
expect(result).toEqual({ isError: true });
|
||||
expect(mockApproveAction).not.toHaveBeenCalled();
|
||||
expect(mockAsk).not.toHaveBeenCalled();
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it('uses the published preview limit for both tool arguments and chat messages', async () => {
|
||||
mockCallTool.mockResolvedValue({ content: [] });
|
||||
mockPreviewLimit.mockReturnValue(10);
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const bridge = latest();
|
||||
expect(
|
||||
await bridge.oncalltool?.({ name: 'next', arguments: { query: 42 } }, requestExtra()),
|
||||
).toEqual({ content: [], isError: true });
|
||||
expect(
|
||||
await bridge.onmessage?.(
|
||||
{ content: [{ type: 'text', text: 'more than ten' }] },
|
||||
requestExtra(),
|
||||
),
|
||||
).toEqual({ isError: true });
|
||||
expect(mockApproveAction).not.toHaveBeenCalled();
|
||||
await bridge.oncalltool?.({ name: 'next', arguments: { q: 2 } }, requestExtra());
|
||||
await bridge.onmessage?.({ content: [{ type: 'text', text: 'ten chars!' }] }, requestExtra());
|
||||
expect(mockApproveAction).toHaveBeenCalledTimes(2);
|
||||
expect(mockCallTool).toHaveBeenCalledTimes(1);
|
||||
expect(mockAsk).toHaveBeenCalledTimes(1);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it('waits for permission and executes the exact arguments shown to the host once', async () => {
|
||||
let grant: ((allowed: boolean) => void) | undefined;
|
||||
mockApproveAction.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
grant = resolve;
|
||||
}),
|
||||
);
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const args = { q: 2 };
|
||||
const request = latest().oncalltool?.({ name: 'next', arguments: args }, requestExtra());
|
||||
await flush();
|
||||
expect(mockApproveAction).toHaveBeenCalledWith(
|
||||
{ kind: 'tool', serverName: 'demo', toolName: 'next', argumentsText: '{"q":2}' },
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
args.q = 42;
|
||||
expect(mockCallTool).not.toHaveBeenCalled();
|
||||
grant?.(true);
|
||||
await request;
|
||||
expect(mockCallTool).toHaveBeenCalledWith(
|
||||
'demo',
|
||||
'binding-demo',
|
||||
'next',
|
||||
{ q: 2 },
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it('does not run a tool if approval settles after View disposal', async () => {
|
||||
let grant: ((allowed: boolean) => void) | undefined;
|
||||
mockApproveAction.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
grant = resolve;
|
||||
}),
|
||||
);
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const request = latest().oncalltool?.({ name: 'next', arguments: {} }, requestExtra());
|
||||
await flush();
|
||||
view.unmount();
|
||||
grant?.(true);
|
||||
await expect(request).resolves.toEqual({ content: [], isError: true });
|
||||
expect(mockCallTool).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports unsupported or rejected message delivery as an error', async () => {
|
||||
|
|
@ -1008,6 +1234,36 @@ describe('useAppBridge', () => {
|
|||
});
|
||||
|
||||
describe('teardown', () => {
|
||||
it('revokes pending tool approval before awaiting App-controlled teardown', async () => {
|
||||
let grant: ((allowed: boolean) => void) | undefined;
|
||||
let finishTeardown: (() => void) | undefined;
|
||||
mockApproveAction.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
grant = resolve;
|
||||
}),
|
||||
);
|
||||
const { view } = mountBridge(makeResource(), client);
|
||||
await flush();
|
||||
const bridge = latest();
|
||||
await bridge.oninitialized?.();
|
||||
bridge.teardownResource = jest.fn(
|
||||
() =>
|
||||
new Promise<Record<string, never>>((resolve) => {
|
||||
finishTeardown = () => resolve({});
|
||||
}),
|
||||
);
|
||||
const pending = bridge.oncalltool?.({ name: 'next', arguments: { id: 1 } }, requestExtra());
|
||||
await flush();
|
||||
bridge.emit('requestteardown');
|
||||
grant?.(true);
|
||||
await expect(pending).resolves.toEqual({ content: [], isError: true });
|
||||
expect(mockCallTool).not.toHaveBeenCalled();
|
||||
finishTeardown?.();
|
||||
await flush();
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it('does not deliver an awaited teardown completion after the View was disposed', async () => {
|
||||
const onTeardown = jest.fn();
|
||||
const mounted = mountBridge(makeResource(), client, { onTeardown });
|
||||
|
|
|
|||
136
client/src/hooks/MCP/approval.tsx
Normal file
136
client/src/hooks/MCP/approval.tsx
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@librechat/client';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
export type MCPAppAction =
|
||||
| { kind: 'tool'; serverName: string; toolName: string; argumentsText: string }
|
||||
| { kind: 'message'; serverName: string; text: string };
|
||||
|
||||
type Pending = {
|
||||
action: MCPAppAction;
|
||||
settle: (allowed: boolean, notify?: boolean) => void;
|
||||
};
|
||||
|
||||
/** An App can request an action but only a host-controlled button can grant it. */
|
||||
export function useMCPAppApproval() {
|
||||
const [pending, setPending] = useState<Pending | null>(null);
|
||||
const pendingRef = useRef<Pending | null>(null);
|
||||
const suspendedRef = useRef(false);
|
||||
const request = useCallback((action: MCPAppAction, signal: AbortSignal): Promise<boolean> => {
|
||||
if (signal.aborted || pendingRef.current || suspendedRef.current) return Promise.resolve(false);
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const settle = (allowed: boolean, notify = true) => {
|
||||
if (pendingRef.current !== entry) return;
|
||||
pendingRef.current = null;
|
||||
signal.removeEventListener('abort', abort);
|
||||
if (notify) setPending(null);
|
||||
resolve(allowed && !signal.aborted);
|
||||
};
|
||||
// An App can abort its own SDK request while the host dialog is visible. Treat that
|
||||
// just like a denial, rather than letting it reopen the dialog in a tight loop.
|
||||
const abort = () => {
|
||||
if (pendingRef.current === entry) suspendedRef.current = true;
|
||||
settle(false);
|
||||
};
|
||||
const entry: Pending = { action, settle };
|
||||
pendingRef.current = entry;
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
if (signal.aborted) abort();
|
||||
else setPending(entry);
|
||||
});
|
||||
}, []);
|
||||
// Escape, backdrop and Cancel all pause further App-requested actions for this View.
|
||||
// Only closing and reopening its View restores the ability to ask.
|
||||
const cancel = useCallback(() => {
|
||||
if (pendingRef.current) {
|
||||
suspendedRef.current = true;
|
||||
pendingRef.current.settle(false);
|
||||
}
|
||||
}, []);
|
||||
// Resolve an outstanding SDK request when the owning View disappears.
|
||||
useEffect(
|
||||
() => () => {
|
||||
pendingRef.current?.settle(false, false);
|
||||
},
|
||||
[],
|
||||
);
|
||||
return {
|
||||
pending: pending?.action ?? null,
|
||||
request,
|
||||
cancel,
|
||||
approve: () => pendingRef.current?.settle(true),
|
||||
};
|
||||
}
|
||||
|
||||
export function MCPAppApproval({
|
||||
action,
|
||||
approve,
|
||||
cancel,
|
||||
close,
|
||||
onCloseAutoFocus,
|
||||
}: {
|
||||
action: MCPAppAction | null;
|
||||
approve: () => void;
|
||||
cancel: () => void;
|
||||
close?: () => void;
|
||||
onCloseAutoFocus?: ComponentProps<typeof AlertDialogContent>['onCloseAutoFocus'];
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
return (
|
||||
<AlertDialog
|
||||
open={action != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) cancel();
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent className="w-11/12 max-w-lg" onCloseAutoFocus={onCloseAutoFocus}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{localize(
|
||||
action?.kind === 'tool'
|
||||
? 'com_ui_mcp_app_confirm_tool'
|
||||
: 'com_ui_mcp_app_confirm_message',
|
||||
)}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{localize('com_ui_mcp_app_action_warning')}{' '}
|
||||
{action?.kind === 'message' && <>{localize('com_ui_mcp_app_message_tool_context')} </>}
|
||||
{localize('com_ui_mcp_app_cancel_pauses')}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{action && (
|
||||
<div className="text-text-primary max-h-64 overflow-auto text-sm">
|
||||
<p className="font-semibold">
|
||||
{action.serverName}
|
||||
{action.kind === 'tool' ? ` / ${action.toolName}` : ''}
|
||||
</p>
|
||||
<pre className="mt-2 break-all whitespace-pre-wrap">
|
||||
{action.kind === 'tool' ? action.argumentsText : action.text}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={cancel}>{localize('com_ui_cancel')}</AlertDialogCancel>
|
||||
{close && (
|
||||
<AlertDialogCancel onClick={close}>{localize('com_ui_mcp_app_stop')}</AlertDialogCancel>
|
||||
)}
|
||||
<AlertDialogAction onClick={approve}>
|
||||
{localize(
|
||||
action?.kind === 'tool' ? 'com_ui_mcp_app_run_tool' : 'com_ui_mcp_app_send_message',
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { useEffect, useId, useRef } from 'react';
|
||||
import { QueryKeys } from 'librechat-data-provider';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { QueryKeys, DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS } from 'librechat-data-provider';
|
||||
import {
|
||||
AppBridge,
|
||||
PostMessageTransport,
|
||||
|
|
@ -9,6 +9,7 @@ import {
|
|||
import type { McpUiStyles, McpUiStyleVariableKey } from '@modelcontextprotocol/ext-apps/app-bridge';
|
||||
import type { UIResource } from 'librechat-data-provider';
|
||||
import type { AppToolResult } from '~/utils/mcpApps';
|
||||
import type { MCPAppAction } from './approval';
|
||||
import {
|
||||
callMCPAppTool,
|
||||
fetchMCPResourceHtml,
|
||||
|
|
@ -44,6 +45,9 @@ export type UseAppBridgeParams = {
|
|||
toolArgs: Record<string, unknown> | undefined;
|
||||
toolResult: AppToolResult | undefined;
|
||||
userId?: string;
|
||||
/** Only a host-owned approval control may resolve this; missing control denies actions. */
|
||||
onRequestAction?: (action: MCPAppAction, signal: AbortSignal) => Promise<boolean>;
|
||||
onCancelAction?: () => void;
|
||||
/** View-owned retry generation. Each attempt gets an isolated bridge and resource query. */
|
||||
attempt: number;
|
||||
onSizeChanged: (params: SizeParams) => void;
|
||||
|
|
@ -95,6 +99,8 @@ export function useAppBridge({
|
|||
toolArgs,
|
||||
toolResult,
|
||||
userId,
|
||||
onRequestAction,
|
||||
onCancelAction,
|
||||
attempt,
|
||||
onSizeChanged,
|
||||
active = true,
|
||||
|
|
@ -106,7 +112,7 @@ export function useAppBridge({
|
|||
// Read-only views (shared transcripts, /search) must not let the embedded app proxy tool calls
|
||||
// or resource reads against the viewer's MCP servers with the viewer's auth.
|
||||
const readOnly = useIsMessagesViewReadOnly();
|
||||
const { cspLimits } = useMCPAppsPolicy();
|
||||
const { cspLimits, maxActionPreviewChars } = useMCPAppsPolicy();
|
||||
const queryClient = useQueryClient();
|
||||
const viewId = useId();
|
||||
// The csp actually delivered to the sandbox document, which is what bounds the app's own egress.
|
||||
|
|
@ -117,11 +123,17 @@ export function useAppBridge({
|
|||
// callback or tool-call snapshot never tears down the live AppBridge. Synced at render time
|
||||
// (idempotent under Strict Mode) rather than via an effect that would only mirror props.
|
||||
const askRef = useRef(ask);
|
||||
const requestActionRef = useRef(onRequestAction);
|
||||
const cancelActionRef = useRef(onCancelAction);
|
||||
const maxActionPreviewCharsRef = useRef(maxActionPreviewChars);
|
||||
const onSizeChangedRef = useRef(onSizeChanged);
|
||||
const onLoadedRef = useRef(onLoaded);
|
||||
const onTeardownRef = useRef(onTeardown);
|
||||
const onFailedRef = useRef(onFailed);
|
||||
askRef.current = ask;
|
||||
requestActionRef.current = onRequestAction;
|
||||
cancelActionRef.current = onCancelAction;
|
||||
maxActionPreviewCharsRef.current = maxActionPreviewChars;
|
||||
onSizeChangedRef.current = onSizeChanged;
|
||||
onLoadedRef.current = onLoaded;
|
||||
onTeardownRef.current = onTeardown;
|
||||
|
|
@ -148,6 +160,7 @@ export function useAppBridge({
|
|||
// Unmount, a resource switch, or a teardown can run cleanup while a read or bridge.connect() is
|
||||
// still pending; this flag stops the pending continuation from touching a disposed bridge.
|
||||
let cancelled = false;
|
||||
const viewAbort = new AbortController();
|
||||
let resourceSent = false;
|
||||
let sendingResource = false;
|
||||
let initialized = false;
|
||||
|
|
@ -242,15 +255,25 @@ export function useAppBridge({
|
|||
if (disposed) return;
|
||||
disposed = true;
|
||||
cancelled = true;
|
||||
viewAbort.abort();
|
||||
cancelActionRef.current?.();
|
||||
themeObserver.disconnect();
|
||||
bridge.close();
|
||||
void queryClient.cancelQueries({ queryKey: resourceQueryKey, exact: true });
|
||||
};
|
||||
|
||||
const interactive = !readOnly;
|
||||
// SDK callbacks may already be queued when a View closes or a peer starts teardown.
|
||||
// Deny new work and propagate View disposal to in-flight authenticated reads/lists.
|
||||
const liveRequestSignal = (signal: AbortSignal): AbortSignal => {
|
||||
if (cancelled || viewAbort.signal.aborted || signal.aborted) {
|
||||
throw new DOMException('MCP App View is closed', 'AbortError');
|
||||
}
|
||||
return AbortSignal.any([signal, viewAbort.signal]);
|
||||
};
|
||||
|
||||
bridge.onopenlink = async ({ url }, { signal }) => {
|
||||
if (signal.aborted) {
|
||||
if (signal.aborted || viewAbort.signal.aborted || cancelled) {
|
||||
return { isError: true };
|
||||
}
|
||||
if (!isAllowedAppLink(url, effectiveCspRef.current, cspLimits)) {
|
||||
|
|
@ -269,38 +292,90 @@ export function useAppBridge({
|
|||
// Host-bound actions (tool calls, resource reads/lists, model messages) run with the viewer's
|
||||
// auth, so they are only wired in interactive views, never in shared transcripts or /search.
|
||||
if (interactive) {
|
||||
bridge.oncalltool = async (params, { signal }) =>
|
||||
callMCPAppTool(
|
||||
serverName,
|
||||
serverBinding,
|
||||
params.name,
|
||||
(params.arguments as Record<string, unknown>) ?? {},
|
||||
signal,
|
||||
);
|
||||
bridge.oncalltool = async (params, { signal }) => {
|
||||
if (signal.aborted || viewAbort.signal.aborted || cancelled || !requestActionRef.current)
|
||||
return { content: [], isError: true };
|
||||
// Snapshot the arguments shown to the user: the App must not mutate them while waiting.
|
||||
let argumentsText: string;
|
||||
let args: Record<string, unknown>;
|
||||
try {
|
||||
argumentsText = JSON.stringify(params.arguments ?? {});
|
||||
if (
|
||||
!argumentsText ||
|
||||
argumentsText.length >
|
||||
(maxActionPreviewCharsRef.current ?? DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS)
|
||||
)
|
||||
return { content: [], isError: true };
|
||||
args = JSON.parse(argumentsText) as Record<string, unknown>;
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args))
|
||||
return { content: [], isError: true };
|
||||
} catch {
|
||||
return { content: [], isError: true };
|
||||
}
|
||||
const toolName = params.name;
|
||||
try {
|
||||
const actionSignal = AbortSignal.any([signal, viewAbort.signal]);
|
||||
const allowed = await requestActionRef.current(
|
||||
{ kind: 'tool', serverName, toolName, argumentsText },
|
||||
actionSignal,
|
||||
);
|
||||
if (!allowed || actionSignal.aborted || cancelled) return { content: [], isError: true };
|
||||
return await callMCPAppTool(serverName, serverBinding, toolName, args, actionSignal);
|
||||
} catch (error) {
|
||||
logger.error('[MCP App] Tool action failed', error);
|
||||
return { content: [], isError: true };
|
||||
}
|
||||
};
|
||||
|
||||
bridge.onreadresource = async (params, { signal }) =>
|
||||
readMCPResource(serverName, serverBinding, params.uri, signal);
|
||||
readMCPResource(serverName, serverBinding, params.uri, liveRequestSignal(signal));
|
||||
|
||||
bridge.onlistresources = async (params, { signal }) =>
|
||||
listMCPResources(serverName, serverBinding, params?.cursor, signal);
|
||||
listMCPResources(serverName, serverBinding, params?.cursor, liveRequestSignal(signal));
|
||||
|
||||
bridge.onlistresourcetemplates = async (params, { signal }) =>
|
||||
listMCPResourceTemplates(serverName, serverBinding, params?.cursor, signal);
|
||||
listMCPResourceTemplates(
|
||||
serverName,
|
||||
serverBinding,
|
||||
params?.cursor,
|
||||
liveRequestSignal(signal),
|
||||
);
|
||||
|
||||
bridge.onmessage = async ({ content }, { signal }) => {
|
||||
const text = (content as MessageContentBlock[])
|
||||
.filter((block) => block.type === 'text' && typeof block.text === 'string')
|
||||
.map((block) => block.text)
|
||||
.join('\n');
|
||||
if (!text || signal.aborted || cancelled) {
|
||||
if (
|
||||
!text.trim() ||
|
||||
text.length >
|
||||
(maxActionPreviewCharsRef.current ?? DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS) ||
|
||||
signal.aborted ||
|
||||
viewAbort.signal.aborted ||
|
||||
cancelled ||
|
||||
!requestActionRef.current
|
||||
) {
|
||||
return { isError: true };
|
||||
}
|
||||
try {
|
||||
const accepted = askRef.current({ text });
|
||||
const actionSignal = AbortSignal.any([signal, viewAbort.signal]);
|
||||
const allowed = await requestActionRef.current(
|
||||
{ kind: 'message', serverName, text },
|
||||
actionSignal,
|
||||
);
|
||||
if (!allowed || actionSignal.aborted || cancelled) return { isError: true };
|
||||
// The selected agent and MCP servers belong to the conversation. Only the
|
||||
// next composer's staged files, manual skill picks and quotes are excluded.
|
||||
const accepted = askRef.current(
|
||||
{ text },
|
||||
{ overrideFiles: [], overrideManualSkills: [], overrideQuotes: [] },
|
||||
);
|
||||
if (accepted === false) {
|
||||
return { isError: true };
|
||||
}
|
||||
return signal.aborted || cancelled ? { isError: true } : {};
|
||||
// ask accepted the turn synchronously. A later App abort cannot undo it;
|
||||
// claiming failure here encourages the App to retry and duplicate the turn.
|
||||
return {};
|
||||
} catch (error) {
|
||||
logger.error('[MCP App] Failed to deliver message', error);
|
||||
return { isError: true };
|
||||
|
|
@ -423,6 +498,10 @@ export function useAppBridge({
|
|||
});
|
||||
|
||||
bridge.addEventListener('requestteardown', async () => {
|
||||
if (cancelled) return;
|
||||
// A peer-controlled teardown handshake can stall. Revoke action authority before awaiting it.
|
||||
viewAbort.abort();
|
||||
cancelActionRef.current?.();
|
||||
if (initialized) {
|
||||
await bridge.teardownResource({}).catch(() => {});
|
||||
}
|
||||
|
|
@ -481,6 +560,8 @@ export function useAppBridge({
|
|||
void start();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
cancelActionRef.current?.();
|
||||
if (initialized) {
|
||||
bridge.teardownResource({}).catch(() => {});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1787,6 +1787,19 @@
|
|||
"com_ui_low": "Low",
|
||||
"com_ui_mcp_app_failed_to_load": "Interactive view failed to load.",
|
||||
"com_ui_mcp_app_frame_title": "MCP App: {{0}}",
|
||||
"com_ui_mcp_app_open": "Open app",
|
||||
"com_ui_mcp_app_close": "Close app",
|
||||
"com_ui_mcp_app_open_named": "Open app: {{0}} ({{1}})",
|
||||
"com_ui_mcp_app_close_named": "Close app: {{0}} ({{1}})",
|
||||
"com_ui_mcp_app_stop": "Close app and stop requests",
|
||||
"com_ui_mcp_app_cancel_pauses": "Cancel pauses further action requests until you close and reopen this app.",
|
||||
"com_ui_mcp_app_at_capacity": "Close another app before opening this one.",
|
||||
"com_ui_mcp_app_confirm_tool": "Run tool from app?",
|
||||
"com_ui_mcp_app_confirm_message": "Send message from app?",
|
||||
"com_ui_mcp_app_message_tool_context": "Sending this message starts a model response in the current conversation. Its selected agent and tools may be used.",
|
||||
"com_ui_mcp_app_action_warning": "Review this request. The app cannot act until you approve it.",
|
||||
"com_ui_mcp_app_run_tool": "Run tool",
|
||||
"com_ui_mcp_app_send_message": "Send message",
|
||||
"com_ui_mcp_app_load_error": "Interactive view could not be loaded.",
|
||||
"com_ui_mcp_app_shared_unavailable": "MCP Apps aren't viewable in shared conversations.",
|
||||
"com_ui_make_production": "Make Production",
|
||||
|
|
|
|||
|
|
@ -12,20 +12,49 @@ The lockfile is the executable version boundary.
|
|||
|
||||
## Support profile
|
||||
|
||||
| Area | Supported behavior |
|
||||
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
||||
| App resource | A tool-linked `ui://` resource with `text/html;profile=mcp-app`, supplied as UTF-8 `text` or base64 `blob` |
|
||||
| MCP connection | Standard shared sessions when Apps are off; profile-separated per-user, MCP OAuth, and direct OpenID sessions when on |
|
||||
| View operations | Same-server tool calls, resource reads, resource and template listing, text messages, policy-controlled links, and logging |
|
||||
| Visibility | Model, App, dual-visible, and omitted visibility follow the MCP Apps visibility rules |
|
||||
| Rendering | Settled Apps render once in a message-owned area below the response; legacy inline HTML keeps its existing adapter |
|
||||
| History | A stored settled result replays its input, unchanged result, and App document while its originating server binding is valid |
|
||||
| Search and public share | Search results do not load Apps; public shares omit UI resources and retain ordinary transcript and tool text |
|
||||
| Unsupported connection profiles | OBO, Graph-token placeholders, and request-body credential placeholders do not offer an interactive App View |
|
||||
| Area | Supported behavior |
|
||||
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| App resource | A tool-linked `ui://` resource with `text/html;profile=mcp-app`, supplied as UTF-8 `text` or base64 `blob` |
|
||||
| MCP connection | Standard shared sessions when Apps are off; profile-separated per-user, MCP OAuth, and direct OpenID sessions when on |
|
||||
| View operations | Same-server tool calls, resource reads, resource and template listing, text messages, policy-controlled links, and logging |
|
||||
| Visibility | Model, App, dual-visible, and omitted visibility follow the MCP Apps visibility rules |
|
||||
| Rendering | Settled Apps show inert placeholders in a message-owned area; legacy inline HTML keeps its adapter |
|
||||
| History | A stored settled result retains its input, unchanged result, and App document; the user explicitly opens its View after binding validation |
|
||||
| Search and public share | Search results do not load Apps; public shares omit UI resources and retain ordinary transcript and tool text |
|
||||
| Unsupported connection profiles | OBO, Graph-token placeholders, and request-body credential placeholders do not offer an interactive App View |
|
||||
|
||||
Optional draft features such as sampling, downloads, App-provided tools, state restoration, external
|
||||
View URLs, and partial tool input are outside this profile.
|
||||
|
||||
## Interactive View authority
|
||||
|
||||
An App attachment displays an inert **Open app** placeholder until the authenticated viewer
|
||||
activates it. Merely opening or restoring a conversation does not create a sandbox iframe,
|
||||
validate a persisted binding, or let an App issue follow-up requests. The default limit is three Apps open
|
||||
concurrently across the host view (`maxActiveViews`, range 1–32); close one to open another. Closing an App tears down its
|
||||
bridge, cancels pending approval and in-flight authenticated resource operations; reopening starts
|
||||
a fresh session and does not restore its previous in-View state. Keyboard focus moves to the new
|
||||
Close/Open control after a user-initiated transition, including the in-dialog Stop app control.
|
||||
|
||||
Opening an App permits its own resource reads and declared link policy, but does not approve actions
|
||||
on the user's behalf. Each App-initiated tool call displays the originating server, tool name and
|
||||
complete arguments in a host-owned confirmation; App-initiated chat text shows the complete text
|
||||
and requires a separate **Send message**. An approved App message contains only that text: files,
|
||||
manual skills, and quotes staged for the user's next composer message are neither submitted nor
|
||||
drained. The confirmation warns that the resulting model response may use the conversation's
|
||||
selected agent and tools. Those selections remain available to the turn; removing them would also
|
||||
change subsequent tool availability. Once chat accepts an approved turn, a later App abort cannot
|
||||
undo it and is not reported as a failed submission. An explicit empty file override
|
||||
prevents a blank App message from becoming submittable just because a draft file exists. Rejecting an action or an App aborting its own pending approval request pauses further
|
||||
action requests from that View until it is closed and reopened. The dialog also provides a Close
|
||||
app and stop requests control for an App that repeatedly asks.
|
||||
Navigating away or closing the App does not execute a pending action. Tool arguments and message
|
||||
previews exceeding `maxActionPreviewChars` (default 16,384; range 1–131,072 UTF-16 characters)
|
||||
fail closed; they are never silently truncated for approval. The existing authenticated same-server binding
|
||||
and visibility checks remain in effect. A user who directly calls their own API can still invoke
|
||||
an allowed tool: this is a consent boundary for embedded App code, not an independent authorization
|
||||
mechanism for authenticated API clients.
|
||||
|
||||
Set `mcpSettings.apps: true` to enable MCP Apps and legacy inline HTML. When the field is omitted,
|
||||
new MCP Apps stay disabled while existing legacy inline HTML remains enabled for upgrade
|
||||
compatibility. An explicit `false` disables both. Authenticated clients fail closed when the
|
||||
|
|
@ -54,6 +83,8 @@ mcpAppSandbox:
|
|||
maxPersistedAppBytes: 2097152
|
||||
maxPersistedMessageBytes: 8388608
|
||||
maxAdmissionRequestsPerMinute: 480
|
||||
maxActiveViews: 3
|
||||
maxActionPreviewChars: 16384
|
||||
```
|
||||
|
||||
These positive-integer settings come only from the base deployment configuration; role, group, and
|
||||
|
|
@ -149,8 +180,8 @@ and on every later App operation. Changing the server owner, effective endpoint,
|
|||
custom variables, or configuration generation invalidates existing Views; routine OAuth or bearer
|
||||
credential refresh does not. Invalidated and older unbound App attachments remain unavailable and
|
||||
never bind by server name to a replacement configuration. The host does not live-revoke a document
|
||||
that is already loaded: a remount or page reload validates before loading it again, and every later
|
||||
App operation validates independently.
|
||||
that is already loaded: reopening an App after close or page reload validates before loading it,
|
||||
and every later App operation validates independently.
|
||||
|
||||
Validation of stored inline HTML compares the binding with the current local admitted server target;
|
||||
it does not connect to the MCP server. A matching persisted document can therefore render while its
|
||||
|
|
@ -226,7 +257,7 @@ node --test e2e/mcp-apps/server.test.mjs
|
|||
node e2e/mcp-apps/run.mjs
|
||||
```
|
||||
|
||||
The Playwright E2E workflow runs these checks on eligible pull requests, the nightly schedule, and manual dispatch, regardless of codegraph selection. Its required `e2e` gate fails if this dedicated job fails. The runner verifies that enabled, disabled, omitted-policy, and quota phases each executed passing browser tests; a successful Playwright exit with only skipped tests does not pass. CI uploads separate reports for each phase and preserves failing traces and screenshots.
|
||||
The Playwright E2E workflow runs these checks on eligible pull requests (including same-repository bot branches, but not untrusted external forks), the nightly schedule, and manual dispatch, regardless of codegraph selection. Its required `e2e` gate fails if this dedicated job fails. The runner verifies that enabled, disabled, omitted-policy, and quota phases each executed passing browser tests; a successful Playwright exit with only skipped tests does not pass. CI uploads separate reports for each phase and preserves failing traces and screenshots.
|
||||
|
||||
The runner builds the client with the chat at `http://127.0.0.1:3080` and the Sandbox Proxy at
|
||||
`http://localhost:3080`. Those URLs reach the same disposable LibreChat process but have distinct
|
||||
|
|
|
|||
30
e2e/mcp-apps/workflow.test.mjs
Normal file
30
e2e/mcp-apps/workflow.test.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { test } from 'node:test';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const yaml = require('js-yaml');
|
||||
const workflow = yaml.load(
|
||||
readFileSync(new URL('../../.github/workflows/playwright-mock.yml', import.meta.url), 'utf8'),
|
||||
);
|
||||
|
||||
// Check the shared eligibility predicate on both the fixture and the required E2E gate.
|
||||
// Otherwise a bot-authored PR silently reports the browser lane as skipped.
|
||||
test('canary bot branches can run the required Apps fixture without admitting external forks', () => {
|
||||
for (const job of ['e2e_shards', 'mcp_tool_list_changed', 'mcp_apps', 'e2e']) {
|
||||
const expression = workflow.jobs[job].if;
|
||||
assert.match(expression, /github\.event_name == 'pull_request'/);
|
||||
assert.match(expression, /github\.event\.pull_request != null/);
|
||||
assert.match(
|
||||
expression,
|
||||
/\(contains\(fromJSON\('\["OWNER", "MEMBER", "COLLABORATOR"\]'\), github\.event\.pull_request\.author_association\) \|\|\s*github\.event\.pull_request\.head\.repo\.full_name == github\.repository\)/,
|
||||
`${job} must require either a trusted association or a same-repository head`,
|
||||
);
|
||||
}
|
||||
assert.ok(workflow.jobs.e2e.needs.includes('mcp_apps'));
|
||||
assert.match(
|
||||
workflow.jobs.e2e.steps.find((step) => step.name === 'Verify every Playwright job passed').if,
|
||||
/needs\.mcp_apps\.result != 'success'/,
|
||||
);
|
||||
});
|
||||
|
|
@ -260,6 +260,19 @@ async function expectConnectedApp(
|
|||
toolName = 'show_app',
|
||||
occurrence = 0,
|
||||
) {
|
||||
// The placeholder is async after reload, and opening one View removes its button.
|
||||
// Match the stable host-owned tool identity rather than a shifting list of placeholders.
|
||||
const view = page.locator(`[data-mcp-app-view="${toolName}"]`).nth(occurrence);
|
||||
await expect(view).toBeVisible({ timeout: 30_000 });
|
||||
const open = view.getByRole('button', { name: 'Open app' });
|
||||
if (await open.count()) {
|
||||
// Pre-scroll before clicking a sibling View: Chrome can drop Playwright's first click when
|
||||
// scrolling past an active sandbox iframe and dispatch it to the old focused frame.
|
||||
await open.scrollIntoViewIfNeeded();
|
||||
await open.boundingBox();
|
||||
await open.click();
|
||||
await expect(view.getByRole('button', { name: 'Close app' })).toBeVisible();
|
||||
}
|
||||
const app = appFrame(page, toolName, occurrence);
|
||||
await expect(app.getByTestId('status')).toHaveText('connected', { timeout: 30_000 });
|
||||
await expect(app.getByTestId('document-source')).toHaveText('resources-read-document');
|
||||
|
|
@ -413,6 +426,10 @@ test.describe('MCP Apps full integration', () => {
|
|||
await expect(messagesView(page).getByText(`E2E MCP App complete: ${label}`)).toBeVisible({
|
||||
timeout: 60_000,
|
||||
});
|
||||
// Merely receiving a completed App result must not run its code or perform App RPCs.
|
||||
await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(0);
|
||||
expect(appRequests).toEqual([]);
|
||||
await page.getByRole('button', { name: 'Open app' }).click();
|
||||
await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(1);
|
||||
const outerCsp = (await sandboxResponse).headers()['content-security-policy'];
|
||||
expect(outerCsp).toContain('frame-src blob:');
|
||||
|
|
@ -447,7 +464,39 @@ test.describe('MCP Apps full integration', () => {
|
|||
expect(viewCsp).not.toContain(MCP_APP_ORIGIN);
|
||||
|
||||
const app = await expectConnectedApp(page, label);
|
||||
await clickAndExpectRoute(page, app, 'call-tool', '/api/mcp/app-tool-call');
|
||||
// App code can dispatch events without a user gesture. It must still be denied by default.
|
||||
await app.getByTestId('call-tool').evaluate((button) => (button as HTMLElement).click());
|
||||
const toolDialog = page.getByRole('alertdialog');
|
||||
await expect(toolDialog).toContainText('follow_up');
|
||||
expect(
|
||||
(await readEvents(page)).filter((event) => event.method === 'tools/call:follow_up'),
|
||||
).toHaveLength(0);
|
||||
await toolDialog.getByRole('button', { name: 'Cancel' }).click();
|
||||
expect(
|
||||
(await readEvents(page)).filter((event) => event.method === 'tools/call:follow_up'),
|
||||
).toHaveLength(0);
|
||||
// Repeated App-generated actions must not trap the viewer behind new approval modals.
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await app.getByTestId('call-tool').evaluate((button) => (button as HTMLElement).click());
|
||||
}
|
||||
await expect(toolDialog).toHaveCount(0);
|
||||
expect(
|
||||
(await readEvents(page)).filter((event) => event.method === 'tools/call:follow_up'),
|
||||
).toHaveLength(0);
|
||||
const appView = page.locator('[data-mcp-app-view="show_app"]').first();
|
||||
await appView.getByRole('button', { name: 'Close app' }).focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(appView.getByRole('button', { name: 'Open app' })).toBeFocused();
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(appView.getByRole('button', { name: 'Close app' })).toBeFocused();
|
||||
await expectConnectedApp(page, label);
|
||||
const approvedTool = page.waitForResponse(
|
||||
(response) => new URL(response.url()).pathname === '/api/mcp/app-tool-call',
|
||||
);
|
||||
await app.getByTestId('call-tool').click();
|
||||
await expect(toolDialog).toContainText('"label":"from-view"');
|
||||
await toolDialog.getByRole('button', { name: 'Run tool' }).click();
|
||||
expect((await approvedTool).ok()).toBeTruthy();
|
||||
await expect(app.getByTestId('operation')).toContainText('"followUp":"from-view"');
|
||||
await page.screenshot({ path: testInfo.outputPath('settled-app.png'), fullPage: true });
|
||||
|
||||
|
|
@ -485,6 +534,10 @@ test.describe('MCP Apps full integration', () => {
|
|||
{ timeout: 30_000 },
|
||||
);
|
||||
await app.getByTestId('send-message').click();
|
||||
const messageDialog = page.getByRole('alertdialog');
|
||||
await expect(messageDialog).toContainText(appMessage);
|
||||
await expect(messageDialog).toContainText('selected agent and tools may be used');
|
||||
await messageDialog.getByRole('button', { name: 'Send message' }).click();
|
||||
await expect(app.getByTestId('operation')).toHaveText('message-sent');
|
||||
expect((await nextGeneration).ok()).toBeTruthy();
|
||||
await expect(messagesView(page).getByText(appMessage, { exact: true })).toBeVisible({
|
||||
|
|
@ -541,6 +594,12 @@ test.describe('MCP Apps full integration', () => {
|
|||
await expect(messagesView(page).getByText(`E2E MCP App complete: ${retryLabel}`)).toBeVisible({
|
||||
timeout: 60_000,
|
||||
});
|
||||
await expect(page.locator('iframe[title="MCP App: show_app"]')).toHaveCount(1);
|
||||
await page
|
||||
.locator('[data-mcp-app-view]')
|
||||
.nth(1)
|
||||
.getByRole('button', { name: 'Open app' })
|
||||
.click();
|
||||
expect((await failedSandboxResponse).status()).toBe(503);
|
||||
await expect(page.locator('iframe[title="MCP App: show_app"]')).toHaveCount(2);
|
||||
|
||||
|
|
@ -591,8 +650,9 @@ test.describe('MCP Apps full integration', () => {
|
|||
await expect(messagesView(page).getByText(`E2E MCP link App complete: ${label}`)).toBeVisible({
|
||||
timeout: 60_000,
|
||||
});
|
||||
await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(3);
|
||||
await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(2);
|
||||
const linkApp = await expectConnectedApp(page, label, 'show_link_app');
|
||||
await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(3);
|
||||
const linkViewCsp = await linkApp
|
||||
.locator('meta[http-equiv="Content-Security-Policy"]')
|
||||
.getAttribute('content');
|
||||
|
|
@ -670,6 +730,7 @@ test.describe('MCP Apps full integration', () => {
|
|||
|
||||
await resetEvents(page);
|
||||
await page.reload({ waitUntil: 'domcontentloaded' });
|
||||
await expect(page.locator('iframe[data-sandbox-url]')).toHaveCount(0);
|
||||
await expectConnectedApp(page, label);
|
||||
await expectConnectedApp(page, retryLabel, 'show_app', 1);
|
||||
await expectConnectedApp(page, label, 'show_link_app');
|
||||
|
|
@ -796,10 +857,11 @@ test.describe('MCP Apps full integration', () => {
|
|||
});
|
||||
await expect(phaseHeader).toBeVisible({ timeout: 60_000 });
|
||||
await expect(phaseHeader).toHaveAttribute('aria-expanded', 'false');
|
||||
await expectAppFramesOutsidePanels(page, 2);
|
||||
await expectAppFramesOutsidePanels(page, 0);
|
||||
|
||||
await expectConnectedApp(page, alphaLabel, 'show_app', 0);
|
||||
await expectConnectedApp(page, betaLabel, 'show_app', 1);
|
||||
await expectAppFramesOutsidePanels(page, 2);
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath('settled-grouped-apps.png'),
|
||||
fullPage: true,
|
||||
|
|
@ -822,9 +884,10 @@ test.describe('MCP Apps full integration', () => {
|
|||
});
|
||||
await expect(reloadedHeader).toBeVisible({ timeout: 60_000 });
|
||||
await expect(reloadedHeader).toHaveAttribute('aria-expanded', 'false');
|
||||
await expectAppFramesOutsidePanels(page, 2);
|
||||
await expectAppFramesOutsidePanels(page, 0);
|
||||
await expectConnectedApp(page, alphaLabel, 'show_app', 0);
|
||||
await expectConnectedApp(page, betaLabel, 'show_app', 1);
|
||||
await expectAppFramesOutsidePanels(page, 2);
|
||||
expect(
|
||||
(await readEvents(page)).filter((event) => event.method === 'resources/read:show_app'),
|
||||
).toHaveLength(2);
|
||||
|
|
|
|||
|
|
@ -583,6 +583,8 @@ actions:
|
|||
# maxSerializedLength: 4096
|
||||
# maxPersistedAppBytes: 1048576
|
||||
# maxAdmissionRequestsPerMinute: 240
|
||||
# maxActiveViews: 3 # simultaneous interactive App views per browser
|
||||
# maxActionPreviewChars: 16384 # App tool arguments and chat message preview
|
||||
|
||||
# Example MCP Servers Object Structure
|
||||
# mcpServers:
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ import {
|
|||
DEFAULT_MCP_APPS_POLICY,
|
||||
DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
} from 'librechat-data-provider';
|
||||
import type * as t from '~/mcp/types';
|
||||
import {
|
||||
|
|
@ -548,6 +550,8 @@ describe('MCPServersRegistry', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
|
@ -563,6 +567,8 @@ describe('MCPServersRegistry', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -11,6 +11,10 @@ import {
|
|||
excludedKeys,
|
||||
DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
MAX_MCP_APP_ACTIVE_VIEWS,
|
||||
MAX_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
MAX_MCP_APP_PERSISTED_BYTES,
|
||||
resolveMCPAppRateLimits,
|
||||
resolveMCPAppsPolicy,
|
||||
|
|
@ -1984,6 +1988,8 @@ describe('MCP Apps configuration', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
},
|
||||
],
|
||||
[
|
||||
|
|
@ -1993,6 +1999,8 @@ describe('MCP Apps configuration', () => {
|
|||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
},
|
||||
],
|
||||
[
|
||||
|
|
@ -2002,6 +2010,8 @@ describe('MCP Apps configuration', () => {
|
|||
legacyHtmlEnabled: false,
|
||||
maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
},
|
||||
],
|
||||
])('resolves raw apps value %s to the effective policy', (value, expected) => {
|
||||
|
|
@ -2014,6 +2024,8 @@ describe('MCP Apps configuration', () => {
|
|||
maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxPersistedMessageBytes: 12 * 1024 * 1024,
|
||||
maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
});
|
||||
expect(
|
||||
configSchema.parse({
|
||||
|
|
@ -2024,6 +2036,8 @@ describe('MCP Apps configuration', () => {
|
|||
maxPersistedAppBytes: 2048,
|
||||
maxPersistedMessageBytes: 1024 * 1024,
|
||||
maxAdmissionRequestsPerMinute: 480,
|
||||
maxActiveViews: 7,
|
||||
maxActionPreviewChars: 32768,
|
||||
url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',
|
||||
},
|
||||
}).mcpAppSandbox,
|
||||
|
|
@ -2033,6 +2047,8 @@ describe('MCP Apps configuration', () => {
|
|||
maxPersistedAppBytes: 2048,
|
||||
maxPersistedMessageBytes: 1024 * 1024,
|
||||
maxAdmissionRequestsPerMinute: 480,
|
||||
maxActiveViews: 7,
|
||||
maxActionPreviewChars: 32768,
|
||||
url: 'https://mcp-sandbox.example.com/api/mcp/sandbox',
|
||||
});
|
||||
for (const mcpAppSandbox of [
|
||||
|
|
@ -2050,6 +2066,12 @@ describe('MCP Apps configuration', () => {
|
|||
{ maxAdmissionRequestsPerMinute: 0 },
|
||||
{ maxAdmissionRequestsPerMinute: 1.5 },
|
||||
{ maxAdmissionRequestsPerMinute: Number.MAX_SAFE_INTEGER + 1 },
|
||||
{ maxActiveViews: 0 },
|
||||
{ maxActiveViews: 1.5 },
|
||||
{ maxActiveViews: MAX_MCP_APP_ACTIVE_VIEWS + 1 },
|
||||
{ maxActionPreviewChars: 0 },
|
||||
{ maxActionPreviewChars: 1.5 },
|
||||
{ maxActionPreviewChars: MAX_MCP_APP_ACTION_PREVIEW_CHARS + 1 },
|
||||
{ url: '/api/mcp/sandbox' },
|
||||
{ url: 'ftp://mcp-sandbox.example.com/api/mcp/sandbox' },
|
||||
]) {
|
||||
|
|
@ -2065,12 +2087,16 @@ describe('MCP Apps configuration', () => {
|
|||
2048,
|
||||
480,
|
||||
'https://mcp-sandbox.example.com/api/mcp/sandbox',
|
||||
7,
|
||||
32768,
|
||||
),
|
||||
).toEqual({
|
||||
enabled: true,
|
||||
legacyHtmlEnabled: true,
|
||||
maxPersistedAppBytes: 2048,
|
||||
maxAdmissionRequestsPerMinute: 480,
|
||||
maxActiveViews: 7,
|
||||
maxActionPreviewChars: 32768,
|
||||
sandboxUrl: 'https://mcp-sandbox.example.com/api/mcp/sandbox',
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2640,6 +2640,10 @@ export type TMCPAppsPolicy = {
|
|||
maxPersistedAppBytes?: number;
|
||||
/** Shared per-user ceiling applied before principal-scoped MCP App admission. */
|
||||
maxAdmissionRequestsPerMinute?: number;
|
||||
/** Maximum simultaneously opened App views per authenticated host. */
|
||||
maxActiveViews?: number;
|
||||
/** Maximum UTF-16 characters displayed for an App-requested action before denying it. */
|
||||
maxActionPreviewChars?: number;
|
||||
/** Deployment-owned dedicated Sandbox Proxy URL published to authenticated clients. */
|
||||
sandboxUrl?: string;
|
||||
};
|
||||
|
|
@ -2650,12 +2654,18 @@ export const MAX_MCP_APP_MESSAGE_BYTES: number = 12 * 1024 * 1024;
|
|||
export const DEFAULT_MCP_APP_PERSISTED_BYTES = 1024 * 1024;
|
||||
export const MAX_MCP_APP_PERSISTED_BYTES = 4 * 1024 * 1024;
|
||||
export const DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE = 240;
|
||||
export const DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS = 3;
|
||||
export const MAX_MCP_APP_ACTIVE_VIEWS = 32;
|
||||
export const DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS = 16_384;
|
||||
export const MAX_MCP_APP_ACTION_PREVIEW_CHARS = 131_072;
|
||||
|
||||
export const DEFAULT_MCP_APPS_POLICY: TMCPAppsPolicy = {
|
||||
enabled: false,
|
||||
legacyHtmlEnabled: false,
|
||||
maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
};
|
||||
|
||||
export function resolveMCPAppsPolicy(
|
||||
|
|
@ -2664,6 +2674,8 @@ export function resolveMCPAppsPolicy(
|
|||
maxPersistedAppBytes = DEFAULT_MCP_APP_PERSISTED_BYTES,
|
||||
maxAdmissionRequestsPerMinute = DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
|
||||
sandboxUrl?: string,
|
||||
maxActiveViews = DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
|
||||
maxActionPreviewChars = DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
|
||||
): TMCPAppsPolicy {
|
||||
return {
|
||||
enabled: value === true,
|
||||
|
|
@ -2671,6 +2683,8 @@ export function resolveMCPAppsPolicy(
|
|||
...(cspLimits != null ? { cspLimits: resolveMCPAppCspLimits(cspLimits) } : {}),
|
||||
maxPersistedAppBytes,
|
||||
maxAdmissionRequestsPerMinute,
|
||||
maxActiveViews,
|
||||
maxActionPreviewChars,
|
||||
...(sandboxUrl !== undefined ? { sandboxUrl } : {}),
|
||||
};
|
||||
}
|
||||
|
|
@ -3352,6 +3366,18 @@ export const configSchema = z.object({
|
|||
.positive()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE),
|
||||
maxActiveViews: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(MAX_MCP_APP_ACTIVE_VIEWS)
|
||||
.default(DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS),
|
||||
maxActionPreviewChars: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(MAX_MCP_APP_ACTION_PREVIEW_CHARS)
|
||||
.default(DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS),
|
||||
})
|
||||
.default({}),
|
||||
mcpSettings: z
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue