fix(webui): resume queued prompts after turn completion (#6242)

* fix(webui): resume queued prompts after turn completion

Persist the lifecycle turn each queued prompt waits for and use canonical completion identities to resume after navigation or reconnect. Release one entry at a time, and retain stopped or rejected entries for manual sending.

* fix(webui): drain temporary chat prompts on live completion

* perf(webui): resume queued prompts from live completion
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-16 13:33:41 +08:00
1 parent 3abcfe70c5
commit 836092424d
6 files changed
+339 -36

No files matched your search

+4
View File
@@ -582,6 +582,7 @@ describe("NanobotClient", () => {
expect(client.getRunStartedAt("chat-stop")).toBeNull();
expect(client.hasUnsettledRun("chat-stop")).toBe(false);
expect(client.isRunCompleted("chat-stop", "turn-stop")).toBe(true);
expect(handler).toHaveBeenLastCalledWith("chat-stop", null);
});
@@ -609,6 +610,7 @@ describe("NanobotClient", () => {
expect(client.status).toBe("reconnecting");
expect(client.getRunStartedAt("chat-strip")).toBe(12_345);
expect(client.getRunTurnId("chat-strip")).toBe("turn-strip");
expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(false);
expect(client.getUnsettledRunChatIds()).toEqual(["chat-strip"]);
expect(handler).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(20);
@@ -621,6 +623,8 @@ describe("NanobotClient", () => {
});
expect(client.getRunStartedAt("chat-strip")).toBeNull();
expect(client.getUnsettledRunChatIds()).toEqual([]);
expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(true);
expect(client.isRunCompleted("another-chat", "turn-strip")).toBe(false);
expect(handler).toHaveBeenLastCalledWith("chat-strip", null);
client.close();
});
+138
View File
@@ -3852,6 +3852,144 @@ describe("ThreadComposer", () => {
});
});
it("resumes a restored queue only after its waiting turn is confirmed complete", async () => {
let acceptDelivery!: (accepted: boolean) => void;
const delivery = new Promise<boolean>((resolve) => { acceptDelivery = resolve; });
const onSend = vi.fn().mockReturnValueOnce(delivery);
const first = render(
<ThreadComposer onSend={onSend} isStreaming activeTurnId="turn-a" pendingQueueKey="chat-a" />,
);
const input = screen.getByLabelText("Message input");
for (const text of ["first follow-up", "second follow-up"]) {
fireEvent.change(input, { target: { value: text } });
fireEvent.keyDown(input, { key: "Enter" });
}
first.unmount();
const otherSend = vi.fn();
const other = render(
<ThreadComposer onSend={otherSend} pendingQueueKey="chat-b" completedTurnIds={["turn-a"]} />,
);
expect(otherSend).not.toHaveBeenCalled();
expect(screen.queryByText("first follow-up")).not.toBeInTheDocument();
other.unmount();
const returned = render(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={[]} />,
);
expect(screen.getByText("first follow-up")).toBeInTheDocument();
expect(onSend).not.toHaveBeenCalled();
returned.rerender(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-other"]} />,
);
expect(onSend).not.toHaveBeenCalled();
returned.rerender(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
);
await waitFor(() => expect(onSend).toHaveBeenCalledWith("first follow-up"));
for (let update = 0; update < 3; update += 1) {
returned.rerender(
<ThreadComposer onSend={(...args) => onSend(...args)} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
);
}
expect(onSend).toHaveBeenCalledTimes(1);
expect(screen.getByText("second follow-up")).toBeInTheDocument();
await act(async () => { acceptDelivery(true); await delivery; });
returned.rerender(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming activeTurnId="turn-next" completedTurnIds={["turn-a"]} />,
);
returned.rerender(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
);
expect(onSend).toHaveBeenCalledTimes(1);
returned.unmount();
render(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a", "turn-next"]} />,
);
await waitFor(() => expect(onSend).toHaveBeenLastCalledWith("second follow-up"));
expect(onSend).toHaveBeenCalledTimes(2);
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
});
it.each(["button", "palette"])("keeps queued messages manual after stopping through %s and remounting", (entrypoint) => {
const onSend = vi.fn();
const onStop = vi.fn();
const view = render(
<ThreadComposer onSend={onSend} onStop={onStop} isStreaming activeTurnId="turn-a" pendingQueueKey="chat-a" slashCommands={COMMANDS} />,
);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "keep for later" } });
fireEvent.keyDown(input, { key: "Enter" });
if (entrypoint === "button") fireEvent.click(screen.getByRole("button", { name: "Stop response" }));
else {
fireEvent.change(input, { target: { value: "/sto" } });
fireEvent.mouseDown(screen.getByRole("option", { name: /\/stop/i }));
}
expect(onStop).toHaveBeenCalledTimes(1);
view.unmount();
const returned = render(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
);
expect(screen.getByText("keep for later")).toBeInTheDocument();
expect(onSend).not.toHaveBeenCalled();
// A run started in another pane must not re-arm a queue the user stopped.
returned.rerender(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming activeTurnId="turn-other-pane" completedTurnIds={["turn-a"]} />,
);
returned.rerender(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a", "turn-other-pane"]} />,
);
expect(onSend).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
expect(onSend).toHaveBeenCalledTimes(1);
expect(onSend).toHaveBeenCalledWith("keep for later", undefined, undefined);
});
it("retains a rejected queued attachment for manual retry after remounting", async () => {
mockBlobUrls();
let rejectDelivery!: (error: Error) => void;
const delivery = new Promise<boolean>((_resolve, reject) => { rejectDelivery = reject; });
const onSend = vi.fn().mockReturnValue(delivery);
const first = render(
<ThreadComposer onSend={onSend} isStreaming activeTurnId="turn-a" pendingQueueKey="chat-a" />,
);
fireEvent.change(first.container.querySelector<HTMLInputElement>('input[type="file"]')!, {
target: { files: [new File(["image"], "queued.png", { type: "image/png" })] },
});
await screen.findByText("queued.png");
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "queued attachment" } });
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" });
first.unmount();
const returned = render(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
);
await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
await act(async () => { rejectDelivery(new Error("Attachment upload interrupted")); });
expect(screen.getByText("queued attachment")).toBeInTheDocument();
expect(onSend).toHaveBeenCalledTimes(1);
returned.unmount();
render(
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
);
expect(screen.getByText("queued attachment")).toBeInTheDocument();
expect(onSend).toHaveBeenCalledTimes(1);
onSend.mockReturnValue(true);
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
expect(onSend).toHaveBeenCalledTimes(2);
expect(onSend.mock.calls[1][1]).toEqual([expect.objectContaining({ media: expect.objectContaining({ name: "queued.png" }) })]);
});
it("retains legacy queued drafts for manual sending when mounted idle", () => {
window.localStorage.setItem("nanobot.webui.composerQueuedGuidance.v1:chat-a", JSON.stringify([
{ id: "legacy-draft", text: "legacy follow-up" },
]));
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["old-turn"]} />);
expect(screen.getByText("legacy follow-up")).toBeInTheDocument();
expect(onSend).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
expect(onSend).toHaveBeenCalledWith("legacy follow-up", undefined, undefined);
});
it("keeps temporary chat guidance in memory only", async () => {
const onSend = vi.fn();
const view = render(
+106
View File
@@ -44,6 +44,7 @@ function makeClient() {
const runStartedAtByChatId = new Map<string, number>();
const runGenerationByChatId = new Map<string, number>();
const latestRunTurnIdByChatId = new Map<string, string>();
const closedRunTurnIdsByChatId = new Map<string, Set<string>>();
const completedTurnIdsByChatId = new Map<string, Set<string>>();
const goalStateByChatId = new Map<string, import("@/lib/types").GoalStateWsPayload>();
let status: ConnectionStatus = "open";
@@ -140,6 +141,10 @@ function makeClient() {
},
getRunStartedAt: (chatId: string) => runStartedAtByChatId.get(chatId) ?? null,
getRunTurnId: (chatId: string) => latestRunTurnIdByChatId.get(chatId) ?? null,
isRunCompleted: (chatId: string, turnId: string) => (
closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true
|| completedTurnIdsByChatId.get(chatId)?.has(turnId) === true
),
finishRunLocally: vi.fn((chatId: string) => {
runStartedAtByChatId.delete(chatId);
latestRunTurnIdByChatId.delete(chatId);
@@ -199,6 +204,11 @@ function makeClient() {
(ev.event === "goal_status" && ev.status === "idle")
|| ev.event === "turn_end"
) {
if (turnId) {
const closed = closedRunTurnIdsByChatId.get(chatId) ?? new Set<string>();
closed.add(turnId);
closedRunTurnIdsByChatId.set(chatId, closed);
}
runStartedAtByChatId.delete(chatId);
for (const h of runStatusHandlers) h(chatId, null);
for (const h of runCompletionHandlers) h(chatId);
@@ -1673,6 +1683,102 @@ describe("ThreadShell", () => {
expect(screen.getByText("persist me across tabs")).toBeInTheDocument();
});
it.each([false, true])("drains persisted follow-ups before history refresh resolves (pending tools=%s)", async (pendingTools) => {
const client = makeClient();
const chatId = "queued-live-completion";
const owner = "queued-owner";
const initialHistory = httpJson({
...transcriptFromSimpleMessages([{ role: "user", content: "Initial question", turnId: owner }]),
has_pending_tool_calls: pendingTools,
active_turn_id: owner,
completed_turn_ids: [],
});
vi.mocked(fetch).mockImplementation(async (input) => (
String(input).includes("/webui-thread") ? initialHistory
: { ok: false, status: 404, json: async () => ({}) }
) as Response);
render(wrap(client, <ThreadShell session={session(chatId)} title="Queued chat" onToggleSidebar={() => {}} />));
await screen.findByText("Initial question");
act(() => client._emitChat(chatId, {
event: "goal_status", chat_id: chatId, turn_id: owner,
status: "running", started_at: 1_000,
}));
const input = screen.getByLabelText("Message input");
for (const text of ["first persisted follow-up", "second persisted follow-up"]) {
fireEvent.change(input, { target: { value: text } });
fireEvent.keyDown(input, { key: "Enter" });
}
let finishRefresh!: (response: Response) => void;
const refresh = new Promise<Response>((resolve) => { finishRefresh = resolve; });
let refreshStarted = false;
vi.mocked(fetch).mockImplementation(async (input) => {
if (String(input).includes("/webui-thread")) {
refreshStarted = true;
return refresh;
}
return { ok: false, status: 404, json: async () => ({}) } as Response;
});
act(() => client._emitSessionUpdate(chatId, "thread"));
await waitFor(() => expect(refreshStarted).toBe(true));
try {
act(() => client._emitChat(chatId, { event: "turn_end", chat_id: chatId, turn_id: owner }));
await waitFor(() => expectSendMessageWithTurn(client, chatId, "first persisted follow-up"));
expect(client.sendMessage).toHaveBeenCalledTimes(1);
const nextTurnId = client.sendMessage.mock.calls[0][3]!.turnId!;
act(() => client._emitChat(chatId, {
event: "goal_status", chat_id: chatId, turn_id: nextTurnId,
status: "running", started_at: 2_000,
}));
expect(client.sendMessage).toHaveBeenCalledTimes(1);
act(() => client._emitChat(chatId, { event: "turn_end", chat_id: chatId, turn_id: nextTurnId }));
await waitFor(() => expectSendMessageWithTurn(client, chatId, "second persisted follow-up"));
expect(client.sendMessage).toHaveBeenCalledTimes(2);
} finally {
await act(async () => { finishRefresh(initialHistory as Response); });
}
});
it("drains temporary follow-ups once per live completed turn without persisted history", async () => {
const client = makeClient();
const chatId = "temporary-queued-follow-ups";
render(wrap(client, <ThreadShell
session={session(chatId)} title="Temporary chat" temporary
temporaryChatIds={[chatId]} onToggleSidebar={() => {}}
/>));
act(() => client._emitChat(chatId, {
event: "goal_status", chat_id: chatId, turn_id: "temporary-owner",
status: "running", started_at: 1_000,
}));
const input = screen.getByLabelText("Message input");
for (const text of ["first temporary follow-up", "second temporary follow-up"]) {
fireEvent.change(input, { target: { value: text } });
fireEvent.keyDown(input, { key: "Enter" });
}
expect(client.sendMessage).not.toHaveBeenCalled();
act(() => client._emitChat(chatId, {
event: "turn_end", chat_id: chatId, turn_id: "temporary-owner",
}));
await waitFor(() => expectSendMessageWithTurn(client, chatId, "first temporary follow-up"));
expect(client.sendMessage).toHaveBeenCalledTimes(1);
expect(screen.getByText("second temporary follow-up")).toBeInTheDocument();
const nextTurnId = client.sendMessage.mock.calls[0][3]!.turnId!;
act(() => client._emitChat(chatId, {
event: "goal_status", chat_id: chatId, turn_id: nextTurnId,
status: "running", started_at: 2_000,
}));
expect(client.sendMessage).toHaveBeenCalledTimes(1);
act(() => client._emitChat(chatId, {
event: "turn_end", chat_id: chatId, turn_id: nextTurnId,
}));
await waitFor(() => expectSendMessageWithTurn(client, chatId, "second temporary follow-up"));
expect(client.sendMessage).toHaveBeenCalledTimes(2);
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/webui-thread"))).toBe(false);
expect(window.localStorage.getItem(`nanobot.webui.composerQueuedGuidance.v1:${chatId}`)).toBeNull();
});
it("keeps temporary messages across navigation and drops them after clear", async () => {
const client = makeClient();
const view = (