import { useId, useMemo, useState } from "react"; import { useQueries, useQuery } from "@tanstack/react-query"; import { Link } from "react-router-dom"; import { Inbox, Loader2 } from "lucide-react"; import type { CompanySecretProviderConfig, SecretProposalStatus, SecretProposalView, } from "@paperclipai/shared"; import { AgentAvatar } from "@/components/AgentAvatar"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { NativeSelect } from "@/components/ui/select"; import { secretsApi } from "../../api/secrets"; import { queryKeys } from "../../lib/queryKeys"; import { deliveryModeForConfigPath } from "../../lib/secret-delivery"; import { cn, relativeTime } from "../../lib/utils"; import { EmptyState } from "../../components/EmptyState"; import { FingerprintChip, ProposalJustification, bindingEnvKey, bindingSecretLabel, useProposalDecision, } from "./proposal-review"; const DECIDED_STATUSES = ["approved", "rejected", "expired"] as const satisfies readonly SecretProposalStatus[]; const DECIDED_LIMIT = 10; /** ISO expiry → "Expires in 12d" / "Expires in 5h" / "Expired". */ function expiryLabel(expiresAt: string): { text: string; urgent: boolean } | null { const ms = new Date(expiresAt).getTime() - Date.now(); if (Number.isNaN(ms)) return null; if (ms <= 0) return { text: "Expired", urgent: true }; const hours = Math.floor(ms / 3_600_000); if (hours < 24) return { text: `Expires in ${hours}h`, urgent: true }; const days = Math.floor(hours / 24); return { text: `Expires in ${days}d`, urgent: days <= 2 }; } /** Trim a typed secret name and drop stray leading/trailing slashes. */ function normalizeSecretName(value: string): string { return value.trim().replace(/^\/+|\/+$/g, ""); } /** " wants to save a new secret, " and its access equivalents. */ function RequestSentence({ proposal }: { proposal: SecretProposalView }) { const proposer = {proposal.proposedBy.name}; if (proposal.kind === "secret") { return ( <> {proposer} wants to save a new secret,{" "} {proposal.proposedName ?? "unnamed"} ); } const secret = {bindingSecretLabel(proposal).name}; if (proposal.target && proposal.target.id !== proposal.proposedBy.id) { return ( <> {proposer} wants {proposal.target.name} to use {secret} ); } return ( <> {proposer} wants to use {secret} ); } /** One line saying how an approved secret would reach the agent. */ function DeliveryLine({ proposal }: { proposal: SecretProposalView }) { const mode = deliveryModeForConfigPath(proposal.configPath); const alias = bindingEnvKey(proposal); const code = {alias}; const agent = proposal.target?.name ?? "the agent"; return (

{mode === "env" ? ( <>It would be available in {agent}’s runs as the environment variable {code}. ) : mode === "api" ? ( <>{agent} could ask for it during a run as {code}. It is never written to the environment. ) : ( <>It would be provided through {agent}’s settings. )}{" "} Access is granted with your permissions.

); } function PendingProposal({ proposal, companyId, vaults, readAs, }: { proposal: SecretProposalView; companyId: string; /** Vaults a new secret can be stored in. */ vaults: CompanySecretProviderConfig[]; /** Environment variable names that pending access requests would expose this new secret as. */ readAs: string[]; }) { const fieldId = useId(); const isSecret = proposal.kind === "secret"; const canDecide = proposal.viewerCanApprove; const defaultVaultId = vaults.find((vault) => vault.isDefault)?.id ?? ""; const [name, setName] = useState(proposal.proposedName ?? ""); const [description, setDescription] = useState(proposal.proposedDescription ?? ""); const [editingDescription, setEditingDescription] = useState(Boolean(proposal.proposedDescription)); // "" stores the secret in the default vault. const [vaultId, setVaultId] = useState(defaultVaultId); // Access to a secret that is itself still waiting can only be approved together with it. const needsSecret = Boolean(proposal.secretProposalId); const [alsoSaveSecret, setAlsoSaveSecret] = useState(needsSecret); const [rejecting, setRejecting] = useState(false); const [reason, setReason] = useState(""); const decision = useProposalDecision(companyId); const expiry = expiryLabel(proposal.expiresAt); const secretName = normalizeSecretName(name); const secretLabel = bindingSecretLabel(proposal).name; const approve = () => { decision.clearError(); if (isSecret) { decision.approve(proposal, { overrides: { name: secretName, description: description.trim() || null, providerConfigId: vaultId || null, }, }); return; } decision.approve(proposal, { cascade: alsoSaveSecret || undefined }); }; return (
  • {proposal.originIssue ? ( <> While working on{" "} “{proposal.originIssue.title}” {" · "} ) : null} {relativeTime(proposal.createdAt)} {expiry ? ( <> {" · "} {expiry.text} ) : null}

    {isSecret ? (
    {vaults.length + (defaultVaultId ? 0 : 1) > 1 ? ( ) : null}
    {editingDescription ? ( ) : canDecide ? ( ) : null}

    {readAs.length > 0 ? ( <> Agents given access will read it as{" "} {readAs.map((key, index) => ( {index > 0 ? ", " : null} {key} ))} .{" "} ) : null} The value stays hidden and is saved exactly as the agent recorded it. Its fingerprint lets you confirm it with the agent:{" "}

    ) : (
    {needsSecret ? ( ) : null}
    )} {decision.error ? (

    {decision.error}

    ) : null} {!canDecide ? (

    {isSecret ? "Only organization admins can approve or reject this." : `Only people who can change ${proposal.target?.name ?? "this agent"}’s settings can approve or reject this.`}

    ) : rejecting ? (
    { event.preventDefault(); if (!reason.trim()) return; decision.clearError(); decision.reject(proposal, reason); }} >
    setReason(event.target.value)} disabled={decision.isBusy} />

    A reason is required. It is sent to {proposal.proposedBy.name}. {isSecret ? " Requests to use this secret are rejected too." : null}

    ) : (
    )}
  • ); } function decidedLabel(proposal: SecretProposalView): string { const outcome = proposal.status === "approved" ? "Approved" : proposal.status === "rejected" ? "Rejected" : "Expired"; const at = proposal.resolvedAt ?? proposal.createdAt; return `${outcome} · ${relativeTime(at)}`; } export function ProposalsTab({ companyId, providerConfigs, }: { companyId: string; providerConfigs: CompanySecretProviderConfig[]; }) { const proposalsQuery = useQuery({ queryKey: queryKeys.secrets.proposals(companyId, "pending"), queryFn: () => secretsApi.listProposals(companyId, "pending"), enabled: Boolean(companyId), }); const decidedQueries = useQueries({ queries: DECIDED_STATUSES.map((status) => ({ queryKey: [...queryKeys.secrets.proposals(companyId, status), "recent"] as const, // Ordered by decision time on the server, so the newest decisions are // in the page even when the request itself is old. queryFn: () => secretsApi.listProposals(companyId, status, { order: "resolved", limit: DECIDED_LIMIT }), enabled: Boolean(companyId), })), }); const proposalsView = useQueryView(proposalsQuery); const proposals = proposalsQuery.data ?? EMPTY_PROPOSALS; // New secrets first, then access — an approver usually saves the secret // before (or alongside) the access requests that depend on it. const pending = useMemo( () => [...proposals].sort((a, b) => { if (a.kind !== b.kind) return a.kind === "secret" ? -1 : 1; return a.createdAt.localeCompare(b.createdAt); }), [proposals], ); const decidedLoading = decidedQueries.some((query) => query.isPending); const decidedFailed = decidedQueries.some((query) => query.isError); const decided = decidedQueries .flatMap((query, index) => (query.data ?? []).filter((row) => row.status === DECIDED_STATUSES[index]), ) .sort((a, b) => (b.resolvedAt ?? b.createdAt).localeCompare(a.resolvedAt ?? a.createdAt)) .slice(0, DECIDED_LIMIT); // A new secret can only be stored in an encrypted vault Paperclip manages. const vaults = useMemo( () => providerConfigs.filter( (config) => config.provider === "local_encrypted" && config.status !== "disabled", ), [providerConfigs], ); if (proposalsView.kind === "error") { return (
    ); } if ( proposalsQuery.isPending || proposalsView.kind === "reconnecting" || (pending.length === 0 && decidedLoading) ) { return (
    Loading requests…
    ); } if (pending.length === 0 && decided.length === 0 && !decidedFailed) { return ( ); } return (

    Agents ask here before they save a secret or use one they don’t have. Nothing changes until you approve.

    {pending.length > 0 ? (
      {pending.map((proposal) => ( other.secretProposalId === proposal.id && deliveryModeForConfigPath(other.configPath) === "env", ) .map(bindingEnvKey) .filter(Boolean), ), ] : EMPTY_KEYS } /> ))}
    ) : (

    You’re caught up. No requests are waiting.

    )}
    {decided.length > 0 || decidedFailed ? (

    Recently decided

    {decided.length > 0 ? (
      {decided.map((proposal) => (
    • {decidedLabel(proposal)}
    • ))}
    ) : null} {decidedFailed ? (

    Some earlier decisions couldn’t be loaded. Reload the page to try again.

    ) : null}
    ) : null}
    ); } const EMPTY_PROPOSALS: SecretProposalView[] = []; const EMPTY_KEYS: string[] = [];