SqlTrace.tsx 7.47 KB
import {
  AlertTriangle, CheckCircle2, Code2, Crosshair, ListChecks, PlayCircle,
  RotateCw, Sparkles, XCircle,
} from "lucide-react";
import { cn, formatDuration } from "@/lib/utils";
import { Badge } from "@/components/ui";
import type { SqlTraceEvent } from "@/lib/types";

const META: Record<string, { label: string; icon: React.ReactNode; tone: string }> = {
  retrieve: { label: "召回上下文", icon: <Crosshair className="h-3.5 w-3.5" />, tone: "bg-sky-500" },
  plan: { label: "查询计划", icon: <ListChecks className="h-3.5 w-3.5" />, tone: "bg-indigo-500" },
  sql_draft: { label: "生成 SQL", icon: <Code2 className="h-3.5 w-3.5" />, tone: "bg-amber-500" },
  validate: { label: "安全校验", icon: <CheckCircle2 className="h-3.5 w-3.5" />, tone: "bg-teal-500" },
  repair: { label: "自愈重试", icon: <RotateCw className="h-3.5 w-3.5" />, tone: "bg-purple-500" },
  execute: { label: "执行", icon: <PlayCircle className="h-3.5 w-3.5" />, tone: "bg-emerald-600" },
  error: { label: "出错", icon: <XCircle className="h-3.5 w-3.5" />, tone: "bg-rose-600" },
};

/** 后端 error 事件里的 stage 值 → 中文步骤名 */
const STAGE_TEXT: Record<string, string> = {
  start: "启动", retrieve: "召回上下文", plan: "查询计划",
  sql_draft: "生成 SQL", validate: "安全校验", execute: "执行",
};

/**
 * 生成轨迹。和「深挖检索」页的时间线是同一套语言 —— 每一步都要看得见:
 * 召回了哪些表和指标(带分数)、用的什么口径、校验拦下了什么、重试了几轮。
 * 黑盒地丢一段 SQL 出来,业务同事没法判断对不对,也就没法纠错。
 */
export function SqlTrace({ trace, running }: { trace: SqlTraceEvent[]; running: boolean }) {
  const steps = trace.filter((e) => META[e.type] && e.type !== "rows");
  if (steps.length === 0 && !running) return null;

  return (
    <ol className="space-y-1.5">
      {steps.map((ev, i) => (
        <li key={i} className="flex gap-2.5">
          <span className={cn("mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full text-white",
            META[ev.type].tone)}>
            {META[ev.type].icon}
          </span>
          <div className="min-w-0 flex-1 pb-1">
            <p className="flex flex-wrap items-center gap-1.5 text-[12.5px] font-medium">
              {META[ev.type].label}
              <StepBadges ev={ev} />
            </p>
            <StepBody ev={ev} />
          </div>
        </li>
      ))}
      {running && (
        <li className="flex items-center gap-2.5 text-[12.5px] text-muted">
          <Sparkles className="h-3.5 w-3.5 animate-pulse" /> 处理中…
        </li>
      )}
    </ol>
  );
}

function StepBadges({ ev }: { ev: SqlTraceEvent }) {
  switch (ev.type) {
    case "retrieve":
      return (
        <>
          <Badge>{ev.models.length} 张表</Badge>
          {ev.metrics.length > 0 && <Badge tone="bg-brand2/10 text-brand2">{ev.metrics.length} 个指标</Badge>}
          {ev.pairs.length > 0 && <Badge tone="bg-ok/10 text-ok">复用 {ev.pairs.length} 条沉淀</Badge>}
          <Badge tone="bg-ink/5 text-muted">{ev.schema_tokens} token</Badge>
        </>
      );
    case "sql_draft":
      return ev.attempt > 1 ? <Badge tone="bg-warn/10 text-warn">第 {ev.attempt} 次</Badge> : null;
    case "validate":
      return ev.ok
        ? <Badge tone="bg-ok/10 text-ok">通过</Badge>
        : <Badge tone="bg-bad/10 text-bad">未通过</Badge>;
    case "execute":
      return (
        <>
          <Badge tone="bg-ok/10 text-ok">{ev.row_count} 行</Badge>
          <Badge tone="bg-ink/5 text-muted">{formatDuration(ev.duration_ms)}</Badge>
          {ev.truncated && <Badge tone="bg-warn/10 text-warn">已截断</Badge>}
        </>
      );
    default:
      return null;
  }
}

function StepBody({ ev }: { ev: SqlTraceEvent }) {
  switch (ev.type) {
    case "retrieve":
      return (
        <div className="mt-1 space-y-1">
          <div className="flex flex-wrap gap-1">
            {ev.models.map((m) => (
              <span key={m.id} className="chip px-1.5 py-0 text-[11px]" title={`相关度 ${m.score}`}>
                {m.table}
                <span className="text-muted">{m.columns} 列</span>
              </span>
            ))}
          </div>
          {ev.metrics.length > 0 && (
            // 口径说明动辄两三行,十几个指标铺开能把整张卡片顶到屏幕外。
            // 这里每个只留一行,完整内容挂在 title 上,要细看去「指标与规则」页。
            <div className="space-y-0.5">
              {ev.metrics.map((m) => (
                <p key={m.id} className="truncate text-[11.5px] text-muted"
                   title={m.calibre || m.name}>
                  指标 <span className="text-ink">{m.name}</span>
                  {m.calibre && <> · 口径:{m.calibre}</>}
                </p>
              ))}
            </div>
          )}
          {ev.pairs.length > 0 && (
            <p className="text-[11.5px] text-muted">
              命中沉淀:{ev.pairs.map((p) => p.question).join(" / ")}
            </p>
          )}
          {ev.dropped_columns > 0 && (
            <p className="text-[11.5px] text-warn">
              上下文超预算,按相关度剪掉了 {ev.dropped_columns} 个列
            </p>
          )}
        </div>
      );

    case "plan":
      return (
        <div className="mt-1 space-y-1 text-[12px] text-muted">
          {ev.plan?.summary && <p className="text-ink">{ev.plan.summary}</p>}
          {ev.plan?.grain && <p>粒度:{ev.plan.grain}</p>}
          {!!ev.plan?.measures?.length && <p>度量:{ev.plan.measures.join("、")}</p>}
          {!!ev.plan?.dimensions?.length && <p>分组:{ev.plan.dimensions.join("、")}</p>}
          {!!ev.plan?.filters?.length && <p>过滤:{ev.plan.filters.join(";")}</p>}
          {ev.plan?.time_range && <p>时间范围:{ev.plan.time_range}</p>}
          {ev.calibre && ev.calibre !== "无特殊口径" && (
            // 口径是这套业务最容易出错的地方,单独高亮
            <p className="rounded-md border border-brand/30 bg-brand/5 px-2 py-1 text-brand">
              口径:{ev.calibre}
            </p>
          )}
          {ev.clarify && <p className="text-warn">需要澄清:{ev.clarify}</p>}
        </div>
      );

    case "validate":
      if (ev.issues.length === 0) {
        return (
          <p className="mt-0.5 text-[11.5px] text-muted">
            只读检查、表与关联白名单都通过{ev.limited && ";已自动补上 LIMIT"}
          </p>
        );
      }
      return (
        <ul className="mt-1 space-y-0.5">
          {ev.issues.map((it, i) => (
            <li key={i} className={cn("flex gap-1.5 text-[11.5px]",
              it.level === "error" ? "text-bad" : "text-warn")}>
              <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />
              <span>
                {it.msg}
                {it.fix && <span className="text-muted"> — {it.fix}</span>}
              </span>
            </li>
          ))}
        </ul>
      );

    case "repair":
      return <p className="mt-0.5 text-[11.5px] text-muted">因为:{ev.reason}</p>;

    case "error":
      // 只说清在哪一步挂的。完整报错在右边的醒目框里,这里重复一遍纯属噪声。
      return (
        <p className="mt-0.5 text-[11.5px] text-muted">
          在「{STAGE_TEXT[ev.stage] ?? ev.stage}」阶段失败
          {ev.attempts ? `,已重试 ${ev.attempts - 1} 轮` : ""}
        </p>
      );

    default:
      return null;
  }
}