import { useEffect, useMemo, useState } from "react"; import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { ChevronDown, ChevronRight, ScrollText } from "lucide-react"; import { Link } from "@/lib/router"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { StatusBadge } from "@/components/StatusBadge"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { cn } from "@/lib/utils"; import { queryKeys } from "@/lib/queryKeys"; import { toolsApi, type ToolAuditOutcome, type ToolAuditWindow, type ToolGatewayActivityEvent, } from "@/api/tools"; import { agentsApi } from "@/api/agents"; import { AgentSelect } from "@/components/AgentMultiSelect"; import { ToolsPageHeader, LoadingState, RelativeTime } from "./shared"; const PAGE_SIZE = 50; const ALL = "__all"; /** Outcome chip vocabulary (spec §4C / §5): Allowed · Blocked · Asked first · Failed · Waiting. */ const OUTCOME_META: Record = { allowed: { label: "Allowed", status: "allowed" }, blocked: { label: "Blocked", status: "denied" }, asked_first: { label: "Asked first", status: "require-approval" }, waiting: { label: "Waiting", status: "deferred" }, failed: { label: "Failed", status: "failed" }, unknown: { label: "Recorded", status: "unchecked" }, }; const OUTCOME_FILTERS: { value: string; label: string }[] = [ { value: ALL, label: "All outcomes" }, { value: "allowed", label: "Allowed" }, { value: "blocked", label: "Blocked" }, { value: "asked_first", label: "Asked first" }, { value: "waiting", label: "Waiting" }, { value: "failed", label: "Failed" }, ]; const WINDOW_FILTERS: { value: ToolAuditWindow; label: string }[] = [ { value: "all", label: "All time" }, { value: "1h", label: "Last 1 hour" }, { value: "24h", label: "Last 24 hours" }, { value: "7d", label: "Last 7 days" }, { value: "30d", label: "Last 30 days" }, ]; function detailString(details: Record | null, key: string): string | undefined { const v = details?.[key]; return typeof v === "string" && v.trim().length > 0 ? v : undefined; } function detailStringArray(details: Record | null, key: string): string[] { const v = details?.[key]; return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; } function detailRecord(value: unknown): Record | null { return value && typeof value === "object" && !Array.isArray(value) ? value as Record : null; } function detailNumber(details: Record | null, key: string): number | undefined { const value = details?.[key]; return typeof value === "number" && Number.isFinite(value) ? value : undefined; } function formattedArguments(details: Record | null): string | undefined { const summary = detailRecord(details?.argumentsSummary); const serialized = typeof summary?.summary === "string" ? summary.summary : undefined; if (!serialized) return undefined; try { return JSON.stringify(JSON.parse(serialized), null, 2); } catch { return serialized; } } function lifecycleSummary(event: ToolGatewayActivityEvent): string | null { if (!event.lifecycleType) return null; const who = event.actorDisplayName ?? event.agentDisplayName ?? "Someone"; const app = event.appDisplayName ?? event.connectionDisplayName ?? "this app"; const count = detailNumber(event.details, "count") ?? 0; const added = detailNumber(event.details, "added") ?? 0; const removed = detailNumber(event.details, "removed") ?? 0; switch (event.lifecycleType) { case "app_connected": return `${who} connected ${app}`; case "app_paused": return `${who} paused ${app}`; case "app_resumed": return `${who} resumed ${app}`; case "reconnected": return `${who} reconnected ${app}`; case "disconnected": return `${who} disconnected ${app}`; case "allowlist_changed": if (added > 0 && removed === 0) return `${who} added ${added} allowed ${added === 1 ? "item" : "items"} in ${app}`; if (removed > 0 && added === 0) return `${who} removed ${removed} allowed ${removed === 1 ? "item" : "items"} in ${app}`; return `${who} updated the allowlist for ${app}`; case "actions_quarantined": return `${count} new ${count === 1 ? "action needs" : "actions need"} review in ${app}`; default: return `${who} updated ${app}`; } } /** Plain-words "why" for the row expander, keyed off the reason code. */ function plainReason(event: ToolGatewayActivityEvent): string { if (event.lifecycleType) return "This connection change was recorded in the app's activity history."; const code = detailString(event.details, "reasonCode"); if (code === "permitted_connections_not_installed") { return "Permitted connections were not installed, so their tools were not added to this run."; } switch (event.normalizedOutcome) { case "allowed": return "Allowed by your rules."; case "blocked": if (code === "rate_limited") return "Blocked because it ran too many times in a short window."; if (code?.includes("secret")) return "Blocked to keep a sensitive value from leaving."; return "Blocked by a rule."; case "asked_first": return "Held for someone to approve before it could run."; case "waiting": return "Waiting — the app it needs wasn't ready yet."; case "failed": return "The app was allowed to run it, but returned an error."; default: return "Recorded by Paperclip."; } } /** Compact monospace fact row inside the Details collapse. */ function DetailFact({ label, value, mono }: { label: string; value: string; mono?: boolean }) { return (
{label} {value}
); } function OutcomeChip({ outcome }: { outcome: ToolAuditOutcome }) { const meta = OUTCOME_META[outcome] ?? OUTCOME_META.unknown; return ; } function ActivityRow({ event, ruleNamesById, }: { event: ToolGatewayActivityEvent; ruleNamesById: Map; }) { const [open, setOpen] = useState(false); const [detailsOpen, setDetailsOpen] = useState(false); const who = event.agentDisplayName ?? "An agent"; const action = event.toolDisplayName ?? "an action"; const app = event.appDisplayName ?? event.connectionDisplayName ?? event.applicationDisplayName ?? null; const lifecycle = lifecycleSummary(event); const rawTool = detailString(event.details, "tool") ?? detailString(event.details, "toolName"); const issueId = detailString(event.details, "issueId"); const runId = event.runId ?? detailString(event.details, "runId"); const agentId = event.agentId ?? detailString(event.details, "agentId"); const reasonCode = detailString(event.details, "reasonCode") ?? event.action.replace("tool_gateway.", ""); const matchedRuleId = detailStringArray(event.details, "matchedPolicyIds").find((id) => ruleNamesById.has(id)); const matchedRuleName = matchedRuleId ? ruleNamesById.get(matchedRuleId) : undefined; const argumentsText = formattedArguments(event.details); const execution = detailRecord(event.details?.execution); const request = detailRecord(execution?.request); const response = detailRecord(execution?.response); const transport = detailString(execution, "transport"); const requestMethod = detailString(request, "httpMethod"); const endpoint = detailString(request, "endpoint"); const mcpMethod = detailString(request, "mcpMethod"); const requestId = detailString(request, "requestId"); const httpStatus = detailNumber(response, "httpStatus"); const contentType = detailString(response, "contentType"); const responseBytes = detailNumber(response, "bodySizeBytes"); const upstreamRequestId = detailString(response, "upstreamRequestId"); const permittedNotInstalledCount = detailNumber(event.details, "permittedNotInstalledCount"); const permittedNotInstalledConnections = Array.isArray(event.details?.permittedNotInstalledConnections) ? event.details.permittedNotInstalledConnections .map(detailRecord) .filter((connection): connection is Record => connection !== null) : []; const isRuntimeMcpDeliveryDiagnostic = reasonCode === "permitted_connections_not_installed"; return (
  • {open ? (

    {plainReason(event)} {matchedRuleName ? ( <> {" "} {matchedRuleName} ) : null}

    {issueId ? ( View task ) : null} {runId && agentId ? ( View run ) : null}
    {detailsOpen ? (
    {rawTool ? : null} {runId ? : null} {transport ? : null} {requestMethod && endpoint ? : null} {mcpMethod ? : null} {requestId ? : null} {request ? : null} {httpStatus !== undefined ? : null} {contentType ? : null} {responseBytes !== undefined ? : null} {upstreamRequestId ? : null} {isRuntimeMcpDeliveryDiagnostic ? ( <> {permittedNotInstalledConnections.map((connection) => { const connectionId = detailString(connection, "id"); const connectionName = detailString(connection, "name") ?? "Unnamed connection"; return connectionId ? (
    Not installed {connectionName}
    ) : null; })} ) : null} {argumentsText ? (
    Parameters (redacted)
                          {argumentsText}
                        
    ) : null}
    ) : null}
    ) : null}
  • ); } export function AuditTab({ companyId }: { companyId: string }) { const [app, setApp] = useState(ALL); const [agent, setAgent] = useState(ALL); const [outcome, setOutcome] = useState(ALL); const [windowKey, setWindowKey] = useState("all"); const [searchInput, setSearchInput] = useState(""); const [search, setSearch] = useState(""); // Debounce the search box so each keystroke doesn't fire a server request. useEffect(() => { const id = setTimeout(() => setSearch(searchInput.trim()), 300); return () => clearTimeout(id); }, [searchInput]); const apps = useQuery({ queryKey: queryKeys.tools.applications(companyId), queryFn: () => toolsApi.listApplications(companyId), }); const agents = useQuery({ queryKey: queryKeys.agents.list(companyId), queryFn: () => agentsApi.list(companyId), }); // Map matched rule IDs to their humanized names for the row "why" link. const policies = useQuery({ queryKey: queryKeys.tools.policies(companyId), queryFn: () => toolsApi.listPolicies(companyId), }); const ruleNamesById = useMemo( () => new Map((policies.data?.policies ?? []).map((p) => [p.id, p.name])), [policies.data], ); const filters = { app: app === ALL ? undefined : app, agent: agent === ALL ? undefined : agent, outcome: outcome === ALL ? undefined : outcome, window: windowKey, search: search || undefined, }; const hasActiveFilters = app !== ALL || agent !== ALL || outcome !== ALL || windowKey !== "all" || search.length > 0; const activity = useInfiniteQuery({ queryKey: queryKeys.tools.activity(companyId, { app: filters.app, agent: filters.agent, outcome: filters.outcome, window: filters.window, search: filters.search, }), queryFn: ({ pageParam }) => toolsApi.listActivity(companyId, { ...filters, limit: PAGE_SIZE, cursor: pageParam ?? undefined }), initialPageParam: null as string | null, getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, }); const activityView = useQueryView(activity); const events = useMemo( () => activity.data?.pages.flatMap((page) => page.events) ?? [], [activity.data], ); const clearFilters = () => { setApp(ALL); setAgent(ALL); setOutcome(ALL); setWindowKey("all"); setSearchInput(""); setSearch(""); }; return (
    setSearchInput(e.target.value)} className="max-w-xs" /> {hasActiveFilters ? ( ) : null}
    {activity.isLoading || activityView.kind === "reconnecting" ? ( ) : activityView.kind === "error" ? ( ) : events.length === 0 ? ( hasActiveFilters ? (

    No activity matches these filters

    Try a wider time window or different filters.

    ) : (

    Nothing here yet

    As soon as your agents start using connected apps, what they do shows up here.

    ) ) : (
      {events.map((event) => ( ))}
    )} {activity.hasNextPage ? (
    ) : null}
    ); }