QueryPage.tsx
16.5 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
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 },
};
}