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): render a mid-turn follow-up where it belongs (#14575)
Abhimanyu Yadavf76c86255ab1
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/messageParts.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/messageParts.test.tsindex 0c9de4d5af..8e9c5299a7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/messageParts.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/messageParts.test.ts@@ -23,6 +23,8 @@ describe("isBookkeepingPart", () => {expect(isBookkeepingPart({ type: "data-status" })).toBe(true);expect(isBookkeepingPart({ type: "data-dream-operations" })).toBe(true);expect(isBookkeepingPart({ type: "data-compaction" })).toBe(true);+ expect(isBookkeepingPart({ type: "data-tool-display" })).toBe(true);+ expect(isBookkeepingPart({ type: "data-pending-drained" })).toBe(true);});it("leaves content alone", () => {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 daa87465f1..aaea0c2e04 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@@ -155,6 +155,67 @@ const RESUME_REPLAY_CHUNKS: UIMessageChunk[] = [{ type: "text-end", id: "replay-2" },];+/** Typed mid-turn and drained into the running turn at a tool boundary, so+ * the backend persisted it as its own user row inside the turn. */+const MIDTURN_FOLLOWUP = "And book the two o clock";++/**+ * The same reload, but the user typed while the turn was running: the drained+ * follow-up is persisted between the turn's two assistant halves.+ */+const DRAINED_MIDTURN_MESSAGES = [+ sessionMessage(1, "user", EARLIER_PROMPT),+ sessionMessage(2, "assistant", EARLIER_ANSWER),+ sessionMessage(3, "user", RESUMED_PROMPT),+ sessionMessage(4, "assistant", PERSISTED_HALF),+ sessionMessage(5, "user", MIDTURN_FOLLOWUP),+];++/** The same replay, plus the drain hint the backend re-emits from the turn's+ * Redis stream — the transcript renders the follow-up bubble from it. */+const RESUME_REPLAY_WITH_DRAIN: UIMessageChunk[] = [+ { type: "start", messageId: "resumed-turn-2" },+ { type: "start-step" },+ { type: "text-start", id: "replay-1" },+ { type: "text-delta", id: "replay-1", delta: PERSISTED_HALF },+ { type: "text-end", id: "replay-1" },+ {+ type: "data-pending-drained",+ id: "hint-1",+ data: {+ drainedCount: 1,+ messages: [{ id: "pm-1", content: MIDTURN_FOLLOWUP }],+ },+ },+ { type: "text-start", id: "replay-2" },+ { type: "text-delta", id: "replay-2", delta: REPLAYED_HALF },+ { type: "text-end", id: "replay-2" },+];++/** The same replay as the backend actually sends it: status chunks land+ * before `start`, so `useChat` parks them in a placeholder under its own id+ * and pushes the turn's real message after it. */+const RESUME_REPLAY_WITH_DRAIN_AFTER_STATUS: UIMessageChunk[] = [+ { type: "data-status", data: { message: "Setting up your environment…" } },+ { type: "data-status", data: { message: "Preparing workspace…" } },+ ...RESUME_REPLAY_WITH_DRAIN,+];++/** The replay from a backend that only reports how many messages it drained:+ * the follow-up text has to come from the hydrated row instead. */+const RESUME_REPLAY_WITH_COUNT_ONLY_DRAIN: UIMessageChunk[] =+ RESUME_REPLAY_WITH_DRAIN.map((chunk) =>+ chunk.type === "data-pending-drained"+ ? { ...chunk, data: { drainedCount: 1 } }+ : chunk,+ );++/** The replay from a backend that emits no drain hint at all. */+const RESUME_REPLAY_WITHOUT_DRAIN_HINT: UIMessageChunk[] =+ RESUME_REPLAY_WITH_DRAIN.filter(+ (chunk) => chunk.type !== "data-pending-drained",+ );+/*** A turn the backend started on its own (the engine-switch continuation* dispatched with ``is_user_message=False``): the completed answer is@@ -171,6 +232,7 @@ const BACKEND_STARTED_TURN_MESSAGES = [function renderResumedSession(messages: SessionDetailResponseMessagesItem[] = HYDRATED_SESSION_MESSAGES,activeStreamStartedAt = "2026-05-13T00:04:00Z",+ replayChunks: UIMessageChunk[] = RESUME_REPLAY_CHUNKS,) {let resumeRequests = 0;server.use(@@ -178,7 +240,7 @@ function renderResumedSession(`${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,() => {resumeRequests += 1;- return parkedSseResponse(RESUME_REPLAY_CHUNKS);+ return parkedSseResponse(replayChunks);},),);@@ -251,6 +313,118 @@ describe("useCopilotStream — resume replays a db-hydrated turn", () => {},);+ it(+ "replays the whole turn around a drained mid-turn follow-up",+ { timeout: 20000 },+ async () => {+ renderResumedSession(+ DRAINED_MIDTURN_MESSAGES,+ "2026-05-13T00:04:00Z",+ RESUME_REPLAY_WITH_DRAIN,+ );++ expect(+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),+ ).toBeDefined();++ // Everything from the running turn now comes from the replay: the work+ // before the drain, the follow-up bubble the hint carries, then the+ // work after it. The hydrated `-seq-4` / `-seq-5` rows sit INSIDE that+ // turn, so leaving them (the cut used to stop at the mid-turn user row)+ // keeps the pre-drain half and the follow-up on screen twice.+ expect(+ Array.from(document.querySelectorAll("[data-message-id]")).map((el) =>+ el.getAttribute("data-message-id"),+ ),+ ).toEqual([+ `${TEST_SESSION_ID}-seq-1`,+ `${TEST_SESSION_ID}-seq-2`,+ `${TEST_SESSION_ID}-seq-3`,+ "resumed-turn-2#seg0",+ "midturn-pm-1",+ "resumed-turn-2",+ ]);+ expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ expect(screen.getAllByText(MIDTURN_FOLLOWUP)).toHaveLength(1);+ },+ );++ it(+ "draws the follow-up once when status chunks precede the replay's start",+ { timeout: 20000 },+ async () => {+ renderResumedSession(+ DRAINED_MIDTURN_MESSAGES,+ "2026-05-13T00:04:00Z",+ RESUME_REPLAY_WITH_DRAIN_AFTER_STATUS,+ );++ expect(+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),+ ).toBeDefined();++ // The kept `-seq-5` row and the bubble the hint draws are the same+ // follow-up. The status-only placeholder the SDK leaves between them+ // must not stop the split from reconciling the two.+ const ids = Array.from(+ document.querySelectorAll("[data-message-id]"),+ ).map((el) => el.getAttribute("data-message-id"));+ expect(ids).toHaveLength(7);+ expect(ids.slice(0, 3)).toEqual([+ `${TEST_SESSION_ID}-seq-1`,+ `${TEST_SESSION_ID}-seq-2`,+ `${TEST_SESSION_ID}-seq-3`,+ ]);+ expect(ids.slice(4)).toEqual([+ "resumed-turn-2#seg0",+ "midturn-pm-1",+ "resumed-turn-2",+ ]);+ expect(ids).not.toContain(`promoted-midturn-${TEST_SESSION_ID}-seq-5`);+ expect(screen.getAllByText(MIDTURN_FOLLOWUP)).toHaveLength(1);+ expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ },+ );++ it.each([+ ["only a drained count", RESUME_REPLAY_WITH_COUNT_ONLY_DRAIN],+ ["no drain hint", RESUME_REPLAY_WITHOUT_DRAIN_HINT],+ ])(+ "keeps the hydrated follow-up when the replay's hint carries %s",+ { timeout: 20000 },+ async (_label, replayChunks) => {+ renderResumedSession(+ DRAINED_MIDTURN_MESSAGES,+ "2026-05-13T00:04:00Z",+ replayChunks,+ );++ expect(+ await screen.findByText(REPLAYED_HALF, undefined, { timeout: 10000 }),+ ).toBeDefined();++ // The replay cannot redraw a follow-up it has no text for, and the+ // pending buffer it came from is already empty, so the hydrated row is+ // the only copy — it must survive the resume cut. The assistant halves+ // still come from the replay alone.+ expect(screen.getAllByText(MIDTURN_FOLLOWUP)).toHaveLength(1);+ expect(screen.getAllByText(PERSISTED_HALF)).toHaveLength(1);+ expect(screen.getAllByText(REPLAYED_HALF)).toHaveLength(1);+ expect(screen.getAllByText(RESUMED_PROMPT)).toHaveLength(1);+ expect(+ Array.from(document.querySelectorAll("[data-message-id]")).map((el) =>+ el.getAttribute("data-message-id"),+ ),+ ).toEqual([+ `${TEST_SESSION_ID}-seq-1`,+ `${TEST_SESSION_ID}-seq-2`,+ `${TEST_SESSION_ID}-seq-3`,+ `promoted-midturn-${TEST_SESSION_ID}-seq-5`,+ "resumed-turn-2",+ ]);+ },+ );+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/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex bd1df81259..f0d663d031 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -25,12 +25,17 @@ import {getLastCompactionCallId,getLatestCompactionPhase,getLatestCompactionStats,- getTurnMessages,parseSpecialMarkers,} from "./helpers";+import {+ isMidTurnSegmentRow,+ splitMessagesAtDrainHints,+ turnMessagesForRow,+} from "./midTurnSplit";import {getLatestAssistantStatusMessage,isBookkeepingPart,+ PENDING_DRAINED_PART_TYPE,} from "../../messageParts";import { RESTORE_STALL_TIMEOUT_MS } from "../../restoreConstants";import type { ExpertIdentity } from "../../useExpertMap";@@ -343,9 +348,15 @@ export function ChatMessagesContainer({// opacity-0 only during the single frame between messages arriving and scroll settlingconst hideForScroll = messagesReady && !settled;+ // Rendered rows, not the array `useChat` owns: a turn whose pending buffer+ // was drained mid-stream renders as chain → follow-up bubble → chain, while+ // the underlying message stays whole. See `splitMessagesAtDrainHints`.+ const renderRows = splitMessagesAtDrainHints(messages);const lastMessage = messages[messages.length - 1];+ // Read off the rendered rows: a fallback follow-up row the split drops in+ // favour of the drain-point bubble has no element to anchor the tail on.const lastUserMessageID =- messages.findLast((message) => message.role === "user")?.id ?? null;+ renderRows.findLast((row) => row.role === "user")?.id ?? null;const graphExecId = useMemo(() => extractGraphExecId(messages), [messages]);// The backend appends a persisted error marker to ``session.messages`` AND@@ -373,10 +384,19 @@ export function ChatMessagesContainer({if (lastMessage?.role !== "assistant") return false;// Ignore bookkeeping parts — none of them counts as "real" content that// hides the Thinking indicator. See `isBookkeepingPart` for the list.- const parts = lastMessage.parts.filter((p) => !isBookkeepingPart(p));- if (parts.length === 0) return false;+ // A drain hint newer than the last content part is the one exception:+ // the follow-up just landed and nothing has been produced past it, so+ // the text or tool above it is settled and Thinking is the only sign+ // the assistant picked the follow-up up.+ let lastIndex = lastMessage.parts.length - 1;+ while (lastIndex >= 0 && isBookkeepingPart(lastMessage.parts[lastIndex])) {+ if (lastMessage.parts[lastIndex].type === PENDING_DRAINED_PART_TYPE)+ return false;+ lastIndex--;+ }+ if (lastIndex < 0) return false;- const lastPart = parts[parts.length - 1];+ const lastPart = lastMessage.parts[lastIndex];if (lastPart.type === "text" && lastPart.text.trim().length > 0)return true;@@ -522,7 +542,7 @@ export function ChatMessagesContainer({<LoadingSpinner className="text-neutral-600" /></div>)}- {messages.map((message, messageIndex) => {+ {renderRows.map((message, rowIndex) => {// A run-post rides structured metadata — render a compact WorkCard// instead of the raw markdown wall (legacy posts have no metadata// and fall through to normal rendering).@@ -552,7 +572,7 @@ export function ChatMessagesContainer({}const isLastAssistant =- messageIndex === messages.length - 1 &&+ rowIndex === renderRows.length - 1 &&message.role === "assistant";const isCurrentlyStreaming =@@ -561,11 +581,15 @@ export function ChatMessagesContainer({const isAssistant = message.role === "assistant";- const nextMessage = messages[messageIndex + 1];+ const nextRow = renderRows[rowIndex + 1];+ // A segment that only runs up to a mid-turn drain is never the end+ // of its turn — the same backend turn continues under the follow-up+ // bubble, so the stats bar and the assistant actions belong to the+ // last segment alone.const isLastInTurn =isAssistant &&- messageIndex <= messages.length - 1 &&- (!nextMessage || nextMessage.role === "user");+ !isMidTurnSegmentRow(message) &&+ (!nextRow || nextRow.role === "user");// Bookkeeping parts are stripped before any render/split logic so// they never reach the user UI, and so one landing between two// tool calls can't split a chain. data-status surfaces via@@ -667,9 +691,9 @@ export function ChatMessagesContainer({)}{isLastInTurn && !isCurrentlyStreaming && (<TurnStatsBar- turnMessages={getTurnMessages(messages, messageIndex)}+ turnMessages={turnMessagesForRow(messages, message)}elapsedSeconds={- messageIndex === messages.length - 1+ rowIndex === renderRows.length - 1? frozenElapsedRef.current: undefined}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsxindex 6f0faa4340..3bbd790589 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx@@ -1,4 +1,5 @@import { act } from "@testing-library/react";+import type { UIDataTypes, UIMessage, UITools } from "ai";import { render, screen, cleanup } from "@/tests/integrations/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ChatMessagesContainer } from "../ChatMessagesContainer";@@ -43,11 +44,17 @@ vi.mock("@/components/ai-elements/message", () => ({Message: ({children,from,+ "data-message-id": messageId,}: {children: React.ReactNode;from?: string;+ "data-message-id"?: string;}) => (- <div data-testid={`message-${from ?? "unknown"}`} data-from={from}>+ <div+ data-testid={`message-${from ?? "unknown"}`}+ data-from={from}+ data-message-id={messageId}+ >{children}</div>),@@ -67,8 +74,18 @@ vi.mock("../components/AssistantMessageActions", () => ({AssistantMessageActions: () => null,}));vi.mock("../components/ChainMessageParts", () => ({- ChainMessageParts: ({ parts }: { parts: unknown[] }) => (- <div data-testid="chain-message-parts" data-parts={JSON.stringify(parts)} />+ ChainMessageParts: ({+ parts,+ isCurrentlyStreaming,+ }: {+ parts: unknown[];+ isCurrentlyStreaming?: boolean;+ }) => (+ <div+ data-testid="chain-message-parts"+ data-parts={JSON.stringify(parts)}+ data-streaming={String(!!isCurrentlyStreaming)}+ />),}));@@ -870,3 +887,248 @@ describe("ChatMessagesContainer — expert kickoff", () => {expect(screen.getAllByTestId("message-user")).toHaveLength(1);});});++// ── mid-turn drain split ──────────────────────────────────────────────────++describe("ChatMessagesContainer — mid-turn follow-up", () => {+ afterEach(cleanup);++ const toolPart = {+ type: "tool-read_file",+ toolCallId: "call-1",+ state: "output-available",+ input: {},+ output: "ok",+ };++ const drainedTurn = [+ {+ id: "user-1",+ role: "user" as const,+ parts: [{ type: "text" as const, text: "plan my week" }],+ },+ {+ id: "assistant-1",+ role: "assistant" as const,+ parts: [+ toolPart,+ {+ type: "data-pending-drained",+ id: "hint-0",+ data: {+ drainedCount: 1,+ messages: [{ id: "pm-1", content: "also check Friday" }],+ },+ },+ { ...toolPart, toolCallId: "call-2" },+ ],+ },+ ] as unknown as UIMessage<unknown, UIDataTypes, UITools>[];++ function renderedRowIds() {+ return Array.from(document.querySelectorAll("[data-message-id]")).map(+ (el) => el.getAttribute("data-message-id"),+ );+ }++ it("renders the drained message between the work before and after it", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ status="streaming"+ messages={drainedTurn}+ />,+ );++ expect(renderedRowIds()).toEqual([+ "user-1",+ "assistant-1#seg0",+ "midturn-pm-1",+ "assistant-1",+ ]);+ expect(+ Array.from(document.querySelectorAll('[data-testid="message-user"]')),+ ).toHaveLength(2);+ });++ it("settles the chain above the follow-up and streams only the last one", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ status="streaming"+ messages={drainedTurn}+ />,+ );++ expect(+ screen+ .getAllByTestId("chain-message-parts")+ .map((el) => el.getAttribute("data-streaming")),+ ).toEqual(["false", "true"]);+ });++ it("draws a promoted fallback bubble once its hint carries the text", () => {+ // The backstop GET promoted the chip above the assistant before the SSE+ // hint arrived; the hint then draws the same follow-up at the drain+ // point. Exactly one bubble, between the two assistant segments.+ const withFallback = [+ drainedTurn[0],+ {+ id: "promoted-midturn-pending-chip-local-1",+ role: "user" as const,+ parts: [{ type: "text" as const, text: "also check Friday" }],+ },+ drainedTurn[1],+ ] as unknown as UIMessage<unknown, UIDataTypes, UITools>[];++ render(+ <ChatMessagesContainer+ {...baseProps}+ status="streaming"+ messages={withFallback}+ />,+ );++ expect(renderedRowIds()).toEqual([+ "user-1",+ "assistant-1#seg0",+ "midturn-pm-1",+ "assistant-1",+ ]);+ // The prompt and one follow-up: the fallback row is not drawn as well.+ expect(screen.getAllByTestId("message-user")).toHaveLength(2);+ });++ it("keeps a text-less hint out of the tool chain it lands in", () => {+ // The hint is stream bookkeeping: left in the parts, it would split the+ // chain around it into two.+ render(+ <ChatMessagesContainer+ {...baseProps}+ status="streaming"+ messages={+ [+ drainedTurn[0],+ {+ ...drainedTurn[1],+ parts: [+ drainedTurn[1].parts[0],+ {+ type: "data-pending-drained",+ id: "hint-0",+ data: { drainedCount: 1 },+ },+ drainedTurn[1].parts[2],+ ],+ },+ ] as unknown as UIMessage<unknown, UIDataTypes, UITools>[]+ }+ />,+ );++ const renderedParts = JSON.parse(+ screen.getByTestId("chain-message-parts").dataset.parts ?? "[]",+ ) as { type: string }[];+ expect(renderedParts.map((p) => p.type)).toEqual([+ "tool-read_file",+ "tool-read_file",+ ]);+ });++ it("shows the thinking indicator while the follow-up is the newest thing in the turn", () => {+ // Answer text is normally inflight, but a drain hint landing after it+ // means the assistant has not produced anything for the follow-up yet.+ render(+ <ChatMessagesContainer+ {...baseProps}+ status="streaming"+ messages={+ [+ drainedTurn[0],+ {+ ...drainedTurn[1],+ parts: [+ { type: "text", text: "Here is your week.", state: "done" },+ drainedTurn[1].parts[1],+ ],+ },+ ] as unknown as UIMessage<unknown, UIDataTypes, UITools>[]+ }+ />,+ );++ expect(renderedRowIds()).toEqual([+ "user-1",+ "assistant-1#seg0",+ "midturn-pm-1",+ "assistant-1",+ ]);+ expect(screen.getByTestId("thinking-indicator")).toBeDefined();+ });++ it("draws one follow-up when the promoted bubble sits behind the stream's placeholder row", () => {+ // The live shape: the prompt, the status-only placeholder `useChat`+ // leaves before the server's message id arrives, the bubble the+ // auto-continue effect promoted, then the assistant whose hint carries+ // the same text.+ render(+ <ChatMessagesContainer+ {...baseProps}+ status="streaming"+ messages={+ [+ drainedTurn[0],+ {+ id: "placeholder-1",+ role: "assistant",+ parts: [{ type: "data-status", data: { message: "Preparing…" } }],+ },+ {+ id: "promoted-auto-continue-pending-chip-local-1",+ role: "user",+ parts: [{ type: "text", text: "also check Friday" }],+ },+ drainedTurn[1],+ ] as unknown as UIMessage<unknown, UIDataTypes, UITools>[]+ }+ />,+ );++ expect(renderedRowIds()).toEqual([+ "user-1",+ "placeholder-1",+ "assistant-1#seg0",+ "midturn-pm-1",+ "assistant-1",+ ]);+ expect(screen.getAllByTestId("message-user")).toHaveLength(2);+ });++ it("leaves the turn whole when the hint carries no text", () => {+ const withoutText = [+ drainedTurn[0],+ {+ ...drainedTurn[1],+ parts: [+ drainedTurn[1].parts[0],+ {+ type: "data-pending-drained",+ id: "hint-0",+ data: { drainedCount: 1 },+ },+ drainedTurn[1].parts[2],+ ],+ },+ ] as unknown as UIMessage<unknown, UIDataTypes, UITools>[];++ render(+ <ChatMessagesContainer+ {...baseProps}+ status="streaming"+ messages={withoutText}+ />,+ );++ expect(renderedRowIds()).toEqual(["user-1", "assistant-1"]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/midTurnSplit.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/midTurnSplit.test.tsnew file mode 100644index 0000000000..4a765279d2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/midTurnSplit.test.ts@@ -0,0 +1,437 @@+import type { UIDataTypes, UIMessage, UITools } from "ai";+import { describe, expect, it } from "vitest";++import { makePromotedUserBubble } from "../../../helpers/makePromotedBubble";+import {+ asMidTurnFallbackRow,+ isMidTurnFallbackRow,+ isMidTurnSegmentRow,+ messagesCarryDrainedText,+ splitMessagesAtDrainHints,+} from "../midTurnSplit";++type ChatMessage = UIMessage<unknown, UIDataTypes, UITools>;+type Part = ChatMessage["parts"][number];++function toolPart(name: string): Part {+ return {+ type: `tool-${name}`,+ toolCallId: `call-${name}`,+ state: "output-available",+ input: {},+ output: "ok",+ } as unknown as Part;+}++function textPart(text: string): Part {+ return { type: "text", text, state: "done" } as Part;+}++function hintPart(messages?: { id: string; content: string }[]): Part {+ return {+ type: "data-pending-drained",+ id: "hint",+ data:+ messages === undefined+ ? { drainedCount: 1 }+ : { drainedCount: messages.length, messages },+ } as unknown as Part;+}++function statusPart(message: string): Part {+ return { type: "data-status", data: { message } } as unknown as Part;+}++function assistant(id: string, parts: Part[]): ChatMessage {+ return { id, role: "assistant", parts };+}++function user(id: string, text: string): ChatMessage {+ return { id, role: "user", parts: [textPart(text)] };+}++const PROMPT = user("user-1", "plan my week");++/** The bubble `useCopilotPendingChips` promotes above the live assistant. */+function fallback(id: string, text: string): ChatMessage {+ return makePromotedUserBubble(text, "midturn", id);+}++describe("splitMessagesAtDrainHints", () => {+ it("returns the same array when no message carries a hint", () => {+ const messages = [+ PROMPT,+ assistant("a1", [toolPart("read"), textPart("done")]),+ ];++ expect(splitMessagesAtDrainHints(messages)).toBe(messages);+ expect(messagesCarryDrainedText(messages)).toBe(false);+ });++ it("does not split on a hint from a backend that sends no text", () => {+ const messages = [+ PROMPT,+ assistant("a1", [toolPart("read"), hintPart(), toolPart("write")]),+ ];++ expect(splitMessagesAtDrainHints(messages)).toBe(messages);+ expect(messagesCarryDrainedText(messages)).toBe(false);+ });++ it("splits one turn into chain, follow-up bubble and the work after it", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "also check Friday" }]),+ toolPart("write"),+ textPart("done"),+ ]),+ ]);++ expect(rows.map((row) => [row.id, row.role])).toEqual([+ ["user-1", "user"],+ ["a1#seg0", "assistant"],+ ["midturn-pm-1", "user"],+ ["a1", "assistant"],+ ]);+ // The hint itself never reaches a segment — it is the delimiter.+ expect(rows[1].parts).toEqual([toolPart("read")]);+ expect(rows[2].parts).toEqual([+ { type: "text", text: "also check Friday", state: "done" },+ ]);+ expect(rows[3].parts).toEqual([toolPart("write"), textPart("done")]);+ });++ it("keeps the original id on the last segment only", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "one" }]),+ toolPart("write"),+ ]),+ ]);++ expect(rows.filter((row) => row.id === "a1")).toHaveLength(1);+ expect(isMidTurnSegmentRow(rows[1])).toBe(true);+ expect(isMidTurnSegmentRow(rows[3])).toBe(false);+ });++ it("renders one bubble per message when a batch drains at once", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([+ { id: "pm-1", content: "first" },+ { id: "pm-2", content: "second" },+ ]),+ toolPart("write"),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "a1#seg0",+ "midturn-pm-1",+ "midturn-pm-2",+ "a1",+ ]);+ });++ it("keeps both follow-ups when two hints land back to back", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "first" }]),+ hintPart([{ id: "pm-2", content: "second" }]),+ toolPart("write"),+ ]),+ ]);++ // The second hint opens on an empty segment: it must still draw its+ // bubble, and must not cut an empty assistant row between the two.+ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "a1#seg0",+ "midturn-pm-1",+ "midturn-pm-2",+ "a1",+ ]);+ expect(rows[1].parts).toEqual([toolPart("read")]);+ expect(rows[4].parts).toEqual([toolPart("write")]);+ });++ it("gives consecutive id-less hints distinct fallback row ids", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "", content: "first" }]),+ hintPart([{ id: "", content: "second" }]),+ ]),+ ]);++ const followUps = rows.filter(+ (row) => row.role === "user" && row !== PROMPT,+ );+ expect(new Set(followUps.map((row) => row.id)).size).toBe(2);+ });++ it("splits again for every later drain in the same turn", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "first" }]),+ toolPart("write"),+ hintPart([{ id: "pm-2", content: "second" }]),+ textPart("done"),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "a1#seg0",+ "midturn-pm-1",+ "a1#seg1",+ "midturn-pm-2",+ "a1",+ ]);+ });++ it("ignores a hint that lands before the turn has drawn anything", () => {+ // The turn-start drain folds the queued text into the opening prompt, so+ // splitting there would show it twice.+ const messages = [+ PROMPT,+ assistant("a1", [+ { type: "step-start" } as Part,+ hintPart([{ id: "pm-1", content: "typed while the last turn ran" }]),+ toolPart("read"),+ ]),+ ];++ expect(splitMessagesAtDrainHints(messages)).toBe(messages);+ });++ it("does not count a text-less hint as the turn's first drawn content", () => {+ // A count-only hint (older backend, or a turn-start drain) renders+ // nothing, so a text-bearing hint right after it is still a turn-start+ // drain: splitting there would cut a segment holding only the hint.+ const messages = [+ PROMPT,+ assistant("a1", [+ hintPart(),+ hintPart([{ id: "pm-1", content: "also check Friday" }]),+ toolPart("read"),+ ]),+ ];++ expect(splitMessagesAtDrainHints(messages)).toBe(messages);+ });++ it("keeps an empty tail segment when the hint is the newest part", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "and book it" }]),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ // Still the live assistant row, so the thinking indicator has a home.+ expect(rows[3].parts).toEqual([]);+ });++ it("leaves non-assistant messages and their parts untouched", () => {+ const messages = [+ PROMPT,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "one" }]),+ textPart("done"),+ ]),+ ];+ const rows = splitMessagesAtDrainHints(messages);++ expect(rows[0]).toBe(messages[0]);+ expect(messages[1].parts).toHaveLength(3);+ });++ it("hides the fallback row whose text a hint draws at the drain point", () => {+ // The backstop GET resolved before the hint reached the client, so the+ // chip was promoted above the assistant; the hint then draws the same+ // follow-up where it belongs. One bubble, not two.+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ fallback("chip-1", "follow up"),+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "follow up" }]),+ toolPart("write"),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ });++ it("keeps a repeated identical fallback row the hint did not draw", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ fallback("chip-1", "continue"),+ fallback("chip-2", "continue"),+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "continue" }]),+ toolPart("write"),+ ]),+ ]);++ // Two distinct drains of the same text: one drawn by its hint, the+ // other (count-only or dropped hint) still on its fallback row.+ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "promoted-midturn-chip-2",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ });++ it("keeps a fallback row with text no hint drew", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ fallback("chip-1", "something else"),+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "follow up" }]),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "promoted-midturn-chip-1",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ });++ it("only reconciles fallback rows sitting directly above the hint's turn", () => {+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ fallback("chip-1", "continue"),+ assistant("a0", [textPart("earlier turn")]),+ user("user-2", "next"),+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "continue" }]),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "promoted-midturn-chip-1",+ "a0",+ "user-2",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ });++ it("reaches a fallback row past the placeholder the stream leaves above the live assistant", () => {+ // The backend emits `data-status` before `start`, so `useChat` parks+ // those parts in a placeholder under its own id and pushes the real+ // message after it. The placeholder draws nothing; it must not shield+ // the fallback row above it from the bubble the hint draws.+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ fallback("pending-chip-local-1", "also check Friday"),+ assistant("placeholder", [statusPart("Preparing workspace…")]),+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "also check Friday" }]),+ toolPart("write"),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "placeholder",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ });++ it("drops a bubble the auto-continue path promoted once the hint draws it", () => {+ // The SDK swapping its placeholder id for the server's message id looks+ // like an auto-continue to `useCopilotPendingChips`, which then promotes+ // the mid-turn chip under that flavour. Same bubble, same reconciliation.+ const rows = splitMessagesAtDrainHints([+ PROMPT,+ makePromotedUserBubble(+ "also check Friday",+ "auto-continue",+ "pending-chip-local-1",+ ),+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "also check Friday" }]),+ toolPart("write"),+ ]),+ ]);++ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ });++ it("treats a hydrated mid-turn row the resume cut kept as a fallback row", () => {+ const hydrated = user("session-seq-5", "and book it");+ const kept = asMidTurnFallbackRow(hydrated);++ expect(isMidTurnFallbackRow(hydrated)).toBe(false);+ expect(isMidTurnFallbackRow(kept)).toBe(true);+ expect(isMidTurnFallbackRow(fallback("chip-1", "x"))).toBe(true);+ expect(isMidTurnFallbackRow(PROMPT)).toBe(false);+ // Idempotent, and the row keeps its parts and its sequence suffix.+ expect(asMidTurnFallbackRow(kept)).toBe(kept);+ expect(kept.parts).toBe(hydrated.parts);+ expect(kept.id.endsWith("-seq-5")).toBe(true);++ const rows = splitMessagesAtDrainHints([+ PROMPT,+ kept,+ assistant("a1", [+ toolPart("read"),+ hintPart([{ id: "pm-1", content: "and book it" }]),+ toolPart("write"),+ ]),+ ]);+ expect(rows.map((row) => row.id)).toEqual([+ "user-1",+ "a1#seg0",+ "midturn-pm-1",+ "a1",+ ]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/midTurnSplit.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/midTurnSplit.tsnew file mode 100644index 0000000000..546f704b70--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/midTurnSplit.ts@@ -0,0 +1,267 @@+import type { UIDataTypes, UIMessage, UITools } from "ai";++import {+ isBookkeepingPart,+ PENDING_DRAINED_PART_TYPE,+} from "../../messageParts";+import { getTurnMessages, type MessagePart } from "./helpers";++type ChatMessage = UIMessage<unknown, UIDataTypes, UITools>;++/** Marks a row that is only part of its source message. The final segment+ * keeps the untouched message id, so everything keyed on it (turn stats,+ * retry, minimap anchors, the thinking indicator) still finds its row. */+const SEGMENT_ID_MARKER = "#seg";++export function isMidTurnSegmentRow(message: ChatMessage): boolean {+ return message.id.includes(SEGMENT_ID_MARKER);+}++/**+ * A follow-up bubble that stands in for the drain point because the stream+ * did not (or has not yet) drawn one: a chip `useCopilotPendingChips`+ * promoted just above the live assistant, or the hydrated mid-turn user row+ * the resume cut keeps (see `useCopilotStream`). `makePromotedUserBubble`+ * builds every promoted id with the same `promoted-` prefix; the flavour+ * behind it is not a reliable signal, since the auto-continue path also+ * fires when the SDK swaps its placeholder id for the server's message id+ * and promotes a mid-turn chip under the `auto-continue` name.+ */+const PROMOTED_ROW_ID_PREFIX = "promoted-";+const MIDTURN_FALLBACK_ID_PREFIX = `${PROMOTED_ROW_ID_PREFIX}midturn-`;++export function isMidTurnFallbackRow(message: ChatMessage): boolean {+ return (+ message.role === "user" && message.id.startsWith(PROMOTED_ROW_ID_PREFIX)+ );+}++/** Keep a hydrated user row as a fallback row. The `-seq-N` suffix stays on+ * the id so hydration can still read the row's sequence. */+export function asMidTurnFallbackRow(message: ChatMessage): ChatMessage {+ if (isMidTurnFallbackRow(message)) return message;+ return { ...message, id: `${MIDTURN_FALLBACK_ID_PREFIX}${message.id}` };+}++interface DrainedMessage {+ /** Backend-assigned id of the pending message; null on a malformed hint. */+ id: string | null;+ content: string;+}++/**+ * Render the mid-turn follow-up in chronological order: the tool chain that+ * ran before the drain, then the user's message, then the work that came+ * after it — the shape every chat app has.+ *+ * The array itself cannot be split that way. AI SDK's `useChat` accumulates+ * a whole turn into ONE assistant `UIMessage` and, on every delta, replaces+ * `messages[len - 1]` only while `lastMessage.id === state.message.id`;+ * otherwise it pushes a fresh copy of the whole turn. So a user bubble+ * inserted between the turn's parts either stops the stream from landing or+ * duplicates the entire chain. Splitting at render time instead leaves the+ * array untouched and keeps the transcript honest.+ *+ * The split point is the backend's `data-pending-drained` hint, which+ * carries the drained text (`data.messages`). A hint without it comes from+ * an older backend: no split, and the fallback row `useCopilotPendingChips`+ * promotes above the live assistant stays the bubble.+ */+export function splitMessagesAtDrainHints(+ messages: ChatMessage[],+): ChatMessage[] {+ if (!messagesCarryDrainedText(messages)) return messages;++ const rows: ChatMessage[] = [];+ for (const message of messages) {+ if (!hasSplittableDrainHint(message)) {+ rows.push(message);+ continue;+ }+ const segments = splitAssistantMessage(message);+ dropFallbackRowsDrawnBy(rows, segments);+ rows.push(...segments);+ }+ return rows;+}++/** Does the live stream carry the drained text itself? */+export function messagesCarryDrainedText(messages: ChatMessage[]): boolean {+ return messages.some(hasSplittableDrainHint);+}++/**+ * A follow-up can reach the transcript twice: as a fallback row (the chip+ * promoted when the backstop GET beat the hint, or the hydrated row a resume+ * kept) and as the bubble a text-bearing hint draws at the drain point. The+ * drain point wins, so the fallback row is dropped from the rendered rows —+ * the message array `useChat` owns is left alone.+ *+ * Fallback rows sit directly above the assistant they belong to, so matching+ * walks back from the split only while it keeps seeing them: an earlier+ * turn's rows are never consumed. The walk also steps over assistant rows+ * that draw nothing: the backend emits `data-status` chunks before `start`,+ * so `useChat` writes them into a placeholder under its own id and then,+ * once `start` carries the server's message id, pushes the real message+ * after it — leaving a bookkeeping-only row between the fallback row and+ * the assistant whose hint draws it. Each drawn bubble consumes one fallback+ * row of the same text, so a repeated "continue" whose second drain carried+ * no text still renders twice.+ */+function dropFallbackRowsDrawnBy(+ rows: ChatMessage[],+ segments: ChatMessage[],+): void {+ const remaining = new Map<string, number>();+ for (const row of segments) {+ if (row.role !== "user") continue;+ const text = userText(row);+ remaining.set(text, (remaining.get(text) ?? 0) + 1);+ }+ if (remaining.size === 0) return;++ let start = rows.length;+ while (+ start > 0 &&+ (isMidTurnFallbackRow(rows[start - 1]) || drawsNothing(rows[start - 1]))+ )+ start--;+ const kept = rows.splice(start).filter((row) => {+ if (!isMidTurnFallbackRow(row)) return true;+ const count = remaining.get(userText(row)) ?? 0;+ if (count === 0) return true;+ remaining.set(userText(row), count - 1);+ return false;+ });+ rows.push(...kept);+}++function drawsNothing(message: ChatMessage): boolean {+ return message.role === "assistant" && !message.parts.some(isVisiblePart);+}++function userText(message: ChatMessage): string {+ return message.parts+ .map((part) => (part.type === "text" ? part.text : ""))+ .join("");+}++function splitAssistantMessage(message: ChatMessage): ChatMessage[] {+ const rows: ChatMessage[] = [];+ let segmentParts: MessagePart[] = [];+ let segmentIndex = 0;+ let followUpIndex = 0;+ // Tracked across the whole turn rather than per segment: back-to-back+ // hints leave the open segment empty, and the second one's text still has+ // to be drawn. Mirrors `hasSplittableDrainHint`, which decides the same+ // thing one message at a time.+ let hasVisibleAbove = false;++ for (const part of message.parts) {+ const drained = readDrainedMessages(part);+ if (drained.length === 0) {+ // Hints render nothing, so a text-less one simply drops through+ // instead of breaking the chain it sits in.+ segmentParts.push(part);+ if (isVisiblePart(part)) hasVisibleAbove = true;+ continue;+ }+ // Nothing drawn yet means this is the turn-start drain, whose text the+ // opening prompt already contains — splitting there would cut an empty+ // segment off the top and double the bubble.+ if (!hasVisibleAbove) continue;++ // Only cut a row when the open segment actually drew something:+ // consecutive hints must not emit empty assistant rows between bubbles.+ if (segmentParts.some(isVisiblePart)) {+ rows.push({+ ...message,+ id: `${message.id}${SEGMENT_ID_MARKER}${segmentIndex}`,+ parts: segmentParts,+ });+ segmentIndex++;+ segmentParts = [];+ }+ for (const entry of drained) {+ // Counter runs over the turn, not the segment: consecutive hints share+ // a segment index, so that alone would not keep fallback ids unique.+ rows.push(+ makeFollowUpRow(+ entry.id ?? `${message.id}-${followUpIndex}`,+ entry.content,+ ),+ );+ followUpIndex++;+ }+ }++ // The tail segment is emitted even while it is still empty (the hint is+ // the newest part of a live turn): it carries the original message id, so+ // turn stats, retry, minimap anchors and the thinking indicator — the only+ // sign that the assistant picked the follow-up up — all still land.+ rows.push({ ...message, parts: segmentParts });+ return rows;+}++function makeFollowUpRow(id: string, content: string): ChatMessage {+ return {+ id: `midturn-${id}`,+ role: "user",+ parts: [{ type: "text", text: content, state: "done" }],+ };+}++/**+ * A hint is a split point only once the turn has drawn something above it.+ * The buffer is also drained at turn *start*, where the queued text is folded+ * into the opening prompt instead of injected mid-turn: splitting there would+ * cut an empty segment off the top of the assistant message and render a+ * bubble for text the user message already contains.+ */+function hasSplittableDrainHint(message: ChatMessage): boolean {+ if (message.role !== "assistant") return false;+ let hasVisiblePartAbove = false;+ for (const part of message.parts) {+ if (readDrainedMessages(part).length > 0) {+ if (hasVisiblePartAbove) return true;+ continue;+ }+ if (isVisiblePart(part)) hasVisiblePartAbove = true;+ }+ return false;+}++/** `step-start` and bookkeeping parts draw nothing on their own. */+function isVisiblePart(part: MessagePart): boolean {+ return part.type !== "step-start" && !isBookkeepingPart(part);+}++function readDrainedMessages(part: MessagePart): DrainedMessage[] {+ if (part.type !== PENDING_DRAINED_PART_TYPE) return [];+ const data = (part as { data?: { messages?: unknown } }).data;+ if (!Array.isArray(data?.messages)) return [];+ const drained: DrainedMessage[] = [];+ for (const entry of data.messages) {+ if (typeof entry !== "object" || entry === null) continue;+ const { id, content } = entry as { id?: unknown; content?: unknown };+ if (typeof content !== "string" || content.length === 0) continue;+ drained.push({+ id: typeof id === "string" && id.length > 0 ? id : null,+ content,+ });+ }+ return drained;+}++/**+ * Turn stats are per backend turn, and a mid-turn follow-up does not start a+ * new one — so the bar reads the turn off the untouched message list rather+ * than off the split rows, where the follow-up looks like a turn boundary.+ */+export function turnMessagesForRow(+ messages: ChatMessage[],+ row: ChatMessage,+): ChatMessage[] {+ const sourceIndex = messages.findIndex((m) => m.id === row.id);+ return sourceIndex === -1 ? [row] : getTurnMessages(messages, sourceIndex);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/messageParts.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/messageParts.tsindex f0d84d8559..905dbf18a4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/messageParts.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/messageParts.ts@@ -6,6 +6,13 @@ import { DREAM_OPERATIONS_PART_TYPE } from "./dreamOperations";/** Transient copy for the Thinking indicator — never rendered inline. */export const STATUS_PART_TYPE = "data-status";export const TOOL_DISPLAY_PART_TYPE = "data-tool-display";+/**+ * Emitted when the pending-message buffer is drained into a running turn.+ * Carries the drained text when the backend ships it; `midTurnSplit` reads+ * that to draw the follow-up bubble at the drain point. The part itself+ * never renders.+ */+export const PENDING_DRAINED_PART_TYPE = "data-pending-drained";/** Legacy resume metadata. */const CURSOR_PART_TYPE = "data-cursor";@@ -25,6 +32,7 @@ const BOOKKEEPING_PART_TYPES: ReadonlySet<string> = new Set([DREAM_OPERATIONS_PART_TYPE,COMPACTION_DATA_PART_TYPE,TOOL_DISPLAY_PART_TYPE,+ PENDING_DRAINED_PART_TYPE,]);export function isBookkeepingPart(part: { type: string }): boolean {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.tsindex 30f5525761..8343303f8b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.test.ts@@ -3,6 +3,7 @@ import { UIDataTypes, UIMessage, UITools } from "ai";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { getV2GetPendingMessages } from "@/app/api/__generated__/endpoints/chat/chat";+import { splitMessagesAtDrainHints } from "./components/ChatMessagesContainer/midTurnSplit";import { useCopilotPendingChips } from "./useCopilotPendingChips";vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({@@ -15,7 +16,12 @@ const mockGetPending = vi.mocked(getV2GetPendingMessages);const ASSISTANT_ID = "assistant-stable-id";-function assistantMessage(drainHints = 0): Messages[number] {+function assistantMessage(+ drainHints = 0,+ /** Text the backend ships on the hint. Present from the release that+ * renders the follow-up bubble at the drain point. */+ drainedText?: string,+): Messages[number] {const parts: Messages[number]["parts"] = [{ type: "text", text: "working…", state: "done" },];@@ -23,12 +29,54 @@ function assistantMessage(drainHints = 0): Messages[number] {parts.push({type: "data-pending-drained",id: `hint-${i}`,- data: { drainedCount: 1 },+ data: {+ drainedCount: 1,+ ...(drainedText+ ? { messages: [{ id: `pm-${i}`, content: drainedText }] }+ : {}),+ },} as Messages[number]["parts"][number]);}return { id: ASSISTANT_ID, role: "assistant", parts };}+type DrainHint = { text: string } | "count-only";++/** One assistant message carrying the given hints in order, with a tool+ * result drawn between them so each one is a split point. */+function assistantWithHints(hints: DrainHint[]): Messages[number] {+ const parts: Messages[number]["parts"] = [+ { type: "text", text: "working…", state: "done" },+ ];+ hints.forEach((hint, i) => {+ parts.push({+ type: "data-pending-drained",+ id: `hint-${i}`,+ data:+ hint === "count-only"+ ? { drainedCount: 1 }+ : {+ drainedCount: 1,+ messages: [{ id: `pm-${i}`, content: hint.text }],+ },+ } as Messages[number]["parts"][number]);+ parts.push({ type: "text", text: `step ${i}`, state: "done" });+ });+ return { id: ASSISTANT_ID, role: "assistant", parts };+}++/** What the transcript draws: the user rows of the render-time split. */+function renderedUserRows(messages: Messages) {+ return splitMessagesAtDrainHints(messages)+ .filter((row) => row.role === "user")+ .map((row) => ({+ id: row.id,+ text: row.parts+ .map((part) => (part.type === "text" ? part.text : ""))+ .join(""),+ }));+}+// Server reports the buffer as fully drained (count 0) so the hook promotes// every locally-queued chip to a bubble.function mockBufferDrained() {@@ -58,7 +106,14 @@ function setupHook(initialMessages: Messages) {{ initialProps: { messages: initialMessages } },);- return { view, setMessages, getMessages: () => current };+ /** Rerender with a new transcript, as `useChat` handing the hook a new+ * `messages` array would, so `getMessages` keeps tracking it. */+ function rerender(messages: Messages) {+ current = messages;+ view.rerender({ messages });+ }++ return { view, setMessages, getMessages: () => current, rerender };}describe("useCopilotPendingChips", () => {@@ -115,6 +170,214 @@ describe("useCopilotPendingChips", () => {expect(promoted?.role).toBe("user");});+ it("draws the follow-up once when the hint carries the text", async () => {+ // The transcript renders the bubble at the drain point itself+ // (splitMessagesAtDrainHints); the fallback bubble promoted here must+ // not show up next to it.+ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);++ act(() => {+ view.result.current.queueMessage("follow up");+ });++ await act(async () => {+ rerender([assistantMessage(1, "follow up")]);+ });++ await waitFor(() => {+ expect(mockGetPending).toHaveBeenCalledWith("s1");+ expect(view.result.current.queuedMessages).toEqual([]);+ });+ expect(renderedUserRows(getMessages())).toEqual([+ { id: "midturn-pm-0", text: "follow up" },+ ]);+ });++ it("draws one bubble when the backstop poll beat the text-bearing hint", async () => {+ vi.useFakeTimers();+ try {+ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);+ act(() => {+ view.result.current.queueMessage("follow up");+ });++ // The GET observes the drained buffer before the SSE hint reaches+ // the client: the chip becomes a fallback bubble above the assistant.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(view.result.current.queuedMessages).toEqual([]);+ const fallback = getMessages().find((m) =>+ m.id.startsWith("promoted-midturn-pending-chip-"),+ );+ expect(fallback?.role).toBe("user");+ expect(renderedUserRows(getMessages())).toEqual([+ { id: fallback!.id, text: "follow up" },+ ]);++ // Now the hint lands with the text. Exactly one follow-up must render,+ // between the two assistant segments, and the live assistant must+ // still be the last message so later deltas keep landing in it.+ await act(async () => {+ rerender([+ ...getMessages().filter((m) => m.role !== "assistant"),+ assistantWithHints([{ text: "follow up" }]),+ ]);+ });+ const rows = splitMessagesAtDrainHints(getMessages());+ expect(rows.map((row) => row.id)).toEqual([+ `${ASSISTANT_ID}#seg0`,+ "midturn-pm-0",+ ASSISTANT_ID,+ ]);+ const messages = getMessages();+ expect(messages[messages.length - 1].id).toBe(ASSISTANT_ID);+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps two identical follow-ups when only the first drain carried text", async () => {+ // Turn-scoped reconciliation: the first "continue" was drawn by its+ // hint, so its chip left no bubble behind. The second "continue" drains+ // through a count-only hint (older backend, rolling deploy) and must+ // still become a bubble — the earlier hint is not its drain.+ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);++ act(() => {+ view.result.current.queueMessage("continue");+ });+ await act(async () => {+ rerender([assistantWithHints([{ text: "continue" }])]);+ });+ await waitFor(() => {+ expect(view.result.current.queuedMessages).toEqual([]);+ });+ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "continue",+ ]);++ act(() => {+ view.result.current.queueMessage("continue");+ });+ await act(async () => {+ rerender([+ ...getMessages().filter((m) => m.role !== "assistant"),+ assistantWithHints([{ text: "continue" }, "count-only"]),+ ]);+ });+ await waitFor(() => {+ expect(view.result.current.queuedMessages).toEqual([]);+ });++ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "continue",+ "continue",+ ]);+ });++ it("keeps two identical follow-ups when the second drain's hint was dropped", async () => {+ vi.useFakeTimers();+ try {+ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);++ act(() => {+ view.result.current.queueMessage("continue");+ });+ await act(async () => {+ rerender([assistantWithHints([{ text: "continue" }])]);+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(view.result.current.queuedMessages).toEqual([]);++ // No second hint ever arrives; the backstop poll sees the drained+ // buffer and must not let the first drain's text stand in for it.+ act(() => {+ view.result.current.queueMessage("continue");+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(10_000);+ });+ expect(view.result.current.queuedMessages).toEqual([]);++ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "continue",+ "continue",+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it("promotes only the copy of a same-batch repeated text the stream did not draw", async () => {+ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);++ act(() => {+ view.result.current.queueMessage("again");+ view.result.current.queueMessage("again");+ });+ // Both chips drain in one batch, but the hint only names one of them.+ await act(async () => {+ rerender([assistantWithHints([{ text: "again" }])]);+ });+ await waitFor(() => {+ expect(view.result.current.queuedMessages).toEqual([]);+ });++ expect(renderedUserRows(getMessages()).map((row) => row.text)).toEqual([+ "again",+ "again",+ ]);+ });++ it("still promotes a count-only drain that follows a text-bearing one", async () => {+ // Mixed hints reach one transcript across a rolling backend deploy. The+ // earlier hint's text is drawn by the split, but the later count-only+ // drain has no text on it, so its chip must still become a bubble —+ // the queue entry is dropped either way.+ function mixedHints(): Messages[number] {+ const parts: Messages[number]["parts"] = [+ { type: "text", text: "working…", state: "done" },+ {+ type: "data-pending-drained",+ id: "hint-text",+ data: {+ drainedCount: 1,+ messages: [{ id: "pm-0", content: "earlier follow up" }],+ },+ } as Messages[number]["parts"][number],+ {+ type: "data-pending-drained",+ id: "hint-count-only",+ data: { drainedCount: 1 },+ } as Messages[number]["parts"][number],+ ];+ return { id: ASSISTANT_ID, role: "assistant", parts };+ }++ const { view, getMessages, rerender } = setupHook([assistantMessage(0)]);++ act(() => {+ view.result.current.queueMessage("later follow up");+ });++ await act(async () => {+ rerender([mixedHints()]);+ });++ await waitFor(() => {+ expect(mockGetPending).toHaveBeenCalledWith("s1");+ expect(view.result.current.queuedMessages).toEqual([]);+ });++ const promoted = getMessages().find((m) =>+ m.id.startsWith("promoted-midturn-pending-chip-"),+ );+ expect(promoted?.role).toBe("user");+ });+it("does not promote when the backend buffer count still covers the local chips", async () => {mockGetPending.mockResolvedValue({status: 200,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.tsindex 54fa1ed058..f83fd2947a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { makePromotedUserBubble } from "./helpers/makePromotedBubble";import { v4 as uuidv4 } from "uuid";+import { PENDING_DRAINED_PART_TYPE } from "./messageParts";// Backstop only. Promotion is normally driven instantly by the backend's// ``data-pending-drained`` SSE hint (see ``useMidTurnDrainPromotion``); this@@ -445,7 +446,7 @@ function countPendingDrainedHints(messages: UIMessage[]): number {let count = 0;for (const message of messages) {for (const part of message.parts) {- if (part.type === "data-pending-drained") count++;+ if (part.type === PENDING_DRAINED_PART_TYPE) count++;}}return count;@@ -477,21 +478,22 @@ async function pollBackendAndPromote(const drained = snapshotQueue.slice(0, drainedCount);const drainedIds = new Set(drained.map((entry) => entry.id));- // Splice the promoted bubble at ``len-1`` so the trailing streaming- // assistant stays at ``messages[-1]``. AI SDK's ``useChat`` streams- // every SSE text/tool delta into the last message; pushing the user- // bubble onto the tail makes ``[-1]`` the user bubble and every- // subsequent chunk lands in the wrong slot (silently) until a page- // refresh. Inserting before the assistant keeps the stream flowing.+ // Every drained chip becomes a fallback bubble, whether or not the+ // ``data-pending-drained`` hint carried its text. A backend that ships the+ // text lets the transcript draw the bubble at the drain point instead+ // (``splitMessagesAtDrainHints``), and the render-time split then drops+ // the fallback row it matches — so deciding here from the transcript's+ // hints is unnecessary, and unsafe: the poll cannot tell which hint was+ // this drain's, so an earlier drain's text would suppress a later chip+ // with the same words (count-only hint, dropped hint) and lose its bubble.//- // The one tradeoff: during streaming the promoted bubbles cluster- // just above the current streaming assistant — which is earlier in- // the chronological order than the DB-canonical spot (between the- // tool result they rode in on and the continuing assistant). AI SDK's- // single-message-per-turn model can't represent that mid-turn split- // client-side. ``useHydrateOnStreamEnd`` replaces the in-memory- // messages with the DB-canonical order once the stream ends, so the- // bubbles snap to the correct position.+ // Why not simply append the bubble? ``useChat`` streams every SSE delta+ // into ``messages[-1]``; pushing the user bubble onto the tail makes+ // ``[-1]`` the user bubble and every subsequent chunk lands in the wrong+ // slot (silently) until a page refresh. Inserting before the assistant+ // 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) =>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex 51111752c8..b3842371ff 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -32,6 +32,7 @@ import {hasVisibleAssistantContent,isEngineSwitchPart,} from "./helpers";+import { asMidTurnFallbackRow } from "./components/ChatMessagesContainer/midTurnSplit";import { extractDbSequence } from "./helpers/convertChatSessionToUiMessages";import { getLatestAssistantStatusMessage } from "./messageParts";import {@@ -433,18 +434,31 @@ export function useCopilotStream({// at the last user message: a turn the backend started on its own// (engine-switch continuation) has no user row in front of it, so a// user-anchored cut would also delete the completed answer above it- // — content the resume never replays. Never cut past the last user- // message either, so the prompt itself always survives.+ // — content the resume never replays. The turn's own opening prompt+ // is kept (the replay does not re-emit it); every assistant row after+ // it goes, and the cut does not stop at a user row the backend drained+ // into the middle of the turn — leaving the pre-drain chain above it+ // would show that chain twice. The drained row itself is kept, as a+ // fallback bubble above the replayed assistant: the pending buffer it+ // came from is empty, and a replay whose hint carries no text (older+ // backend) cannot redraw it. When the hint does carry the text, the+ // transcript draws the bubble at the drain point and drops the+ // matching fallback row (`splitMessagesAtDrainHints`).const lastUserIndex = prev.findLastIndex((m) => m.role === "user");const userCut = lastUserIndex === -1 ? -1 : lastUserIndex + 1;const activeTurnIndex = activeTurnStartMessageId? prev.findIndex((m) => m.id === activeTurnStartMessageId): -1;const cutIndex =- activeTurnIndex === -1 ? userCut : Math.max(activeTurnIndex, userCut);+ activeTurnIndex === -1+ ? userCut+ : activeTurnIndex + (prev[activeTurnIndex].role === "user" ? 1 : 0);const tail = cutIndex === -1 ? [] : prev.slice(cutIndex);if (tail.length > 0 && tail.every((m) => extractDbSequence(m) !== null)) {- return prev.slice(0, cutIndex);+ const drainedFollowUps = tail+ .filter((m) => m.role === "user")+ .map(asMidTurnFallbackRow);+ return [...prev.slice(0, cutIndex), ...drainedFollowUps];}const last = prev[prev.length - 1];return hasInProgressAssistantParts(last) ? prev.slice(0, -1) : prev;