QueryPage.tsx 16.5 KB
import { CornerDownLeft, History, Loader2, Send, Sparkles, Square, Trash2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api } from "@/lib/api";
import { cn, formatDuration, formatTime, MODE_INFO, shortHeading } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { useQueryStore, type QueryTurn } from "@/store/useQueryStore";
import { Badge, Card, ErrorNote, Modal, Skeleton } from "@/components/ui";
import type { ChunkRecord, GraphPayload, QueryBrief, QueryMode, TraceEvent } from "@/lib/types";
import { SigmaGraph, type SigmaGraphHandle } from "../graph/SigmaGraph";
import { AnswerPanel } from "./AnswerPanel";
import { TraceTimeline } from "./TraceTimeline";

const EXAMPLES = [
  "门店没达标要赔多少钱?怎么算的?",
  "生态系数怎么评分?和哪些渗透率有关?",
  "生态月和自然月怎么判断,对取数有什么影响?",
  "策略盯防的 T-1/T/T+1 是怎么定义的?",
  "整个门店运营数据分析平台由哪几块能力组成?",
];

const MODES: QueryMode[] = ["agentic", "mix", "hybrid", "local", "global", "naive"];

/**
 * 深挖检索:左右两栏,左边是对话框(提问在最下面,检索轨迹 + 回答依次往上滚动输出,
 * 和 Claude / ChatGPT 的对话形式一致),右边整栏放命中子图,方便盯着图看。
 */
export function QueryPage() {
  const s = useQueryStore();
  const sigmaRef = useRef<SigmaGraphHandle>(null);
  const taRef = useRef<HTMLTextAreaElement>(null);
  const feedRef = useRef<HTMLDivElement>(null);
  const [history, setHistory] = useState<QueryBrief[]>([]);
  const [chunk, setChunk] = useState<ChunkRecord | null>(null);
  const [chunkLoading, setChunkLoading] = useState(false);
  const [showHistory, setShowHistory] = useState(false);

  const refreshHistory = useCallback(() => {
    void api.queries(20).then(setHistory).catch(() => undefined);
  }, []);
  useEffect(refreshHistory, [refreshHistory]);
  const latestTurn = s.turns[s.turns.length - 1] ?? null;
  useEffect(() => { if (!s.running && latestTurn?.answer) refreshHistory(); }, [s.running, latestTurn?.answer, refreshHistory]);

  // 提问/检索/回答产生新内容时,对话区自动滚到底部
  useEffect(() => {
    if (s.running) feedRef.current?.scrollTo({ top: feedRef.current.scrollHeight, behavior: "smooth" });
  }, [s.running, latestTurn?.trace.length, latestTurn?.answer.length]);

  // 右栏子图:跟随"当前聚焦的轮次"(默认最新一轮;点某一轮的某个步骤会切过去并回放到那一步)
  const focusedTurn = useMemo(() => {
    if (s.replay) {
      const t = s.turns.find((x) => x.id === s.replay!.turnId);
      if (t) return t;
    }
    return latestTurn;
  }, [s.replay, s.turns, latestTurn]);
  const focusedReplayStep = s.replay && focusedTurn && s.replay.turnId === focusedTurn.id ? s.replay.step : null;
  const { payload, emphasis } = useMemo(
    () => buildSubgraph(focusedTurn?.trace ?? [], focusedReplayStep, focusedTurn?.subgraph ?? null),
    [focusedTurn, focusedReplayStep],
  );

  const openChunk = async (id: string) => {
    setChunkLoading(true);
    setChunk(null);
    try {
      setChunk(await api.chunk(id));
    } catch (e) {
      toast("error", "原文片段加载失败", e instanceof Error ? e.message : undefined);
    } finally {
      setChunkLoading(false);
    }
  };

  const focusNodeInTurn = (turnId: number, id: string) => {
    s.setReplay({ turnId, step: null });
    setTimeout(() => sigmaRef.current?.focusNode(id), 60);
  };

  const submit = () => {
    if (!s.question.trim()) { toast("warn", "请先输入问题"); return; }
    s.ask();
  };
  const retryLast = () => {
    if (!latestTurn) return;
    s.setQuestion(latestTurn.question);
    setTimeout(() => useQueryStore.getState().ask(), 0);
  };

  return (
    <div className="grid h-full min-h-0 gap-3 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,1fr)]">
      {/* 左栏:对话框 */}
      <Card className="flex min-h-[480px] flex-col overflow-hidden">
        <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-line px-3 py-2">
          <div className="flex flex-wrap items-center gap-0.5 rounded-lg border border-line p-0.5">
            {MODES.map((m) => (
              <button key={m}
                      title={MODE_INFO[m].desc}
                      className={cn("rounded-md px-2 py-1 text-xs transition-colors",
                        s.mode === m ? "bg-brand text-white" : "text-muted hover:bg-ink/5")}
                      onClick={() => s.setMode(m)}>
                {MODE_INFO[m].name}
              </button>
            ))}
          </div>
          <p className="hidden min-w-0 flex-1 truncate text-[11px] text-muted sm:block">{MODE_INFO[s.mode].desc}</p>
          {s.running && <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-brand" />}
          <button className="btn btn-sm ml-auto" onClick={() => setShowHistory(true)}>
            <History className="h-3.5 w-3.5" />历史
          </button>
          {s.turns.length > 0 && (
            <button className="btn btn-sm" onClick={s.reset}><Trash2 className="h-3.5 w-3.5" />清空</button>
          )}
        </div>

        {/* 消息流 */}
        <div ref={feedRef} className="min-h-0 flex-1 overflow-auto px-3 py-3">
          {s.turns.length === 0 ? (
            <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center">
              <CornerDownLeft className="h-7 w-7 text-muted/40" />
              <div>
                <p className="text-[13px] font-medium">还没有开始检索</p>
                <p className="mx-auto mt-1 max-w-xs text-xs leading-relaxed text-muted">
                  和黑盒 RAG 不同,这里会把大模型的每一步都摊开:拆了哪些词、命中哪些节点、
                  沿哪些边扩展、剪掉了多少低分候选、为什么判断还要继续挖。
                </p>
              </div>
              <div className="flex flex-wrap justify-center gap-1.5">
                {EXAMPLES.map((q) => (
                  <button key={q} className="chip hover:border-brand/50"
                          onClick={() => { s.setQuestion(q); setTimeout(() => useQueryStore.getState().ask(), 0); }}>
                    {q}
                  </button>
                ))}
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              {s.turns.map((turn) => (
                <TurnBlock key={turn.id} turn={turn}
                           replayStep={s.replay && s.replay.turnId === turn.id ? s.replay.step : null}
                           onReplay={(n) => s.setReplay(n === null ? null : { turnId: turn.id, step: n })}
                           onOpenChunk={openChunk}
                           onFocusNode={(id) => focusNodeInTurn(turn.id, id)} />
              ))}
            </div>
          )}
        </div>

        {/* 提问区:固定在底部 */}
        <div className="shrink-0 border-t border-line p-3">
          {latestTurn?.error && !s.running && (
            <div className="mb-2"><ErrorNote onRetry={retryLast}>{latestTurn.error}</ErrorNote></div>
          )}
          <div className="flex gap-2">
            <textarea
              ref={taRef}
              className="input min-h-[46px] resize-y py-2"
              rows={2}
              placeholder="输入一个业务问题…(Ctrl/⌘ + Enter 开始检索)"
              value={s.question}
              onChange={(e) => s.setQuestion(e.target.value)}
              onKeyDown={(e) => {
                if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); submit(); }
              }}
            />
            <div className="flex shrink-0 flex-col gap-1.5">
              {s.running ? (
                <button className="btn btn-danger h-full px-4" onClick={s.stop}>
                  <Square className="h-3.5 w-3.5" />停止
                </button>
              ) : (
                <button className="btn btn-primary h-full px-4" onClick={submit} disabled={!s.question.trim()}>
                  <Send className="h-3.5 w-3.5" />发送
                </button>
              )}
            </div>
          </div>
        </div>
      </Card>

      {/* 右栏:命中子图,单独一整栏,方便看 */}
      <Card className="relative flex min-h-[420px] flex-col overflow-hidden">
        <div className="flex shrink-0 items-center gap-2 border-b border-line px-3 py-2">
          <h3 className="text-[13px] font-semibold">命中子图</h3>
          <span className="text-[11px] text-muted">
            {payload ? `${payload.nodes.length} 节点 · ${payload.edges.length} 关系` : "等待检索"}
            {focusedReplayStep !== null && " · 回放中"}
          </span>
          <div className="ml-auto flex gap-1">
            <button className="btn btn-ghost btn-sm" onClick={() => sigmaRef.current?.reset()}>适配</button>
            <button className="btn btn-ghost btn-sm"
                    onClick={() => sigmaRef.current?.exportPNG("subgraph.png")}>导出</button>
          </div>
        </div>
        <div className="min-h-0 flex-1">
          {payload && payload.nodes.length > 0 ? (
            <SigmaGraph ref={sigmaRef} data={payload} emphasis={emphasis}
                        showNodeLabels showEdgeLabels layout="forceatlas2" />
          ) : (
            <div className="flex h-full items-center justify-center px-6 text-center text-xs text-muted">
              <div>
                <Sparkles className="mx-auto mb-2 h-6 w-6 text-muted/40" />
                检索命中的节点与关系会实时画在这里,并随对话逐步生长。
                点一轮回答里的某个步骤,可以单独回放那一轮的子图。
              </div>
            </div>
          )}
        </div>
      </Card>

      {/* 原文片段 */}
      <Modal open={chunkLoading || !!chunk} onClose={() => setChunk(null)}
             title={chunk ? shortHeading(chunk.heading, 3) : "加载原文…"} width="max-w-3xl"
             bodyClass="p-0">
        {chunkLoading && <div className="space-y-2 p-4">
          {Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-3 w-full" />)}
        </div>}
        {chunk && (
          <div className="p-4">
            <div className="mb-2 flex flex-wrap items-center gap-1.5">
              <Badge tone="bg-brand/10 text-brand">{chunk.document?.filename ?? `文档 ${chunk.doc_id}`}</Badge>
              <Badge>{chunk.tokens} token</Badge>
              <code className="rounded bg-ink/5 px-1.5 py-0.5 font-mono text-[11px] text-muted">{chunk.id}</code>
            </div>
            {chunk.heading && <p className="mb-2 text-xs text-muted">{chunk.heading}</p>}
            <pre className="whitespace-pre-wrap break-words rounded-lg bg-ink/[0.04] p-3
                            font-sans text-[13px] leading-7">{chunk.text}</pre>
          </div>
        )}
      </Modal>

      {/* 历史 */}
      <Modal open={showHistory} onClose={() => setShowHistory(false)} title="检索历史" width="max-w-2xl"
             bodyClass="p-0">
        <div className="p-2">
          {history.length === 0 && <p className="p-4 text-center text-xs text-muted">还没有检索记录</p>}
          {history.map((h) => (
            <button key={h.id}
                    className="block w-full rounded-lg px-3 py-2 text-left hover:bg-ink/5"
                    onClick={async () => {
                      try {
                        const d = await api.queryDetail(h.id);
                        s.loadFromLog(d);
                        setShowHistory(false);
                      } catch (e) {
                        toast("error", "记录加载失败", e instanceof Error ? e.message : undefined);
                      }
                    }}>
              <div className="flex items-center gap-2">
                <span className="min-w-0 flex-1 truncate text-[13px] font-medium">{h.question}</span>
                <Badge>{MODE_INFO[h.mode]?.name ?? h.mode}</Badge>
                <span className="shrink-0 text-[11px] text-muted">{formatTime(h.created_at)}</span>
              </div>
              <p className="mt-0.5 truncate text-[11.5px] text-muted">
                {formatDuration(h.duration_ms)} · {h.answer_preview}
              </p>
            </button>
          ))}
        </div>
      </Modal>
    </div>
  );
}

/** 一轮问答:右侧用户问题气泡 + 下方检索轨迹(可折叠)与回答,依次往下排。 */
function TurnBlock({ turn, replayStep, onReplay, onOpenChunk, onFocusNode }: {
  turn: QueryTurn; replayStep: number | null; onReplay: (n: number | null) => void;
  onOpenChunk: (id: string) => void; onFocusNode: (id: string) => void;
}) {
  const hasSteps = turn.trace.some((t) => t.type !== "start");
  return (
    <div className="space-y-2">
      <div className="flex justify-end">
        <div className="max-w-[85%] whitespace-pre-wrap break-words rounded-2xl rounded-tr-sm
                        bg-brand/10 px-3 py-2 text-[13.5px] leading-relaxed text-ink">
          {turn.question}
        </div>
      </div>
      {turn.error && <ErrorNote>{turn.error}</ErrorNote>}
      {hasSteps && (
        <TraceTimeline trace={turn.trace} running={turn.running} replayStep={replayStep}
                       onReplay={onReplay} onOpenChunk={onOpenChunk} onFocusNode={onFocusNode} />
      )}
      <AnswerPanel embedded answer={turn.answer} streaming={turn.streaming} citations={turn.citations}
                   durationMs={turn.durationMs} onOpenChunk={onOpenChunk} />
    </div>
  );
}

/** 按轨迹(可截断到第 n 步)拼出用于渲染的子图 payload + 强调集合。 */
function buildSubgraph(trace: TraceEvent[], replayStep: number | null,
                       finalSub: { nodes: { id: string; label: string; type: string; seed: boolean; degree: number; community: number | null }[]; edges: { id: string; source: string; target: string; relation: string; occurrence: number }[] } | null) {
  const steps = trace.filter((t) => t.type !== "start");
  const upto = replayStep === null ? steps : steps.slice(0, replayStep + 1);

  const nodes = new Map<string, { label: string; type: string; degree: number; community: number | null; seed: boolean }>();
  const edges = new Map<string, { source: string; target: string; relation: string; occurrence: number }>();
  const seeds = new Set<string>();

  const meta = new Map<string, { type: string; degree: number; community: number | null }>();
  if (finalSub) for (const n of finalSub.nodes) meta.set(n.id, { type: n.type, degree: n.degree, community: n.community });

  const addNode = (id: string, label?: string, type?: string, seed = false) => {
    const m = meta.get(id);
    const cur = nodes.get(id);
    nodes.set(id, {
      label: label ?? cur?.label ?? id,
      type: type ?? m?.type ?? cur?.type ?? "其他",
      degree: m?.degree ?? cur?.degree ?? 2,
      community: m?.community ?? cur?.community ?? null,
      seed: seed || cur?.seed || false,
    });
    if (seed) seeds.add(id);
  };

  for (const ev of upto) {
    if (ev.type === "link") {
      for (const l of ev.links) for (const m of l.matches) addNode(m.id, m.label, m.type, true);
    } else if (ev.type === "hop") {
      for (const p of ev.paths) {
        addNode(p.source);
        addNode(p.target);
        edges.set(p.id, { source: p.source, target: p.target, relation: p.relation, occurrence: p.occurrence });
      }
    } else if (ev.type === "answer" && replayStep === null) {
      for (const n of ev.subgraph.nodes) addNode(n.id, n.label, n.type, n.seed);
      for (const e of ev.subgraph.edges) {
        edges.set(e.id, { source: e.source, target: e.target, relation: e.relation, occurrence: e.occurrence });
      }
    }
  }

  if (nodes.size === 0) return { payload: null as GraphPayload | null, emphasis: null };

  const payload: GraphPayload = {
    nodes: [...nodes].map(([key, v]) => ({
      key,
      attributes: {
        label: v.label, type: v.type, degree: v.degree,
        size: v.seed ? 11 : 6 + Math.min(8, v.degree * 0.35),
        community: v.community, occurrence: 1, doc_ids: [], verified: false,
      },
    })),
    edges: [...edges].filter(([, e]) => nodes.has(e.source) && nodes.has(e.target))
      .map(([key, e]) => ({
        key, source: e.source, target: e.target,
        attributes: {
          label: e.relation, relation: e.relation, occurrence: e.occurrence,
          size: 1 + Math.min(2.5, e.occurrence * 0.25), verified: false,
        },
      })),
    truncated: false,
    total_matched: nodes.size,
  };

  return {
    payload,
    emphasis: { nodes: new Set(nodes.keys()), edges: new Set(edges.keys()), seeds },
  };
}