"use client"; import { AlertCircle,CheckCircle2, Download, Loader2 } from "lucide-react"; import { useMemo, useState } from "react"; import { toast } from "sonner"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { downloadToolMetricsExcel, TOOL_ERROR_CATEGORIES, TOOL_ERROR_CATEGORY_LABELS, type ToolMetric, type ToolMetricsFilters, } from "@/core/tool-metrics/api"; import { useToolMetrics, useToolMetricsSummary } from "@/core/tool-metrics/hooks"; import { cn } from "@/lib/utils"; import { useTheme } from "@/contexts/ThemeContext"; const PAGE_SIZE = 50; type StatusFilter = "all" | "success" | "error"; type KindFilter = "skill" | "all"; function displayUser(row: { user_name?: string | null; user_id?: string | null }): string { if (row.user_name && row.user_name.trim()) return row.user_name.trim(); const id = (row.user_id ?? "").trim(); return id || "—"; } function formatDate(value?: string | null): string { if (!value) return "—"; try { return new Date(value).toLocaleString(); } catch { return value; } } function formatDuration(value?: number | null): string { if (value === null || value === undefined || Number.isNaN(value)) return "—"; if (value === 0) return "0 ms"; if (value < 1000) return `${value} ms`; if (value < 60_000) return `${(value / 1000).toFixed(1)} s`; const minutes = Math.floor(value / 60_000); const seconds = Math.round((value % 60_000) / 1000); return `${minutes}m ${seconds}s`; } function categoryLabel(category?: string | null): string { if (!category) return "—"; return TOOL_ERROR_CATEGORY_LABELS[category] ?? category; } export function ToolMetricsPanel() { const { theme } = useTheme(); const [page, setPage] = useState(0); const [tool, setTool] = useState(""); const [user, setUser] = useState(""); const [skill, setSkill] = useState(""); // Default to skill-only — the table is otherwise flooded with low-level // bash / file-op calls. "全部" reveals every tool invocation. const [kind, setKind] = useState("skill"); const [status, setStatus] = useState("all"); const [category, setCategory] = useState("all"); const [since, setSince] = useState(""); const [until, setUntil] = useState(""); const [exporting, setExporting] = useState(false); const [detailRow, setDetailRow] = useState(null); /** 成功 toast:仅暗色模式,浅色走 Sonner 默认 */ const successToastDarkOptions = { classNames: { toast: "!rounded-[2px] !border !border-[#106455] !bg-[#052934] !text-[#FFFFFF] shadow-md", title: "!text-[#FFFFFF]", description: "!text-[#FFFFFF]", }, icon: , } as const; /** 失败 toast:仅暗色模式,浅色走 Sonner 默认 */ const errorToastDarkOptions = { classNames: { toast: "!rounded-[2px] !border !border-[#7F1A2A] !bg-[#311629] !text-[#FFFFFF] shadow-md", title: "!text-[#FFFFFF]", description: "!text-[#FFFFFF]", }, icon: , } as const; const darkToastOpts = theme === "dark" ? { success: successToastDarkOptions, error: errorToastDarkOptions } : { success: undefined, error: undefined }; const filters = useMemo(() => { const out: ToolMetricsFilters = {}; if (tool.trim()) out.tool_name = tool.trim(); if (user.trim()) out.user_name = user.trim(); if (skill.trim()) out.skill_name = skill.trim(); if (kind !== "all") out.kind = kind; if (status !== "all") out.status = status; if (category !== "all") out.error_category = category; if (since) out.since = new Date(since).toISOString(); if (until) out.until = new Date(until).toISOString(); return out; }, [tool, user, skill, kind, status, category, since, until]); const query = useMemo( () => ({ ...filters, limit: PAGE_SIZE, offset: page * PAGE_SIZE }), [filters, page], ); const { data, isLoading, error, isFetching } = useToolMetrics(query); // The summary ignores the status/category filter so the breakdown always // reflects the full failure picture for the chosen tool/user/time window. const summaryFilters = useMemo(() => { const out: ToolMetricsFilters = {}; if (tool.trim()) out.tool_name = tool.trim(); if (user.trim()) out.user_name = user.trim(); if (skill.trim()) out.skill_name = skill.trim(); if (kind !== "all") out.kind = kind; if (since) out.since = new Date(since).toISOString(); if (until) out.until = new Date(until).toISOString(); return out; }, [tool, user, skill, kind, since, until]); const { data: summary } = useToolMetricsSummary(summaryFilters); const handleExport = async () => { setExporting(true); try { await downloadToolMetricsExcel(filters); toast.success("已导出为 Excel",darkToastOpts.success); } catch (e) { toast.error(e instanceof Error ? e.message : "导出失败",darkToastOpts.error); } finally { setExporting(false); } }; const resetFilters = () => { setTool(""); setUser(""); setSkill(""); setKind("skill"); setStatus("all"); setCategory("all"); setSince(""); setUntil(""); setPage(0); }; const items = data?.items ?? []; const total = data?.total ?? 0; const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE)); const errorRate = summary && summary.total > 0 ? ((summary.error_total / summary.total) * 100).toFixed(1) : "0.0"; return (

工具调用统计

记录每一次工具 / 技能 / MCP 调用,并对失败进行归类:检索为空、IP 被封、限流、超时、鉴权失败等。后台无条件记录。

{/* Summary strip */}
总调用 {summary?.total ?? "—"}
失败数 {summary?.error_total ?? "—"}
失败率 {errorRate}%
{summary && Object.keys(summary.by_category).length === 0 && ( 暂无失败记录 )} {summary && Object.entries(summary.by_category) .sort((a, b) => b[1] - a[1]) .map(([cat, count]) => ( ))}
{/* Per-skill breakdown — answers "was skill X invoked, and did it succeed". */} {summary && summary.by_skill.length > 0 && (

各技能调用情况

{summary.by_skill.map((s) => { const rate = s.total > 0 ? ((s.success / s.total) * 100).toFixed(0) : "0"; return ( { setSkill(s.skill_name); setPage(0); }} > ); })}
技能名称 调用次数 成功 失败 成功率
{s.skill_name} {s.total} {s.success} {s.error} {rate}%
)} {summary && kind === "skill" && summary.by_skill.length === 0 && (
当前筛选范围内没有检测到任何技能调用记录。技能只有在被 Agent 通过 skill_view 读取(即真正"调用")时才会被记录;仅在系统提示里被列出、但未被读取的技能不会计入。
)} {/* Filters */}
{ setSkill(e.target.value); setPage(0); }} />
{ setTool(e.target.value); setPage(0); }} />
{ setUser(e.target.value); setPage(0); }} />
{ setSince(e.target.value); setPage(0); }} />
{ setUntil(e.target.value); setPage(0); }} />
{/* Table */}
{isLoading && ( )} {!isLoading && error && ( )} {!isLoading && !error && items.length === 0 && ( )} {items.map((row) => ( ))}
时间 用户 Agent 技能 工具 耗时 状态 错误类型 错误详情
加载失败:{error.message}
暂无符合条件的调用记录。
{formatDate(row.created_at)} {displayUser(row)} {row.agent_name ?? "—"} {row.skill_name ? ( ) : ( — )} {row.tool_name ?? "—"} {formatDuration(row.duration_ms)} {row.status === "success" ? "成功" : "失败"} {row.error_category ? ( {categoryLabel(row.error_category)} ) : ( "—" )} {row.error_message ? ( ) : ( — )}
{isFetching && !isLoading ? "更新中..." : `共 ${total} 条`}
第 {page + 1} / {totalPages} 页
{/* Full error detail popup */} { if (!open) setDetailRow(null); }} > 工具调用报错详情 {detailRow && (
完整报错信息
                  {detailRow.error_message ?? "(无)"}
                
)}
); } function DetailField({ label, value, mono, }: { label: string; value: string; mono?: boolean; }) { return (
{label} {value}
); } function Th({ children, className, }: { children: React.ReactNode; className?: string; }) { return ( {children} ); } function Td({ children, className, title, }: { children: React.ReactNode; className?: string; title?: string; }) { return ( {children} ); }