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 message sent right after Stop on screen until its row is stored (#15931)
Reinier van der Leer352feaffb383
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/send-after-stop.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/send-after-stop.test.tsxnew file mode 100644index 0000000000..687493810b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/send-after-stop.test.tsx@@ -0,0 +1,211 @@+import type { SessionDetailResponseMessagesItem } from "@/app/api/__generated__/models/sessionDetailResponseMessagesItem";+import { server } from "@/mocks/mock-server";+import {+ assistantTextChunks,+ createStreamHold,+ streamSseResponse,+} from "@/tests/integrations/copilot-sse";+import { screen, waitFor } from "@testing-library/react";+import type { UIMessageChunk } from "ai";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { CANCELLED_MARKER } from "../useCopilotStop";+import {+ clickStop,+ renderHost,+ resetChatRuntimes,+ TEST_BACKEND_BASE_URL,+ TEST_SESSION_ID,+ typeAndSend,+} from "./sse-helpers";++// A message sent while the backend is still tearing down a stopped turn is+// queued as that turn's follow-up, and its row is written only later. The+// stream-end hydrate used to replace the chat with rows that did not have it+// yet, so the message vanished until a reload (SECRT-2843).++vi.mock("@/services/environment", async (importActual) => {+ const actual = await importActual<typeof import("@/services/environment")>();+ return {+ ...actual,+ environment: {+ ...actual.environment,+ getAGPTServerBaseUrl: () => TEST_BACKEND_BASE_URL,+ },+ };+});++vi.mock("../helpers", async (importActual) => {+ const actual = await importActual<typeof import("../helpers")>();+ return {+ ...actual,+ getCopilotAuthHeaders: async () => ({ "x-test-auth": "yes" }),+ };+});++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),+}));++vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {+ const actual =+ await importActual<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return { ...actual, useGetFlag: () => false };+});++const FIRST = "Plan my week";+const AFTER_STOP = "Just Monday, please";+const LATER = "Thanks";+const LIVE_PARTIAL = "Looking at your calendar";+// Each stored row reads differently from what was streamed, so seeing it on+// screen means a hydrate has replaced the list. The stopped partial runs+// further because the backend kept generating until the cancel landed.+const STORED_PARTIAL = "Looking at your calendar, then your inbox";+const LATER_ANSWER = "You're welcome.";+const STORED_LATER_ANSWER = "You're welcome!";++const stored = { messages: [] as SessionDetailResponseMessagesItem[] };++beforeEach(() => {+ resetChatRuntimes();+ stored.messages = [];+});++afterEach(() => {+ resetChatRuntimes();+ server.resetHandlers();+});++describe("a message sent right after Stop", () => {+ it("stays in the chat through the hydrate, and appears once when its row lands", async () => {+ const posts: string[] = [];+ const { hold } = createStreamHold(4);+ server.use(+ http.post(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ async ({ request }) => {+ const { message = "" } = (await request.json()) as {+ message?: string;+ };+ posts.push(message);+ if (message === FIRST) {+ store("user", FIRST);+ return streamSseResponse(stoppableTurnChunks(), {+ hold,+ abortSignal: request.signal,+ });+ }+ if (message === AFTER_STOP) {+ // The stopped turn finishes tearing down while this send waits.+ store("assistant", STORED_PARTIAL);+ store("assistant", CANCELLED_MARKER);+ return streamSseResponse(followUpQueuedChunks(), {+ abortSignal: request.signal,+ });+ }+ store("user", message);+ store("assistant", STORED_LATER_ANSWER);+ return streamSseResponse(+ assistantTextChunks(LATER_ANSWER, {+ messageId: "later-answer",+ textPartId: "later-answer-text",+ }),+ { abortSignal: request.signal },+ );+ },+ ),+ );+ renderHost();+ // Registered after renderHost so the stored rows win over the empty session.+ server.use(storedSessionHandler());++ await typeAndSend(FIRST);+ await screen.findByText(LIVE_PARTIAL, undefined, { timeout: 5000 });+ await clickStop();+ await waitForTurnToSettle();++ await typeAndSend(AFTER_STOP);+ await screen.findByText(STORED_PARTIAL, undefined, { timeout: 5000 });+ await waitForTurnToSettle();+ expect(screen.getAllByText(AFTER_STOP)).toHaveLength(1);++ // The queued follow-up's row is written once the stopped turn is gone.+ store("user", AFTER_STOP);+ await typeAndSend(LATER);+ await screen.findByText(STORED_LATER_ANSWER, undefined, { timeout: 5000 });+ await waitFor(() => expect(posts).toEqual([FIRST, AFTER_STOP, LATER]));+ for (const text of [FIRST, AFTER_STOP, LATER]) {+ expect(screen.getAllByText(text)).toHaveLength(1);+ }+ }, 20_000);+});++function store(role: "user" | "assistant", content: string) {+ const sequence = stored.messages.length + 1;+ stored.messages = [+ ...stored.messages,+ {+ id: `db-${sequence}`,+ role,+ content,+ tool_call_id: null,+ tool_calls: null,+ sequence,+ duration_ms: null,+ created_at: `2026-05-13T00:${String(sequence).padStart(2, "0")}:00Z`,+ metadata: null,+ },+ ];+}++function storedSessionHandler() {+ return http.get(`*/api/chat/sessions/${TEST_SESSION_ID}`, () =>+ HttpResponse.json({+ id: TEST_SESSION_ID,+ created_at: "2026-05-13T00:00:00Z",+ updated_at: "2026-05-13T00:00:00Z",+ user_id: "test-user",+ chat_status: "idle",+ messages: stored.messages,+ has_more_messages: false,+ oldest_sequence: null,+ active_stream: null,+ metadata: { dry_run: false, builder_graph_id: null },+ }),+ );+}++// Held open after the first delta, so only the Stop click ends it.+function stoppableTurnChunks(): UIMessageChunk[] {+ return [+ { type: "start", messageId: "stopped-turn" },+ { type: "start-step" },+ { type: "text-start", id: "stopped-text" },+ // The trailing space lets the smoother release the last word.+ { type: "text-delta", id: "stopped-text", delta: `${LIVE_PARTIAL} ` },+ { type: "text-end", id: "stopped-text" },+ { type: "finish-step" },+ { type: "finish" },+ ];+}++// What `stream_chat_post` answers while a turn is still in flight: the send+// went to the pending buffer, and the stream carries nothing but that fact.+function followUpQueuedChunks(): UIMessageChunk[] {+ return [+ { type: "start", messageId: "queued-follow-up" },+ { type: "start-step" },+ { type: "data-follow-up-queued", data: {} },+ { type: "finish-step" },+ { type: "finish" },+ ];+}++async function waitForTurnToSettle() {+ await waitFor(+ () => expect(screen.queryByRole("button", { name: "Stop" })).toBeNull(),+ { timeout: 5000 },+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.tsindex 485b077fe8..93cb44b9b6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts@@ -45,10 +45,13 @@ function runForceHydrate({prev,staleWindow,freshWindow,+ statuses = ["ready"],}: {prev: Messages;staleWindow: Messages;freshWindow: Messages;+ /** What the chat passes through after streaming, before the refetch lands. */+ statuses?: Parameters<typeof useHydrateOnStreamEnd>[0]["status"][];}): Messages | null {let captured: Messages | null = null;const setMessages = vi.fn(@@ -78,16 +81,18 @@ function runForceHydrate({);// Stream ends → arms force-hydrate, snapshots the stale (pre-turn) window.- rerender({- ...baseProps,- status: "ready",- hydratedMessages: staleWindow,- } satisfies Props);+ for (const status of statuses) {+ rerender({+ ...baseProps,+ status,+ hydratedMessages: staleWindow,+ } satisfies Props);+ }// React Query swaps in the fresh post-turn window → force-hydrate applies.rerender({...baseProps,- status: "ready",+ status: statuses[statuses.length - 1],hydratedMessages: freshWindow,} satisfies Props);@@ -425,3 +430,149 @@ describe("useHydrateOnStreamEnd — a turn the user stopped", () => {).toEqual(persisted);});});++describe("useHydrateOnStreamEnd — a send the backend has not written yet", () => {+ afterEach(() => {+ _resetInterruptedToastLedgerForTests();+ cleanup();+ });++ function row(+ seq: number,+ role: "user" | "assistant",+ text: string,+ ): UIMessage<unknown, UIDataTypes, UITools> {+ return {+ id: `${SESSION_ID}-seq-${seq}`,+ role,+ parts: [{ type: "text", text, state: "done" }],+ };+ }++ it('keeps a second "yes" that the earlier "yes" row does not account for', () => {+ const answered = [row(1, "user", "yes"), row(2, "assistant", "Booked.")];+ const queued: UIMessage<unknown, UIDataTypes, UITools> = {+ id: "local-send",+ role: "user",+ parts: [{ type: "text", text: "yes" }],+ };++ const result = runForceHydrate({+ prev: [...answered, queued],+ staleWindow: [row(1, "user", "yes")],+ freshWindow: answered,+ });++ expect(result).toEqual([...answered, queued]);+ });++ function local(+ id: string,+ role: "user" | "assistant",+ text: string,+ ): UIMessage<unknown, UIDataTypes, UITools> {+ return { id, role, parts: [{ type: "text", text }] };+ }++ it.each([+ {+ // A long turn pushed the prompt's row out of the latest-rows window.+ name: "a prompt whose row lies before the refetched window",+ prev: [+ row(1, "user", "Plan it"),+ row(2, "assistant", "Planned."),+ local("local-prompt", "user", "Build it"),+ local("live-answer", "assistant", "Built."),+ ],+ fresh: range(60, 70),+ expected: [+ row(1, "user", "Plan it"),+ row(2, "assistant", "Planned."),+ ...range(60, 70),+ ],+ },+ {+ name: "a first send refused before it was saved, then retried",+ prev: [+ local("refused", "user", "yes"),+ local("retried", "user", "yes"),+ local("live-answer", "assistant", "Booked."),+ ],+ // A session's first row is sequence 0.+ fresh: [row(0, "user", "yes"), row(1, "assistant", "Booked.")],+ expected: [row(0, "user", "yes"), row(1, "assistant", "Booked.")],+ },+ {+ name: "a send whose stream failed",+ prev: [row(0, "user", "Plan it"), local("refused", "user", "Build it")],+ fresh: [row(0, "user", "Plan it")],+ expected: [row(0, "user", "Plan it")],+ statuses: ["error" as const],+ },+ {+ name: "a refused send once its retry has ended cleanly",+ prev: [+ row(0, "user", "Plan it"),+ row(1, "assistant", "Planned."),+ local("refused", "user", "yes"),+ local("retried", "user", "yes"),+ local("live-answer", "assistant", "Booked."),+ ],+ fresh: [+ row(0, "user", "Plan it"),+ row(1, "assistant", "Planned."),+ row(2, "user", "yes"),+ row(3, "assistant", "Booked."),+ ],+ expected: [+ row(0, "user", "Plan it"),+ row(1, "assistant", "Planned."),+ row(2, "user", "yes"),+ row(3, "assistant", "Booked."),+ ],+ statuses: [+ "error" as const,+ "submitted" as const,+ "streaming" as const,+ "ready" as const,+ ],+ },+ ])("does not keep $name", ({ prev, fresh, expected, statuses }) => {+ expect(+ runForceHydrate({ prev, staleWindow: [], freshWindow: fresh, statuses }),+ ).toEqual(expected);+ });++ it("leaves a promoted bubble's row to it, not to a later bubble with the same text", () => {+ const promoted = local("promoted-midturn-1", "user", "yes");+ const queued = local("local-send", "user", "yes");+ const stored = [+ row(1, "user", "Book both"),+ row(2, "user", "yes"),+ row(3, "assistant", "Booked."),+ ];++ const result = runForceHydrate({+ prev: [row(1, "user", "Book both"), promoted, queued],+ staleWindow: [],+ freshWindow: stored,+ });++ expect(result).toEqual([...stored, queued]);+ });++ it("gives a promoted bubble its own later row, not an earlier one with the same text", () => {+ const answered = [row(0, "user", "yes"), row(1, "assistant", "Booked.")];+ const promoted = local("promoted-midturn-1", "user", "yes");+ const queued = local("local-send", "user", "yes");+ const stored = [...answered, row(2, "user", "yes")];++ const result = runForceHydrate({+ prev: [...answered, promoted, queued],+ staleWindow: [],+ freshWindow: stored,+ });++ expect(result).toEqual([...stored, queued]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.tsindex 37ea0de6e8..c32aa36b6e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.ts@@ -33,13 +33,8 @@ function retainOlderHistory(prev: UIMessage[],hydrated: UIMessage[],): UIMessage[] {- let oldestHydratedSeq: number | null = null;- for (const message of hydrated) {- oldestHydratedSeq = extractDbSequence(message);- if (oldestHydratedSeq !== null) break;- }- if (oldestHydratedSeq === null) return hydrated;- const windowStart = oldestHydratedSeq;+ const windowStart = firstSequence(hydrated);+ if (windowStart === null) return hydrated;const windowStartIndex = prev.findIndex((message) => {const seq = extractDbSequence(message);@@ -72,10 +67,7 @@ function preservePromotedUserBubbles(prev: UIMessage[],hydrated: UIMessage[],): UIMessage[] {- const promoted = prev.filter(- (m) =>- typeof m.id === "string" && m.id.startsWith(PROMOTED_BUBBLE_ID_PREFIX),- );+ const promoted = prev.filter(isPromotedBubble);if (promoted.length === 0) return hydrated;const hydratedUserText = hydrated@@ -93,6 +85,91 @@ function preservePromotedUserBubbles(return [...hydrated, ...orphans];}+/**+ * Keep a send the backend took but has not written yet (a follow-up queued+ * behind a stopped turn's teardown, SECRT-2843) until a user row with its text+ * lands after the row it was sent behind; each row answers for one bubble.+ * A bubble whose row may lie before the refetched window is left to it.+ */+function preserveUnpersistedUserBubbles(+ prev: UIMessage[],+ hydrated: UIMessage[],+ windowStart: number | null,+): UIMessage[] {+ // With no stored row drawn yet, nothing says which sends the backend took;+ // a first send refused before it was saved is one of them.+ if (!prev.some((message) => extractDbSequence(message) !== null))+ return hydrated;+ const bubbles = localUserBubbles(prev);+ const claimed = new Set<number>();+ // A promoted bubble's row is its own, so a later bubble with the same text+ // cannot take it.+ for (const bubble of bubbles.filter((b) => isPromotedBubble(b.message))) {+ const rowIndex = findUnclaimedUserRow(hydrated, claimed, bubble);+ if (rowIndex !== -1) claimed.add(rowIndex);+ }+ const orphans: UIMessage[] = [];+ for (const bubble of bubbles.filter((b) => !isPromotedBubble(b.message))) {+ const rowIndex = findUnclaimedUserRow(hydrated, claimed, bubble);+ if (rowIndex !== -1) claimed.add(rowIndex);+ else if (windowStart === null || bubble.sentAfter >= windowStart - 1)+ orphans.push(bubble.message);+ }+ if (orphans.length === 0) return hydrated;+ return [...hydrated, ...orphans];+}++interface LocalBubble {+ message: UIMessage;+ text: string;+ /** Sequence of the last stored row before it; -1 when there is none. */+ sentAfter: number;+}++function localUserBubbles(prev: UIMessage[]): LocalBubble[] {+ const bubbles: LocalBubble[] = [];+ let sentAfter = -1;+ for (const message of prev) {+ const seq = extractDbSequence(message);+ if (seq !== null) {+ sentAfter = seq;+ continue;+ }+ const text = message.role === "user" ? getMessageText(message) : "";+ if (text) bubbles.push({ message, text, sentAfter });+ }+ return bubbles;+}++function findUnclaimedUserRow(+ hydrated: UIMessage[],+ claimed: Set<number>,+ { text, sentAfter }: LocalBubble,+): number {+ return hydrated.findIndex(+ (row, index) =>+ !claimed.has(index) &&+ row.role === "user" &&+ (extractDbSequence(row) ?? -1) > sentAfter &&+ getMessageText(row).includes(text),+ );+}++function firstSequence(messages: UIMessage[]): number | null {+ for (const message of messages) {+ const seq = extractDbSequence(message);+ if (seq !== null) return seq;+ }+ return null;+}++function isPromotedBubble(message: UIMessage): boolean {+ return (+ typeof message.id === "string" &&+ message.id.startsWith(PROMOTED_BUBBLE_ID_PREFIX)+ );+}+/*** A stopped turn is finalised client-side — ``useCopilotStop`` appends the* cancellation marker — and the backend persists nothing for it, so a blind@@ -197,6 +274,9 @@ export function useHydrateOnStreamEnd({const prevStatusRef = useRef(status);const needsForceHydrateRef = useRef(false);const staleRefAtStreamEnd = useRef<typeof hydratedMessages | null>(null);+ // A stream that failed since the last replace may have been refused before+ // its send was saved, even when a retry ended cleanly after it.+ const streamFailedSinceReplaceRef = useRef(false);// Arm the force-hydrate flag the moment the stream transitions to idle.useEffect(() => {@@ -208,6 +288,7 @@ export function useHydrateOnStreamEnd({if (wasActive && isNowIdle) {needsForceHydrateRef.current = true;staleRefAtStreamEnd.current = hydratedMessages ?? null;+ if (status === "error") streamFailedSinceReplaceRef.current = true;}}, [status, hydratedMessages]);@@ -270,17 +351,26 @@ export function useHydrateOnStreamEnd({// session refetch — either way this effect re-fires and the replace// lands once the backend goes idle, so no timeout fallback is needed.if (hasActiveStream) return;- setMessages((prev) =>- preservePromotedUserBubbles(+ const sendsWereTaken = !streamFailedSinceReplaceRef.current;+ setMessages((prev) => {+ const replaced = preservePromotedUserBubbles(prev,preserveStoppedAssistantMessage(prev,retainOlderHistory(prev, finalized),),- ),- );+ );+ return sendsWereTaken+ ? preserveUnpersistedUserBubbles(+ prev,+ replaced,+ firstSequence(finalized),+ )+ : replaced;+ });needsForceHydrateRef.current = false;staleRefAtStreamEnd.current = null;+ streamFailedSinceReplaceRef.current = false;return;}