From 712edc08fe686e1bf72b808c720e554bd6b8cae3 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:13:03 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=9B=82=20refactor:=20Move=20the=20Tool=20?= =?UTF-8?q?Approval=20Review=20Into=20@librechat/chat=20(#18133)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .../Chat/Messages/Content/ApprovalContext.tsx | 647 +++--------------- .../__tests__/ApprovalContext.test.tsx | 496 ++------------ .../src/components/Chat/approval/Review.tsx | 324 +++------ .../Chat/approval/__tests__/Review.test.tsx | 149 ++-- .../response-review-lifecycle.spec.ts | 6 +- packages/chat/src/components.ts | 20 + .../chat/src/components/approval/Review.tsx | 327 +++++++++ .../approval/__tests__/Review.spec.tsx | 311 +++++++++ .../approval/__tests__/context.spec.tsx | 523 ++++++++++++++ .../chat/src/components/approval/context.tsx | 550 +++++++++++++++ packages/chat/src/react/approval.ts | 73 +- 11 files changed, 2081 insertions(+), 1345 deletions(-) create mode 100644 packages/chat/src/components/approval/Review.tsx create mode 100644 packages/chat/src/components/approval/__tests__/Review.spec.tsx create mode 100644 packages/chat/src/components/approval/__tests__/context.spec.tsx create mode 100644 packages/chat/src/components/approval/context.tsx diff --git a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx index 1e06faeddc..41eba557b0 100644 --- a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx +++ b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx @@ -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; - submitAskAnswer: (actionId: string, resolution: string | Record) => Promise; -} - -/** Host-owned I/O; the shared hook owns selected payloads, submission locks and status. */ -export const ResumeSubmitContext = createContext(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(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 | 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 {children}; -} - -function ApprovalStateProvider({ - children, - pendingAction, -}: { - children: React.ReactNode; - pendingAction?: Pick | 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>()); - const decisionDraftsRef = useRef(new Map>()); - const registeredRef = useRef(new Map>()); - /** Server-owned batch membership. Unlike card registrations, this survives - * folding, virtualization, late tool parts, and a second composer surface. */ - const authoritativeRef = useRef(new Map()); - const authoritativeActionIdRef = useRef(null); - const askAnswerDraftsRef = useRef(new Map()); - const submittingToolActionIdsRef = useRef(new Set()); - const [version, bump] = useState(0); - const rerender = useCallback(() => bump((v) => v + 1), []); - const [statusByAction, setStatusByAction] = useState>({}); - - 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(); - 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( - () => ({ - 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 {children}; -} - -/** A host may reject asynchronously or throw before returning its request promise. */ -function submitHost( - submit: () => Promise, - 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( + () => ({ + 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, - 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); } diff --git a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx index 3389b9d47d..e7d52fe31a 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx @@ -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; const createWrapper = (generationCreatedAt: number | null) => @@ -42,488 +44,96 @@ const createWrapper = (generationCreatedAt: number | null) => return created; }); return ( - - + + {children} - - + + ); }; -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(); - const transport: ResumeSubmitTransport = { - submitToolApproval: jest.fn(() => pending.promise), - submitAskAnswer: jest.fn(async () => {}), - }; - const onSuccess = jest.fn(); - const hostWrapper = ({ children }: { children: React.ReactNode }) => ( - - - {children} - - - ); - 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 }) => ( - - {children} - - ); - 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(); - const retry = Promise.withResolvers(); - const send = jest - .fn() - .mockImplementationOnce(() => first.promise) - .mockImplementationOnce(() => retry.promise); - const transport: ResumeSubmitTransport = { submitToolApproval: send, submitAskAnswer: send }; - const hostWrapper = ({ children }: { children: React.ReactNode }) => ( - - - - {children} - - - - ); - 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, []>() - .mockImplementationOnce(() => { - throw new Error('synchronous failure'); - }) - .mockRejectedValueOnce({ response: { status: 409 } }); - const transport: ResumeSubmitTransport = { submitToolApproval: send, submitAskAnswer: send }; - const hostWrapper = ({ children }: { children: React.ReactNode }) => ( - - - - {children} - - - - ); - 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 }) => ( - - - {children} - - - ); - 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 }) => ( - - - {children} - - - ); - 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 }) => ( - - - - {children} - - - - ); - 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 }) => ( + + {children} + + ), }); - 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), + ); }); }); diff --git a/client/src/components/Chat/approval/Review.tsx b/client/src/components/Chat/approval/Review.tsx index 9ea0a7f0a9..6e4d630462 100644 --- a/client/src/components/Chat/approval/Review.tsx +++ b/client/src/components/Chat/approval/Review.tsx @@ -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['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, - localize: ReturnType, -): 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; }) { 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) => { - 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) => , + [], + ); + const renderCollapse = useCallback( + ({ onClick, label }: { onClick: () => void; label: string }) => ( + + ), + [], + ); return ( -
-
-
-

- {localize(reviews.length === 1 ? 'com_ui_review_action' : 'com_ui_review_actions', { - 0: reviews.length, - })} -

- -
-
- {reviews.map(({ request, config, preview }, index) => ( -
-
-

- {reviews.length > 1 - ? `${index + 1}. ${previewTitle(preview, localize)}` - : previewTitle(preview, localize)} -

-

{localize(KIND_LABELS[preview.kind])}

-
-
-                {preview.body || localize('com_ui_no_arguments')}
-              
- {preview.truncated && ( -

- {localize('com_ui_preview_truncated')} -

- )} - {config != null ? ( - - ) : ( -

-

- )} -
- ))} -
-
- - {localize('com_ui_decisions_selected', { - 0: decisions.length, - 1: reviews.length, - })} - -
- {(status === 'expired' || status === 'error') && ( - - - )} - -
-
-
-
+ + + ); }); +/** 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; }) { 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; + expanded: boolean; + onClick: () => void; + children: ReactNode; + }) => ( + + ), + [], + ); return ( - + ); }); diff --git a/client/src/components/Chat/approval/__tests__/Review.test.tsx b/client/src/components/Chat/approval/__tests__/Review.test.tsx index fb844f2b8a..b79e072c04 100644 --- a/client/src/components/Chat/approval/__tests__/Review.test.tsx +++ b/client/src/components/Chat/approval/__tests__/Review.test.tsx @@ -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 = { 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; + 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( - - - - + + + + + + + , ); - 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(null); - return ( - <> - - - - ); - } - - const renderPanel = () => { - const jotaiStore = createStore(); - jotaiStore.set(pendingApprovalActionFamily('conversation-1'), pendingAction); - render( - - - - - - - , - ); - 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(); - }); - }); }); diff --git a/e2e/specs/mock/scenarios/response-review-lifecycle.spec.ts b/e2e/specs/mock/scenarios/response-review-lifecycle.spec.ts index d37d8ab816..3b3d85cb70 100644 --- a/e2e/specs/mock/scenarios/response-review-lifecycle.spec.ts +++ b/e2e/specs/mock/scenarios/response-review-lifecycle.spec.ts @@ -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(); @@ -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(); } diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 05c0f255e9..f1a9b088a1 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -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'; diff --git a/packages/chat/src/components/approval/Review.tsx b/packages/chat/src/components/approval/Review.tsx new file mode 100644 index 0000000000..72ec7d6d61 --- /dev/null +++ b/packages/chat/src/components/approval/Review.tsx @@ -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; +}['translate']; + +/** One paused call, drawn by the host's tool-approval card. */ +export type ApprovalRequestRenderProps = { + approval: NonNullable; + 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['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, + 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; + 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(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 ( +
+
+
+

+ {localize(reviews.length === 1 ? 'com_ui_review_action' : 'com_ui_review_actions', { + 0: reviews.length, + })} +

+ +
+
+ {reviews.map(({ request, config, preview }, index) => ( +
+
+

+ {reviews.length > 1 + ? `${index + 1}. ${previewTitle(preview, localize)}` + : previewTitle(preview, localize)} +

+

{localize(KIND_LABELS[preview.kind])}

+
+
+                {preview.body || localize('com_ui_no_arguments')}
+              
+ {preview.truncated && ( +

+ {localize('com_ui_preview_truncated')} +

+ )} + {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, + }) + ) : ( +

+

+ )} +
+ ))} +
+
+ + {localize('com_ui_decisions_selected', { + 0: decisions.length, + 1: reviews.length, + })} + +
+ {(status === 'expired' || status === 'error') && ( + + + )} + +
+
+
+
+ ); +}); + +export type PendingToolApprovalButtonProps = { + conversationId: string; + triggerRef?: RefObject; + localize: ApprovalReviewCopy; + /** Host-drawn composer toggle. Omitted, the package draws a quiet button. */ + renderToggle?: (props: { + ref?: RefObject; + 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 = ( + <> +