Skip to content

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): make Copilot error retries start a new turn (#15166)

Toran Bruce Richards8cd8fc2dcca8
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
index de17987256..c6f1486468 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx
@@ -5,15 +5,20 @@ import {
import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";
import { server } from "@/mocks/mock-server";
import {
+ assistantTextChunks,
copilotStreamErrorHandler,
copilotStreamHandler,
+ streamSseResponse,
} from "@/tests/integrations/copilot-sse";
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { UIMessageChunk } from "ai";
import { http, HttpResponse } from "msw";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { resetCopilotChatRegistry } from "../copilotChatRegistry";
+import {
+ getOrCreateCopilotChatRuntime,
+ resetCopilotChatRegistry,
+} from "../copilotChatRegistry";
import { useCopilotStreamStore } from "../copilotStreamStore";
import { getKickoffStatus, kickoffStorageKey } from "../expertKickoff";
import { useCopilotUIStore } from "../store";
@@ -80,6 +85,69 @@ afterEach(() => {
});
describe("Otto streaming — error paths", () => {
+ it.each(["ready", "error"] as const)(
+ "retries an empty response with a fresh stream when status is %s",
+ async (status) => {
+ const errorText = "The model returned an empty response.";
+ const failureChunks = assistantTextChunks(
+ `[__COPILOT_RETRYABLE_ERROR_a9c2__] ${errorText}`,
+ { messageId: "failed-response" },
+ );
+ if (status === "error") {
+ failureChunks.splice(-1, 1, { type: "error", errorText });
+ }
+ const requests: unknown[] = [];
+ const queueRequest = vi.fn(() =>
+ HttpResponse.json(
+ {
+ detail:
+ "Session has no active turn. Start a new turn with POST /stream.",
+ },
+ { status: 409 },
+ ),
+ );
+ server.use(
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/stream`,
+ async ({ request }) => {
+ requests.push(await request.json());
+ return streamSseResponse(
+ requests.length === 1
+ ? failureChunks
+ : assistantTextChunks("Retry succeeded.", {
+ messageId: "retried-response",
+ }),
+ { abortSignal: request.signal },
+ );
+ },
+ ),
+ http.post(
+ `${TEST_BACKEND_BASE_URL}/api/chat/sessions/${TEST_SESSION_ID}/messages/pending`,
+ queueRequest,
+ ),
+ );
+
+ renderHost();
+ await typeAndSend("Please try this task");
+ await screen.findByText(errorText);
+ await waitFor(() =>
+ expect(getOrCreateCopilotChatRuntime(TEST_SESSION_ID).chat.status).toBe(
+ status,
+ ),
+ );
+
+ await userEvent
+ .setup()
+ .click(screen.getByRole("button", { name: /try again/i }));
+
+ await waitFor(() => expect(requests).toHaveLength(2));
+ expect(requests[1]).toMatchObject({ message: "Please try this task" });
+ expect(await screen.findByText("Retry succeeded.")).toBeDefined();
+ expect(queueRequest).not.toHaveBeenCalled();
+ },
+ 15_000,
+ );
+
it("surfaces an SSE error chunk to the user", async () => {
const chunks: UIMessageChunk[] = [
{ type: "start", messageId: "msg-1" },
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx
index 9bad373572..90fb9315a9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx
@@ -155,7 +155,6 @@ vi.mock("../components/ChatMessagesContainer/helpers", () => ({
getLatestCompactionPhase: () => null,
getTurnMessages: () => [],
isChainableToolPart: () => false,
- parseSpecialMarkers: () => ({ markerType: null }),
}));
vi.mock("../components/JobStatsBar/TurnStatsBar", () => ({
TurnStatsBar: () => null,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/followup-after-local-stream.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/followup-after-local-stream.test.tsx
index df6f779852..1c428b0560 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/followup-after-local-stream.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/followup-after-local-stream.test.tsx
@@ -151,6 +151,7 @@ vi.mock("../helpers/queueFollowUpMessage", () => ({ queueFollowUpMessage }));
import { useCopilotUIStore } from "../store";
import { useCopilotPage } from "../useCopilotPage";
+import * as copilotHelpers from "../helpers";
function noActiveTurn() {
const error = new Error("Session has no active turn to queue against.");
@@ -177,10 +178,74 @@ beforeEach(() => {
afterEach(() => {
vi.clearAllMocks();
+ vi.restoreAllMocks();
window.sessionStorage.clear();
});
describe("useCopilotPage — follow-up refused by the backend mid-stream", () => {
+ it.each(["ready", "error"] as const)(
+ "starts a new turn directly after the stream settles with status %s",
+ async (status) => {
+ const { result, rerender } = renderHook(() => useCopilotPage());
+
+ streamState.status = status;
+ rerender();
+ await result.current.onSend("Retry the failed request");
+
+ expect(queueFollowUpMessage).not.toHaveBeenCalled();
+ expect(sendNewMessage).toHaveBeenCalledWith(
+ "Retry the failed request",
+ undefined,
+ undefined,
+ undefined,
+ );
+ },
+ );
+
+ it.each(["ready", "error"] as const)(
+ "starts a new turn after a real pending-message 409 and local status %s",
+ async (status) => {
+ const actualQueue = await vi.importActual<
+ typeof import("../helpers/queueFollowUpMessage")
+ >("../helpers/queueFollowUpMessage");
+ queueFollowUpMessage.mockImplementation(actualQueue.queueFollowUpMessage);
+ vi.spyOn(copilotHelpers, "getCopilotAuthHeaders").mockResolvedValue({});
+ const fetchMock = vi.spyOn(global, "fetch").mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ detail:
+ "Session has no active turn. Start a new turn with POST /stream.",
+ }),
+ { status: 409 },
+ ),
+ );
+ const { result, rerender } = renderHook(() => useCopilotPage());
+
+ const send = result.current.onSend("Retry the failed request");
+ await flush();
+ expect(fetchMock).toHaveBeenCalledWith(
+ expect.stringContaining(
+ "/api/chat/sessions/session-1/messages/pending",
+ ),
+ expect.objectContaining({ method: "POST" }),
+ );
+ expect(sendNewMessage).not.toHaveBeenCalled();
+
+ streamState.status = status;
+ rerender();
+ await send;
+
+ expect(sendNewMessage).toHaveBeenCalledWith(
+ "Retry the failed request",
+ undefined,
+ undefined,
+ undefined,
+ );
+ expect(queueMessage).not.toHaveBeenCalled();
+ expect(toast).not.toHaveBeenCalled();
+ },
+ );
+
it("holds the follow-up until this tab's stream has settled", async () => {
const { result, rerender } = renderHook(() => useCopilotPage());
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
index c217df7548..823da724cb 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
@@ -227,6 +227,80 @@ describe("shouldSuppressDuplicateSend", () => {
});
describe("getSendSuppressionReason", () => {
+ const failedMessages = [
+ makeMsg("user", "hello"),
+ makeMsg(
+ "assistant",
+ "[__COPILOT_RETRYABLE_ERROR_a9c2__] The model returned an empty response.",
+ ),
+ ];
+
+ it.each(["ready", "error"] as const)(
+ "allows retrying a failed turn when status is %s",
+ (status) => {
+ expect(
+ getSendSuppressionReason({
+ text: "hello",
+ isReconnectScheduled: false,
+ lastSubmittedText: "hello",
+ messages: failedMessages,
+ status,
+ }),
+ ).toBeNull();
+ },
+ );
+
+ it("allows resending after an SDK error without a persisted marker", () => {
+ expect(
+ getSendSuppressionReason({
+ text: "hello",
+ isReconnectScheduled: false,
+ lastSubmittedText: "hello",
+ messages: [makeMsg("user", "hello")],
+ status: "error",
+ }),
+ ).toBeNull();
+ });
+
+ it.each(["streaming", "submitted"] as const)(
+ "still suppresses duplicates while status is %s",
+ (status) => {
+ expect(
+ getSendSuppressionReason({
+ text: "hello",
+ isReconnectScheduled: false,
+ lastSubmittedText: "hello",
+ messages: failedMessages,
+ status,
+ }),
+ ).toBe("duplicate");
+ },
+ );
+
+ it("still suppresses a retry during reconnect", () => {
+ expect(
+ getSendSuppressionReason({
+ text: "hello",
+ isReconnectScheduled: true,
+ lastSubmittedText: "hello",
+ messages: failedMessages,
+ status: "error",
+ }),
+ ).toBe("reconnecting");
+ });
+
+ it("does not treat an earlier turn's error marker as a failed current turn", () => {
+ expect(
+ getSendSuppressionReason({
+ text: "hello",
+ isReconnectScheduled: false,
+ lastSubmittedText: "hello",
+ messages: [...failedMessages, makeMsg("user", "hello")],
+ status: "ready",
+ }),
+ ).toBe("duplicate");
+ });
+
it("returns 'reconnecting' when reconnect is scheduled", () => {
expect(
getSendSuppressionReason({
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
index 1ec82e9f52..a93fc6b1c2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
@@ -5,6 +5,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/atoms/Tooltip/BaseTooltip";
+import { toast } from "@/components/molecules/Toast/use-toast";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { UIDataTypes, UIMessage, UITools } from "ai";
import { LayoutGroup, motion } from "framer-motion";
@@ -42,6 +43,7 @@ import { breakdownCacheKey } from "../../tokenDevtool/tokenMath";
import type { SentFrom } from "../../sentFrom";
import type { AutopilotMode } from "../../autopilotModeStore";
import { AutopilotModeSelector } from "../ChatInput/components/AutopilotModeSelector/AutopilotModeSelector";
+import { describeSendFailure } from "../ChatInput/helpers";
import { isHeldCallRow } from "../ChatMessagesContainer/heldCallRows";
import {
getKickoffAttemptToken,
@@ -270,42 +272,58 @@ export const ChatContainer = ({
}
// Retry: re-send the last user message (used by ErrorCard on transient errors).
- const handleRetry = useCallback(() => {
- const lastRow = [...messages].reverse().find((m) => m.role === "user");
- // A turn an answered card started failed after the call ran: resuming it
- // must not re-send the request that led to the call.
- if (lastRow && isHeldCallRow(lastRow)) {
- guardedOnSend(CONTINUE_AFTER_HELD_CALL);
- return;
- }
- const lastUserMsg = lastRow;
- const lastText = lastUserMsg?.parts
- .filter(
- (p): p is Extract<typeof p, { type: "text" }> => p.type === "text",
- )
- .map((p) => p.text)
- .join("");
- if (lastText) {
- const kickoffExpertId = lastUserMsg
- ? getKickoffExpertId(lastUserMsg)
- : null;
- const kickoffAttemptToken = lastUserMsg
- ? getKickoffAttemptToken(lastUserMsg)
- : null;
- guardedOnSend(
- kickoffExpertId ? stripLegacyKickoffMarker(lastText) : lastText,
- undefined,
- undefined,
- kickoffExpertId
- ? {
- kind: "expert_kickoff",
- expertId: kickoffExpertId,
- ...(kickoffAttemptToken
- ? { attemptToken: kickoffAttemptToken }
- : {}),
- }
- : undefined,
- );
+ const isRetryingRef = useRef(false);
+ const handleRetry = useCallback(async () => {
+ if (isRetryingRef.current) return;
+ isRetryingRef.current = true;
+ try {
+ const lastRow = [...messages].reverse().find((m) => m.role === "user");
+ // A turn an answered card started failed after the call ran: resuming it
+ // must not re-send the request that led to the call.
+ if (lastRow && isHeldCallRow(lastRow)) {
+ await guardedOnSend(CONTINUE_AFTER_HELD_CALL);
+ return;
+ }
+ const lastUserMsg = lastRow;
+ const lastText = lastUserMsg?.parts
+ .filter(
+ (p): p is Extract<typeof p, { type: "text" }> => p.type === "text",
+ )
+ .map((p) => p.text)
+ .join("");
+ if (lastText) {
+ const kickoffExpertId = lastUserMsg
+ ? getKickoffExpertId(lastUserMsg)
+ : null;
+ const kickoffAttemptToken = lastUserMsg
+ ? getKickoffAttemptToken(lastUserMsg)
+ : null;
+ await guardedOnSend(
+ kickoffExpertId ? stripLegacyKickoffMarker(lastText) : lastText,
+ undefined,
+ undefined,
+ kickoffExpertId
+ ? {
+ kind: "expert_kickoff",
+ expertId: kickoffExpertId,
+ ...(kickoffAttemptToken
+ ? { attemptToken: kickoffAttemptToken }
+ : {}),
+ }
+ : undefined,
+ );
+ }
+ } catch (error) {
+ toast({
+ title: "Couldn't retry message",
+ description: describeSendFailure(
+ error,
+ "your previous message is still in the chat",
+ ),
+ variant: "destructive",
+ });
+ } finally {
+ isRetryingRef.current = false;
}
}, [guardedOnSend, messages]);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx
index 49014c073e..e0faac4248 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx
@@ -16,6 +16,12 @@ import { useCopilotUIStore } from "../../../store";
const mockIsUsageLimitReached = vi.fn();
const clipboardWrite = vi.fn(async (_text: string) => {});
+const toast = vi.hoisted(() => vi.fn());
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast,
+ useToast: () => ({ toast, dismiss: vi.fn() }),
+}));
const ARTIFACT_A_ID = "11111111-0000-0000-0000-000000000000";
const ARTIFACT_B_ID = "22222222-0000-0000-0000-000000000000";
@@ -328,6 +334,118 @@ describe("ChatContainer", () => {
expect(onSend.mock.calls[0][0]).toBe("Continue from where you left off.");
});
+ it.each([false, true])(
+ "shows an error when retrying fails (held call: %s)",
+ async (isHeldCall) => {
+ const failure = Promise.reject(new Error("Could not reach the server"));
+ void failure.catch(() => undefined);
+ const onSend = vi.fn((_message: string) => failure);
+ render(
+ <ChatContainer
+ {...baseProps}
+ error={new Error("The model returned an empty response.")}
+ onSend={onSend}
+ messages={[
+ {
+ id: "failed-request",
+ role: "user",
+ parts: [{ type: "text", text: "Try this request" }],
+ ...(isHeldCall
+ ? { metadata: { held_call: { review_id: "r1" } } }
+ : {}),
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Retry message" }));
+
+ await waitFor(() =>
+ expect(toast).toHaveBeenCalledWith({
+ title: "Couldn't retry message",
+ description:
+ "Could not reach the server — your previous message is still in the chat.",
+ variant: "destructive",
+ }),
+ );
+ expect(toast).toHaveBeenCalledTimes(1);
+ expect(onSend).toHaveBeenCalledTimes(1);
+ expect(onSend.mock.calls[0][0]).toBe(
+ isHeldCall ? "Continue from where you left off." : "Try this request",
+ );
+ },
+ );
+
+ it("shows an error when retrying throws before dispatch", async () => {
+ const onSend = vi.fn(() => {
+ throw new Error("Could not start the request");
+ });
+ render(
+ <ChatContainer
+ {...baseProps}
+ onSend={onSend}
+ messages={[
+ {
+ id: "failed-request",
+ role: "user",
+ parts: [{ type: "text", text: "Try this request" }],
+ },
+ ]}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Retry message" }));
+
+ await waitFor(() =>
+ expect(toast).toHaveBeenCalledWith({
+ title: "Couldn't retry message",
+ description:
+ "Could not start the request — your previous message is still in the chat.",
+ variant: "destructive",
+ }),
+ );
+ expect(toast).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores repeated retry clicks until the attempt settles and allows retrying again after failure", async () => {
+ let rejectSend: (error: Error) => void = () => {};
+ const pendingSend = new Promise<void>((_resolve, reject) => {
+ rejectSend = reject;
+ });
+ const onSend = vi
+ .fn()
+ .mockReturnValueOnce(pendingSend)
+ .mockResolvedValue(undefined);
+ render(
+ <ChatContainer
+ {...baseProps}
+ error={new Error("The model returned an empty response.")}
+ onSend={onSend}
+ messages={[
+ {
+ id: "failed-request",
+ role: "user",
+ parts: [{ type: "text", text: "Try this request" }],
+ },
+ ]}
+ />,
+ );
+ const retryButton = screen.getByRole("button", { name: "Retry message" });
+
+ fireEvent.click(retryButton);
+ fireEvent.click(retryButton);
+
+ expect(onSend).toHaveBeenCalledTimes(1);
+
+ await act(async () => rejectSend(new Error("Could not reach the server")));
+ await waitFor(() => expect(toast).toHaveBeenCalledTimes(1));
+
+ fireEvent.click(retryButton);
+
+ expect(onSend).toHaveBeenCalledTimes(2);
+ expect(onSend.mock.calls[1][0]).toBe("Try this request");
+ });
+
it("does not render the shared-chat notice for unshared chats", async () => {
render(<ChatContainer {...baseProps} />);
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.tsx
index 475b3ab6d3..7a1825f02a 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
@@ -1,3 +1,4 @@
+import { parseSpecialMarkers } from "../../helpers/messageMarkers";
import { CredentialMentionText } from "../CredentialMention/CredentialMentionText";
import { cn } from "@/lib/utils";
import { useMemo, useState } from "react";
@@ -29,7 +30,6 @@ import {
getLastCompactionCallId,
getLatestCompactionPhase,
getLatestCompactionStats,
- parseSpecialMarkers,
} from "./helpers";
import {
isMidTurnSegmentRow,
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.tsx
index 57410623b5..f7f16fcedb 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
@@ -142,6 +142,9 @@ vi.mock("../helpers", async (importOriginal) => ({
getLatestCompactionPhase: () => null,
getTurnMessages: () => [],
isChainableToolPart: () => false,
+}));
+
+vi.mock("../../../helpers/messageMarkers", () => ({
parseSpecialMarkers: (text: string) => {
if (typeof text === "string" && text.startsWith("[__COPILOT_ERROR_")) {
return { markerType: "error" };
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
index 41b35e2f1f..847700006a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
@@ -1,3 +1,4 @@
+import { parseSpecialMarkers } from "../../../helpers/messageMarkers";
import { describe, expect, it } from "vitest";
import {
WORKSPACE_FILE_PATTERN,
@@ -8,7 +9,6 @@ import {
getLatestCompactionStats,
getMessageArtifacts,
getMostRecentArtifact,
- parseSpecialMarkers,
resolveWorkspaceUrls,
} from "../helpers";
import type { MessagePart } from "../helpers";
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
index 5d286d87f3..4068a9f6bd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
@@ -1,3 +1,4 @@
+import { parseSpecialMarkers } from "../../../helpers/messageMarkers";
import { CredentialMentionMarkdown } from "../../CredentialMention/CredentialMentionMarkdown";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
import { StoppedTaskCard } from "./StoppedTaskCard";
@@ -35,7 +36,6 @@ import { COMPACTION_PART_TYPE } from "../../ToolChain/helpers";
import {
extractWorkspaceArtifacts,
isRetiredCompactionRow,
- parseSpecialMarkers,
resolveWorkspaceUrls,
} from "../helpers";
import { ReasoningCollapse } from "./ReasoningCollapse";
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts
index 2a69e8a302..4c586a33fb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts
@@ -153,70 +153,11 @@ export function getTurnMessages(
return messages.slice(start, end);
}
-// Special message prefixes for text-based markers (set by backend).
-// The hex suffix makes it virtually impossible for an LLM to accidentally
-// produce these strings in normal conversation.
-const COPILOT_ERROR_PREFIX = "[__COPILOT_ERROR_f7a1__]";
-const COPILOT_RETRYABLE_ERROR_PREFIX = "[__COPILOT_RETRYABLE_ERROR_a9c2__]";
-const COPILOT_SYSTEM_PREFIX = "[__COPILOT_SYSTEM_e3b0__]";
-
-export type MarkerType = "error" | "retryable_error" | "system" | null;
-
/** Escape all regex special characters in a string. */
function escapeRegExp(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
-// Pre-compiled marker regexes (avoids re-creating on every call / render).
-// Retryable check must come first since it's more specific.
-const RETRYABLE_ERROR_MARKER_RE = new RegExp(
- `${escapeRegExp(COPILOT_RETRYABLE_ERROR_PREFIX)}\\s*(.+?)$`,
- "s",
-);
-const ERROR_MARKER_RE = new RegExp(
- `${escapeRegExp(COPILOT_ERROR_PREFIX)}\\s*(.+?)$`,
- "s",
-);
-const SYSTEM_MARKER_RE = new RegExp(
- `${escapeRegExp(COPILOT_SYSTEM_PREFIX)}\\s*(.+?)$`,
- "s",
-);
-
-export function parseSpecialMarkers(text: string): {
- markerType: MarkerType;
- markerText: string;
- cleanText: string;
-} {
- const retryableMatch = text.match(RETRYABLE_ERROR_MARKER_RE);
- if (retryableMatch) {
- return {
- markerType: "retryable_error",
- markerText: retryableMatch[1].trim(),
- cleanText: text.replace(retryableMatch[0], "").trim(),
- };
- }
-
- const errorMatch = text.match(ERROR_MARKER_RE);
- if (errorMatch) {
- return {
- markerType: "error",
- markerText: errorMatch[1].trim(),
- cleanText: text.replace(errorMatch[0], "").trim(),
- };
- }
-
- const systemMatch = text.match(SYSTEM_MARKER_RE);
- if (systemMatch) {
- return {
- markerType: "system",
- markerText: systemMatch[1].trim(),
- cleanText: text.replace(systemMatch[0], "").trim(),
- };
- }
-
- return { markerType: null, markerText: "", cleanText: text };
-}
-
export function filePartToArtifactRef(
file: FileUIPart,
origin: ArtifactRef["origin"] = "user-upload",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
index c192d121b0..f28aafe538 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
@@ -1,9 +1,10 @@
import { getSystemHeaders } from "@/lib/impersonation";
import { getWebSocketToken } from "@/lib/auth/actions";
-import type { UIMessage } from "ai";
+import type { ChatStatus, UIMessage } from "ai";
import { deleteV2DisconnectSessionStream } from "@/app/api/__generated__/endpoints/chat/chat";
import { TOOL_PART_PREFIX } from "./components/JobStatsBar/constants";
+import { parseSpecialMarkers } from "./helpers/messageMarkers";
export const ORIGINAL_TITLE = "AutoGPT";
@@ -229,6 +230,7 @@ interface SuppressDuplicateArgs {
isReconnectScheduled: boolean;
lastSubmittedText: string | null;
messages: UIMessage[];
+ status?: ChatStatus;
}
/**
@@ -253,9 +255,21 @@ export function getSendSuppressionReason({
isReconnectScheduled,
lastSubmittedText,
messages,
+ status,
}: SuppressDuplicateArgs): SuppressReason {
if (isReconnectScheduled) return "reconnecting";
+ const lastMessage = messages.at(-1);
+ const hasRetryableError =
+ status === "ready" &&
+ lastMessage?.role === "assistant" &&
+ lastMessage.parts.some(
+ (part) =>
+ part.type === "text" &&
+ parseSpecialMarkers(part.text).markerType === "retryable_error",
+ );
+ if (status === "error" || hasRetryableError) return null;
+
if (text && lastSubmittedText === text) {
const lastUserMsg = messages.filter((m) => m.role === "user").pop();
const lastUserText = lastUserMsg?.parts
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/messageMarkers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/messageMarkers.ts
new file mode 100644
index 0000000000..c6d31fa7be
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/messageMarkers.ts
@@ -0,0 +1,63 @@
+// Special message prefixes for text-based markers (set by backend).
+// The hex suffix makes it virtually impossible for an LLM to accidentally
+// produce these strings in normal conversation.
+const COPILOT_ERROR_PREFIX = "[__COPILOT_ERROR_f7a1__]";
+const COPILOT_RETRYABLE_ERROR_PREFIX = "[__COPILOT_RETRYABLE_ERROR_a9c2__]";
+const COPILOT_SYSTEM_PREFIX = "[__COPILOT_SYSTEM_e3b0__]";
+
+export type MarkerType = "error" | "retryable_error" | "system" | null;
+
+/** Escape all regex special characters in a string. */
+function escapeRegExp(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+// Pre-compiled marker regexes (avoids re-creating on every call / render).
+// Retryable check must come first since it's more specific.
+const RETRYABLE_ERROR_MARKER_RE = new RegExp(
+ `${escapeRegExp(COPILOT_RETRYABLE_ERROR_PREFIX)}\\s*(.+?)$`,
+ "s",
+);
+const ERROR_MARKER_RE = new RegExp(
+ `${escapeRegExp(COPILOT_ERROR_PREFIX)}\\s*(.+?)$`,
+ "s",
+);
+const SYSTEM_MARKER_RE = new RegExp(
+ `${escapeRegExp(COPILOT_SYSTEM_PREFIX)}\\s*(.+?)$`,
+ "s",
+);
+
+export function parseSpecialMarkers(text: string): {
+ markerType: MarkerType;
+ markerText: string;
+ cleanText: string;
+} {
+ const retryableMatch = text.match(RETRYABLE_ERROR_MARKER_RE);
+ if (retryableMatch) {
+ return {
+ markerType: "retryable_error",
+ markerText: retryableMatch[1].trim(),
+ cleanText: text.replace(retryableMatch[0], "").trim(),
+ };
+ }
+
+ const errorMatch = text.match(ERROR_MARKER_RE);
+ if (errorMatch) {
+ return {
+ markerType: "error",
+ markerText: errorMatch[1].trim(),
+ cleanText: text.replace(errorMatch[0], "").trim(),
+ };
+ }
+
+ const systemMatch = text.match(SYSTEM_MARKER_RE);
+ if (systemMatch) {
+ return {
+ markerType: "system",
+ markerText: systemMatch[1].trim(),
+ cleanText: text.replace(systemMatch[0], "").trim(),
+ };
+ }
+
+ return { markerType: null, markerText: "", cleanText: text };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
index d778bc81aa..6cf88b713c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts
@@ -519,7 +519,8 @@ export function useCopilotStream({
text,
isReconnectScheduled: reconnectScheduledRef.current,
lastSubmittedText: coord?.lastSubmittedMessageText ?? null,
- messages: rawMessages,
+ messages: chatRuntime?.chat.messages ?? rawMessages,
+ status: chatRuntime?.chat.status ?? status,
});
if (suppressReason === "reconnecting") {
@@ -726,9 +727,8 @@ export function useCopilotStream({
// `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 (the "duplicate" branch
- // checks both the store and the visible last user message, so legitimate
- // re-sends after a different reply are still allowed).
+ // message immediately after a successful turn. Failed turns are exempt
+ // from duplicate suppression so the error card can retry the same text.
const prevStatusRef = useRef(status);
useEffect(() => {
const prev = prevStatusRef.current;