TraceTimeline.tsx 13.2 KB
import {
  Brain, CheckCircle2, ChevronDown, ChevronsDownUp, ChevronsUpDown, Crosshair, FileText, GitBranch, Layers,
  Gauge, RotateCw, Sparkles, XCircle,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { typeColor } from "@/lib/colors";
import { cn, shortHeading } from "@/lib/utils";
import { Badge, Pill } from "@/components/ui";
import type { TraceEvent } from "@/lib/types";

const STEP_META: Record<string, { label: string; icon: React.ReactNode; tone: string }> = {
  start: { label: "开始", icon: <Sparkles className="h-3.5 w-3.5" />, tone: "bg-muted" },
  understand: { label: "理解问题", icon: <Brain className="h-3.5 w-3.5" />, tone: "bg-indigo-500" },
  link: { label: "定位入口", icon: <Crosshair className="h-3.5 w-3.5" />, tone: "bg-sky-500" },
  hop: { label: "图谱扩展", icon: <GitBranch className="h-3.5 w-3.5" />, tone: "bg-amber-500" },
  evidence: { label: "证据召回", icon: <FileText className="h-3.5 w-3.5" />, tone: "bg-teal-500" },
  community: { label: "主题摘要", icon: <Layers className="h-3.5 w-3.5" />, tone: "bg-fuchsia-500" },
  reflect: { label: "反思", icon: <RotateCw className="h-3.5 w-3.5" />, tone: "bg-purple-500" },
  context: { label: "上下文装配", icon: <Gauge className="h-3.5 w-3.5" />, tone: "bg-cyan-600" },
  answer: { label: "作答", icon: <CheckCircle2 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" },
};

/**
 * 检索轨迹时间线 —— 本系统的核心卖点。
 *
 * 每一步都显示大模型到底做了什么:拆出了哪些检索词、链接到哪些节点(带分数与
 * 匹配方式)、沿哪些边扩展(带排序分数、剪掉了多少候选)、召回了哪些原文、
 * 为什么判断还要继续挖、上下文预算怎么分配的。
 * 点击任意一步可以在右侧图上回放到那一步的子图状态。
 */
export function TraceTimeline({ trace, running, replayStep, onReplay, onOpenChunk, onFocusNode }: {
  trace: TraceEvent[];
  running: boolean;
  replayStep: number | null;
  onReplay: (n: number | null) => void;
  onOpenChunk: (id: string) => void;
  onFocusNode: (id: string) => void;
}) {
  const endRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (running && replayStep === null) endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
  }, [trace.length, running, replayStep]);

  const steps = trace.filter((t) => t.type !== "start");

  // 步骤默认展开;一轮问答结束后自动收起,保持对话区紧凑,点开单步或用"全部展开"按需细看
  const [collapsed, setCollapsed] = useState<Set<number>>(new Set());
  const stepsRef = useRef(steps);
  stepsRef.current = steps;
  const prevRunning = useRef(running);
  useEffect(() => {
    if (prevRunning.current && !running) {
      setCollapsed(new Set(stepsRef.current.map((_, i) => i)));
    }
    prevRunning.current = running;
  }, [running]);
  const toggleOne = (i: number) => setCollapsed((s) => {
    const next = new Set(s);
    if (next.has(i)) next.delete(i); else next.add(i);
    return next;
  });
  const allCollapsed = steps.length > 0 && collapsed.size >= steps.length;

  return (
    <div className="flex h-full flex-col">
      {replayStep !== null && (
        <div className="flex items-center gap-2 border-b border-line bg-warn/10 px-3 py-1.5 text-xs">
          <span>回放模式:显示到第 {replayStep + 1} 步</span>
          <button className="btn btn-sm ml-auto" onClick={() => onReplay(null)}>退出回放</button>
        </div>
      )}
      {steps.length > 1 && (
        <div className="flex items-center justify-end border-b border-line px-3 py-1">
          <button className="btn btn-ghost btn-sm text-[11px]"
                  onClick={() => setCollapsed(allCollapsed ? new Set() : new Set(steps.map((_, i) => i)))}>
            {allCollapsed
              ? <><ChevronsUpDown className="h-3 w-3" />全部展开</>
              : <><ChevronsDownUp className="h-3 w-3" />全部收起</>}
          </button>
        </div>
      )}
      <div className="flex-1 space-y-2 overflow-auto p-3">
        {steps.map((ev, i) => {
          const meta = STEP_META[ev.type] ?? STEP_META.start;
          const dimmed = replayStep !== null && i > replayStep;
          const isCollapsed = collapsed.has(i);
          return (
            <div key={i}
                 className={cn("card animate-fade-up cursor-pointer p-0 transition-opacity",
                   dimmed && "opacity-35")}
                 onClick={() => onReplay(replayStep === i ? null : i)}>
              <div className="flex items-center gap-2 border-b border-line px-3 py-1.5">
                <span className={cn("grid h-5 w-5 shrink-0 place-items-center rounded-full text-white", meta.tone)}>
                  {meta.icon}
                </span>
                <span className="text-[13px] font-medium">{meta.label}</span>
                {"round" in ev && ev.round != null && (
                  <Badge>第 {ev.round}{"max_rounds" in ev ? `/${ev.max_rounds}` : ""} 轮</Badge>
                )}
                <button className="btn btn-ghost btn-sm ml-auto -mr-1.5"
                        title={isCollapsed ? "展开" : "收起"}
                        onClick={(e) => { e.stopPropagation(); toggleOne(i); }}>
                  <ChevronDown className={cn("h-3.5 w-3.5 shrink-0 text-muted transition-transform",
                    !isCollapsed && "rotate-180")} />
                </button>
              </div>
              {!isCollapsed && (
                <div className="px-3 py-2 text-[12.5px]">
                  <StepBody ev={ev} onOpenChunk={onOpenChunk} onFocusNode={onFocusNode} />
                </div>
              )}
            </div>
          );
        })}
        {running && (
          <div className="flex items-center gap-2 px-1 py-2 text-xs text-muted">
            <span className="flex gap-1">
              {[0, 1, 2].map((i) => (
                <i key={i} className="h-1.5 w-1.5 animate-bounce rounded-full bg-brand"
                   style={{ animationDelay: `${i * 120}ms` }} />
              ))}
            </span>
            正在检索…
          </div>
        )}
        <div ref={endRef} />
      </div>
    </div>
  );
}

function StepBody({ ev, onOpenChunk, onFocusNode }: {
  ev: TraceEvent; onOpenChunk: (id: string) => void; onFocusNode: (id: string) => void;
}) {
  switch (ev.type) {
    case "understand":
      return (
        <div className="space-y-1.5">
          <p className="text-muted">意图</p>
          <p>{ev.intent || "—"}</p>
          <div className="flex flex-wrap items-center gap-1.5 pt-1">
            <span className="text-muted">具体实体</span>
            {ev.entities.length
              ? ev.entities.map((e) => <Pill key={e} color="#6366f1">{e}</Pill>)
              : <span className="text-muted">未识别</span>}
          </div>
          {ev.keywords.length > 0 && (
            <div className="flex flex-wrap items-center gap-1.5">
              <span className="text-muted">主题关键词</span>
              {ev.keywords.map((k) => <Pill key={k} color="#0ea5e9">{k}</Pill>)}
            </div>
          )}
          <Badge>问题类型:{ev.question_type}</Badge>
        </div>
      );

    case "link":
      return (
        <div className="space-y-2">
          {ev.links.map((l) => (
            <div key={l.term}>
              <p className="mb-1 font-medium">{l.term} →</p>
              {l.matches.length === 0 && <p className="text-muted">未匹配到图谱节点</p>}
              {l.matches.map((m) => (
                <button key={m.id}
                        className="mb-1 flex w-full items-center gap-2 rounded-md px-1 py-0.5 text-left hover:bg-ink/5"
                        onClick={(e) => { e.stopPropagation(); onFocusNode(m.id); }}>
                  <Pill color={typeColor(m.type)}>{m.label}</Pill>
                  <span className="h-1.5 flex-1 overflow-hidden rounded-full bg-ink/8">
                    <i className="block h-full rounded-full"
                       style={{ width: `${Math.round(m.score * 100)}%`,
                                background: "linear-gradient(90deg,rgb(var(--brand2)),rgb(var(--brand)))" }} />
                  </span>
                  <Badge>{m.method} {m.score.toFixed(2)}</Badge>
                </button>
              ))}
            </div>
          ))}
        </div>
      );

    case "hop":
      return (
        <div className="space-y-1.5">
          <p className="text-muted">
            沿关系扩展,新增 {ev.new_nodes.length} 个节点
            {ev.pruned > 0 && <>;按相关度剪掉 <b className="text-ink">{ev.pruned}</b> 条低分候选边</>}
          </p>
          {ev.paths.length === 0 && <p className="text-muted">本轮无新增关系</p>}
          {ev.paths.slice(0, 14).map((p) => (
            <div key={p.id} className="flex flex-wrap items-center gap-1 rounded-md bg-ink/[0.03] px-1.5 py-1">
              <button className="rounded bg-brand/10 px-1.5 py-0.5 font-medium text-brand hover:bg-brand/20"
                      onClick={(e) => { e.stopPropagation(); onFocusNode(p.source); }}>{p.source}</button>
              <span className="text-warn">—[{p.relation}]→</span>
              <button className="rounded bg-brand/10 px-1.5 py-0.5 font-medium text-brand hover:bg-brand/20"
                      onClick={(e) => { e.stopPropagation(); onFocusNode(p.target); }}>{p.target}</button>
              <Badge tone="bg-ink/5 text-muted">{p.score.toFixed(3)}</Badge>
              {p.occurrence > 1 && <Badge>{p.occurrence}×佐证</Badge>}
            </div>
          ))}
          {ev.paths.length > 14 && (
            <p className="text-muted">…另有 {ev.paths.length - 14} 条(已按分数排序)</p>
          )}
        </div>
      );

    case "evidence":
      return (
        <div className="space-y-1.5">
          <p className="text-muted">混合召回 {ev.items.length} 条原文</p>
          {ev.items.map((it) => (
            <button key={it.id}
                    className="block w-full rounded-md border-l-2 border-ok bg-ok/5 px-2 py-1.5 text-left hover:bg-ok/10"
                    onClick={(e) => { e.stopPropagation(); onOpenChunk(it.id); }}>
              <span className="flex items-center gap-1.5 text-[11px] font-medium text-ok">
                <span className="min-w-0 truncate">{shortHeading(it.heading)}</span>
                <Badge tone="bg-ok/10 text-ok">{it.method || "混合"} {it.score.toFixed(2)}</Badge>
                <code className="ml-auto shrink-0 font-mono text-[10px] opacity-70">{it.id}</code>
              </span>
              <span className="mt-0.5 block text-muted">{it.snippet}…</span>
            </button>
          ))}
        </div>
      );

    case "community":
      return (
        <div className="space-y-1.5">
          {ev.items.map((c, i) => (
            <div key={i} className="rounded-md bg-ink/[0.03] px-2 py-1.5">
              <p className="font-medium">{c.title}</p>
              <p className="text-muted">{c.summary}</p>
            </div>
          ))}
        </div>
      );

    case "reflect":
      return (
        <div className="space-y-1.5">
          <p className={cn("font-medium", ev.sufficient ? "text-ok" : "text-warn")}>
            {ev.sufficient ? "✔ 证据充分,进入作答" : "↻ 证据不足,继续下钻"}
          </p>
          <p className="text-muted">{ev.reason}</p>
          {ev.next_targets.length > 0 && (
            <div className="flex flex-wrap items-center gap-1.5">
              <span className="text-muted">下一步深挖</span>
              {ev.next_targets.map((t) => <Pill key={t} color="#a855f7">{t}</Pill>)}
            </div>
          )}
        </div>
      );

    case "context": {
      const pct = Math.round((ev.used_tokens / Math.max(1, ev.budget)) * 100);
      const dropped = Object.entries(ev.dropped).filter(([, v]) => v > 0);
      return (
        <div className="space-y-1.5">
          <p className="text-muted">
            按 token 预算排序装配(<b className="text-ink tabular-nums">{ev.used_tokens}</b> / {ev.budget},{pct}%)
          </p>
          <div className="h-1.5 w-full overflow-hidden rounded-full bg-ink/8">
            <i className="block h-full rounded-full bg-brand2" style={{ width: `${Math.min(100, pct)}%` }} />
          </div>
          <div className="flex flex-wrap gap-1.5">
            <Badge>实体 {ev.counts.entities}</Badge>
            <Badge>关系 {ev.counts.relations}</Badge>
            <Badge>原文 {ev.counts.chunks}</Badge>
            {ev.counts.communities > 0 && <Badge>主题 {ev.counts.communities}</Badge>}
          </div>
          {dropped.length > 0 && (
            <p className="text-[11px] text-muted">
              预算不足,按分数低的先舍弃:{dropped.map(([k, v]) => `${k} ${v}`).join("、")}
            </p>
          )}
        </div>
      );
    }

    case "answer":
      return (
        <p className="text-muted">
          已综合子图关系与原文证据生成回答,耗时 {(ev.duration_ms / 1000).toFixed(1)} 秒,
          引用 {ev.citations.length} 处原文。
        </p>
      );

    case "error":
      return <p className="text-bad">{ev.error}</p>;

    default:
      return null;
  }
}