diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx index 33eed0ca1..86386c3dc 100644 --- a/webui/src/components/thread/ThreadComposer.tsx +++ b/webui/src/components/thread/ThreadComposer.tsx @@ -214,6 +214,8 @@ interface ThreadComposerProps { inputAriaLabel?: string; compactWhenIdle?: boolean; isStreaming?: boolean; + activeTurnId?: string | null; + completedTurnIds?: readonly string[]; modelLabel?: string | null; modelDetail?: string | null; modelPreset?: string | null; @@ -295,6 +297,7 @@ const SLASH_PALETTE_CHROME_PX = 12; const SLASH_RECENTS_STORAGE_KEY = "nanobot.webui.slashCommandRecents"; const SLASH_RECENTS_LIMIT = 5; const QUEUED_PROMPTS_STORAGE_PREFIX = "nanobot.webui.composerQueuedGuidance.v1:"; +const EMPTY_COMPLETED_TURN_IDS: readonly string[] = []; const QUEUED_PROMPTS_LIMIT = 20; const QUEUED_PROMPT_MAX_CHARS = 4000; const SESSION_MENTIONS_LIMIT = 8; @@ -351,6 +354,16 @@ interface QueuedPrompt { images?: QueuedPromptImage[]; quotedContext?: string; sessionMentions?: SessionMention[]; + autoAfterTurnId?: string; + autoPaused?: boolean; +} + +function pauseQueuedPrompt(prompt: QueuedPrompt): QueuedPrompt { + return { ...prompt, autoAfterTurnId: undefined, autoPaused: true }; +} + +function waitForNextQueuedTurn(prompt: QueuedPrompt): QueuedPrompt { + return { ...prompt, autoAfterTurnId: undefined, autoPaused: false }; } interface QueuedPromptImage { @@ -538,6 +551,10 @@ function normalizeQueuedPrompt(item: unknown, index: number): QueuedPrompt | nul ...(images.length > 0 ? { images } : {}), ...(quotedContext ? { quotedContext } : {}), ...(sessionMentions.length > 0 ? { sessionMentions } : {}), + ...(typeof record.autoAfterTurnId === "string" && record.autoAfterTurnId.trim() + ? { autoAfterTurnId: record.autoAfterTurnId.trim() } + : {}), + ...(record.autoPaused === true ? { autoPaused: true } : {}), }; } @@ -574,6 +591,8 @@ function storeQueuedPrompts(storageKey: string, prompts: QueuedPrompt[]): void { ...(prompt.sessionMentions?.length ? { sessionMentions: prompt.sessionMentions.slice(0, SESSION_MENTIONS_LIMIT) } : {}), + ...(prompt.autoAfterTurnId ? { autoAfterTurnId: prompt.autoAfterTurnId } : {}), + ...(prompt.autoPaused ? { autoPaused: true } : {}), })), ), ); @@ -941,6 +960,8 @@ export function ThreadComposer({ inputAriaLabel, compactWhenIdle = false, isStreaming = false, + activeTurnId = null, + completedTurnIds = EMPTY_COMPLETED_TURN_IDS, modelLabel = null, modelDetail = null, modelPreset = null, @@ -1052,7 +1073,6 @@ export function ThreadComposer({ const draggedQueuedPromptIdRef = useRef(null); const previousPendingQueueKeyRef = useRef(pendingQueueKey); const previousQueueRunRef = useRef({ key: pendingQueueKey, isStreaming }); - const skipNextQueuedFlushRef = useRef(false); const skipQueuedPromptPersistRef = useRef(false); const voiceShortcutDownRef = useRef(false); const voiceErrorFadeTimerRef = useRef | null>(null); @@ -1079,6 +1099,20 @@ export function ThreadComposer({ setQueuedPrompts(queuedPromptStorageKey ? readQueuedPrompts(queuedPromptStorageKey) : []); }, [pendingQueueKey, queuedPromptStorageKey]); + useEffect(() => { + if (!isStreaming || !activeTurnId) return; + // The next lifecycle owner, not a guidance input, releases the remaining queue. + setQueuedPrompts((items) => { + let changed = false; + const next = items.map((item) => { + if (item.autoPaused || item.autoAfterTurnId === activeTurnId) return item; + changed = true; + return { ...item, autoAfterTurnId: activeTurnId }; + }); + return changed ? next : items; + }); + }, [activeTurnId, isStreaming, pendingQueueKey]); + useEffect(() => { if (!queuedPromptStorageKey) return; if (skipQueuedPromptPersistRef.current) { @@ -1751,10 +1785,18 @@ export function ThreadComposer({ }; }, [onTranscribeAudio, voiceRecorder.beginShortcutHold, voiceRecorder.endShortcutHold]); + const handleStop = useCallback(() => { + secondEnterPromptIdRef.current = null; + if (queuedPrompts.length > 0) { + setQueuedPrompts((items) => items.map(pauseQueuedPrompt)); + } + onStop?.(); + }, [onStop, queuedPrompts.length]); + const chooseSlashCommand = useCallback( (command: SlashPaletteCommand) => { if (command.command === "/stop" && isStreaming && onStop) { - onStop(); + handleStop(); setValue(""); setSlashMenuDismissed(true); setCliAppMenuDismissed(false); @@ -1784,7 +1826,7 @@ export function ThreadComposer({ setInlineError(null); resizeTextarea(); }, - [isStreaming, onStop, recentSlashCommands, replaceMentionInput, resizeTextarea, skillQuery, value], + [handleStop, isStreaming, onStop, recentSlashCommands, replaceMentionInput, resizeTextarea, skillQuery, value], ); const insertMentionCandidate = useCallback( @@ -1922,6 +1964,7 @@ export function ThreadComposer({ { id, text, + ...(activeTurnId ? { autoAfterTurnId: activeTurnId } : {}), ...(queuedImages.length > 0 ? { images: queuedImages } : {}), ...(normalizedQuotedContext ? { quotedContext: normalizedQuotedContext } : {}), ...(activeSessionMentions.length > 0 @@ -1934,6 +1977,7 @@ export function ThreadComposer({ onQuotedContextChange?.(null); }, [ activeSessionMentions, + activeTurnId, canQueueGuidance, clear, clearComposerText, @@ -1984,8 +2028,9 @@ export function ThreadComposer({ const observeQueuedSend = useCallback((prompt: QueuedPrompt, result: void | boolean | Promise) => { const restore = (error?: unknown) => { - skipNextQueuedFlushRef.current = true; - setQueuedPrompts((items) => items.some((item) => item.id === prompt.id) ? items : [prompt, ...items]); + setQueuedPrompts((items) => (items.some((item) => item.id === prompt.id) + ? items + : [prompt, ...items]).map(pauseQueuedPrompt)); setInlineError(error instanceof Error ? error.message : "Message not sent; queued draft retained"); }; if (result instanceof Promise) void result.then((accepted) => { if (accepted === false) restore(); }).catch(restore); @@ -1997,7 +2042,10 @@ export function ThreadComposer({ secondEnterPromptIdRef.current = null; const text = prompt.text.trim(); const queuedImages = queuedImagesToSendImages(prompt.images); - setQueuedPrompts((items) => items.filter((item) => item.id !== prompt.id)); + setQueuedPrompts((items) => { + const remaining = items.filter((item) => item.id !== prompt.id); + return isStreaming ? remaining : remaining.map(waitForNextQueuedTurn); + }); if (text || queuedImages?.length) { const options: SendOptions | undefined = ( prompt.quotedContext @@ -2026,7 +2074,7 @@ export function ThreadComposer({ setQueuedPrompts([]); return; } - setQueuedPrompts((items) => items.filter((item) => item.id !== nextPrompt.id)); + setQueuedPrompts((items) => items.filter((item) => item.id !== nextPrompt.id).map(waitForNextQueuedTurn)); const queuedImages = queuedImagesToSendImages(nextPrompt.images); const options: SendOptions | undefined = ( nextPrompt.quotedContext || nextPrompt.sessionMentions?.length @@ -2051,25 +2099,16 @@ export function ThreadComposer({ previousQueueRunRef.current = { key: pendingQueueKey, isStreaming }; if (!isStreaming) secondEnterPromptIdRef.current = null; // Switching to an idle session is not completion of the previous session's run. - if (previous.key !== pendingQueueKey) { - skipNextQueuedFlushRef.current = false; - return; - } - if (!previous.isStreaming || isStreaming || queuedPrompts.length === 0) return; - if (skipNextQueuedFlushRef.current) { - skipNextQueuedFlushRef.current = false; - return; - } + if (previous.key !== pendingQueueKey) return; + if (isStreaming || interactionDisabled || queuedPrompts.length === 0) return; + const first = queuedPrompts[0]; + if (first.autoPaused) return; + const waitingTurnCompleted = queuedPromptStorageKey !== null && first.autoAfterTurnId !== undefined + ? completedTurnIds.includes(first.autoAfterTurnId) + : previous.isStreaming; + if (!waitingTurnCompleted) return; sendNextQueuedPrompt(); - }, [sendNextQueuedPrompt, isStreaming, pendingQueueKey, queuedPrompts.length]); - - const handleStop = useCallback(() => { - secondEnterPromptIdRef.current = null; - if (queuedPrompts.length > 0) { - skipNextQueuedFlushRef.current = true; - } - onStop?.(); - }, [onStop, queuedPrompts.length]); + }, [completedTurnIds, interactionDisabled, sendNextQueuedPrompt, isStreaming, pendingQueueKey, queuedPrompts, queuedPromptStorageKey]); const submit = useCallback(() => { if (modelNeedsSetup) { diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index b7db50b8b..75692675f 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -1259,6 +1259,23 @@ export function ThreadShell({ // its history response can race with another send or running event. }, [chatId, client, historyKey]); + const canonicalCompletedTurnIds = useMemo(() => Array.from(new Set([ + ...completedTurnIds, + ...(!completionIdsProvided && !hasPendingToolCalls && historyActiveTurnId === null + ? completedAssistantTurnIds(projectWebuiThreadMessages(historical)) + : []), + ])), [completedTurnIds, completionIdsProvided, hasPendingToolCalls, historical, historyActiveTurnId]); + + const lastRunTurnId = chatId ? client.getRunTurnId(chatId) : null; + const completedRunTurnId = chatId && lastRunTurnId && client.isRunCompleted(chatId, lastRunTurnId) + ? lastRunTurnId : null; + const queueCompletedTurnIds = useMemo(() => { + const canonical = hasPendingToolCalls ? [] : canonicalCompletedTurnIds; + // Live terminal facts can release the queue before the history refresh finishes. + return completedRunTurnId && !canonical.includes(completedRunTurnId) + ? [...canonical, completedRunTurnId] : canonical; + }, [canonicalCompletedTurnIds, completedRunTurnId, hasPendingToolCalls]); + useEffect(() => { if (!historyKey || !chatId || loading) return; const pendingCanonicalHydrate = pendingCanonicalHydrateRef.current.get(chatId); @@ -1274,12 +1291,6 @@ export function ThreadShell({ ) ); const normalizedHistory = projectWebuiThreadMessages(historical); - const canonicalCompletedTurnIds = Array.from(new Set([ - ...completedTurnIds, - ...(!completionIdsProvided && !hasPendingToolCalls && historyActiveTurnId === null - ? completedAssistantTurnIds(normalizedHistory) - : []), - ])); // Completion is a fact about a turn, even when a newer local turn prevents // this snapshot from settling the conversation's current run. client.fenceCanonicalCompletedTurns(chatId, canonicalCompletedTurnIds); @@ -1386,6 +1397,7 @@ export function ThreadShell({ chatId, client, completedTurnIds, + canonicalCompletedTurnIds, completionIdsProvided, historical, historyVersion, @@ -1874,6 +1886,9 @@ export function ThreadShell({ disabled={!chatId} inputAriaLabel={composerInputAriaLabel} isStreaming={turnActive} + activeTurnId={turnActive && chatId ? client.getRunTurnId(chatId) ?? historyActiveTurnId : null} + completedTurnIds={messagesReady && !recoveryNeedsDecision + && chatId && !client.hasUnsettledRun(chatId) ? queueCompletedTurnIds : undefined} placeholder={ composerVariant === "hero" ? t("thread.composer.placeholderHero") diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index 30af8b556..b317f027e 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -336,6 +336,12 @@ export class NanobotClient { return this.latestRunTurnIdByChatId.get(chatId) ?? null; } + /** Whether a turn has a terminal wire, canonical, or local stop disposition. */ + isRunCompleted(chatId: string, turnId: string): boolean { + return this.closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true + || this.canonicalCompletedTurnIdsByChatId.get(chatId)?.has(turnId) === true; + } + /** Clear the optimistic run state immediately after the user stops a turn. */ finishRunLocally(chatId: string): void { const unsettled = [...(this.unsettledRunTurnIdsByChatId.get(chatId) ?? [])]; @@ -748,11 +754,6 @@ export class NanobotClient { ); } - private isRunCompleted(chatId: string, turnId: string): boolean { - return this.closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true - || this.canonicalCompletedTurnIdsByChatId.get(chatId)?.has(turnId) === true; - } - private rememberRunCompletion(chatId: string, turnId: string): void { const closed = this.closedRunTurnIdsByChatId.get(chatId) ?? new Set(); closed.add(turnId); diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index dfb16f91f..6240ac706 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -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(); }); diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx index 56ba28770..bacbf6cfa 100644 --- a/webui/src/tests/thread-composer.test.tsx +++ b/webui/src/tests/thread-composer.test.tsx @@ -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((resolve) => { acceptDelivery = resolve; }); + const onSend = vi.fn().mockReturnValueOnce(delivery); + const first = render( + , + ); + 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( + , + ); + expect(otherSend).not.toHaveBeenCalled(); + expect(screen.queryByText("first follow-up")).not.toBeInTheDocument(); + other.unmount(); + + const returned = render( + , + ); + expect(screen.getByText("first follow-up")).toBeInTheDocument(); + expect(onSend).not.toHaveBeenCalled(); + returned.rerender( + , + ); + expect(onSend).not.toHaveBeenCalled(); + returned.rerender( + , + ); + await waitFor(() => expect(onSend).toHaveBeenCalledWith("first follow-up")); + for (let update = 0; update < 3; update += 1) { + returned.rerender( + 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( + , + ); + returned.rerender( + , + ); + expect(onSend).toHaveBeenCalledTimes(1); + returned.unmount(); + render( + , + ); + 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( + , + ); + 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( + , + ); + 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( + , + ); + returned.rerender( + , + ); + 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((_resolve, reject) => { rejectDelivery = reject; }); + const onSend = vi.fn().mockReturnValue(delivery); + const first = render( + , + ); + fireEvent.change(first.container.querySelector('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( + , + ); + 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( + , + ); + 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(); + 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( diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 4020034a1..47663e409 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -44,6 +44,7 @@ function makeClient() { const runStartedAtByChatId = new Map(); const runGenerationByChatId = new Map(); const latestRunTurnIdByChatId = new Map(); + const closedRunTurnIdsByChatId = new Map>(); const completedTurnIdsByChatId = new Map>(); const goalStateByChatId = new Map(); 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(); + 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, {}} />)); + 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((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, {}} + />)); + 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 = (