"use client"; import * as React from "react"; import { BotIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon, ClipboardListIcon, CopyIcon, RefreshCwIcon, ShieldAlertIcon, XIcon, } from "lucide-react"; import { toast } from "sonner"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty"; import { Skeleton } from "@/components/ui/skeleton"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { api } from "@/lib/api"; import type { InterceptApprovalRow, InterceptAudit, InterceptDetail } from "@/lib/types"; import { cn } from "@/lib/utils"; function fmtTime(value?: string) { if (!value) return "—"; return new Date(value).toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", }); } function source(row: InterceptApprovalRow) { if (row.decision_source) return row.decision_source; if (row.rule_id) return "rule"; return row.reason?.startsWith("[模型]") ? "model" : "unknown"; } function StatusBadge({ status }: { status: string }) { const labels: Record = { pending: "待审批", allowed: "已允许", denied: "已拒绝", timeout: "已超时" }; let variant: "default" | "destructive" | "secondary" | "outline" = "outline"; if (status === "allowed") variant = "default"; if (status === "denied") variant = "destructive"; if (status === "pending") variant = "secondary"; return {labels[status] ?? status}; } function MatchCell({ row, showReason = true }: { row: InterceptApprovalRow; showReason?: boolean }) { const reason = row.reason?.replace(/^\[模型\]\s*/, ""); return (
{source(row) === "model" ? ( 模型判定 ) : ( {row.rule_name || "规则未记录或已删除"} )} {showReason ? (

{reason || "未记录理由"}

) : null}
); } function CodeBlock({ label, text, truncated = false }: { label: string; text: string; truncated?: boolean }) { async function copy() { try { await navigator.clipboard.writeText(text); toast.success("已复制"); } catch { toast.error("复制失败,请手动选择内容复制"); } } return (

{label}

{text ? ( ) : null}
        {text || "未记录"}
      
{truncated ?

内容已截断,以上为保存的片段。

: null}
); } const contextLabels: Record = { user: "用户消息", assistant: "Agent 消息", text: "Agent 消息", tool_use: "工具请求", tool_result: "工具输出", }; const actionLabels: Record = { allow: "允许", ask: "转人工审批", deny: "拒绝" }; const executionLabels: Record = { not_started: "尚未执行", not_executed: "未执行", awaiting_result: "已允许,等待执行结果", succeeded: "执行成功", failed: "执行失败", unknown: "执行结果未知", }; type Decide = (id: number, decision: "allowed" | "denied") => Promise; function DecisionActions({ row, busy, decide }: { row: InterceptApprovalRow; busy: boolean; decide: Decide }) { if (row.status !== "pending") return null; return (
); } function ApprovalDetail({ row, busy, decide, revision, }: { row: InterceptApprovalRow; busy: boolean; decide: Decide; revision: number; }) { const [detail, setDetail] = React.useState(null); const [error, setError] = React.useState(""); const [retry, setRetry] = React.useState(0); const [more, setMore] = React.useState(false); // biome-ignore lint/correctness/useExhaustiveDependencies: Status, refresh and retry invalidate details without closing the panel. React.useEffect(() => { let cancelled = false; let timer: ReturnType | undefined; async function load() { try { const next = await api.interceptDetail(row.id); if (cancelled) return; setDetail(next); setError(""); if (next.status === "pending" || next.audit?.execution_status === "awaiting_result") timer = setTimeout(() => void load(), 5000); } catch (e) { if (!cancelled) setError((e as Error).message || "详情加载失败"); } } void load(); return () => { cancelled = true; clearTimeout(timer); }; }, [row.id, row.status, revision, retry]); // Row updates are authoritative until the lazy detail has caught up. const current = detail?.status === row.status ? detail : row; const audit = detail?.audit; let execution = audit ? executionLabels[audit.execution_status] : "未记录"; if (row.status === "pending") execution = "尚未执行"; if (audit && audit.correlation !== "exact" && audit.effective_action === "allow") execution = "未关联执行结果"; const command = typeof row.tool_input?.command === "string" ? row.tool_input.command : undefined; let initialLabel = source(row) === "model" ? "模型初判" : "规则初判"; if (audit?.model_fallback) initialLabel = "模型异常回退"; return (
{command ? ( ) : null}

执行结果:{detail ? execution : "加载中…"}

{current.status === "pending" ? "审查状态" : "审批裁决"}

{current.reason?.replace(/^\[模型\]\s*/, "") || "未记录审批理由"}

{audit?.decision_reason ?

{audit.decision_reason}

: null} {audit?.effective_action ?

最终动作:{actionLabels[audit.effective_action]}

: null}
来源
{row.conv_title || (row.task_id ? `任务 ${row.task_id}` : row.agent_name || "未记录")}
申请时间
{fmtTime(row.created_at)}
决定时间
{fmtTime(current.decided_at)}
{audit?.rule_name ? ( <>
规则快照
{audit.rule_name}
) : null} {audit?.profile_id ? ( <>
审批模型配置
#{audit.profile_id}
) : null}
{error ? (
详情加载失败:{error}
) : null} {!detail && !error ? : null} {detail && !audit ? ( 此记录未保存审批详情快照,无法还原当时的上下文、模型初判和执行输出。 ) : null} {audit ? (

可见会话上下文

保存于 {fmtTime(audit.captured_at)} 的会话记录片段。模型审批目前仅接收工具名称和参数。

{audit.context_truncated ? (

仅保存最近的上下文,部分内容已截断。

) : null} {audit.context?.length ? ( audit.context.map((entry, index) => ( )) ) : (

未记录可关联的上下文

)}
{audit.correlation !== "exact" ? ( {audit.correlation === "ambiguous" ? "存在相同参数的并发调用,无法唯一关联工具调用;本记录不展示推测的执行结果。" : "未记录可唯一关联的工具调用 ID。"} ) : null}
工具调用 ID:{audit.tool_use_id || "未记录"}
参数摘要 SHA-256:{audit.input_digest}
审查配置指纹 SHA-256:{audit.config_digest || "未记录"}
{audit.execution_ended_at ?
结果记录时间:{fmtTime(audit.execution_ended_at)}
: null}
) : null}
); } // Hidden cells do not occupy table columns. Keep the detail span in sync so // expansion cannot create empty columns and leave a gap in the selected row. const approvalBreakpoints = ["(min-width: 40rem)", "(min-width: 48rem)", "(min-width: 64rem)", "(min-width: 80rem)"]; function subscribeColumns(onChange: () => void) { const queries = approvalBreakpoints.map((query) => window.matchMedia(query)); for (const query of queries) query.addEventListener("change", onChange); return () => { for (const query of queries) query.removeEventListener("change", onChange); }; } function visibleColumnCount() { const matches = approvalBreakpoints.map((query) => window.matchMedia(query).matches); return 3 + Number(matches[0]) + Number(matches[1]) + 2 * Number(matches[2]) + 2 * Number(matches[3]); } function serverColumnCount() { return 9; } function ApprovalTable({ rows, busy, decide, revision, label, }: { rows: InterceptApprovalRow[]; busy: boolean; decide: Decide; revision: number; label: string; }) { const [expanded, setExpanded] = React.useState>(() => new Set()); const columns = React.useSyncExternalStore(subscribeColumns, visibleColumnCount, serverColumnCount); const prefix = React.useId(); function toggle(id: number) { setExpanded((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } return ( 展开详情 # 工具 来源 匹配规则 参数 状态 申请时间 决定时间 {rows.map((row) => { const open = expanded.has(row.id); const panelID = `${prefix}-${row.id}`; return ( toggle(row.id)} > {row.id} {row.tool_name}
{row.conv_title || row.task_id || "—"} {row.agent_name || row.conv_agent_key}
{JSON.stringify(row.tool_input)} {fmtTime(row.created_at)} {fmtTime(row.decided_at)}
{open ? (
) : null}
); })}
); } export function ApprovalRecords({ taskId }: { taskId?: string }) { const [rows, setRows] = React.useState([]); const [loading, setLoading] = React.useState(true); const [refreshing, setRefreshing] = React.useState(false); const [error, setError] = React.useState(""); const [deciding, setDeciding] = React.useState(false); const [revision, setRevision] = React.useState(0); const request = React.useRef(0); const decisionLock = React.useRef(false); const load = React.useCallback( async (manual = false) => { const id = ++request.current; if (manual) setRefreshing(true); try { const items = taskId ? await api.interceptTask(taskId) : await api.interceptHistory(); if (id !== request.current) return; setRows(items); setError(""); if (manual) setRevision((v) => v + 1); } catch (e) { if (id === request.current) setError((e as Error).message || "加载失败"); } finally { if (id === request.current) { setLoading(false); setRefreshing(false); } } }, [taskId], ); React.useEffect(() => { void load(); const timer = setInterval(() => void load(), 5000); return () => { request.current++; clearInterval(timer); }; }, [load]); const decide: Decide = async (id, decision) => { if (decisionLock.current) return; decisionLock.current = true; setDeciding(true); try { await api.interceptDecide(id, decision); // Invalidate a list request started before this decision. request.current++; setRows((prev) => prev.map((row) => (row.id === id ? { ...row, status: decision, decided_at: new Date().toISOString() } : row)), ); setRevision((v) => v + 1); toast.success(decision === "allowed" ? "已允许执行" : "已拒绝执行"); } catch (e) { toast.error((e as Error).message); await load(true); } finally { decisionLock.current = false; setDeciding(false); } }; const pending = rows.filter((row) => row.status === "pending"); const title = taskId ? "拦截审批" : "审批记录"; return (

{title}

{pending.length ? {pending.length} 待审批 : null}

展开记录查看工具请求和审批裁决,以及当时的上下文与执行结果。

{error ? ( 记录加载失败:{error}。请点击刷新重试。 ) : null} {pending.length ? (
待处理({pending.length})展开后允许或拒绝
) : null}
{taskId ? "全部记录" : "最近记录"}({rows.length})
{loading ? (
) : null} {!loading && !rows.length && !error ? ( 暂无审批记录 规则或模型作出审批决定后,记录将显示在这里。 ) : null} {rows.length ? ( ) : null}
); }