import { useMemo, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { ArrowUpRight, Check, Loader2, MoreHorizontal, ShieldQuestion, X } from "lucide-react"; import type { Agent, ToolActionRequestListItem } from "@paperclipai/shared"; import { googleWorkspaceToolTitle, humanizeConnectionDisplayName } from "@paperclipai/shared"; import { useCompany } from "@/context/CompanyContext"; import { useToast } from "@/context/ToastContext"; import { queryKeys } from "@/lib/queryKeys"; import { timeAgo } from "@/lib/timeAgo"; import { issuesApi } from "@/api/issues"; import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { toolsApi } from "@/api/tools"; import { Button } from "@/components/ui/button"; import { MarkdownBody } from "@/components/MarkdownBody"; import { describeError } from "@/api/errors"; import { agentsApi } from "@/api/agents"; import { Link } from "@/lib/router"; import { cn } from "@/lib/utils"; import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; import { AgentAvatar } from "@/components/AgentAvatar"; import { DecisionCardFooter } from "@/components/DecisionCardFooter"; import { NeedsYouPanel, NeedsYouPanelNote, NeedsYouPanelRow } from "@/components/coordinator/NeedsYouCardKit"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { AppLogo } from "./AppLogo"; /** * "Ask first" review queue (M1b float / M9 card, PAP-10859). * * Renders pending `tool_action_requests` as prosumer cards with three choices: * • Allow once → approve this single request * • Always allow → approve + create a trust rule (won't ask again) * • Decline → reject this request * * Pass `connectionId` to scope the queue to a single app (App detail); omit it * to show every pending request (Needs attention page). * * `layout="decisions"` draws each request as a decision card with no section * heading, for the Reviews page, which carries its own title and count. */ export function ReviewQueueCard({ connectionId, emptyState = "hidden", heading = "Waiting for your OK", plain = false, layout = "queue", }: { connectionId?: string; emptyState?: "hidden" | "reassure"; heading?: string; plain?: boolean; layout?: "queue" | "decisions"; }) { const { selectedCompanyId } = useCompany(); const query = useQuery({ queryKey: queryKeys.tools.actionRequests(selectedCompanyId ?? "__none__", "pending"), queryFn: () => toolsApi.listActionRequests(selectedCompanyId!, "pending"), enabled: !!selectedCompanyId, refetchInterval: 20_000, }); const view = useQueryView(query); const items = useMemo(() => { const all = query.data?.actionRequests ?? []; return connectionId ? all.filter((item) => item.connectionId === connectionId) : all; }, [query.data, connectionId]); const decisions = layout === "decisions"; const agentsQuery = useQuery({ queryKey: queryKeys.agents.list(selectedCompanyId ?? "__none__"), queryFn: () => agentsApi.list(selectedCompanyId!), enabled: decisions && !!selectedCompanyId && items.some((item) => item.requestedByAgentId), }); const agents = useMemo(() => indexAgentsById(agentsQuery.data ?? []), [agentsQuery.data]); if (!selectedCompanyId) return null; if (query.isLoading || view.kind === "reconnecting") return null; if (view.kind === "error") return ; if (items.length === 0) { if (emptyState === "hidden") return null; return (
Nothing is waiting for your OK right now.
); } if (decisions) { return ( ); } return (

{heading}

{items.length}
{items.map((item) => ( ))}
); } function ReviewRow({ companyId, item, plain, decision = false, agent = null, }: { companyId: string; item: ToolActionRequestListItem; plain: boolean; decision?: boolean; agent?: Agent | null; }) { const queryClient = useQueryClient(); const { pushToast } = useToast(); const [resolving, setResolving] = useState(null); const interactionQuery = useQuery({ queryKey: queryKeys.issues.interactions(item.request.issueId ?? "__none__"), queryFn: () => issuesApi.listInteractions(item.request.issueId!), enabled: Boolean(item.request.issueId && item.request.interactionId), }); const linkedInteraction = interactionQuery.data?.find(row => row.id === item.request.interactionId); const invalidate = () => { queryClient.invalidateQueries({ queryKey: queryKeys.tools.actionRequests(companyId, "pending") }); queryClient.invalidateQueries({ queryKey: queryKeys.apps.attention(companyId) }); queryClient.invalidateQueries({ queryKey: queryKeys.tools.trustRules(companyId) }); if (item.request.issueId) queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(item.request.issueId) }); }; const allowOnce = useMutation({ mutationFn: () => toolsApi.approveActionRequest(companyId, item.request.id), onMutate: () => setResolving("allow"), onSuccess: () => { pushToast({ title: "Allowed once", body: `${actionLabel(item)} can run this time.`, tone: "success" }); invalidate(); }, onError: (error) => { invalidate(); failToast(pushToast, error); }, onSettled: () => setResolving(null), }); const alwaysAllow = useMutation({ mutationFn: async () => { return toolsApi.approveActionRequest(companyId, item.request.id, true); }, onMutate: () => setResolving("always"), onSuccess: () => { pushToast({ title: "Always allowed", body: `${actionLabel(item)} won’t ask again.`, tone: "success", }); invalidate(); queryClient.invalidateQueries({ queryKey: queryKeys.tools.trustRules(companyId) }); }, onError: (error) => { invalidate(); failToast(pushToast, error); }, onSettled: () => setResolving(null), }); const decline = useMutation({ mutationFn: () => toolsApi.declineActionRequest(companyId, item.request.id), onMutate: () => setResolving("decline"), onSuccess: () => { pushToast({ title: "Declined", body: `${actionLabel(item)} won’t run.`, tone: "info" }); invalidate(); }, onError: (error) => { invalidate(); failToast(pushToast, error); }, onSettled: () => setResolving(null), }); if (decision && interactionQuery.isLoading) { return (

Loading request…

); } if (linkedInteraction) { const card = { try { await toolsApi.approveActionRequest(companyId, item.request.id, rememberAction); } finally { invalidate(); } }} onRejectInteraction={async (_interaction, reason) => { try { await toolsApi.declineActionRequest(companyId, item.request.id, reason); } finally { invalidate(); } }} />; return decision ?
{card}
: card; } const busy = resolving !== null; const preview = item.request.previewMarkdown?.trim(); const canAlwaysAllow = Boolean(item.requestedByAgentId && item.connectionId && !item.request.approvalId); if (decision) { const action = actionLabel(item); const app = item.applicationName ? humanizeConnectionDisplayName(item.applicationName) : null; const risk = item.riskLevel ? RISK_LABELS[item.riskLevel] : null; return (
Approve tool access
{agent ? ( from {agent.name} ) : null} {canAlwaysAllow ? ( alwaysAllow.mutate()}> Always allow This agent can run this action on this connection without asking again. ) : null}

{app ? `${action} in ${app}` : action}

{app ? `${action} is set to Ask first in ${app}, so it waits for your OK.` : "This action is set to Ask first, so it waits for your OK."} Allow once runs it now.

{app ? ( } title={app} meta={<>{action}{risk ? <> · {risk.label} : null}} /> ) : null} {preview ?
{preview}
: null} {agent ? Requested by {agent.name}. : null}
{agent ? `Open task · Chat with ${agent.name}` : "Open task"} ) : undefined} >
); } return (
{actionLabel(item)} {item.applicationName && ( in {humanizeConnectionDisplayName(item.applicationName)} )} · asked {timeAgo(item.request.createdAt)}
{preview ? (
{preview}
) : (

An agent wants to run this action. Your connection policy requires approval first.

)} {item.requestedByAgentId && item.connectionId && !item.request.approvalId ?

Always allow lets this agent use this action with different arguments on this connection, within the current project when present.

: null}
{item.requestedByAgentId && item.connectionId && !item.request.approvalId ? : null}
); } const RISK_LABELS: Record, { label: string; danger: boolean }> = { low: { label: "Low risk", danger: false }, medium: { label: "Medium risk", danger: false }, high: { label: "High risk", danger: true }, critical: { label: "Critical risk", danger: true }, read: { label: "Reads data", danger: false }, write: { label: "Changes data", danger: false }, destructive: { label: "Destructive", danger: true }, }; export function indexAgentsById(agents: readonly T[]): Map { const byId = new Map(); for (const agent of agents) byId.set(agent.id, agent); return byId; } function actionLabel(item: ToolActionRequestListItem): string { if (!item.toolTitle && !item.toolName) return "This action"; return humanizeConnectionDisplayName(item.toolName ?? "", { title: googleWorkspaceToolTitle(item.toolName ?? "", item.toolTitle) }); } function failToast( pushToast: ReturnType["pushToast"], error: unknown, ) { pushToast({ title: "Couldn’t save that", body: describeError(error).body, tone: "error", }); }