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