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

🧐 feat: Restore Interactive Tool Approval Review (#15717)

Danny Avila6f05678bfc49
diff --git a/api/package.json b/api/package.json
index 1eb1194707..bd3d311b49 100644
--- a/api/package.json
+++ b/api/package.json
@@ -46,7 +46,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.8.1",
+ "@librechat/agents": "^3.8.2",
"@librechat/api": "*",
"@librechat/data-schemas": "*",
"@microsoft/microsoft-graph-client": "^3.0.7",
diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.js
index 062edf6639..b31d89b7f3 100644
--- a/api/server/controllers/agents/__tests__/resume.spec.js
+++ b/api/server/controllers/agents/__tests__/resume.spec.js
@@ -206,6 +206,7 @@ jest.mock('~/server/services/MCPRequestContext', () => ({
// Import after mocks
const ResumeAgentController = require('~/server/controllers/agents/resume');
+const { captureCodeExecutionApprovalBinding } = require('@librechat/api');
/** Drain the microtask + immediate queues so the post-ACK continuation settles. */
const flush = () => new Promise((resolve) => setImmediate(resolve));
@@ -2606,6 +2607,69 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
});
describe('happy path: approve -> reconstruct -> resume -> finalize', () => {
+ const statefulCodeAgent = (bridgeWorkerId) => ({
+ id: AGENT_ID,
+ codeExecutionContext: {
+ baseUrl: 'https://bridge.example/v1',
+ codeSessionKey: `execute_code:stateful:route-a:${bridgeWorkerId}`,
+ executionProfile: 'stateful',
+ executionRouteKey: 'stateful:route-a',
+ runtimeSessionHint: 'v3:environment-a:agent-user:scope-a',
+ statefulSessions: true,
+ environmentId: 'environment-a',
+ environmentType: 'attached',
+ bridgeWorkerId,
+ },
+ });
+
+ it('resumes when the rebuilt stateful code target matches the paused approval', async () => {
+ const agent = statefulCodeAgent('worker-a');
+ const codeExecutionBinding = captureCodeExecutionApprovalBinding([agent]);
+ mockGenerationJobManager.getJob.mockResolvedValue(
+ makeToolApprovalJob({ metadata: { pendingAction: { codeExecutionBinding } } }),
+ );
+ const resumedClient = makeClient({
+ options: { agent },
+ agentConfigs: new Map(),
+ });
+ mockInitializeClient.mockResolvedValue({ client: resumedClient, userMCPAuthMap: {} });
+
+ const res = await post(approveBody());
+ expect(res.status).toBe(200);
+ await settled;
+ await flush();
+
+ expect(mockGenerationJobManager.beginProviderExecution).toHaveBeenCalledTimes(1);
+ expect(resumedClient.resumeCompletion).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails before provider execution when the approved stateful code target changed', async () => {
+ const pausedAgent = statefulCodeAgent('worker-a');
+ const codeExecutionBinding = captureCodeExecutionApprovalBinding([pausedAgent]);
+ mockGenerationJobManager.getJob.mockResolvedValue(
+ makeToolApprovalJob({ metadata: { pendingAction: { codeExecutionBinding } } }),
+ );
+ const resumedClient = makeClient({
+ options: { agent: statefulCodeAgent('worker-b') },
+ agentConfigs: new Map(),
+ });
+ mockInitializeClient.mockResolvedValue({ client: resumedClient, userMCPAuthMap: {} });
+
+ const res = await post(approveBody());
+ expect(res.status).toBe(200);
+ await settled;
+ await flush();
+
+ expect(mockGenerationJobManager.beginProviderExecution).not.toHaveBeenCalled();
+ expect(resumedClient.resumeCompletion).not.toHaveBeenCalled();
+ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(
+ CONVO_ID,
+ expect.stringContaining('Retry the request and review the action again'),
+ 1000,
+ );
+ expect(mockDisposeClient).toHaveBeenCalledWith(resumedClient);
+ });
+
it('seals the exact paused legacy-event fence only after resumed history persists', async () => {
mockGenerationJobManager.getJob.mockResolvedValue(
makeToolApprovalJob({ metadata: { agentEventLegacyTurnToken: 'legacy-hitl-token' } }),
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 42b44580fa..9dada8692e 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -42,6 +42,7 @@ const {
resolveRecursionLimit,
buildPendingAction,
toClientPendingAction,
+ captureCodeExecutionApprovalBinding,
computeAgentRequestFingerprint,
getRunDiscoveredTools,
captureResumeModelParameters,
@@ -56,6 +57,7 @@ const {
collectAttachedCodeEnvironmentPolicySettings,
buildAttachedCodeEnvironmentAdmissionHooks,
resolveAttachedCodeApprovalMode,
+ markNativeCodeToolApprovalRequests,
agentRunUsesCheckpointer,
canAgentGraphPause,
getPluginHookSource,
@@ -143,6 +145,7 @@ const {
hasModelBoundContentProtection,
assertResumeRuntimeContentAllowed,
collectReachableAgents,
+ isStatefulCodeEnvironmentToolName,
stampMcpServerIdentities,
getDynamicToolContexts,
getSafeErrorMetadata,
@@ -4252,7 +4255,23 @@ class AgentClient extends BaseClient {
this.contentParts.push(...stamped);
}
}
- const pendingAction = buildPendingAction(interrupt.payload, {
+ const reachableAgents = collectReachableAgents([
+ this.options.agent,
+ ...(this.agentConfigs?.values() ?? []),
+ ]);
+ const interruptPayload =
+ interrupt.payload?.type === 'tool_approval'
+ ? markNativeCodeToolApprovalRequests(interrupt.payload, reachableAgents)
+ : interrupt.payload;
+ const codeExecutionBinding =
+ interrupt.payload?.type === 'tool_approval' &&
+ interrupt.payload.action_requests.some(
+ (action) =>
+ typeof action?.name === 'string' && isStatefulCodeEnvironmentToolName(action.name),
+ )
+ ? captureCodeExecutionApprovalBinding(reachableAgents)
+ : undefined;
+ const pendingAction = buildPendingAction(interruptPayload, {
streamId,
conversationId: this.conversationId,
// runId mirrors the LangGraph checkpoint namespace when the SDK provides it
@@ -4273,6 +4292,7 @@ class AgentClient extends BaseClient {
// reload/cross-replica resume can't reconstruct the ephemeral config client-side,
// so the server restores it and rebuilds the same graph (and the fingerprint matches).
resumeContext,
+ codeExecutionBinding,
});
// Job-replacement guard: streamId == conversationId is reused per conversation, so a
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index 9cb5cf424a..634590b888 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -949,6 +949,87 @@ describe('AgentClient - interrupt discovery persistence', () => {
});
});
+ it('binds a paused code approval to the resolved stateful target without storing raw routing data', async () => {
+ const streamId = 'conversation-code-target-pause';
+ const job = await GenerationJobManager.createJob(streamId, 'user-123', streamId);
+ const client = new AgentClient({
+ req: {
+ user: { id: 'user-123' },
+ body: { endpoint: EModelEndpoint.agents, agent_id: 'agent-123' },
+ config: { endpoints: { [EModelEndpoint.agents]: {} } },
+ },
+ res: {},
+ agent: {
+ id: 'agent-123',
+ endpoint: EModelEndpoint.openAI,
+ provider: EModelEndpoint.openAI,
+ model_parameters: { model: 'gpt-4' },
+ toolDefinitions: [{ name: 'bash_tool', toolType: 'builtin' }],
+ codeExecutionContext: {
+ baseUrl: 'https://private-bridge.example/v1',
+ codeSessionKey: 'execute_code:stateful:private-route:private-session',
+ executionProfile: 'stateful',
+ executionRouteKey: 'stateful:private-route',
+ runtimeSessionHint: 'private-session',
+ statefulSessions: true,
+ environmentId: 'personal-machine',
+ environmentType: 'attached',
+ bridgeWorkerId: 'private-worker',
+ },
+ },
+ contentParts: [],
+ collectedUsage: [],
+ artifactPromises: [],
+ });
+ client.conversationId = streamId;
+ client.responseMessageId = 'response-code-target-pause';
+ client.jobCreatedAt = job.createdAt;
+
+ await client.handleRunInterrupt(
+ {
+ getInterrupt: () => ({
+ interruptId: 'code-interrupt',
+ threadId: streamId,
+ payload: {
+ type: 'tool_approval',
+ action_requests: [
+ { name: 'bash_tool', arguments: { command: 'git status' }, tool_call_id: 'tc1' },
+ ],
+ review_configs: [
+ {
+ action_name: 'bash_tool',
+ tool_call_id: 'tc1',
+ allowed_decisions: ['approve', 'reject'],
+ },
+ ],
+ },
+ }),
+ getDiscoveredTools: () => ['bash_tool'],
+ getRunMessages: () => [],
+ },
+ streamId,
+ );
+
+ const paused = await GenerationJobManager.getJob(streamId);
+ expect(paused?.metadata.pendingAction.codeExecutionBinding).toEqual({
+ version: 1,
+ targets: [
+ {
+ agentId: 'agent-123',
+ targetHash: expect.stringMatching(/^[a-f0-9]{64}$/),
+ },
+ ],
+ });
+ expect(paused?.metadata.pendingAction.payload.action_requests[0]).toMatchObject({
+ name: 'bash_tool',
+ source: 'librechat_code',
+ });
+ const stored = JSON.stringify(paused?.metadata.pendingAction.codeExecutionBinding);
+ expect(stored).not.toContain('private-bridge');
+ expect(stored).not.toContain('private-worker');
+ expect(stored).not.toContain('private-session');
+ });
+
it('makes the run context meta durable when the run pauses', async () => {
const streamId = 'conversation-context-meta-pause';
const job = await GenerationJobManager.createJob(streamId, 'user-123', streamId);
diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js
index d6ec8c54fe..484ae01d7e 100644
--- a/api/server/controllers/agents/resume.js
+++ b/api/server/controllers/agents/resume.js
@@ -46,6 +46,8 @@ const {
createAgentEventActionRecorder,
createAgentEventActorDetachedActionLifecycle,
findAgentEventAppliedAction,
+ assertCodeExecutionApprovalBinding,
+ collectReachableAgents,
} = require('@librechat/api');
const { disposeClient } = require('~/server/cleanup');
const { decryptMetadata } = require('~/server/services/ActionService');
@@ -1826,6 +1828,14 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)
});
client = result.client;
+ // The user approved the code action against the route/session selected at
+ // pause time. Re-resolve it on this replica and fail before provider/tool
+ // execution if the environment, worker, or workspace scope moved.
+ assertCodeExecutionApprovalBinding(
+ pendingAction.codeExecutionBinding,
+ collectReachableAgents([client.options?.agent, ...(client.agentConfigs?.values() ?? [])]),
+ );
+
// Bind the rebuilt client to the in-flight turn's identity (no new user message).
client.conversationId = streamId;
// The resume operates on the SAME job (it moved it running again), so its identity is
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx
index 7647e99bea..96b0ad732a 100644
--- a/client/src/components/Chat/ChatView.tsx
+++ b/client/src/components/Chat/ChatView.tsx
@@ -1,4 +1,5 @@
import { memo, useMemo } from 'react';
+import { useAtomValue } from 'jotai';
import { useRecoilValue } from 'recoil';
import { useForm } from 'react-hook-form';
import { Spinner } from '@librechat/client';
@@ -15,7 +16,9 @@ import {
useLocalize,
} from '~/hooks';
import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers';
+import ApprovalProvider from './Messages/Content/ApprovalContext';
import ConversationStarters from './Input/ConversationStarters';
+import { pendingApprovalActionFamily } from './approval/state';
import { useGetMessagesByConvoId } from '~/data-provider';
import { AskAnswerHostProvider } from './ask/state';
import MessagesView from './Messages/MessagesView';
@@ -44,6 +47,9 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));
const saveDrafts = useRecoilValue(store.saveDrafts);
const centerFormOnLanding = useRecoilValue(store.centerFormOnLanding);
+ const pendingAction = useAtomValue(
+ pendingApprovalActionFamily(conversationId ?? Constants.NEW_CONVO),
+ );
const methods = useForm<ChatFormValues>({
defaultValues: { text: '' },
@@ -132,57 +138,59 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
<ChatFormProvider {...methods}>
<ChatContext.Provider value={chatHelpers}>
<AddedChatContext.Provider value={addedChatHelpers}>
- <Presentation>
- <div className="relative flex h-full w-full flex-col">
- <h1 className="sr-only">{pageHeading}</h1>
- <Header
- parentConversationId={parentConversationId}
- readOnly={isSubagentThreadReadOnly}
- />
- <>
- <div
- className={cn(
- 'flex flex-col',
- isLandingPage
- ? 'flex-1 items-center justify-end sm:justify-center'
- : 'h-full overflow-y-auto',
- )}
- >
- {content}
- {/* Named + opaque so a view transition (the ask_user_question
- popover ⇄ chat-card morph) paints the whole composer band
- over the travelling card instead of letting it show
- through below the composer. The background matches the
- page, so normal rendering is unchanged. */}
+ <ApprovalProvider pendingAction={pendingAction}>
+ <Presentation>
+ <div className="relative flex h-full w-full flex-col">
+ <h1 className="sr-only">{pageHeading}</h1>
+ <Header
+ parentConversationId={parentConversationId}
+ readOnly={isSubagentThreadReadOnly}
+ />
+ <>
<div
className={cn(
- 'w-full bg-presentation [view-transition-name:chat-form]',
- !isLandingPage && 'scrollbar-gutter-spacer',
- isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',
+ 'flex flex-col',
+ isLandingPage
+ ? 'flex-1 items-center justify-end sm:justify-center'
+ : 'h-full overflow-y-auto',
)}
>
- {isLandingPage && <ConversationStarters />}
- {isSubagentThreadReadOnly ? (
- <div
- className="mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm text-text-secondary xl:max-w-4xl"
- role="note"
- >
- {localize('com_ui_subagent_thread_read_only')}
- </div>
- ) : (
- <ChatForm
- index={index}
- placeholder={chatFormPlaceholder}
- project={isProjectLandingPage ? project : undefined}
- />
- )}
- {!isLandingPage && <Footer />}
+ {content}
+ {/* Named + opaque so a view transition (the ask_user_question
+ popover ⇄ chat-card morph) paints the whole composer band
+ over the travelling card instead of letting it show
+ through below the composer. The background matches the
+ page, so normal rendering is unchanged. */}
+ <div
+ className={cn(
+ 'w-full bg-presentation [view-transition-name:chat-form]',
+ !isLandingPage && 'scrollbar-gutter-spacer',
+ isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',
+ )}
+ >
+ {isLandingPage && <ConversationStarters />}
+ {isSubagentThreadReadOnly ? (
+ <div
+ className="mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm text-text-secondary xl:max-w-4xl"
+ role="note"
+ >
+ {localize('com_ui_subagent_thread_read_only')}
+ </div>
+ ) : (
+ <ChatForm
+ index={index}
+ placeholder={chatFormPlaceholder}
+ project={isProjectLandingPage ? project : undefined}
+ />
+ )}
+ {!isLandingPage && <Footer />}
+ </div>
</div>
- </div>
- {isLandingPage && <Footer />}
- </>
- </div>
- </Presentation>
+ {isLandingPage && <Footer />}
+ </>
+ </div>
+ </Presentation>
+ </ApprovalProvider>
</AddedChatContext.Provider>
</ChatContext.Provider>
</ChatFormProvider>
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index d350f5c80e..bcee4fa0f5 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -32,6 +32,10 @@ import {
useAddedChatContext,
useAssistantsMapContext,
} from '~/Providers';
+import {
+ PendingToolApprovalButton,
+ PendingToolApprovalPanel,
+} from '~/components/Chat/approval/Review';
import PendingManualSkillsChips from './PendingManualSkillsChips';
import usePastedTextEdit from '~/hooks/Files/usePastedTextEdit';
import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';
@@ -630,6 +634,9 @@ const ChatForm = memo(function ChatForm({
{index === 0 && (
<AskUserQuestionPopover conversationId={conversationId} textAreaRef={textAreaRef} />
)}
+ {index === 0 && conversationId != null && (
+ <PendingToolApprovalPanel conversationId={conversationId} />
+ )}
<SkillsCommand
index={index}
textAreaRef={textAreaRef}
@@ -789,6 +796,9 @@ const ChatForm = memo(function ChatForm({
setConversation={setConversation}
disabled={disableInputs || isSubmitting}
/>
+ {index === 0 && conversationId != null && (
+ <PendingToolApprovalButton conversationId={conversationId} />
+ )}
<div className="mx-auto flex" />
<TokenUsage index={index} conversation={conversation} isSubmitting={isSubmitting} />
{SpeechToText && (
diff --git a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
index eb4ce6bf13..ed1bf597ea 100644
--- a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
+++ b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
@@ -1,6 +1,14 @@
-import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';
-import { useAtom } from 'jotai';
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
import { useRecoilValue } from 'recoil';
+import { useAtom, useStore } from 'jotai';
import { Constants } from 'librechat-data-provider';
import type { Agents } from 'librechat-data-provider';
import type { AskAnswerStatus } from '~/components/Chat/ask/state';
@@ -9,6 +17,7 @@ import {
useSubmitAskAnswerMutation,
type ResumeAgentFields,
} from '~/data-provider';
+import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { askSubmitStatusAtom } from '~/components/Chat/ask/state';
import { resolveAskUserQuestionPart } from '~/utils/approval';
import { ChatContext } from '~/Providers/ChatContext';
@@ -49,6 +58,14 @@ interface ApprovalContextValue {
) => void;
/** Current decision a card holds, if any (drives selected-state styling). */
getDecision: (actionId: string, toolCallId: string) => Agents.ToolApprovalResolution | undefined;
+ /** Shared form state for duplicated timeline/composer review surfaces. */
+ getDecisionDraft: (actionId: string, toolCallId: string) => ToolApprovalDecisionDraft | undefined;
+ /** Replace a tool call's shared form state and notify every rendered surface. */
+ setDecisionDraft: (
+ actionId: string,
+ toolCallId: string,
+ draft: ToolApprovalDecisionDraft,
+ ) => void;
/** Every recorded decision for an action, in registration order (the submit batch). */
getDecisions: (actionId: string) => Agents.ToolApprovalResolution[];
/** Declare that a tool_call belongs to an action so submit can require all. */
@@ -67,6 +84,10 @@ interface ApprovalContextValue {
getStatus: (actionId: string) => AskAnswerStatus;
/** Set an action's submission status (driven by the cards' submit via `useResumeSubmit`). */
setStatus: (actionId: string, status: AskAnswerStatus) => void;
+ /** Atomically claim submission for an action across every rendered review surface. */
+ beginToolSubmission: (actionId: string) => boolean;
+ /** Release a claimed action after a retryable submission failure. */
+ endToolSubmission: (actionId: string) => void;
/** Restore a free-form question answer after transient phase-slice remounts. */
getAskAnswerDraft: (actionId: string) => string;
/** Retain a free-form question answer for this response message's lifetime. */
@@ -75,6 +96,13 @@ interface ApprovalContextValue {
const ApprovalContext = createContext<ApprovalContextValue | null>(null);
+export interface ToolApprovalDecisionDraft {
+ active: Agents.ToolApprovalDecisionType | null;
+ editText: string;
+ responseText: string;
+ reason: string;
+}
+
/** Cards call this; outside a provider it degrades to inert no-ops so a tool
* call without an active approval never crashes. */
export const useApprovalContext = (): ApprovalContextValue => {
@@ -86,6 +114,8 @@ const FALLBACK: ApprovalContextValue = {
version: 0,
setDecision: () => undefined,
getDecision: () => undefined,
+ getDecisionDraft: () => undefined,
+ setDecisionDraft: () => undefined,
getDecisions: () => [],
registerToolCall: () => undefined,
unregisterToolCall: () => undefined,
@@ -94,6 +124,8 @@ const FALLBACK: ApprovalContextValue = {
isReady: () => false,
getStatus: () => 'idle',
setStatus: () => undefined,
+ beginToolSubmission: () => false,
+ endToolSubmission: () => undefined,
getAskAnswerDraft: () => '',
setAskAnswerDraft: () => undefined,
};
@@ -117,27 +149,77 @@ const isExpiredError = (error: unknown): boolean => {
* context-dependent submit lives in {@link useResumeSubmit}, which the cards call —
* and the cards only render inside a live chat view where those providers exist.
*/
-export default function ApprovalProvider({ children }: { children: React.ReactNode }) {
+export default function ApprovalProvider({
+ children,
+ pendingAction,
+}: {
+ children: React.ReactNode;
+ pendingAction?: Agents.PendingAction | null;
+}) {
+ /** Content slices keep their historical local provider so exported/read-only
+ * renderers remain self-contained. Inside a live chat, reuse the provider
+ * spanning messages and composer instead of shadowing its decisions. */
+ const parent = useContext(ApprovalContext);
+ if (parent != null) {
+ return <>{children}</>;
+ }
+ return <ApprovalStateProvider pendingAction={pendingAction}>{children}</ApprovalStateProvider>;
+}
+
+function ApprovalStateProvider({
+ children,
+ pendingAction,
+}: {
+ children: React.ReactNode;
+ pendingAction?: Agents.PendingAction | null;
+}) {
/** actionId → (tool_call_id → resolution). Mutable refs so reads are
* synchronous for `isReady`/submit; `version` is threaded into the context
* value so each bump produces a new value reference and consumers re-render
* (the callbacks alone are referentially stable, so without it a bump would
* never propagate past the memoized value). */
const decisionsRef = useRef(new Map<string, Map<string, Agents.ToolApprovalResolution>>());
- const registeredRef = useRef(new Map<string, Set<string>>());
+ const decisionDraftsRef = useRef(new Map<string, Map<string, ToolApprovalDecisionDraft>>());
+ const registeredRef = useRef(new Map<string, Map<string, number>>());
+ /** Server-owned batch membership. Unlike card registrations, this survives
+ * folding, virtualization, late tool parts, and a second composer surface. */
+ const authoritativeRef = useRef(new Map<string, string[]>());
+ const authoritativeActionIdRef = useRef<string | null>(null);
const askAnswerDraftsRef = useRef(new Map<string, string>());
+ const submittingToolActionIdsRef = useRef(new Set<string>());
const [version, bump] = useState(0);
const rerender = useCallback(() => bump((v) => v + 1), []);
const [statusByAction, setStatusByAction] = useState<Record<string, AskAnswerStatus>>({});
+ useEffect(() => {
+ if (pendingAction?.payload.type !== 'tool_approval') {
+ authoritativeRef.current.clear();
+ authoritativeActionIdRef.current = null;
+ rerender();
+ return;
+ }
+ const { actionId } = pendingAction;
+ const nextIds = Array.from(
+ new Set(pendingAction.payload.action_requests.map((request) => request.tool_call_id)),
+ );
+ if (authoritativeActionIdRef.current !== actionId) {
+ decisionsRef.current.clear();
+ decisionDraftsRef.current.clear();
+ registeredRef.current.clear();
+ authoritativeRef.current.clear();
+ submittingToolActionIdsRef.current.clear();
+ setStatusByAction({});
+ }
+ authoritativeActionIdRef.current = actionId;
+ authoritativeRef.current.set(actionId, nextIds);
+ rerender();
+ }, [pendingAction, rerender]);
+
const registerToolCall = useCallback(
(actionId: string, toolCallId: string) => {
- const set = registeredRef.current.get(actionId) ?? new Set<string>();
- if (set.has(toolCallId)) {
- return;
- }
- set.add(toolCallId);
- registeredRef.current.set(actionId, set);
+ const counts = registeredRef.current.get(actionId) ?? new Map<string, number>();
+ counts.set(toolCallId, (counts.get(toolCallId) ?? 0) + 1);
+ registeredRef.current.set(actionId, counts);
/** A newly-registered call shifts the lead / "of N" count for sibling
* cards — re-render so they reflect it. */
rerender();
@@ -147,12 +229,17 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
const unregisterToolCall = useCallback(
(actionId: string, toolCallId: string) => {
- const set = registeredRef.current.get(actionId);
- if (!set || !set.has(toolCallId)) {
+ const counts = registeredRef.current.get(actionId);
+ const count = counts?.get(toolCallId);
+ if (!counts || count == null) {
return;
}
- set.delete(toolCallId);
- if (set.size === 0) {
+ if (count > 1) {
+ counts.set(toolCallId, count - 1);
+ } else {
+ counts.delete(toolCallId);
+ }
+ if (counts.size === 0) {
registeredRef.current.delete(actionId);
}
/** Keep the decision for the provider's message-scoped lifetime. A
@@ -166,12 +253,17 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
);
const getLeadToolCallId = useCallback(
- (actionId: string) => registeredRef.current.get(actionId)?.values().next().value,
+ (actionId: string) =>
+ authoritativeRef.current.get(actionId)?.[0] ??
+ registeredRef.current.get(actionId)?.keys().next().value,
[],
);
const getRegisteredCount = useCallback(
- (actionId: string) => registeredRef.current.get(actionId)?.size ?? 0,
+ (actionId: string) =>
+ authoritativeRef.current.get(actionId)?.length ??
+ registeredRef.current.get(actionId)?.size ??
+ 0,
[],
);
@@ -194,25 +286,45 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
[],
);
+ const getDecisionDraft = useCallback(
+ (actionId: string, toolCallId: string) =>
+ decisionDraftsRef.current.get(actionId)?.get(toolCallId),
+ [],
+ );
+
+ const setDecisionDraft = useCallback(
+ (actionId: string, toolCallId: string, draft: ToolApprovalDecisionDraft) => {
+ const drafts = decisionDraftsRef.current.get(actionId) ?? new Map();
+ drafts.set(toolCallId, draft);
+ decisionDraftsRef.current.set(actionId, drafts);
+ rerender();
+ },
+ [rerender],
+ );
+
const getDecisions = useCallback((actionId: string) => {
- const registered = registeredRef.current.get(actionId);
+ const required = authoritativeRef.current.get(actionId) ?? [
+ ...(registeredRef.current.get(actionId)?.keys() ?? []),
+ ];
const decisions = decisionsRef.current.get(actionId);
- if (registered == null || decisions == null) {
+ if (required.length === 0 || decisions == null) {
return [];
}
- return [...registered].flatMap((toolCallId) => {
+ return required.flatMap((toolCallId) => {
const decision = decisions.get(toolCallId);
return decision == null ? [] : [decision];
});
}, []);
const isReady = useCallback((actionId: string) => {
- const registered = registeredRef.current.get(actionId);
+ const required = authoritativeRef.current.get(actionId) ?? [
+ ...(registeredRef.current.get(actionId)?.keys() ?? []),
+ ];
const decided = decisionsRef.current.get(actionId);
- if (!registered || registered.size === 0) {
+ if (required.length === 0) {
return false;
}
- for (const toolCallId of registered) {
+ for (const toolCallId of required) {
if (!decided?.has(toolCallId)) {
return false;
}
@@ -229,6 +341,18 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
setStatusByAction((prev) => ({ ...prev, [actionId]: status }));
}, []);
+ const beginToolSubmission = useCallback((actionId: string): boolean => {
+ if (submittingToolActionIdsRef.current.has(actionId)) {
+ return false;
+ }
+ submittingToolActionIdsRef.current.add(actionId);
+ return true;
+ }, []);
+
+ const endToolSubmission = useCallback((actionId: string) => {
+ submittingToolActionIdsRef.current.delete(actionId);
+ }, []);
+
const getAskAnswerDraft = useCallback(
(actionId: string) => askAnswerDraftsRef.current.get(actionId) ?? '',
[],
@@ -247,6 +371,8 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
version,
setDecision,
getDecision,
+ getDecisionDraft,
+ setDecisionDraft,
getDecisions,
registerToolCall,
unregisterToolCall,
@@ -255,6 +381,8 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
isReady,
getStatus,
setStatus,
+ beginToolSubmission,
+ endToolSubmission,
getAskAnswerDraft,
setAskAnswerDraft,
}),
@@ -262,6 +390,8 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
version,
setDecision,
getDecision,
+ getDecisionDraft,
+ setDecisionDraft,
getDecisions,
registerToolCall,
unregisterToolCall,
@@ -270,6 +400,8 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
isReady,
getStatus,
setStatus,
+ beginToolSubmission,
+ endToolSubmission,
getAskAnswerDraft,
setAskAnswerDraft,
],
@@ -292,15 +424,14 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
* than crashing.
*/
export function useResumeSubmit() {
+ const jotaiStore = useStore();
const chatContext = useContext(ChatContext);
const conversation = chatContext?.conversation;
const getEphemeralAgent = useGetEphemeralAgent();
const approvalMutation = useSubmitToolApprovalMutation();
const askMutation = useSubmitAskAnswerMutation();
- const { getDecisions, isReady, setStatus } = useApprovalContext();
- /** React state cannot lock a second click in the same browser task. Keep a
- * synchronous action-id guard alongside the rendered submission status. */
- const submittingToolActionIdsRef = useRef(new Set<string>());
+ const { getDecisions, isReady, setStatus, beginToolSubmission, endToolSubmission } =
+ useApprovalContext();
const submittingAskActionIdsRef = useRef(new Set<string>());
/** Ask status lives in Jotai so it works from the composer (outside the
* provider); tool-approval status stays on the context. */
@@ -340,27 +471,41 @@ export function useResumeSubmit() {
if (!fields || decisions.length === 0 || !isReady(actionId)) {
return;
}
- if (submittingToolActionIdsRef.current.has(actionId)) {
+ if (!beginToolSubmission(actionId)) {
return;
}
- submittingToolActionIdsRef.current.add(actionId);
setStatus(actionId, 'submitting');
approvalMutation.mutate(
{ ...fields, actionId, decisions },
{
- onSuccess: () => setStatus(actionId, 'submitted'),
+ onSuccess: () => {
+ setStatus(actionId, 'submitted');
+ const pendingAtom = pendingApprovalActionFamily(fields.conversationId);
+ if (jotaiStore.get(pendingAtom)?.actionId === actionId) {
+ jotaiStore.set(pendingAtom, null);
+ }
+ },
onError: (error) => {
const expired = isExpiredError(error);
if (!expired) {
// Network/validation failures are retryable; a 409 is terminal.
- submittingToolActionIdsRef.current.delete(actionId);
+ endToolSubmission(actionId);
}
setStatus(actionId, expired ? 'expired' : 'error');
},
},
);
},
- [approvalMutation, buildResumeFields, getDecisions, isReady, setStatus],
+ [
+ approvalMutation,
+ beginToolSubmission,
+ buildResumeFields,
+ endToolSubmission,
+ getDecisions,
+ isReady,
+ jotaiStore,
+ setStatus,
+ ],
);
const submitAskAnswer = useCallback(
diff --git a/client/src/components/Chat/Messages/Content/ToolApproval.tsx b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
index 3e5a43d25f..61eb1840e4 100644
--- a/client/src/components/Chat/Messages/Content/ToolApproval.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
@@ -1,8 +1,9 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo } from 'react';
import { Button, TextareaAutosize } from '@librechat/client';
import { Check, X, Pencil, MessageSquare, TriangleAlert } from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
import type { TranslationKeys } from '~/hooks';
+import { boundApprovalLabel } from '~/components/Chat/approval/preview';
import { useApprovalContext, useResumeSubmit } from './ApprovalContext';
import { useLocalize } from '~/hooks';
import { cn, logger } from '~/utils';
@@ -62,10 +63,13 @@ export default function ToolApproval({
approval,
toolCallId,
args,
+ showSubmit = true,
}: {
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;
}) {
const localize = useLocalize();
const { actionId, allowed_decisions: allowedDecisions, description } = approval;
@@ -74,6 +78,8 @@ export default function ToolApproval({
unregisterToolCall,
setDecision,
getDecision,
+ getDecisionDraft,
+ setDecisionDraft,
isReady,
getStatus,
getLeadToolCallId,
@@ -86,20 +92,20 @@ export default function ToolApproval({
retainedDecision != null && allowedDecisions.includes(retainedDecision.decision)
? retainedDecision
: undefined;
- const [active, setActive] = useState<DecisionType | null>(
- () => initialDecision?.decision ?? null,
- );
- const [editText, setEditText] = useState(() =>
+ const initialEditText =
initialDecision?.decision === 'edit'
? (JSON.stringify(initialDecision.editedArguments, null, 2) ?? '{}')
- : seedArgs(args),
- );
- const [responseText, setResponseText] = useState(() =>
- initialDecision?.decision === 'respond' ? (initialDecision.responseText ?? '') : '',
- );
- const [reason, setReason] = useState(() =>
- initialDecision?.decision === 'reject' ? (initialDecision.reason ?? '') : '',
- );
+ : seedArgs(args);
+ const decisionDraft = getDecisionDraft(actionId, toolCallId) ?? {
+ active: initialDecision?.decision ?? null,
+ editText: initialEditText,
+ responseText:
+ initialDecision?.decision === 'respond' ? (initialDecision.responseText ?? '') : '',
+ reason: initialDecision?.decision === 'reject' ? (initialDecision.reason ?? '') : '',
+ };
+ const { active, editText, responseText, reason } = decisionDraft;
+ const updateDecisionDraft = (updates: Partial<typeof decisionDraft>) =>
+ setDecisionDraft(actionId, toolCallId, { ...decisionDraft, ...updates });
useEffect(() => {
registerToolCall(actionId, toolCallId);
@@ -110,6 +116,8 @@ export default function ToolApproval({
const status = getStatus(actionId);
const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
+ const safeDescription =
+ description == null ? undefined : boundApprovalLabel(description, 1024).label;
/** Recompute and store this card's decision whenever inputs change. A null
* resolution (e.g. invalid edit JSON) clears it so submit stays disabled. */
@@ -195,8 +203,8 @@ export default function ToolApproval({
data-testid="tool-approval"
data-tool-call-id={toolCallId}
>
- {description != null && description.length > 0 && (
- <p className="text-sm text-text-secondary">{description}</p>
+ {safeDescription != null && safeDescription.length > 0 && (
+ <p className="text-sm text-text-secondary">{safeDescription}</p>
)}
<div className="flex flex-wrap gap-2">
{allowedDecisions.map((decision) => {
@@ -208,7 +216,7 @@ export default function ToolApproval({
variant={active === decision ? 'default' : 'outline'}
disabled={locked}
aria-pressed={active === decision}
- onClick={() => setActive((prev) => (prev === decision ? null : decision))}
+ onClick={() => updateDecisionDraft({ active: active === decision ? null : decision })}
className="inline-flex items-center gap-1.5"
>
<Icon className="h-4 w-4" aria-hidden="true" />
@@ -223,7 +231,7 @@ export default function ToolApproval({
<TextareaAutosize
value={editText}
disabled={locked}
- onChange={(e) => setEditText(e.target.value)}
+ onChange={(e) => updateDecisionDraft({ editText: e.target.value })}
minRows={3}
maxRows={16}
className={cn(
@@ -242,7 +250,7 @@ export default function ToolApproval({
<TextareaAutosize
value={responseText}
disabled={locked}
- onChange={(e) => setResponseText(e.target.value)}
+ onChange={(e) => updateDecisionDraft({ responseText: e.target.value })}
minRows={2}
maxRows={12}
placeholder={localize('com_ui_tool_response_placeholder')}
@@ -255,7 +263,7 @@ export default function ToolApproval({
<TextareaAutosize
value={reason}
disabled={locked}
- onChange={(e) => setReason(e.target.value)}
+ onChange={(e) => updateDecisionDraft({ reason: e.target.value })}
minRows={1}
maxRows={6}
placeholder={localize('com_ui_reject_reason_placeholder')}
@@ -264,7 +272,7 @@ export default function ToolApproval({
/>
)}
- {isLead && (
+ {showSubmit && isLead && (
<div className="mt-1 flex items-center gap-3">
<Button
size="sm"
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx
index bbfee64788..42fea58c9c 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx
@@ -51,6 +51,31 @@ const createWrapper = (generationCreatedAt: number | null) =>
const wrapper = createWrapper(1000);
+const pendingAction: import('librechat-data-provider').Agents.PendingAction = {
+ actionId: 'action-1',
+ streamId: 'stream-1',
+ payload: {
+ type: 'tool_approval',
+ action_requests: [
+ { name: 'create_file', arguments: { path: 'one.ts' }, tool_call_id: 'call-1' },
+ { name: 'bash_tool', arguments: { command: 'npm test' }, tool_call_id: 'call-2' },
+ ],
+ review_configs: [
+ {
+ action_name: 'create_file',
+ tool_call_id: 'call-1',
+ allowed_decisions: ['approve', 'reject'],
+ },
+ {
+ action_name: 'bash_tool',
+ tool_call_id: 'call-2',
+ allowed_decisions: ['approve', 'reject'],
+ },
+ ],
+ },
+ createdAt: 1000,
+};
+
describe('useResumeSubmit', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -99,6 +124,80 @@ describe('useResumeSubmit', () => {
expect(mockApprovalMutate).toHaveBeenCalledTimes(2);
});
+ test('shares the synchronous submit lock across timeline and composer surfaces', () => {
+ const { result } = renderHook(
+ () => ({
+ approval: useApprovalContext(),
+ timeline: useResumeSubmit(),
+ composer: useResumeSubmit(),
+ }),
+ { wrapper },
+ );
+
+ act(() => {
+ result.current.approval.registerToolCall('action-1', 'call-1');
+ result.current.approval.setDecision('action-1', 'call-1', {
+ tool_call_id: 'call-1',
+ decision: 'approve',
+ });
+ result.current.timeline.submitToolApproval('action-1');
+ result.current.composer.submitToolApproval('action-1');
+ });
+
+ expect(mockApprovalMutate).toHaveBeenCalledTimes(1);
+ });
+
+ test('uses the server action payload as batch membership even when a card is hidden', () => {
+ const authoritativeWrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={createStore()}>
+ <ApprovalProvider pendingAction={pendingAction}>{children}</ApprovalProvider>
+ </JotaiProvider>
+ </RecoilRoot>
+ );
+ const { result } = renderHook(() => useApprovalContext(), {
+ wrapper: authoritativeWrapper,
+ });
+
+ expect(result.current.getRegisteredCount('action-1')).toBe(2);
+ expect(result.current.getLeadToolCallId('action-1')).toBe('call-1');
+
+ act(() => {
+ result.current.setDecision('action-1', 'call-1', {
+ tool_call_id: 'call-1',
+ decision: 'approve',
+ });
+ });
+ expect(result.current.isReady('action-1')).toBe(false);
+
+ act(() => {
+ result.current.setDecision('action-1', 'call-2', {
+ tool_call_id: 'call-2',
+ decision: 'reject',
+ });
+ });
+ expect(result.current.isReady('action-1')).toBe(true);
+
+ act(() => result.current.unregisterToolCall('action-1', 'call-2'));
+ expect(result.current.getRegisteredCount('action-1')).toBe(2);
+ expect(result.current.isReady('action-1')).toBe(true);
+ });
+
+ test('nested approval providers reuse the chat-level decision state', () => {
+ const nestedWrapper = ({ children }: { children: React.ReactNode }) => (
+ <RecoilRoot>
+ <JotaiProvider store={createStore()}>
+ <ApprovalProvider pendingAction={pendingAction}>
+ <ApprovalProvider>{children}</ApprovalProvider>
+ </ApprovalProvider>
+ </JotaiProvider>
+ </RecoilRoot>
+ );
+ const { result } = renderHook(() => useApprovalContext(), { wrapper: nestedWrapper });
+
+ expect(result.current.getRegisteredCount('action-1')).toBe(2);
+ });
+
test('retains a decision across a transient card unregister and re-register', () => {
const { result } = renderHook(() => useApprovalContext(), { wrapper });
const decision = { tool_call_id: 'call-1', decision: 'approve' } as const;
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 94905f7f49..cdf5c7992a 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
@@ -103,6 +103,38 @@ describe('ToolApproval', () => {
expect(submit).toBeEnabled();
});
+ test('duplicated review surfaces show and submit the same decision state', () => {
+ renderCards(
+ <>
+ <ToolApproval approval={approval()} toolCallId="call-1" args={{ a: 1 }} />
+ <ToolApproval
+ approval={approval()}
+ toolCallId="call-1"
+ args={{ a: 1 }}
+ showSubmit={false}
+ />
+ </>,
+ );
+
+ const [timelineApprove, composerApprove] = screen.getAllByRole('button', { name: 'Approve' });
+ const [timelineReject, composerReject] = screen.getAllByRole('button', { name: 'Reject' });
+
+ fireEvent.click(timelineApprove);
+ expect(timelineApprove).toHaveAttribute('aria-pressed', 'true');
+ expect(composerApprove).toHaveAttribute('aria-pressed', 'true');
+
+ fireEvent.click(composerReject);
+ expect(timelineApprove).toHaveAttribute('aria-pressed', 'false');
+ expect(composerApprove).toHaveAttribute('aria-pressed', 'false');
+ expect(timelineReject).toHaveAttribute('aria-pressed', 'true');
+ expect(composerReject).toHaveAttribute('aria-pressed', 'true');
+ const [timelineReason, composerReason] = screen.getAllByRole('textbox', { name: 'Reject' });
+ fireEvent.change(timelineReason, { target: { value: 'not on this machine' } });
+ expect(timelineReason).toHaveValue('not on this machine');
+ expect(composerReason).toHaveValue('not on this machine');
+ expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled();
+ });
+
test('restores a selected decision when the card remounts inside the same message', () => {
const tree = (key: string) => (
<RecoilRoot>
diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
index 7eae1f93c4..8ebccc4c61 100644
--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
@@ -9,7 +9,9 @@ jest.mock('react-router-dom', () => ({
}));
jest.mock('recoil', () => ({
+ atomFamily: () => () => ({}),
useRecoilValue: () => false,
+ useRecoilCallback: () => () => undefined,
}));
jest.mock('react-hook-form', () => ({
diff --git a/client/src/components/Chat/approval/Review.tsx b/client/src/components/Chat/approval/Review.tsx
new file mode 100644
index 0000000000..586b796e34
--- /dev/null
+++ b/client/src/components/Chat/approval/Review.tsx
@@ -0,0 +1,239 @@
+import { memo, useEffect, useMemo } from 'react';
+import { atomFamily } from 'jotai/utils';
+import { atom, 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';
+import type { TranslationKeys } from '~/hooks';
+import {
+ useApprovalContext,
+ useResumeSubmit,
+} from '~/components/Chat/Messages/Content/ApprovalContext';
+import { buildApprovalPreview, buildApprovalPreviews } from '~/components/Chat/approval/preview';
+import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
+import ToolApproval from '~/components/Chat/Messages/Content/ToolApproval';
+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'
+ ? (pendingAction as Agents.PendingAction & {
+ payload: Agents.ToolApprovalInterruptPayload;
+ })
+ : null;
+}
+
+const KIND_LABELS: Record<ReturnType<typeof buildApprovalPreview>['kind'], TranslationKeys> = {
+ command: 'com_ui_proposed_command',
+ create: 'com_ui_proposed_contents',
+ edit: 'com_ui_proposed_replacements',
+ generic: 'com_ui_proposed_arguments',
+};
+
+function previewTitle(
+ preview: ReturnType<typeof buildApprovalPreview>,
+ localize: ReturnType<typeof useLocalize>,
+): string {
+ if (preview.kind === 'command') return localize('com_ui_review_run_command');
+ if (preview.kind === 'create') {
+ return preview.target
+ ? localize('com_ui_review_create_file', { 0: preview.target })
+ : localize('com_ui_review_create_file_generic');
+ }
+ if (preview.kind === 'edit') {
+ return preview.target
+ ? localize('com_ui_review_edit_file', { 0: preview.target })
+ : localize('com_ui_review_edit_file_generic');
+ }
+ return preview.toolName;
+}
+
+export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
+ conversationId,
+}: {
+ conversationId: string;
+}) {
+ const localize = useLocalize();
+ const pendingAction = usePendingToolApproval(conversationId);
+ const [open, setOpen] = useAtom(approvalPanelOpenFamily(conversationId));
+ const { getDecisions, getStatus, isReady } = useApprovalContext();
+ const { submitToolApproval } = useResumeSubmit();
+ const actionId = pendingAction?.actionId;
+
+ useEffect(() => {
+ if (actionId != null) {
+ setOpen(true);
+ }
+ }, [actionId, setOpen]);
+
+ const reviews = useMemo(() => {
+ if (pendingAction == null) return [];
+ const configById = new Map(
+ pendingAction.payload.review_configs.map((config) => [config.tool_call_id, config]),
+ );
+ const previews = buildApprovalPreviews(pendingAction.payload.action_requests);
+ return pendingAction.payload.action_requests.map((request, index) => ({
+ request,
+ config: configById.get(request.tool_call_id),
+ preview: previews[index],
+ }));
+ }, [pendingAction]);
+
+ if (!open || pendingAction == null) {
+ return null;
+ }
+
+ const decisions = getDecisions(pendingAction.actionId);
+ const status = getStatus(pendingAction.actionId);
+ const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
+
+ return (
+ <div
+ id="pending-tool-approval-panel"
+ className="absolute bottom-28 z-10 w-full"
+ role="region"
+ aria-labelledby="pending-tool-approval-title"
+ aria-live="polite"
+ >
+ <div className="popover border-token-border-light flex max-h-[70vh] flex-col rounded-2xl border bg-surface-primary-alt shadow-lg">
+ <div className="flex shrink-0 items-center justify-between gap-2 border-b border-border-light px-3 py-2">
+ <p id="pending-tool-approval-title" className="text-sm font-medium text-text-primary">
+ {localize(reviews.length === 1 ? 'com_ui_review_action' : 'com_ui_review_actions', {
+ 0: reviews.length,
+ })}
+ </p>
+ <TooltipAnchor
+ description={localize('com_ui_collapse')}
+ side="top"
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={localize('com_ui_collapse')}
+ className="size-auto rounded-md p-1 text-text-secondary"
+ onClick={() => setOpen(false)}
+ >
+ <ChevronDown className="size-4" aria-hidden="true" />
+ </Button>
+ }
+ />
+ </div>
+ <div className="min-h-0 flex-1 space-y-3 overflow-y-auto p-3">
+ {reviews.map(({ request, config, preview }, index) => (
+ <section
+ key={request.tool_call_id}
+ aria-labelledby={`approval-${request.tool_call_id}`}
+ >
+ <div className="mb-2">
+ <h3
+ id={`approval-${request.tool_call_id}`}
+ className="text-sm font-medium text-text-primary [overflow-wrap:anywhere]"
+ >
+ {reviews.length > 1
+ ? `${index + 1}. ${previewTitle(preview, localize)}`
+ : previewTitle(preview, localize)}
+ </h3>
+ <p className="text-xs text-text-secondary">{localize(KIND_LABELS[preview.kind])}</p>
+ </div>
+ <pre className="max-h-52 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border-light bg-surface-tertiary p-3 font-mono text-xs text-text-primary">
+ {preview.body || localize('com_ui_no_arguments')}
+ </pre>
+ {preview.truncated && (
+ <p className="mt-1 text-xs text-text-secondary">
+ {localize('com_ui_preview_truncated')}
+ </p>
+ )}
+ {config != null ? (
+ <ToolApproval
+ approval={{
+ actionId: pendingAction.actionId,
+ allowed_decisions: config.allowed_decisions,
+ description: preview.description,
+ }}
+ toolCallId={request.tool_call_id}
+ args={request.arguments}
+ showSubmit={false}
+ />
+ ) : (
+ <p className="mt-2 flex items-center text-xs text-text-warning" role="alert">
+ <TriangleAlert className="mr-1.5 size-4" aria-hidden="true" />
+ {localize('com_ui_approval_unavailable')}
+ </p>
+ )}
+ </section>
+ ))}
+ </div>
+ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border-light px-3 py-2">
+ <span className="text-xs text-text-secondary">
+ {localize('com_ui_decisions_selected', {
+ 0: decisions.length,
+ 1: reviews.length,
+ })}
+ </span>
+ <div className="flex items-center gap-2">
+ {(status === 'expired' || status === 'error') && (
+ <span className="flex items-center text-xs text-text-warning" role="alert">
+ <TriangleAlert className="mr-1.5 size-4" aria-hidden="true" />
+ {localize(
+ status === 'expired' ? 'com_ui_approval_expired' : 'com_ui_approval_error',
+ )}
+ </span>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ variant="submit"
+ disabled={!isReady(pendingAction.actionId) || locked}
+ onClick={() => submitToolApproval(pendingAction.actionId)}
+ >
+ {status === 'submitting'
+ ? localize('com_ui_submitting')
+ : localize('com_ui_continue')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+});
+
+export const PendingToolApprovalButton = memo(function PendingToolApprovalButton({
+ conversationId,
+}: {
+ conversationId: string;
+}) {
+ const localize = useLocalize();
+ const pendingAction = usePendingToolApproval(conversationId);
+ const [open, setOpen] = useAtom(approvalPanelOpenFamily(conversationId));
+
+ if (pendingAction == null) {
+ return null;
+ }
+
+ const count = pendingAction.payload.action_requests.length;
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-expanded={open}
+ aria-controls="pending-tool-approval-panel"
+ onClick={() => setOpen((current) => !current)}
+ className="h-8 gap-1.5 rounded-full px-2 text-text-secondary"
+ data-testid="pending-tool-approval-button"
+ >
+ <ShieldQuestion className="size-4" aria-hidden="true" />
+ <span>
+ {localize(count === 1 ? 'com_ui_review_action' : 'com_ui_review_actions', { 0: count })}
+ </span>
+ {open ? (
+ <ChevronDown className="size-3.5" aria-hidden="true" />
+ ) : (
+ <ChevronUp className="size-3.5" aria-hidden="true" />
+ )}
+ </Button>
+ );
+});
diff --git a/client/src/components/Chat/approval/__tests__/Review.test.tsx b/client/src/components/Chat/approval/__tests__/Review.test.tsx
new file mode 100644
index 0000000000..c0b894a784
--- /dev/null
+++ b/client/src/components/Chat/approval/__tests__/Review.test.tsx
@@ -0,0 +1,124 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { Provider as JotaiProvider, createStore } from 'jotai';
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { Agents } from 'librechat-data-provider';
+import { PendingToolApprovalButton, PendingToolApprovalPanel } from '../Review';
+import ApprovalProvider from '../../Messages/Content/ApprovalContext';
+import { pendingApprovalActionFamily } from '../state';
+
+jest.mock('@librechat/client', () => ({
+ Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props}>{children}</button>
+ ),
+ TextareaAutosize: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => (
+ <textarea {...props} />
+ ),
+ TooltipAnchor: ({ render }: { render: React.ReactNode }) => render,
+}));
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, values?: Record<string | number, string | number>) => {
+ const labels: Record<string, string> = {
+ com_ui_review_action: 'Review 1 action',
+ com_ui_review_actions: `Review ${values?.[0]} actions`,
+ com_ui_review_run_command: 'Run command',
+ com_ui_review_create_file: `Create ${values?.[0]}`,
+ com_ui_review_create_file_generic: 'Create file',
+ com_ui_review_edit_file: `Edit ${values?.[0]}`,
+ com_ui_review_edit_file_generic: 'Edit file',
+ com_ui_proposed_command: 'Proposed command',
+ com_ui_proposed_contents: 'Proposed contents',
+ com_ui_proposed_replacements: 'Proposed replacements',
+ com_ui_proposed_arguments: 'Proposed arguments',
+ com_ui_decisions_selected: `${values?.[0]} of ${values?.[1]} decisions selected`,
+ com_ui_approve: 'Approve',
+ com_ui_reject: 'Reject',
+ com_ui_continue: 'Continue',
+ com_ui_collapse: 'Collapse',
+ };
+ return labels[key] ?? key;
+ },
+}));
+
+jest.mock('~/data-provider', () => ({
+ useSubmitToolApprovalMutation: () => ({ mutate: jest.fn() }),
+ useSubmitAskAnswerMutation: () => ({ mutate: jest.fn() }),
+}));
+
+jest.mock('~/store/agents', () => ({
+ useGetEphemeralAgent: () => () => undefined,
+}));
+
+const pendingAction: Agents.PendingAction = {
+ actionId: 'action-1',
+ streamId: 'stream-1',
+ conversationId: 'conversation-1',
+ createdAt: 1000,
+ payload: {
+ type: 'tool_approval',
+ action_requests: [
+ {
+ name: 'create_file',
+ source: 'librechat_code',
+ tool_call_id: 'call-1',
+ arguments: { path: 'src/new.ts', content: 'export const value = 1;' },
+ },
+ {
+ name: 'bash_tool',
+ source: 'librechat_code',
+ tool_call_id: 'call-2',
+ arguments: { command: 'npm test -- new' },
+ },
+ ],
+ review_configs: [
+ {
+ action_name: 'create_file',
+ tool_call_id: 'call-1',
+ allowed_decisions: ['approve', 'reject'],
+ },
+ {
+ action_name: 'bash_tool',
+ tool_call_id: 'call-2',
+ allowed_decisions: ['approve', 'reject'],
+ },
+ ],
+ },
+};
+
+describe('PendingToolApproval', () => {
+ test('reviews the authoritative batch beside the composer and can be collapsed', async () => {
+ const jotaiStore = createStore();
+ jotaiStore.set(pendingApprovalActionFamily('conversation-1'), pendingAction);
+ render(
+ <RecoilRoot>
+ <JotaiProvider store={jotaiStore}>
+ <ApprovalProvider pendingAction={pendingAction}>
+ <PendingToolApprovalPanel conversationId="conversation-1" />
+ <PendingToolApprovalButton conversationId="conversation-1" />
+ </ApprovalProvider>
+ </JotaiProvider>
+ </RecoilRoot>,
+ );
+
+ expect(await screen.findByRole('region', { name: 'Review 2 actions' })).toBeInTheDocument();
+ expect(screen.getByText(/Create src\/new\.ts/)).toBeInTheDocument();
+ expect(screen.getByText('npm test -- new')).toBeInTheDocument();
+ expect(screen.getByText('0 of 2 decisions selected')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled();
+
+ const approvals = screen.getAllByRole('button', { name: 'Approve' });
+ fireEvent.click(approvals[0]);
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled();
+ fireEvent.click(approvals[1]);
+ expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled();
+ expect(screen.getByText('2 of 2 decisions selected')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Collapse' }));
+ expect(screen.queryByRole('region', { name: 'Review 2 actions' })).not.toBeInTheDocument();
+ expect(screen.getByTestId('pending-tool-approval-button')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+});
diff --git a/client/src/components/Chat/approval/__tests__/preview.test.ts b/client/src/components/Chat/approval/__tests__/preview.test.ts
new file mode 100644
index 0000000000..77111f9abc
--- /dev/null
+++ b/client/src/components/Chat/approval/__tests__/preview.test.ts
@@ -0,0 +1,152 @@
+import { buildApprovalPreview, buildApprovalPreviews } from '../preview';
+
+describe('buildApprovalPreview', () => {
+ test('shows the exact effective command and reveals bidi control characters', () => {
+ const preview = buildApprovalPreview({
+ name: 'bash_tool',
+ source: 'librechat_code',
+ tool_call_id: 'call-1',
+ arguments: { command: 'git status\u202etest' },
+ });
+
+ expect(preview).toMatchObject({
+ kind: 'command',
+ toolName: 'bash_tool',
+ body: 'git status\\u202etest',
+ truncated: false,
+ });
+ });
+
+ test('renders ordered edit replacements as proposals', () => {
+ const preview = buildApprovalPreview({
+ name: 'edit_file',
+ source: 'librechat_code',
+ tool_call_id: 'call-1',
+ arguments: {
+ path: 'src/index.ts',
+ edits: [
+ { old_text: 'one', new_text: 'two' },
+ { old_text: '', new_text: 'three' },
+ ],
+ },
+ });
+
+ expect(preview.target).toBe('src/index.ts');
+ expect(JSON.parse(preview.body)).toEqual([
+ { old_text: 'one', new_text: 'two' },
+ { old_text: '', new_text: 'three' },
+ ]);
+ });
+
+ test('does not classify an MCP-qualified coding name as a built-in', () => {
+ const preview = buildApprovalPreview({
+ name: 'filesystem__create_file',
+ tool_call_id: 'call-1',
+ arguments: { path: 'outside.txt', content: 'data' },
+ });
+
+ expect(preview.kind).toBe('generic');
+ expect(preview.toolName).toBe('filesystem__create_file');
+ expect(preview.body).toContain('"path": "outside.txt"');
+ });
+
+ test('does not specialize a same-name tool without native server provenance', () => {
+ const preview = buildApprovalPreview({
+ name: 'create_file',
+ tool_call_id: 'call-1',
+ arguments: { path: 'outside.txt', content: 'data' },
+ });
+
+ expect(preview.kind).toBe('generic');
+ expect(preview.target).toBeUndefined();
+ expect(preview.body).toContain('"path": "outside.txt"');
+ });
+
+ test('bounds an initially rendered preview by line count and character count', () => {
+ const preview = buildApprovalPreview({
+ name: 'create_file',
+ source: 'librechat_code',
+ tool_call_id: 'call-1',
+ arguments: { path: 'large.txt', content: `${'x'.repeat(20_000)}\n${'line\n'.repeat(250)}` },
+ });
+
+ expect(preview.truncated).toBe(true);
+ expect(preview.body.length).toBeLessThanOrEqual(16 * 1024);
+ expect(preview.body.split('\n')).toHaveLength(1);
+ });
+
+ test('bounds the aggregate initial preview for a large approval batch', () => {
+ const previews = buildApprovalPreviews(
+ Array.from({ length: 8 }, (_, index) => ({
+ name: 'create_file',
+ source: 'librechat_code' as const,
+ tool_call_id: `call-${index}`,
+ arguments: { path: `${index}.txt`, content: 'x'.repeat(16 * 1024) },
+ })),
+ );
+
+ expect(
+ previews.reduce(
+ (total, preview) =>
+ total +
+ preview.toolName.length +
+ (preview.description?.length ?? 0) +
+ preview.body.length +
+ (preview.target?.length ?? 0),
+ 0,
+ ),
+ ).toBeLessThanOrEqual(64 * 1024);
+ expect(previews.at(-1)).toMatchObject({ body: '', truncated: true });
+ });
+
+ test('applies the visible cap after expanding hidden control characters', () => {
+ const preview = buildApprovalPreview({
+ name: 'create_file',
+ source: 'librechat_code',
+ tool_call_id: 'call-1',
+ arguments: { path: 'controls.txt', content: '\u202e'.repeat(16 * 1024) },
+ });
+
+ expect(preview.body.length).toBeLessThanOrEqual(16 * 1024);
+ expect(preview.truncated).toBe(true);
+ });
+
+ test('reveals and bounds hostile file targets inside the total preview budget', () => {
+ const preview = buildApprovalPreview({
+ name: 'create_file',
+ source: 'librechat_code',
+ tool_call_id: 'call-1',
+ arguments: {
+ path: `spoof\nname\u202ets/${'nested/'.repeat(300)}`,
+ content: 'x'.repeat(16 * 1024),
+ },
+ });
+
+ expect(preview.target).not.toContain('\n');
+ expect(preview.target).toContain('\\u000a');
+ expect(preview.target?.length).toBeLessThanOrEqual(1024);
+ expect((preview.target?.length ?? 0) + preview.body.length).toBeLessThanOrEqual(16 * 1024);
+ expect(preview.truncated).toBe(true);
+ });
+
+ test('reveals and bounds generic tool labels and descriptions', () => {
+ const preview = buildApprovalPreview({
+ name: `run\nspoof\u061c\u200e\u200f\u206a${'x'.repeat(500)}`,
+ description: `explain\r\u0085${'y'.repeat(2000)}`,
+ tool_call_id: 'call-1',
+ arguments: { value: 'safe' },
+ });
+
+ expect(preview.toolName).toContain('\\u000a');
+ expect(preview.toolName).toContain('\\u061c');
+ expect(preview.toolName).toContain('\\u200e');
+ expect(preview.toolName).toContain('\\u200f');
+ expect(preview.toolName).toContain('\\u206a');
+ expect(preview.toolName).not.toContain('\n');
+ expect(preview.toolName.length).toBeLessThanOrEqual(256);
+ expect(preview.description).toContain('\\u000d');
+ expect(preview.description).toContain('\\u0085');
+ expect(preview.description?.length).toBeLessThanOrEqual(1024);
+ expect(preview.truncated).toBe(true);
+ });
+});
diff --git a/client/src/components/Chat/approval/preview.ts b/client/src/components/Chat/approval/preview.ts
new file mode 100644
index 0000000000..23652e1051
--- /dev/null
+++ b/client/src/components/Chat/approval/preview.ts
@@ -0,0 +1,178 @@
+import type { Agents } from 'librechat-data-provider';
+
+const MAX_PREVIEW_CHARS = 16 * 1024;
+const MAX_PREVIEW_LINES = 200;
+const MAX_BATCH_PREVIEW_CHARS = 64 * 1024;
+const MAX_TARGET_CHARS = 1024;
+const MAX_DESCRIPTION_CHARS = 1024;
+const MAX_TOOL_NAME_CHARS = 256;
+
+export interface ApprovalPreview {
+ kind: 'command' | 'create' | 'edit' | 'generic';
+ toolName: string;
+ description?: string;
+ target?: string;
+ body: string;
+ truncated: boolean;
+}
+
+/* eslint-disable no-control-regex -- reviewing hidden controls requires matching the C0 ranges */
+const CONTROL_CHARACTERS =
+ /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u206f]/g;
+/* eslint-enable no-control-regex */
+
+function revealControlCharacters(value: string): string {
+ return value.replace(CONTROL_CHARACTERS, (character) => {
+ const codePoint = character.codePointAt(0)?.toString(16).padStart(4, '0') ?? '????';
+ return `\\u${codePoint}`;
+ });
+}
+
+/* eslint-disable no-control-regex -- headings must reveal even ordinary whitespace controls */
+const TARGET_CONTROL_CHARACTERS =
+ /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u206f]/g;
+/* eslint-enable no-control-regex */
+
+export function boundApprovalLabel(
+ value: string,
+ maxChars: number,
+): { label: string; truncated: boolean } {
+ const revealed = value.replace(TARGET_CONTROL_CHARACTERS, (character) => {
+ const codePoint = character.codePointAt(0)?.toString(16).padStart(4, '0') ?? '????';
+ return `\\u${codePoint}`;
+ });
+ return {
+ label: revealed.slice(0, maxChars),
+ truncated: revealed.length > maxChars,
+ };
+}
+
+function boundPreview(
+ value: string,
+ maxChars = MAX_PREVIEW_CHARS,
+): { body: string; truncated: boolean } {
+ const lines = value.split('\n');
+ const lineBounded = lines.length > MAX_PREVIEW_LINES ? lines.slice(0, MAX_PREVIEW_LINES) : lines;
+ const rawBody = lineBounded.join('\n');
+ let body = revealControlCharacters(rawBody);
+ const truncatedByLines = lineBounded.length < lines.length;
+ const truncatedByChars = body.length > maxChars;
+ if (truncatedByChars) {
+ body = body.slice(0, maxChars);
+ }
+ return {
+ body,
+ truncated: truncatedByLines || truncatedByChars,
+ };
+}
+
+function parseArguments(
+ args: Agents.ToolApprovalRequest['arguments'],
+): Record<string, unknown> | undefined {
+ if (typeof args === 'object' && args !== null && !Array.isArray(args)) {
+ return args;
+ }
+ if (typeof args !== 'string') {
+ return undefined;
+ }
+ try {
+ const parsed: unknown = JSON.parse(args);
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function stringField(args: Record<string, unknown> | undefined, ...keys: string[]): string {
+ for (const key of keys) {
+ const value = args?.[key];
+ if (typeof value === 'string') {
+ return value;
+ }
+ }
+ return '';
+}
+
+function stringifyArguments(args: unknown): string {
+ if (typeof args === 'string') {
+ return args;
+ }
+ try {
+ return JSON.stringify(args, null, 2);
+ } catch {
+ return String(args);
+ }
+}
+
+/** Build a bounded, inert preview from the exact effective arguments in the interrupt. */
+export function buildApprovalPreview(
+ request: Agents.ToolApprovalRequest,
+ maxChars = MAX_PREVIEW_CHARS,
+): ApprovalPreview {
+ const parsed = parseArguments(request.arguments);
+ let kind: ApprovalPreview['kind'] = 'generic';
+ let target: string | undefined;
+ let rawBody = stringifyArguments(request.arguments);
+
+ if (request.source === 'librechat_code' && request.name === 'bash_tool' && parsed) {
+ kind = 'command';
+ rawBody = stringField(parsed, 'command');
+ } else if (request.source === 'librechat_code' && request.name === 'create_file' && parsed) {
+ kind = 'create';
+ target = stringField(parsed, 'path', 'file_path') || undefined;
+ rawBody = stringField(parsed, 'content') || stringifyArguments(request.arguments);
+ } else if (request.source === 'librechat_code' && request.name === 'edit_file' && parsed) {
+ kind = 'edit';
+ target = stringField(parsed, 'path', 'file_path') || undefined;
+ rawBody = stringifyArguments(parsed.edits ?? parsed);
+ }
+
+ const totalBudget = Math.max(0, maxChars);
+ const boundedToolName = boundApprovalLabel(
+ request.name,
+ Math.min(MAX_TOOL_NAME_CHARS, totalBudget),
+ );
+ let remainingBudget = Math.max(0, totalBudget - boundedToolName.label.length);
+ const boundedDescription =
+ request.description == null
+ ? undefined
+ : boundApprovalLabel(request.description, Math.min(MAX_DESCRIPTION_CHARS, remainingBudget));
+ remainingBudget = Math.max(0, remainingBudget - (boundedDescription?.label.length ?? 0));
+ const boundedTarget =
+ target == null
+ ? undefined
+ : boundApprovalLabel(target, Math.min(MAX_TARGET_CHARS, remainingBudget));
+ remainingBudget = Math.max(0, remainingBudget - (boundedTarget?.label.length ?? 0));
+ const boundedBody = boundPreview(rawBody, remainingBudget);
+ return {
+ kind,
+ toolName: boundedToolName.label,
+ description: boundedDescription?.label,
+ target: boundedTarget?.label,
+ body: boundedBody.body,
+ truncated:
+ boundedBody.truncated ||
+ boundedTarget?.truncated === true ||
+ boundedDescription?.truncated === true ||
+ boundedToolName.truncated,
+ };
+}
+
+/** Keep a large approval batch from multiplying per-action preview work in the composer. */
+export function buildApprovalPreviews(requests: Agents.ToolApprovalRequest[]): ApprovalPreview[] {
+ let remainingChars = MAX_BATCH_PREVIEW_CHARS;
+ return requests.map((request) => {
+ const preview = buildApprovalPreview(request, Math.min(MAX_PREVIEW_CHARS, remainingChars));
+ remainingChars = Math.max(
+ 0,
+ remainingChars -
+ preview.body.length -
+ preview.toolName.length -
+ (preview.description?.length ?? 0) -
+ (preview.target?.length ?? 0),
+ );
+ return preview;
+ });
+}
diff --git a/client/src/components/Chat/approval/state.ts b/client/src/components/Chat/approval/state.ts
new file mode 100644
index 0000000000..d812e1627e
--- /dev/null
+++ b/client/src/components/Chat/approval/state.ts
@@ -0,0 +1,14 @@
+import { atom } from 'jotai';
+import { atomFamily } from 'jotai/utils';
+import type { Agents } from 'librechat-data-provider';
+
+/**
+ * The server-owned pending action for one conversation.
+ *
+ * Kept outside message rendering so the composer and timeline can project the
+ * same action without making mounted cards the source of truth. This state is
+ * memory-only: reload hydration comes from the stream status endpoint.
+ */
+export const pendingApprovalActionFamily = atomFamily((_conversationId: string) =>
+ atom<Agents.PendingAction | null>(null),
+);
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index c45d99c442..a42af9fa7c 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -1,3 +1,4 @@
+import { getDefaultStore } from 'jotai';
import { renderHook, act, waitFor } from '@testing-library/react';
import {
Constants,
@@ -9,6 +10,7 @@ import {
request,
} from 'librechat-data-provider';
import type { TMessage, TSubmission } from 'librechat-data-provider';
+import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
type SSEEventListener = (e: Partial<MessageEvent> & { responseCode?: number }) => void;
@@ -2171,6 +2173,12 @@ describe('useResumableSSE', () => {
mockFetchStreamStatus.mockResolvedValue({ active: false, generationProtocolVersion: 2 });
const submission = buildSubmission();
const chatHelpers = buildChatHelpers();
+ getDefaultStore().set(pendingApprovalActionFamily(CONV_ID), {
+ actionId: 'stale-action',
+ streamId: CONV_ID,
+ createdAt: 1000,
+ payload: { type: 'tool_approval', action_requests: [], review_configs: [] },
+ });
const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
await flushMicrotasks();
@@ -2194,6 +2202,7 @@ describe('useResumableSSE', () => {
expect(mockFinalHandler).not.toHaveBeenCalled();
expect(mockErrorHandler).not.toHaveBeenCalled();
+ expect(getDefaultStore().get(pendingApprovalActionFamily(CONV_ID))).toBeNull();
expect(mockInvalidateQueries).toHaveBeenCalledWith({
queryKey: [QueryKeys.messages, CONV_ID],
refetchType: 'none',
diff --git a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
index 7261870e77..0521479130 100644
--- a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
+++ b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
@@ -3,11 +3,12 @@ import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Provider as JotaiProvider, createStore, useAtomValue } from 'jotai';
import { Constants, ContentTypes, QueryKeys } from 'librechat-data-provider';
-import type { TMessage, TConversation, TSubmission } from 'librechat-data-provider';
+import type { Agents, TMessage, TConversation, TSubmission } from 'librechat-data-provider';
import type { MutableSnapshot } from 'recoil';
import type { ReactNode } from 'react';
import type { PendingSteer, QueuedMessage } from '~/store/families';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
+import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import useResumeOnLoad from '../useResumeOnLoad';
import store from '~/store';
@@ -185,6 +186,7 @@ function renderUseResumeOnLoad({
return {
queryClient,
+ jotaiStore,
getMessages,
setSubmission: (nextSubmission: TSubmission | null) => setSubmissionState?.(nextSubmission),
setIsSubmitting: (value: boolean) => setIsSubmittingState?.(value),
@@ -343,6 +345,53 @@ describe('useResumeOnLoad', () => {
expect(attached?.resumeGenerationCreatedAt).toBe(4242);
});
+ it('restores the composer approval surface from the authoritative status snapshot', async () => {
+ const pendingAction: Agents.PendingAction = {
+ actionId: 'action-1',
+ streamId: CONVERSATION_ID,
+ conversationId: CONVERSATION_ID,
+ createdAt: 4242,
+ payload: {
+ type: 'tool_approval',
+ action_requests: [
+ {
+ name: 'bash_tool',
+ tool_call_id: 'call-1',
+ arguments: { command: 'npm test' },
+ },
+ ],
+ review_configs: [
+ {
+ action_name: 'bash_tool',
+ tool_call_id: 'call-1',
+ allowed_decisions: ['approve', 'reject'],
+ },
+ ],
+ },
+ };
+ mockUseStreamStatus.mockReturnValue({
+ ...ACTIVE_STATUS,
+ data: {
+ ...ACTIVE_STATUS.data,
+ status: 'requires_action',
+ pendingAction,
+ resumeState: {
+ ...ACTIVE_STATUS.data.resumeState,
+ pendingAction,
+ },
+ },
+ });
+
+ const { jotaiStore } = renderUseResumeOnLoad({
+ messages: [buildUserMessage(CONVERSATION_ID)],
+ });
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(jotaiStore.get(pendingApprovalActionFamily(CONVERSATION_ID))).toEqual(pendingAction);
+ });
+
/** The elapsed indicator's baseline must be the generation's real start:
* an attach with no surviving anchor (a reload, or a run another client
* started) rebuilds it clock-locally from the server-computed generation
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index f30dcae4d1..8a9696b439 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -1,6 +1,7 @@
import { useEffect, useState, useRef, useCallback } from 'react';
import { v4 } from 'uuid';
import { SSE } from 'sse.js';
+import { useStore } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
import { useSetRecoilState, useRecoilCallback } from 'recoil';
import {
@@ -79,6 +80,7 @@ import {
GENERATION_PROTOCOL_VERSION,
} from '~/data-provider';
import useEventHandlers, { buildCreatedInitialResponse } from './useEventHandlers';
+import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { useAuthContext } from '~/hooks/AuthContext';
import useUsageHandler from './useUsageHandler';
@@ -751,6 +753,7 @@ export default function useResumableSSE(
isAddedRequest = false,
runIndex = 0,
) {
+ const jotaiStore = useStore();
const queryClient = useQueryClient();
const setActiveRunId = useSetRecoilState(store.activeRunFamily(runIndex));
@@ -1291,6 +1294,23 @@ export default function useResumableSSE(
return;
}
const startedAsNewConversation = optimisticStreamIdsRef.current.has(currentStreamId);
+ /** Terminal handlers below are fenced by this subscription and its generation.
+ * Clear every key the same run may have occupied, including the temporary
+ * new-chat key, so aborts and resumes from another tab cannot leave a stale
+ * approval card beside an idle composer. */
+ const clearPendingApprovalForTerminal = (conversationId?: string | null) => {
+ const conversationIds = new Set<string>([
+ currentStreamId,
+ ...(conversationId ? [conversationId] : []),
+ ...(currentSubmission.conversation?.conversationId
+ ? [currentSubmission.conversation.conversationId]
+ : []),
+ ...(startedAsNewConversation ? [String(Constants.NEW_CONVO)] : []),
+ ]);
+ for (const id of conversationIds) {
+ jotaiStore.set(pendingApprovalActionFamily(id), null);
+ }
+ };
const clearAttachedGenerationCreatedAt = () => {
updateActiveGenerationCreatedAt(currentStreamId, null, generationCreatedAt);
if (startedAsNewConversation) {
@@ -1447,6 +1467,11 @@ export default function useResumableSSE(
if (!isCurrentSubscription()) {
return;
}
+ const pendingConversationId =
+ pendingAction.conversationId ??
+ currentSubmission.conversation?.conversationId ??
+ currentStreamId;
+ jotaiStore.set(pendingApprovalActionFamily(pendingConversationId), pendingAction);
const retryNextFrame = () => {
if (attempt < PENDING_ACTION_MAX_RETRY_FRAMES) {
pendingActionRetryRef.current = requestAnimationFrame(() => {
@@ -1972,6 +1997,7 @@ export default function useResumableSSE(
conversationId: data.conversation?.conversationId,
hasResponseMessage: !!data.responseMessage,
});
+ clearPendingApprovalForTerminal(finalConvoId);
clearComposerDrafts(runIndex, currentSubmission.conversation?.conversationId, {
includeNewChatDraft:
!currentSubmission.conversation?.conversationId ||
@@ -2899,6 +2925,7 @@ export default function useResumableSSE(
resetLive({ ...currentSubmission, userMessage });
removeActiveJob(currentStreamId);
clearAttachedGenerationCreatedAt();
+ clearPendingApprovalForTerminal(reconciliationConvoId);
clearComposerDrafts(runIndex, reconciliationConvoId, {
includeNewChatDraft:
!reconciliationConvoId ||
@@ -3170,6 +3197,7 @@ export default function useResumableSSE(
removeActiveJob(currentStreamId);
clearAttachedGenerationCreatedAt();
+ clearPendingApprovalForTerminal(recoveryConvoId);
if (
!createdStreamIdsRef.current.has(currentStreamId) &&
optimisticStreamIdsRef.current.has(currentStreamId)
@@ -3269,6 +3297,7 @@ export default function useResumableSSE(
flushPendingDeltas();
removeActiveJob(currentStreamId);
clearAttachedGenerationCreatedAt();
+ clearPendingApprovalForTerminal(recoveryConvoId);
resetLive({ ...currentSubmission, userMessage });
if (
!createdStreamIdsRef.current.has(currentStreamId) &&
@@ -3598,6 +3627,7 @@ export default function useResumableSSE(
resetLive({ ...currentSubmission, userMessage });
removeActiveJob(currentStreamId);
clearAttachedGenerationCreatedAt();
+ clearPendingApprovalForTerminal(recoveryConvoId);
if (
!createdStreamIdsRef.current.has(currentStreamId) &&
optimisticStreamIdsRef.current.has(currentStreamId)
@@ -3767,6 +3797,7 @@ export default function useResumableSSE(
addActiveJob,
setSubmission,
updateActiveGenerationCreatedAt,
+ jotaiStore,
],
);
diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/client/src/hooks/SSE/useResumeOnLoad.ts
index 6d091daa14..185bfe0e9c 100644
--- a/client/src/hooks/SSE/useResumeOnLoad.ts
+++ b/client/src/hooks/SSE/useResumeOnLoad.ts
@@ -35,6 +35,7 @@ import {
supportsGenerationProtocolV2,
} from '~/data-provider/SSE/protocol';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
+import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import store from '~/store';
@@ -843,6 +844,14 @@ export default function useResumeOnLoad(
return;
}
+ const statusPendingAction =
+ streamStatus.pendingAction ?? streamStatus.resumeState?.pendingAction;
+ if (statusPendingAction != null) {
+ jotaiStore.set(pendingApprovalActionFamily(conversationId), statusPendingAction);
+ } else if (!streamStatus.active) {
+ jotaiStore.set(pendingApprovalActionFamily(conversationId), null);
+ }
+
/** useResumableSSE detected that this conversation-scoped stream now
* belongs to a newer generation. It cleared the stale submission and
* cached the replacement snapshot; allow the same conversation to be
@@ -1026,6 +1035,7 @@ export default function useResumeOnLoad(
settleAppliedSteerParts,
convertSteersToQueued,
setActiveGenerationCreatedAt,
+ jotaiStore,
externalRunArm,
]);
diff --git a/client/src/hooks/SSE/useSSE.ts b/client/src/hooks/SSE/useSSE.ts
index 9e46204530..cd2447e6fa 100644
--- a/client/src/hooks/SSE/useSSE.ts
+++ b/client/src/hooks/SSE/useSSE.ts
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { v4 } from 'uuid';
import { SSE } from 'sse.js';
+import { useStore } from 'jotai';
import { useSetRecoilState } from 'recoil';
import {
request,
@@ -20,6 +21,7 @@ import type {
import type { EventHandlerParams } from './useEventHandlers';
import type { TResData } from '~/common';
import { clearComposerDrafts, applyPendingAction, findPendingActionMessageIndex } from '~/utils';
+import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { useGetStartupConfig, useGetUserBalance } from '~/data-provider';
import { startedAsNewConversation } from './useEventHandlers';
import { useAuthContext } from '~/hooks/AuthContext';
@@ -38,6 +40,7 @@ export default function useSSE(
isAddedRequest = false,
runIndex = 0,
) {
+ const jotaiStore = useStore();
const setActiveRunId = useSetRecoilState(store.activeRunFamily(runIndex));
const { token, isAuthenticated } = useAuthContext();
@@ -158,6 +161,11 @@ export default function useSSE(
* produced — apply any queued delta before reading the cache. */
flushPendingDeltas();
const pendingAction = data.data as Agents.PendingAction;
+ const pendingConversationId =
+ pendingAction.conversationId ?? submission.conversation?.conversationId;
+ if (pendingConversationId) {
+ jotaiStore.set(pendingApprovalActionFamily(pendingConversationId), pendingAction);
+ }
const messages = getMessages() ?? [];
const index = findPendingActionMessageIndex(messages, pendingAction);
if (index >= 0) {
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 5aa6cb4b78..f75da3dd3c 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -4,6 +4,21 @@
"com_ui_code_approval_ask_description": "Ask before editing files or running commands",
"com_ui_code_approval_accept_edits": "Accept edits",
"com_ui_code_approval_accept_edits_description": "Allow file edits; continue asking before commands",
+ "com_ui_review_action": "Review 1 action",
+ "com_ui_review_actions": "Review {{0}} actions",
+ "com_ui_review_run_command": "Run command",
+ "com_ui_review_create_file": "Create {{0}}",
+ "com_ui_review_create_file_generic": "Create file",
+ "com_ui_review_edit_file": "Edit {{0}}",
+ "com_ui_review_edit_file_generic": "Edit file",
+ "com_ui_proposed_command": "Proposed command",
+ "com_ui_proposed_contents": "Proposed contents",
+ "com_ui_proposed_replacements": "Proposed replacements",
+ "com_ui_proposed_arguments": "Proposed arguments",
+ "com_ui_no_arguments": "No arguments provided",
+ "com_ui_preview_truncated": "Preview truncated. Use the timeline tool card to inspect the full proposal.",
+ "com_ui_approval_unavailable": "This action cannot be reviewed because its approval policy is incomplete.",
+ "com_ui_decisions_selected": "{{0}} of {{1}} decisions selected",
"chat_direction_left_to_right": "Left to Right",
"chat_direction_right_to_left": "Right to Left",
"com_a11y_ai_composing": "The AI is still composing.",
diff --git a/e2e/byom/native.spec.ts b/e2e/byom/native.spec.ts
index e24da5f849..12e20c1e67 100644
--- a/e2e/byom/native.spec.ts
+++ b/e2e/byom/native.spec.ts
@@ -183,13 +183,13 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
expect(request.postDataJSON()).toMatchObject({ codeApprovalMode: selectedApprovalMode });
const { conversationId } = (await admitted.json()) as { conversationId: string };
if (decision) {
- const card = page.getByTestId('tool-approval').last();
- await expect(card).toBeVisible({ timeout: 30_000 });
+ const reviewPanel = page.locator('#pending-tool-approval-panel');
+ await expect(reviewPanel).toBeVisible({ timeout: 30_000 });
/** The side effect must not occur before the user has decided. */
if (operation === 'create')
expect(await readdir(selectedWorker.root)).not.toContain('proof.txt');
- await card.getByRole('button', { name: decision, exact: true }).click();
- await card.getByRole('button', { name: 'Submit', exact: true }).click();
+ await reviewPanel.getByRole('button', { name: decision, exact: true }).click();
+ await reviewPanel.getByRole('button', { name: 'Continue', exact: true }).click();
}
let result: Message | undefined;
await expect
diff --git a/e2e/specs/mock/tool-approvals.spec.ts b/e2e/specs/mock/tool-approvals.spec.ts
index f60c78f61e..7702affbe6 100644
--- a/e2e/specs/mock/tool-approvals.spec.ts
+++ b/e2e/specs/mock/tool-approvals.spec.ts
@@ -77,6 +77,14 @@ type ApprovalResumeResponse = {
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 (
@@ -143,6 +151,13 @@ async function startApproval(
const card = approvalCards(page).first();
await expect(card).toBeVisible({ timeout: 30000 });
await expect(card).toContainText(expectedReason);
+ /**
+ * The primary composer review opens automatically above the historical
+ * timeline card. Verify that entry point, then collapse it so these tests
+ * can keep exercising the timeline fallback without an overlay intercepting
+ * its controls. The native BYOM acceptance spec submits through the composer.
+ */
+ await collapseComposerApproval(page);
return card;
}
@@ -495,6 +510,7 @@ test.describe('tool approvals', () => {
// decisions, not just the simpler one-call resume path.
await page.reload({ waitUntil: 'domcontentloaded' });
await expect.poll(() => new URL(page.url()).pathname).toBe(conversationPath);
+ await collapseComposerApproval(page);
await expect(approvalCards(page)).toHaveCount(2);
const firstCard = approvalCard(page, firstCallId);
@@ -610,6 +626,7 @@ test.describe('tool approvals', () => {
await page.reload({ waitUntil: 'domcontentloaded' });
await expect.poll(() => new URL(page.url()).pathname).toBe(conversationPath);
+ await collapseComposerApproval(page);
const rehydratedCard = approvalCard(page, toolCallId);
await expect(rehydratedCard).toBeVisible({ timeout: 30000 });
await expect(rehydratedCard).toContainText(APPROVAL_REASON);
@@ -617,6 +634,7 @@ test.describe('tool approvals', () => {
await page.goto(NEW_CHAT_PATH, { waitUntil: 'domcontentloaded' });
await expect(approvalCards(page)).toHaveCount(0);
await page.goto(conversationPath, { waitUntil: 'domcontentloaded' });
+ await collapseComposerApproval(page);
const navigatedCard = approvalCard(page, toolCallId);
await expect(navigatedCard).toBeVisible({ timeout: 30000 });
await expect(navigatedCard).toContainText(APPROVAL_REASON);
diff --git a/package-lock.json b/package-lock.json
index 1ec4afa851..cff4efab10 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -64,7 +64,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.8.1",
+ "@librechat/agents": "^3.8.2",
"@librechat/api": "*",
"@librechat/data-schemas": "*",
"@microsoft/microsoft-graph-client": "^3.0.7",
@@ -10636,9 +10636,9 @@
}
},
"node_modules/@librechat/agents": {
- "version": "3.8.1",
- "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.8.1.tgz",
- "integrity": "sha512-77V4K6HI9lQsysbBiMqLxvATaZnMG1+EJPAdIVv47YCFSSku47zPSgEfP+sTaoUpDXy14aGGtmA/kCdIsBaLfg==",
+ "version": "3.8.2",
+ "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.8.2.tgz",
+ "integrity": "sha512-F41fY3HZJGpGFB6WCVLgsbMOxNQpxWKgsk13kRHcMJtnhE7DyTu9P78h7/3ruN+UoS8eTtWBNcOGgh2MglC9yw==",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.115.0",
@@ -43645,7 +43645,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.8.1",
+ "@librechat/agents": "^3.8.2",
"@librechat/data-schemas": "*",
"@modelcontextprotocol/sdk": "^1.30.0",
"@opentelemetry/api": "^1.9.0",
diff --git a/packages/api/package.json b/packages/api/package.json
index c575194581..1bd3ee85d0 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -114,7 +114,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "5.1.6",
- "@librechat/agents": "^3.8.1",
+ "@librechat/agents": "^3.8.2",
"@librechat/data-schemas": "*",
"@modelcontextprotocol/sdk": "^1.30.0",
"@opentelemetry/api": "^1.9.0",
diff --git a/packages/api/src/agents/execution.spec.ts b/packages/api/src/agents/execution.spec.ts
index b12f16e932..39aeab7537 100644
--- a/packages/api/src/agents/execution.spec.ts
+++ b/packages/api/src/agents/execution.spec.ts
@@ -2,6 +2,8 @@ import winston from 'winston';
import { Writable } from 'node:stream';
import { logger } from '@librechat/data-schemas';
import {
+ assertCodeExecutionApprovalBinding,
+ captureCodeExecutionApprovalBinding,
codeExecutionAuthHeaders,
codeExecutionHeaders,
resolveCodeExecutionContext,
@@ -321,6 +323,119 @@ describe('resolveCodeExecutionContext', () => {
});
});
+describe('stateful code approval target binding', () => {
+ const context = (overrides: Record<string, unknown> = {}) => ({
+ baseUrl: 'https://bridge.example/v1',
+ codeSessionKey: 'execute_code:stateful:route-a:session-a',
+ executionProfile: 'stateful' as const,
+ executionRouteKey: 'stateful:route-a',
+ runtimeSessionHint: 'v3:environment-a:agent-user:session-a',
+ statefulSessions: true,
+ environmentId: 'environment-a',
+ environmentType: 'attached' as const,
+ bridgeWorkerId: 'worker-a',
+ ...overrides,
+ });
+
+ it('captures only opaque, canonical identities for stateful targets', () => {
+ const binding = captureCodeExecutionApprovalBinding([
+ {
+ id: 'agent-z',
+ codeExecutionContext: context({ bridgeWorkerId: 'worker-z' }),
+ },
+ {
+ id: 'agent-a',
+ codeExecutionContext: context(),
+ },
+ {
+ id: 'stateless',
+ codeExecutionContext: {
+ baseUrl: 'https://default.example/v1',
+ codeSessionKey: 'execute_code',
+ executionProfile: 'default',
+ statefulSessions: false,
+ },
+ },
+ ]);
+
+ expect(binding).toEqual({
+ version: 1,
+ targets: [
+ { agentId: 'agent-a', targetHash: expect.stringMatching(/^[a-f0-9]{64}$/) },
+ { agentId: 'agent-z', targetHash: expect.stringMatching(/^[a-f0-9]{64}$/) },
+ ],
+ });
+ const serialized = JSON.stringify(binding);
+ expect(serialized).not.toContain('bridge.example');
+ expect(serialized).not.toContain('worker-a');
+ expect(serialized).not.toContain('session-a');
+ });
+
+ it('accepts the same targets regardless of traversal order', () => {
+ const first = { id: 'agent-a', codeExecutionContext: context() };
+ const second = {
+ id: 'agent-b',
+ codeExecutionContext: context({ bridgeWorkerId: 'worker-b' }),
+ };
+ const binding = captureCodeExecutionApprovalBinding([first, second]);
+
+ expect(() => assertCodeExecutionApprovalBinding(binding, [second, first])).not.toThrow();
+ });
+
+ it('deduplicates snapshots and orders targets independently of replica locale', () => {
+ const laterByCodeUnit = {
+ id: 'agent-ä',
+ codeExecutionContext: context({ bridgeWorkerId: 'worker-umlaut' }),
+ };
+ const earlierByCodeUnit = {
+ id: 'agent-z',
+ codeExecutionContext: context({ bridgeWorkerId: 'worker-z' }),
+ };
+
+ const binding = captureCodeExecutionApprovalBinding([
+ laterByCodeUnit,
+ earlierByCodeUnit,
+ earlierByCodeUnit,
+ ]);
+
+ expect(binding?.targets.map((target) => target.agentId)).toEqual(['agent-z', 'agent-ä']);
+ });
+
+ it.each([
+ ['route', { executionRouteKey: 'stateful:route-b' }],
+ ['worker', { bridgeWorkerId: 'worker-b' }],
+ ['workspace session', { runtimeSessionHint: 'v3:environment-a:agent-user:session-b' }],
+ ['base URL', { baseUrl: 'https://replacement.example/v1' }],
+ ])('rejects a changed %s before execution', (_label, overrides) => {
+ const binding = captureCodeExecutionApprovalBinding([
+ { id: 'agent-a', codeExecutionContext: context() },
+ ]);
+
+ expect(() =>
+ assertCodeExecutionApprovalBinding(binding, [
+ { id: 'agent-a', codeExecutionContext: context(overrides) },
+ ]),
+ ).toThrow('Retry the request and review the action again');
+ });
+
+ it('fails closed for a malformed persisted binding', () => {
+ expect(() =>
+ assertCodeExecutionApprovalBinding(
+ { version: 1, targets: [{ agentId: 'agent-a', targetHash: 'not-a-hash' }] },
+ [{ id: 'agent-a', codeExecutionContext: context() }],
+ ),
+ ).toThrow('attached code environment changed');
+ });
+
+ it('keeps pre-binding pauses backward compatible', () => {
+ expect(() =>
+ assertCodeExecutionApprovalBinding(undefined, [
+ { id: 'agent-a', codeExecutionContext: context() },
+ ]),
+ ).not.toThrow();
+ });
+});
+
describe('codeExecutionAuthHeaders', () => {
let errorSpy: jest.SpyInstance;
diff --git a/packages/api/src/agents/execution.ts b/packages/api/src/agents/execution.ts
index 5c7c9cadeb..478ba5e5e2 100644
--- a/packages/api/src/agents/execution.ts
+++ b/packages/api/src/agents/execution.ts
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
import { logger } from '@librechat/data-schemas';
import { Constants, getCodeBaseURL } from '@librechat/agents';
import type {
+ Agents,
CodeEnvironmentUserConfigSchema,
CodeEnvironmentUserSettings,
StatefulCodeEnvironment,
@@ -33,6 +34,135 @@ export interface CodeExecutionContext {
codeEnvironmentSettings?: CodeEnvironmentUserSettings;
}
+type CodeExecutionApprovalAgent = {
+ id?: string | null;
+ codeExecutionContext?: CodeExecutionContext | null;
+};
+
+const CODE_EXECUTION_TARGET_HASH = /^[a-f0-9]{64}$/;
+const MAX_CODE_EXECUTION_APPROVAL_TARGETS = 128;
+
+/**
+ * Captures an opaque identity for every stateful code target reachable by a
+ * paused run. Raw base URLs, worker IDs and session hints never enter the
+ * pending-action client projection.
+ */
+export function captureCodeExecutionApprovalBinding(
+ agents: readonly (CodeExecutionApprovalAgent | null | undefined)[],
+): Agents.CodeExecutionApprovalBinding | undefined {
+ const targetsByIdentity = new Map<string, Agents.CodeExecutionApprovalTargetBinding>();
+ for (const agent of agents) {
+ const context = agent?.codeExecutionContext;
+ if (context?.statefulSessions !== true) {
+ continue;
+ }
+ const targetHash = createHash('sha256')
+ .update(
+ JSON.stringify([
+ agent?.id ?? null,
+ context.executionProfile,
+ context.baseUrl,
+ context.codeSessionKey,
+ context.executionRouteKey ?? null,
+ context.runtimeSessionHint ?? null,
+ context.environmentId ?? null,
+ context.environmentType ?? null,
+ context.bridgeWorkerId ?? null,
+ ]),
+ )
+ .digest('hex');
+ const target = { agentId: agent?.id ?? null, targetHash };
+ targetsByIdentity.set(`${target.agentId ?? ''}\u0000${target.targetHash}`, target);
+ }
+ const targets = [...targetsByIdentity.values()];
+ if (targets.length === 0) {
+ return undefined;
+ }
+ /** Relational string comparison is defined over UTF-16 code units. Unlike
+ * localeCompare, this produces the same canonical order on every replica
+ * regardless of its ICU build or process locale. */
+ targets.sort((left, right) => {
+ const leftAgentId = left.agentId ?? '';
+ const rightAgentId = right.agentId ?? '';
+ if (leftAgentId !== rightAgentId) {
+ return leftAgentId < rightAgentId ? -1 : 1;
+ }
+ if (left.targetHash === right.targetHash) {
+ return 0;
+ }
+ return left.targetHash < right.targetHash ? -1 : 1;
+ });
+ return { version: 1, targets };
+}
+
+function isCodeExecutionApprovalBinding(
+ value: unknown,
+): value is Agents.CodeExecutionApprovalBinding {
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
+ return false;
+ }
+ const binding = value as Partial<Agents.CodeExecutionApprovalBinding>;
+ if (
+ binding.version !== 1 ||
+ !Array.isArray(binding.targets) ||
+ binding.targets.length === 0 ||
+ binding.targets.length > MAX_CODE_EXECUTION_APPROVAL_TARGETS
+ ) {
+ return false;
+ }
+ const identities = new Set<string>();
+ for (const target of binding.targets) {
+ if (
+ target == null ||
+ typeof target !== 'object' ||
+ Array.isArray(target) ||
+ !(
+ target.agentId === null ||
+ (typeof target.agentId === 'string' && target.agentId.length <= 256)
+ ) ||
+ typeof target.targetHash !== 'string' ||
+ !CODE_EXECUTION_TARGET_HASH.test(target.targetHash)
+ ) {
+ return false;
+ }
+ const identity = `${target.agentId ?? ''}\u0000${target.targetHash}`;
+ if (identities.has(identity)) {
+ return false;
+ }
+ identities.add(identity);
+ }
+ return true;
+}
+
+export class CodeExecutionApprovalTargetChangedError extends Error {
+ readonly code = 'CODE_EXECUTION_APPROVAL_TARGET_CHANGED';
+
+ constructor() {
+ super(
+ 'The attached code environment changed while this action awaited approval. Retry the request and review the action again before running it.',
+ );
+ this.name = 'CodeExecutionApprovalTargetChangedError';
+ }
+}
+
+/** Backward-compatible for old pauses; present bindings always fail closed. */
+export function assertCodeExecutionApprovalBinding(
+ expected: unknown,
+ agents: readonly (CodeExecutionApprovalAgent | null | undefined)[],
+): void {
+ if (expected == null) {
+ return;
+ }
+ const current = captureCodeExecutionApprovalBinding(agents);
+ if (
+ !isCodeExecutionApprovalBinding(expected) ||
+ current == null ||
+ JSON.stringify(expected.targets) !== JSON.stringify(current.targets)
+ ) {
+ throw new CodeExecutionApprovalTargetChangedError();
+ }
+}
+
export function createCodeExecutionRouteKey(
profile: CodeExecutionProfile,
environment?: Pick<CodeEnvironmentConfig, 'id' | 'baseURL' | 'workerId' | 'pairing'>,
diff --git a/packages/api/src/agents/hitl/byom.spec.ts b/packages/api/src/agents/hitl/byom.spec.ts
index 36927d46a2..31e52cc60d 100644
--- a/packages/api/src/agents/hitl/byom.spec.ts
+++ b/packages/api/src/agents/hitl/byom.spec.ts
@@ -5,12 +5,75 @@ import {
collectAttachedCodeEnvironmentAgentIds,
collectAttachedCodeEnvironmentPolicySettings,
createAttachedCodeEnvironmentPolicyHook,
+ isStatefulCodeEnvironmentToolName,
+ markNativeCodeToolApprovalRequests,
resolveAttachedCodeApprovalMode,
} from './byom';
import { canAgentGraphPause } from './admission';
const signal = new AbortController().signal;
+test('identifies every built-in tool that can touch a stateful code target', () => {
+ for (const toolName of [
+ 'read_file',
+ 'write_file',
+ 'edit_file',
+ 'create_file',
+ 'bash_tool',
+ 'execute_code',
+ 'search_workspace',
+ 'list_workspace_files',
+ ]) {
+ expect(isStatefulCodeEnvironmentToolName(toolName)).toBe(true);
+ }
+ expect(isStatefulCodeEnvironmentToolName('mcp__github__create_issue')).toBe(false);
+});
+
+describe('markNativeCodeToolApprovalRequests', () => {
+ const payload = {
+ type: 'tool_approval' as const,
+ action_requests: [
+ { name: 'create_file', arguments: { path: 'one.ts' }, tool_call_id: 'call-1' },
+ ],
+ review_configs: [
+ {
+ action_name: 'create_file',
+ tool_call_id: 'call-1',
+ allowed_decisions: ['approve' as const],
+ },
+ ],
+ };
+
+ test('marks a server-registered native code tool', () => {
+ expect(
+ markNativeCodeToolApprovalRequests(payload, [
+ { toolDefinitions: [{ name: 'create_file', toolType: 'builtin' }] },
+ ]).action_requests[0],
+ ).toMatchObject({ source: 'librechat_code' });
+ });
+
+ test('keeps a same-name user tool generic and strips a forged source', () => {
+ const forged = {
+ ...payload,
+ action_requests: [{ ...payload.action_requests[0], source: 'librechat_code' as const }],
+ };
+ expect(
+ markNativeCodeToolApprovalRequests(forged, [
+ { toolDefinitions: [{ name: 'create_file', toolType: 'action' }] },
+ ]).action_requests[0],
+ ).not.toHaveProperty('source');
+ });
+
+ test('falls back to generic when reachable agents expose conflicting definitions', () => {
+ expect(
+ markNativeCodeToolApprovalRequests(payload, [
+ { toolDefinitions: [{ name: 'create_file', toolType: 'builtin' }] },
+ { toolRegistry: new Map([['create_file', { name: 'create_file', toolType: 'mcp' }]]) },
+ ]).action_requests[0],
+ ).not.toHaveProperty('source');
+ });
+});
+
describe('createAttachedCodeEnvironmentPolicyHook', () => {
test('asks before a shell action in an attached environment', async () => {
const hook = createAttachedCodeEnvironmentPolicyHook(new Set(['attached-agent']));
diff --git a/packages/api/src/agents/hitl/byom.ts b/packages/api/src/agents/hitl/byom.ts
index e8adf90da8..dd0bab3a6b 100644
--- a/packages/api/src/agents/hitl/byom.ts
+++ b/packages/api/src/agents/hitl/byom.ts
@@ -6,6 +6,7 @@ import {
resolveCodePermissionDecision,
} from 'librechat-data-provider';
import type {
+ Agents,
CodeApprovalMode,
CodeEnvironmentPermissionDecision,
CodeEnvironmentUserConfigSchema,
@@ -13,7 +14,12 @@ import type {
} from 'librechat-data-provider';
import type { HookCallback } from '@librechat/agents';
import type { ResolvedToolApprovalHook } from './hooks';
-import { CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME } from '~/agents/tools';
+import {
+ CREATE_FILE_TOOL_NAME,
+ EDIT_FILE_TOOL_NAME,
+ FILE_AUTHORING_TOOL_NAMES,
+ isCodeSessionToolName,
+} from '~/agents/tools';
import { isSkillFilePath } from '~/agents/skills';
const BYOM_FILE_WRITE_TOOLS = new Set<string>([
@@ -31,6 +37,16 @@ const BYOM_COMMAND_EXECUTION_TOOLS = new Set<string>([
Constants.COMPILE_CHECK,
]);
+/** Exact built-in tool names whose execution can touch a stateful code target. */
+export function isStatefulCodeEnvironmentToolName(name: string): boolean {
+ return (
+ name === Constants.READ_FILE ||
+ BYOM_FILE_WRITE_TOOLS.has(name) ||
+ BYOM_COMMAND_EXECUTION_TOOLS.has(name) ||
+ isCodeSessionToolName(name, FILE_AUTHORING_TOOL_NAMES)
+ );
+}
+
export type AttachedCodeEnvironmentPolicySettings = {
configSchema?: CodeEnvironmentUserConfigSchema;
settings?: CodeEnvironmentUserSettings;
@@ -42,6 +58,8 @@ type PermissionCategory = 'fileWrite' | 'commandExecution';
type CodeEnvironmentPolicyAgent = {
id?: string;
skillAuthoringAvailable?: boolean;
+ toolDefinitions?: readonly { name?: string; toolType?: string }[];
+ toolRegistry?: ReadonlyMap<string, { name?: string; toolType?: string }>;
codeExecutionContext?: {
environmentType?: string;
codeEnvironmentConfigSchema?: CodeEnvironmentUserConfigSchema;
@@ -78,6 +96,47 @@ function collectCodeEnvironmentPolicyAgents(
return agents;
}
+/**
+ * Mark code-specific approval previews only when the initialized server tool
+ * graph proves the effective name belongs exclusively to LibreChat's native
+ * code tools. A same-name user/MCP/action definition makes the name ambiguous
+ * and deliberately falls back to the generic argument preview.
+ */
+export function markNativeCodeToolApprovalRequests(
+ payload: Agents.ToolApprovalInterruptPayload,
+ roots: readonly (CodeEnvironmentPolicyAgent | null | undefined)[],
+): Agents.ToolApprovalInterruptPayload {
+ const provenance = new Map<string, { native: boolean; conflicting: boolean }>();
+ for (const agent of collectCodeEnvironmentPolicyAgents(roots)) {
+ const definitions = [...(agent.toolDefinitions ?? []), ...(agent.toolRegistry?.values() ?? [])];
+ for (const definition of definitions) {
+ const name = definition.name;
+ if (typeof name !== 'string' || !isStatefulCodeEnvironmentToolName(name)) {
+ continue;
+ }
+ const current = provenance.get(name) ?? { native: false, conflicting: false };
+ if (definition.toolType === 'builtin') {
+ current.native = true;
+ } else {
+ current.conflicting = true;
+ }
+ provenance.set(name, current);
+ }
+ }
+ return {
+ ...payload,
+ action_requests: payload.action_requests.map((request) => {
+ const source = provenance.get(request.name);
+ if (source?.native !== true || source.conflicting) {
+ const genericRequest = { ...request };
+ delete genericRequest.source;
+ return genericRequest;
+ }
+ return { ...request, source: 'librechat_code' };
+ }),
+ };
+}
+
export class AttachedCodeEnvironmentApprovalError extends Error {
readonly code = 'BYOM_TOOL_APPROVAL_UNSUPPORTED';
diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.ts
index f05be9fa1f..50ee848763 100644
--- a/packages/api/src/agents/hitl/policy.spec.ts
+++ b/packages/api/src/agents/hitl/policy.spec.ts
@@ -383,18 +383,27 @@ describe('toClientPendingAction', () => {
endpoint: 'agents',
model_parameters: { temperature: 0.5 },
},
+ codeExecutionBinding: {
+ version: 1,
+ targets: [{ agentId: 'agent-1', targetHash: 'a'.repeat(64) }],
+ },
});
const clientSafe = toClientPendingAction(full);
expect(clientSafe).toBeDefined();
expect(clientSafe?.resumeContext).toBeUndefined();
expect(clientSafe?.requestFingerprint).toBeUndefined();
+ expect(clientSafe?.codeExecutionBinding).toBeUndefined();
expect(clientSafe?.actionId).toBe(full.actionId);
expect(clientSafe?.streamId).toBe('stream-1');
expect(clientSafe?.payload).toBe(full.payload);
// Non-mutating: the stored record keeps its replay state for the resume route.
expect(full.resumeContext).toBeDefined();
expect(full.requestFingerprint).toBe('fp-hash');
+ expect(full.codeExecutionBinding).toEqual({
+ version: 1,
+ targets: [{ agentId: 'agent-1', targetHash: 'a'.repeat(64) }],
+ });
});
test('passes through nullish input', () => {
diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.ts
index 371e7441b2..1647a6a7d3 100644
--- a/packages/api/src/agents/hitl/policy.ts
+++ b/packages/api/src/agents/hitl/policy.ts
@@ -346,6 +346,8 @@ export interface PendingActionContext {
requestFingerprint?: string;
/** Graph-determining fields to replay on resume; see {@link RESUME_CONTEXT_KEYS}. */
resumeContext?: Record<string, unknown>;
+ /** Opaque server-only binding to the stateful code targets selected at pause time. */
+ codeExecutionBinding?: Agents.CodeExecutionApprovalBinding;
}
/** Request fields that decide which agent/graph + tool set a turn runs. */
@@ -782,11 +784,13 @@ export function buildPendingAction(
threadId: ctx.threadId,
requestFingerprint: ctx.requestFingerprint,
resumeContext: ctx.resumeContext,
+ codeExecutionBinding: ctx.codeExecutionBinding,
};
}
/**
- * Client-facing projection of a pending action. `requestFingerprint` and `resumeContext`
+ * Client-facing projection of a pending action. `requestFingerprint`, `resumeContext`, and
+ * `codeExecutionBinding`
* are server-only replay state — `resumeContext` in particular carries the resolved
* model parameters — so every copy that leaves the server (SSE, status, resume state)
* must go through this. The full record stays in the job store for the resume route.
@@ -800,6 +804,7 @@ export function toClientPendingAction(
const {
requestFingerprint: _requestFingerprint,
resumeContext: _resumeContext,
+ codeExecutionBinding: _codeExecutionBinding,
...clientSafe
} = pendingAction;
return clientSafe;
diff --git a/packages/api/src/agents/tools.ts b/packages/api/src/agents/tools.ts
index 75b8bc0047..ec3392fe32 100644
--- a/packages/api/src/agents/tools.ts
+++ b/packages/api/src/agents/tools.ts
@@ -417,6 +417,7 @@ Also accepts authored skill file paths using "skills/{skillName}/...", including
const READ_FILE_DEF: LCTool = Object.freeze({
name: ReadFileToolDefinition.name,
+ toolType: 'builtin',
description: SKILL_READ_FILE_DESCRIPTION,
parameters: ReadFileToolDefinition.parameters as unknown as LCTool['parameters'],
responseFormat: ReadFileToolDefinition.responseFormat,
@@ -465,6 +466,7 @@ const ATTACHED_WORKSPACE_READ_FILE_PARAMETERS: LCTool['parameters'] = Object.fre
const CODE_READ_FILE_DEF: LCTool = Object.freeze({
name: ReadFileToolDefinition.name,
+ toolType: 'builtin',
description: CODE_READ_FILE_DESCRIPTION,
parameters: CODE_READ_FILE_PARAMETERS,
responseFormat: ReadFileToolDefinition.responseFormat,
@@ -476,6 +478,7 @@ function createAttachedWorkspaceReadFileDef(includeSkillFileInstructions: boolea
: CODE_READ_FILE_DESCRIPTION;
return Object.freeze({
name: ReadFileToolDefinition.name,
+ toolType: 'builtin',
description: `${baseDescription}\n\n${ATTACHED_WORKSPACE_READ_FILE_INSTRUCTIONS}`,
parameters: ATTACHED_WORKSPACE_READ_FILE_PARAMETERS,
responseFormat: ReadFileToolDefinition.responseFormat,
@@ -487,6 +490,7 @@ const ATTACHED_SKILL_READ_FILE_DEF = createAttachedWorkspaceReadFileDef(true);
const SEARCH_WORKSPACE_TOOL_DEF: LCTool = Object.freeze({
name: SEARCH_WORKSPACE_TOOL_NAME,
+ toolType: 'builtin',
description:
'Search for literal text within the attached worker workspace directory. Git is not required. Respects normal ignore files, does not follow symlinks, and returns bounded path, line, column, and text matches. Use path to limit the search to a relative file or directory.',
parameters: Object.freeze({
@@ -514,6 +518,7 @@ const SEARCH_WORKSPACE_TOOL_DEF: LCTool = Object.freeze({
const LIST_WORKSPACE_FILES_TOOL_DEF: LCTool = Object.freeze({
name: LIST_WORKSPACE_FILES_TOOL_NAME,
+ toolType: 'builtin',
description:
'List relative file paths in the attached worker workspace directory. Use this to discover files in an existing project, Git repository, or empty directory before reading or searching them. Respects normal ignore files, does not follow symlinks, and returns a bounded deterministic listing. When a result supplies an after_path continuation, pass it unchanged with the same path to fetch the next page.',
parameters: Object.freeze({
@@ -685,6 +690,7 @@ Targets code-execution sandbox paths, such as /mnt/data/result.txt.`;
const SKILL_CREATE_FILE_DEF: LCTool = Object.freeze({
name: CREATE_FILE_TOOL_NAME,
+ toolType: 'builtin',
description: SKILL_CREATE_FILE_DESCRIPTION,
parameters: SKILL_CREATE_FILE_PARAMETERS,
responseFormat: 'content_and_artifact' as LCTool['responseFormat'],
@@ -692,6 +698,7 @@ const SKILL_CREATE_FILE_DEF: LCTool = Object.freeze({
const CODE_CREATE_FILE_DEF: LCTool = Object.freeze({
name: CREATE_FILE_TOOL_NAME,
+ toolType: 'builtin',
description: CODE_CREATE_FILE_DESCRIPTION,
parameters: CODE_CREATE_FILE_PARAMETERS,
responseFormat: 'content_and_artifact' as LCTool['responseFormat'],
@@ -699,6 +706,7 @@ const CODE_CREATE_FILE_DEF: LCTool = Object.freeze({
const SKILL_EDIT_FILE_DEF: LCTool = Object.freeze({
name: EDIT_FILE_TOOL_NAME,
+ toolType: 'builtin',
description: SKILL_EDIT_FILE_DESCRIPTION,
parameters: SKILL_EDIT_FILE_PARAMETERS,
responseFormat: 'content_and_artifact' as LCTool['responseFormat'],
@@ -706,6 +714,7 @@ const SKILL_EDIT_FILE_DEF: LCTool = Object.freeze({
const CODE_EDIT_FILE_DEF: LCTool = Object.freeze({
name: EDIT_FILE_TOOL_NAME,
+ toolType: 'builtin',
description: CODE_EDIT_FILE_DESCRIPTION,
parameters: CODE_EDIT_FILE_PARAMETERS,
responseFormat: 'content_and_artifact' as LCTool['responseFormat'],
@@ -864,6 +873,7 @@ function createBashToolDef(
const descriptionOpts = { enableToolOutputReferences, statefulSessions };
return Object.freeze({
name: BashExecutionToolDefinition.name,
+ toolType: 'builtin',
description: workspaceTools
? buildAttachedWorkspaceBashDescription(enableToolOutputReferences)
: buildBashExecutionToolDescription(descriptionOpts),
diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts
index ec05724999..cfa7e101bf 100644
--- a/packages/data-provider/src/types/agents.ts
+++ b/packages/data-provider/src/types/agents.ts
@@ -420,6 +420,8 @@ export namespace Agents {
tool_call_id: string;
/** Optional human-readable description shown alongside the prompt */
description?: string;
+ /** Server-authored provenance. Absent for user, MCP, action, and older tool calls. */
+ source?: 'librechat_code';
}
/**
@@ -540,6 +542,24 @@ export namespace Agents {
* no longer reconstruct the ephemeral config — still rebuilds the same agent/graph.
*/
resumeContext?: Record<string, unknown>;
+ /**
+ * Opaque, server-only identity of the stateful code targets selected when a
+ * tool approval paused. Resume rejects a changed target before provider or
+ * tool execution so an approval cannot migrate to another VM or workspace.
+ */
+ codeExecutionBinding?: CodeExecutionApprovalBinding;
+ }
+
+ export interface CodeExecutionApprovalTargetBinding {
+ /** Agent identity when available; anonymous ephemeral agents use null. */
+ agentId: string | null;
+ /** SHA-256 of the resolved route, worker and runtime-session identity. */
+ targetHash: string;
+ }
+
+ export interface CodeExecutionApprovalBinding {
+ version: 1;
+ targets: CodeExecutionApprovalTargetBinding[];
}
/**