Elffuss BraidHub

kikocis/utopia public

A generation that outlives its request should be reattachable (#172)

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

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

* An answer already being written should survive the reader leaving

* An answer being written should still be there when you come back

* wip: live registry

* wip: reattach endpoint + client

* wip: client reattach
Changeset748fe722b929046aadcb5c154b5f880c4c5d40d00c8f5b4e50e44f1e2f247c1b
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-02 14:22 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-02 14:22 +08:00
Parents56d4767a713f

Browse the files at this changeset

7 files changed

modified crates/utopia-server/src/api/chat.rs +112 −23
@@ -2,6 +2,7 @@
22 //! 事件序列:step*(行动轨迹)| sources(引用清单,随检索增量更新)| delta*(增量文本)→ done | error。
33 //! 模型不支持 tool-calling 时自动降级为一次性 RAG 注入。
44
5+use crate::live::Frame;
56 use axum::extract::{Path, Query, State};
67 use axum::response::sse::{Event, KeepAlive, Sse};
78 use axum::Json;
@@ -326,7 +327,23 @@
326327 .await?;
327328 let workspace_id = kb.workspace_id;
328329
329- let stream = async_stream::stream! {
330+ // 注册表在生成器之前取出来:下面那个 `async_stream!` 会把 `state` 整个搬走
331+ let live = state.live.clone();
332+
333+ // 生成过程不挂在这条连接上。
334+ //
335+ // **切走一次就丢一个回答**,而且丢得比看上去彻底:整段生成住在下面这个
336+ // 生成器里,助手消息只在走完时落库;浏览器一导航,axum 丢掉响应体、
337+ // 生成器 future 被丢弃,于是 LLM 调用当场取消,那句 `append_message`
338+ // 永远不执行。实测掐断连接时已经收到 1219 字节的正文,二十秒后库里
339+ // 只剩用户那一行——**那个回答不是存在但没显示,是根本没被生成完**。
340+ //
341+ // 所以把生成器交给一个独立任务去驱动,这条连接降级成一个订阅者。
342+ // 任务不随连接消失,答案照常写完、照常落库,人回来就在。
343+ //
344+ // 代价说清楚:**没人看的时候仍然在花钱**。这是有意的——丢答案比多跑一轮贵,
345+ // 而 `MAX_ROUNDS` 已经给了上限。send 失败(接收端没了)不中断,那正是要点。
346+ let producer = async_stream::stream! {
330347 let ds_names: Vec<String> = mounted_sources.iter().map(|d| d.name.clone()).collect();
331348 let tools = tools_schema(can_write, &ds_names);
332349 let mut system_prompt = if can_write {
@@ -410,9 +427,7 @@
410427 }
411428
412429 // 会话 id 先行下发(新会话由此告知前端)
413- yield Ok(Event::default()
414- .event("conversation")
415- .data(json!({ "id": conversation_id }).to_string()));
430+ yield Frame::new("conversation", json!({ "id": conversation_id }).to_string());
416431
417432 // 引用清单:跨轮累积、去重、编号稳定。键 = chunk uuid 或 "charter:{slug}#{anchor}"
418433 let mut source_ids: Vec<String> = Vec::new();
@@ -470,10 +485,10 @@
470485 .enumerate()
471486 .map(|(i, c)| source_json(i + 1, c))
472487 .collect();
473- yield Ok(Event::default().event("sources").data(
474- serde_json::to_string(&legacy_sources)
475- .unwrap_or_else(|_| "[]".into()),
476- ));
488+ yield Frame::new(
489+ "sources",
490+ serde_json::to_string(&legacy_sources).unwrap_or_else(|_| "[]".into()),
491+ );
477492 let mut lmsgs =
478493 vec![json!({ "role": "system", "content": legacy_system_prompt(&chunks) })];
479494 for (role, content) in &history {
@@ -838,13 +853,12 @@
838853 obj.insert("at".into(), json!(answer_acc.encode_utf16().count()));
839854 }
840855 steps_acc.push(step.clone());
841- yield Ok(Event::default()
842- .event("step")
843- .data(serde_json::to_string(&step).unwrap_or_default()));
856+ yield Frame::new("step", serde_json::to_string(&step).unwrap_or_default());
844857 if step["kind"] == "search" || step["kind"] == "docs" {
845- yield Ok(Event::default()
846- .event("sources")
847- .data(serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into())));
858+ yield Frame::new(
859+ "sources",
860+ serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into()),
861+ );
848862 }
849863 msgs.push(tool_result_message(&call.id, &result));
850864 }
@@ -852,21 +866,96 @@
852866 }
853867 };
854868
855- Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
869+ // 生成登记在案,然后**这条连接也只是去「接上」它**——与刷新之后
870+ // 那条重连走的是同一段代码。两条路分开写的话,迟早只有一条是对的
871+ let handle = live.begin(conversation_id).await;
872+ let attached = live.attach(conversation_id).await;
873+ tokio::spawn(async move {
874+ let mut producer = std::pin::pin!(producer);
875+ while let Some(frame) = producer.next().await {
876+ // 没有订阅者是常态(人走了)。**照发不误**:这里中断就等于
877+ // 把「切走一次丢一个回答」原样搬回来
878+ handle.emit(frame).await;
879+ }
880+ // 注销之后再接上的人得到「没有在跑的」,那时答案已经落库
881+ handle.finish().await;
882+ });
883+
884+ Ok(sse_from(attached))
885+}
886+
887+/// 把一次「接上」变成 SSE:先补一份快照,再照常收增量。
888+///
889+/// `None` = 这个会话没有在跑的生成。回一条 `idle` 而不是 404——**客户端
890+/// 每次打开会话都会问一次**,而「没有在跑」是最常见的答案,不是错误
891+fn sse_from(
892+ attached: Option<(
893+ crate::live::Snapshot,
894+ tokio::sync::broadcast::Receiver<Frame>,
895+ )>,
896+) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
897+ let stream = async_stream::stream! {
898+ let Some((snapshot, mut rx)) = attached else {
899+ yield to_event(&Frame::new("idle", "{}".into()));
900+ return;
901+ };
902+ yield to_event(&snapshot.to_frame());
903+ loop {
904+ match rx.recv().await {
905+ Ok(frame) => {
906+ let done = frame.event == "done" || frame.event == "error";
907+ yield to_event(&frame);
908+ if done { return; }
909+ }
910+ // 生成结束、发送端销毁:正常收尾
911+ Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
912+ // 这个客户端读得太慢,被广播缓冲甩下了。**说出来**——
913+ // 静默继续会让它少掉中间一段而毫不知情
914+ Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
915+ yield to_event(&Frame::new(
916+ "error",
917+ format!("Fell behind the stream by {n} messages; reopen the conversation"),
918+ ));
919+ return;
920+ }
921+ }
922+ }
923+ };
924+ Sse::new(stream).keep_alive(KeepAlive::default())
925+}
926+
927+fn to_event(frame: &Frame) -> Result<Event, Infallible> {
928+ Ok(Event::default().event(frame.event).data(&frame.data))
929+}
930+
931+/// 接上一次正在跑的生成(刷新页面之后走这里)。
932+pub async fn reattach(
933+ State(state): State<AppState>,
934+ AuthUser(user): AuthUser,
935+ Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
936+) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
937+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
938+ // **归属要查。** 会话 id 是可以猜的,而这条流会把别人的回答一字不差地念出来
939+ utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
940+ .await?;
941+ Ok(sse_from(state.live.attach(conversation_id).await))
856942 }
857943
858-fn delta_event(text: &str) -> Result<Event, Infallible> {
859- Ok(Event::default()
860- .event("delta")
861- .data(serde_json::to_string(&json!({ "text": text })).unwrap_or_default()))
944+/// 生成器产出的是 `Frame`,不是 `axum` 的 `Event`。
945+/// **广播与快照都要读回事件的内容**,而 `Event` 读不回来(见 `live`)
946+fn delta_event(text: &str) -> Frame {
947+ Frame::new(
948+ "delta",
949+ serde_json::to_string(&json!({ "text": text })).unwrap_or_default(),
950+ )
862951 }
863952
864-fn done_event() -> Result<Event, Infallible> {
865- Ok(Event::default().event("done").data("{}"))
953+fn done_event() -> Frame {
954+ Frame::new("done", "{}".into())
866955 }
867956
868-fn error_event(message: &str) -> Result<Event, Infallible> {
869- Ok(Event::default().event("error").data(message))
957+fn error_event(message: &str) -> Frame {
958+ Frame::new("error", message.into())
870959 }
871960
872961 fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
modified crates/utopia-server/src/api/mod.rs +5 −0
@@ -243,6 +243,11 @@
243243 )
244244 .route("/kbs/{id}/search", post(search_routes::search))
245245 .route("/kbs/{id}/chat", post(chat::chat))
246+ // 刷新页面后重新接上正在生成的那个回答(见 `live`)
247+ .route(
248+ "/kbs/{id}/conversations/{conversation_id}/stream",
249+ get(chat::reattach),
250+ )
246251 .route("/kbs/{id}/conversations", get(chat::list_conversations))
247252 .route(
248253 "/kbs/{id}/conversations/{conversation_id}",
added crates/utopia-server/src/live.rs +159 −0
@@ -0,0 +1,159 @@
1+//! 正在生成的回答,能被重新接上。
2+//!
3+//! **一条 SSE 流绑在一个 HTTP 请求上,而回答比请求活得长。** 生成已经搬进
4+//! 独立任务(`api::chat`),所以刷新页面不会再丢答案;但那条流断了就是断了,
5+//! 刷新之后只能等它落库,中间那段看不见。前端把进行中的那一次搬出组件,
6+//! 解决的是同一个标签页里切来切去;**刷新、换标签页、换设备都不在其中**。
7+//!
8+//! 这里补上最后一段:生成期间把它登记下来,谁都可以再接上。
9+//!
10+//! **接上时先给一份快照,不是重放事件。** 事件流会无限长,缓冲它等于把
11+//! 一次对话的全部增量都留在内存里;而快照的大小就是那个回答本身的大小,
12+//! 有天然上限。客户端那边也更简单:拿快照覆盖当前状态,然后照常收增量,
13+//! 不必去想"我重放到哪一条了"。
14+use serde_json::json;
15+use std::collections::HashMap;
16+use std::sync::Arc;
17+use tokio::sync::{broadcast, RwLock};
18+use uuid::Uuid;
19+
20+/// 一个 SSE 事件:事件名 + 已经序列化好的 data。
21+///
22+/// 不用 `axum::response::sse::Event`——它没有读回内容的办法,而这里既要
23+/// 广播出去,又要拿它更新快照。
24+#[derive(Clone, Debug)]
25+pub struct Frame {
26+ pub event: &'static str,
27+ pub data: String,
28+}
29+
30+impl Frame {
31+ pub fn new(event: &'static str, data: String) -> Self {
32+ Self { event, data }
33+ }
34+}
35+
36+/// 到此刻为止这个回答长什么样。接上的人先拿到它。
37+#[derive(Clone, Default, Debug)]
38+pub struct Snapshot {
39+ pub content: String,
40+ pub steps: Vec<serde_json::Value>,
41+ pub sources: Vec<serde_json::Value>,
42+}
43+
44+impl Snapshot {
45+ /// **快照由事件本身推出来,不另设一套写入口。** 两套写法迟早对不上——
46+ /// 那正是这个仓库反复踩到的形状(一处认得新字段,另一处不认)
47+ fn apply(&mut self, f: &Frame) {
48+ match f.event {
49+ "delta" => {
50+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&f.data) {
51+ if let Some(t) = v["text"].as_str() {
52+ self.content.push_str(t);
53+ }
54+ }
55+ }
56+ "step" => {
57+ if let Ok(v) = serde_json::from_str(&f.data) {
58+ self.steps.push(v);
59+ }
60+ }
61+ // sources 是全量重发,不是追加
62+ "sources" => {
63+ if let Ok(serde_json::Value::Array(a)) = serde_json::from_str(&f.data) {
64+ self.sources = a;
65+ }
66+ }
67+ _ => {}
68+ }
69+ }
70+
71+ pub fn to_frame(&self) -> Frame {
72+ Frame::new(
73+ "snapshot",
74+ json!({
75+ "content": self.content,
76+ "steps": self.steps,
77+ "sources": self.sources,
78+ })
79+ .to_string(),
80+ )
81+ }
82+}
83+
84+struct Entry {
85+ tx: broadcast::Sender<Frame>,
86+ snap: Arc<RwLock<Snapshot>>,
87+}
88+
89+/// 进行中的生成,按会话查。
90+#[derive(Default)]
91+pub struct Registry(RwLock<HashMap<Uuid, Entry>>);
92+
93+/// 一次生成期间握着的把手。发事件、结束时注销。
94+pub struct Handle {
95+ conversation_id: Uuid,
96+ tx: broadcast::Sender<Frame>,
97+ snap: Arc<RwLock<Snapshot>>,
98+ registry: Arc<Registry>,
99+}
100+
101+impl Handle {
102+ /// 发一个事件:记进快照,然后广播。
103+ ///
104+ /// **广播时仍然握着快照的写锁**,这一点是必需的。只保证「先写后发」
105+ /// 挡不住重复:接上的人在两步之间订阅,就会既在快照里看到这一段、
106+ /// 又从广播里再收一次。握着锁发,`attach` 那边握着读锁订阅,两者互斥——
107+ /// 于是接上的时刻要么整个在这次 emit 之前,要么整个在它之后
108+ pub async fn emit(&self, frame: Frame) {
109+ let mut snap = self.snap.write().await;
110+ snap.apply(&frame);
111+ // 没有订阅者是常态(人走了),不是错
112+ let _ = self.tx.send(frame);
113+ }
114+
115+ /// 生成结束。**注销之后再接上的人得到的是「没有在跑的」**,
116+ /// 那时答案已经落库,从库里读就是了
117+ pub async fn finish(self) {
118+ self.registry.0.write().await.remove(&self.conversation_id);
119+ }
120+}
121+
122+impl Registry {
123+ /// 登记一次生成。同一个会话重复登记会顶掉旧的——正常情况下不会发生,
124+ /// 真发生了也是新的那次说了算
125+ pub async fn begin(self: &Arc<Self>, conversation_id: Uuid) -> Handle {
126+ let (tx, _) = broadcast::channel(256);
127+ let snap = Arc::new(RwLock::new(Snapshot::default()));
128+ self.0.write().await.insert(
129+ conversation_id,
130+ Entry {
131+ tx: tx.clone(),
132+ snap: snap.clone(),
133+ },
134+ );
135+ Handle {
136+ conversation_id,
137+ tx,
138+ snap,
139+ registry: self.clone(),
140+ }
141+ }
142+
143+ /// 接上一次正在跑的生成:拿到此刻的快照,以及之后的增量。
144+ ///
145+ /// 返回 `None` = 这个会话没有在跑的生成。**那不是错**,是最常见的情况
146+ pub async fn attach(
147+ &self,
148+ conversation_id: Uuid,
149+ ) -> Option<(Snapshot, broadcast::Receiver<Frame>)> {
150+ let map = self.0.read().await;
151+ let entry = map.get(&conversation_id)?;
152+ // **握着快照的读锁再订阅。** `emit` 是握着写锁广播的,所以这一段
153+ // 与任何一次 emit 互斥:拿到的快照与订阅起点严丝合缝,
154+ // 中间那一小段既不会漏、也不会重
155+ let guard = entry.snap.read().await;
156+ let rx = entry.tx.subscribe();
157+ Some((guard.clone(), rx))
158+ }
159+}
modified crates/utopia-server/src/main.rs +1 −0
@@ -11,6 +11,7 @@
1111 mod github_issues;
1212 mod ingest_sources;
1313 mod jira_issues;
14+mod live;
1415 mod llm_util;
1516 mod mappings;
1617 mod ontology_index;
modified crates/utopia-server/src/state.rs +3 −0
@@ -34,6 +34,8 @@
3434 /// 按模型的并发闸门:后台任务调 LLM 前取许可。限额存库,改完即时生效
3535 pub model_gates: Arc<crate::llm_util::ModelGates>,
3636 pub events: broadcast::Sender<AppEvent>,
37+ /// 正在生成的回答,按会话查。**刷新页面之后还能接上**(见 `live`)
38+ pub live: Arc<crate::live::Registry>,
3739 }
3840
3941 impl AppState {
@@ -59,6 +61,7 @@
5961 worker_concurrency: Arc::new(std::sync::atomic::AtomicUsize::new(32)),
6062 model_gates: Arc::new(crate::llm_util::ModelGates::default()),
6163 events,
64+ live: Arc::new(crate::live::Registry::default()),
6265 }
6366 }
6467
modified web/src/api.ts +52 −14
@@ -1678,28 +1678,64 @@
16781678 }),
16791679 };
16801680
1681+export interface ChatHandlers {
1682+ onConversation: (id: string) => void;
1683+ onSources: (s: Source[]) => void;
1684+ onStep: (s: ChatStep) => void;
1685+ onDelta: (text: string) => void;
1686+ onDone: () => void;
1687+ onError: (message: string) => void;
1688+ /** 接上一个已经在跑的回答:这是它此刻的样子,**覆盖,不是追加** */
1689+ onSnapshot?: (s: { content: string; steps: ChatStep[]; sources: Source[] }) => void;
1690+ /** 这个会话没有在跑的生成——最常见的答案,不是错误 */
1691+ onIdle?: () => void;
1692+}
1693+
1694+/** 接上一个正在生成的回答(刷新页面之后走这里)。
1695+ *
1696+ * 与 `streamChat` 读的是同一条事件流,只是多了开头那份快照。 */
1697+export function reattachChat(
1698+ kbId: string,
1699+ conversationId: string,
1700+ handlers: ChatHandlers,
1701+): () => void {
1702+ return consumeChatStream(
1703+ (signal) =>
1704+ fetch(`/api/v1/kbs/${kbId}/conversations/${conversationId}/stream`, {
1705+ credentials: "include",
1706+ signal,
1707+ }),
1708+ handlers,
1709+ );
1710+}
1711+
16811712 export function streamChat(
16821713 kbId: string,
16831714 body: { conversation_id?: string; message: string },
1684- handlers: {
1685- onConversation: (id: string) => void;
1686- onSources: (s: Source[]) => void;
1687- onStep: (s: ChatStep) => void;
1688- onDelta: (text: string) => void;
1689- onDone: () => void;
1690- onError: (message: string) => void;
1691- },
1715+ handlers: ChatHandlers,
16921716 ): () => void {
1693- const controller = new AbortController();
1694- (async () => {
1695- try {
1696- const res = await fetch(`/api/v1/kbs/${kbId}/chat`, {
1717+ return consumeChatStream(
1718+ (signal) =>
1719+ fetch(`/api/v1/kbs/${kbId}/chat`, {
16971720 method: "POST",
16981721 credentials: "include",
16991722 headers: { "Content-Type": "application/json" },
17001723 body: JSON.stringify(body),
1701- signal: controller.signal,
1702- });
1724+ signal,
1725+ }),
1726+ handlers,
1727+ );
1728+}
1729+
1730+/** SSE 的读法只有一份:发起请求的方式不同,收下来之后的处理完全一样。 */
1731+function consumeChatStream(
1732+ open: (signal: AbortSignal) => Promise<Response>,
1733+ handlers: ChatHandlers,
1734+): () => void {
1735+ const controller = new AbortController();
1736+ (async () => {
1737+ try {
1738+ const res = await open(controller.signal);
17031739 if (!res.ok || !res.body) {
17041740 let message = res.statusText;
17051741 try {
@@ -1736,6 +1772,8 @@
17361772 handlers.onStep(JSON.parse(data) as ChatStep);
17371773 else if (event === "delta")
17381774 handlers.onDelta((JSON.parse(data) as { text: string }).text);
1775+ else if (event === "snapshot") handlers.onSnapshot?.(JSON.parse(data));
1776+ else if (event === "idle") handlers.onIdle?.();
17391777 else if (event === "done") handlers.onDone();
17401778 else if (event === "error") handlers.onError(data);
17411779 }
modified web/src/pages/Chat.tsx +56 −8
@@ -26,6 +26,7 @@
2626 import { ThinkingOrb, type OrbState } from "thinking-orbs";
2727 import {
2828 conversationsApi,
29+ reattachChat,
2930 streamChat,
3031 type ChatStep,
3132 type ConversationRow,
@@ -179,6 +180,46 @@
179180 params: { kbId, conversationId: id },
180181 });
181182
183+ /** 接回一个正在生成的回答。没有在跑的话服务端回 `idle`,什么都不发生。 */
184+ const attachIfRunning = (id: string, history: Turn[]) => {
185+ let abort = () => {};
186+ const stop = reattachChat(kb!.id, id, {
187+ onConversation: () => {},
188+ /* **快照到了才建这一轮。** 先摆一个空位再等回答的话,没有在跑的会话
189+ 上会闪一下空的助手气泡——而那是绝大多数情况。
190+ 快照是覆盖:它是那个回答此刻的全貌,不是增量 */
191+ onSnapshot: (s) =>
192+ liveAnswer.start(
193+ id,
194+ [
195+ ...history,
196+ {
197+ role: "assistant",
198+ content: s.content,
199+ steps: s.steps.length ? s.steps : undefined,
200+ sources: s.sources.length ? s.sources : undefined,
201+ },
202+ ],
203+ abort,
204+ ),
205+ onSources: (sources) => liveAnswer.patchLast((t) => ({ ...t, sources })),
206+ onStep: (step) =>
207+ liveAnswer.patchLast((t) => ({ ...t, steps: [...(t.steps ?? []), step] })),
208+ onDelta: (text) => liveAnswer.patchLast((t) => ({ ...t, content: t.content + text })),
209+ onDone: () => {
210+ liveAnswer.finish();
211+ invalidateList();
212+ },
213+ onError: (message) => {
214+ liveAnswer.patchLast((t) => ({ ...t, error: message }));
215+ liveAnswer.finish();
216+ },
217+ onIdle: () => {},
218+ });
219+ abort = stop;
220+ abortRef.current = stop;
221+ };
222+
182223 const loadConversation = async (id: string) => {
183224 // 回到正在写的那一场:直接认领,别去库里读——库里要等它写完才有那一行
184225 if (liveAnswer.get()?.conversationId === id) {
@@ -191,14 +232,21 @@
191232 try {
192233 const { messages } = await conversationsApi.detail(kb!.id, id);
193234 sessionStorage.setItem(lastKey(kb!.id), id);
194- setTurns(
195- messages.map((m) => ({
196- role: m.role,
197- content: m.content,
198- steps: m.steps.length ? m.steps : undefined,
199- sources: m.sources.length ? m.sources : undefined,
200- })),
201- );
235+ const history: Turn[] = messages.map((m) => ({
236+ role: m.role,
237+ content: m.content,
238+ steps: m.steps.length ? m.steps : undefined,
239+ sources: m.sources.length ? m.sources : undefined,
240+ }));
241+ setTurns(history);
242+ /* **刷新之后接回去。** 上面那个 store 只活在这一个页面里;刷新、
243+ 新标签页、换台机器都拿不到它,而服务端那边生成还在跑。问一句
244+ 「这个会话有没有在跑的」——没有是最常见的答案,代价是一次会
245+ 立刻回 `idle` 的请求。
246+ 最后一条是用户说的话时才问:那正好是「问了但还没答上」的形状 */
247+ if (history[history.length - 1]?.role === "user") {
248+ attachIfRunning(id, history);
249+ }
202250 } catch {
203251 // 失效链接(会话已删 / 属于别的库):安静回到新对话
204252 sessionStorage.removeItem(lastKey(kb!.id));