🛂 refactor: Move the Tool Approval Review Into @librechat/chat (#18133)

- refactor: Move Tool Approval Review into the Chat Package
- refactor: Tag the Response Review Tool Batch Spec as a Scenario
- fix: Resume the Composer Review Panel Through the App Host
This commit is contained in:
Marco Beretta 2026-11-14 16:13:03 +01:00 • committed by GitHub
parent 393328f93c
commit 712edc08fe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 2081 additions and 1345 deletions

View file

@ -1,581 +1,98 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useContext, useMemo, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { Constants } from 'librechat-data-provider';
import { useAtom, useStore, useAtomValue } from 'jotai';
import { resolveAskUserQuestionPart } from '@librechat/chat';
import {
askSubmitStatusAtom,
pendingApprovalActionFamily,
activeGenerationCreatedAtByConvoId,
} from '@librechat/chat/react';
import type { AskAnswerStatus } from '@librechat/chat/react';
import type { Agents } from 'librechat-data-provider';
import {
useSubmitToolApprovalMutation,
useSubmitAskAnswerMutation,
type ResumeAgentFields,
} from '~/data-provider';
import { activeGenerationCreatedAtByConvoId } from '@librechat/chat/react';
import { useResumeSubmit as resumeWithHost } from '@librechat/chat/components';
import type { ApprovalResumeHost } from '@librechat/chat/react';
import { useSubmitAskAnswerMutation, useSubmitToolApprovalMutation } from '~/data-provider';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import { ChatContext } from '~/Providers/ChatContext';
export interface ResumeSubmitTransport {
submitToolApproval: (
actionId: string,
decisions: Agents.ToolApprovalResolution[],
) => Promise<void>;
submitAskAnswer: (actionId: string, resolution: string | Record<string, string>) => Promise<void>;
}
/** Host-owned I/O; the shared hook owns selected payloads, submission locks and status. */
export const ResumeSubmitContext = createContext<ResumeSubmitTransport | null>(null);
/** Shared read/write for the ask-answer submit status. */
export function useAskSubmitStatus(): {
getAskStatus: (actionId: string) => AskAnswerStatus;
setAskStatus: (actionId: string, status: AskAnswerStatus) => void;
} {
const [statusMap, setStatusMap] = useAtom(askSubmitStatusAtom);
const getAskStatus = useCallback(
(actionId: string): AskAnswerStatus => statusMap[actionId] ?? 'idle',
[statusMap],
);
const setAskStatus = useCallback(
(actionId: string, status: AskAnswerStatus) =>
setStatusMap((prev) => ({ ...prev, [actionId]: status })),
[setStatusMap],
);
return { getAskStatus, setAskStatus };
}
interface ApprovalContextValue {
/**
* Bumped whenever registrations or decisions change. Decisions live in refs
* (synchronous reads), so this is what makes the context value a NEW reference
* on each change; without it, consumers never re-render and never re-read
* `isReady`/`getLeadToolCallId` after an update.
*/
version: number;
/** Record (or clear) a card's decision for its tool_call within an action. */
setDecision: (
actionId: string,
toolCallId: string,
decision: Agents.ToolApprovalResolution | null,
) => 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. */
registerToolCall: (actionId: string, toolCallId: string) => void;
/** Drop a tool_call's registration when its card unmounts, so a resolved/removed
* card can't keep `isReady` false and wedge the batch submit. */
unregisterToolCall: (actionId: string, toolCallId: string) => void;
/** The first-registered tool_call for an action — the single card that owns
* the batch submit button (avoids N buttons across sibling cards). */
getLeadToolCallId: (actionId: string) => string | undefined;
/** Number of tool calls paused under an action (for a "1 of N" label). */
getRegisteredCount: (actionId: string) => number;
/** True once every registered tool_call in the action has a decision. */
isReady: (actionId: string) => boolean;
/** Lifecycle status for an action (so cards can disable / show messages). */
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. */
setAskAnswerDraft: (actionId: string, answer: string) => void;
}
const ApprovalContext = createContext<ApprovalContextValue | null>(null);
export interface ToolApprovalDecisionDraft {
active: Agents.ToolApprovalDecisionType | null;
/** With `active === 'approve'`: also approve this tool for the rest of the conversation. */
allowAlways?: boolean;
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 => {
const ctx = useContext(ApprovalContext);
return ctx ?? FALLBACK;
};
const FALLBACK: ApprovalContextValue = {
version: 0,
setDecision: () => undefined,
getDecision: () => undefined,
getDecisionDraft: () => undefined,
setDecisionDraft: () => undefined,
getDecisions: () => [],
registerToolCall: () => undefined,
unregisterToolCall: () => undefined,
getLeadToolCallId: () => undefined,
getRegisteredCount: () => 0,
isReady: () => false,
getStatus: () => 'idle',
setStatus: () => undefined,
beginToolSubmission: () => false,
endToolSubmission: () => undefined,
getAskAnswerDraft: () => '',
setAskAnswerDraft: () => undefined,
};
const isExpiredError = (error: unknown): boolean => {
const status = (error as { response?: { status?: number } } | undefined)?.response?.status;
return status === 409;
};
export {
ApprovalProvider as default,
ResumeSubmitContext,
useApprovalContext,
useAskSubmitStatus,
} from '@librechat/chat/components';
export type { ResumeSubmitTransport, ToolApprovalDecisionDraft } from '@librechat/chat/components';
/**
* Coordinates human-in-the-loop decisions for a single response message.
*
* An action may pause multiple tool calls (same `actionId`); each `ToolApproval`
* card registers its `tool_call_id` and records a decision here, and the lead card
* submits ONCE with the full `decisions[]` covering every paused call (the server
* rejects a partial batch).
*
* Intentionally PURE state — it does NOT read `ChatContext`, the agent store, or
* React Query. Message content renders in places without those providers (shared /
* exported views, tests), so the provider must be safe to mount anywhere. The
* context-dependent submit lives in {@link useResumeSubmit}, which the cards call —
* which chooses the ordinary chat transport or an explicitly supplied host transport.
* The app's resume adapter: conversation fields, ephemeral agent settings, and the
* mutations that send a tool decision or an ask answer. The package hook owns the lock
* and the status. Built here, not in the provider, so the composer can resume outside
* `ApprovalProvider`. Package components that submit on their own (the composer review
* panel) read it from `ApprovalResumeHostProvider`, so the app wraps them with this host.
*/
export default function ApprovalProvider({
children,
pendingAction,
}: {
children: React.ReactNode;
pendingAction?: Pick<Agents.PendingAction, 'actionId' | 'payload'> | 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?: Pick<Agents.PendingAction, 'actionId' | 'payload'> | 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 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 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();
},
[rerender],
);
const unregisterToolCall = useCallback(
(actionId: string, toolCallId: string) => {
const counts = registeredRef.current.get(actionId);
const count = counts?.get(toolCallId);
if (!counts || count == null) {
return;
}
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
* phase label can resolve while an approval card is visible, moving
* that card through a nested phase segment; its transient unmount must
* not erase the user's selection. Unregistered decisions are excluded
* from submit/readiness and disappear with this provider. */
rerender();
},
[rerender],
);
const getLeadToolCallId = useCallback(
(actionId: string) =>
authoritativeRef.current.get(actionId)?.[0] ??
registeredRef.current.get(actionId)?.keys().next().value,
[],
);
const getRegisteredCount = useCallback(
(actionId: string) =>
authoritativeRef.current.get(actionId)?.length ??
registeredRef.current.get(actionId)?.size ??
0,
[],
);
const setDecision = useCallback(
(actionId: string, toolCallId: string, decision: Agents.ToolApprovalResolution | null) => {
const map = decisionsRef.current.get(actionId) ?? new Map();
if (decision == null) {
map.delete(toolCallId);
} else {
map.set(toolCallId, decision);
}
decisionsRef.current.set(actionId, map);
rerender();
},
[rerender],
);
const getDecision = useCallback(
(actionId: string, toolCallId: string) => decisionsRef.current.get(actionId)?.get(toolCallId),
[],
);
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 required = authoritativeRef.current.get(actionId) ?? [
...(registeredRef.current.get(actionId)?.keys() ?? []),
];
const decisions = decisionsRef.current.get(actionId);
if (required.length === 0 || decisions == null) {
return [];
}
return required.flatMap((toolCallId) => {
const decision = decisions.get(toolCallId);
return decision == null ? [] : [decision];
});
}, []);
const isReady = useCallback((actionId: string) => {
const required = authoritativeRef.current.get(actionId) ?? [
...(registeredRef.current.get(actionId)?.keys() ?? []),
];
const decided = decisionsRef.current.get(actionId);
if (required.length === 0) {
return false;
}
for (const toolCallId of required) {
if (!decided?.has(toolCallId)) {
return false;
}
}
return true;
}, []);
const getStatus = useCallback(
(actionId: string): AskAnswerStatus => statusByAction[actionId] ?? 'idle',
[statusByAction],
);
const setStatus = useCallback((actionId: string, status: AskAnswerStatus) => {
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) ?? '',
[],
);
const setAskAnswerDraft = useCallback((actionId: string, answer: string) => {
if (answer.length === 0) {
askAnswerDraftsRef.current.delete(actionId);
return;
}
askAnswerDraftsRef.current.set(actionId, answer);
}, []);
const value = useMemo<ApprovalContextValue>(
() => ({
version,
setDecision,
getDecision,
getDecisionDraft,
setDecisionDraft,
getDecisions,
registerToolCall,
unregisterToolCall,
getLeadToolCallId,
getRegisteredCount,
isReady,
getStatus,
setStatus,
beginToolSubmission,
endToolSubmission,
getAskAnswerDraft,
setAskAnswerDraft,
}),
[
version,
setDecision,
getDecision,
getDecisionDraft,
setDecisionDraft,
getDecisions,
registerToolCall,
unregisterToolCall,
getLeadToolCallId,
getRegisteredCount,
isReady,
getStatus,
setStatus,
beginToolSubmission,
endToolSubmission,
getAskAnswerDraft,
setAskAnswerDraft,
],
);
return <ApprovalContext.Provider value={value}>{children}</ApprovalContext.Provider>;
}
/** A host may reject asynchronously or throw before returning its request promise. */
function submitHost(
submit: () => Promise<void>,
callbacks: { onSuccess: () => void; onError: (error: unknown) => void },
): void {
try {
void submit().then(callbacks.onSuccess, callbacks.onError);
} catch (error) {
callbacks.onError(error);
}
}
/**
* Submit hook for the approval cards. Sources the resume body's agent/endpoint
* fields from the active conversation (so the route's shared `buildEndpointOption`
* middleware reconstructs the same agent) and fires the resume mutation, threading
* the result back into the action's status.
*
* Reads `ChatContext` / the agent store / React Query. The cards render it from
* live chat views but ALSO from contexts without a `ChatContext.Provider` (e.g. a
* subagent tool paused inside an isolated activity surface, or a search/citation render that
* passes chat context as a prop), so it reads the context non-throwingly: with no
* conversation, the ordinary transport stays inert. An explicit host supplies only
* I/O; payload readiness, synchronous locks and submission status stay shared.
*/
export function useResumeSubmit() {
const transport = useContext(ResumeSubmitContext);
const jotaiStore = useStore();
export function useChatApprovalHost(): ApprovalResumeHost {
const chatContext = useContext(ChatContext);
const conversation = chatContext?.conversation;
const { getEphemeralAgent } = useChatSettings();
const approvalMutation = useSubmitToolApprovalMutation();
const askMutation = useSubmitAskAnswerMutation();
const { getDecisions, isReady, setStatus, beginToolSubmission, endToolSubmission } =
useApprovalContext();
/** Ask status lives in Jotai so it works from the composer (outside the
* provider); tool-approval status stays on the context. */
const { setAskStatus } = useAskSubmitStatus();
const conversationId = chatContext?.conversation?.conversationId ?? Constants.NEW_CONVO;
const activeGenerationCreatedAt = useAtomValue(
activeGenerationCreatedAtByConvoId(conversation?.conversationId ?? Constants.NEW_CONVO),
activeGenerationCreatedAtByConvoId(conversationId),
);
const latest = useRef({
chatContext,
getEphemeralAgent,
approvalMutation,
askMutation,
activeGenerationCreatedAt,
});
latest.current = {
chatContext,
getEphemeralAgent,
approvalMutation,
askMutation,
activeGenerationCreatedAt,
};
const buildResumeFields = useCallback((): ResumeAgentFields | null => {
const conversationId = conversation?.conversationId;
if (!conversationId || conversationId === Constants.NEW_CONVO) {
return null;
}
return {
conversationId,
/** Sent as a replacement fence when known. Without it the server still
* resolves the action against its own job and rejects a stale actionId. */
...(activeGenerationCreatedAt != null && { generationCreatedAt: activeGenerationCreatedAt }),
endpoint: conversation?.endpoint,
endpointType: conversation?.endpointType,
agent_id: conversation?.agent_id,
model: conversation?.model,
spec: conversation?.spec,
// Ephemeral agents derive their instructions from promptPrefix — re-send it so
// the resumed run rebuilds the same graph and matches the server fingerprint.
promptPrefix: conversation?.promptPrefix,
ephemeralAgent: getEphemeralAgent(conversationId),
};
}, [conversation, getEphemeralAgent, activeGenerationCreatedAt]);
const submitToolApproval = useCallback(
(actionId: string) => {
const fields = transport ? null : buildResumeFields();
const decisions = getDecisions(actionId);
if ((!transport && !fields) || decisions.length === 0 || !isReady(actionId)) return;
if (!beginToolSubmission(actionId)) return;
setStatus(actionId, 'submitting');
const callbacks = {
onSuccess: () => {
setStatus(actionId, 'submitted');
if (!fields) return;
const pendingAtom = pendingApprovalActionFamily(fields.conversationId);
if (jotaiStore.get(pendingAtom)?.actionId === actionId) jotaiStore.set(pendingAtom, null);
},
onError: (error: unknown) => {
const expired = isExpiredError(error);
if (!expired) endToolSubmission(actionId);
setStatus(actionId, expired ? 'expired' : 'error');
},
};
if (transport) {
submitHost(() => transport.submitToolApproval(actionId, decisions), callbacks);
} else if (fields) {
approvalMutation.mutate({ ...fields, actionId, decisions }, callbacks);
}
},
[
approvalMutation,
beginToolSubmission,
buildResumeFields,
endToolSubmission,
getDecisions,
isReady,
jotaiStore,
setStatus,
transport,
],
return useMemo<ApprovalResumeHost>(
() => ({
readFields: () => {
const current = latest.current;
const conversation = current.chatContext?.conversation;
const id = conversation?.conversationId;
if (!id || id === Constants.NEW_CONVO) {
return null;
}
return {
conversationId: id,
...(current.activeGenerationCreatedAt != null && {
generationCreatedAt: current.activeGenerationCreatedAt,
}),
endpoint: conversation.endpoint,
endpointType: conversation.endpointType,
agent_id: conversation.agent_id,
model: conversation.model,
spec: conversation.spec,
// Ephemeral agents derive their instructions from promptPrefix. Re-send it so
// the resumed run rebuilds the same graph and matches the server fingerprint.
promptPrefix: conversation.promptPrefix,
ephemeralAgent: current.getEphemeralAgent(id),
};
},
submitToolApproval: (body, callbacks) => {
latest.current.approvalMutation.mutate(body, callbacks);
},
submitAskAnswer: (body, callbacks) => {
latest.current.askMutation.mutate(body, callbacks);
},
readMessages: () => {
const chat = latest.current.chatContext;
const messages = chat?.getMessages?.();
if (chat == null || messages == null || chat.setMessages == null) {
return null;
}
return { messages, setMessages: chat.setMessages };
},
}),
[],
);
const submitAskAnswer = useCallback(
(
actionId: string,
resolution: string | Record<string, string>,
opts?: { onSuccess?: () => void },
) => {
const fields = transport ? null : buildResumeFields();
const isBatch = typeof resolution !== 'string';
const hasAnswer = isBatch ? Object.keys(resolution).length > 0 : resolution.length > 0;
if ((!transport && !fields) || !hasAnswer) return;
// Read the shared Jotai store synchronously: two rendered surfaces must
// not both enter before React publishes their next render.
const status = jotaiStore.get(askSubmitStatusAtom)[actionId];
if (status === 'submitting' || status === 'submitted' || status === 'expired') return;
setAskStatus(actionId, 'submitting');
const callbacks = {
onSuccess: () => {
setAskStatus(actionId, 'submitted');
if (!transport) {
// Only the ordinary chat transport owns synthetic timeline question parts.
const messages = chatContext?.getMessages?.();
if (messages && chatContext?.setMessages) {
let changed = false;
const next = messages.map((message) => {
const resolved = resolveAskUserQuestionPart(message, actionId, resolution);
if (resolved !== message) changed = true;
return resolved;
});
if (changed) chatContext.setMessages(next);
}
}
// A failed request must retain the caller's only copy of the answer.
opts?.onSuccess?.();
},
onError: (error: unknown) => {
setAskStatus(actionId, isExpiredError(error) ? 'expired' : 'error');
},
};
if (transport) {
submitHost(() => transport.submitAskAnswer(actionId, resolution), callbacks);
} else if (fields) {
askMutation.mutate(
{ ...fields, actionId, ...(isBatch ? { answers: resolution } : { answer: resolution }) },
callbacks,
);
}
},
[askMutation, buildResumeFields, setAskStatus, chatContext, jotaiStore, transport],
);
return { submitToolApproval, submitAskAnswer };
}
/** App resume hook. The package owns readiness, locks and status; this supplies the host. */
export function useResumeSubmit() {
const host = useChatApprovalHost();
return resumeWithHost(host);
}

View file

@ -1,5 +1,4 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { act, renderHook } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { activeGenerationCreatedAtByConvoId } from '@librechat/chat/react';
@ -7,29 +6,32 @@ import type { ResumeSubmitTransport } from '../ApprovalContext';
import ApprovalProvider, {
ResumeSubmitContext,
useApprovalContext,
useAskSubmitStatus,
useResumeSubmit,
} from '../ApprovalContext';
import { ChatSettingsContext, defaultChatSettings } from '~/Providers/ChatSettingsContext';
import { ChatContext } from '~/Providers/ChatContext';
const mockApprovalMutate = jest.fn();
const mockAskMutate = jest.fn();
const getEphemeralAgent = jest.fn(() => ({ mcp: ['server'] }));
jest.mock('~/data-provider', () => ({
useSubmitToolApprovalMutation: () => ({ mutate: mockApprovalMutate }),
useSubmitAskAnswerMutation: () => ({ mutate: mockAskMutate }),
}));
jest.mock('~/store/agents', () => ({
useGetEphemeralAgent: () => () => undefined,
}));
const chatContextValue = {
conversation: {
conversationId: 'conversation-1',
endpoint: 'agents',
endpointType: 'custom',
agent_id: 'agent-1',
model: 'model-1',
spec: 'spec-1',
promptPrefix: 'be brief',
},
getMessages: () => [{ messageId: 'm1', content: [{ type: 'text', text: 'hi' }] }],
setMessages: jest.fn(),
} as unknown as React.ContextType<typeof ChatContext>;
const createWrapper = (generationCreatedAt: number | null) =>
@ -42,488 +44,96 @@ const createWrapper = (generationCreatedAt: number | null) =>
return created;
});
return (
<RecoilRoot>
<JotaiProvider store={jotaiStore}>
<JotaiProvider store={jotaiStore}>
<ChatSettingsContext.Provider value={{ ...defaultChatSettings, getEphemeralAgent }}>
<ChatContext.Provider value={chatContextValue}>
<ApprovalProvider>{children}</ApprovalProvider>
</ChatContext.Provider>
</JotaiProvider>
</RecoilRoot>
</ChatSettingsContext.Provider>
</JotaiProvider>
);
};
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', () => {
describe('app approval resume host', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('passes full selected batches and answers through a host while owning submission state outside chat', async () => {
const pending = Promise.withResolvers<void>();
const transport: ResumeSubmitTransport = {
submitToolApproval: jest.fn(() => pending.promise),
submitAskAnswer: jest.fn(async () => {}),
};
const onSuccess = jest.fn();
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ResumeSubmitContext.Provider value={transport}>
<ApprovalProvider>{children}</ApprovalProvider>
</ResumeSubmitContext.Provider>
</JotaiProvider>
);
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
first: useResumeSubmit(),
second: useResumeSubmit(),
}),
{ wrapper: hostWrapper },
);
const decisions: import('librechat-data-provider').Agents.ToolApprovalResolution[] = [
{ tool_call_id: 'approve', decision: 'approve', scope: 'session' },
{
tool_call_id: 'edit',
decision: 'edit',
editedArguments: { path: 'new.ts', nested: { enabled: true } },
},
{ tool_call_id: 'respond', decision: 'respond', responseText: 'Use the existing file.' },
{ tool_call_id: 'reject', decision: 'reject', reason: 'Do not run this command.' },
];
act(() => {
for (const decision of decisions) {
result.current.approval.registerToolCall('approval-action', decision.tool_call_id);
result.current.approval.setDecision('approval-action', decision.tool_call_id, decision);
}
result.current.first.submitToolApproval('approval-action');
result.current.second.submitToolApproval('approval-action');
});
expect(transport.submitToolApproval).toHaveBeenCalledTimes(1);
expect(transport.submitToolApproval).toHaveBeenCalledWith('approval-action', decisions);
expect(result.current.approval.getStatus('approval-action')).toBe('submitting');
await act(async () => {
pending.resolve();
});
expect(result.current.approval.getStatus('approval-action')).toBe('submitted');
await act(async () => {
result.current.first.submitAskAnswer('single-action', 'answer', { onSuccess });
result.current.first.submitAskAnswer('batch-action', { first: 'yes', second: 'no' });
});
expect(transport.submitAskAnswer).toHaveBeenNthCalledWith(1, 'single-action', 'answer');
expect(transport.submitAskAnswer).toHaveBeenNthCalledWith(2, 'batch-action', {
first: 'yes',
second: 'no',
});
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(mockApprovalMutate).not.toHaveBeenCalled();
expect(mockAskMutate).not.toHaveBeenCalled();
});
test('switches host transports without changing hook order and restores ordinary chat submission', async () => {
const first: ResumeSubmitTransport = {
submitToolApproval: jest.fn(async () => {}),
submitAskAnswer: jest.fn(async () => {}),
};
const second: ResumeSubmitTransport = {
submitToolApproval: jest.fn(async () => {}),
submitAskAnswer: jest.fn(async () => {}),
};
let transport: ResumeSubmitTransport | null = null;
const ChatWrapper = createWrapper(1000);
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<ChatWrapper>
<ResumeSubmitContext.Provider value={transport}>{children}</ResumeSubmitContext.Provider>
</ChatWrapper>
);
const { result, rerender } = renderHook(() => useResumeSubmit(), { wrapper: hostWrapper });
transport = first;
rerender();
await act(async () => result.current.submitAskAnswer('host-first', 'first'));
expect(first.submitAskAnswer).toHaveBeenCalledWith('host-first', 'first');
transport = second;
rerender();
await act(async () => result.current.submitAskAnswer('host-second', 'second'));
expect(second.submitAskAnswer).toHaveBeenCalledWith('host-second', 'second');
expect(mockAskMutate).not.toHaveBeenCalled();
transport = null;
rerender();
act(() => result.current.submitAskAnswer('chat-action', 'ordinary'));
expect(mockAskMutate).toHaveBeenCalledTimes(1);
expect(mockAskMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
actionId: 'chat-action',
answer: 'ordinary',
}),
expect.any(Object),
);
});
test.each(['tool', 'ask'] as const)(
'owns pending, retryable failure and success for %s host submissions across hook instances',
async (kind) => {
const first = Promise.withResolvers<void>();
const retry = Promise.withResolvers<void>();
const send = jest
.fn()
.mockImplementationOnce(() => first.promise)
.mockImplementationOnce(() => retry.promise);
const transport: ResumeSubmitTransport = { submitToolApproval: send, submitAskAnswer: send };
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ApprovalProvider>
<ResumeSubmitContext.Provider value={transport}>
{children}
</ResumeSubmitContext.Provider>
</ApprovalProvider>
</JotaiProvider>
);
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
ask: useAskSubmitStatus(),
first: useResumeSubmit(),
second: useResumeSubmit(),
}),
{ wrapper: hostWrapper },
);
const onSuccess = jest.fn();
const submit = (surface: 'first' | 'second') =>
kind === 'tool'
? result.current[surface].submitToolApproval('action')
: result.current[surface].submitAskAnswer('action', 'answer', { onSuccess });
const status = () =>
kind === 'tool'
? result.current.approval.getStatus('action')
: result.current.ask.getAskStatus('action');
act(() => {
result.current.approval.registerToolCall('action', 'tool');
result.current.approval.setDecision('action', 'tool', {
tool_call_id: 'tool',
decision: 'approve',
});
submit('first');
submit('second');
});
expect(send).toHaveBeenCalledTimes(1);
expect(status()).toBe('submitting');
await act(async () => {
first.reject(new Error('temporary'));
});
expect(status()).toBe('error');
expect(onSuccess).not.toHaveBeenCalled();
act(() => {
submit('second');
submit('first');
});
expect(send).toHaveBeenCalledTimes(2);
expect(status()).toBe('submitting');
await act(async () => {
retry.resolve();
});
expect(status()).toBe('submitted');
act(() => {
submit('first');
submit('second');
});
expect(send).toHaveBeenCalledTimes(2);
expect(onSuccess).toHaveBeenCalledTimes(kind === 'ask' ? 1 : 0);
},
);
test.each(['tool', 'ask'] as const)(
'keeps expired %s host submissions terminal and catches synchronous transport errors',
async (kind) => {
const send = jest
.fn<Promise<void>, []>()
.mockImplementationOnce(() => {
throw new Error('synchronous failure');
})
.mockRejectedValueOnce({ response: { status: 409 } });
const transport: ResumeSubmitTransport = { submitToolApproval: send, submitAskAnswer: send };
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ApprovalProvider>
<ResumeSubmitContext.Provider value={transport}>
{children}
</ResumeSubmitContext.Provider>
</ApprovalProvider>
</JotaiProvider>
);
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
ask: useAskSubmitStatus(),
submit: useResumeSubmit(),
}),
{ wrapper: hostWrapper },
);
const submit = () =>
kind === 'tool'
? result.current.submit.submitToolApproval('action')
: result.current.submit.submitAskAnswer('action', 'answer');
const status = () =>
kind === 'tool'
? result.current.approval.getStatus('action')
: result.current.ask.getAskStatus('action');
act(() => {
result.current.approval.registerToolCall('action', 'tool');
result.current.approval.setDecision('action', 'tool', {
tool_call_id: 'tool',
decision: 'approve',
});
});
await act(async () => submit());
expect(status()).toBe('error');
await act(async () => submit());
expect(status()).toBe('expired');
act(() => submit());
expect(send).toHaveBeenCalledTimes(2);
},
);
test('accepts only action identity and payload without requiring chat stream metadata', () => {
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ApprovalProvider
pendingAction={{ actionId: pendingAction.actionId, payload: pendingAction.payload }}
>
{children}
</ApprovalProvider>
</JotaiProvider>
);
const { result } = renderHook(() => useApprovalContext(), { wrapper: hostWrapper });
expect(result.current.getRegisteredCount('action-1')).toBe(2);
expect(result.current.getLeadToolCallId('action-1')).toBe('call-1');
expect(result.current.isReady('action-1')).toBe(false);
});
test('synchronously deduplicates tool approval submissions and unlocks a retryable error', () => {
test('sends conversation fields, the epoch and the ephemeral agent', () => {
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
resume: useResumeSubmit(),
}),
{ wrapper },
{ wrapper: createWrapper(1000) },
);
act(() => {
result.current.approval.registerToolCall('action-1', 'call-1');
result.current.approval.setDecision('action-1', 'call-1', {
tool_call_id: 'call-1',
decision: 'approve',
});
});
act(() => {
result.current.resume.submitToolApproval('action-1');
result.current.resume.submitToolApproval('action-1');
});
expect(mockApprovalMutate).toHaveBeenCalledTimes(1);
expect(mockApprovalMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
generationCreatedAt: 1000,
actionId: 'action-1',
}),
expect.any(Object),
);
const firstOptions = mockApprovalMutate.mock.calls[0][1] as {
onError: (error: unknown) => void;
};
act(() => firstOptions.onError(new Error('temporary failure')));
act(() => {
result.current.resume.submitToolApproval('action-1');
result.current.resume.submitToolApproval('action-1');
});
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;
act(() => {
result.current.registerToolCall('action-1', 'call-1');
result.current.setDecision('action-1', 'call-1', decision);
});
act(() => result.current.unregisterToolCall('action-1', 'call-1'));
expect(result.current.getDecisions('action-1')).toEqual([]);
expect(result.current.getDecision('action-1', 'call-1')).toEqual(decision);
act(() => result.current.registerToolCall('action-1', 'call-1'));
expect(result.current.getDecisions('action-1')).toEqual([decision]);
expect(result.current.isReady('action-1')).toBe(true);
});
test('submits approval and ask-answer resumes without an epoch when none is known', () => {
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
resume: useResumeSubmit(),
}),
{ wrapper: createWrapper(null) },
);
act(() => {
result.current.approval.registerToolCall('action-1', 'call-1');
result.current.approval.setDecision('action-1', 'call-1', {
tool_call_id: 'call-1',
decision: 'approve',
});
});
act(() => {
result.current.resume.submitToolApproval('action-1');
result.current.resume.submitAskAnswer('ask-1', 'answer');
});
expect(mockApprovalMutate).toHaveBeenCalledTimes(1);
expect(mockApprovalMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
generationCreatedAt: 1000,
endpoint: 'agents',
endpointType: 'custom',
agent_id: 'agent-1',
model: 'model-1',
spec: 'spec-1',
promptPrefix: 'be brief',
ephemeralAgent: { mcp: ['server'] },
actionId: 'action-1',
decisions: [{ tool_call_id: 'call-1', decision: 'approve' }],
}),
expect.any(Object),
);
expect(mockApprovalMutate.mock.calls[0][0]).not.toHaveProperty('generationCreatedAt');
expect(mockAskMutate).toHaveBeenCalledTimes(1);
expect(mockAskMutate.mock.calls[0][0]).toEqual(
expect.objectContaining({ conversationId: 'conversation-1', actionId: 'ask-1' }),
);
expect(mockAskMutate.mock.calls[0][0]).not.toHaveProperty('generationCreatedAt');
});
test('synchronously deduplicates ask answers and unlocks a retryable error', () => {
const { result } = renderHook(() => useResumeSubmit(), { wrapper });
act(() => {
result.current.submitAskAnswer('ask-1', 'answer');
result.current.submitAskAnswer('ask-1', 'answer');
});
expect(mockAskMutate).toHaveBeenCalledTimes(1);
expect(mockAskMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
generationCreatedAt: 1000,
actionId: 'ask-1',
answer: 'answer',
ephemeralAgent: { mcp: ['server'] },
}),
expect.any(Object),
);
});
const firstOptions = mockAskMutate.mock.calls[0][1] as {
onError: (error: unknown) => void;
test('omits the epoch when the client has not observed one', () => {
const { result } = renderHook(() => useResumeSubmit(), { wrapper: createWrapper(null) });
act(() => result.current.submitAskAnswer('ask-1', 'answer'));
expect(mockAskMutate.mock.calls[0][0]).not.toHaveProperty('generationCreatedAt');
});
test('an explicit transport replaces the chat mutation until it is cleared', async () => {
const first: ResumeSubmitTransport = {
submitToolApproval: jest.fn(async () => {}),
submitAskAnswer: jest.fn(async () => {}),
};
act(() => firstOptions.onError(new Error('temporary failure')));
act(() => {
result.current.submitAskAnswer('ask-1', 'answer');
result.current.submitAskAnswer('ask-1', 'answer');
let transport: ResumeSubmitTransport | null = first;
const ChatWrapper = createWrapper(1000);
const { result, rerender } = renderHook(() => useResumeSubmit(), {
wrapper: ({ children }) => (
<ChatWrapper>
<ResumeSubmitContext.Provider value={transport}>{children}</ResumeSubmitContext.Provider>
</ChatWrapper>
),
});
expect(mockAskMutate).toHaveBeenCalledTimes(2);
await act(async () => result.current.submitAskAnswer('host-action', 'first'));
expect(first.submitAskAnswer).toHaveBeenCalledWith('host-action', 'first');
expect(mockAskMutate).not.toHaveBeenCalled();
transport = null;
rerender();
act(() => result.current.submitAskAnswer('chat-action', 'ordinary'));
expect(mockAskMutate).toHaveBeenCalledWith(
expect.objectContaining({ actionId: 'chat-action', answer: 'ordinary' }),
expect.any(Object),
);
});
});

View file

@ -1,58 +1,22 @@
import { memo, useEffect, useMemo } from 'react';
import { useAtom, useAtomValue } from 'jotai';
import { isCancelKey } from '@librechat/chat';
import { Button, TooltipAnchor } from '@librechat/client';
import { buildApprovalPreview, buildApprovalPreviews } from '@librechat/chat';
import { ChevronDown, ChevronUp, ShieldQuestion, TriangleAlert } from 'lucide-react';
import { memo, useCallback } from 'react';
import { ChevronDown } from 'lucide-react';
import { Button } from '@librechat/client';
import { ApprovalResumeHostProvider } from '@librechat/chat/react';
import {
useComposerOverlay,
approvalPanelOpenFamily,
pendingApprovalActionFamily,
} from '@librechat/chat/react';
import type { Agents } from 'librechat-data-provider';
import type { KeyboardEvent, RefObject } from 'react';
import type { TranslationKeys } from '~/hooks';
import {
useApprovalContext,
useResumeSubmit,
} from '~/components/Chat/Messages/Content/ApprovalContext';
PendingToolApprovalButton as PackageButton,
PendingToolApprovalPanel as PackagePanel,
} from '@librechat/chat/components';
import type { ApprovalRequestRenderProps } from '@librechat/chat/components';
import type { ReactNode, RefObject } from 'react';
import { useChatApprovalHost } from '~/components/Chat/Messages/Content/ApprovalContext';
import ToolApproval from '~/components/Chat/Messages/Content/ToolApproval';
import { useLocalize } from '~/hooks';
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;
}
/**
* The app's review panel: package chrome, with this app's approval card in each row. The
* panel's Continue button resumes through the host, which only this app can build from
* the active conversation.
*/
export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
conversationId,
triggerRef,
@ -62,175 +26,40 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
triggerRef?: RefObject<HTMLButtonElement>;
}) {
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]);
useComposerOverlay(conversationId, open && pendingAction != null);
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;
}
/** Collapsing unmounts the focused control, so focus goes back to the
* toggle rather than falling to the page. Decisions and drafts are kept. */
const collapse = () => {
setOpen(false);
triggerRef?.current?.focus();
};
const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const isComposing = e.nativeEvent.isComposing || e.key === 'Process' || e.keyCode === 229;
if (!isCancelKey(e.nativeEvent) || isComposing) {
return;
}
e.preventDefault();
collapse();
};
const decisions = getDecisions(pendingAction.actionId);
const status = getStatus(pendingAction.actionId);
const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
const host = useChatApprovalHost();
const renderRequest = useCallback(
(props: ApprovalRequestRenderProps) => <ToolApproval {...props} surface="composer" />,
[],
);
const renderCollapse = useCallback(
({ onClick, label }: { onClick: () => void; label: string }) => (
<Button
type="button"
variant="quiet"
size="icon"
aria-label={label}
className="size-auto rounded-md p-1"
onClick={onClick}
>
<ChevronDown className="size-4" aria-hidden="true" />
</Button>
),
[],
);
return (
<div
id="pending-tool-approval-panel"
/* The absolute review layer spans the composer width, but only its card
* is painted and interactive. Let the thread receive clicks through the
* transparent remainder of the layer. */
className="pointer-events-none absolute bottom-28 z-10 w-full"
role="region"
aria-labelledby="pending-tool-approval-title"
aria-live="polite"
onKeyDown={handleKeyDown}
>
<div className="popover border-border-light bg-surface-primary-alt rounded-theme-popover pointer-events-auto flex max-h-[70vh] flex-col border shadow-lg">
<div className="border-border-light flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2">
<p id="pending-tool-approval-title" className="text-text-primary text-sm font-medium">
{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="quiet"
size="icon"
aria-label={localize('com_ui_collapse')}
className="size-auto rounded-md p-1"
onClick={collapse}
>
<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-text-primary text-sm font-medium [overflow-wrap:anywhere]"
>
{reviews.length > 1
? `${index + 1}. ${previewTitle(preview, localize)}`
: previewTitle(preview, localize)}
</h3>
<p className="text-text-secondary text-xs">{localize(KIND_LABELS[preview.kind])}</p>
</div>
<pre className="border-border-light bg-surface-tertiary text-text-primary max-h-52 overflow-auto rounded-lg border p-3 font-mono text-xs break-words whitespace-pre-wrap">
{preview.body || localize('com_ui_no_arguments')}
</pre>
{preview.truncated && (
<p className="text-text-secondary mt-1 text-xs">
{localize('com_ui_preview_truncated')}
</p>
)}
{config != null ? (
<ToolApproval
approval={{
actionId: pendingAction.actionId,
allowed_decisions: config.allowed_decisions,
remember_scope: config.remember_scope,
remember_unavailable: config.remember_unavailable,
description: preview.description,
allow_always: config.allow_always === true,
}}
toolCallId={request.tool_call_id}
args={request.arguments}
surface="composer"
/>
) : (
<p className="text-text-warning mt-2 flex items-center text-xs" role="alert">
<TriangleAlert className="me-1.5 size-4" aria-hidden="true" />
{localize('com_ui_approval_unavailable')}
</p>
)}
</section>
))}
</div>
<div className="border-border-light flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2">
<span className="text-text-secondary text-xs">
{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="text-text-warning flex items-center text-xs" role="alert">
<TriangleAlert className="me-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>
<ApprovalResumeHostProvider host={host}>
<PackagePanel
conversationId={conversationId}
triggerRef={triggerRef}
localize={localize}
renderRequest={renderRequest}
renderCollapse={renderCollapse}
/>
</ApprovalResumeHostProvider>
);
});
/** The composer toggle that opens the review panel. */
export const PendingToolApprovalButton = memo(function PendingToolApprovalButton({
conversationId,
triggerRef,
@ -239,35 +68,40 @@ export const PendingToolApprovalButton = memo(function PendingToolApprovalButton
triggerRef?: RefObject<HTMLButtonElement>;
}) {
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;
const renderToggle = useCallback(
({
ref,
expanded,
onClick,
children,
}: {
ref?: RefObject<HTMLButtonElement>;
expanded: boolean;
onClick: () => void;
children: ReactNode;
}) => (
<Button
ref={ref}
type="button"
variant="quiet"
size="sm"
aria-expanded={expanded}
aria-controls="pending-tool-approval-panel"
onClick={onClick}
className="h-8 gap-1.5 rounded-full px-2"
data-testid="pending-tool-approval-button"
>
{children}
</Button>
),
[],
);
return (
<Button
ref={triggerRef}
type="button"
variant="quiet"
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"
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>
<PackageButton
conversationId={conversationId}
triggerRef={triggerRef}
localize={localize}
renderToggle={renderToggle}
/>
);
});

View file

@ -2,10 +2,17 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { fireEvent, render, screen } from '@testing-library/react';
import { composerOverlayCountFamily, pendingApprovalActionFamily } from '@librechat/chat/react';
import {
activeGenerationCreatedAtByConvoId,
pendingApprovalActionFamily,
} from '@librechat/chat/react';
import type { Agents } from 'librechat-data-provider';
import { PendingToolApprovalButton, PendingToolApprovalPanel } from '../Review';
import ApprovalProvider from '../../Messages/Content/ApprovalContext';
import { ChatSettingsContext, defaultChatSettings } from '~/Providers/ChatSettingsContext';
import ApprovalProvider from '~/components/Chat/Messages/Content/ApprovalContext';
import { ChatContext } from '~/Providers/ChatContext';
import { PendingToolApprovalPanel } from '../Review';
const mockApprovalMutate = jest.fn();
jest.mock('@librechat/client', () => ({
Button: jest
@ -31,15 +38,10 @@ jest.mock('~/hooks', () => ({
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_review_run_command: 'Run command',
com_ui_proposed_contents: 'Proposed contents',
com_ui_proposed_replacements: 'Proposed replacements',
com_ui_proposed_arguments: 'Proposed arguments',
com_ui_proposed_command: 'Proposed command',
com_ui_decisions_selected: `${values?.[0]} of ${values?.[1]} decisions selected`,
com_ui_approve: 'Approve',
com_ui_reject: 'Reject',
@ -51,7 +53,7 @@ jest.mock('~/hooks', () => ({
}));
jest.mock('~/data-provider', () => ({
useSubmitToolApprovalMutation: () => ({ mutate: jest.fn() }),
useSubmitToolApprovalMutation: () => ({ mutate: mockApprovalMutate }),
useSubmitAskAnswerMutation: () => ({ mutate: jest.fn() }),
}));
@ -59,6 +61,19 @@ jest.mock('~/store/agents', () => ({
useGetEphemeralAgent: () => () => undefined,
}));
const getEphemeralAgent = jest.fn(() => ({ mcp: ['server'] }));
const chatContextValue = {
conversation: {
conversationId: 'conversation-1',
endpoint: 'agents',
agent_id: 'agent-1',
model: 'model-1',
},
getMessages: () => [],
setMessages: jest.fn(),
} as unknown as React.ContextType<typeof ChatContext>;
const pendingAction: Agents.PendingAction = {
actionId: 'action-1',
streamId: 'stream-1',
@ -95,97 +110,53 @@ const pendingAction: Agents.PendingAction = {
},
};
describe('PendingToolApproval', () => {
test('reviews the authoritative batch beside the composer and can be collapsed', async () => {
describe('app composer review panel', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('Continue sends the whole batch with the conversation fields through the app host', async () => {
const jotaiStore = createStore();
jotaiStore.set(pendingApprovalActionFamily('conversation-1'), pendingAction);
jotaiStore.set(activeGenerationCreatedAtByConvoId('conversation-1'), 1000);
render(
<RecoilRoot>
<JotaiProvider store={jotaiStore}>
<ApprovalProvider pendingAction={pendingAction}>
<PendingToolApprovalPanel conversationId="conversation-1" />
<PendingToolApprovalButton conversationId="conversation-1" />
</ApprovalProvider>
<ChatSettingsContext.Provider value={{ ...defaultChatSettings, getEphemeralAgent }}>
<ChatContext.Provider value={chatContextValue}>
<ApprovalProvider pendingAction={pendingAction}>
<PendingToolApprovalPanel conversationId="conversation-1" />
</ApprovalProvider>
</ChatContext.Provider>
</ChatSettingsContext.Provider>
</JotaiProvider>
</RecoilRoot>,
);
expect(await screen.findByRole('region', { name: 'Review 2 actions' })).toBeInTheDocument();
expect(jotaiStore.get(composerOverlayCountFamily('conversation-1'))).toBe(1);
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();
await screen.findByRole('region', { name: 'Review 2 actions' });
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();
const submit = screen.getByRole('button', { name: 'Continue' });
expect(submit).toBeEnabled();
fireEvent.click(submit);
fireEvent.click(screen.getByRole('button', { name: 'Collapse' }));
expect(screen.queryByRole('region', { name: 'Review 2 actions' })).not.toBeInTheDocument();
expect(jotaiStore.get(composerOverlayCountFamily('conversation-1'))).toBe(0);
expect(screen.getByTestId('pending-tool-approval-button')).toHaveAttribute(
'aria-expanded',
'false',
expect(mockApprovalMutate).toHaveBeenCalledTimes(1);
expect(mockApprovalMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
generationCreatedAt: 1000,
endpoint: 'agents',
agent_id: 'agent-1',
model: 'model-1',
ephemeralAgent: { mcp: ['server'] },
actionId: 'action-1',
decisions: [
expect.objectContaining({ tool_call_id: 'call-1', decision: 'approve' }),
expect.objectContaining({ tool_call_id: 'call-2', decision: 'approve' }),
],
}),
expect.any(Object),
);
});
describe('collapsing from the keyboard', () => {
function Harness() {
const triggerRef = React.useRef<HTMLButtonElement>(null);
return (
<>
<PendingToolApprovalPanel conversationId="conversation-1" triggerRef={triggerRef} />
<PendingToolApprovalButton conversationId="conversation-1" triggerRef={triggerRef} />
</>
);
}
const renderPanel = () => {
const jotaiStore = createStore();
jotaiStore.set(pendingApprovalActionFamily('conversation-1'), pendingAction);
render(
<RecoilRoot>
<JotaiProvider store={jotaiStore}>
<ApprovalProvider pendingAction={pendingAction}>
<Harness />
</ApprovalProvider>
</JotaiProvider>
</RecoilRoot>,
);
return jotaiStore;
};
test('Escape collapses the panel, keeps decisions and returns focus to the toggle', async () => {
renderPanel();
await screen.findByRole('region', { name: 'Review 2 actions' });
const approve = screen.getAllByRole('button', { name: 'Approve' })[0];
fireEvent.click(approve);
approve.focus();
fireEvent.keyDown(approve, { key: 'Escape', isComposing: true });
fireEvent.keyDown(approve, { key: 'Escape', keyCode: 229 });
fireEvent.keyDown(approve, { key: 'Escape', shiftKey: true });
expect(screen.getByRole('region', { name: 'Review 2 actions' })).toBeInTheDocument();
fireEvent.keyDown(approve, { key: 'Escape' });
expect(screen.queryByRole('region', { name: 'Review 2 actions' })).not.toBeInTheDocument();
const toggle = screen.getByTestId('pending-tool-approval-button');
expect(toggle).toHaveFocus();
expect(toggle).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(toggle);
expect(screen.getByText('1 of 2 decisions selected')).toBeInTheDocument();
});
test('the Collapse button also returns focus to the toggle', async () => {
renderPanel();
await screen.findByRole('region', { name: 'Review 2 actions' });
fireEvent.click(screen.getByRole('button', { name: 'Collapse' }));
expect(screen.getByTestId('pending-tool-approval-button')).toHaveFocus();
});
});
});

View file

@ -63,7 +63,7 @@ for (const mode of ['light', 'dark']) {
expect(writes).toBe(1);
await expect(page.getByRole('button', { name: /Stop/, exact: false })).toBeDisabled();
});
test(`owner tool review preserves the exact batch through uncertain acknowledgement (${mode})`, async ({
test(`owner tool review preserves the exact batch through uncertain acknowledgement (${mode}) @scenario:response-review-resubmits-its-exact-tool-batch-after-uncertain-acknowledgement`, async ({
page,
}) => {
const acknowledgement = Promise.withResolvers<void>();
@ -144,7 +144,9 @@ for (const mode of ['light', 'dark']) {
await page.getByRole('button', { name: 'Retry', exact: true }).click();
await expect.poll(() => decisions.length).toBe(2);
expect(decisions[1]).toEqual(expected);
await expect(page.getByRole('status').filter({ hasText: /decision was received/i })).toBeVisible();
await expect(
page.getByRole('status').filter({ hasText: /decision was received/i }),
).toBeVisible();
} finally {
acknowledgement.resolve();
}

View file

@ -280,3 +280,23 @@ export {
export { default as CopyButton } from './components/parts/CopyButton';
export { default as ActionButton } from './components/parts/ActionButton';
export { default as LangIcon, hasLangIcon } from './components/parts/LangIcon';
/** Tool approval: the shared decision state and the composer's review panel. */
export {
default as ApprovalProvider,
ResumeSubmitContext,
useApprovalContext,
useAskSubmitStatus,
useResumeSubmit,
} from './components/approval/context';
export type {
ResumeSubmitTransport,
ToolApprovalDecisionDraft,
} from './components/approval/context';
export { PendingToolApprovalButton, PendingToolApprovalPanel } from './components/approval/Review';
export type {
ApprovalRequestRenderProps,
ApprovalReviewCopy,
PendingToolApprovalButtonProps,
PendingToolApprovalPanelProps,
} from './components/approval/Review';

View file

@ -0,0 +1,327 @@
import { memo, useEffect, useMemo, useRef } from 'react';
import { useAtom, useAtomValue } from 'jotai';
import { Button, TooltipAnchor } from '@librechat/client';
import { ChevronDown, ChevronUp, ShieldQuestion, TriangleAlert } from 'lucide-react';
import type { MemoExoticComponent, ReactElement, ReactNode, RefObject } from 'react';
import type { Agents } from 'librechat-data-provider';
import { approvalPanelOpenFamily, pendingApprovalActionFamily } from '../../react/approval';
import { buildApprovalPreview, buildApprovalPreviews } from '../../core/parts/approval';
import { useApprovalContext, useResumeSubmit } from './context';
import { useComposerOverlay } from '../../react/overlay';
import { isCancelKey } from '../../core/shortcuts';
/** Copy for the review panel. A method, so a host localize typed with its own
* key union still fits. The keys passed here come from this panel. */
export type ApprovalReviewCopy = {
translate(key: string, values?: Record<string, string | number>): string;
}['translate'];
/** One paused call, drawn by the host's tool-approval card. */
export type ApprovalRequestRenderProps = {
approval: NonNullable<Agents.ToolCall['approval']>;
toolCallId: string;
args: Agents.ToolApprovalRequest['arguments'];
};
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'], string> = {
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: ApprovalReviewCopy,
): 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 type PendingToolApprovalPanelProps = {
conversationId: string;
/** The composer toggle that reopens the panel; collapsing returns focus to it. */
triggerRef?: RefObject<HTMLButtonElement>;
localize: ApprovalReviewCopy;
/** The host's approval card for one paused call. */
renderRequest: (props: ApprovalRequestRenderProps) => ReactNode;
/** Host-drawn collapse control. Omitted, the package draws a quiet icon button. */
renderCollapse?: (props: { onClick: () => void; label: string }) => ReactElement;
};
export const PendingToolApprovalPanel: MemoExoticComponent<
(props: PendingToolApprovalPanelProps) => ReactNode
> = memo(function PendingToolApprovalPanel({
conversationId,
triggerRef,
localize,
renderRequest,
renderCollapse,
}: PendingToolApprovalPanelProps) {
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]);
useComposerOverlay(conversationId, open && pendingAction != null);
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]);
const regionRef = useRef<HTMLDivElement>(null);
const collapseRef = useRef<() => void>(() => undefined);
/** Collapsing unmounts the focused control, so focus goes back to the
* toggle rather than falling to the page. Decisions and drafts are kept. */
collapseRef.current = () => {
setOpen(false);
triggerRef?.current?.focus();
};
useEffect(() => {
const region = regionRef.current;
if (!open || pendingAction == null || region == null) {
return undefined;
}
const onKeyDown = (event: KeyboardEvent) => {
const isComposing = event.isComposing || event.key === 'Process' || event.keyCode === 229;
if (!isCancelKey(event) || isComposing) {
return;
}
event.preventDefault();
collapseRef.current();
};
region.addEventListener('keydown', onKeyDown);
return () => region.removeEventListener('keydown', onKeyDown);
}, [open, pendingAction]);
if (!open || pendingAction == null) {
return null;
}
const collapse = () => collapseRef.current();
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"
/* The absolute review layer spans the composer width, but only its card
* is painted and interactive. Let the thread receive clicks through the
* transparent remainder of the layer. */
ref={regionRef}
className="pointer-events-none absolute bottom-28 z-10 w-full"
role="region"
aria-labelledby="pending-tool-approval-title"
aria-live="polite"
>
<div className="popover border-border-light bg-surface-primary-alt rounded-theme-popover pointer-events-auto flex max-h-[70vh] flex-col border shadow-lg">
<div className="border-border-light flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2">
<p id="pending-tool-approval-title" className="text-text-primary text-sm font-medium">
{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={
renderCollapse != null ? (
renderCollapse({
onClick: collapse,
label: localize('com_ui_collapse'),
})
) : (
<Button
type="button"
variant="quiet"
size="icon"
aria-label={localize('com_ui_collapse')}
onClick={collapse}
>
<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-text-primary text-sm font-medium [overflow-wrap:anywhere]"
>
{reviews.length > 1
? `${index + 1}. ${previewTitle(preview, localize)}`
: previewTitle(preview, localize)}
</h3>
<p className="text-text-secondary text-xs">{localize(KIND_LABELS[preview.kind])}</p>
</div>
<pre className="border-border-light bg-surface-tertiary text-text-primary max-h-52 overflow-auto rounded-lg border p-3 font-mono text-xs break-words whitespace-pre-wrap">
{preview.body || localize('com_ui_no_arguments')}
</pre>
{preview.truncated && (
<p className="text-text-secondary mt-1 text-xs">
{localize('com_ui_preview_truncated')}
</p>
)}
{config != null ? (
renderRequest({
approval: {
actionId: pendingAction.actionId,
allowed_decisions: config.allowed_decisions,
remember_scope: config.remember_scope,
remember_unavailable: config.remember_unavailable,
description: preview.description,
allow_always: config.allow_always === true,
},
toolCallId: request.tool_call_id,
args: request.arguments,
})
) : (
<p className="text-text-warning mt-2 flex items-center text-xs" role="alert">
<TriangleAlert className="me-1.5 size-4" aria-hidden="true" />
{localize('com_ui_approval_unavailable')}
</p>
)}
</section>
))}
</div>
<div className="border-border-light flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2">
<span className="text-text-secondary text-xs">
{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="text-text-warning flex items-center text-xs" role="alert">
<TriangleAlert className="me-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 type PendingToolApprovalButtonProps = {
conversationId: string;
triggerRef?: RefObject<HTMLButtonElement>;
localize: ApprovalReviewCopy;
/** Host-drawn composer toggle. Omitted, the package draws a quiet button. */
renderToggle?: (props: {
ref?: RefObject<HTMLButtonElement>;
expanded: boolean;
onClick: () => void;
children: ReactNode;
}) => ReactNode;
};
export const PendingToolApprovalButton: MemoExoticComponent<
(props: PendingToolApprovalButtonProps) => ReactNode
> = memo(function PendingToolApprovalButton({
conversationId,
triggerRef,
localize,
renderToggle,
}: PendingToolApprovalButtonProps) {
const pendingAction = usePendingToolApproval(conversationId);
const [open, setOpen] = useAtom(approvalPanelOpenFamily(conversationId));
if (pendingAction == null) {
return null;
}
const count = pendingAction.payload.action_requests.length;
const onClick = () => setOpen((current) => !current);
const content = (
<>
<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" />
)}
</>
);
if (renderToggle != null) {
return renderToggle({ ref: triggerRef, expanded: open, onClick, children: content });
}
return (
<Button
ref={triggerRef}
type="button"
variant="quiet"
size="sm"
aria-expanded={open}
aria-controls="pending-tool-approval-panel"
onClick={onClick}
data-testid="pending-tool-approval-button"
>
{content}
</Button>
);
});

View file

@ -0,0 +1,311 @@
/**
* @jest-environment jsdom
*/
import React, { useEffect } from 'react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { act, fireEvent, render, screen } from '@testing-library/react';
import type { Agents } from 'librechat-data-provider';
import type { ApprovalRequestRenderProps, ApprovalReviewCopy } from '../Review';
import type { ApprovalResumeHost } from '../../../react/approval';
import { ApprovalResumeHostProvider, pendingApprovalActionFamily } from '../../../react/approval';
import { PendingToolApprovalButton, PendingToolApprovalPanel } from '../Review';
import { composerOverlayCountFamily } from '../../../react/overlay';
import ApprovalProvider, { useApprovalContext } from '../context';
const localize: ApprovalReviewCopy = (key, values) => {
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_submitting: 'Submitting',
com_ui_collapse: 'Collapse',
};
return labels[key] ?? key;
};
function FakeRequest({ approval, toolCallId }: ApprovalRequestRenderProps) {
const { registerToolCall, unregisterToolCall, setDecision } = useApprovalContext();
useEffect(() => {
registerToolCall(approval.actionId, toolCallId);
return () => unregisterToolCall(approval.actionId, toolCallId);
}, [approval.actionId, toolCallId, registerToolCall, unregisterToolCall]);
return (
<button
type="button"
onClick={() =>
setDecision(approval.actionId, toolCallId, {
tool_call_id: toolCallId,
decision: 'approve',
})
}
>
Approve
</button>
);
}
function renderRequest(props: ApprovalRequestRenderProps) {
return <FakeRequest {...props} />;
}
jest.mock('@librechat/client', () => ({
Button: jest
.requireActual('react')
.forwardRef(
(
{ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>,
ref: React.Ref<HTMLButtonElement>,
) => (
<button ref={ref} {...props}>
{children}
</button>
),
),
TextareaAutosize: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => (
<textarea {...props} />
),
TooltipAnchor: ({ render }: { render: React.ReactNode }) => render,
}));
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(
<JotaiProvider store={jotaiStore}>
<ApprovalProvider pendingAction={pendingAction}>
<PendingToolApprovalPanel
conversationId="conversation-1"
localize={localize}
renderRequest={renderRequest}
/>
<PendingToolApprovalButton conversationId="conversation-1" localize={localize} />
</ApprovalProvider>
</JotaiProvider>,
);
expect(await screen.findByRole('region', { name: 'Review 2 actions' })).toBeInTheDocument();
expect(jotaiStore.get(composerOverlayCountFamily('conversation-1'))).toBe(1);
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(jotaiStore.get(composerOverlayCountFamily('conversation-1'))).toBe(0);
expect(screen.getByTestId('pending-tool-approval-button')).toHaveAttribute(
'aria-expanded',
'false',
);
});
describe('resuming through the host', () => {
const createHost = (fields: ReturnType<ApprovalResumeHost['readFields']>) => {
const submitToolApproval = jest.fn();
const host: ApprovalResumeHost = {
readFields: () => fields,
submitToolApproval,
submitAskAnswer: jest.fn(),
readMessages: () => null,
};
return { host, submitToolApproval };
};
const renderWithHost = (host: ApprovalResumeHost) => {
const jotaiStore = createStore();
jotaiStore.set(pendingApprovalActionFamily('conversation-1'), pendingAction);
render(
<JotaiProvider store={jotaiStore}>
<ApprovalResumeHostProvider host={host}>
<ApprovalProvider pendingAction={pendingAction}>
<PendingToolApprovalPanel
conversationId="conversation-1"
localize={localize}
renderRequest={renderRequest}
/>
</ApprovalProvider>
</ApprovalResumeHostProvider>
</JotaiProvider>,
);
return jotaiStore;
};
const approveBoth = async () => {
await screen.findByRole('region', { name: 'Review 2 actions' });
for (const approve of screen.getAllByRole('button', { name: 'Approve' })) {
fireEvent.click(approve);
}
};
test('Continue sends the whole batch and closes the review once the host accepts it', async () => {
const { host, submitToolApproval } = createHost({
conversationId: 'conversation-1',
generationCreatedAt: 1000,
});
const jotaiStore = renderWithHost(host);
await approveBoth();
fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(submitToolApproval).toHaveBeenCalledTimes(1);
expect(submitToolApproval).toHaveBeenCalledWith(
{
conversationId: 'conversation-1',
generationCreatedAt: 1000,
actionId: 'action-1',
decisions: [
{ tool_call_id: 'call-1', decision: 'approve' },
{ tool_call_id: 'call-2', decision: 'approve' },
],
},
expect.any(Object),
);
expect(screen.getByRole('button', { name: 'Submitting' })).toBeDisabled();
act(() => submitToolApproval.mock.calls[0][1].onSuccess());
expect(jotaiStore.get(pendingApprovalActionFamily('conversation-1'))).toBeNull();
expect(screen.queryByRole('region', { name: 'Review 2 actions' })).not.toBeInTheDocument();
});
test('a failed submit keeps the batch and lets Continue retry', async () => {
const { host, submitToolApproval } = createHost({ conversationId: 'conversation-1' });
renderWithHost(host);
await approveBoth();
fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
act(() => submitToolApproval.mock.calls[0][1].onError(new Error('offline')));
expect(screen.getByText('2 of 2 decisions selected')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(submitToolApproval).toHaveBeenCalledTimes(2);
});
test('Continue does nothing while the host has no live conversation', async () => {
const { host, submitToolApproval } = createHost(null);
renderWithHost(host);
await approveBoth();
fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(submitToolApproval).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled();
});
});
describe('collapsing from the keyboard', () => {
function Harness() {
const triggerRef = React.useRef<HTMLButtonElement>(null);
return (
<>
<PendingToolApprovalPanel
conversationId="conversation-1"
triggerRef={triggerRef}
localize={localize}
renderRequest={renderRequest}
/>
<PendingToolApprovalButton
conversationId="conversation-1"
triggerRef={triggerRef}
localize={localize}
/>
</>
);
}
const renderPanel = () => {
const jotaiStore = createStore();
jotaiStore.set(pendingApprovalActionFamily('conversation-1'), pendingAction);
render(
<JotaiProvider store={jotaiStore}>
<ApprovalProvider pendingAction={pendingAction}>
<Harness />
</ApprovalProvider>
</JotaiProvider>,
);
return jotaiStore;
};
test('Escape collapses the panel, keeps decisions and returns focus to the toggle', async () => {
renderPanel();
await screen.findByRole('region', { name: 'Review 2 actions' });
const approve = screen.getAllByRole('button', { name: 'Approve' })[0];
fireEvent.click(approve);
approve.focus();
fireEvent.keyDown(approve, { key: 'Escape', isComposing: true });
fireEvent.keyDown(approve, { key: 'Escape', keyCode: 229 });
fireEvent.keyDown(approve, { key: 'Escape', shiftKey: true });
expect(screen.getByRole('region', { name: 'Review 2 actions' })).toBeInTheDocument();
fireEvent.keyDown(approve, { key: 'Escape' });
expect(screen.queryByRole('region', { name: 'Review 2 actions' })).not.toBeInTheDocument();
const toggle = screen.getByTestId('pending-tool-approval-button');
expect(toggle).toHaveFocus();
expect(toggle).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(toggle);
expect(screen.getByText('1 of 2 decisions selected')).toBeInTheDocument();
});
test('the Collapse button also returns focus to the toggle', async () => {
renderPanel();
await screen.findByRole('region', { name: 'Review 2 actions' });
fireEvent.click(screen.getByRole('button', { name: 'Collapse' }));
expect(screen.getByTestId('pending-tool-approval-button')).toHaveFocus();
});
});
});

View file

@ -0,0 +1,523 @@
/**
* @jest-environment jsdom
*/
import React from 'react';
import { act, renderHook } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import type { ApprovalResumeHost } from '../../../react/approval';
import type { ResumeSubmitTransport } from '../context';
import ApprovalProvider, {
ResumeSubmitContext,
useApprovalContext,
useAskSubmitStatus,
useResumeSubmit,
} from '../context';
import { ApprovalResumeHostProvider } from '../../../react/approval';
const mockApprovalMutate = jest.fn();
const mockAskMutate = jest.fn();
function deferred() {
let resolve: () => void = () => undefined;
let reject: (reason?: unknown) => void = () => undefined;
const promise = new Promise<void>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
const createWrapper = (generationCreatedAt: number | null) =>
function ResumeWrapper({ children }: { children: React.ReactNode }) {
const [jotaiStore] = React.useState(() => createStore());
const [host] = React.useState<ApprovalResumeHost>(() => ({
readFields: () => ({
conversationId: 'conversation-1',
endpoint: 'agents',
agent_id: 'agent-1',
...(generationCreatedAt != null && { generationCreatedAt }),
}),
submitToolApproval: (body, callbacks) => mockApprovalMutate(body, callbacks),
submitAskAnswer: (body, callbacks) => mockAskMutate(body, callbacks),
readMessages: () => null,
}));
return (
<JotaiProvider store={jotaiStore}>
<ApprovalResumeHostProvider host={host}>
<ApprovalProvider>{children}</ApprovalProvider>
</ApprovalResumeHostProvider>
</JotaiProvider>
);
};
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();
});
test('passes full selected batches and answers through a host while owning submission state outside chat', async () => {
const pending = deferred();
const transport: ResumeSubmitTransport = {
submitToolApproval: jest.fn(() => pending.promise),
submitAskAnswer: jest.fn(async () => {}),
};
const onSuccess = jest.fn();
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ResumeSubmitContext.Provider value={transport}>
<ApprovalProvider>{children}</ApprovalProvider>
</ResumeSubmitContext.Provider>
</JotaiProvider>
);
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
first: useResumeSubmit(),
second: useResumeSubmit(),
}),
{ wrapper: hostWrapper },
);
const decisions: import('librechat-data-provider').Agents.ToolApprovalResolution[] = [
{ tool_call_id: 'approve', decision: 'approve', scope: 'session' },
{
tool_call_id: 'edit',
decision: 'edit',
editedArguments: { path: 'new.ts', nested: { enabled: true } },
},
{ tool_call_id: 'respond', decision: 'respond', responseText: 'Use the existing file.' },
{ tool_call_id: 'reject', decision: 'reject', reason: 'Do not run this command.' },
];
act(() => {
for (const decision of decisions) {
result.current.approval.registerToolCall('approval-action', decision.tool_call_id);
result.current.approval.setDecision('approval-action', decision.tool_call_id, decision);
}
result.current.first.submitToolApproval('approval-action');
result.current.second.submitToolApproval('approval-action');
});
expect(transport.submitToolApproval).toHaveBeenCalledTimes(1);
expect(transport.submitToolApproval).toHaveBeenCalledWith('approval-action', decisions);
expect(result.current.approval.getStatus('approval-action')).toBe('submitting');
await act(async () => {
pending.resolve();
});
expect(result.current.approval.getStatus('approval-action')).toBe('submitted');
await act(async () => {
result.current.first.submitAskAnswer('single-action', 'answer', { onSuccess });
result.current.first.submitAskAnswer('batch-action', { first: 'yes', second: 'no' });
});
expect(transport.submitAskAnswer).toHaveBeenNthCalledWith(1, 'single-action', 'answer');
expect(transport.submitAskAnswer).toHaveBeenNthCalledWith(2, 'batch-action', {
first: 'yes',
second: 'no',
});
expect(onSuccess).toHaveBeenCalledTimes(1);
expect(mockApprovalMutate).not.toHaveBeenCalled();
expect(mockAskMutate).not.toHaveBeenCalled();
});
test('switches host transports without changing hook order and restores ordinary chat submission', async () => {
const first: ResumeSubmitTransport = {
submitToolApproval: jest.fn(async () => {}),
submitAskAnswer: jest.fn(async () => {}),
};
const second: ResumeSubmitTransport = {
submitToolApproval: jest.fn(async () => {}),
submitAskAnswer: jest.fn(async () => {}),
};
let transport: ResumeSubmitTransport | null = null;
const ChatWrapper = createWrapper(1000);
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<ChatWrapper>
<ResumeSubmitContext.Provider value={transport}>{children}</ResumeSubmitContext.Provider>
</ChatWrapper>
);
const { result, rerender } = renderHook(() => useResumeSubmit(), { wrapper: hostWrapper });
transport = first;
rerender();
await act(async () => result.current.submitAskAnswer('host-first', 'first'));
expect(first.submitAskAnswer).toHaveBeenCalledWith('host-first', 'first');
transport = second;
rerender();
await act(async () => result.current.submitAskAnswer('host-second', 'second'));
expect(second.submitAskAnswer).toHaveBeenCalledWith('host-second', 'second');
expect(mockAskMutate).not.toHaveBeenCalled();
transport = null;
rerender();
act(() => result.current.submitAskAnswer('chat-action', 'ordinary'));
expect(mockAskMutate).toHaveBeenCalledTimes(1);
expect(mockAskMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
actionId: 'chat-action',
answer: 'ordinary',
}),
expect.any(Object),
);
});
test.each(['tool', 'ask'] as const)(
'owns pending, retryable failure and success for %s host submissions across hook instances',
async (kind) => {
const first = deferred();
const retry = deferred();
const send = jest
.fn()
.mockImplementationOnce(() => first.promise)
.mockImplementationOnce(() => retry.promise);
const transport: ResumeSubmitTransport = { submitToolApproval: send, submitAskAnswer: send };
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ApprovalProvider>
<ResumeSubmitContext.Provider value={transport}>
{children}
</ResumeSubmitContext.Provider>
</ApprovalProvider>
</JotaiProvider>
);
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
ask: useAskSubmitStatus(),
first: useResumeSubmit(),
second: useResumeSubmit(),
}),
{ wrapper: hostWrapper },
);
const onSuccess = jest.fn();
const submit = (surface: 'first' | 'second') =>
kind === 'tool'
? result.current[surface].submitToolApproval('action')
: result.current[surface].submitAskAnswer('action', 'answer', { onSuccess });
const status = () =>
kind === 'tool'
? result.current.approval.getStatus('action')
: result.current.ask.getAskStatus('action');
act(() => {
result.current.approval.registerToolCall('action', 'tool');
result.current.approval.setDecision('action', 'tool', {
tool_call_id: 'tool',
decision: 'approve',
});
submit('first');
submit('second');
});
expect(send).toHaveBeenCalledTimes(1);
expect(status()).toBe('submitting');
await act(async () => {
first.reject(new Error('temporary'));
});
expect(status()).toBe('error');
expect(onSuccess).not.toHaveBeenCalled();
act(() => {
submit('second');
submit('first');
});
expect(send).toHaveBeenCalledTimes(2);
expect(status()).toBe('submitting');
await act(async () => {
retry.resolve();
});
expect(status()).toBe('submitted');
act(() => {
submit('first');
submit('second');
});
expect(send).toHaveBeenCalledTimes(2);
expect(onSuccess).toHaveBeenCalledTimes(kind === 'ask' ? 1 : 0);
},
);
test.each(['tool', 'ask'] as const)(
'keeps expired %s host submissions terminal and catches synchronous transport errors',
async (kind) => {
const send = jest
.fn<Promise<void>, []>()
.mockImplementationOnce(() => {
throw new Error('synchronous failure');
})
.mockRejectedValueOnce({ response: { status: 409 } });
const transport: ResumeSubmitTransport = { submitToolApproval: send, submitAskAnswer: send };
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ApprovalProvider>
<ResumeSubmitContext.Provider value={transport}>
{children}
</ResumeSubmitContext.Provider>
</ApprovalProvider>
</JotaiProvider>
);
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
ask: useAskSubmitStatus(),
submit: useResumeSubmit(),
}),
{ wrapper: hostWrapper },
);
const submit = () =>
kind === 'tool'
? result.current.submit.submitToolApproval('action')
: result.current.submit.submitAskAnswer('action', 'answer');
const status = () =>
kind === 'tool'
? result.current.approval.getStatus('action')
: result.current.ask.getAskStatus('action');
act(() => {
result.current.approval.registerToolCall('action', 'tool');
result.current.approval.setDecision('action', 'tool', {
tool_call_id: 'tool',
decision: 'approve',
});
});
await act(async () => submit());
expect(status()).toBe('error');
await act(async () => submit());
expect(status()).toBe('expired');
act(() => submit());
expect(send).toHaveBeenCalledTimes(2);
},
);
test('accepts only action identity and payload without requiring chat stream metadata', () => {
const hostWrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider>
<ApprovalProvider
pendingAction={{ actionId: pendingAction.actionId, payload: pendingAction.payload }}
>
{children}
</ApprovalProvider>
</JotaiProvider>
);
const { result } = renderHook(() => useApprovalContext(), { wrapper: hostWrapper });
expect(result.current.getRegisteredCount('action-1')).toBe(2);
expect(result.current.getLeadToolCallId('action-1')).toBe('call-1');
expect(result.current.isReady('action-1')).toBe(false);
});
test('synchronously deduplicates tool approval submissions and unlocks a retryable error', () => {
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
resume: 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',
});
});
act(() => {
result.current.resume.submitToolApproval('action-1');
result.current.resume.submitToolApproval('action-1');
});
expect(mockApprovalMutate).toHaveBeenCalledTimes(1);
expect(mockApprovalMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
generationCreatedAt: 1000,
actionId: 'action-1',
}),
expect.any(Object),
);
const firstOptions = mockApprovalMutate.mock.calls[0][1] as {
onError: (error: unknown) => void;
};
act(() => firstOptions.onError(new Error('temporary failure')));
act(() => {
result.current.resume.submitToolApproval('action-1');
result.current.resume.submitToolApproval('action-1');
});
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 }) => (
<JotaiProvider store={createStore()}>
<ApprovalProvider pendingAction={pendingAction}>{children}</ApprovalProvider>
</JotaiProvider>
);
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 }) => (
<JotaiProvider store={createStore()}>
<ApprovalProvider pendingAction={pendingAction}>
<ApprovalProvider>{children}</ApprovalProvider>
</ApprovalProvider>
</JotaiProvider>
);
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;
act(() => {
result.current.registerToolCall('action-1', 'call-1');
result.current.setDecision('action-1', 'call-1', decision);
});
act(() => result.current.unregisterToolCall('action-1', 'call-1'));
expect(result.current.getDecisions('action-1')).toEqual([]);
expect(result.current.getDecision('action-1', 'call-1')).toEqual(decision);
act(() => result.current.registerToolCall('action-1', 'call-1'));
expect(result.current.getDecisions('action-1')).toEqual([decision]);
expect(result.current.isReady('action-1')).toBe(true);
});
test('submits approval and ask-answer resumes without an epoch when none is known', () => {
const { result } = renderHook(
() => ({
approval: useApprovalContext(),
resume: useResumeSubmit(),
}),
{ wrapper: createWrapper(null) },
);
act(() => {
result.current.approval.registerToolCall('action-1', 'call-1');
result.current.approval.setDecision('action-1', 'call-1', {
tool_call_id: 'call-1',
decision: 'approve',
});
});
act(() => {
result.current.resume.submitToolApproval('action-1');
result.current.resume.submitAskAnswer('ask-1', 'answer');
});
expect(mockApprovalMutate).toHaveBeenCalledTimes(1);
expect(mockApprovalMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
actionId: 'action-1',
decisions: [{ tool_call_id: 'call-1', decision: 'approve' }],
}),
expect.any(Object),
);
expect(mockApprovalMutate.mock.calls[0][0]).not.toHaveProperty('generationCreatedAt');
expect(mockAskMutate).toHaveBeenCalledTimes(1);
expect(mockAskMutate.mock.calls[0][0]).toEqual(
expect.objectContaining({ conversationId: 'conversation-1', actionId: 'ask-1' }),
);
expect(mockAskMutate.mock.calls[0][0]).not.toHaveProperty('generationCreatedAt');
});
test('synchronously deduplicates ask answers and unlocks a retryable error', () => {
const { result } = renderHook(() => useResumeSubmit(), { wrapper });
act(() => {
result.current.submitAskAnswer('ask-1', 'answer');
result.current.submitAskAnswer('ask-1', 'answer');
});
expect(mockAskMutate).toHaveBeenCalledTimes(1);
expect(mockAskMutate).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: 'conversation-1',
generationCreatedAt: 1000,
actionId: 'ask-1',
answer: 'answer',
}),
expect.any(Object),
);
const firstOptions = mockAskMutate.mock.calls[0][1] as {
onError: (error: unknown) => void;
};
act(() => firstOptions.onError(new Error('temporary failure')));
act(() => {
result.current.submitAskAnswer('ask-1', 'answer');
result.current.submitAskAnswer('ask-1', 'answer');
});
expect(mockAskMutate).toHaveBeenCalledTimes(2);
});
});

View file

@ -0,0 +1,550 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useAtom, useStore } from 'jotai';
import type { Agents } from 'librechat-data-provider';
import type { Context, ReactNode } from 'react';
import type { ApprovalResumeHost } from '../../react/approval';
import type { AskAnswerStatus } from '../../react/parts/ask';
import { pendingApprovalActionFamily, useApprovalResumeHost } from '../../react/approval';
import { resolveAskUserQuestionPart } from '../../core/parts/questions';
import { askSubmitStatusAtom } from '../../react/parts/ask';
export interface ResumeSubmitTransport {
submitToolApproval: (
actionId: string,
decisions: Agents.ToolApprovalResolution[],
) => Promise<void>;
submitAskAnswer: (actionId: string, resolution: string | Record<string, string>) => Promise<void>;
}
/** Host-owned I/O; the shared hook owns selected payloads, submission locks and status. */
export const ResumeSubmitContext: Context<ResumeSubmitTransport | null> =
createContext<ResumeSubmitTransport | null>(null);
/** Shared read/write for the ask-answer submit status. */
export function useAskSubmitStatus(): {
getAskStatus: (actionId: string) => AskAnswerStatus;
setAskStatus: (actionId: string, status: AskAnswerStatus) => void;
} {
const [statusMap, setStatusMap] = useAtom(askSubmitStatusAtom);
const getAskStatus = useCallback(
(actionId: string): AskAnswerStatus => statusMap[actionId] ?? 'idle',
[statusMap],
);
const setAskStatus = useCallback(
(actionId: string, status: AskAnswerStatus) =>
setStatusMap((prev) => ({ ...prev, [actionId]: status })),
[setStatusMap],
);
return { getAskStatus, setAskStatus };
}
interface ApprovalContextValue {
/**
* Bumped whenever registrations or decisions change. Decisions live in refs
* (synchronous reads), so this is what makes the context value a NEW reference
* on each change; without it, consumers never re-render and never re-read
* `isReady`/`getLeadToolCallId` after an update.
*/
version: number;
/** Record (or clear) a card's decision for its tool_call within an action. */
setDecision: (
actionId: string,
toolCallId: string,
decision: Agents.ToolApprovalResolution | null,
) => 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. */
registerToolCall: (actionId: string, toolCallId: string) => void;
/** Drop a tool_call's registration when its card unmounts, so a resolved/removed
* card can't keep `isReady` false and wedge the batch submit. */
unregisterToolCall: (actionId: string, toolCallId: string) => void;
/** The first-registered tool_call for an action: the single card that owns
* the batch submit button (avoids N buttons across sibling cards). */
getLeadToolCallId: (actionId: string) => string | undefined;
/** Number of tool calls paused under an action (for a "1 of N" label). */
getRegisteredCount: (actionId: string) => number;
/** True once every registered tool_call in the action has a decision. */
isReady: (actionId: string) => boolean;
/** Lifecycle status for an action (so cards can disable / show messages). */
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. */
setAskAnswerDraft: (actionId: string, answer: string) => void;
}
const ApprovalContext = createContext<ApprovalContextValue | null>(null);
export interface ToolApprovalDecisionDraft {
active: Agents.ToolApprovalDecisionType | null;
/** With `active === 'approve'`: also approve this tool for the rest of the conversation. */
allowAlways?: boolean;
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 => {
const ctx = useContext(ApprovalContext);
return ctx ?? FALLBACK;
};
const FALLBACK: ApprovalContextValue = {
version: 0,
setDecision: () => undefined,
getDecision: () => undefined,
getDecisionDraft: () => undefined,
setDecisionDraft: () => undefined,
getDecisions: () => [],
registerToolCall: () => undefined,
unregisterToolCall: () => undefined,
getLeadToolCallId: () => undefined,
getRegisteredCount: () => 0,
isReady: () => false,
getStatus: () => 'idle',
setStatus: () => undefined,
beginToolSubmission: () => false,
endToolSubmission: () => undefined,
getAskAnswerDraft: () => '',
setAskAnswerDraft: () => undefined,
};
const isExpiredError = (error: unknown): boolean => {
const status = (error as { response?: { status?: number } } | undefined)?.response?.status;
return status === 409;
};
/**
* Coordinates human-in-the-loop decisions for a single response message.
*
* An action may pause multiple tool calls (same `actionId`); each `ToolApproval`
* card registers its `tool_call_id` and records a decision here, and the lead card
* submits ONCE with the full `decisions[]` covering every paused call (the server
* rejects a partial batch).
*
* Intentionally pure state. It does not read chat context, the agent store, or
* React Query. Message content renders in places without those providers (shared
* views, exports, tests), so the provider must be safe to mount anywhere. The
* context-dependent submit lives in {@link useResumeSubmit}, which the cards call,
* and which chooses the ordinary chat transport or an explicitly supplied host transport.
*/
export default function ApprovalProvider({
children,
pendingAction,
}: {
children: ReactNode;
pendingAction?: Pick<Agents.PendingAction, 'actionId' | 'payload'> | null;
}): ReactNode {
/** 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: ReactNode;
pendingAction?: Pick<Agents.PendingAction, 'actionId' | 'payload'> | 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 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 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, so re-render so they reflect it. */
rerender();
},
[rerender],
);
const unregisterToolCall = useCallback(
(actionId: string, toolCallId: string) => {
const counts = registeredRef.current.get(actionId);
const count = counts?.get(toolCallId);
if (!counts || count == null) {
return;
}
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
* phase label can resolve while an approval card is visible, moving
* that card through a nested phase segment; its transient unmount must
* not erase the user's selection. Unregistered decisions are excluded
* from submit/readiness and disappear with this provider. */
rerender();
},
[rerender],
);
const getLeadToolCallId = useCallback(
(actionId: string) =>
authoritativeRef.current.get(actionId)?.[0] ??
registeredRef.current.get(actionId)?.keys().next().value,
[],
);
const getRegisteredCount = useCallback(
(actionId: string) =>
authoritativeRef.current.get(actionId)?.length ??
registeredRef.current.get(actionId)?.size ??
0,
[],
);
const setDecision = useCallback(
(actionId: string, toolCallId: string, decision: Agents.ToolApprovalResolution | null) => {
const map = decisionsRef.current.get(actionId) ?? new Map();
if (decision == null) {
map.delete(toolCallId);
} else {
map.set(toolCallId, decision);
}
decisionsRef.current.set(actionId, map);
rerender();
},
[rerender],
);
const getDecision = useCallback(
(actionId: string, toolCallId: string) => decisionsRef.current.get(actionId)?.get(toolCallId),
[],
);
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 required = authoritativeRef.current.get(actionId) ?? [
...(registeredRef.current.get(actionId)?.keys() ?? []),
];
const decisions = decisionsRef.current.get(actionId);
if (required.length === 0 || decisions == null) {
return [];
}
return required.flatMap((toolCallId) => {
const decision = decisions.get(toolCallId);
return decision == null ? [] : [decision];
});
}, []);
const isReady = useCallback((actionId: string) => {
const required = authoritativeRef.current.get(actionId) ?? [
...(registeredRef.current.get(actionId)?.keys() ?? []),
];
const decided = decisionsRef.current.get(actionId);
if (required.length === 0) {
return false;
}
for (const toolCallId of required) {
if (!decided?.has(toolCallId)) {
return false;
}
}
return true;
}, []);
const getStatus = useCallback(
(actionId: string): AskAnswerStatus => statusByAction[actionId] ?? 'idle',
[statusByAction],
);
const setStatus = useCallback((actionId: string, status: AskAnswerStatus) => {
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) ?? '',
[],
);
const setAskAnswerDraft = useCallback((actionId: string, answer: string) => {
if (answer.length === 0) {
askAnswerDraftsRef.current.delete(actionId);
return;
}
askAnswerDraftsRef.current.set(actionId, answer);
}, []);
const value = useMemo<ApprovalContextValue>(
() => ({
version,
setDecision,
getDecision,
getDecisionDraft,
setDecisionDraft,
getDecisions,
registerToolCall,
unregisterToolCall,
getLeadToolCallId,
getRegisteredCount,
isReady,
getStatus,
setStatus,
beginToolSubmission,
endToolSubmission,
getAskAnswerDraft,
setAskAnswerDraft,
}),
[
version,
setDecision,
getDecision,
getDecisionDraft,
setDecisionDraft,
getDecisions,
registerToolCall,
unregisterToolCall,
getLeadToolCallId,
getRegisteredCount,
isReady,
getStatus,
setStatus,
beginToolSubmission,
endToolSubmission,
getAskAnswerDraft,
setAskAnswerDraft,
],
);
return <ApprovalContext.Provider value={value}>{children}</ApprovalContext.Provider>;
}
/** A host may reject asynchronously or throw before returning its request promise. */
function submitHost(
submit: () => Promise<void>,
callbacks: { onSuccess: () => void; onError: (error: unknown) => void },
): void {
try {
void submit().then(callbacks.onSuccess, callbacks.onError);
} catch (error) {
callbacks.onError(error);
}
}
/**
* Submit hook for the approval cards. The host supplies the resume body's agent fields and
* fires the resume request. This hook keeps the selected payload, the synchronous lock, and
* the status.
*
* Cards call it from live chat and from views with no chat provider (a subagent tool paused
* in an isolated activity surface, or a response review). With no host fields, the ordinary
* transport stays inert. An explicit transport supplies only I/O.
*
* Pass `host` when the caller builds the adapter itself (the app hook does, so a composer
* outside this provider can still resume). A provider host wins when one is present.
*/
export function useResumeSubmit(host: ApprovalResumeHost | null = null): {
submitToolApproval: (actionId: string) => void;
submitAskAnswer: (
actionId: string,
resolution: string | Record<string, string>,
opts?: { onSuccess?: () => void },
) => void;
} {
const transport = useContext(ResumeSubmitContext);
const providedHost = useApprovalResumeHost();
const resumeHost = providedHost ?? host;
const jotaiStore = useStore();
const { getDecisions, isReady, setStatus, beginToolSubmission, endToolSubmission } =
useApprovalContext();
/** Ask status lives in Jotai so it works from the composer (outside the
* provider); tool-approval status stays on the context. */
const { setAskStatus } = useAskSubmitStatus();
const submitToolApproval = useCallback(
(actionId: string) => {
const fields = transport ? null : (resumeHost?.readFields() ?? null);
const decisions = getDecisions(actionId);
if ((!transport && !fields) || decisions.length === 0 || !isReady(actionId)) return;
if (!beginToolSubmission(actionId)) return;
setStatus(actionId, 'submitting');
const callbacks = {
onSuccess: () => {
setStatus(actionId, 'submitted');
if (!fields) return;
const pendingAtom = pendingApprovalActionFamily(fields.conversationId);
if (jotaiStore.get(pendingAtom)?.actionId === actionId) jotaiStore.set(pendingAtom, null);
},
onError: (error: unknown) => {
const expired = isExpiredError(error);
if (!expired) endToolSubmission(actionId);
setStatus(actionId, expired ? 'expired' : 'error');
},
};
if (transport) {
submitHost(() => transport.submitToolApproval(actionId, decisions), callbacks);
} else if (fields && resumeHost) {
resumeHost.submitToolApproval({ ...fields, actionId, decisions }, callbacks);
}
},
[
beginToolSubmission,
endToolSubmission,
getDecisions,
isReady,
jotaiStore,
resumeHost,
setStatus,
transport,
],
);
const submitAskAnswer = useCallback(
(
actionId: string,
resolution: string | Record<string, string>,
opts?: { onSuccess?: () => void },
) => {
const fields = transport ? null : (resumeHost?.readFields() ?? null);
const isBatch = typeof resolution !== 'string';
const hasAnswer = isBatch ? Object.keys(resolution).length > 0 : resolution.length > 0;
if ((!transport && !fields) || !hasAnswer) return;
// Read the shared Jotai store synchronously: two rendered surfaces must
// not both enter before React publishes their next render.
const status = jotaiStore.get(askSubmitStatusAtom)[actionId];
if (status === 'submitting' || status === 'submitted' || status === 'expired') return;
setAskStatus(actionId, 'submitting');
const callbacks = {
onSuccess: () => {
setAskStatus(actionId, 'submitted');
if (!transport && resumeHost) {
// Only the ordinary chat transport owns synthetic timeline question parts.
const thread = resumeHost.readMessages();
if (thread) {
let changed = false;
const next = thread.messages.map((message) => {
const resolved = resolveAskUserQuestionPart(message, actionId, resolution);
if (resolved !== message) changed = true;
return resolved;
});
if (changed) thread.setMessages(next);
}
}
// A failed request must retain the caller's only copy of the answer.
opts?.onSuccess?.();
},
onError: (error: unknown) => {
setAskStatus(actionId, isExpiredError(error) ? 'expired' : 'error');
},
};
if (transport) {
submitHost(() => transport.submitAskAnswer(actionId, resolution), callbacks);
} else if (fields && resumeHost) {
resumeHost.submitAskAnswer(
{ ...fields, actionId, ...(isBatch ? { answers: resolution } : { answer: resolution }) },
callbacks,
);
}
},
[jotaiStore, resumeHost, setAskStatus, transport],
);
return { submitToolApproval, submitAskAnswer };
}

View file

@ -1,7 +1,9 @@
import { createElement, createContext, useContext } from 'react';
import { atomFamily } from 'jotai/utils';
import { atom, useAtomValue } from 'jotai';
import { Constants } from 'librechat-data-provider';
import type { Agents } from 'librechat-data-provider';
import type { Agents, TEphemeralAgent, TMessage } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import type { Family } from './steer/family';
/**
@ -41,3 +43,72 @@ export function useComposerPresentsApproval(
pendingAction.payload.type === 'tool_approval'
);
}
/** Fields the ordinary chat resume sends so the server can rebuild the paused agent. */
export interface ApprovalResumeFields {
conversationId: string;
/** Exact paused generation, when the client has observed it. */
generationCreatedAt?: number;
endpoint?: string | null;
endpointType?: string | null;
agent_id?: string | null;
model?: string | null;
spec?: string | null;
promptPrefix?: string | null;
ephemeralAgent?: TEphemeralAgent | null;
}
export type ApprovalResumeCallbacks = {
onSuccess: () => void;
onError: (error: unknown) => void;
};
/**
* Ordinary chat I/O for a tool approval or an ask answer: the conversation fields, the resume
* request, and the thread an ask answer patches locally. Absent when this view has no live
* conversation. An explicit resume transport still wins over this host.
*
* This is not a member of the steer or stream hosts. Those providers throw when they are
* missing, and this hook also runs from the composer, a response review, and shared renders,
* where it must stay inert instead of throwing.
*/
export interface ApprovalResumeHost {
/** Resume fields for the active conversation, or null when there is nothing to resume. */
readFields: () => ApprovalResumeFields | null;
submitToolApproval: (
body: ApprovalResumeFields & {
actionId: string;
decisions: Agents.ToolApprovalResolution[];
},
callbacks: ApprovalResumeCallbacks,
) => void;
submitAskAnswer: (
body: ApprovalResumeFields & {
actionId: string;
answer?: string;
answers?: Record<string, string>;
},
callbacks: ApprovalResumeCallbacks,
) => void;
/** The thread the ordinary transport may patch after an ask answer. */
readMessages: () => {
messages: TMessage[];
setMessages: (messages: TMessage[]) => void;
} | null;
}
const ApprovalResumeHostContext = createContext<ApprovalResumeHost | null>(null);
export function ApprovalResumeHostProvider({
host,
children,
}: {
host: ApprovalResumeHost;
children?: ReactNode;
}): ReactNode {
return createElement(ApprovalResumeHostContext.Provider, { value: host }, children);
}
export function useApprovalResumeHost(): ApprovalResumeHost | null {
return useContext(ApprovalResumeHostContext);
}