From fe3519a5cdfb9a46ad7265d6ffe6dffe67cee00a Mon Sep 17 00:00:00 2001 From: xiaomakuaiz Date: Thu, 30 Jul 2026 05:40:32 +0000 Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E6=9C=AC=E5=9C=B0=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E6=8E=92=E9=98=9F=E6=B6=88=E6=81=AF=E6=8C=89=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E6=9A=82=E5=AD=98,=E5=88=87=E8=B5=B0=E4=B8=8D?= =?UTF-8?q?=E4=B8=A2=E5=88=87=E5=9B=9E=E6=81=A2=E5=A4=8D=E8=A1=A5=E6=8A=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 切会话不再红条报警丢弃排队消息:排队/待发附件按 sid 暂存(仅内存), 切回同步恢复;historyLoaded 闸门保证尾部窗口归约完(running 可信)才 补投,不被内核忙碌守卫拒掉 - 直发/排队/首条消息三条异步回执路径补会话纪元守卫:回执落在切会话之后 不清新会话的附件、不发进新会话,失败内容写回原会话暂存 - Conn.send 失败回执在 close 后不再回喊状态行(不踩新会话「未连接」); 删除非当前打开的会话经 dropStash 清其暂存 - 假壳加 sendGate/uploadGate 门闸,8 条新测试确定性复现上述竞态 --- desktop/ui/src/App.tsx | 1 + desktop/ui/src/session.ts | 4 +- desktop/ui/src/useSession.test.ts | 174 ++++++++++++++++++++++++++++-- desktop/ui/src/useSession.ts | 98 ++++++++++++++--- 4 files changed, 254 insertions(+), 23 deletions(-) diff --git a/desktop/ui/src/App.tsx b/desktop/ui/src/App.tsx index e26d1bfb..a498e925 100644 --- a/desktop/ui/src/App.tsx +++ b/desktop/ui/src/App.tsx @@ -405,6 +405,7 @@ export default function App() { setView("new"); setDrawer(null); } + session.dropStash(m.id); // 删非当前打开的会话不走 close(forget),排队暂存在此清 void refreshSessions(); }; diff --git a/desktop/ui/src/session.ts b/desktop/ui/src/session.ts index fefb8b60..17a4b97f 100644 --- a/desktop/ui/src/session.ts +++ b/desktop/ui/src/session.ts @@ -136,7 +136,9 @@ export function connect(sessionId: string, h: ConnHandlers): Conn { await invoke("session_send", { id: sessionId, ftype: type, payload }); return true; } catch (e) { - h.onStatus("⚠ " + String(e), false); + // close 之后状态行已归新连接所有:旧连接的失败回执不再回喊, + // 否则会把新会话打成「⚠ …/未连接」 + if (!closed) h.onStatus("⚠ " + String(e), false); return false; } }, diff --git a/desktop/ui/src/useSession.test.ts b/desktop/ui/src/useSession.test.ts index ffaa3951..74629a5d 100644 --- a/desktop/ui/src/useSession.test.ts +++ b/desktop/ui/src/useSession.test.ts @@ -22,6 +22,9 @@ let trace: string[] = []; /** 上行帧(session_send) */ let sent: { ftype: string; payload: Record }[] = []; let sendFail = false; // session_send 是否失败(壳侧发送失败窗口) +/** 门闸:置上后对应命令的应答挂起到 resolve,用于确定性复现「回执落在切会话之后」 */ +let sendGate: Promise | null = null; +let uploadGate: Promise | null = null; /** session_open 返回的尾部窗口 */ let replay: Frame[] = []; let replayCursor = 0; @@ -63,6 +66,8 @@ beforeEach(() => { trace = []; sent = []; sendFail = false; + sendGate = null; + uploadGate = null; replay = []; replayCursor = 0; replayHasMore = false; @@ -94,9 +99,12 @@ beforeEach(() => { return Promise.resolve(outlineScript); } if (cmd === "session_send") { - if (sendFail) return Promise.reject(new Error("引擎未就绪")); - sent.push({ ftype: args!.ftype as string, payload: args!.payload as Record }); - return Promise.resolve(null); + const finish = () => { + if (sendFail) return Promise.reject(new Error("引擎未就绪")); + sent.push({ ftype: args!.ftype as string, payload: args!.payload as Record }); + return Promise.resolve(null); + }; + return sendGate ? sendGate.then(finish) : finish(); } if (cmd === "session_call") { const kind = args!.kind as string; @@ -109,9 +117,12 @@ beforeEach(() => { } if (cmd === "upload_file") { const name = args!.name as string; - if (uploadDeny.has(name)) return Promise.reject(new Error("磁盘已满")); - uploaded.push(name); - return Promise.resolve({ path: ".monkeycode/uploads/" + name }); + const finish = () => { + if (uploadDeny.has(name)) return Promise.reject(new Error("磁盘已满")); + uploaded.push(name); + return Promise.resolve({ path: ".monkeycode/uploads/" + name }); + }; + return uploadGate ? uploadGate.then(finish) : finish(); } return Promise.reject(new Error("unexpected cmd " + cmd)); }, @@ -208,6 +219,12 @@ async function openAndSettle(core: ReturnType["core"], sid = "s await vi.waitFor(() => expect(trace).toContain("invoke:session_open")); await Promise.resolve(); } +/** 等第 nth 次 session_open 落定(切会话的测试要按次数等,contains 不够) */ +async function settleOpen(nth: number) { + await vi.waitFor(() => expect(trace.filter((t) => t === "invoke:session_open")).toHaveLength(nth)); + await Promise.resolve(); + await Promise.resolve(); +} describe("本地会话核心:「监听先于命令」不变式(契约 3)", () => { it("open 先等两个监听注册落地,再发 session_open;壳的同步回放一帧不丢", async () => { @@ -317,6 +334,30 @@ describe("本地会话核心:连接生命周期", () => { expect(userInputs()[0]).toBe("看这张图\n[图片] .monkeycode/uploads/shot.png"); expect(out.notices.some((n) => n.includes("附件上传失败"))).toBe(true); }); + + it("首条消息上传期间切会话:不发进新会话,转入原会话排队暂存,切回补投", async () => { + stubFileReader(); + let release!: () => void; + uploadGate = new Promise((r) => (release = r)); + const { core, out } = makeCore(); + callScript.repo_file_changes = { result: [], is_git_repo: true }; + core.open("s1", { firstMessage: "首条", firstFiles: [fakeFile("slow.png")] }); + await vi.waitFor(() => expect(trace).toContain("invoke:upload_file")); // 上传在途 + + core.open("s2"); // 上传完成前切走 + await settleOpen(2); + release(); + await vi.waitFor(() => expect(uploaded).toEqual(["slow.png"])); + await new Promise((r) => setTimeout(r, 0)); + // 旧实现:闭包在 await 后重读 conn,首条消息会经 s2 的连接发出去 + expect(userInputs()).toEqual([]); + + // 切回 s1:成品(正文+附件行)按排队恢复,历史落地即补投 + core.open("s1"); + expect(out.queued).toBe("首条\n[图片] .monkeycode/uploads/slow.png"); + await vi.waitFor(() => expect(userInputs()).toEqual(["首条\n[图片] .monkeycode/uploads/slow.png"])); + expect(out.queued).toBe(null); + }); }); describe("本地会话核心:composer(排队与附件)", () => { @@ -417,13 +458,128 @@ describe("本地会话核心:composer(排队与附件)", () => { expect(out.queued).toBe(null); }); - it("切走会话时还压着排队消息:外显提醒,不静默丢", async () => { + it("切走会话排队不丢:不报警、会话间隔离,切回恢复并在原会话轮末补投", async () => { const { core, out } = makeCore(); await openAndSettle(core); pushFrames("s1", [frame("task-started")]); - core.send("会被切掉的"); + core.send("切走也不能丢"); + expect(out.queued).toBe("切走也不能丢"); + core.open("s2"); - expect(out.notices.some((n) => n.includes("会被切掉的"))).toBe(true); + await settleOpen(2); + expect(out.notices).toEqual([]); // 不再红条报警 + expect(out.queued).toBe(null); // 隔离:s2 看不到 s1 的排队 + expect(userInputs()).toEqual([]); + + // 切回 s1:后台仍在跑,尾部窗口停在 task-started + replay = [frame("task-started")]; + core.open("s1"); + expect(out.queued).toBe("切走也不能丢"); // 恢复是同步的,chip 立即可见 + await settleOpen(3); + expect(userInputs()).toEqual([]); // 历史显示轮未结束:不抢投(忙碌守卫会拒) + + pushFrames("s1", [frame("task-ended")]); + await vi.waitFor(() => expect(userInputs()).toEqual(["切走也不能丢"])); + expect(out.queued).toBe(null); + }); + + it("切回已空闲的会话:排队消息在历史窗口落地后立即补投", async () => { + const { core, out } = makeCore(); + await openAndSettle(core); + pushFrames("s1", [frame("task-started")]); + core.send("等你跑完"); + core.open("s2"); + await settleOpen(2); + + // 切走期间 s1 的轮已在后台结束:重开时尾部窗口是一段完整的轮 + replay = [frame("task-started"), frame("task-ended")]; + core.open("s1"); + await vi.waitFor(() => expect(userInputs()).toEqual(["等你跑完"])); + expect(out.queued).toBe(null); + }); + + it("删除会话(close forget)连排队暂存一起清,重开不复活", async () => { + const { core, out } = makeCore(); + await openAndSettle(core); + pushFrames("s1", [frame("task-started")]); + core.send("将随会话一起删除"); + core.close(true); + expect(out.queued).toBe(null); + + core.open("s1"); + await settleOpen(2); + expect(out.queued).toBe(null); + expect(userInputs()).toEqual([]); + }); + + it("直发回执落在切会话之后:不清新会话恢复的附件,已送达的附件暂存不复活", async () => { + stubFileReader(); + const { core, out } = makeCore(); + await openAndSettle(core); // s1 + await core.addFiles([fakeFile("mine.png")]); // s1 的待发附件 + core.open("s2"); // 切走:mine.png 入 s1 暂存 + await settleOpen(2); + + await core.addFiles([fakeFile("sent.png")]); + core.send("s2 的消息"); // 直发在途:附件行已折进正文,atts 等回执才清 + core.open("s1"); // 回执落地前切走,s1 的 mine.png 同步恢复 + expect(out.atts.map((a) => a.name)).toEqual(["mine.png"]); + await settleOpen(3); + // s2 的成功回执不能把 s1 恢复出来的附件清掉(旧写法 setAtts([]) 会串会话) + expect(out.atts.map((a) => a.name)).toEqual(["mine.png"]); + expect(userInputs()).toEqual(["s2 的消息\n[图片] .monkeycode/uploads/sent.png"]); + + // 已送达:s2 暂存里的附件一并清掉,切回不复活(否则会重复发送) + core.open("s2"); + expect(out.atts).toEqual([]); + }); + + it("待发附件同样按会话暂存:切走隔离,切回恢复", async () => { + stubFileReader(); + const { core, out } = makeCore(); + await openAndSettle(core); + await core.addFiles([fakeFile("keep.png")]); + expect(out.atts.map((a) => a.name)).toEqual(["keep.png"]); + + core.open("s2"); + await settleOpen(2); + expect(out.atts).toEqual([]); // 隔离:s2 没有 s1 的附件 + + core.open("s1"); + expect(out.atts.map((a) => a.name)).toEqual(["keep.png"]); // 切回恢复 + }); + + it("直发失败的回执落在切会话之后:不把新会话的状态行打成未连接", async () => { + const { core, out } = makeCore(); + await openAndSettle(core); + let release!: () => void; + sendGate = new Promise((r) => (release = r)); + sendFail = true; + core.send("会失败的在途消息"); + + core.open("s2"); // 回执前切走(open 会 close 旧连接) + await settleOpen(2); + expect(out.status).toBe("已连接"); + + release(); // 旧连接的失败回执此刻才到:closed 闸住,不再回喊状态 + await new Promise((r) => setTimeout(r, 0)); + expect(out.status).toBe("已连接"); + expect(out.connected).toBe(true); + }); + + it("dropStash:删除未打开的会话时清其排队暂存,重开不复活", async () => { + const { core, out } = makeCore(); + await openAndSettle(core); + pushFrames("s1", [frame("task-started")]); + core.send("要被删的会话的排队"); + core.open("s2"); // s1 排队入暂存 + await settleOpen(2); + + core.dropStash("s1"); // App 删除 s1(非当前打开)时调用 + core.open("s1"); + await settleOpen(3); + expect(out.queued).toBe(null); + expect(userInputs()).toEqual([]); }); it("取消排队后本轮结束不再投递", async () => { diff --git a/desktop/ui/src/useSession.ts b/desktop/ui/src/useSession.ts index 4f48b87c..bad23541 100644 --- a/desktop/ui/src/useSession.ts +++ b/desktop/ui/src/useSession.ts @@ -110,6 +110,12 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = let chat: ChatState = initialChat; let queued: string | null = null; let atts: Attachment[] = []; + // 每会话 composer 暂存:切会话时排队消息与待发附件按 sid 留档,切回恢复 + // (排队会话隔离,不再报警丢弃)。仅内存,重启即丢;删除会话随 close(forget) 清除 + const stash = new Map(); + // 打开后首份历史(尾部窗口)归约前 running 未知:恢复的排队消息不能抢投—— + // 后台可能正跑轮,直发会被壳的忙碌守卫拒掉,且 send 失败会把连接态误打回未连接 + let historyLoaded = false; // 连接态的核心镜像:false→true 的转变才是「连上」时机(含断线重连), // 原 useEffect([connected]) 的依赖语义在此显式化 let connected = false; @@ -138,6 +144,12 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = atts = v; io.setAtts(v); }; + /** 把当前会话的排队/附件写回暂存(空则清条目);open/close 复位前调用 */ + const stashCurrent = () => { + if (!sid) return; + if (queued || atts.length) stash.set(sid, { queued, atts }); + else stash.delete(sid); + }; async function refreshChanges(): Promise { const c = conn; @@ -172,11 +184,21 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = // 等),之后每批帧都在闸门处提前返回,消息卡死在队列里直到被切会话清掉 function flushQueued() { const c = conn; - if (chat.running || sending || !queued || !c) return; + const fromSid = sid; + if (!historyLoaded || chat.running || sending || !queued || !c || !fromSid) return; const q = queued; sending = true; setQueued(null); void c.send("user-input", { content: b64encode(q) }).then((ok) => { + if (sid !== fromSid) { + // 回执落在切会话之后:结果只归原会话——失败写回它的暂存, + // 不能把旧内容复活到当前会话的队列槽里 + if (!ok) { + const prev = stash.get(fromSid); + stash.set(fromSid, { queued: prev?.queued ?? q, atts: prev?.atts ?? [] }); + } + return; + } if (ok) return; // 回执 = 回显帧到达,onFrames 解除 sending sending = false; // 失败回队;在途期间用户又排了新的,按单槽语义保留最新那条 @@ -192,6 +214,10 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = void refreshChanges(); flushQueued(); // 断线/发送失败会打回未连接,重连即是排队消息的补投时机 if (!pendingMsg && !pendingFiles) return; + // 上传耗时可观(大文件数秒),期间可能已切会话:写回与发送前都要对表, + // 否则首条消息会经新会话的连接发进错的会话(refreshChanges 同款纪元守卫) + const forSid = sid; + if (!forSid) return; void (async () => { let text = pendingMsg ?? ""; const pf = pendingFiles; @@ -207,11 +233,27 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = } } text = [text, ...lines].filter(Boolean).join("\n"); - pendingMsg = text || null; + // 上传结果(含失败后的残句)回写 pendingMsg,send 失败时下次 connected + // 重试只重发文本,不重复上传;已切会话则不可写(槽位已归新会话) + if (sid === forSid) pendingMsg = text || null; } if (!text) return; + // 已切会话时的兜底:成品转入原会话的排队暂存,切回时按排队语义恢复 + // 补投;该会话已有新排队时不覆盖(后来者优先,单槽语义) + const rescueToStash = () => { + const prev = stash.get(forSid); + if (!prev?.queued) stash.set(forSid, { queued: text, atts: prev?.atts ?? [] }); + }; + if (sid !== forSid) { + rescueToStash(); + return; + } const ok = await conn?.send("user-input", { content: b64encode(text) }); - if (ok) pendingMsg = null; + if (ok) { + if (sid === forSid) pendingMsg = null; + } else if (sid !== forSid) { + rescueToStash(); + } })(); } @@ -245,6 +287,9 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = cursor = page.cursor; hasMore = page.hasMore; io.setCanLoadEarlier(hasMore && cursor > 0); + // 尾部窗口落地后 running 才可信:切回恢复的排队消息在此补投(空闲即发) + historyLoaded = true; + flushQueued(); void refreshOutline(); } @@ -310,8 +355,8 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = return { /** 打开会话并接上 WS(见 SessionHandle.open) */ open(id: string, o: { model?: string; mode?: string; think?: string; firstMessage?: string; firstFiles?: File[] } = {}) { - // 复位会丢掉还压着的排队消息:外显提醒,不静默丢(与云端 handleEnded 同款) - if (queued) io.notify(`已离开会话,未发送的排队消息:「${queued.slice(0, 60)}」`); + // 切走前暂存本会话的排队/附件,切回时恢复(排队会话隔离,不丢不报警) + stashCurrent(); conn?.close(); sid = id; io.setId(id); @@ -319,8 +364,10 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = // model_update / permission_mode_update 帧经 reduce 覆盖(回放/多客户端 // 同步)。此前 hook 里另存镜像 state 靠 effect 缝合,存在不一致窗口。 setChat({ ...initialChat, model: o.model ?? "", think: o.think ?? "", permMode: o.mode ?? "" }); - setQueued(null); - setAtts([]); + const saved = stash.get(id); + setQueued(saved?.queued ?? null); + setAtts(saved?.atts ?? []); + historyLoaded = false; io.setChanges(null); io.setIsGitRepo(null); io.setChangesErr(""); @@ -340,6 +387,12 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = /** 断开并复位;forget 时一并清掉"上次会话"记忆(删除流程) */ close(forget = false) { + // forget(删除会话):排队暂存一并清掉;普通复位则留档,重开可恢复 + if (forget) { + if (sid) stash.delete(sid); + } else { + stashCurrent(); + } conn?.close(); conn = null; pendingMsg = null; @@ -356,6 +409,7 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = io.setIsGitRepo(null); io.setChangesErr(""); sending = false; + historyLoaded = false; cursor = 0; hasMore = false; loadingEarlier = false; @@ -380,14 +434,23 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = return true; } sending = true; + const fromSid = sid; void conn.send("user-input", { content: b64encode(text) }).then((ok) => { - // 失败时保留输入与附件(原因已经 onStatus 外显),用户可重试 - if (ok) { - io.setInput(""); - setAtts([]); - } else { - sending = false; + if (ok) io.setInput(""); + if (sid !== fromSid) { + // 回执落在切会话之后:不碰当前会话的附件/sending(否则会清掉 + // 恢复出来的附件)。已送达时,原会话暂存里的附件已随正文的附件行 + // 发出,条目里清掉,免得切回复活重复发送 + if (ok && fromSid) { + const prev = stash.get(fromSid); + if (prev?.queued) stash.set(fromSid, { queued: prev.queued, atts: [] }); + else stash.delete(fromSid); + } + return; } + // 失败时保留输入与附件(原因已经 onStatus 外显),用户可重试 + if (ok) setAtts([]); + else sending = false; }); return true; }, @@ -400,6 +463,12 @@ export function createSessionCore(io: SessionCoreIO, openConn: typeof connect = setQueued(null); }, + /** 删除会话的伴随清理:丢弃其排队/附件暂存。当前打开的会话走 close(forget) + * 已顺带清;删「非当前打开」的会话不经过 close,暂存靠这里清 */ + dropStash(id: string) { + stash.delete(id); + }, + async addFiles(files: File[]) { if (!sid) return; for (const f of files) { @@ -597,6 +666,8 @@ export interface SessionHandle { send(): boolean; stop(): void; clearQueued(): void; + /** 删除会话的伴随清理:丢弃其排队/附件暂存(删非当前打开的会话时调用) */ + dropStash(id: string): void; addFiles(files: File[]): Promise; removeAtt(i: number): void; answerPerm(id: string, action: PermAction): void; @@ -714,6 +785,7 @@ export function useSession(opts: { onSessionsChanged?: () => void } = {}): Sessi send: () => core.send(input), stop: core.stop, clearQueued: core.clearQueued, + dropStash: core.dropStash, addFiles: core.addFiles, removeAtt: core.removeAtt, answerPerm: core.answerPerm,