import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { dequal } from "dequal"; import { ChevronLeftIcon, ChevronRightIcon, ShieldCheckIcon } from "lucide-react"; import { OpenGeniApiError, toolReviewDetails, type ToolActionReview } from "@opengeni/sdk"; import type { PendingApproval } from "../approvals"; import { cn } from "../lib/cn"; import { useErrorMessage } from "../lib/error-message"; import { approvalAnswerLabels, approvalToolName, formatApprovalToolName, pendingApprovalReview, } from "../approval-review-model"; import { ToolActionReviewCard, ToolActionReviewDetails, ToolReviewFrame, DeclineButton, UNRECOVERABLE_TEXT, type ToolReviewDetailsLoader, } from "./tool-action-review"; import { DecisionActions } from "./decision-card"; import { useOpenGeniText, type OpenGeniText } from "../messages/runtime"; import { McpElicitationRequest } from "./mcp-elicitation-request"; import type { McpElicitationAnswer, McpElicitationContent, } from "@opengeni/contracts/mcp-elicitation-model"; export type ApprovalSurfaceMessages = { title: string; description: string; approve: string; reject: string; approving: string; rejecting: string; formatToolName: (name: string) => string; showDetails?: string | undefined; hideDetails?: string | undefined; }; export const defaultApprovalSurfaceMessages = (t: OpenGeniText): ApprovalSurfaceMessages => ({ title: t("approvalSurface.approvalNeeded"), description: t("approvalSurface.reviewTheActionBeforeIt"), approve: t("approvalSurface.approveAction"), reject: t("approvalSurface.decline"), approving: t("approvalSurface.approving"), rejecting: t("approvalSurface.declining"), formatToolName: (name) => formatApprovalToolName(t, name), showDetails: t("approvalSurface.viewFullDetails"), hideDetails: t("approvalSurface.backToReview"), }); export type ApprovalSurfaceProps = { approvals: PendingApproval[]; /** * `answer` is present when the approval answers its MCP server's questions * (`approval.elicitation`); send it with the decision. */ onApprove: (approval: PendingApproval, answer?: McpElicitationAnswer) => void | Promise; onReject: (approval: PendingApproval) => void | Promise; responding?: boolean | undefined; error?: string | Error | null | undefined; messages?: Partial | undefined; renderApproval?: ((approval: PendingApproval) => ReactNode) | undefined; /** Authenticated server facts; hosts need not import any web-app code. */ loadReview?: ((approval: PendingApproval) => Promise) | undefined; loadDetails?: ToolReviewDetailsLoader | undefined; onViewDetails?: ((review: ToolActionReview, path: string) => void) | undefined; selectedApprovalId?: string | null | undefined; onSelectedApprovalChange?: ((id: string) => void) | undefined; className?: string | undefined; }; export type ApprovalField = { key: string; label: string; value: string }; /** Backoff for re-reading a waiting review that offered no decision. */ const UNDECIDABLE_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 8_000]; function reviewUndecidable(review: ToolActionReview | undefined): review is ToolActionReview { return ( review?.status === "pending" && !review.availableActions.includes("approve") && !review.availableActions.includes("reject") ); } /** Hosts provide decisions; this surface never mutates the approved payload. */ export function ApprovalSurface({ approvals, onApprove, onReject, responding, error, messages: overrides, renderApproval, loadReview, loadDetails, onViewDetails, selectedApprovalId, onSelectedApprovalChange, className, }: ApprovalSurfaceProps) { const t = useOpenGeniText(); const messages = { ...defaultApprovalSurfaceMessages(t), ...overrides }; const formatError = useErrorMessage(); const [pending, setPending] = useState<{ id: string; decision: "approve" | "reject"; } | null>(null); const pendingRef = useRef(null); const [decisionError, setDecisionError] = useState<{ cause: unknown } | null>(null); const [localSelectedId, setLocalSelectedId] = useState(null); const selectedId = selectedApprovalId === undefined ? localSelectedId : selectedApprovalId; const setSelectedId = (id: string) => { setLocalSelectedId(id); onSelectedApprovalChange?.(id); }; const surface = useRef(null); useEffect(() => { if (pending && !approvals.some((approval) => approval.id === pending.id)) { pendingRef.current = null; setPending(null); // Hand focus to the next card without moving the view: a reader at the // bottom already sees it, and one who scrolled up keeps their place. requestAnimationFrame(() => surface.current?.querySelector("h3")?.focus({ preventScroll: true }), ); } }, [approvals, pending]); if (!approvals.length) return null; const selectedIndex = Math.max( 0, approvals.findIndex((approval) => approval.id === selectedId), ); const selected = approvals[selectedIndex]!; const decide = async ( approval: PendingApproval, decision: "approve" | "reject", answer?: McpElicitationAnswer, ) => { if (responding || pendingRef.current) return; pendingRef.current = approval.id; setPending({ id: approval.id, decision }); setDecisionError(null); try { await (decision === "approve" ? answer ? onApprove(approval, answer) : onApprove(approval) : onReject(approval)); } catch (cause) { if (pendingRef.current === approval.id) { pendingRef.current = null; setPending(null); setDecisionError({ cause }); } } }; const errorText = decisionError ? formatError(decisionError.cause) : error instanceof Error ? formatError(error) : error; return (
{approvals.length > 1 && ( )}
{[selected].map((approval) => ( void decide(approval, "approve")} onAnswer={(content) => approval.elicitation ? void decide(approval, "approve", { content, elicitationRound: approval.elicitation.round, }) : undefined } onReject={() => void decide(approval, "reject")} /> ))}
{errorText && (

{errorText}

)}
); } function ApprovalRequest({ approval, loadReview, loadDetails, messages, custom, onViewDetails, onAnswer, ...actions }: { approval: PendingApproval; loadReview: ApprovalSurfaceProps["loadReview"]; messages: ApprovalSurfaceMessages; loadDetails: ToolReviewDetailsLoader | undefined; custom: ReactNode; onViewDetails: ApprovalSurfaceProps["onViewDetails"]; submitting: "approve" | "reject" | null; disabled: boolean; onApprove: () => void; onAnswer: (content: McpElicitationContent) => void; onReject: () => void; }) { const t = useOpenGeniText(); const [retry, setRetry] = useState(0); // A server's question is answered from the approval itself; there is no // saved review of a call that has already started. const reviewLoader = approval.elicitation ? undefined : loadReview; // Event projection recreates the same approval on unrelated timeline updates. // Keep one request for equal facts, but never reuse it across changed facts, // an explicit retry, or a loader change (the host's client/access boundary). const requestRef = useRef({ approval, loadReview: reviewLoader, retry }); if ( requestRef.current.loadReview !== reviewLoader || requestRef.current.retry !== retry || !dequal(requestRef.current.approval, approval) ) { requestRef.current = { approval, loadReview: reviewLoader, retry }; } const request = requestRef.current; const [result, setResult] = useState<{ request: typeof request; review?: ToolActionReview; failed?: boolean; legacy?: boolean; denied?: boolean; } | null>(null); // Hide stale facts during render, before passive effect cleanup can run. A // re-read of the same undecided action (same facts, same loader) keeps its // notice up meanwhile. const current = result?.request === request || (result !== null && result.request.loadReview === request.loadReview && reviewUndecidable(result.review) && dequal(result.request.approval, request.approval)) ? result : null; const loaded = current?.review; const failed = current?.failed; const legacy = current?.legacy; const denied = current?.denied; // Still waiting, yet the saved review offers no decision: it was read while // the chat was between states. Never a silent footer: say so, offer a retry, // and re-read it on its own a few times. const undecidable = reviewUndecidable(loaded); const undecidableRetries = useRef(0); const [detailPath, setDetailPath] = useState(null); useEffect(() => { let active = true; if (request.loadReview) void request.loadReview(request.approval).then( (review) => { if (active) { setResult( review.id !== request.approval.id ? { request, failed: true } : { request, review }, ); } }, (error) => { if (active) { // 404: no saved review (older or non-connector actions); use the // approval's own arguments. 401/403: this person cannot review it. if (error instanceof OpenGeniApiError && error.status === 404) setResult({ request, legacy: true }); else if ( error instanceof OpenGeniApiError && (error.status === 401 || error.status === 403) ) setResult({ request, failed: true, denied: true }); else setResult({ request, failed: true }); } }, ); return () => { active = false; }; }, [request]); // Each automatic re-read waits from when the previous read answered. const readSettled = result?.request === request; useEffect(() => { if ( !undecidable || !readSettled || undecidableRetries.current >= UNDECIDABLE_RETRY_DELAYS_MS.length ) return; const delay = UNDECIDABLE_RETRY_DELAYS_MS[undecidableRetries.current]!; const timer = setTimeout(() => { undecidableRetries.current += 1; setRetry((value) => value + 1); }, delay); return () => clearTimeout(timer); }, [undecidable, readSettled, request]); const stableApproval = request.approval; const { formatToolName, approve: approveLabel } = messages; const toolName = approvalToolName(stableApproval); const answer = approvalAnswerLabels(t, toolName); const fallback = useMemo( () => pendingApprovalReview(stableApproval, { formatToolName, approveLabel }), [stableApproval, formatToolName, approveLabel], ); const loadLegacyDetails = useCallback( async (value, path, offset) => ({ version: 1, id: value.id, actionDigest: value.actionDigest, ...toolReviewDetails(stableApproval.arguments, undefined, path, offset, 25, toolName), }), [stableApproval, toolName], ); if (reviewLoader && !loaded && !failed && !legacy) return (