AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend/copilot): keep a mid-turn follow-up queued until the backend drains it (#14777)
Abhimanyu Yadavd08a23b09fab
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsxindex aaea0c2e04..1d1fb4224f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resume-hydrated-turn.test.tsx@@ -216,6 +216,23 @@ const RESUME_REPLAY_WITHOUT_DRAIN_HINT: UIMessageChunk[] =(chunk) => chunk.type !== "data-pending-drained",);+/** Typed while the resumed turn was still running: the backend holds it in+ * the pending buffer and has not reached a tool boundary to drain it. */+const QUEUED_FOLLOWUP = "Also check the weather";++/** The replay of a turn still busy mid-tool: status chunks, then the+ * persisted half, then nothing more — no drain hint, because the follow-up+ * is still queued. `useChat` parks the status chunks in a placeholder under+ * its own id and pushes the real message once `start` lands. */+const RESUME_REPLAY_STILL_RUNNING: UIMessageChunk[] = [+ { type: "data-status", data: { message: "Setting up your environment…" } },+ { type: "start", messageId: "resumed-turn-3" },+ { type: "start-step" },+ { type: "text-start", id: "replay-1" },+ { type: "text-delta", id: "replay-1", delta: PERSISTED_HALF },+ { type: "text-end", id: "replay-1" },+];+/*** A turn the backend started on its own (the engine-switch continuation* dispatched with ``is_user_message=False``): the completed answer is@@ -233,6 +250,8 @@ function renderResumedSession(messages: SessionDetailResponseMessagesItem[] = HYDRATED_SESSION_MESSAGES,activeStreamStartedAt = "2026-05-13T00:04:00Z",replayChunks: UIMessageChunk[] = RESUME_REPLAY_CHUNKS,+ pendingMessages: string[] = [],+ strictMode = false,) {let resumeRequests = 0;server.use(@@ -253,6 +272,8 @@ function renderResumedSession(started_at: activeStreamStartedAt,},},+ pendingMessages,+ strictMode,});return { getResumeRequests: () => resumeRequests };}@@ -425,6 +446,56 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {},);+ // The dev server mounts under Strict Mode, so the load-time buffer peek+ // fires twice; the reload the user sees must draw the follow-up once+ // either way.+ it.each([+ ["a plain mount", false],+ ["a Strict Mode mount", true],+ ])(+ "keeps a follow-up the backend still holds as a queued bubble under the live turn on %s",+ { timeout: 20000 },+ async (_label, strictMode) => {+ renderResumedSession(+ HYDRATED_SESSION_MESSAGES,+ "2026-05-13T00:04:00Z",+ RESUME_REPLAY_STILL_RUNNING,+ [QUEUED_FOLLOWUP],+ strictMode,+ );++ expect(+ await screen.findByText(PERSISTED_HALF, undefined, { timeout: 10000 }),+ ).toBeDefined();+ await waitFor(+ () =>+ expect(+ document.querySelector('[data-message-id="resumed-turn-3"]'),+ ).not.toBeNull(),+ { timeout: 10000 },+ );++ // The server's message id landing after the status-only placeholder+ // looks like an auto-continue, but the buffer still holds the+ // follow-up: it stays a single queued bubble, drawn below the live+ // assistant, not a promoted user row above the chain.+ await waitFor(() => expect(screen.getByText("Queued")).toBeDefined());+ expect(screen.getAllByText(QUEUED_FOLLOWUP)).toHaveLength(1);+ const ids = Array.from(+ document.querySelectorAll("[data-message-id]"),+ ).map((el) => el.getAttribute("data-message-id"));+ expect(ids.filter((id) => id?.startsWith("promoted-"))).toEqual([]);+ const liveAssistant = document.querySelector(+ '[data-message-id="resumed-turn-3"]',+ )!;+ const queuedBubble = screen.getByText(QUEUED_FOLLOWUP);+ expect(+ liveAssistant.compareDocumentPosition(queuedBubble) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ },+ );+it("keeps the completed answer when the running turn started without a user row",{ timeout: 20000 },diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsxindex 27ff21adde..da47271770 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx@@ -16,7 +16,7 @@ import userEvent from "@testing-library/user-event";import type { UIMessageChunk } from "ai";import { http, type HttpHandler } from "msw";import { NuqsTestingAdapter } from "nuqs/adapters/testing";-import { ReactNode, useState } from "react";+import { ReactNode, StrictMode, useState } from "react";import { expect } from "vitest";import { CopilotChatHost } from "../CopilotChatHost";@@ -109,7 +109,15 @@ function Wrapper({* input into "limit reached" or injects ghost queued chips, so we pin them.*/export function renderHost(- opts: { sessionOverride?: SessionOverride; searchParams?: string } = {},+ opts: {+ sessionOverride?: SessionOverride;+ searchParams?: string;+ /** Follow-ups the backend still holds in the session's pending buffer. */+ pendingMessages?: string[];+ /** Mount under React Strict Mode, as the dev server does: every effect+ * runs twice on mount, so load-time requests fire twice. */+ strictMode?: boolean;+ } = {},) {server.use(sessionHandler(opts.sessionOverride),@@ -126,8 +134,8 @@ export function renderHost(reset_cost: 0,}),getGetV2GetPendingMessagesMockHandler200({- count: 0,- messages: [],+ count: opts.pendingMessages?.length ?? 0,+ messages: opts.pendingMessages ?? [],}),// useCopilotStop POSTs here when the user clicks Stop. The default// Orval handler returns random faker fields; pin to a deterministic@@ -139,18 +147,18 @@ export function renderHost(reason: null,}),);- return render(- <CopilotChatHost droppedFiles={[]} onDroppedFilesConsumed={() => {}} />,- {- wrapper: ({ children }) => (- <Wrapper- searchParams={opts.searchParams ?? `?sessionId=${TEST_SESSION_ID}`}- >- {children}- </Wrapper>- ),- },+ const host = (+ <CopilotChatHost droppedFiles={[]} onDroppedFilesConsumed={() => {}} />);+ return render(opts.strictMode ? <StrictMode>{host}</StrictMode> : host, {+ wrapper: ({ children }) => (+ <Wrapper+ searchParams={opts.searchParams ?? `?sessionId=${TEST_SESSION_ID}`}+ >+ {children}+ </Wrapper>+ ),+ });}/**diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.tsindex 8343303f8b..d15f18819b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.ts@@ -1,5 +1,6 @@import { act, cleanup, renderHook, waitFor } from "@testing-library/react";import { UIDataTypes, UIMessage, UITools } from "ai";+import { StrictMode } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { getV2GetPendingMessages } from "@/app/api/__generated__/endpoints/chat/chat";@@ -11,6 +12,7 @@ vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({}));type Messages = UIMessage<unknown, UIDataTypes, UITools>[];+type ChatStatus = Parameters<typeof useCopilotPendingChips>[0]["status"];const mockGetPending = vi.mocked(getV2GetPendingMessages);@@ -65,6 +67,41 @@ function assistantWithHints(hints: DrainHint[]): Messages[number] {return { id: ASSISTANT_ID, role: "assistant", parts };}+/** The auto-continue assistant, optionally carrying drain hints of its+ * own with a visible step between them so each is a split point. */+function continuationMessage(hints: DrainHint[] = []): Messages[number] {+ return { ...assistantWithHints(hints), id: "assistant-continuation" };+}++/** Hold every pending-buffer GET open until the test resolves it, so two+ * reconciliations of the same chip can overlap the way they do live. */+function deferPendingGets() {+ const resolvers: Array<(count: number) => void> = [];+ mockGetPending.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolvers.push((count) =>+ resolve({+ status: 200,+ data: { count, messages: [] },+ headers: new Headers(),+ } as Awaited<ReturnType<typeof getV2GetPendingMessages>>),+ );+ }),+ );+ return {+ count: () => resolvers.length,+ resolveDrained: (index: number) =>+ act(async () => {+ resolvers[index](0);+ }),+ };+}++function storedFallbacks(messages: Messages) {+ return messages.filter((m) => m.id.startsWith("promoted-"));+}+/** What the transcript draws: the user rows of the render-time split. */function renderedUserRows(messages: Messages) {return splitMessagesAtDrainHints(messages)@@ -378,6 +415,211 @@ describe("useCopilotPendingChips", () => {expect(promoted?.role).toBe("user");});+ it("keeps the chip queued when useChat swaps its placeholder id while the backend still holds the message", async () => {+ mockGetPending.mockResolvedValue({+ status: 200,+ data: { count: 1, messages: ["follow up"] },+ headers: new Headers(),+ } as Awaited<ReturnType<typeof getV2GetPendingMessages>>);++ // The backend emits `data-status` before `start`, so the turn opens as+ // a status-only placeholder under the SDK's own id…+ const placeholder: Messages[number] = {+ id: "sdk-placeholder",+ role: "assistant",+ parts: [+ { type: "data-status", data: { message: "Preparing…" } },+ ] as Messages[number]["parts"],+ };+ const { view, getMessages, rerender } = setupHook([placeholder]);+ act(() => {+ view.result.current.queueMessage("follow up");+ });++ // …and the server's message id lands after it. That is not an+ // auto-continue: the follow-up is still in the buffer.+ await act(async () => {+ rerender([placeholder, assistantMessage(0)]);+ });++ await waitFor(() => expect(mockGetPending).toHaveBeenCalledWith("s1"));+ expect(view.result.current.queuedMessages).toEqual(["follow up"]);+ expect(getMessages().some((m) => m.id.startsWith("promoted-"))).toBe(false);++ // Every later delta lands in the same message: one reconciliation per+ // new id, not one per chunk.+ await act(async () => {+ rerender([placeholder, assistantMessage(0)]);+ });+ expect(mockGetPending).toHaveBeenCalledTimes(1);+ });++ it("promotes chips before the auto-continue assistant once the backend confirms the drain", async () => {+ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);+ act(() => {+ view.result.current.queueMessage("follow up");+ });++ const continuation: Messages[number] = {+ id: "assistant-continuation",+ role: "assistant",+ parts: [{ type: "text", text: "continuing…", state: "done" }],+ };+ await act(async () => {+ rerender([assistantMessage(0), continuation]);+ });++ await waitFor(() => {+ expect(mockGetPending).toHaveBeenCalledWith("s1");+ expect(view.result.current.queuedMessages).toEqual([]);+ });+ const ids = getMessages().map((m) => m.id);+ expect(ids).toHaveLength(3);+ expect(ids[0]).toBe(ASSISTANT_ID);+ expect(ids[1]).toMatch(/^promoted-auto-continue-pending-chip-/);+ expect(ids[2]).toBe("assistant-continuation");+ });++ describe("overlapping reconciliations of one queued chip", () => {+ // A new assistant id and a drain hint (or the backstop poll) can each+ // start a GET for the same chip before the other resolves. Each sees a+ // drained buffer; only one bubble may be stored for the chip, whichever+ // path wins — the promotion flavour is not part of the chip's identity.+ it.each([+ ["auto-continue first", [0, 1]],+ ["drain hint first", [1, 0]],+ ])(+ "stores one fallback when the text-bearing hint's GET overlaps the new-id GET (%s)",+ async (_label, order) => {+ const gets = deferPendingGets();+ const { view, getMessages, rerender } = setupHook([+ assistantMessage(0),+ ]);+ act(() => {+ view.result.current.queueMessage("follow up");+ });++ await act(async () => {+ rerender([assistantMessage(0), continuationMessage()]);+ });+ expect(gets.count()).toBe(1);++ await act(async () => {+ rerender([+ assistantMessage(0),+ continuationMessage([{ text: "follow up" }]),+ ]);+ });+ expect(gets.count()).toBe(2);++ for (const index of order) await gets.resolveDrained(index);++ expect(view.result.current.queuedMessages).toEqual([]);+ expect(storedFallbacks(getMessages())).toHaveLength(1);+ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "follow up",+ ]);+ const messages = getMessages();+ expect(messages[messages.length - 1].id).toBe("assistant-continuation");+ },+ );++ it.each([+ ["auto-continue first", [0, 1]],+ ["count-only hint first", [1, 0]],+ ])(+ "renders one follow-up when a count-only hint's GET overlaps the new-id GET (%s)",+ async (_label, order) => {+ const gets = deferPendingGets();+ const { view, getMessages, rerender } = setupHook([+ assistantMessage(0),+ ]);+ act(() => {+ view.result.current.queueMessage("follow up");+ });++ await act(async () => {+ rerender([assistantMessage(0), continuationMessage()]);+ });+ await act(async () => {+ rerender([assistantMessage(0), continuationMessage(["count-only"])]);+ });+ expect(gets.count()).toBe(2);++ for (const index of order) await gets.resolveDrained(index);++ expect(view.result.current.queuedMessages).toEqual([]);+ expect(storedFallbacks(getMessages())).toHaveLength(1);+ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "follow up",+ ]);+ },+ );++ it("renders one follow-up when the backstop poll overlaps the new-id GET", async () => {+ vi.useFakeTimers();+ try {+ const gets = deferPendingGets();+ const { view, getMessages, rerender } = setupHook([+ assistantMessage(0),+ ]);+ act(() => {+ view.result.current.queueMessage("follow up");+ });++ await act(async () => {+ rerender([assistantMessage(0), continuationMessage()]);+ });+ expect(gets.count()).toBe(1);++ // No hint ever arrives; the backstop fires while the first GET is+ // still open.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(gets.count()).toBe(2);++ await gets.resolveDrained(1);+ await gets.resolveDrained(0);++ expect(view.result.current.queuedMessages).toEqual([]);+ expect(storedFallbacks(getMessages())).toHaveLength(1);+ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "follow up",+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps two bubbles for two genuinely repeated follow-ups drained together", async () => {+ const gets = deferPendingGets();+ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);+ act(() => {+ view.result.current.queueMessage("continue");+ view.result.current.queueMessage("continue");+ });++ await act(async () => {+ rerender([assistantMessage(0), continuationMessage()]);+ });+ await act(async () => {+ rerender([assistantMessage(0), continuationMessage(["count-only"])]);+ });+ expect(gets.count()).toBe(2);++ await gets.resolveDrained(0);+ await gets.resolveDrained(1);++ expect(view.result.current.queuedMessages).toEqual([]);+ expect(storedFallbacks(getMessages())).toHaveLength(2);+ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "continue",+ "continue",+ ]);+ });+ });+it("does not promote when the backend buffer count still covers the local chips", async () => {mockGetPending.mockResolvedValue({status: 200,@@ -475,4 +717,209 @@ describe("useCopilotPendingChips", () => {vi.useRealTimers();}});++ describe("restoring the buffer on session load", () => {+ /** Hold every peek GET open. `resolveAll` answers each with the same+ * one-message buffer, the way the backend does while a follow-up is+ * still queued; `resolveWith` answers one peek with a given buffer. */+ function deferBufferPeeks(text: string) {+ const resolvers: Array<(messages: string[]) => void> = [];+ mockGetPending.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolvers.push((messages) =>+ resolve({+ status: 200,+ data: { count: messages.length, messages },+ headers: new Headers(),+ } as Awaited<ReturnType<typeof getV2GetPendingMessages>>),+ );+ }),+ );+ return {+ count: () => resolvers.length,+ resolveAll: () =>+ act(async () => {+ resolvers.splice(0).forEach((resolve) => resolve([text]));+ }),+ resolveWith: (index: number, messages: string[]) =>+ act(async () => {+ resolvers[index](messages);+ }),+ };+ }++ it("shows the queued follow-up once when two peeks overlap on load", async () => {+ const peeks = deferBufferPeeks("follow up");+ const setMessages = vi.fn();+ const view = renderHook(+ ({ status }) =>+ useCopilotPendingChips({+ sessionId: "s1",+ status,+ messages: [],+ setMessages,+ }),+ { initialProps: { status: "ready" as "ready" | "error" } },+ );+ // A second idle edge lands before the first peek has answered.+ view.rerender({ status: "error" });+ expect(peeks.count()).toBe(2);++ await peeks.resolveAll();++ // Both peeks report the same buffer: the strip must show that one+ // message, not one copy per peek. A doubled strip is what made the+ // next new-assistant reconciliation promote the extra copy above the+ // running tool chain while the backend still held the message.+ await waitFor(() =>+ expect(view.result.current.queuedMessages).toEqual(["follow up"]),+ );+ expect(setMessages).not.toHaveBeenCalled();+ });++ it("shows the queued follow-up once under a Strict Mode mount", async () => {+ const peeks = deferBufferPeeks("follow up");+ const setMessages = vi.fn();+ // The dev server mounts every effect twice, so the load peek fires+ // twice with the same empty snapshot.+ const view = renderHook(+ () =>+ useCopilotPendingChips({+ sessionId: "s1",+ status: "ready",+ messages: [],+ setMessages,+ }),+ { wrapper: StrictMode },+ );+ expect(peeks.count()).toBe(2);++ await peeks.resolveAll();++ await waitFor(() =>+ expect(view.result.current.queuedMessages).toEqual(["follow up"]),+ );+ });++ it("keeps a message typed between two overlapping peeks", async () => {+ const peeks = deferBufferPeeks("typed meanwhile");+ const setMessages = vi.fn();+ const view = renderHook(+ ({ status }) =>+ useCopilotPendingChips({+ sessionId: "s1",+ status,+ messages: [],+ setMessages,+ }),+ { initialProps: { status: "ready" as "ready" | "error" } },+ );+ act(() => {+ view.result.current.queueMessage("typed meanwhile");+ });+ view.rerender({ status: "error" });+ expect(peeks.count()).toBe(2);++ // The newer peek already sees the message on the server; the older+ // one predates it and answers last. Its stale, empty buffer must not+ // wipe the message the newer peek restored — and the snapshot it+ // filters with must be its own, not the newer peek's, or it would+ // treat the typed entry as already on the server and drop it.+ await peeks.resolveWith(1, ["typed meanwhile"]);+ await peeks.resolveWith(0, []);++ await waitFor(() =>+ expect(view.result.current.queuedMessages).toEqual(["typed meanwhile"]),+ );+ });++ it("restores a buffer the turn-start peek finds when it superseded the load peek", async () => {+ const peeks = deferBufferPeeks("from before");+ const setMessages = vi.fn();+ const view = renderHook(+ ({ status }) =>+ useCopilotPendingChips({+ sessionId: "s1",+ status,+ messages: [],+ setMessages,+ }),+ { initialProps: { status: "ready" as ChatStatus } },+ );+ // The user sends a prompt before the load peek has answered.+ view.rerender({ status: "submitted" });+ view.rerender({ status: "streaming" });+ expect(peeks.count()).toBe(2);++ // The turn-start peek answers first and wins; the load peek's answer+ // is stale and dropped. The buffered message must still reach the+ // strip, or nothing would poll for it during the whole turn.+ await peeks.resolveWith(1, ["from before"]);+ await peeks.resolveWith(0, ["from before"]);++ await waitFor(() =>+ expect(view.result.current.queuedMessages).toEqual(["from before"]),+ );+ expect(setMessages).not.toHaveBeenCalled();+ });++ it("restores only the buffered messages the strip does not already hold", async () => {+ const peeks = deferBufferPeeks("from before");+ const setMessages = vi.fn();+ const view = renderHook(+ ({ status }) =>+ useCopilotPendingChips({+ sessionId: "s1",+ status,+ messages: [],+ setMessages,+ }),+ { initialProps: { status: "ready" as ChatStatus } },+ );+ view.rerender({ status: "submitted" });+ act(() => {+ view.result.current.queueMessage("typed now");+ });+ view.rerender({ status: "streaming" });+ expect(peeks.count()).toBe(2);++ await peeks.resolveWith(1, ["from before", "typed now"]);+ await peeks.resolveWith(0, ["from before"]);++ await waitFor(() =>+ expect(view.result.current.queuedMessages).toEqual([+ "from before",+ "typed now",+ ]),+ );+ expect(setMessages).not.toHaveBeenCalled();+ });++ it("keeps a message typed during the peek window", async () => {+ const peeks = deferBufferPeeks("from server");+ const setMessages = vi.fn();+ const view = renderHook(() =>+ useCopilotPendingChips({+ sessionId: "s1",+ status: "ready",+ messages: [],+ setMessages,+ }),+ );+ expect(peeks.count()).toBe(1);+ act(() => {+ view.result.current.queueMessage("typed meanwhile");+ });++ await peeks.resolveAll();++ await waitFor(() =>+ expect(view.result.current.queuedMessages).toEqual([+ "from server",+ "typed meanwhile",+ ]),+ );+ });+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.tsindex f83fd2947a..33c7194a47 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts@@ -66,8 +66,14 @@ export function useCopilotPendingChips({() => queue.map((entry) => entry.text),[queue],);+ // Live view of the strip for the peek effect, which needs the queue at the+ // moment it issues a GET without re-running on every enqueue.+ const queueRef = useRef(queue);+ useEffect(() => {+ queueRef.current = queue;+ }, [queue]);- usePeekOnBoundary({ sessionId, status, setMessages, setQueue });+ usePeekOnBoundary({ sessionId, status, queueRef, setMessages, setQueue });useAutoContinuePromotion({sessionId,@@ -106,23 +112,24 @@ export function useCopilotPendingChips({function usePeekOnBoundary({sessionId,status,+ queueRef,setMessages,setQueue,}: {sessionId: string | null;status: ChatStatus;+ queueRef: { current: QueuedMessage[] };setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void;setQueue: (updater: QueueUpdater) => void;}) {const prevSessionIdRef = useRef<string | null>(sessionId);const prevStatusRef = useRef<ChatStatus>(status);- // Snapshot of chip ids known to be in-flight to the server at the- // moment a peek GET is issued. Anything NOT in this set when the GET- // resolves was appended after the request — preserve it so a- // concurrently-queued chip isn't wiped by the server's now-stale- // truth. Set inside the effect (closes over the current chips- // value), read inside the ``.then`` handler.- const inFlightSnapshotIdsRef = useRef<Set<string>>(new Set());+ // Peeks overlap: Strict Mode mounts this effect twice, and two idle edges+ // can land within one round trip. Only the newest peek's answer is+ // applied — an older one resolving later would rebase over fresher+ // server truth (and, before this guard, the two answers each carried the+ // other's copy of a buffered message forward, doubling the strip).+ const latestPeekSeqRef = useRef(0);useEffect(() => {const prevStatus = prevStatusRef.current;@@ -154,19 +161,21 @@ function usePeekOnBoundary({// we don't want chip-appends in another effect to invalidate this// peek's result.const requestSessionId = sessionId;- // Capture the id-set of queue entries currently in local state so- // the resolve handler can preserve any entry the user queues during- // the GET window.- setQueue((current) => {- inFlightSnapshotIdsRef.current = new Set(- current.map((entry) => entry.id),- );- return current;- });+ const peekSeq = ++latestPeekSeqRef.current;+ // Snapshot of chip ids known to be in-flight to the server at the+ // moment this GET is issued. Anything NOT in this set when it+ // resolves was appended after the request — preserve it so a+ // concurrently-queued chip isn't wiped by the server's now-stale+ // truth. Captured per request: a shared snapshot let a later peek+ // overwrite an earlier one's, and the earlier answer then dropped a+ // chip typed between the two as if the server already had it.+ const inFlightIds = new Set(+ (sessionChanged ? [] : queueRef.current).map((entry) => entry.id),+ );void getV2GetPendingMessages(sessionId).then((res) => {if (prevSessionIdRef.current !== requestSessionId) return;+ if (peekSeq !== latestPeekSeqRef.current) return;if (res.status !== 200) return;- const inFlightIds = inFlightSnapshotIdsRef.current;// Turn-start drain path: when the backend has drained everything// it had at GET time, promote those drained entries to user// bubbles BEFORE removing them from local state. Without the@@ -188,6 +197,21 @@ function usePeekOnBoundary({}return current.filter((entry) => !inFlightIds.has(entry.id));});+ return;+ }+ // The backend holds more than the strip knows about: a session-load+ // peek this one superseded would have restored them, and the+ // mid-turn polls only run once the strip is non-empty. Prepend the+ // surplus (the buffer is FIFO, so the unknown ones are the oldest).+ // Local entries keep their ids: a turn-start drain hint can already+ // have a promotion in flight for them, and rebasing them to fresh+ // ids would leave that promotion's copy stuck in the strip.+ const unknownCount = res.data.count - inFlightIds.size;+ if (unknownCount > 0) {+ const restored = res.data.messages+ .slice(0, unknownCount)+ .map((text) => ({ id: uuidv4({}), text }));+ setQueue((current) => [...restored, ...current]);}return;}@@ -208,7 +232,7 @@ function usePeekOnBoundary({return [...fromServer, ...queuedDuringWindow];});});- }, [sessionId, status, setQueue]);+ }, [sessionId, status, queueRef, setQueue]);}// ── 2. Auto-continue promotion ─────────────────────────────────────────@@ -220,6 +244,14 @@ function usePeekOnBoundary({// `submitted → streaming` (that's Turn 1's opener). Any later new// assistant id in the same chain is the auto-continue. Reset on every// turn boundary.+//+// A new id is only a *cue* to reconcile, never proof of a drain: the+// backend emits `data-status` before `start`, so `useChat` parks the turn+// in a placeholder under its own id and then pushes the real message once+// `start` carries the server's id — the same "new assistant id" shape, with+// the follow-up still sitting in the buffer. Promoting on the cue alone+// drew the chip as a plain user bubble above the live tool chain (twice+// after a mid-turn reload, once per peek). The buffer re-read decides.function useAutoContinuePromotion({sessionId,@@ -242,6 +274,10 @@ function useAutoContinuePromotion({// Reset to null on every turn boundary (turn-start or becameIdle) so// the next chain starts fresh.const openerAssistantIdRef = useRef<string | null>(null);+ const latestSessionIdRef = useRef<string | null>(sessionId);+ useEffect(() => {+ latestSessionIdRef.current = sessionId;+ }, [sessionId]);useEffect(() => {const prevStatus = prevStatusRef.current;@@ -272,41 +308,56 @@ function useAutoContinuePromotion({}// Same id as opener — no new assistant yet, wait.if (latest === openerAssistantIdRef.current) return;- // A different id means the backend auto-continued.+ // A different id: reconcile once against the buffer, then treat this+ // id as the current opener so later deltas into it stay quiet.+ openerAssistantIdRef.current = latest;if (queue.length === 0) return;- const promotedIds = new Set(queue.map((entry) => entry.id));- promoteBeforeAssistant(setMessages, latest, queue);- // Drop only the entries we promoted; entries appended after the- // snapshot (during the React commit) survive.- setQueue((current) =>- current.filter((entry) => !promotedIds.has(entry.id)),+ const requestSessionId = sessionId;+ const isCurrentSession = () =>+ latestSessionIdRef.current === requestSessionId;+ void pollBackendAndPromote(+ sessionId,+ queue,+ setMessages,+ setQueue,+ isCurrentSession,+ "auto-continue",);}, [messages, status, sessionId, queue, setMessages, setQueue]);}+type PromotionFlavour = Parameters<typeof makePromotedUserBubble>[1];++const PROMOTION_FLAVOURS: PromotionFlavour[] = ["auto-continue", "midturn"];+/*** Splice promoted user bubbles for *drained* in just before the trailing- * streaming assistant message — same insertion shape as the mid-turn poll- * promotion so AI SDK's streaming continues into the right slot.+ * streaming assistant message, so AI SDK's streaming continues into the+ * right slot. Every promotion path funnels through here: the turn-start+ * drain in ``usePeekOnBoundary`` (the backend drained chips before the+ * first peek resolved, and the bubble would otherwise only appear via+ * hydration after the turn ends), the auto-continue reconciliation, and+ * the mid-turn hint / backstop poll.*- * Used by the turn-start drain path in ``usePeekOnBoundary``: when the- * backend has already drained chips before the frontend's first peek- * resolves, we'd otherwise just remove them from local state and the- * bubble would only appear via hydration after the turn ends. This- * helper makes the bubble visible immediately so the user can see what- * the model is responding to.+ * An entry that already has a bubble under *either* flavour is skipped.+ * Two reconciliations of the same chip can be in flight at once — a new+ * assistant id and a drain hint (or the backstop) each issue their own+ * GET — and both see the drained buffer; keyed on the exact id, each+ * flavour would store its own copy and the transcript would draw the+ * follow-up twice.*/function promoteChipsToTrailingBubbles(setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void,drained: QueuedMessage[],+ flavour: PromotionFlavour = "midturn",): void {setMessages((prev) => {const newBubbles = drained+ .filter((entry) => !prev.some((m) => isPromotedBubbleFor(m, entry))).map((entry) =>- makePromotedUserBubble(entry.text, "midturn", bubbleIdFor(entry)),- )- .filter((bubble) => !prev.some((m) => m.id === bubble.id));+ makePromotedUserBubble(entry.text, flavour, bubbleIdFor(entry)),+ );if (newBubbles.length === 0) return prev;const lastIdx = prev.length - 1;if (lastIdx >= 0 && prev[lastIdx].role === "assistant") {@@ -324,23 +375,19 @@ function bubbleIdFor(entry: QueuedMessage): string {return `pending-chip-${entry.id}`;}-function promoteBeforeAssistant(- setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void,- assistantId: string,- queue: QueuedMessage[],-): void {- setMessages((prev) => {- const idx = prev.findIndex((m) => m.id === assistantId);- const insertAt = idx === -1 ? prev.length : idx;- const newBubbles = queue- .map((entry) =>- makePromotedUserBubble(entry.text, "auto-continue", bubbleIdFor(entry)),- )- // Skip bubbles that are already in the array (effect re-run safety).- .filter((bubble) => !prev.some((m) => m.id === bubble.id));- if (newBubbles.length === 0) return prev;- return [...prev.slice(0, insertAt), ...newBubbles, ...prev.slice(insertAt)];- });+// Whether *message* is the promoted bubble for *entry*, whichever path+// promoted it. The queue id is the chip's identity; the flavour prefix+// only records which path got there first. Repeated user messages carry+// distinct queue ids, so they still each get a bubble.+function isPromotedBubbleFor(+ message: UIMessage,+ entry: QueuedMessage,+): boolean {+ const suffix = bubbleIdFor(entry);+ return PROMOTION_FLAVOURS.some(+ (flavour) =>+ message.id === makePromotedUserBubble(entry.text, flavour, suffix).id,+ );}// ── 3. Mid-turn drain promotion ────────────────────────────────────────@@ -458,6 +505,7 @@ async function pollBackendAndPromote(setMessages: (updater: (prev: UIMessage[]) => UIMessage[]) => void,setQueue: (updater: QueueUpdater) => void,isCurrentSession: () => boolean,+ flavour: PromotionFlavour = "midturn",): Promise<void> {let backendCount: number;try {@@ -494,20 +542,7 @@ async function pollBackendAndPromote(// keeps the stream flowing, at the cost of showing a count-only follow-up// above the work that preceded it until ``useHydrateOnStreamEnd`` snaps// the list to the DB order at the end of the turn.- setMessages((prev) => {- const newBubbles = drained- .map((entry) =>- makePromotedUserBubble(entry.text, "midturn", bubbleIdFor(entry)),- )- // Skip bubbles that are already there (effect re-run safety).- .filter((bubble) => !prev.some((m) => m.id === bubble.id));- if (newBubbles.length === 0) return prev;- const lastIdx = prev.length - 1;- if (lastIdx >= 0 && prev[lastIdx].role === "assistant") {- return [...prev.slice(0, lastIdx), ...newBubbles, prev[lastIdx]];- }- return [...prev, ...newBubbles];- });+ promoteChipsToTrailingBubbles(setMessages, drained, flavour);// Drop only the drained entries by id; entries appended after the// snapshot survive the in-flight poll race.setQueue((current) => current.filter((entry) => !drainedIds.has(entry.id)));