Elffuss BraidHub

kikocis/utopia public

2d1966ff85f5 · 26.0 KiBRawPermalink
1/* Chat:agentic 对话(检索/图谱工具 + remember 记忆)。
2 会话持久化:左栏会话列表;上下文由服务端拼,前端只发 conversation_id + 新消息;
3 行动轨迹(steps)与引用(sources)随消息落库,历史回放与实时流共用渲染。 */
4import { useEffect, useRef, useState } from "react";
5import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
6import { Link, useNavigate, useParams } from "@tanstack/react-router";
7import Markdown from "react-markdown";
8import remarkGfm from "remark-gfm";
9import rehypeHighlight from "rehype-highlight";
10import remend from "remend";
11import {
12 ArrowUp,
13 BookOpen,
14 Check,
15 ChevronDown,
16 Database,
17 GitCompareArrows,
18 History,
19 Search as SearchIcon,
20 Square,
21 SquarePen,
22 MoreHorizontal,
23 Waypoints,
24 Wrench,
25} from "lucide-react";
26import { ThinkingOrb, type OrbState } from "thinking-orbs";
27import {
28 conversationsApi,
29 streamChat,
30 type ChatStep,
31 type ConversationRow,
32 type Source,
33} from "../api";
34import { S } from "../i18n";
35import { toast } from "../toast";
36import { useKb, useKbId } from "../kb";
37import { DangerConfirm, RAIL_CLS } from "../ui";
38
39interface Turn {
40 role: "user" | "assistant";
41 content: string;
42 sources?: Source[];
43 steps?: ChatStep[];
44 error?: string;
45}
46
47/** 同标签页记忆:上次会话(按库)与未发送草稿——切页回来还原,新标签页从头开始 */
48const lastKey = (kbId: string) => `chat:last:${kbId}`;
49const DRAFT_KEY = "chat:draft";
50
51export function Chat() {
52 const kbId = useKbId();
53 const { kb, kbs, setKb } = useKb();
54 const queryClient = useQueryClient();
55 const navigate = useNavigate();
56 // 会话即路由:/chat/$conversationId,URL 是当前会话的唯一事实来源(刷新/回退天然可用)
57 const { conversationId: routeConvId } = useParams({ strict: false }) as {
58 conversationId?: string;
59 };
60 const [activeId, setActiveId] = useState<string | null>(null);
61 // 路由同步 effect 的判据:state 的提交时序晚于 navigate 触发的重渲染,
62 // 用 ref 同步写入才能让"流式新建后仅换 URL"的守卫可靠命中
63 const activeIdRef = useRef<string | null>(null);
64 const [turns, setTurns] = useState<Turn[]>([]);
65 const [input, setInput] = useState(() => sessionStorage.getItem(DRAFT_KEY) ?? "");
66 const [streaming, setStreaming] = useState(false);
67 const [scopeOpen, setScopeOpen] = useState(false);
68 const [pendingDelete, setPendingDelete] = useState<ConversationRow | null>(null);
69 // 会话搜索。**搜标题也搜正文**——人记得住的往往是问过的那句话
70 const [convSearch, setConvSearch] = useState("");
71 // 三点菜单展开的是哪一条。同时只开一个
72 const [menuFor, setMenuFor] = useState<string | null>(null);
73 const abortRef = useRef<(() => void) | null>(null);
74 const scopeRef = useRef<HTMLDivElement>(null);
75 const bottomRef = useRef<HTMLDivElement>(null);
76 const inputRef = useRef<HTMLTextAreaElement>(null);
77
78 // 作用域弹层:点外面 / Esc 关闭(与 ui/Dropdown 同惯例)
79 useEffect(() => {
80 if (!scopeOpen) return;
81 const onDoc = (e: MouseEvent) => {
82 if (!scopeRef.current?.contains(e.target as Node)) setScopeOpen(false);
83 };
84 const onKey = (e: KeyboardEvent) => {
85 if (e.key === "Escape") setScopeOpen(false);
86 };
87 document.addEventListener("mousedown", onDoc);
88 document.addEventListener("keydown", onKey);
89 return () => {
90 document.removeEventListener("mousedown", onDoc);
91 document.removeEventListener("keydown", onKey);
92 };
93 }, [scopeOpen]);
94
95 const convs = useQuery({
96 queryKey: ["conversations", kb?.id, convSearch],
97 queryFn: () => conversationsApi.list(kb!.id, convSearch),
98 enabled: !!kb,
99 placeholderData: (prev) => prev,
100 });
101 // 改标题:**就地编辑**,不弹对话框——改一个名字不值得打断整页
102 const [renamingId, setRenamingId] = useState<string | null>(null);
103 const [renameDraft, setRenameDraft] = useState("");
104 const rename = useMutation({
105 mutationFn: (v: { id: string; title: string }) =>
106 conversationsApi.rename(kb!.id, v.id, v.title),
107 onSuccess: () => {
108 setRenamingId(null);
109 queryClient.invalidateQueries({ queryKey: ["conversations", kb?.id] });
110 },
111 onError: (e: Error) => toast.error(e.message),
112 });
113
114 // 直落底部(instant):平滑滚动在流式追加下会一路慢爬
115 useEffect(() => {
116 bottomRef.current?.scrollIntoView({ behavior: "instant" });
117 }, [turns]);
118
119 // 切库回到新会话(首次拿到 kb 不算切换——直刷 /chat/$id 时不能把 URL 冲掉)
120 const prevKbRef = useRef<string | null>(null);
121 useEffect(() => {
122 const prev = prevKbRef.current;
123 prevKbRef.current = kb?.id ?? null;
124 if (prev && kb && prev !== kb.id) {
125 if (streaming) abortRef.current?.();
126 setStreaming(false);
127 activeIdRef.current = null;
128 setActiveId(null);
129 setTurns([]);
130 navigate({ to: "/kb/$kbId/chat", params: { kbId }, replace: true });
131 }
132 // eslint-disable-next-line react-hooks/exhaustive-deps
133 }, [kb?.id]);
134
135 // 路由 → 会话装载;裸 /chat 还原本库上次会话(切页回来仍在原对话)
136 useEffect(() => {
137 if (!kb) return;
138 if (!routeConvId) {
139 const last = sessionStorage.getItem(lastKey(kb.id));
140 if (last) {
141 navigate({
142 to: "/kb/$kbId/chat/$conversationId",
143 params: { kbId, conversationId: last },
144 replace: true,
145 });
146 }
147 return;
148 }
149 if (routeConvId === activeIdRef.current) return; // 流式新建会话后仅 URL 同步,勿重载
150 loadConversation(routeConvId);
151 // eslint-disable-next-line react-hooks/exhaustive-deps
152 }, [kb?.id, routeConvId]);
153
154 // 还原的草稿撑开输入框(高度平时由 onChange 维护)
155 useEffect(() => {
156 const el = inputRef.current;
157 if (el && el.value) {
158 el.style.height = "auto";
159 el.style.height = `${Math.min(el.scrollHeight, 192)}px`;
160 }
161 }, []);
162
163 const invalidateList = () =>
164 queryClient.invalidateQueries({ queryKey: ["conversations", kb?.id] });
165
166 /** 列表点击只改 URL,装载由路由同步 effect 负责 */
167 const openConversation = (id: string) =>
168 navigate({
169 to: "/kb/$kbId/chat/$conversationId",
170 params: { kbId, conversationId: id },
171 });
172
173 const loadConversation = async (id: string) => {
174 if (streaming) abortRef.current?.();
175 setStreaming(false);
176 activeIdRef.current = id;
177 setActiveId(id);
178 try {
179 const { messages } = await conversationsApi.detail(kb!.id, id);
180 sessionStorage.setItem(lastKey(kb!.id), id);
181 setTurns(
182 messages.map((m) => ({
183 role: m.role,
184 content: m.content,
185 steps: m.steps.length ? m.steps : undefined,
186 sources: m.sources.length ? m.sources : undefined,
187 })),
188 );
189 } catch {
190 // 失效链接(会话已删 / 属于别的库):安静回到新对话
191 sessionStorage.removeItem(lastKey(kb!.id));
192 activeIdRef.current = null;
193 setActiveId(null);
194 setTurns([]);
195 navigate({ to: "/kb/$kbId/chat", params: { kbId }, replace: true });
196 }
197 };
198
199 const newChat = () => {
200 if (streaming) abortRef.current?.();
201 setStreaming(false);
202 if (kb) sessionStorage.removeItem(lastKey(kb.id));
203 activeIdRef.current = null;
204 setActiveId(null);
205 setTurns([]);
206 navigate({ to: "/kb/$kbId/chat", params: { kbId } });
207 inputRef.current?.focus();
208 };
209
210 const removeConversation = async (id: string) => {
211 await conversationsApi.remove(kb!.id, id);
212 if (sessionStorage.getItem(lastKey(kb!.id)) === id) {
213 sessionStorage.removeItem(lastKey(kb!.id));
214 }
215 invalidateList();
216 if (id === activeId) newChat();
217 };
218
219 const send = () => {
220 const q = input.trim();
221 if (!q || streaming || !kb) return;
222 setInput("");
223 sessionStorage.removeItem(DRAFT_KEY);
224 if (inputRef.current) inputRef.current.style.height = "auto";
225 setTurns((prev) => [...prev, { role: "user", content: q }, { role: "assistant", content: "" }]);
226 setStreaming(true);
227
228 abortRef.current = streamChat(
229 kb.id,
230 { conversation_id: activeId ?? undefined, message: q },
231 {
232 onConversation: (id) => {
233 // 先同步写 ref 再换 URL:路由同步 effect 因 id 相等而跳过重载,不打断流
234 activeIdRef.current = id;
235 setActiveId(id);
236 sessionStorage.setItem(lastKey(kb.id), id);
237 navigate({
238 to: "/kb/$kbId/chat/$conversationId",
239 params: { kbId, conversationId: id },
240 replace: true,
241 });
242 invalidateList();
243 },
244 onSources: (sources) =>
245 setTurns((prev) => {
246 const next = [...prev];
247 next[next.length - 1] = { ...next[next.length - 1], sources };
248 return next;
249 }),
250 onStep: (step) =>
251 setTurns((prev) => {
252 const next = [...prev];
253 const last = next[next.length - 1];
254 next[next.length - 1] = { ...last, steps: [...(last.steps ?? []), step] };
255 return next;
256 }),
257 onDelta: (text) =>
258 setTurns((prev) => {
259 const next = [...prev];
260 const last = next[next.length - 1];
261 next[next.length - 1] = { ...last, content: last.content + text };
262 return next;
263 }),
264 onDone: () => {
265 setStreaming(false);
266 invalidateList();
267 },
268 onError: (message) => {
269 setStreaming(false);
270 setTurns((prev) => {
271 const next = [...prev];
272 next[next.length - 1] = { ...next[next.length - 1], error: message };
273 return next;
274 });
275 },
276 },
277 );
278 };
279
280 /* Composer 卡:新对话首屏居中出场,进入对话后停靠底部(同一块 JSX 两处复用) */
281 const composerCard = (
282 <div className="rounded-2xl border border-white/[0.12] bg-white/[0.04] backdrop-blur-md focus-within:border-white/30 transition-colors px-4 pt-3 pb-2">
283 <textarea
284 ref={inputRef}
285 rows={1}
286 className="w-full bg-transparent outline-none text-sm resize-none leading-relaxed max-h-48 u-scroll placeholder:text-neutral-600"
287 placeholder={S.ask.placeholder}
288 value={input}
289 onChange={(e) => {
290 setInput(e.target.value);
291 sessionStorage.setItem(DRAFT_KEY, e.target.value);
292 const el = e.currentTarget;
293 el.style.height = "auto";
294 el.style.height = `${Math.min(el.scrollHeight, 192)}px`;
295 }}
296 onKeyDown={(e) => {
297 if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
298 e.preventDefault();
299 send();
300 }
301 }}
302 />
303 <div className="flex items-center justify-between gap-3 pt-1">
304 <div className="flex items-center gap-2.5 min-w-0">
305 {/* 作用域 chip:提问点位可见"在问哪个库",切库沿用现有语义(开新会话) */}
306 <div ref={scopeRef} className="relative shrink-0">
307 <button
308 onClick={() => setScopeOpen((v) => !v)}
309 title={S.ask.scopeLabel}
310 className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-neutral-400 hover:text-neutral-200 hover:bg-white/[0.07] transition-colors max-w-52"
311 >
312 <Database size={12} className="shrink-0 text-neutral-500" />
313 <span className="truncate">{kb?.name ?? "…"}</span>
314 <ChevronDown
315 size={11}
316 className={`shrink-0 text-neutral-600 transition-transform ${
317 scopeOpen ? "rotate-180" : ""
318 }`}
319 />
320 </button>
321 {scopeOpen && (
322 <div className="u-pop u-pop-up absolute bottom-full mb-1.5 left-0 z-50 w-56 rounded-lg shadow-xl overflow-hidden">
323 <div className="px-2.5 pt-2 pb-1 text-[9.5px] font-medium uppercase tracking-[0.1em] text-neutral-600 border-b border-white/5">
324 {S.ask.scopeLabel}
325 </div>
326 <div className="u-scroll max-h-60 overflow-y-auto">
327 {kbs.map((k) => (
328 <button
329 key={k.id}
330 onClick={() => {
331 setScopeOpen(false);
332 if (k.id !== kb?.id) setKb(k.id);
333 }}
334 className={`w-full flex items-center gap-2 text-left px-2.5 py-1.5 text-xs ${
335 k.id === kb?.id
336 ? "bg-white/[0.12] text-white"
337 : "text-neutral-300 hover:bg-white/[0.06] hover:text-white"
338 }`}
339 >
340 <span className="flex-1 min-w-0 truncate">{k.name}</span>
341 {k.id === kb?.id && <Check size={12} className="shrink-0 text-neutral-400" />}
342 </button>
343 ))}
344 </div>
345 </div>
346 )}
347 </div>
348 <span className="text-[11px] text-neutral-600 truncate">{S.ask.composerHint}</span>
349 </div>
350 {streaming ? (
351 <button
352 onClick={() => {
353 abortRef.current?.();
354 setStreaming(false);
355 }}
356 title={S.ask.stop}
357 className="h-8 w-8 shrink-0 rounded-lg grid place-items-center bg-white/[0.08] text-neutral-200 hover:bg-white/[0.14] transition-colors"
358 >
359 <Square size={11} fill="currentColor" />
360 </button>
361 ) : (
362 <button
363 onClick={send}
364 disabled={!input.trim()}
365 title={S.ask.send}
366 className={`h-8 w-8 shrink-0 rounded-lg grid place-items-center transition-colors ${
367 input.trim()
368 ? "bg-white text-black hover:bg-neutral-200"
369 : "bg-white/[0.07] text-neutral-600"
370 }`}
371 >
372 <ArrowUp size={15} strokeWidth={2.4} />
373 </button>
374 )}
375 </div>
376 </div>
377 );
378
379 return (
380 <div className="h-full flex">
381 {/* 会话栏 */}
382 <aside className={`${RAIL_CLS} flex flex-col`}>
383 <div className="px-2 pt-3 pb-1">
384 {/* 与会话行同一套样式:左栏是一列同质的行,新对话只是第一行 */}
385 <button
386 onClick={newChat}
387 className="w-full flex items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[13px] text-neutral-300 hover:bg-white/[0.05] hover:text-white transition-colors"
388 >
389 <SquarePen size={14} className="shrink-0 text-neutral-500" />
390 {S.ask.newChat}
391 </button>
392 </div>
393 {/* 搜索。**标题重是常态**(同一个问题问两次就重了),而正文里那句话
394 才是人记得住的——所以服务端两处都搜 */}
395 <div className="px-2 pb-2">
396 <input
397 className="input-dark w-full px-2.5 py-1.5 text-[12.5px]"
398 placeholder={S.ask.searchConversations}
399 value={convSearch}
400 onChange={(e) => setConvSearch(e.target.value)}
401 onKeyDown={(e) => e.key === "Escape" && setConvSearch("")}
402 />
403 </div>
404 <div className="u-scroll flex-1 overflow-y-auto px-2 pb-3 space-y-0.5">
405 {(convs.data?.conversations ?? []).map((c: ConversationRow) => (
406 <div
407 key={c.id}
408 className={`group relative rounded-lg transition-colors ${
409 c.id === activeId ? "u-nav-active" : "hover:bg-white/[0.05]"
410 }`}
411 >
412 {/* 单行标题;删除键悬停浮现(弹确认,不直接删) */}
413 {renamingId === c.id ? (
414 /* 就地编辑:Enter 保存、Esc 取消。改一个名字不值得弹对话框 */
415 <input
416 autoFocus
417 className="input-dark w-full px-2 py-1.5 text-[13px]"
418 value={renameDraft}
419 onChange={(e) => setRenameDraft(e.target.value)}
420 onBlur={() => setRenamingId(null)}
421 onKeyDown={(e) => {
422 if (e.key === "Enter" && renameDraft.trim())
423 rename.mutate({ id: c.id, title: renameDraft });
424 if (e.key === "Escape") setRenamingId(null);
425 }}
426 />
427 ) : (
428 <button
429 onClick={() => openConversation(c.id)}
430 className="w-full text-left px-2.5 py-2"
431 >
432 <span
433 className={`block truncate pr-5 text-[13px] ${
434 c.id === activeId ? "text-white" : "text-neutral-300"
435 }`}
436 >
437 {c.title || S.ask.untitled}
438 </span>
439 </button>
440 )}
441 {/* 三点菜单:**一个入口装下所有动作**。从前右边直接是删除,
442 而删除是这里最不该一步到位的那个 */}
443 {renamingId !== c.id && (
444 <button
445 onClick={() => setMenuFor(menuFor === c.id ? null : c.id)}
446 title={S.ask.moreActions}
447 className="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:block text-neutral-600 hover:text-neutral-200"
448 >
449 <MoreHorizontal size={14} />
450 </button>
451 )}
452 {menuFor === c.id && (
453 <>
454 {/* 点别处就关。铺满全屏而不是监听 document:不必在卸载时
455 记得摘监听器 */}
456 <div
457 className="fixed inset-0 z-10"
458 onClick={() => setMenuFor(null)}
459 />
460 <div className="glass-strong absolute right-2 top-8 z-20 w-32 rounded-lg py-1 shadow-xl">
461 <button
462 className="w-full px-3 py-1.5 text-left text-xs text-neutral-300 hover:bg-white/5"
463 onClick={() => {
464 setRenameDraft(c.title || "");
465 setRenamingId(c.id);
466 setMenuFor(null);
467 }}
468 >
469 {S.ask.rename}
470 </button>
471 <button
472 className="w-full px-3 py-1.5 text-left text-xs text-neutral-300 hover:bg-white/5"
473 onClick={() => {
474 navigator.clipboard?.writeText(c.title || "");
475 setMenuFor(null);
476 }}
477 >
478 {S.ask.copyTitle}
479 </button>
480 <button
481 className="w-full px-3 py-1.5 text-left text-xs text-[var(--u-danger)] hover:bg-white/5"
482 onClick={() => {
483 setPendingDelete(c);
484 setMenuFor(null);
485 }}
486 >
487 {S.ask.deleteConversation}
488 </button>
489 </div>
490 </>
491 )}
492 </div>
493 ))}
494 {convs.data?.conversations.length === 0 && (
495 <p className="px-2.5 py-2 text-xs text-neutral-600">{S.ask.noConversations}</p>
496 )}
497 </div>
498 </aside>
499
500 {/* 对话区:新对话首屏 = 问候 + 居中 composer(ChatGPT/Claude 惯例);
501 有消息后 composer 停靠底部 */}
502 <div className="flex-1 min-w-0 flex flex-col">
503 {turns.length === 0 ? (
504 /* 锚定上三分之一而非垂直居中:居中在高窗口下会显得下坠。
505 22vh + 顶部 chrome(~100px) ≈ 问候落在 37% 高度、composer 中心 ~49% */
506 <div className="flex-1 px-4 pt-[22vh]">
507 <div className="w-full max-w-3xl mx-auto">
508 <h1
509 className="text-center text-[26px] text-neutral-100 mb-9"
510 style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.03em" }}
511 >
512 {S.ask.greeting}
513 </h1>
514 {composerCard}
515 </div>
516 </div>
517 ) : (
518 <>
519 <div className="flex-1 overflow-y-auto u-scroll px-4 py-6">
520 <div className="max-w-3xl mx-auto space-y-4">
521 {turns.map((t, i) => (
522 <TurnView key={i} turn={t} live={streaming && i === turns.length - 1} />
523 ))}
524 <div ref={bottomRef} />
525 </div>
526 </div>
527 <div className="px-4 pb-4 pt-2">
528 <div className="max-w-3xl mx-auto">{composerCard}</div>
529 </div>
530 </>
531 )}
532 </div>
533
534 {pendingDelete && (
535 <DangerConfirm
536 title={S.ask.deleteTitle}
537 hint={S.ask.deleteHint(pendingDelete.title || S.ask.untitled)}
538 confirmLabel={S.ask.deleteBtn}
539 cancelLabel={S.ask.cancel}
540 onConfirm={() => {
541 removeConversation(pendingDelete.id);
542 setPendingDelete(null);
543 }}
544 onCancel={() => setPendingDelete(null)}
545 />
546 )}
547 </div>
548 );
549}
550
551function stepIcon(kind: ChatStep["kind"]) {
552 if (kind === "search") return <SearchIcon size={11} />;
553 if (kind === "docs") return <BookOpen size={11} />;
554 if (kind === "entity") return <Waypoints size={11} />;
555 if (kind === "facts") return <History size={11} />;
556 // facts 读世界轴、changes 读认知轴,两个图谱工具给不同的图标——
557 // 用户看步骤条时该看得出问的是哪根轴
558 if (kind === "changes") return <GitCompareArrows size={11} />;
559 if (kind === "query") return <Database size={11} />;
560 return <Wrench size={11} />;
561}
562
563/** 工具步骤 → 球体状态:思考球讲当前动作的语言 */
564function orbState(kind?: ChatStep["kind"]): OrbState {
565 if (kind === "search" || kind === "docs") return "searching";
566 if (kind === "entity") return "connecting";
567 if (kind === "facts" || kind === "changes") return "solving";
568 if (kind === "query" || kind === "tool") return "working";
569 return "listening"; // 尚无步骤:刚接到消息
570}
571
572/** 思考指示:thinking-orbs 球体 + 当前动作(应用是深色定妆,theme 钉死 dark)。 */
573function Thinking({ step }: { step?: ChatStep }) {
574 return (
575 <span className="inline-flex items-center gap-2.5 text-neutral-500">
576 <ThinkingOrb state={orbState(step?.kind)} size={20} theme="dark" />
577 {step && (
578 <span className="text-xs truncate">
579 {step.label} · {step.detail}
580 </span>
581 )}
582 </span>
583 );
584}
585
586function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {
587 const kbId = useKbId();
588 if (turn.role === "user") {
589 return (
590 <div className="flex justify-end">
591 <div className="u-bubble-user max-w-[85%] rounded-2xl rounded-tr-sm px-4 py-2 text-sm whitespace-pre-wrap text-neutral-100">
592 {turn.content}
593 </div>
594 </div>
595 );
596 }
597
598 const thinking = live && !turn.content && !turn.error;
599 const lastStep = turn.steps?.[turn.steps.length - 1];
600
601 return (
602 <div className="max-w-[95%]">
603 {/* agent 回复无气泡:正文直接落在画布上(用户消息保留气泡以区分角色) */}
604 <div className="py-1 text-sm text-neutral-200 leading-relaxed">
605 {turn.steps && turn.steps.length > 0 && (
606 <div className="mb-2.5 space-y-1 border-l border-white/15 pl-2.5">
607 {turn.steps.map((s, i) => (
608 <div key={i} className="flex items-center gap-1.5 text-xs">
609 <span className="text-neutral-600">{stepIcon(s.kind)}</span>
610 <span className="text-neutral-400 truncate">{s.label}</span>
611 <span className="text-neutral-600 shrink-0">· {s.detail}</span>
612 </div>
613 ))}
614 </div>
615 )}
616 {turn.content && (
617 /* react-markdown 承载渲染(皮肤全归 u-chat-prose 设计系统),
618 流式中经 remend 修补未闭合语法(粗体/围栏/链接),
619 rehype-highlight 做代码高亮——成熟件组装,观感自持 */
620 <div className="u-chat-prose">
621 <Markdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
622 {live ? remend(turn.content) : turn.content}
623 </Markdown>
624 </div>
625 )}
626 {thinking && <Thinking step={lastStep} />}
627 {turn.error && <div className="text-rose-400">{turn.error}</div>}
628 </div>
629 {turn.sources && turn.sources.length > 0 && (
630 <div className="mt-2 space-y-1">
631 {turn.sources.map((s) =>
632 s.kind === "charter" ? (
633 /* 手册引用:视觉上与数据引用隔离(BookOpen),跳排版好的 /docs 小节 */
634 <Link
635 key={s.n}
636 to="/docs/$slug"
637 params={{ slug: s.slug! }}
638 hash={s.anchor || undefined}
639 title={s.excerpt}
640 className="flex items-center gap-1.5 text-xs text-neutral-500 glass rounded-lg px-3 py-1.5 glass-hover hover:text-neutral-300"
641 >
642 <span className="u-num text-[var(--u-accent)]">[{s.n}]</span>
643 <BookOpen size={11} className="shrink-0 text-neutral-600" />
644 <span className="truncate">
645 {/* 引言节 heading 即文章名,避免 "X › X" */}
646 {s.heading && s.heading !== s.filename
647 ? `${s.filename} › ${s.heading}`
648 : s.filename}
649 </span>
650 </Link>
651 ) : (
652 <Link
653 key={s.n}
654 to="/kb/$kbId/doc/$docId"
655 params={{ kbId, docId: s.document_id! }}
656 search={{ chunk: s.chunk_id }}
657 title={s.excerpt}
658 className="block text-xs text-neutral-500 glass rounded-lg px-3 py-1.5 glass-hover hover:text-neutral-300"
659 >
660 <span className="u-num text-[var(--u-accent)]">[{s.n}]</span> {s.filename} ·{" "}
661 {s.excerpt.slice(0, 60)}…
662 </Link>
663 ),
664 )}
665 </div>
666 )}
667 </div>
668 );
669}