Elffuss BraidHub

kikocis/utopia public

An answer being written should still be there when you come back (#171)

* The trace belongs where it happened, not all at the top

* Citations are the sign-off, not part of the process

* An answer being written should still be there when you come back
Changeset56d4767a713feca26362cfc2a15f1ae4bc90d53dad85f28a32f5a08e8bd3829e
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-02 14:19 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-02 14:19 +08:00
Parents398734e8a1ca

Browse the files at this changeset

2 files changed

added web/src/liveAnswer.ts +80 −0
@@ -0,0 +1,80 @@
1+// 正在生成的那一次回答,活在组件之外。
2+//
3+// **切走一次就看不见了。** 流式中的 `turns` 从前是 Chat 的组件状态,而离开
4+// 对话页会卸载这个组件:状态没了,那个 fetch 还在跑,回调写进的是一个已经
5+// 死掉的组件。切回来时组件重新挂载、从库里读——库里要等生成结束才有那一行,
6+// 于是只看得见自己问的那句话。等一会儿再回来就正常,因为那时已经落库了。
7+//
8+// 服务端那半边(生成不随连接消失)是另一条修复;这半边解决的是**回来的时候
9+// 看不看得见**。两条缺一不可:服务端保住了答案,这里保住了那条流。
10+//
11+// 同时只会有一次进行中的回答——所以这是个单例,不是按会话开的表。
12+import type { ChatStep, Source } from "./api";
13+
14+export interface Turn {
15+ role: "user" | "assistant";
16+ content: string;
17+ steps?: ChatStep[];
18+ sources?: Source[];
19+ error?: string;
20+}
21+
22+interface Live {
23+ conversationId: string | null;
24+ turns: Turn[];
25+ /** 停止按钮用;切页面**不调它**,那正是这次修复的意思 */
26+ abort: () => void;
27+ /** 还在写,还是已经写完。**写完不清空**——见 `finish` */
28+ streaming: boolean;
29+}
30+
31+let live: Live | null = null;
32+const listeners = new Set<() => void>();
33+
34+function emit() {
35+ listeners.forEach((l) => l());
36+}
37+
38+export const liveAnswer = {
39+ /** `useSyncExternalStore` 要求同一个快照对象在没变时保持同一引用 */
40+ get: () => live,
41+ subscribe: (l: () => void) => {
42+ listeners.add(l);
43+ return () => {
44+ listeners.delete(l);
45+ };
46+ },
47+ start: (conversationId: string | null, turns: Turn[], abort: () => void) => {
48+ live = { conversationId, turns, abort, streaming: true };
49+ emit();
50+ },
51+ /** 会话是流式中途新建的:`onConversation` 回来才知道 id */
52+ identify: (conversationId: string) => {
53+ if (!live) return;
54+ live = { ...live, conversationId };
55+ emit();
56+ },
57+ /** 改最后一轮(助手那一轮)。生成期间只有它在变 */
58+ patchLast: (f: (t: Turn) => Turn) => {
59+ if (!live) return;
60+ const turns = [...live.turns];
61+ turns[turns.length - 1] = f(turns[turns.length - 1]);
62+ live = { ...live, turns };
63+ emit();
64+ },
65+ /** 结束(正常、出错、或人按了停止)。
66+ *
67+ * **不清空。** 清空过一版,那一版有个很难看的 bug:切走时组件卸载,
68+ * 而「把最终结果交回组件」是调在已经死掉的那个组件上——空操作。于是
69+ * store 空了、新组件早前已经认领过这一场因而不会再去读库,切回来
70+ * 整场对话一片空白,连自己问的那句都没有。
71+ *
72+ * 那一刻这里是唯一还握着这份内容的地方,所以留着:只把 `streaming`
73+ * 落下来。下一次 `start` 会替掉它,切到别的会话时 id 对不上自然不显示。
74+ */
75+ finish: () => {
76+ if (!live) return;
77+ live = { ...live, streaming: false };
78+ emit();
79+ },
80+};
modified web/src/pages/Chat.tsx +52 −49
@@ -1,7 +1,7 @@
11 /* Chat:agentic 对话(检索/图谱工具 + remember 记忆)。
22 会话持久化:左栏会话列表;上下文由服务端拼,前端只发 conversation_id + 新消息;
33 行动轨迹(steps)与引用(sources)随消息落库,历史回放与实时流共用渲染。 */
4-import { useEffect, useRef, useState } from "react";
4+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
55 import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
66 import { Link, useNavigate, useParams } from "@tanstack/react-router";
77 import Markdown from "react-markdown";
@@ -29,20 +29,15 @@
2929 streamChat,
3030 type ChatStep,
3131 type ConversationRow,
32- type Source,
3332 } from "../api";
3433 import { S } from "../i18n";
3534 import { toast } from "../toast";
3635 import { useKb, useKbId } from "../kb";
3736 import { DangerConfirm, RAIL_CLS } from "../ui";
37+import { liveAnswer, type Turn } from "../liveAnswer";
3838
39-interface Turn {
40- role: "user" | "assistant";
41- content: string;
42- sources?: Source[];
43- steps?: ChatStep[];
44- error?: string;
45-}
39+/* `Turn` 定义在 liveAnswer 里:进行中的那一次也是一串 Turn,
40+ 而它必须活得比这个组件长(见那个文件顶上的说明) */
4641
4742 /** 同标签页记忆:上次会话(按库)与未发送草稿——切页回来还原,新标签页从头开始 */
4843 const lastKey = (kbId: string) => `chat:last:${kbId}`;
@@ -61,9 +56,24 @@
6156 // 路由同步 effect 的判据:state 的提交时序晚于 navigate 触发的重渲染,
6257 // 用 ref 同步写入才能让"流式新建后仅换 URL"的守卫可靠命中
6358 const activeIdRef = useRef<string | null>(null);
59+ // 已经结束的那些轮次,从库里读来。**进行中的那一次不在这里**——见下
6460 const [turns, setTurns] = useState<Turn[]>([]);
6561 const [input, setInput] = useState(() => sessionStorage.getItem(DRAFT_KEY) ?? "");
66- const [streaming, setStreaming] = useState(false);
62+ // 进行中的那一次活在组件之外,所以切走再回来它还在(见 liveAnswer.ts)。
63+ // 新建会话时它的 id 是 null,而此时 activeId 也是 null,两者对得上
64+ const live = useSyncExternalStore(liveAnswer.subscribe, liveAnswer.get);
65+ /* **是「这一场」在流,不是「有一场」在流。**
66+ 写成全局的话,另一场在生成时这一场的输入框也会变成停止按钮、发不出消息,
67+ 而且最后一轮会被当成还在流——引用于是被藏起来(那条判据见 TurnView)。
68+ 一个正在别处生成的回答不该改变这里的任何东西 */
69+ /* **按 URL 认领,不按 state。** 这个文件开头就写着「URL 是当前会话的唯一
70+ 事实来源」,而这里一度用了 `activeId`——它是 state,切走再回来时更新得
71+ 比第一次渲染晚,于是那一帧认不出自己,屏幕空着。用地址栏里的那个 id
72+ 就没有时序可言。新会话还没拿到 id 时两者都是空,也对得上 */
73+ const currentId = routeConvId ?? activeId;
74+ const liveHere = live && live.conversationId === currentId ? live : null;
75+ const streaming = liveHere?.streaming ?? false;
76+ const shown = liveHere ? liveHere.turns : turns;
6777 const [scopeOpen, setScopeOpen] = useState(false);
6878 const [pendingDelete, setPendingDelete] = useState<ConversationRow | null>(null);
6979 // 会话搜索。**搜标题也搜正文**——人记得住的往往是问过的那句话
@@ -114,7 +124,7 @@
114124 // 直落底部(instant):平滑滚动在流式追加下会一路慢爬
115125 useEffect(() => {
116126 bottomRef.current?.scrollIntoView({ behavior: "instant" });
117- }, [turns]);
127+ }, [shown]);
118128
119129 // 切库回到新会话(首次拿到 kb 不算切换——直刷 /chat/$id 时不能把 URL 冲掉)
120130 const prevKbRef = useRef<string | null>(null);
@@ -122,8 +132,7 @@
122132 const prev = prevKbRef.current;
123133 prevKbRef.current = kb?.id ?? null;
124134 if (prev && kb && prev !== kb.id) {
125- if (streaming) abortRef.current?.();
126- setStreaming(false);
135+ // **不 abort**:换库不该杀掉另一个库里正在写的回答,它落到那边的会话里
127136 activeIdRef.current = null;
128137 setActiveId(null);
129138 setTurns([]);
@@ -171,8 +180,12 @@
171180 });
172181
173182 const loadConversation = async (id: string) => {
174- if (streaming) abortRef.current?.();
175- setStreaming(false);
183+ // 回到正在写的那一场:直接认领,别去库里读——库里要等它写完才有那一行
184+ if (liveAnswer.get()?.conversationId === id) {
185+ activeIdRef.current = id;
186+ setActiveId(id);
187+ return;
188+ }
176189 activeIdRef.current = id;
177190 setActiveId(id);
178191 try {
@@ -197,8 +210,7 @@
197210 };
198211
199212 const newChat = () => {
200- if (streaming) abortRef.current?.();
201- setStreaming(false);
213+ // 同样不 abort:开一场新的不等于放弃上一场
202214 if (kb) sessionStorage.removeItem(lastKey(kb.id));
203215 activeIdRef.current = null;
204216 setActiveId(null);
@@ -222,14 +234,17 @@
222234 setInput("");
223235 sessionStorage.removeItem(DRAFT_KEY);
224236 if (inputRef.current) inputRef.current.style.height = "auto";
225- setTurns((prev) => [...prev, { role: "user", content: q }, { role: "assistant", content: "" }]);
226- setStreaming(true);
227237
228- abortRef.current = streamChat(
238+ /* **结果留在 store 里,不交回组件状态。**
239+ 交回去要经过一个 `setTurns`,而流结束时这个组件可能早就卸载了——
240+ 那一下是空操作,内容就此消失(切回来一片空白,问题气泡都没有)。
241+ 留在 store 里,谁挂载谁认领 */
242+ const abort = streamChat(
229243 kb.id,
230244 { conversation_id: activeId ?? undefined, message: q },
231245 {
232246 onConversation: (id) => {
247+ liveAnswer.identify(id);
233248 // 先同步写 ref 再换 URL:路由同步 effect 因 id 相等而跳过重载,不打断流
234249 activeIdRef.current = id;
235250 setActiveId(id);
@@ -241,40 +256,27 @@
241256 });
242257 invalidateList();
243258 },
244- onSources: (sources) =>
245- setTurns((prev) => {
246- const next = [...prev];
247- next[next.length - 1] = { ...next[next.length - 1], sources };
248- return next;
249- }),
259+ onSources: (sources) => liveAnswer.patchLast((t) => ({ ...t, sources })),
250260 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- }),
261+ liveAnswer.patchLast((t) => ({ ...t, steps: [...(t.steps ?? []), step] })),
257262 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- }),
263+ liveAnswer.patchLast((t) => ({ ...t, content: t.content + text })),
264264 onDone: () => {
265- setStreaming(false);
265+ liveAnswer.finish();
266266 invalidateList();
267267 },
268268 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- });
269+ liveAnswer.patchLast((t) => ({ ...t, error: message }));
270+ liveAnswer.finish();
275271 },
276272 },
277273 );
274+ abortRef.current = abort;
275+ liveAnswer.start(
276+ activeId,
277+ [...turns, { role: "user", content: q }, { role: "assistant", content: "" }],
278+ abort,
279+ );
278280 };
279281
280282 /* Composer 卡:新对话首屏居中出场,进入对话后停靠底部(同一块 JSX 两处复用) */
@@ -350,8 +352,9 @@
350352 {streaming ? (
351353 <button
352354 onClick={() => {
355+ // **只有这里 abort**——切页面、换会话、换库都不再打断(liveAnswer.ts)
353356 abortRef.current?.();
354- setStreaming(false);
357+ liveAnswer.finish();
355358 }}
356359 title={S.ask.stop}
357360 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"
@@ -500,7 +503,7 @@
500503 {/* 对话区:新对话首屏 = 问候 + 居中 composer(ChatGPT/Claude 惯例);
501504 有消息后 composer 停靠底部 */}
502505 <div className="flex-1 min-w-0 flex flex-col">
503- {turns.length === 0 ? (
506+ {shown.length === 0 ? (
504507 /* 锚定上三分之一而非垂直居中:居中在高窗口下会显得下坠。
505508 22vh + 顶部 chrome(~100px) ≈ 问候落在 37% 高度、composer 中心 ~49% */
506509 <div className="flex-1 px-4 pt-[22vh]">
@@ -518,8 +521,8 @@
518521 <>
519522 <div className="flex-1 overflow-y-auto u-scroll px-4 py-6">
520523 <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} />
524+ {shown.map((t, i) => (
525+ <TurnView key={i} turn={t} live={streaming && i === shown.length - 1} />
523526 ))}
524527 <div ref={bottomRef} />
525528 </div>