Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
fix(chatbot): keep queued messages when switching conversations (#1004)
Robert0622e270ef03a669
diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.jsindex 9689d9e6..50c626ae 100644--- a/chatbot/src/useChat.js+++ b/chatbot/src/useChat.js@@ -142,6 +142,10 @@ export function useChat() {// The generation whose final transcript has been loaded. A queued message// waits for it, so it is sent after the finished (or unfinished) reply.[settledId, setSettledId] = useState(null),+ // The conversation whose reply status has been fetched since it was+ // opened. Until then a reply may still be running there, so queued+ // messages must not go out (they would be rejected and get lost).+ [generationKnown, setGenerationKnown] = useState(null),// A queued message sent with "send now": it interrupts the running reply// and stays on screen until the server's follow-up turn has started.[steering, setSteering] = useState(null);@@ -204,6 +208,7 @@ export function useChat() {if (id === currentId.current && sessionRef.current?.id === id) return;setError("");setGeneration(null);+ setGenerationKnown(null);setLive({ answer: "", thinking: "", tools: [] });setSession(null);executionMachines.resetMachine();@@ -394,6 +399,7 @@ export function useChat() {accumulated = mergeEvents(accumulated, events);setLive(accumulated);setGeneration(g);+ setGenerationKnown(activeId);if (g.status !== "running") setStopRequest((old) => old?.generationId === g.id ? null : old);if (g.status === "running" && ["platform", "workspace"].includes(g.runtimeMode)) {setSession((stored) => stored?.id === activeId && stored.runtimeMode !== g.runtimeMode ? { ...stored, runtimeMode: g.runtimeMode } : stored);@@ -448,7 +454,9 @@ export function useChat() {timer = setTimeout(poll, g.status === "running" ? 200 : 2000);} catch (e) {if (cancelled) return;- if (e.status !== 404) {+ // No reply was ever started here: nothing can be running.+ if (e.status === 404) setGenerationKnown(activeId);+ else {connectionError = e.status ? e.message : "连接暂时中断,正在重连…";setError(connectionError);}@@ -693,6 +701,9 @@ export function useChat() {if (!next || dispatchingRef.current || submittingRef.current) return;if (steeringRef.current) return;if (generation?.status === "running" || sessionRef.current?.id !== id) return;+ // Wait until this conversation's reply status is known: right after+ // switching back the transcript can arrive before the running reply does.+ if (generationKnown !== id) return;// Wait until the ended turn's transcript (with its reply) is loaded.if (generation && settledId !== generation.id) return;dispatchingRef.current = true;@@ -723,7 +734,7 @@ export function useChat() {const item = id ? queues[id]?.items.find((m) => m.id === itemId) : null;if (!item || steeringRef.current || dispatchingRef.current) return false;if (generation?.status !== "running" || !generation.id) {- if (submittingRef.current) return false;+ if (submittingRef.current || generationKnown !== id) return false;dispatchingRef.current = true;setQueues((old) => removeQueued(old, id, item.id));try {@@ -905,8 +916,12 @@ export function useChat() {]);if (currentId.current === s.id) setSession(stored);if (g?.id !== previousGeneration && g?.status === "running") {- setGeneration(g);- return true;+ if (currentId.current === s.id) setGeneration(g);+ // Only a lost response may hide an accepted turn. A clear+ // rejection (e.g. 409 while another reply runs) means this+ // message was not taken, so a queued one goes back instead of+ // being dropped.+ if (!e.status || e.status >= 500) return true;}} catch {}}diff --git a/chatbot/tests/message-queue-hook.test.jsx b/chatbot/tests/message-queue-hook.test.jsxindex 5a6fa5d5..2565347b 100644--- a/chatbot/tests/message-queue-hook.test.jsx+++ b/chatbot/tests/message-queue-hook.test.jsx@@ -1,7 +1,7 @@import { act, renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-const state = vi.hoisted(() => ({ transcript: [], generation: null }));+const state = vi.hoisted(() => ({ transcript: [], generation: null, generationGate: null }));const { apiMock, writeMock } = vi.hoisted(() => {const apiMock = vi.fn(async (path) => {if (path === "/api/auth/current")@@ -11,7 +11,14 @@ const { apiMock, writeMock } = vi.hoisted(() => {return { default: "m1", sponsoredModel: "m1", models: [{ id: "m1", name: "模型一" }] };if (path === "/api/users") return [{ id: 1, loginName: "tester", codeBuddyApiKeyConfigured: true }];if (path === "/api/assistant/sessions") return [];- if (path.includes("/generation")) return structuredClone(state.generation);+ if (path.startsWith("/api/assistant/sessions/s2")) {+ if (path.includes("/generation")) throw Object.assign(new Error("not found"), { status: 404 });+ return { id: "s2", title: "别的会话", projectId: "p1", model: "m1", messages: [] };+ }+ if (path.includes("/generation")) {+ if (state.generationGate) await state.generationGate;+ return structuredClone(state.generation);+ }if (path.startsWith("/api/assistant/sessions/"))return { id: "s1", title: "排队", projectId: "p1", model: "m1", messages: structuredClone(state.transcript) };return [];@@ -83,6 +90,7 @@ describe("sending while a reply runs", () => {history.replaceState({}, "", "/");state.transcript = [{ role: "user", content: "查失败节点" }];state.generation = { id: "g-running", status: "running", events: [{ sequence: 1, data: { kind: "tool", tool: "runs_get" } }] };+ state.generationGate = null;globalThis.EventSource = FakeEventSource;});afterEach(() => {@@ -258,4 +266,65 @@ describe("sending while a reply runs", () => {expect(generationPosts()[0][1].messages.at(-1).content).toBe("补充一句");unmount();});++ test("switching away and back keeps the queue while the reply still runs", async () => {+ const { result, unmount } = await openRunning();+ await act(async () => {+ await result.current.send({ text: "切走前排队的消息" });+ });+ expect(result.current.queue.map((m) => m.text)).toEqual(["切走前排队的消息"]);++ act(() => result.current.open("s2"));+ await waitFor(() => expect(result.current.session?.id).toBe("s2"));+ expect(result.current.queue).toHaveLength(0);++ // Coming back, the conversation loads before its running generation does.+ // The server rejects a new turn while one runs (409).+ let release;+ state.generationGate = new Promise((done) => { release = done; });+ writeMock.mockImplementation(async (path) => {+ if (path === "/api/assistant/generations")+ throw Object.assign(new Error("此会话正在后台生成"), { status: 409 });+ return {};+ });+ act(() => result.current.open("s1"));+ await waitFor(() => expect(result.current.session?.id).toBe("s1"));+ await act(async () => { await new Promise((done) => setTimeout(done, 50)); });+ expect(generationPosts()).toHaveLength(0);+ expect(result.current.queue.map((m) => m.text)).toEqual(["切走前排队的消息"]);++ state.generationGate = null;+ await act(async () => { release(); });+ await waitFor(() => expect(result.current.busy).toBe(true));+ expect(generationPosts()).toHaveLength(0);+ expect(result.current.queue.map((m) => m.text)).toEqual(["切走前排队的消息"]);+ expect(result.current.queueHeld).toBe(false);+ unmount();+ });++ test("a rejected queued send is never mistaken for an accepted one", async () => {+ const { result, unmount } = await openRunning();+ await act(async () => {+ await result.current.send({ text: "不能丢" });+ });+ act(() => result.current.open("s2"));+ await waitFor(() => expect(result.current.session?.id).toBe("s2"));+ act(() => result.current.open("s1"));+ await waitFor(() => expect(result.current.busy).toBe(true));+ // The reply finishes but another one is already running there; the+ // server rejects the queued send with 409. The message must come back, not disappear.+ writeMock.mockImplementationOnce(async () => {+ throw Object.assign(new Error("此会话正在后台生成"), { status: 409 });+ });+ state.generation = { id: "g-other", status: "running", events: [] };+ state.transcript = [{ role: "user", content: "查失败节点" }, unfinished];+ await act(async () => {+ sources.at(-1).generation({ data: JSON.stringify({ id: "g-running", status: "completed", events: [] }) });+ });+ await waitFor(() => expect(generationPosts()).toHaveLength(1));+ await waitFor(() => expect(result.current.queue.map((m) => m.text)).toEqual(["不能丢"]));+ // The rejected message is not left on screen as if it had been sent.+ await waitFor(() => expect(result.current.session?.messages.map((m) => m.content)).toEqual(["查失败节点", unfinished.content]));+ unmount();+ });});