"use client"; import * as React from "react"; import { BotIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon, ChevronUpIcon, ClipboardListIcon, CopyIcon, RefreshCwIcon, SearchIcon, ShieldAlertIcon, XIcon, } from "lucide-react"; import { toast } from "sonner"; import { DateSelect } from "@/components/date-select"; import { SideQuestionButton, SideQuestionWorkspace } from "@/components/side-question-workspace"; import { TablePagination } from "@/components/table-pagination"; 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 { Field, FieldGroup, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Skeleton } from "@/components/ui/skeleton"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { useSideQuestions } from "@/hooks/use-side-questions"; import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation"; import { api } from "@/lib/api"; import type { InterceptApprovalFilter, InterceptApprovalRow, InterceptAudit, InterceptDetail, InterceptPending, InterceptReviewInput, } from "@/lib/types"; import { cn } from "@/lib/utils"; function fmtTime(value: string | undefined, ui: UITranslate) { if (!value) return "—"; return new Date(value).toLocaleString(ui("screen.91610255157661"), { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", }); } function source(row: InterceptApprovalRow, ui: UITranslate) { if (row.decision_source) return row.decision_source; if (row.rule_id) return "rule"; // Persisted legacy prefixes are protocol data, independent of the UI language. return row.reason?.startsWith("[模型]") || row.reason?.startsWith("[Model]") ? "model" : "unknown"; } function originLabel(row: InterceptApprovalRow, ui: UITranslate) { if (row.task_id) return row.task_id; if (row.conversation_id) return ui("screen.7cb8ef7708e0c9", { v0: row.conversation_id }); return "—"; } // Background task runs carry a pool label such as "work#2 · #2770", while // conversation-backed runs carry the agent key (for example "reporter"). // Present a stable, human-readable agent label in both cases. function agentLabel(row: InterceptApprovalRow, ui: UITranslate) { const key = (row.conv_agent_key || "").trim().toLowerCase(); const labels: Record = { auto: ui("screen.f47916cc6d8bee"), mainagent: ui("screen.565311dc5e56ac"), planner: ui("screen.27c00694ec29ae"), worker: ui("screen.fa408509bb3beb"), reporter: ui("screen.4a089c8a70311e"), retester: ui("screen.5687b31efebf25"), pentest: ui("screen.221e3cbe5ee467"), }; if (key && labels[key]) return labels[key]; const raw = (row.agent_name || "").trim(); if (/^work#\d+(?:\s|$)/i.test(raw)) return ui("screen.fa408509bb3beb"); const rawKey = raw.toLowerCase(); if (labels[rawKey]) return labels[rawKey]; return raw || ui("screen.1bc790653b8568"); } function ApprovalOrigin({ row, detail = false }: { row: InterceptApprovalRow; detail?: boolean }) { const { ui } = useUITranslation(); const [locating, setLocating] = React.useState(false); const label = detail && row.task_id ? ui("screen.60af8e99ccd7c5", { v0: row.task_id }) : originLabel(row, ui); const query = new URLSearchParams({ approval: String(row.id) }); let href: string | undefined; if (row.conversation_id) { query.set("c", String(row.conversation_id)); href = `/chat?${query}`; } else if (row.task_id) { query.set("id", row.task_id); href = `/function/tasks/detail?${query}`; } return href ? ( { e.stopPropagation(); if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; e.preventDefault(); if (locating) return; setLocating(true); try { await api.interceptExecution(row.id, row.conversation_id ?? undefined); window.location.assign(href); } catch (error) { toast.error((error as Error).message || ui("screen.8f66d5abc0cb9f")); setLocating(false); } }} > {label} ) : ( {label} ); } function StatusBadge({ status }: { status: string }) { const { ui } = useUITranslation(); const labels: Record = { pending: ui("screen.dcb49342a5e5fb"), allowed: ui("screen.75d889ac43a261"), denied: ui("screen.f098218a3032a6"), timeout: ui("screen.73ce15fee42ed3"), }; 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 { ui } = useUITranslation(); const reason = row.reason?.replace(/^\[模型\]\s*/, ""); const decisionSource = source(row, ui); return (
{decisionSource === "model" ? ( {ui("screen.80ae6d5293d6d8")} ) : decisionSource === "manual" ? ( {ui("screen.0f99a349059ac0")} ) : ( {row.rule_name || ui("screen.f841534297bbc5")} )} {showReason ? (

{reason || ui("screen.df246a6a1cbe71")}

) : null}
); } function CodeBlock({ label, text, truncated = false }: { label: string; text: string; truncated?: boolean }) { const { ui } = useUITranslation(); async function copy() { try { await navigator.clipboard.writeText(text); toast.success(ui("screen.8f6f8d979c981c")); } catch { toast.error(ui("screen.3889e92517c51b")); } } return (

{label}

{text ? ( ) : null}
        {text || ui("screen.7450cc5b16e245")}
      
{truncated ?

{ui("screen.a7b110a3ffcacf")}

: null}
); } const contextLabels = (ui: UITranslate): Record => ({ user: ui("screen.a7dfeaf0c12ca5"), assistant: ui("screen.148743ace1f7e4"), text: ui("screen.148743ace1f7e4"), tool_use: ui("screen.d549abd1ab432d"), tool_result: ui("screen.d15e8edc823e30"), }); const actionLabels = (ui: UITranslate): Record => ({ allow: ui("screen.ce7ef28b670ade"), ask: ui("screen.1b1bd81c56e340"), deny: ui("screen.136de7a8c46fc8"), }); const executionLabels = (ui: UITranslate): Record => ({ not_started: ui("screen.b697fe7de3b110"), not_executed: ui("screen.231fe220426532"), awaiting_result: ui("screen.acfbb4338de315"), succeeded: ui("screen.ae3fb35412112c"), failed: ui("screen.9344597efd4950"), unknown: ui("screen.5403a18bfa5503"), }); function ReviewBackgroundBlock({ background }: { background?: InterceptReviewInput["background"] }) { const { ui } = useUITranslation(); if (!background) return

{ui("screen.34fec66763f017")}

; return (

{background.source === "user_message" ? ui("screen.ed50646c0a6922") : ui("screen.c8859f14639f0c")}

); } function ScriptSnapshotSummary({ input }: { input: InterceptReviewInput }) { const { ui } = useUITranslation(); const files = input.script_files ?? []; if (!files.length) return null; return (

{ui("screen.8a3d39e68bbf9f")}

{input.script_capture_status === "incomplete" ? ui("screen.51568f879b3c20") : ui("screen.8e0e5b1ab8ef55")}
{files.map((file) => ( ))}

{ui("screen.5722042ad8038c")}

); } function ScriptFileSnapshot({ file }: { file: NonNullable[number] }) { const { ui } = useUITranslation(); const [open, setOpen] = React.useState(false); return (
{file.path} {file.sha256 ? SHA-256 {file.sha256.slice(0, 12)}… : null} {file.bytes != null ? ( {file.bytes} {ui("screen.b1c5e73e1471e8")} ) : null}
{file.read_error ?

{file.read_error}

: null} {file.content ? ( <> {open ? : null} ) : null}
); } function ModelReviewContext({ input }: { input: InterceptReviewInput }) { const { ui } = useUITranslation(); return (

{ui("screen.f1850625c2c3ff")}

{ui("screen.5d9ffb627df38e")} {input.version < 4 ? ui("screen.2e6ff6b1b91650") : null}

{input.version >= 2 ? ( ) : ( <> {input.turn_input ? ( ) : null} {input.task ? ( <> ) : null} {input.worker_intent ? ( ) : null} )} {input.working_directory ? ( ) : null} {input.script_files?.length ? (

{ui("screen.008778e27e2165")}

{ui("screen.d63bc40ac7a1bd")}

{input.script_files.map((file) => (
{file.path} {file.source ? ( {file.source === "command" ? ui("screen.3eea8dd1e99824") : ui("screen.9350d6a2c014d8")} ) : null} {file.sha256 ? SHA-256 {file.sha256} : null} {file.bytes != null ? ( {file.bytes} {ui("screen.b1c5e73e1471e8")} ) : null}
{file.content ? : null} {file.read_error ? ( {file.read_error} ) : null} {file.truncated ?

{ui("screen.4f31405bd3a3f4")}

: null}
))} {input.script_capture_status === "incomplete" ? ( {ui("screen.68ece931e0809c")} ) : null}
) : null} {input.version >= 3 ? (

{ui("screen.8bce0326213eb8")}

) : (

{ui("screen.6bc505f9020770")}

{input.history?.length ? ( input.history.map((entry) => (

{entry.tool} ·{" "} {entry.status === "succeeded" ? ui("screen.053461ce86d265") : ui("screen.12c133de12d3a7")}

)) ) : (

{ui("screen.513287f1afa50f")}

)} {input.history_truncated ? (

{ui("screen.674f64320031ec")}

) : null}
)}
); } type Decide = (id: number, decision: "allowed" | "denied") => Promise; function DecisionActions({ row, busy, decide }: { row: InterceptApprovalRow; busy: boolean; decide: Decide }) { const { ui } = useUITranslation(); if (row.status !== "pending") return null; return (
); } export function ApprovalDetail({ row, busy, decide, revision, readOnly = false, defaultExpanded = false, onResolved, }: { row: InterceptApprovalRow; busy: boolean; decide: Decide; revision: number; readOnly?: boolean; defaultExpanded?: boolean; onResolved?: (status: "allowed" | "denied" | "timeout") => void; }) { const { ui, liveUI } = useUITranslation(); const [detail, setDetail] = React.useState(null); const [error, setError] = React.useState(""); const [retry, setRetry] = React.useState(0); const [more, setMore] = React.useState(defaultExpanded); const side = useSideQuestions(`/api/intercept/history/${row.id}`); // 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") onResolved?.(next.status); if (next.status === "pending" || next.audit?.execution_status === "awaiting_result") timer = setTimeout(() => void load(), 5000); } catch (e) { if (!cancelled) setError((e as Error).message || liveUI("screen.19a7ca44a09a85")); } } void load(); return () => { cancelled = true; clearTimeout(timer); }; }, [row.id, row.status, revision, retry, onResolved, liveUI]); // 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(ui)[audit.execution_status] : ui("screen.7450cc5b16e245"); if (row.status === "pending") execution = ui("screen.b697fe7de3b110"); if (audit && audit.correlation !== "exact" && audit.effective_action === "allow") execution = ui("screen.0c20f40c18c058"); const command = typeof row.tool_input?.command === "string" ? row.tool_input.command : undefined; let initialLabel = source(row, ui) === "model" ? ui("screen.3e285ad28fd2d8") : source(row, ui) === "manual" ? ui("screen.0f99a349059ac0") : ui("screen.15731399c8bfea"); if (audit?.model_fallback) initialLabel = ui("screen.89bc2e9f988b76"); return (
{ui("screen.dd803ab17c0d64")}
{command ? ( ) : null}

{ui("screen.17b31cc23654a9")} {detail ? execution : ui("screen.4927a53bcc886a")}

{audit?.model_input ? : null}

{current.status === "pending" ? ui("screen.720f57aae33d93") : ui("screen.9e17e62ff60a69")}

{current.reason?.replace(/^\[模型\]\s*/, "") || ui("screen.fb73cc98cf22dc")}

{audit?.decision_reason ?

{audit.decision_reason}

: null} {audit?.effective_action ? (

{ui("screen.5d65f7a3ec3d30")} {actionLabels(ui)[audit.effective_action]}

) : null}
{ui("screen.a488e93d69cc12")}
{ui("screen.e9b5d944cc4b72")}
{fmtTime(row.created_at, ui)}
{ui("screen.c5be0c531aca6e")}
{fmtTime(current.decided_at, ui)}
{audit?.rule_name ? ( <>
{ui("screen.45959434b24c1d")}
{audit.rule_name}
) : null} {audit?.profile_id ? ( <>
{ui("screen.e4c46b9edf47f6")}
#{audit.profile_id}
) : null}
{!readOnly ? : null}
{error ? (
{ui("screen.61291638aed6d7")} {error}
) : null} {!detail && !error ? : null} {detail && !audit ? ( {ui("screen.3a4be60688885a")} ) : null} {audit ? (
{audit.model_input ? ( ) : ( {audit.model_input_digest ? ui("screen.b1e0db3ba7308f") : ui("screen.93ee5c5d63f01b")} )} {audit.user_message || audit.context?.length ? (
{audit.user_message ? ( ) : null}

{ui("screen.ac4d08c8b23de0")}

{ui("screen.b4986fc5162d6f")} {fmtTime(audit.captured_at, ui)} {ui("screen.7a75968934cd29")}

{audit.context_truncated ? (

{ui("screen.47c205defcbdbd")}

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

{ui("screen.391a23903e178a")}

)}
) : null} {audit.correlation !== "exact" ? ( {audit.correlation === "ambiguous" ? ui("screen.1d24b2c7a740d8") : ui("screen.1726c7ff05712e")} ) : null}
{ui("screen.bb711c49c28166")} {audit.tool_use_id || ui("screen.7450cc5b16e245")}
{ui("screen.be389dfbe3fa68")} {audit.input_digest}
{ui("screen.dca3524c282048")} {audit.config_digest || ui("screen.7450cc5b16e245")}
{audit.model_input_digest ? (
{ui("screen.e452aea446b4c3")} {audit.model_input_digest}
) : null} {audit.execution_ended_at ? (
{ui("screen.624bddb71bbda9")} {fmtTime(audit.execution_ended_at, ui)}
) : 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 { ui } = useUITranslation(); 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 ( {ui("screen.4bf0fb2140bae8")} # {ui("screen.5ca6730d441522")} {ui("screen.a488e93d69cc12")} {ui("screen.fcaf67982b20e2")} {ui("screen.9634fb0832be62")} {ui("screen.6320b4a8722a85")} {ui("screen.e9b5d944cc4b72")} {ui("screen.c5be0c531aca6e")} {rows.map((row) => { const open = expanded.has(row.id); const panelID = `${prefix}-${row.id}`; return ( toggle(row.id)} > {row.id} {row.tool_name}
{ui("punctuation.ece2891a25")} {agentLabel(row, ui)}
{JSON.stringify(row.tool_input)} {fmtTime(row.created_at, ui)} {fmtTime(row.decided_at, ui)}
{open ? (
) : null}
); })}
); } export function ApprovalRecords({ taskId }: { taskId?: string }) { const { ui, liveUI } = useUITranslation(); const [rows, setRows] = React.useState([]); const [pendingRows, setPendingRows] = React.useState([]); const [page, setPage] = React.useState(1); const [pageSize, setPageSize] = React.useState(20); const [total, setTotal] = React.useState(0); const [filter, setFilter] = React.useState({}); const [searchText, setSearchText] = React.useState(""); const [fromDate, setFromDate] = React.useState(""); const [toDate, setToDate] = React.useState(""); const [loading, setLoading] = React.useState(true); const [refreshing, setRefreshing] = React.useState(false); const [error, setError] = React.useState(""); const [pendingError, setPendingError] = 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 filterID = React.useId(); const filtered = Boolean(filter.status || filter.decision_source || filter.q || filter.from || filter.to); // A task can stay mounted while the user switches between task details. // Reset the cursor so the new scope always starts at its newest records. // biome-ignore lint/correctness/useExhaustiveDependencies: taskId intentionally resets pagination when scope changes. React.useEffect(() => { setPage(1); }, [taskId]); const load = React.useCallback( async (manual = false) => { const id = ++request.current; if (manual) setRefreshing(true); try { // The approval queue is independent of the current history page and its // filter. Older requests must remain actionable even when newer decisions // fill the page or a filter would hide them. const [history, pending] = await Promise.allSettled([ taskId ? api.interceptTaskPage(taskId, page, pageSize, filter) : api.interceptHistoryPage(page, pageSize, filter), api.interceptPending(), ]); if (id !== request.current) return; if (history.status === "fulfilled") { setRows(history.value.items); setTotal(history.value.total); setError(""); } else { setError((history.reason as Error).message || liveUI("screen.d1d044826a45ef")); } if (pending.status === "fulfilled") { setPendingRows(pending.value); setPendingError(""); } else { setPendingError((pending.reason as Error).message || liveUI("screen.d1d044826a45ef")); } if (manual) setRevision((v) => v + 1); } catch (e) { if (id === request.current) setError((e as Error).message || liveUI("screen.d1d044826a45ef")); } finally { if (id === request.current) { setLoading(false); setRefreshing(false); } } }, [taskId, page, pageSize, filter, liveUI], ); const latestLoad = React.useRef(load); latestLoad.current = load; React.useEffect(() => { void load(); const timer = setInterval(() => void load(), 5000); return () => { request.current++; clearInterval(timer); }; }, [load]); const changePageSize = (next: number) => { setPageSize(next); setPage(1); }; const changeFilter = (next: InterceptApprovalFilter) => { // An in-flight response for the old filter must not repopulate the table. request.current++; setFilter(next); setSearchText(next.q ?? ""); setFromDate(next.from ?? ""); setToDate(next.to ?? ""); setPage(1); setRows([]); setTotal(0); setError(""); setLoading(true); }; const submitSearch = () => { const q = searchText.trim(); changeFilter({ ...filter, q: q || undefined }); }; const changeDate = (key: "from" | "to", value: string) => { changeFilter({ ...filter, [key]: value || undefined }); }; React.useEffect(() => { const q = searchText.trim(); if (q === (filter.q ?? "")) return; const timer = setTimeout(() => { request.current++; setFilter((previous) => ({ ...previous, q: q || undefined })); setPage(1); setRows([]); setTotal(0); setError(""); setLoading(true); }, 300); return () => clearTimeout(timer); }, [searchText, filter.q]); 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++; // Optimistically drop the decided item from the independent pending queue // for instant feedback; the re-fetch below reconciles with server truth. setRows((prev) => prev.map((row) => (row.id === id ? { ...row, status: decision, decided_at: new Date().toISOString() } : row)), ); setPendingRows((prev) => prev.filter((row) => row.id !== id)); setRevision((v) => v + 1); toast.success(decision === "allowed" ? ui("screen.c90e80972b10bf") : ui("screen.846e5cf371bfdc")); // Re-fetch counts and rows: a decided item may no longer match the filter. await latestLoad.current(true); } catch (e) { toast.error((e as Error).message); await latestLoad.current(true); } finally { decisionLock.current = false; setDeciding(false); } }; const historyById = new Map(rows.map((row) => [row.id, row])); const pending: InterceptApprovalRow[] = pendingRows .filter((row) => !taskId || row.task_id === taskId) .map((row) => ({ conv_title: "", conv_agent_key: "", rule_name: row.rule_id ? ui("screen.8562e879652223", { v0: row.rule_id }) : "", ...historyById.get(row.id), ...row, })); const title = taskId ? ui("screen.b4c245b6421a35") : ui("screen.b75d0f43cd1eb7"); return (

{title}

{pending.length ? ( {pending.length} {ui("screen.dcb49342a5e5fb")} ) : null}

{ui("screen.99a80f89fba868")}

{ui("screen.3f025832c5bc06")}
setSearchText(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); submitSearch(); } }} />
{ui("screen.22aaa59dda96fb")} changeDate("from", value)} optional placeholder={ui("screen.c25ee7fd0c3498")} aria-label={ui("screen.22aaa59dda96fb")} /> {ui("screen.872bf1a9ad3745")} changeDate("to", value)} optional placeholder={ui("screen.97b4df10480574")} aria-label={ui("screen.872bf1a9ad3745")} /> {ui("screen.5d9f1d27b14c8a")} {ui("screen.3d7f1b6c6cb3b7")} {filtered ? ( ) : null}
{error ? ( {ui("screen.32fab96dcfaf1b")} {error} {ui("screen.49248c0ab5297c")} ) : null} {pendingError ? ( {ui("screen.bfe27675d200d4")} {pendingError} {ui("screen.49248c0ab5297c")} ) : null} {pending.length ? (
{ui("screen.cd8ab9e97af96c")} {pending.length} {ui("punctuation.f2e44c6c95")} {ui("screen.7d36855d81f15d")}
) : null}
{filtered ? ui("screen.479424539ce56d") : ui("screen.e4257920848098")} {ui("punctuation.da047c04c9")} {total} {ui("punctuation.f2e44c6c95")} {filter.q ? ( {ui("screen.1a122e99038917")} {filter.q} ) : null}
{loading ? (
) : null} {!loading && !rows.length && !error ? ( {filtered ? ui("screen.341650c0aa69e2") : ui("screen.e0a34c79ee2462")} {filtered ? ui("screen.7829e7febe1ae4") : ui("screen.c0f62ba93415c1")} ) : null} {rows.length ? ( ) : null} {!loading && !error ? ( ) : null}
); }