Skip to content

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

🗳️ fix: Defer Thread Approval Card to the Open Composer Review (#16437)

Marco Beretta12efd62a7faa
diff --git a/client/src/components/Chat/Messages/Content/ToolApproval.tsx b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
index 359c190533..a75d05ecdf 100644
--- a/client/src/components/Chat/Messages/Content/ToolApproval.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
@@ -1,10 +1,12 @@
-import { useEffect, useMemo } from 'react';
+import { useContext, useEffect, useMemo } from 'react';
import { Button, TextareaAutosize } from '@librechat/client';
-import { Check, X, Pencil, MessageSquare, TriangleAlert } from 'lucide-react';
+import { Check, X, Pencil, MessageSquare, ShieldQuestion, TriangleAlert } from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
import type { TranslationKeys } from '~/hooks';
+import { useComposerPresentsApproval } from '~/components/Chat/approval/state';
import { boundApprovalLabel } from '~/components/Chat/approval/preview';
import { useApprovalContext, useResumeSubmit } from './ApprovalContext';
+import { ChatContext } from '~/Providers/ChatContext';
import { useLocalize } from '~/hooks';
import { cn, logger } from '~/utils';
@@ -69,22 +71,28 @@ function seedArgs(args: string | Record<string, unknown> | undefined): string {
* Renders approve / reject / edit / respond controls for a paused tool call,
* scoped to the decisions the server allows. Records its decision in the
* batch {@link useApprovalContext}; the lead card additionally renders the
- * single submit button covering every paused call in the action.
+ * single submit button covering every paused call in the action. While the
+ * composer's review panel is open on the same action, a thread card renders
+ * only the record of the request: the panel owns the decisions and the submit,
+ * and it overlays the tail of the thread where this card sits.
*/
export default function ToolApproval({
approval,
toolCallId,
args,
- showSubmit = true,
+ surface = 'thread',
}: {
approval: NonNullable<Agents.ToolCall['approval']>;
toolCallId: string;
args: string | Record<string, unknown> | undefined;
- /** The composer owns one batch submit; timeline cards keep the historical lead button. */
- showSubmit?: boolean;
+ /** The composer panel owns one batch submit; thread cards keep the lead button. */
+ surface?: 'thread' | 'composer';
}) {
const localize = useLocalize();
const { actionId, allowed_decisions: allowedDecisions, description } = approval;
+ const conversationId = useContext(ChatContext)?.conversation?.conversationId;
+ const composerPresents = useComposerPresentsApproval(conversationId, actionId);
+ const deferToComposer = surface === 'thread' && composerPresents;
const {
registerToolCall,
unregisterToolCall,
@@ -209,15 +217,33 @@ export default function ToolApproval({
return null;
}
+ const descriptionNode = safeDescription != null && safeDescription.length > 0 && (
+ <p className="text-sm text-text-secondary">{safeDescription}</p>
+ );
+
+ if (deferToComposer) {
+ return (
+ <div
+ className="my-2 flex w-full flex-col gap-2 rounded-lg border border-border-light bg-surface-secondary p-3"
+ data-testid="tool-approval"
+ data-tool-call-id={toolCallId}
+ >
+ {descriptionNode}
+ <p className="flex items-center gap-1.5 text-xs text-text-secondary">
+ <ShieldQuestion className="size-4 shrink-0" aria-hidden="true" />
+ {localize('com_ui_approval_review_in_composer')}
+ </p>
+ </div>
+ );
+ }
+
return (
<div
className="my-2 flex w-full flex-col gap-2 rounded-lg border border-border-light bg-surface-secondary p-3"
data-testid="tool-approval"
data-tool-call-id={toolCallId}
>
- {safeDescription != null && safeDescription.length > 0 && (
- <p className="text-sm text-text-secondary">{safeDescription}</p>
- )}
+ {descriptionNode}
<div className="flex flex-wrap gap-2">
{allowedDecisions.map((decision) => {
const Icon = DECISION_ICON[decision];
@@ -281,7 +307,7 @@ export default function ToolApproval({
/>
)}
- {showSubmit && isLead && (
+ {surface === 'thread' && isLead && (
<div className="mt-1 flex items-center gap-3">
<Button
size="sm"
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
index 7066770ea0..7938114a31 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
@@ -1,7 +1,13 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { Provider, createStore } from 'jotai';
+import { act, fireEvent, render, screen, within } from '@testing-library/react';
import type { Agents } from 'librechat-data-provider';
+import {
+ approvalPanelOpenFamily,
+ pendingApprovalActionFamily,
+} from '~/components/Chat/approval/state';
+import { ChatContext } from '~/Providers/ChatContext';
import ApprovalProvider from '../ApprovalContext';
import ToolApproval from '../ToolApproval';
@@ -20,6 +26,7 @@ jest.mock('~/hooks', () => ({
com_ui_invalid_json: 'Invalid JSON',
com_ui_reject_reason_placeholder: 'Reason',
com_ui_tool_response_placeholder: 'Response',
+ com_ui_approval_review_in_composer: 'Review in composer',
};
return map[key] ?? key;
},
@@ -146,7 +153,7 @@ describe('ToolApproval', () => {
approval={approval()}
toolCallId="call-1"
args={{ a: 1 }}
- showSubmit={false}
+ surface="composer"
/>
</>,
);
@@ -187,4 +194,96 @@ describe('ToolApproval', () => {
expect(screen.getByRole('button', { name: 'Approve' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled();
});
+
+ describe('while the composer review panel presents the pending action', () => {
+ const conversationId = 'convo-1';
+ const pendingAction: Agents.PendingAction = {
+ actionId: 'action-1',
+ streamId: 'stream-1',
+ conversationId,
+ createdAt: 1000,
+ payload: {
+ type: 'tool_approval',
+ action_requests: [{ name: 'probe', tool_call_id: 'call-1', arguments: { a: 1 } }],
+ review_configs: [
+ {
+ action_name: 'probe',
+ tool_call_id: 'call-1',
+ allowed_decisions: ['approve', 'reject'],
+ },
+ ],
+ },
+ };
+
+ const renderWithComposer = (open: boolean, extra?: React.ReactNode) => {
+ const store = createStore();
+ store.set(pendingApprovalActionFamily(conversationId), pendingAction);
+ store.set(approvalPanelOpenFamily(conversationId), open);
+ render(
+ <RecoilRoot>
+ <Provider store={store}>
+ <ChatContext.Provider value={{ conversation: { conversationId } } as never}>
+ <ApprovalProvider pendingAction={pendingAction}>
+ <div data-testid="thread">
+ <ToolApproval approval={approval()} toolCallId="call-1" args={{ a: 1 }} />
+ </div>
+ <div data-testid="composer">
+ <ToolApproval
+ approval={approval()}
+ toolCallId="call-1"
+ args={{ a: 1 }}
+ surface="composer"
+ />
+ </div>
+ {extra}
+ </ApprovalProvider>
+ </ChatContext.Provider>
+ </Provider>
+ </RecoilRoot>,
+ );
+ return store;
+ };
+
+ test('the thread card is a record with no decisions or Submit while the panel is open', () => {
+ renderWithComposer(true);
+ const thread = screen.getByTestId('thread');
+
+ expect(thread).toHaveTextContent('Review in composer');
+ expect(thread.querySelectorAll('button')).toHaveLength(0);
+ expect(screen.queryByRole('button', { name: 'Submit' })).not.toBeInTheDocument();
+ expect(screen.getAllByRole('button', { name: 'Approve' })).toHaveLength(1);
+ });
+
+ test('collapsing the panel hands the decisions and Submit back to the thread card', () => {
+ const store = renderWithComposer(true);
+
+ act(() => store.set(approvalPanelOpenFamily(conversationId), false));
+
+ const thread = screen.getByTestId('thread');
+ expect(thread).not.toHaveTextContent('Review in composer');
+ fireEvent.click(within(thread).getByRole('button', { name: 'Approve' }));
+ expect(within(thread).getByRole('button', { name: 'Submit' })).toBeEnabled();
+ expect(
+ within(screen.getByTestId('composer')).queryByRole('button', { name: 'Submit' }),
+ ).not.toBeInTheDocument();
+ });
+
+ test('a thread card for a different action keeps its controls', () => {
+ renderWithComposer(
+ true,
+ <div data-testid="other-action">
+ <ToolApproval
+ approval={{ actionId: 'action-2', allowed_decisions: ['approve'] }}
+ toolCallId="call-9"
+ args={{}}
+ />
+ </div>,
+ );
+
+ const other = screen.getByTestId('other-action');
+ expect(other).not.toHaveTextContent('Review in composer');
+ expect(within(other).getByRole('button', { name: 'Approve' })).toBeInTheDocument();
+ expect(screen.getByTestId('thread')).toHaveTextContent('Review in composer');
+ });
+ });
});
diff --git a/client/src/components/Chat/approval/Review.tsx b/client/src/components/Chat/approval/Review.tsx
index b38742afa7..c0cf148f47 100644
--- a/client/src/components/Chat/approval/Review.tsx
+++ b/client/src/components/Chat/approval/Review.tsx
@@ -1,6 +1,5 @@
import { memo, useEffect, useMemo } from 'react';
-import { atomFamily } from 'jotai/utils';
-import { atom, useAtom, useAtomValue } from 'jotai';
+import { useAtom, useAtomValue } from 'jotai';
import { Button, TooltipAnchor } from '@librechat/client';
import { ChevronDown, ChevronUp, ShieldQuestion, TriangleAlert } from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
@@ -9,14 +8,15 @@ import {
useApprovalContext,
useResumeSubmit,
} from '~/components/Chat/Messages/Content/ApprovalContext';
+import {
+ approvalPanelOpenFamily,
+ pendingApprovalActionFamily,
+} from '~/components/Chat/approval/state';
import { buildApprovalPreview, buildApprovalPreviews } from '~/components/Chat/approval/preview';
-import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import ToolApproval from '~/components/Chat/Messages/Content/ToolApproval';
import { useComposerOverlay } from '~/components/Chat/Input/overlay';
import { useLocalize } from '~/hooks';
-const approvalPanelOpenFamily = atomFamily((_conversationId: string) => atom(false));
-
function usePendingToolApproval(conversationId: string) {
const pendingAction = useAtomValue(pendingApprovalActionFamily(conversationId));
return pendingAction?.payload.type === 'tool_approval'
@@ -158,7 +158,7 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
}}
toolCallId={request.tool_call_id}
args={request.arguments}
- showSubmit={false}
+ surface="composer"
/>
) : (
<p className="mt-2 flex items-center text-xs text-text-warning" role="alert">
diff --git a/client/src/components/Chat/approval/state.ts b/client/src/components/Chat/approval/state.ts
index d812e1627e..e21f6ad246 100644
--- a/client/src/components/Chat/approval/state.ts
+++ b/client/src/components/Chat/approval/state.ts
@@ -1,5 +1,6 @@
-import { atom } from 'jotai';
import { atomFamily } from 'jotai/utils';
+import { atom, useAtomValue } from 'jotai';
+import { Constants } from 'librechat-data-provider';
import type { Agents } from 'librechat-data-provider';
/**
@@ -12,3 +13,28 @@ import type { Agents } from 'librechat-data-provider';
export const pendingApprovalActionFamily = atomFamily((_conversationId: string) =>
atom<Agents.PendingAction | null>(null),
);
+
+/** Whether the composer's review panel is expanded for one conversation. */
+export const approvalPanelOpenFamily = atomFamily((_conversationId: string) => atom(false));
+
+/**
+ * True while the composer's review panel is open on this tool-approval action.
+ * The panel then owns the decisions and the batch submit, and it overlays the
+ * tail of the thread where the live approval card sits, so the thread card
+ * steps back to a record of the request until the panel is collapsed.
+ * Without a conversation there is no composer, so nothing is presented there.
+ */
+export function useComposerPresentsApproval(
+ conversationId: string | null | undefined,
+ actionId: string,
+): boolean {
+ const key = conversationId ?? Constants.NEW_CONVO;
+ const pendingAction = useAtomValue(pendingApprovalActionFamily(key));
+ const open = useAtomValue(approvalPanelOpenFamily(key));
+ return (
+ conversationId != null &&
+ open &&
+ pendingAction?.actionId === actionId &&
+ pendingAction.payload.type === 'tool_approval'
+ );
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index da661641f9..a74bc7141f 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1111,6 +1111,7 @@
"com_ui_api_keys_load_error": "Failed to load API keys",
"com_ui_approval_error": "Something went wrong submitting your decision. Please try again.",
"com_ui_approval_expired": "This request expired or was already handled.",
+ "com_ui_approval_review_in_composer": "Review this request in the panel above the message box.",
"com_ui_approve": "Approve",
"com_ui_archive": "Archive",
"com_ui_archive_all_error": "Failed to archive all chats",
diff --git a/e2e/specs/mock/agents.helpers.ts b/e2e/specs/mock/agents.helpers.ts
index 79445ebbfd..b5d11fdc09 100644
--- a/e2e/specs/mock/agents.helpers.ts
+++ b/e2e/specs/mock/agents.helpers.ts
@@ -136,6 +136,20 @@ export async function openAgentBuilder(page: Page) {
return form;
}
+/** Closes the narrow-layout drawer `openAgentBuilder` opened, so it cannot
+ * cover the composer. A no-op on the desktop layout, where the builder is a rail. */
+export async function closeMobileDrawer(page: Page) {
+ if ((page.viewportSize()?.width ?? DESKTOP_WIDTH) > NARROW_MAX_WIDTH) {
+ return;
+ }
+ const drawer = page.locator(`#${MOBILE_DRAWER_ID}`);
+ if (await drawer.evaluate((element) => element.hasAttribute('inert'))) {
+ return;
+ }
+ await page.getByRole('button', { name: 'Close sidebar', exact: true }).click();
+ await expect(drawer).toHaveAttribute('inert', /.*/);
+}
+
export async function selectMockModel(page: Page, clickBackToBuilder = false) {
const form = page.getByRole('form', { name: 'Agent configuration form' });
diff --git a/e2e/specs/mock/approvals.helpers.ts b/e2e/specs/mock/approvals.helpers.ts
new file mode 100644
index 0000000000..885345f6b3
--- /dev/null
+++ b/e2e/specs/mock/approvals.helpers.ts
@@ -0,0 +1,139 @@
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { expect } from '@playwright/test';
+import type { Page, Request } from '@playwright/test';
+import type { AgentDetail } from './agents.helpers';
+import { openAgentBuilder, uniqueAgentName } from './agents.helpers';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ fetchJson,
+ getAccessToken,
+ messagesView,
+ requestJson,
+} from './helpers';
+
+const MCP_SERVER_NAME = 'e2e-memory';
+const MCP_SERVER_TOOL_ID = `sys__server__sys_mcp_${MCP_SERVER_NAME}`;
+const APPROVAL_TOOL_NAME = 'approval_probe';
+export const APPROVAL_TOOL_ID = `${APPROVAL_TOOL_NAME}_mcp_${MCP_SERVER_NAME}`;
+export const APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL:';
+export const BATCH_APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL_BATCH:';
+export const RESTRICTED_APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL_RESTRICTED:';
+export const REWRITTEN_APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL_REWRITE:';
+export const APPROVAL_REASON = `E2E approval required before running ${APPROVAL_TOOL_ID}.`;
+export const APPROVAL_ERROR = 'Something went wrong submitting your decision. Please try again.';
+export const APPROVAL_EXPIRED = 'This request expired or was already handled.';
+const DESCRIPTION = 'Verifies human approval behavior for MCP tool calls in mock E2E tests.';
+const APPROVAL_AUDIT_DIR = path.join('/tmp', 'librechat-e2e-approval-audit');
+export const uniqueLabel = () => `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+const approvalInvocationPath = (value: string) =>
+ path.join(APPROVAL_AUDIT_DIR, Buffer.from(value).toString('base64url'));
+
+export function clearApprovalInvocations(...values: string[]) {
+ values.forEach((value) => fs.rmSync(approvalInvocationPath(value), { force: true }));
+}
+
+function approvalInvocationCount(value: string) {
+ const filename = approvalInvocationPath(value);
+ if (!fs.existsSync(filename)) {
+ return 0;
+ }
+ return fs
+ .readFileSync(filename, 'utf8')
+ .split('\n')
+ .filter((line) => line.length > 0).length;
+}
+
+export async function expectApprovalInvocationCount(value: string, count: number) {
+ await expect.poll(() => approvalInvocationCount(value), { timeout: 30000 }).toBe(count);
+}
+
+type MCPToolsResponse = {
+ servers?: Record<string, { tools?: Array<{ pluginKey: string }> }>;
+};
+
+export type ApprovalResumeBody = {
+ actionId?: string;
+ agent_id?: string;
+ conversationId?: string;
+ endpoint?: string;
+ decisions?: Array<{
+ tool_call_id?: string;
+ decision?: string;
+ reason?: string;
+ responseText?: string;
+ editedArguments?: Record<string, unknown>;
+ }>;
+};
+
+export type ApprovalResumeResponse = {
+ conversationId?: string;
+ status?: string;
+ streamId?: string;
+};
+
+export const approvalCards = (page: Page) => messagesView(page).getByTestId('tool-approval');
+export const approvalCard = (page: Page, toolCallId: string) =>
+ messagesView(page).locator(`[data-testid="tool-approval"][data-tool-call-id="${toolCallId}"]`);
+export const composerApprovalPanel = (page: Page) => page.locator('#pending-tool-approval-panel');
+
+export async function collapseComposerApproval(page: Page) {
+ const panel = composerApprovalPanel(page);
+ await expect(panel).toBeVisible({ timeout: 30000 });
+ await panel.getByRole('button', { name: 'Collapse', exact: true }).click();
+ await expect(panel).toHaveCount(0);
+}
+
+export function isResumeRequest(request: Request) {
+ return (
+ request.method() === 'POST' && new URL(request.url()).pathname === '/api/agents/chat/resume'
+ );
+}
+
+async function waitForApprovalTool(page: Page) {
+ const token = await getAccessToken(page);
+ let latestTools: MCPToolsResponse | null = null;
+
+ for (let attempt = 0; attempt < 20; attempt++) {
+ latestTools = await fetchJson<MCPToolsResponse>(page, '/api/mcp/tools', token);
+ const tools = latestTools.servers?.[MCP_SERVER_NAME]?.tools ?? [];
+ if (tools.some((tool) => tool.pluginKey === APPROVAL_TOOL_ID)) {
+ return;
+ }
+ await page.waitForTimeout(500);
+ }
+
+ expect(
+ latestTools?.servers?.[MCP_SERVER_NAME]?.tools,
+ `Expected ${MCP_SERVER_NAME} to expose ${APPROVAL_TOOL_ID}`,
+ ).toEqual(expect.arrayContaining([expect.objectContaining({ pluginKey: APPROVAL_TOOL_ID })]));
+}
+
+export async function createAndSelectApprovalAgent(page: Page): Promise<string> {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await waitForApprovalTool(page);
+
+ const token = await getAccessToken(page);
+ const agentName = uniqueAgentName('E2E Tool Approval Agent');
+ const agent = await requestJson<AgentDetail>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name: agentName,
+ description: DESCRIPTION,
+ instructions: 'Use the requested approval probe tools and report their results.',
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ tools: [MCP_SERVER_TOOL_ID, APPROVAL_TOOL_ID],
+ },
+ });
+
+ const form = await openAgentBuilder(page);
+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();
+ await page.getByRole('option', { name: agentName }).click();
+ await expect(form.getByLabel('Agent name')).toHaveValue(agentName);
+ await form.getByRole('button', { name: 'Select Agent' }).click();
+ return agent.id;
+}
diff --git a/e2e/specs/mock/scenarios/composer-tool-approval.spec.ts b/e2e/specs/mock/scenarios/composer-tool-approval.spec.ts
new file mode 100644
index 0000000000..73361fdca2
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-tool-approval.spec.ts
@@ -0,0 +1,179 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ APPROVAL_REASON,
+ APPROVAL_PROMPT_MARKER,
+ uniqueLabel,
+ approvalCard,
+ approvalCards,
+ isResumeRequest,
+ composerApprovalPanel,
+ clearApprovalInvocations,
+ createAndSelectApprovalAgent,
+ expectApprovalInvocationCount,
+} from '../approvals.helpers';
+import { messagesView, replyPrompt, replyText, sendMessage } from '../helpers';
+import { cleanupAgent, closeMobileDrawer } from '../agents.helpers';
+
+const REVIEW_IN_COMPOSER = 'Review this request in the panel above the message box.';
+
+const approvalChip = (page: Page) => page.getByTestId('pending-tool-approval-button');
+/** The thread's own card: the composer panel renders a copy with the same call id. */
+const threadApprovalCard = (page: Page, toolCallId: string) =>
+ approvalCard(page, toolCallId).and(page.locator(':not(#pending-tool-approval-panel *)'));
+
+async function startWithApprovalAgent(page: Page): Promise<string> {
+ const agentId = await createAndSelectApprovalAgent(page);
+ await closeMobileDrawer(page);
+ return agentId;
+}
+
+async function expectComposerReview(page: Page) {
+ const panel = composerApprovalPanel(page);
+ await expect(panel).toBeVisible({ timeout: 30000 });
+ await expect(approvalChip(page)).toBeVisible();
+ await expect(approvalChip(page)).toHaveAttribute('aria-expanded', 'true');
+ return panel;
+}
+
+async function approveFromComposer(page: Page) {
+ const panel = composerApprovalPanel(page);
+ await panel.getByRole('button', { name: 'Approve' }).click();
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (candidate) => isResumeRequest(candidate.request()) && candidate.status() === 200,
+ ),
+ panel.getByRole('button', { name: 'Continue', exact: true }).click(),
+ ]);
+ return response;
+}
+
+async function expectRunCompleted(page: Page, value: string) {
+ await expect(
+ messagesView(page)
+ .getByText(/^E2E approval outcomes:/)
+ .last(),
+ ).toBeVisible({
+ timeout: 30000,
+ });
+ await expectApprovalInvocationCount(value, 1);
+ await expect(composerApprovalPanel(page)).toHaveCount(0);
+ await expect(approvalChip(page)).toHaveCount(0);
+ await expect(approvalCards(page)).toHaveCount(0);
+}
+
+test.describe('composer tool approval review', () => {
+ test('@scenario:composer-review-opens-when-a-new-chat-pauses-for-approval', async ({ page }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel();
+ const value = `original-${label}`;
+ let agentId: string | undefined;
+ clearApprovalInvocations(value);
+
+ try {
+ agentId = await startWithApprovalAgent(page);
+ const response = await sendMessage(page, `${APPROVAL_PROMPT_MARKER}${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+
+ const panel = await expectComposerReview(page);
+ await expect(panel).toContainText(APPROVAL_REASON);
+
+ await approveFromComposer(page);
+ await expectRunCompleted(page, value);
+ } finally {
+ clearApprovalInvocations(value);
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('@scenario:composer-review-opens-when-a-follow-up-turn-pauses-for-approval', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel();
+ const value = `original-${label}`;
+ let agentId: string | undefined;
+ clearApprovalInvocations(value);
+
+ try {
+ agentId = await startWithApprovalAgent(page);
+ await sendMessage(page, replyPrompt(label));
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+ await expect(messagesView(page).getByText(replyText(label))).toBeVisible({
+ timeout: 30000,
+ });
+ const conversationPath = new URL(page.url()).pathname;
+ await expect(composerApprovalPanel(page)).toHaveCount(0);
+ await expect(approvalChip(page)).toHaveCount(0);
+
+ const response = await sendMessage(page, `${APPROVAL_PROMPT_MARKER}${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(approvalCards(page).first()).toBeVisible({ timeout: 30000 });
+ expect(new URL(page.url()).pathname).toBe(conversationPath);
+
+ const panel = await expectComposerReview(page);
+ await expect(panel).toContainText(APPROVAL_REASON);
+
+ await approveFromComposer(page);
+ await expectRunCompleted(page, value);
+ } finally {
+ clearApprovalInvocations(value);
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('@scenario:thread-approval-card-defers-to-the-open-composer-review', async ({ page }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel();
+ const toolCallId = `call_e2e_approval_${label}`;
+ const value = `original-${label}`;
+ let agentId: string | undefined;
+ clearApprovalInvocations(value);
+
+ try {
+ agentId = await startWithApprovalAgent(page);
+ await sendMessage(page, `${APPROVAL_PROMPT_MARKER}${label}`);
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+ const panel = await expectComposerReview(page);
+
+ const card = threadApprovalCard(page, toolCallId);
+ await expect(card).toContainText(APPROVAL_REASON);
+ await expect(card).toContainText(REVIEW_IN_COMPOSER);
+ await expect(card.getByRole('button')).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Submit', exact: true })).toHaveCount(0);
+
+ await panel.getByRole('button', { name: 'Approve' }).click();
+
+ const chip = approvalChip(page);
+ await chip.focus();
+ await page.keyboard.press('Enter');
+ await expect(panel).toHaveCount(0);
+ await expect(chip).toHaveAttribute('aria-expanded', 'false');
+
+ await expect(card).not.toContainText(REVIEW_IN_COMPOSER);
+ await expect(card.getByRole('button', { name: 'Approve' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ const submit = card.getByRole('button', { name: 'Submit', exact: true });
+ await expect(submit).toBeEnabled();
+
+ await chip.press('Enter');
+ await expect(composerApprovalPanel(page)).toBeVisible();
+ await expect(card).toContainText(REVIEW_IN_COMPOSER);
+ await expect(card.getByRole('button')).toHaveCount(0);
+
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ const restoredPanel = await expectComposerReview(page);
+ await expect(threadApprovalCard(page, toolCallId)).toContainText(REVIEW_IN_COMPOSER);
+ await expect(restoredPanel).toContainText(APPROVAL_REASON);
+
+ await approveFromComposer(page);
+ await expectRunCompleted(page, value);
+ } finally {
+ clearApprovalInvocations(value);
+ await cleanupAgent(page, agentId);
+ }
+ });
+});
diff --git a/e2e/specs/mock/tool-approvals.spec.ts b/e2e/specs/mock/tool-approvals.spec.ts
index 7702affbe6..66feeee12c 100644
--- a/e2e/specs/mock/tool-approvals.spec.ts
+++ b/e2e/specs/mock/tool-approvals.spec.ts
@@ -1,143 +1,25 @@
-import * as fs from 'node:fs';
-import * as path from 'node:path';
import { expect, test } from '@playwright/test';
-import type { Locator, Page, Request, Route } from '@playwright/test';
-import type { AgentDetail } from './agents.helpers';
-import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';
+import type { Locator, Page, Route } from '@playwright/test';
+import type { ApprovalResumeBody, ApprovalResumeResponse } from './approvals.helpers';
import {
- MOCK_ENDPOINTS,
- NEW_CHAT_PATH,
- fetchJson,
- getAccessToken,
- messagesView,
- requestJson,
- sendMessage,
-} from './helpers';
-
-const MCP_SERVER_NAME = 'e2e-memory';
-const MCP_SERVER_TOOL_ID = `sys__server__sys_mcp_${MCP_SERVER_NAME}`;
-const APPROVAL_TOOL_NAME = 'approval_probe';
-const APPROVAL_TOOL_ID = `${APPROVAL_TOOL_NAME}_mcp_${MCP_SERVER_NAME}`;
-const APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL:';
-const BATCH_APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL_BATCH:';
-const RESTRICTED_APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL_RESTRICTED:';
-const REWRITTEN_APPROVAL_PROMPT_MARKER = 'E2E_TOOL_APPROVAL_REWRITE:';
-const APPROVAL_REASON = `E2E approval required before running ${APPROVAL_TOOL_ID}.`;
-const APPROVAL_ERROR = 'Something went wrong submitting your decision. Please try again.';
-const APPROVAL_EXPIRED = 'This request expired or was already handled.';
-const DESCRIPTION = 'Verifies human approval behavior for MCP tool calls in mock E2E tests.';
-const APPROVAL_AUDIT_DIR = path.join('/tmp', 'librechat-e2e-approval-audit');
-const uniqueLabel = () => `${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
-const approvalInvocationPath = (value: string) =>
- path.join(APPROVAL_AUDIT_DIR, Buffer.from(value).toString('base64url'));
-
-function clearApprovalInvocations(...values: string[]) {
- values.forEach((value) => fs.rmSync(approvalInvocationPath(value), { force: true }));
-}
-
-function approvalInvocationCount(value: string) {
- const filename = approvalInvocationPath(value);
- if (!fs.existsSync(filename)) {
- return 0;
- }
- return fs
- .readFileSync(filename, 'utf8')
- .split('\n')
- .filter((line) => line.length > 0).length;
-}
-
-async function expectApprovalInvocationCount(value: string, count: number) {
- await expect.poll(() => approvalInvocationCount(value), { timeout: 30000 }).toBe(count);
-}
-
-type MCPToolsResponse = {
- servers?: Record<string, { tools?: Array<{ pluginKey: string }> }>;
-};
-
-type ApprovalResumeBody = {
- actionId?: string;
- agent_id?: string;
- conversationId?: string;
- endpoint?: string;
- decisions?: Array<{
- tool_call_id?: string;
- decision?: string;
- reason?: string;
- responseText?: string;
- editedArguments?: Record<string, unknown>;
- }>;
-};
-
-type ApprovalResumeResponse = {
- conversationId?: string;
- status?: string;
- streamId?: string;
-};
-
-const approvalCards = (page: Page) => messagesView(page).getByTestId('tool-approval');
-const approvalCard = (page: Page, toolCallId: string) =>
- messagesView(page).locator(`[data-testid="tool-approval"][data-tool-call-id="${toolCallId}"]`);
-const composerApprovalPanel = (page: Page) => page.locator('#pending-tool-approval-panel');
-
-async function collapseComposerApproval(page: Page) {
- const panel = composerApprovalPanel(page);
- await expect(panel).toBeVisible({ timeout: 30000 });
- await panel.getByRole('button', { name: 'Collapse', exact: true }).click();
- await expect(panel).toHaveCount(0);
-}
-
-function isResumeRequest(request: Request) {
- return (
- request.method() === 'POST' && new URL(request.url()).pathname === '/api/agents/chat/resume'
- );
-}
-
-async function waitForApprovalTool(page: Page) {
- const token = await getAccessToken(page);
- let latestTools: MCPToolsResponse | null = null;
-
- for (let attempt = 0; attempt < 20; attempt++) {
- latestTools = await fetchJson<MCPToolsResponse>(page, '/api/mcp/tools', token);
- const tools = latestTools.servers?.[MCP_SERVER_NAME]?.tools ?? [];
- if (tools.some((tool) => tool.pluginKey === APPROVAL_TOOL_ID)) {
- return;
- }
- await page.waitForTimeout(500);
- }
-
- expect(
- latestTools?.servers?.[MCP_SERVER_NAME]?.tools,
- `Expected ${MCP_SERVER_NAME} to expose ${APPROVAL_TOOL_ID}`,
- ).toEqual(expect.arrayContaining([expect.objectContaining({ pluginKey: APPROVAL_TOOL_ID })]));
-}
-
-async function createAndSelectApprovalAgent(page: Page): Promise<string> {
- await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
- await waitForApprovalTool(page);
-
- const token = await getAccessToken(page);
- const agentName = uniqueAgentName('E2E Tool Approval Agent');
- const agent = await requestJson<AgentDetail>(page, {
- path: '/api/agents',
- token,
- method: 'POST',
- body: {
- name: agentName,
- description: DESCRIPTION,
- instructions: 'Use the requested approval probe tools and report their results.',
- provider: MOCK_ENDPOINTS[0].label,
- model: MOCK_ENDPOINTS[0].model,
- tools: [MCP_SERVER_TOOL_ID, APPROVAL_TOOL_ID],
- },
- });
-
- const form = await openAgentBuilder(page);
- await form.getByRole('combobox', { name: 'Agent', exact: true }).click();
- await page.getByRole('option', { name: agentName }).click();
- await expect(form.getByLabel('Agent name')).toHaveValue(agentName);
- await form.getByRole('button', { name: 'Select Agent' }).click();
- return agent.id;
-}
+ APPROVAL_ERROR,
+ APPROVAL_REASON,
+ APPROVAL_EXPIRED,
+ APPROVAL_PROMPT_MARKER,
+ BATCH_APPROVAL_PROMPT_MARKER,
+ REWRITTEN_APPROVAL_PROMPT_MARKER,
+ RESTRICTED_APPROVAL_PROMPT_MARKER,
+ uniqueLabel,
+ approvalCard,
+ approvalCards,
+ isResumeRequest,
+ collapseComposerApproval,
+ clearApprovalInvocations,
+ createAndSelectApprovalAgent,
+ expectApprovalInvocationCount,
+} from './approvals.helpers';
+import { NEW_CHAT_PATH, getAccessToken, messagesView, requestJson, sendMessage } from './helpers';
+import { cleanupAgent } from './agents.helpers';
async function startApproval(
page: Page,