AgentTrace.tsx 28.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
/**
 * 多智能体推理过程的展示:
 * - ThinkingCard:嵌在每轮回答上方。进行中显示正在工作的 Agent、逐字流出的思考、最近的工具调用;
 *   结束后折叠成一行摘要。
 * - TraceView:右侧面板里的完整推理链(按 Agent 分组的时间线树),每一步都能展开看参数、多跳路径、
 *   反思、SQL 与结果 —— 给领导看的是过程,给实施排错的是证据。
 * - GraphView:本体图谱,随推理逐跳生长。
 * - DataView:本轮所有取数。
 */
import {
  ArrowRight, BookOpen, Brain, CheckCircle2, ChevronDown, ChevronRight, CircleDot, Database, FileText, GitBranch,
  History, Lightbulb, Loader2, RotateCw, Search, Sparkles, Target, XCircle, Zap,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Badge, CopyButton, Empty } from "@/components/ui";
import { SigmaGraph, type SigmaGraphHandle } from "@/features/graph/SigmaGraph";
import { pageOfKind } from "@/features/ontology/routes";
import { go } from "@/lib/nav";
import { cn } from "@/lib/utils";
import { DataTable } from "./DataTable";
import { buildGraph, traceSummary, type AgentNode, type ToolNode, type TraceState } from "./trace";

export const AGENT_STYLE: Record<string, { color: string; icon: React.ReactNode; label: string }> = {
  lead: { color: "#6366f1", icon: <Brain className="h-3.5 w-3.5" />, label: "主持" },
  knowledge: { color: "#10b981", icon: <BookOpen className="h-3.5 w-3.5" />, label: "查资料" },
  data: { color: "#0ea5e9", icon: <Database className="h-3.5 w-3.5" />, label: "查数据" },
  action: { color: "#f43f5e", icon: <Zap className="h-3.5 w-3.5" />, label: "给办法" },
};
const styleOf = (agent: string) => AGENT_STYLE[agent] || { color: "#64748b", icon: <CircleDot className="h-3.5 w-3.5" />, label: agent };

const INTENT_LABEL: Record<string, string> = {
  knowledge: "知识", data: "数据", mixed: "数据 + 知识", impact: "影响分析", process: "流程", action: "行动",
  meta: "元信息", chitchat: "闲聊",
};

function StatusIcon({ status, className }: { status: string; className?: string }) {
  if (status === "running") return <Loader2 className={cn("h-3.5 w-3.5 animate-spin text-brand2", className)} />;
  if (status === "error") return <XCircle className={cn("h-3.5 w-3.5 text-bad", className)} />;
  return <CheckCircle2 className={cn("h-3.5 w-3.5 text-ok", className)} />;
}

function AgentChip({ a }: { a: AgentNode }) {
  const st = styleOf(a.agent);
  return (
    <span className={cn("relative inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-label font-medium",
      a.status === "running" && "agent-pulse")}
          style={{ background: `${st.color}18`, color: st.color, boxShadow: `inset 0 0 0 1px ${st.color}40`,
                   ["--pulse" as any]: `${st.color}55` }}>
      {st.icon}{a.label || st.label}
      {a.status === "running" ? <Loader2 className="h-3 w-3 animate-spin" />
        : a.status === "error" ? <XCircle className="h-3 w-3" /> : <CheckCircle2 className="h-3 w-3" />}
    </span>
  );
}

// ------------------------------------------------------------------ 思考卡
export function ThinkingCard({ trace, running, durationMs, onOpenPanel, onReplay, canReplay }: {
  trace: TraceState; running: boolean; durationMs?: number;
  onOpenPanel: () => void; onReplay?: () => void; canReplay?: boolean;
}) {
  const [open, setOpen] = useState(running);
  useEffect(() => { setOpen(running); }, [running]);
  const agents = trace.order.map((s) => trace.agents[s]).filter(Boolean);
  const active = [...agents].reverse().find((a) => a.status === "running" && a.thought) ||
    [...agents].reverse().find((a) => a.thought);
  const tools = Object.values(trace.tools).sort((a, b) => a.startTs - b.startTs);
  const recent = tools.slice(-4);
  const summary = traceSummary(trace, durationMs);
  const empty = !agents.length && !trace.links;

  return (
    <div className={cn("overflow-hidden rounded-xl border transition-colors",
      running ? "border-brand/40 bg-brand/[0.03] thinking-glow" : "border-line bg-surface")}>
      <div className="flex items-center gap-2 px-3 py-2">
        <button className="flex min-w-0 flex-1 items-center gap-2 text-left" onClick={() => setOpen((v) => !v)}>
          <ChevronRight className={cn("h-3.5 w-3.5 shrink-0 text-muted transition-transform", open && "rotate-90")} />
          {running ? <Sparkles className="h-4 w-4 shrink-0 animate-pulse text-brand" /> : <Brain className="h-4 w-4 shrink-0 text-brand" />}
          <span className="shrink-0 text-label font-medium">{running ? "正在思考" : "推理过程"}</span>
          {running && <span className="thinking-dots text-brand" aria-hidden><i /><i /><i /></span>}
          <span className="min-w-0 flex-1 truncate text-label text-muted">
            {summary || (running ? "理解问题,对照本体…" : "")}
          </span>
        </button>
        {!running && canReplay && onReplay && (
          <button className="btn btn-ghost btn-sm shrink-0 text-muted" onClick={onReplay} title="按原节奏重播推理过程">
            <History className="h-3.5 w-3.5" /> 回放
          </button>
        )}
        <button className="btn btn-ghost btn-sm shrink-0 text-muted" onClick={onOpenPanel} title="在右侧查看完整推理链与图谱">
          <GitBranch className="h-3.5 w-3.5" /> 详情
        </button>
      </div>
      {open && (
        <div className="space-y-2.5 border-t border-line/70 px-3 py-2.5">
          {empty && <p className="flex items-center gap-1.5 text-label text-muted"><Loader2 className="h-3.5 w-3.5 animate-spin" /> 正在理解问题…</p>}
          {trace.links && (trace.links.concepts.length > 0 || trace.links.instances.length > 0) && (
            <div className="flex flex-wrap items-center gap-1.5 text-label">
              <Target className="h-3.5 w-3.5 text-muted" />
              <span className="text-muted">对应到本体:</span>
              {trace.links.concepts.slice(0, 8).map((c: any) => (
                <span key={c.id} className="rounded-md bg-brand/10 px-1.5 py-0.5 text-brand animate-fade-up">{c.name}</span>
              ))}
              {trace.links.instances.slice(0, 5).map((i: any) => (
                <span key={`${i.concept_id}:${i.key}`} className="rounded-md bg-ink/5 px-1.5 py-0.5 animate-fade-up">{i.type_name}:{i.label}</span>
              ))}
            </div>
          )}
          {trace.memory && (trace.memory.cases.length > 0 || trace.memory.facts.length > 0) && (
            <p className="flex items-center gap-1.5 text-label text-muted animate-fade-up">
              <History className="h-3.5 w-3.5" />
              {trace.memory.fast ? "命中已验证案例,复用当时的分析路径" :
                `参考 ${trace.memory.cases.length} 个相似案例${trace.memory.facts.length ? `、${trace.memory.facts.length} 条组织记忆` : ""}`}
            </p>
          )}
          {agents.length > 0 && (
            <div className="flex flex-wrap items-center gap-1.5">
              {agents.map((a, i) => (
                <span key={a.span} className="flex items-center gap-1.5">
                  {i > 0 && <ArrowRight className="h-3 w-3 text-muted/60" />}
                  <AgentChip a={a} />
                </span>
              ))}
            </div>
          )}
          {active?.thought && (
            <div className="rounded-lg bg-ink/[0.03] px-2.5 py-2 text-label leading-relaxed">
              <span className="mr-1.5 font-medium" style={{ color: styleOf(active.agent).color }}>{active.label}:</span>
              <span className="text-ink/80">{running ? active.thought.slice(-220) : active.thought}</span>
              {running && active.status === "running" && <span className="typing-caret" />}
            </div>
          )}
          {recent.length > 0 && (
            <ul className="space-y-1">
              {recent.map((t) => (
                <li key={t.span} className="flex items-center gap-2 text-label animate-fade-up">
                  <StatusIcon status={t.status} />
                  <span className="shrink-0 rounded px-1 text-caption font-medium"
                        style={{ background: `${styleOf(t.agent).color}18`, color: styleOf(t.agent).color }}>
                    {styleOf(t.agent).label}
                  </span>
                  <span className="shrink-0 font-medium">{t.label}</span>
                  <span className="min-w-0 flex-1 truncate text-muted">{t.error || t.summary || liveHint(t) || t.why}</span>
                </li>
              ))}
              {tools.length > recent.length && <li className="text-caption text-muted">…共 {tools.length} 次调用,点「详情」看全部</li>}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}

/** 工具还在跑时,从它的过程事件里挑一句最新进展。 */
function liveHint(t: ToolNode): string {
  const ev = t.events[t.events.length - 1];
  if (!ev) return "";
  switch (ev.type) {
    case "understand": return `拆出检索词:${(ev.entities || []).slice(0, 4).join("、")}`;
    case "link": return `定位到 ${(ev.links || []).reduce((n: number, l: any) => n + (l.matches?.length || 0), 0)} 个图谱入口`;
    case "hop": return `第 ${ev.round} 轮扩展:新增 ${(ev.paths || []).length} 条关系`;
    case "evidence": return `召回 ${(ev.items || []).length} 段原文`;
    case "reflect": return ev.sufficient ? "证据充分" : `证据不足,继续下钻:${(ev.next_targets || []).join("、")}`;
    case "data_route": return ev.route === "metric" ? "按已定义指标确定性取数" : "生成只读 SQL";
    case "sql_draft": case "sql": return "SQL 已生成,校验中";
    case "validate": return "只读校验";
    case "repair": return "SQL 自动修复";
    case "execute": case "rows": return "执行查询";
    default: return "";
  }
}

// ------------------------------------------------------------------ 推理链
export function TraceView({ trace, onOpenChunk }: { trace: TraceState; onOpenChunk?: (id: string) => void }) {
  const lead = trace.order.map((s) => trace.agents[s]).find((a) => a?.agent === "lead");
  const subs = trace.order.map((s) => trace.agents[s]).filter((a) => a && a.agent !== "lead");
  if (!lead && !subs.length && !trace.links) {
    return <Empty icon={<Brain className="h-8 w-8" />} title="提问后这里会显示过程" />;
  }
  return (
    <div className="space-y-3">
      {trace.links && (
        <Section icon={<Target className="h-3.5 w-3.5" />} title="对应到本体">
          <div className="flex flex-wrap gap-1.5">
            {trace.links.concepts.map((c: any) => (
              <button key={c.id} className="chip" onClick={() => go(pageOfKind(c.kind), { id: c.id })}
                      title={c.matched?.length ? `问句中:${c.matched.join("、")}` : ""}>{c.name}</button>
            ))}
            {trace.links.instances.map((i: any) => (
              <button key={`${i.concept_id}:${i.key}`} className="chip"
                      onClick={() => go("objects", { type: i.concept_id, key: i.key })}>{i.type_name}:{i.label}</button>
            ))}
            {trace.links.time && <Badge tone="bg-ok/10 text-ok">时间:{trace.links.time.phrase || trace.links.time.ref}</Badge>}
            {!trace.links.concepts.length && !trace.links.instances.length && !trace.links.time &&
              <span className="text-label text-muted">没有直接对上已有的定义,按问题本身理解</span>}
          </div>
        </Section>
      )}
      {trace.used.length > 0 && (
        <Section icon={<Target className="h-3.5 w-3.5" />} title="本次用到的本体">
          <div className="flex flex-wrap gap-1.5">
            {trace.used.map((u) => (
              <button key={u.id || u.name} className="chip border-brand/40" disabled={!u.id}
                      onClick={() => u.id && go(pageOfKind(u.kind_label.includes("动作") ? "action" : u.kind_label.includes("对象") ? "object_type" : "function"), { id: u.id })}
                      title={`${u.kind_label} · ${u.how}`}>
                <span className="text-caption text-muted">{u.how}</span>{u.name}
              </button>
            ))}
          </div>
        </Section>
      )}
      {trace.memory && (trace.memory.cases.length > 0 || trace.memory.facts.length > 0) && (
        <Section icon={<History className="h-3.5 w-3.5" />} title="经验召回">
          <ul className="space-y-1 text-label">
            {trace.memory.cases.map((c: any) => (
              <li key={c.id} className="flex items-center gap-2">
                <Badge tone={c.id === trace.memory?.fast ? "bg-ok/10 text-ok" : c.status === "verified" ? "bg-brand/10 text-brand" : "bg-ink/5 text-muted"}>
                  {c.id === trace.memory?.fast ? "复用路径" : c.status === "verified" ? "已验证" : "参考"}
                </Badge>
                <span className="min-w-0 flex-1 truncate">{c.question}</span>
                {typeof c.score === "number" && <span className="shrink-0 tabular-nums text-muted">{Math.round(c.score * 100)}%</span>}
              </li>
            ))}
            {trace.memory.facts.map((f: any) => (
              <li key={f.id} className="flex items-start gap-2 text-muted">
                <Lightbulb className="mt-0.5 h-3 w-3 shrink-0 text-warn" /><span>{f.text}</span>
              </li>
            ))}
          </ul>
        </Section>
      )}
      {lead && <AgentBlock a={lead} trace={trace} onOpenChunk={onOpenChunk} plan={trace.plan} />}
      {subs.length > 0 && (
        <div className="relative space-y-3 border-l-2 border-dashed border-line pl-3">
          {subs.map((a) => <AgentBlock key={a.span} a={a} trace={trace} onOpenChunk={onOpenChunk} />)}
        </div>
      )}
      {trace.reflect.map((r, i) => (
        <Section key={i} icon={<RotateCw className="h-3.5 w-3.5" />} title="复查">
          <p className="text-label">
            {r.sufficient ? <span className="text-ok">✔ 信息足够,开始作答</span>
              : <span className="text-warn">↻ 信息不足:{r.missing || "需要补充"},追加分派</span>}
          </p>
        </Section>
      ))}
    </div>
  );
}

function Section({ icon, title, children }: { icon: React.ReactNode; title: string; children: React.ReactNode }) {
  return (
    <div className="rounded-lg border border-line p-2.5 animate-fade-up">
      <p className="mb-1.5 flex items-center gap-1.5 text-label font-medium text-muted">{icon}{title}</p>
      {children}
    </div>
  );
}

function AgentBlock({ a, trace, plan, onOpenChunk }: {
  a: AgentNode; trace: TraceState; plan?: any; onOpenChunk?: (id: string) => void;
}) {
  const st = styleOf(a.agent);
  const tools = a.tools.map((s) => trace.tools[s]).filter(Boolean);
  return (
    <div className="rounded-lg border bg-surface animate-fade-up" style={{ borderColor: `${st.color}40` }}>
      <div className="flex items-center gap-2 rounded-t-lg px-2.5 py-1.5" style={{ background: `${st.color}10` }}>
        <span style={{ color: st.color }}>{st.icon}</span>
        <span className="text-label font-semibold" style={{ color: st.color }}>{a.label || st.label}</span>
        <StatusIcon status={a.status} />
        {typeof a.confidence === "number" && a.status !== "running" && (
          <span className="ml-auto flex items-center gap-1 text-caption text-muted" title="对这一步结果的把握">
            把握
            <span className="h-1.5 w-12 overflow-hidden rounded-full bg-ink/10">
              <span className="block h-full rounded-full" style={{ width: `${Math.round(a.confidence * 100)}%`, background: st.color }} />
            </span>
          </span>
        )}
        {a.ms ? <span className={cn("text-caption tabular-nums text-muted", typeof a.confidence !== "number" && "ml-auto")}>{(a.ms / 1000).toFixed(1)}s</span> : null}
      </div>
      <div className="space-y-2 px-2.5 py-2">
        {a.task && a.agent !== "lead" && <p className="text-label"><span className="text-muted">任务:</span>{a.task}</p>}
        {a.thought && (
          <p className="whitespace-pre-wrap rounded-md bg-ink/[0.03] px-2 py-1.5 text-label leading-relaxed text-ink/85">
            {a.thought}{a.status === "running" && <span className="typing-caret" />}
          </p>
        )}
        {plan && a.agent === "lead" && (
          <div className="space-y-1 text-label">
            <p className="flex flex-wrap items-center gap-1.5">
              {plan.intent && <Badge tone="bg-brand/10 text-brand">{INTENT_LABEL[plan.intent] || plan.intent}</Badge>}
              {plan.from_case && <Badge tone="bg-ok/10 text-ok">复用已验证案例</Badge>}
              {plan.lane && <Badge variant="info" title={plan.why}>{plan.lane_label || "快速通道"}</Badge>}
              {plan.rewrite && <span className="text-muted">理解为:{plan.rewrite}</span>}
            </p>
            {(plan.delegations || []).map((d: any, i: number) => (
              <p key={i} className="flex items-center gap-1.5">
                <ArrowRight className="h-3 w-3 text-muted" />
                <span className="font-medium" style={{ color: styleOf(d.agent).color }}>{styleOf(d.agent).label}</span>
                <span className="min-w-0 flex-1 truncate text-muted">{d.task}</span>
              </p>
            ))}
          </div>
        )}
        {tools.length > 0 && <div className="space-y-1">{tools.map((t) => <ToolRow key={t.span} t={t} onOpenChunk={onOpenChunk} />)}</div>}
        {a.status !== "running" && a.agent !== "lead" && (a.summary || a.findings.length > 0 || a.insights.length > 0) && (
          <div className="rounded-md border border-line/70 px-2 py-1.5 text-label">
            {a.summary && <p><span className="text-muted">结论:</span>{a.summary}</p>}
            {a.findings.map((f, i) => <p key={i} className="text-ink/80">· {f}</p>)}
            {a.insights.map((f, i) => <p key={`i${i}`} className="flex items-start gap-1 text-warn"><Lightbulb className="mt-0.5 h-3 w-3 shrink-0" />{f}</p>)}
          </div>
        )}
      </div>
    </div>
  );
}

function ToolRow({ t, onOpenChunk }: { t: ToolNode; onOpenChunk?: (id: string) => void }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="rounded-md border border-line">
      <button className="flex w-full items-center gap-2 px-2 py-1.5 text-left" onClick={() => setOpen((v) => !v)}>
        <StatusIcon status={t.status} />
        <span className="shrink-0 text-label font-medium">{t.label}</span>
        <span className="min-w-0 flex-1 truncate text-label text-muted">{t.error || t.summary || liveHint(t) || t.why}</span>
        {t.ms ? <span className="shrink-0 text-caption tabular-nums text-muted">{(t.ms / 1000).toFixed(1)}s</span> : null}
        <ChevronDown className={cn("h-3 w-3 shrink-0 text-muted transition-transform", open && "rotate-180")} />
      </button>
      {open && (
        <div className="space-y-2 border-t border-line p-2 text-label">
          {t.why && <p className="text-muted">为什么:{t.why}</p>}
          <details>
            <summary className="cursor-pointer text-label text-muted">调用参数({t.tool})</summary>
            <pre className="mt-1 max-h-32 overflow-auto rounded bg-ink/5 p-2 font-mono text-caption">{JSON.stringify(t.args, null, 2)}</pre>
          </details>
          <EventList events={t.events} onOpenChunk={onOpenChunk} />
          <ResultView r={t.result} onOpenChunk={onOpenChunk} />
          {t.error && <p className="text-bad">失败:{t.error}</p>}
        </div>
      )}
    </div>
  );
}

/** 工具内部的过程事件:知识检索的理解 → 定位 → 逐跳扩展 → 证据 → 反思;问数的选路 → SQL → 校验 → 执行。 */
function EventList({ events, onOpenChunk }: { events: any[]; onOpenChunk?: (id: string) => void }) {
  if (!events.length) return null;
  return (
    <ol className="space-y-1.5 border-l border-line pl-2.5">
      {events.map((ev, i) => {
        if (!ev || typeof ev !== "object") return null;
        switch (ev.type) {
          case "understand":
            return <li key={i}><b className="text-label">理解</b> <span className="text-muted">检索词</span> {(ev.entities || []).concat(ev.keywords || []).slice(0, 10).map((x: string) => <span key={x} className="mr-1 rounded bg-ink/5 px-1">{x}</span>)}</li>;
          case "link":
            return (
              <li key={i}><b className="text-label">定位入口</b>
                {(ev.links || []).map((l: any, j: number) => (
                  <span key={j} className="ml-1 text-muted">{l.term} → {(l.matches || []).slice(0, 2).map((m: any) => `${m.label}(${Math.round((m.score || 0) * 100)}%)`).join("、") || "无"};</span>
                ))}
              </li>
            );
          case "hop":
            return (
              <li key={i}>
                <b className="text-label">第 {ev.round} 轮图谱扩展</b>
                <span className="ml-1 text-muted">新增 {(ev.paths || []).length} 条关系{ev.pruned ? `,剪掉 ${ev.pruned} 条弱相关` : ""}</span>
                <ul className="mt-0.5 space-y-0.5">
                  {(ev.paths || []).slice(0, 6).map((p: any) => (
                    <li key={p.id} className="flex items-center gap-1 text-label">
                      <span className="truncate">{p.source}</span>
                      <span className="shrink-0 rounded bg-warn/10 px-1 text-warn">{p.relation}</span>
                      <ArrowRight className="h-3 w-3 shrink-0 text-muted" />
                      <span className="truncate">{p.target}</span>
                    </li>
                  ))}
                  {(ev.paths || []).length > 6 && <li className="text-caption text-muted">…其余 {(ev.paths || []).length - 6} 条</li>}
                </ul>
              </li>
            );
          case "evidence":
            return (
              <li key={i}><b className="text-label">第 {ev.round} 轮证据</b>
                <ul className="mt-0.5 space-y-0.5">
                  {(ev.items || []).slice(0, 4).map((c: any) => (
                    <li key={c.id}>
                      <button className="flex w-full items-start gap-1 text-left text-label hover:text-brand"
                              onClick={() => onOpenChunk?.(c.id)}>
                        <FileText className="mt-0.5 h-3 w-3 shrink-0 text-muted" />
                        <span className="line-clamp-1">{c.heading || c.id}:{c.snippet}</span>
                      </button>
                    </li>
                  ))}
                </ul>
              </li>
            );
          case "reflect":
            return (
              <li key={i}><b className="text-label">反思</b>{" "}
                {ev.sufficient ? <span className="text-ok">✔ 证据充分</span>
                  : <span className="text-warn">↻ 证据不足,继续下钻:{(ev.next_targets || []).join("、")}</span>}
                {ev.reason && <span className="ml-1 text-muted">{ev.reason}</span>}
              </li>
            );
          case "community":
            return <li key={i}><b className="text-label">主题</b> <span className="text-muted">{(ev.items || []).map((x: any) => x.title).join("、")}</span></li>;
          case "data_route":
            return <li key={i}><b className="text-label">选路</b> <span className="text-muted">{ev.route === "metric" ? "按已定义指标确定性取数" : ev.route === "clarify" ? "需要追问" : "生成只读 SQL"}{ev.detail?.why ? `(${ev.detail.why})` : ""}</span></li>;
          case "sql":
            return (
              <li key={i}><b className="text-label">SQL</b>
                <pre className="mt-0.5 max-h-28 overflow-auto rounded bg-ink/5 p-1.5 font-mono text-caption">{ev.sql}</pre>
              </li>
            );
          case "validate":
            return <li key={i}><b className="text-label">只读校验</b> <span className={ev.ok === false ? "text-bad" : "text-ok"}>{ev.ok === false ? "未通过" : "通过"}</span></li>;
          case "repair":
            return <li key={i}><b className="text-label">自动修复</b> <span className="text-muted">{ev.reason || ev.error || ""}</span></li>;
          case "execute":
            return <li key={i}><b className="text-label">执行</b> <span className="text-muted">{ev.row_count != null ? `${ev.row_count} 行` : ""}{ev.duration_ms ? ` · ${ev.duration_ms}ms` : ""}</span></li>;
          case "error":
            return <li key={i} className="text-bad"><b className="text-label">出错</b> {ev.error}</li>;
          default:
            return null;
        }
      })}
    </ol>
  );
}

function ResultView({ r, onOpenChunk }: { r: any; onOpenChunk?: (id: string) => void }) {
  if (!r || typeof r !== "object") return null;
  return (
    <div className="space-y-1.5">
      {Array.isArray(r.columns) && r.columns.length > 0 && <DataTable columns={r.columns} rows={Array.isArray(r.rows) ? r.rows : []} max={15} />}
      {Array.isArray(r.chunks) && r.chunks.length > 0 && (
        <ul className="space-y-0.5">
          {r.chunks.slice(0, 5).map((c: any) => (
            <li key={c.id}>
              <button className="flex w-full items-start gap-1 text-left text-label hover:text-brand" onClick={() => onOpenChunk?.(c.id)}>
                <FileText className="mt-0.5 h-3 w-3 shrink-0 text-muted" />
                <span className="line-clamp-2"><b>{c.heading || c.id}</b> {c.text}</span>
              </button>
            </li>
          ))}
        </ul>
      )}
      {r.concept && <p className="text-label"><b>{r.concept.name}</b>:{r.concept.description}</p>}
      {Array.isArray(r.layers) && (
        <ul className="space-y-0.5 text-label">
          {r.layers.map((l: any) => (
            <li key={l.depth}>第 {l.depth} 跳:{(l.groups || []).map((g: any) => `${g.type_name} ${g.count}`).join("、")}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

// ------------------------------------------------------------------ 图谱
export function GraphView({ trace }: { trace: TraceState }) {
  const ref = useRef<SigmaGraphHandle>(null);
  const { payload, emphasis } = useMemo(() => buildGraph(trace), [trace]);
  // 图在长:力导布局每次停下来,把镜头拉回全图,别让新节点跑到画面外
  const onLayout = useCallback((running: boolean) => { if (!running) ref.current?.reset(); }, []);
  if (!payload) {
    return (
      <div className="flex h-full items-center justify-center px-6 text-center text-label text-muted">
        <div><Search className="mx-auto mb-2 h-6 w-6 text-muted/40" />
          命中的本体概念、知识图谱里逐跳扩展出的关系、关系网上受影响的对象,会实时画在这里。</div>
      </div>
    );
  }
  return (
    <div className="relative h-full min-h-[320px]">
      <SigmaGraph ref={ref} data={payload} emphasis={emphasis} showNodeLabels showEdgeLabels layout="forceatlas2"
                  onLayoutStateChange={onLayout} />
      <div className="absolute right-2 top-2 flex gap-1">
        <button className="btn btn-sm" onClick={() => ref.current?.reset()}>适配</button>
        <button className="btn btn-sm" onClick={() => ref.current?.exportPNG("推理图谱.png")}>导出</button>
      </div>
      <p className="absolute bottom-2 left-2 rounded bg-surface/80 px-1.5 text-caption text-muted">
        {payload.nodes.length} 个节点 · {payload.edges.length} 条关系
      </p>
    </div>
  );
}

// ------------------------------------------------------------------ 数据
export function DataView({ trace }: { trace: TraceState }) {
  const runs = Object.values(trace.tools).filter((t) => t.result && Array.isArray(t.result.columns));
  if (!runs.length) return <Empty icon={<Database className="h-8 w-8" />} title="这一轮没有取数" />;
  return (
    <div className="space-y-4">
      {runs.map((t) => {
        const sql = t.result.sql || t.events.find((e) => e?.type === "sql")?.sql || "";
        return (
          <div key={t.span} className="space-y-1.5">
            <p className="flex items-center gap-2 text-label font-medium">
              <Database className="h-3.5 w-3.5 text-brand2" />
              {t.result.metric?.name || t.label}
              {t.result.route && <Badge>{t.result.route === "metric" ? "指标确定性取数" : "生成 SQL"}</Badge>}
              {t.result.run_id ? <span className="text-muted">取数记录 #{t.result.run_id}</span> : null}
            </p>
            {(t.result.notes || []).map((n: string, i: number) => <p key={i} className="text-label text-warn">⚠ {n}</p>)}
            {sql && (
              <div>
                <div className="flex items-center justify-between"><span className="text-caption text-muted">SQL(只读校验通过)</span><CopyButton text={sql} /></div>
                <pre className="max-h-32 overflow-auto rounded bg-ink/5 p-2 font-mono text-caption">{sql}</pre>
              </div>
            )}
            <DataTable columns={t.result.columns} rows={Array.isArray(t.result.rows) ? t.result.rows : []} max={30} />
          </div>
        );
      })}
    </div>
  );
}