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(platform/copilot): send the same message again once the last one was answered, stopped or failed (#15918)
Reinier van der Leerd43e4d7a647b
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex f100225b5c..702ec22c61 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -2107,6 +2107,9 @@ async def stream_chat_post(user_id=user_id,message=message,message_id=message_id,+ # The id already stops a retransmit; matching on text as well would+ # drop a resend after a turn stopped before it wrote a reply.+ dedupe_content=client_message_id is None,message_metadata=message_metadata,message_already_persisted=resume_persisted_kickoff,is_user_message=request.is_user_message,diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex c56bca23e1..1daaf1728d 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -686,6 +686,28 @@ def test_stream_chat_skips_enqueue_for_duplicate_message(mocks.enqueue.assert_called_once()+ ("body", "dedupe_content"),+ [+ # A turn stopped before it streamed leaves "yes" as the last row; the+ # resend carries a fresh id and must not be collapsed into it.+ ({"message": "yes", "message_id": "client-send-2"}, False),+ ({"message": "yes"}, True),+ ],+)+def test_stream_chat_collapses_same_text_only_without_a_client_id(+ mocker: pytest_mock.MockerFixture,+ body: dict[str, str],+ dedupe_content: bool,+):+ mocks = _mock_stream_internals(mocker)++ response = client.post("/sessions/sess-1/stream", json=body)++ assert response.status_code == 200+ assert mocks.enqueue.await_args.kwargs["dedupe_content"] is dedupe_content++def test_stream_chat_canonicalizes_expert_kickoff(mocker: pytest_mock.MockerFixture,test_user_id: str,diff --git a/autogpt_platform/backend/backend/copilot/executor/utils.py b/autogpt_platform/backend/backend/copilot/executor/utils.pyindex 73353659fe..2f076b22ec 100644--- a/autogpt_platform/backend/backend/copilot/executor/utils.py+++ b/autogpt_platform/backend/backend/copilot/executor/utils.py@@ -931,9 +931,13 @@ async def schedule_chat_turn(content=message,metadata=message_metadata,)+ # A refreshed slot means a turn already runs for this chat, so the+ # same text again is a double send, whatever id it carries.is_duplicate = (await append_and_save_message(- session_id, chat_message, dedupe_content=dedupe_content+ session_id,+ chat_message,+ dedupe_content=dedupe_content or not slot.admitted,)) is Noneif not is_duplicate and is_user_message:diff --git a/autogpt_platform/backend/backend/copilot/executor/utils_test.py b/autogpt_platform/backend/backend/copilot/executor/utils_test.pyindex 299a6ee920..5ee62b8de8 100644--- a/autogpt_platform/backend/backend/copilot/executor/utils_test.py+++ b/autogpt_platform/backend/backend/copilot/executor/utils_test.py@@ -459,6 +459,22 @@ async def test_schedule_chat_turn_passes_content_dedupe_off_to_the_save():assert append.await_args.kwargs["dedupe_content"] is False+async def test_schedule_chat_turn_dedupes_content_on_a_refreshed_slot_whatever_it_was_told():+ # Two sends of one text racing past the in-flight check: the second only+ # refreshes the first's slot, and must not start a second turn.+ with _scheduling(admitted=False) as (append, _dispatch):+ await utils.schedule_chat_turn(+ session_id="s1",+ user_id="u1",+ message="yes",+ message_id="client-send-2",+ dedupe_content=False,+ )++ assert append.await_args.kwargs["dedupe_content"] is True++class TestNarrowPermissions:"""The envelope's tool set becomes the turn's whitelist. The encoding of"no tools at all" is the trap: it is a blacklist of every tool, and adiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.tsindex 7f23b7b549..7cbbb8857f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts@@ -179,8 +179,8 @@ describe("shouldSuppressDuplicateSend", () => {).toBe(false);});- it("suppresses when text matches last submitted AND last user message", () => {- const messages = [makeMsg("user", "hello"), makeMsg("assistant", "hi")];+ it("suppresses when text matches an unanswered last user message", () => {+ const messages = [makeMsg("user", "hello")];expect(shouldSuppressDuplicateSend({text: "hello",@@ -339,23 +339,50 @@ describe("getSendSuppressionReason", () => {).toBe("reconnecting");});- it("returns 'duplicate' when text matches last submitted AND last user message", () => {- const messages = [makeMsg("user", "hello"), makeMsg("assistant", "hi")];+ it("returns 'duplicate' while the echoed send is still unanswered", () => {+ const messages = [makeMsg("user", "hello")];expect(getSendSuppressionReason({text: "hello",isReconnectScheduled: false,lastSubmittedText: "hello",messages,+ status: "ready",}),).toBe("duplicate");});- it("lets the same caption through when it carries other attachments", () => {+ it("sends the same text again once it has been answered", () => {+ const messages = [makeMsg("user", "hello"), makeMsg("assistant", "hi")];+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ status: "ready",+ }),+ ).toBeNull();+ });++ it("sends the same text again after the previous turn was stopped", () => {const messages = [- makeMsg("user", "summarize this"),- makeMsg("assistant", "ok"),+ makeMsg("user", "hello"),+ makeMsg("assistant", "[__COPILOT_ERROR_f7a1__] Operation cancelled"),];+ expect(+ getSendSuppressionReason({+ text: "hello",+ isReconnectScheduled: false,+ lastSubmittedText: "hello",+ messages,+ status: "ready",+ }),+ ).toBeNull();+ });++ it("lets the same caption through when it carries other attachments", () => {+ const messages = [makeMsg("user", "summarize this")];expect(getSendSuppressionReason({text: "summarize this",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resend-after-answer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resend-after-answer.test.tsxnew file mode 100644index 0000000000..4ef04e8e3e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/resend-after-answer.test.tsx@@ -0,0 +1,210 @@+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 { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotStreamStore } from "../copilotStreamStore";+import {+ clickStop,+ renderHost,+ resetChatRuntimes,+ TEST_BACKEND_BASE_URL,+ TEST_SESSION_ID,+ typeAndSend,+} from "./sse-helpers";++// A user who answers "yes" to one question and then "yes" to the next. The+// duplicate guard used to swallow the second send for as long as the chat+// lived, with the composer already cleared (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 ANSWERS = ["Sure, go ahead.", "Done, both booked."];++// What the backend has persisted so far: the stream-end hydrate replaces the+// live list with these rows, exactly as it does in production.+const stored = { messages: [] as SessionDetailResponseMessagesItem[] };++function sessionMessage(+ sequence: number,+ role: "user" | "assistant",+ content: string,+): SessionDetailResponseMessagesItem {+ return {+ id: `db-${sequence}`,+ role,+ content,+ tool_call_id: null,+ tool_calls: null,+ sequence,+ duration_ms: null,+ created_at: `2026-05-13T00:0${sequence}: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 },+ }),+ );+}++function answeringStreamHandler(posts: string[]) {+ return http.post(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ async ({ request }) => {+ const body = (await request.json()) as { message?: string };+ posts.push(body.message ?? "");+ const turn = posts.length;+ const answer = ANSWERS[turn - 1] ?? ANSWERS[ANSWERS.length - 1];+ stored.messages = [+ ...stored.messages,+ sessionMessage(turn * 2 - 1, "user", body.message ?? ""),+ sessionMessage(turn * 2, "assistant", answer),+ ];+ return streamSseResponse(+ assistantTextChunks(answer, {+ messageId: `answer-${turn}`,+ textPartId: `answer-${turn}-text`,+ }),+ { abortSignal: request.signal },+ );+ },+ );+}++async function waitForTurnToSettle() {+ await waitFor(+ () => expect(screen.queryByRole("button", { name: "Stop" })).toBeNull(),+ { timeout: 5000 },+ );+}++beforeEach(() => {+ resetChatRuntimes();+ stored.messages = [];+});++afterEach(() => {+ resetChatRuntimes();+ server.resetHandlers();+});++describe("sending the same text twice in a row", () => {+ it('sends "yes" again once the first "yes" has been answered', async () => {+ const posts: string[] = [];+ server.use(answeringStreamHandler(posts));+ renderHost();+ // Registered after renderHost so the stored rows win over the empty session.+ server.use(storedSessionHandler());++ await typeAndSend("yes");+ await screen.findByText(ANSWERS[0], undefined, { timeout: 5000 });+ await waitForTurnToSettle();++ await typeAndSend("yes");++ await waitFor(() => expect(posts).toEqual(["yes", "yes"]), {+ timeout: 5000,+ });+ await screen.findByText(ANSWERS[1], undefined, { timeout: 5000 });+ expect(screen.getAllByText("yes")).toHaveLength(2);+ }, 15_000);++ it("forgets a send once it is stopped, so a reload cannot drop a resend", async () => {+ // The turn has opened its stream but not started answering when Stop lands.+ const { hold } = createStreamHold(1);+ server.use(+ http.post(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ ({ request }) =>+ streamSseResponse(assistantTextChunks(ANSWERS[0]), {+ hold,+ abortSignal: request.signal,+ }),+ ),+ );+ renderHost();++ await typeAndSend("yes");+ await waitFor(() => expect(lastSubmittedText()).toBe("yes"));+ await clickStop();+ await waitForTurnToSettle();++ // A turn cancelled before it streams leaves the stored chat ending on the+ // user's row, and this memory survives a reload in sessionStorage; kept,+ // it would mark the user's resend of "yes" as a double-click and drop it.+ expect(lastSubmittedText()).toBeNull();+ }, 15_000);++ it("forgets a send whose turn failed, so a reload cannot drop a resend", async () => {+ server.use(+ http.post(+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,+ async () => {+ // Long enough to see the send remembered before the failure lands.+ await new Promise((resolve) => setTimeout(resolve, 300));+ return HttpResponse.json({ detail: "boom" }, { status: 500 });+ },+ ),+ );+ renderHost();++ await typeAndSend("yes");+ await waitFor(() => expect(lastSubmittedText()).toBe("yes"));++ await waitFor(() => expect(lastSubmittedText()).toBeNull(), {+ timeout: 5000,+ });+ }, 15_000);+});++function lastSubmittedText() {+ return useCopilotStreamStore.getState().getCoord(TEST_SESSION_ID)+ .lastSubmittedMessageText;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.tsindex 9647097579..ee7225826c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts@@ -271,8 +271,9 @@ interface SuppressDuplicateArgs {* - ``"reconnecting"``: the stream is reconnecting; the caller should* notify the user (the UI may not yet reflect the disabled state).* - ``"duplicate"``: the same text, with the same attachments, was just- * submitted and echoed back by the session — safe to silently drop- * (user double-clicked).+ * submitted, echoed back by the session and not answered yet — safe to+ * silently drop (user double-clicked), because the message is already+ * on screen.*/export type SuppressReason = "reconnecting" | "duplicate" | null;@@ -312,11 +313,18 @@ export function getSendSuppressionReason({.trim();// The same caption on other files is a new message, not a resend.const lastUserAttachments = attachmentKeys(lastUserMsg?.parts ?? []);- if (+ const isResend =lastUserText === text &&- lastUserAttachments.join("\n") === attachments.join("\n")- )- return "duplicate";+ lastUserAttachments.join("\n") === attachments.join("\n");+ // A resend is a duplicate only while the first send is still being+ // answered: the turn is in flight, or its echo is the newest message.+ // Once a reply (or a Stop marker) followed it, "yes" after "yes" is a+ // new message, and dropping it would lose text the composer already cleared.+ const stillBeingAnswered =+ status === "streaming" ||+ status === "submitted" ||+ lastMessage?.role === "user";+ if (isResend && stillBeingAnswered) return "duplicate";}return null;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex 5c42b3321a..e6cbedaf61 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -309,10 +309,14 @@ export function useCopilotStream({};const failureForThisTurn = providerFailureRef.current;providerFailureRef.current = null;+ // Resuming keeps the send in flight, and a refused send's text is kept+ // by `restoreUnsentSend` when the composer is busy.+ let keepSendMemory = false;handleStreamError({error,providerFailure: failureForThisTurn,onRateLimit: (message, limitFailure, origin) => {+ keepSendMemory = true;restoreUnsentSend();// A provider's own limit is not answered by upgrading with us, so// it opens the continue path instead of the plan dialog.@@ -341,10 +345,23 @@ export function useCopilotStream({setRateLimitMessage(limitFailure?.message || message);}},- onReconnect: () => handleReconnectRef.current(),- onPaywall: restoreUnsentSend,+ onReconnect: () => {+ keepSendMemory = true;+ handleReconnectRef.current();+ },+ onPaywall: () => {+ keepSendMemory = true;+ restoreUnsentSend();+ },isUserStoppingRef,});+ // A turn that failed before answering can leave its echo as the newest+ // row, which after a reload would make the guard drop the user's resend.+ if (!keepSendMemory) {+ useCopilotStreamStore.getState().updateCoord(sessionId, {+ lastSubmittedMessageText: null,+ });+ }if (kickoffExpertId) {releaseKickoffPending();useCopilotStreamStore.getState().updateCoord(sessionId, {@@ -664,9 +681,19 @@ export function useCopilotStream({return `${rawMessages.length}:${last?.parts.length ?? 0}:${textLen}`;}, [rawMessages]);+ const stopSdkStream = sdkStopStream(sdkStop, setMessages);const stop = useCopilotStop({sessionId,- stopStream: sdkStopStream(sdkStop, setMessages),+ stopStream: () => {+ // A turn stopped before it streams stores no marker, so after a reload+ // its echo is the newest row; the guard must not treat a resend as a double-click.+ if (sessionId) {+ useCopilotStreamStore.getState().updateCoord(sessionId, {+ lastSubmittedMessageText: null,+ });+ }+ stopSdkStream();+ },isUserStoppingRef,setIsUserStopping,});@@ -755,10 +782,10 @@ export function useCopilotStream({// Invalidate session + usage caches when the stream completes.// Reconnect counter/timer reset on the same transition is owned by// `useCopilotReconnect`, which watches `status` internally.- // `lastSubmittedMessageText` is intentionally NOT cleared here: it prevents- // `getSendSuppressionReason` from allowing a duplicate POST of the same- // message immediately after a successful turn. Failed turns are exempt- // from duplicate suppression so the error card can retry the same text.+ // `lastSubmittedMessageText` is intentionally NOT cleared here: a resume+ // may still re-POST it, and `getSendSuppressionReason` only treats a+ // resend as a duplicate while its echo is the newest message or the turn+ // is in flight, so keeping it cannot swallow a later message.const prevStatusRef = useRef(status);useEffect(() => {const prev = prevStatusRef.current;