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): no false errors, stuck spinners or endless retries after a lost chat connection (#15398)
Reinier van der Leer514d7beb5460
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsxindex e5a575ca04..cc951d8f22 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-content.test.tsx@@ -270,7 +270,7 @@ describe.each(STREAM_PATHS)("on the %s path", (path) => {},{ timeout: 5000 },);- expect(screen.queryByText(/encountered an error/i)).toBeNull();+ expect(screen.queryByTestId("chat-error-banner")).toBeNull();});it("renders both assistant replies across two back-to-back turns in the same session", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatErrorGuidance.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatErrorGuidance.test.tsnew file mode 100644index 0000000000..570540e9ae--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatErrorGuidance.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from "vitest";++import { describeChatError } from "../chatErrorGuidance";+import { CopilotAuthError } from "../helpers";+import {+ ChatUnavailableError,+ MessageTooLongError,+ SendRefusedError,+} from "../stream/turnRuntime";++const RESEND = /send (it|your message) again|try sending/i;++describe("describeChatError", () => {+ it("a message over the length limit says to shorten it", () => {+ const guidance = describeChatError(+ new MessageTooLongError('{"detail":[…]}', 422),+ );+ expect(guidance).toEqual({+ title: "Your message is too long. Shorten it and send again.",+ action: null,+ });+ });++ it.each([+ ["no session token", new CopilotAuthError(), "sign-in"],+ [+ "a send refused 401",+ new SendRefusedError('{"detail":"Unauthorized"}', 401),+ "sign-in",+ ],+ [+ "the flag-off path's auth failure",+ new Error("Not authenticated"),+ "sign-in",+ ],+ ["a chat that is gone", new ChatUnavailableError(), "new-chat"],+ [+ "a send refused 404",+ new SendRefusedError('{"detail":"Session not found"}', 404),+ "new-chat",+ ],+ [+ "a conversation over the model's limit",+ new Error("SDK stream error: Prompt is too long"),+ "new-chat",+ ],+ ])("%s points to what works instead of a resend", (_state, error, action) => {+ const guidance = describeChatError(error);+ expect(guidance.action).toBe(action);+ expect(guidance.title).not.toMatch(RESEND);+ });++ it.each([+ [+ "a usage limit",+ new SendRefusedError('{"detail":"usage limit reached"}', 429),+ ],+ [+ "a plan refusal",+ new SendRefusedError('{"detail":"advanced_tier_not_entitled"}', 403),+ ],+ ])("%s does not promise a resend", (_state, error) => {+ const guidance = describeChatError(error);+ expect(guidance.title).not.toMatch(RESEND);+ expect(guidance.action).toBeNull();+ });++ const REFUSED =+ "The request was refused. Reload the page and try again; if it keeps happening, contact support.";+ const NOTIFIED = "The system maintainer has been notified of the issue";++ it.each([+ [+ "a 403",+ new SendRefusedError('{"detail":"advanced_tier_not_entitled"}', 403),+ ],+ ["a 422", new SendRefusedError('{"detail":"Message too long"}', 422)],+ [+ "a 400 with a non-JSON body",+ new SendRefusedError("Couldn't reach the server (HTTP 400).", 400),+ ],+ ])(+ "%s the app never provokes reads as a refusal we were notified of",+ (_state, error) => {+ expect(describeChatError(error)).toEqual({+ title: REFUSED,+ action: null,+ note: NOTIFIED,+ });+ },+ );++ it.each([+ ["a dropped connection", new TypeError("Failed to fetch")],+ [+ "a proxy's 502",+ new SendRefusedError("Couldn't reach the server (HTTP 502).", 502),+ ],+ ["a 500", new SendRefusedError('{"detail":"Internal error"}', 500)],+ [+ "a conflict with a running turn",+ new SendRefusedError('{"detail":"busy"}', 409),+ ],+ ["an unknown failure", new Error("kaboom")],+ ])("%s says to send again, since that can work", (_state, error) => {+ const guidance = describeChatError(error);+ expect(guidance.title).toMatch(RESEND);+ expect(guidance.action).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.tsindex 61a73b81f9..397978258e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/drift-report.ts@@ -41,8 +41,6 @@ interface DriftReport {type Invariant = keyof DriftReport;-const ERROR_BOX_TEXT = "The assistant encountered an error";-/** Every transcript the page paints, one sample per DOM mutation. */export function sampleTranscripts() {const samples: TranscriptEntry[][] = [];@@ -100,7 +98,9 @@ export async function reportDrift({maxTimesPainted(painted.samples, block) > 0 && !shownText.includes(block),);const toasts = connectionToasts(toast);- const errorShown = document.body.textContent?.includes(ERROR_BOX_TEXT);+ const errorBanner = document.querySelector(+ '[data-testid="chat-error-banner"]',+ );const reloaded = await renderReloaded(sim.finalRows());return {connectionToast: toasts.length ? toasts : null,@@ -113,7 +113,7 @@ export async function reportDrift({missingWhileRunning: missingWhileRunning.length? missingWhileRunning: null,- errorShown: errorShown ? ERROR_BOX_TEXT : null,+ errorShown: errorBanner?.textContent ?? null,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/chatErrorGuidance.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/chatErrorGuidance.tsnew file mode 100644index 0000000000..fa3ac621e0--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/chatErrorGuidance.ts@@ -0,0 +1,80 @@+import { CopilotAuthError } from "./helpers";+import {+ ChatUnavailableError,+ isUnexpectedRefusal,+ MessageTooLongError,+} from "./stream/turnRuntime";++export type ChatErrorAction = "sign-in" | "new-chat";++export interface ChatErrorGuidance {+ /** What happened, and what will work next. */+ title: string;+ action: ChatErrorAction | null;+ /** A small muted line under the guidance. */+ note?: string;+}++/** Guidance for a failed send or stream; it promises a resend only where one can succeed. */+export function describeChatError(error: Error): ChatErrorGuidance {+ const status = statusOf(error);+ if (+ error instanceof CopilotAuthError ||+ status === 401 ||+ /authentication failed|not authenticated/i.test(error.message)+ )+ return {+ title: "You're signed out. Sign in again to keep chatting.",+ action: "sign-in",+ };+ if (error instanceof ChatUnavailableError || status === 404)+ return {+ title: "This chat no longer exists. Start a new chat to keep going.",+ action: "new-chat",+ };+ if (error instanceof MessageTooLongError)+ return {+ title: "Your message is too long. Shorten it and send again.",+ action: null,+ };+ if (/prompt is too long/i.test(error.message))+ return {+ title:+ "This conversation is too long to continue. Start a new chat to keep going.",+ action: "new-chat",+ };+ if (status === 429 || /usage limit/i.test(error.message))+ return {+ title: "You've reached a usage limit, so this message wasn't sent.",+ action: null,+ };+ // The app only sends what the server accepts, so this is our bug.+ if (status !== null && isUnexpectedRefusal(status))+ return {+ title:+ "The request was refused. Reload the page and try again; if it keeps happening, contact support.",+ action: null,+ note: "The system maintainer has been notified of the issue",+ };+ if (status !== null && status >= 500)+ return {+ title:+ "The server had a problem. Please try sending your message again in a moment.",+ action: null,+ };+ if (error.name === "TypeError")+ return {+ title:+ "The connection dropped before your message was sent. Check your connection and send it again.",+ action: null,+ };+ return {+ title: "Something went wrong. Please try sending your message again.",+ action: null,+ };+}++function statusOf(error: Error) {+ const status = (error as { status?: unknown }).status;+ return typeof status === "number" ? status : null;+}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 7a1825f02a..0eb83a0a09 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@@ -75,6 +75,7 @@ import {} from "../../helpers/workspaceAttachments";import { Clock01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";+import { ChatErrorBanner } from "./components/ChatErrorBanner/ChatErrorBanner";interface Props {messages: UIMessage<unknown, UIDataTypes, UITools>[];@@ -859,15 +860,7 @@ export function ChatMessagesContainer({</Message>))}{!readOnly && error && !lastAssistantHasErrorMarker && (- <details className="rounded-lg bg-red-50 p-4 text-sm text-red-700">- <summary className="cursor-pointer font-medium">- The assistant encountered an error. Please try sending your- message again.- </summary>- <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs text-red-600">- {error instanceof Error ? error.message : String(error)}- </pre>- </details>+ <ChatErrorBanner error={error} />)}<TailSpacermessageID={lastUserMessageID}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 f7f16fcedb..4a637834db 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@@ -455,7 +455,7 @@ describe("ChatMessagesContainer — error banner dedup", () => {expect(screen.getByText("SDK stream error: Prompt is too long"),).toBeDefined();- expect(screen.getByText(/encountered an error/i)).toBeDefined();+ expect(screen.getByTestId("chat-error-banner")).toBeDefined();});it("suppresses the trailing banner when the last assistant message carries an error marker", () => {@@ -483,7 +483,7 @@ describe("ChatMessagesContainer — error banner dedup", () => {]}/>,);- expect(screen.queryByText(/encountered an error/i)).toBeNull();+ expect(screen.queryByTestId("chat-error-banner")).toBeNull();});it("suppresses the trailing banner when the marker is retryable", () => {@@ -511,7 +511,7 @@ describe("ChatMessagesContainer — error banner dedup", () => {]}/>,);- expect(screen.queryByText(/encountered an error/i)).toBeNull();+ expect(screen.queryByTestId("chat-error-banner")).toBeNull();});});@@ -1039,7 +1039,7 @@ describe("ChatMessagesContainer — readOnly mode", () => {]}/>,);- expect(screen.queryByText(/encountered an error/i)).toBeNull();+ expect(screen.queryByTestId("chat-error-banner")).toBeNull();expect(screen.queryByText(/upstream blew up/i)).toBeNull();});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/ChatErrorBanner.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/ChatErrorBanner.tsxnew file mode 100644index 0000000000..66b9e4f0be--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/ChatErrorBanner.tsx@@ -0,0 +1,48 @@+import { Button } from "@/components/atoms/Button/Button";++import {+ describeChatError,+ type ChatErrorAction,+} from "../../../../chatErrorGuidance";++interface Props {+ error: Error;+}++export function ChatErrorBanner({ error }: Props) {+ const { title, action, note } = describeChatError(error);+ return (+ <div+ data-testid="chat-error-banner"+ className="rounded-lg bg-red-50 p-4 text-sm text-red-700"+ >+ <details>+ <summary className="cursor-pointer font-medium">{title}</summary>+ <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs text-red-600">+ {error.message}+ </pre>+ </details>+ {note ? <p className="mt-1 text-xs text-zinc-500">{note}</p> : null}+ {action ? (+ <Button+ as="NextLink"+ href={hrefFor(action)}+ variant="secondary"+ size="small"+ className="mt-3"+ >+ {action === "sign-in" ? "Sign in" : "Start a new chat"}+ </Button>+ ) : null}+ </div>+ );+}++function hrefFor(action: ChatErrorAction) {+ if (action === "new-chat") return "/copilot";+ const here =+ typeof window === "undefined"+ ? "/copilot"+ : `${window.location.pathname}${window.location.search}`;+ return `/login?next=${encodeURIComponent(here)}`;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/__tests__/ChatErrorBanner.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/__tests__/ChatErrorBanner.test.tsxnew file mode 100644index 0000000000..89c080d947--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChatErrorBanner/__tests__/ChatErrorBanner.test.tsx@@ -0,0 +1,81 @@+import { render, screen } from "@/tests/integrations/test-utils";+import { afterEach, describe, expect, it } from "vitest";++import { CopilotAuthError } from "../../../../../helpers";+import {+ ChatUnavailableError,+ SendRefusedError,+} from "../../../../../stream/turnRuntime";+import { ChatErrorBanner } from "../ChatErrorBanner";++afterEach(() => {+ window.history.replaceState(null, "", "/");+});++describe("ChatErrorBanner", () => {+ it("signed out: offers sign-in that returns to this chat", () => {+ window.history.replaceState(null, "", "/copilot?sessionId=s-1");+ render(<ChatErrorBanner error={new CopilotAuthError()} />);++ expect(+ screen.getByText("You're signed out. Sign in again to keep chatting."),+ ).toBeDefined();+ expect(+ screen.getByRole("link", { name: "Sign in" }).getAttribute("href"),+ ).toBe(`/login?next=${encodeURIComponent("/copilot?sessionId=s-1")}`);+ });++ it("a chat that is gone: offers a new chat", () => {+ render(<ChatErrorBanner error={new ChatUnavailableError()} />);++ expect(+ screen.getByText(+ "This chat no longer exists. Start a new chat to keep going.",+ ),+ ).toBeDefined();+ expect(+ screen+ .getByRole("link", { name: "Start a new chat" })+ .getAttribute("href"),+ ).toBe("/copilot");+ });++ it("a refusal the app never provokes: the refusal, its response body folded away, and the notified line", () => {+ render(+ <ChatErrorBanner+ error={+ new SendRefusedError('{"detail":"advanced_tier_not_entitled"}', 403)+ }+ />,+ );++ const banner = screen.getByTestId("chat-error-banner");+ const details = banner.querySelector("details");+ expect(details?.open).toBe(false);+ expect(details?.querySelector("summary")?.textContent).toBe(+ "The request was refused. Reload the page and try again; if it keeps happening, contact support.",+ );+ expect(details?.querySelector("pre")?.textContent).toBe(+ '{"detail":"advanced_tier_not_entitled"}',+ );+ expect(+ Array.from(banner.querySelectorAll("p")).map((p) => p.textContent),+ ).toEqual(["The system maintainer has been notified of the issue"]);+ });++ it("a dropped connection: says to send again, with no action", () => {+ render(<ChatErrorBanner error={new TypeError("Failed to fetch")} />);++ expect(+ screen.getByText(+ "The connection dropped before your message was sent. Check your connection and send it again.",+ ),+ ).toBeDefined();+ expect(screen.queryByRole("link")).toBeNull();+ expect(+ screen.queryByText(+ "The system maintainer has been notified of the issue",+ ),+ ).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.tsindex f28aafe538..8f823d0ebb 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts@@ -33,7 +33,7 @@ export async function getCopilotAuthHeaders(): Promise<Record<string, string>> {const { token, error } = await getWebSocketToken();if (error || !token) {console.warn("[Copilot] Failed to get auth token:", error);- throw new Error("Authentication failed — please sign in again.");+ throw new CopilotAuthError();}return {Authorization: `Bearer ${token}`,@@ -41,6 +41,14 @@ export async function getCopilotAuthHeaders(): Promise<Record<string, string>> {};}+/** The server answered and has no session token: signed out, not offline. */+export class CopilotAuthError extends Error {+ constructor() {+ super("Authentication failed — please sign in again.");+ this.name = "CopilotAuthError";+ }+}+/*** Build the document title showing how many sessions are ready.* Returns the base title when count is 0.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.tsindex ebf9604085..41f85f146b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/__tests__/turnRuntime.test.ts@@ -9,11 +9,15 @@ import {type Mock,} from "vitest";+import { CopilotAuthError } from "../../helpers";import { createTailRenderer } from "../renderTail";import {ANOMALY_TOAST,+ ChatUnavailableError,LIVENESS_MS,+ MessageTooLongError,ROTATE_AFTER_MS,+ SendRefusedError,TurnRuntime,type RuntimeDeps,type RuntimeSnapshot,@@ -33,6 +37,7 @@ let backend: FakeBackend;let runtime: TurnRuntime;let toast: Mock<RuntimeDeps["toast"]>;let report: Mock<RuntimeDeps["report"]>;+let tokenFailures = 0;beforeEach(() => {vi.useFakeTimers();@@ -40,9 +45,16 @@ beforeEach(() => {backend = fakeBackend(toolTurn);toast = vi.fn<RuntimeDeps["toast"]>();report = vi.fn<RuntimeDeps["report"]>();+ tokenFailures = 0;runtime = new TurnRuntime("session-1", {baseUrl: () => "http://backend.test",- headers: async () => ({}),+ headers: async () => {+ if (tokenFailures > 0) {+ tokenFailures -= 1;+ throw new CopilotAuthError();+ }+ return {};+ },fetch: backend.fetch,fetchSession: async () => backend.view(),toast,@@ -488,6 +500,394 @@ describe("recovery", () => {});});+describe("after a lost send, what the user is told follows the server", () => {+ it("shows a lost send's answer without a lingering notice when the first reads on return fail", async () => {+ loseSendWhileHidden();+ void runtime.send({ text: PROMPT }, undefined);+ await advance(60_000);+ backend.beginRunning();+ backend.publish();+ viewsFailFirst(2);+ setVisibility("visible");+ await advance(30_000);++ expect(snapshot().notice).toBeNull();+ expect(snapshot().error).toBeNull();+ expect(textsOf(render()).join("")).toBe(+ `${PROMPT}${FIRST_TEXT}${SECOND_TEXT}`,+ );+ });++ it("still reports a send that never reached the server when the first reads on return fail", async () => {+ loseSendWhileHidden();+ void runtime.send({ text: PROMPT }, undefined);+ await advance(60_000);+ viewsFailFirst(2);+ setVisibility("visible");+ await advance(30_000);++ expect(snapshot().error?.message).toBe("Failed to fetch");+ expect(snapshot().notice).toBeNull();+ });++ it("reports no error when another read attaches the lost send's turn first", async () => {+ backend.respond(({ method }) =>+ method === "POST" ? "network-error" : "stream",+ );+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ runtime.bind({}, async () => {+ await held;+ return backend.view();+ });+ backend.beginRunning();+ backend.publish(FIRST_BLOCK_DONE);+ void runtime.send({ text: PROMPT }, undefined);+ await advance(0);+ // The page's own read lands while the recovery's first read is in flight.+ runtime.observe(backend.view());+ release();+ await advance(10_000);+ expect(snapshot().error).toBeNull();+ expect(snapshot().phase).toBe("live");++ backend.publish();+ await advance(5_000);+ expect(snapshot().error).toBeNull();+ expect(snapshot().phase).toBe("finished");+ });++ it("clears a failed send's error once a turn the server started is followed", async () => {+ backend.respond(({ method }) =>+ method === "POST" ? "network-error" : "stream",+ );+ void runtime.send({ text: PROMPT }, undefined);+ await advance(10_000);+ expect(snapshot().error?.message).toBe("Failed to fetch");++ backend.beginRunning();+ backend.publish(FIRST_BLOCK_DONE);+ runtime.followBackendTurn();+ await advance(2_000);+ expect(snapshot().phase).toBe("live");+ expect(snapshot().error).toBeNull();+ });++ it("stops reading the session once the lost send's prompt has landed and nothing runs", async () => {+ backend.respond(({ method }) =>+ method === "POST" ? "network-error" : "stream",+ );+ backend.beginRunning();+ backend.publish();+ const views = vi.spyOn(backend, "view");+ void runtime.send({ text: PROMPT }, undefined);+ await advance(10_000);++ expect(views).toHaveBeenCalledTimes(1);+ expect(snapshot().error).toBeNull();+ });++ it("keeps reading while the session runs a landed prompt whose turn has not registered yet", async () => {+ backend.respond(({ method }) =>+ method === "POST" ? "network-error" : "stream",+ );+ backend.beginRunning();+ backend.publish(FIRST_BLOCK_DONE);+ // The slot is claimed and the prompt written before the turn's stream exists.+ let reads = 0;+ runtime.bind({}, async () => {+ reads += 1;+ const view = backend.view();+ return reads <= 2+ ? { ...view, active_stream: null, chat_status: "running" }+ : view;+ });+ void runtime.send({ text: PROMPT }, undefined);+ await advance(5_000);++ expect(backend.connections.at(-1)?.url.searchParams.get("turn")).toBe(+ backend.turnId,+ );+ expect(snapshot().phase).toBe("live");+ });++ it("shows the offline notice while a send waits for the network", async () => {+ const online = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false);+ backend.respond(({ method }) =>+ method === "POST" ? "network-error" : "stream",+ );+ void runtime.send({ text: PROMPT }, undefined);+ await advance(10_000);+ expect(snapshot().notice).toBe("offline");+ expect(snapshot().error).toBeNull();++ online.mockReturnValue(true);+ window.dispatchEvent(new Event("online"));+ await advance(10_000);+ expect(snapshot().notice).toBeNull();+ expect(snapshot().error?.message).toBe("Failed to fetch");+ });+});++describe("refusals no retry can change", () => {+ it("a send while signed out reports the sign-in error after one retry, and stops", async () => {+ const onError = vi.fn();+ signOut(() => true, onError);+ void runtime.send({ text: PROMPT }, undefined);+ await advance(120_000);++ expect(snapshot().error).toBeInstanceOf(CopilotAuthError);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(snapshot().notice).toBeNull();+ expect(toast).not.toHaveBeenCalled();+ });++ it("a send whose token fails once goes out a second later", async () => {+ tokenFailsFirst(1);+ void runtime.send({ text: PROMPT }, undefined);+ await advance(500);+ expect(backend.requests.filter((r) => r.method === "POST")).toHaveLength(0);++ await advance(1_000);+ backend.publish(FIRST_BLOCK_DONE);+ await advance(100);+ expect(backend.requests.filter((r) => r.method === "POST")).toHaveLength(1);+ expect(snapshot().error).toBeNull();+ expect(snapshot().phase).toBe("live");+ });++ it("a resume whose token fails once resumes", async () => {+ await sendAndPublish(FIRST_BLOCK_DONE);+ tokenFailsFirst(1);+ backend.connections[0].fail();+ await advance(2_000);++ expect(snapshot().error).toBeNull();+ expect(backend.connections.at(-1)?.url.searchParams.get("turn")).toBe(+ backend.turnId,+ );+ });++ it("a second send while a send waits out its token retry opens no second request", async () => {+ tokenFailsFirst(1);+ void runtime.send({ text: PROMPT }, undefined);+ await advance(500);+ void runtime.send({ text: "And example.org?" }, undefined);+ await advance(1_000);+ backend.publish(FIRST_BLOCK_DONE);+ await advance(100);++ expect(backend.requests.filter((r) => r.method === "POST")).toHaveLength(1);+ expect(backend.connections.some((c) => c.aborted)).toBe(false);+ expect(snapshot().error).toBeNull();+ expect(snapshot().phase).toBe("live");+ });++ it("a stop while a send waits out its token retry sends nothing after", async () => {+ tokenFailsFirst(1);+ void runtime.send({ text: PROMPT }, undefined);+ await advance(500);+ runtime.stop();+ await advance(5_000);++ expect(backend.requests.filter((r) => r.method === "POST")).toHaveLength(0);+ expect(snapshot().error).toBeNull();+ });++ it("signed out mid-turn ends the turn with the sign-in error, without the connection toast", async () => {+ let signedOut = false;+ signOut(() => signedOut);+ await sendAndPublish(FIRST_BLOCK_DONE);+ signedOut = true;+ backend.connections[0].fail();+ await advance(180_000);++ expect(snapshot().error).toBeInstanceOf(CopilotAuthError);+ expect(snapshot().phase).toBe("failed");+ expect(snapshot().notice).toBeNull();+ expect(toast).not.toHaveBeenCalled();+ });++ it("a resume refused twice with 401 ends the turn with the sign-in error", async () => {+ await sendAndPublish(FIRST_BLOCK_DONE);+ backend.respond(() => ({ status: 401, body: { detail: "Unauthorized" } }));+ backend.connections[0].fail();+ await advance(180_000);++ expect(backend.requests.filter((r) => r.method === "GET")).toHaveLength(2);+ expect(snapshot().error).toBeInstanceOf(CopilotAuthError);+ expect(snapshot().phase).toBe("failed");+ expect(toast).not.toHaveBeenCalled();+ });++ it("a resume refused once with 401 resumes on a fresh token", async () => {+ await sendAndPublish(FIRST_BLOCK_DONE);+ let refusals = 0;+ backend.respond(() =>+ refusals++ === 0+ ? { status: 401, body: { detail: "Unauthorized" } }+ : "stream",+ );+ backend.connections[0].fail();+ await advance(1_000);+ backend.publish();+ await advance(1_000);++ expect(backend.requests.filter((r) => r.method === "GET")).toHaveLength(2);+ expect(snapshot().phase).toBe("finished");+ expect(snapshot().error).toBeNull();+ });++ it("a resume refused 403 twice ends with the refusal, not the sign-in error", async () => {+ await sendAndPublish(FIRST_BLOCK_DONE);+ backend.respond(() => ({ status: 403, body: { detail: "Forbidden" } }));+ backend.connections[0].fail();+ await advance(180_000);++ expect(backend.requests.filter((r) => r.method === "GET")).toHaveLength(2);+ expect(snapshot().error).toEqual(+ new SendRefusedError('{"detail":"Forbidden"}', 403),+ );+ expect(snapshot().error).not.toBeInstanceOf(CopilotAuthError);+ expect(report).toHaveBeenCalledWith(+ "refused",+ expect.objectContaining({ status: 403 }),+ );+ expect(toast).not.toHaveBeenCalled();+ });++ it("reports a send refused with a 4xx the app never provokes, with its status", async () => {+ backend.respond(() => ({+ status: 422,+ body: { detail: "Message too long" },+ }));+ void runtime.send({ text: PROMPT }, undefined);+ await advance(1_000);++ expect(report).toHaveBeenCalledWith("refused", {+ status: 422,+ body: { detail: "Message too long" },+ });+ expect(snapshot().error).toEqual(+ new SendRefusedError('{"detail":"Message too long"}', 422),+ );+ });++ it("a message over the server's length limit is its own refusal, not reported", async () => {+ // FastAPI's 422 for StreamChatRequest.message over max_length=64_000.+ backend.respond(() => ({+ status: 422,+ body: {+ detail: [+ {+ type: "string_too_long",+ loc: ["body", "message"],+ msg: "String should have at most 64000 characters",+ },+ ],+ },+ }));+ void runtime.send({ text: PROMPT }, undefined);+ await advance(1_000);++ expect(snapshot().error).toBeInstanceOf(MessageTooLongError);+ expect(report).not.toHaveBeenCalled();+ });++ it.each([401, 404, 429])(+ "does not report a send refused %i, which the user's state explains",+ async (status) => {+ backend.respond(() => ({ status, body: { detail: "refused" } }));+ void runtime.send({ text: PROMPT }, undefined);+ await advance(1_000);++ expect(report).not.toHaveBeenCalled();+ },+ );++ it("a resume refused 404 ends the turn: the chat is gone", async () => {+ await sendAndPublish(FIRST_BLOCK_DONE);+ backend.respond(() => ({ status: 404, body: { detail: "Not found" } }));+ backend.connections[0].fail();+ await advance(180_000);++ expect(backend.requests.filter((r) => r.method === "GET")).toHaveLength(1);+ expect(snapshot().error).toBeInstanceOf(ChatUnavailableError);+ expect(toast).not.toHaveBeenCalled();+ });++ it("a send refused by a proxy's HTML page reads as plain language", async () => {+ backend.respond(() => ({+ status: 502,+ body: "<html><head><title>502 Server Error</title></head></html>",+ }));+ void runtime.send({ text: PROMPT }, undefined);+ await advance(1_000);++ expect(snapshot().error).toEqual(+ new SendRefusedError("Couldn't reach the server (HTTP 502).", 502),+ );+ expect(snapshot().error).toBeInstanceOf(SendRefusedError);+ });+});++describe("a return to the tab", () => {+ it("after more than 30 s away, follows a turn started elsewhere meanwhile", async () => {+ runtime.observe(backend.view());+ setVisibility("hidden");+ await advance(60_000);+ backend.beginRunning();+ backend.publish(FIRST_BLOCK_DONE);+ setVisibility("visible");+ await advance(1_000);++ expect(backend.connections.at(-1)?.url.searchParams.get("turn")).toBe(+ backend.turnId,+ );+ expect(snapshot().phase).toBe("live");+ });++ it("when the first read on return fails, reads again and follows the turn", async () => {+ runtime.observe(backend.view());+ setVisibility("hidden");+ await advance(60_000);+ backend.beginRunning();+ backend.publish(FIRST_BLOCK_DONE);+ let reads = 0;+ runtime.bind({}, async () => (reads++ === 0 ? null : backend.view()));+ setVisibility("visible");+ await advance(3_000);++ expect(reads).toBe(2);+ expect(snapshot().phase).toBe("live");+ });++ it("stops re-reading after three failed retries", async () => {+ runtime.observe(backend.view());+ setVisibility("hidden");+ await advance(60_000);+ let reads = 0;+ runtime.bind({}, async () => {+ reads += 1;+ return null;+ });+ setVisibility("visible");+ await advance(120_000);++ expect(reads).toBe(4);+ });++ it("within 30 s, reads nothing", async () => {+ runtime.observe(backend.view());+ setVisibility("hidden");+ await advance(10_000);+ const views = vi.spyOn(backend, "view");+ setVisibility("visible");+ await advance(1_000);+ expect(views).not.toHaveBeenCalled();+ });+});+describe("one connection slot", () => {it("W1: two resumes inside the window open one connection and draw one bubble", async () => {await sendAndPublish(FIRST_BLOCK_DONE);@@ -668,6 +1068,42 @@ describe("the end-of-turn reconcile", () => {});});+function loseSendWhileHidden() {+ backend.respond(({ method }) =>+ method === "POST" ? "network-error" : "stream",+ );+ setVisibility("hidden");+}++function viewsFailFirst(count: number) {+ let failed = 0;+ runtime.bind({}, async () => (failed++ < count ? null : backend.view()));+}++// Signed out: no token for any request, and the session read is refused too.+function signOut(isSignedOut: () => boolean, onError = vi.fn()) {+ runtime.dispose();+ runtime = new TurnRuntime("session-1", {+ baseUrl: () => "http://backend.test",+ headers: async () => {+ if (isSignedOut()) throw new CopilotAuthError();+ return {};+ },+ fetch: backend.fetch,+ fetchSession: async () => backend.view(),+ toast,+ report,+ });+ runtime.bind({ onError }, async () =>+ isSignedOut() ? null : backend.view(),+ );+}++// The token action fails the next `count` times, then hands out tokens again.+function tokenFailsFirst(count: number) {+ tokenFailures = count;+}+async function sendAndPublish(count: number) {void runtime.send({ text: PROMPT }, undefined);await advance(0);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.tsindex febfc471ba..70b2ff962f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/stream/turnRuntime.ts@@ -6,7 +6,11 @@ import type { FileUIPart, UIMessage } from "ai";import { v4 as uuidv4 } from "uuid";import { streamRequestBody } from "../copilotStreamTransport";-import { getCopilotAuthHeaders, isEngineSwitchPart } from "../helpers";+import {+ CopilotAuthError,+ getCopilotAuthHeaders,+ isEngineSwitchPart,+} from "../helpers";import type { CopilotLlmModel } from "../store";import { isTokenDevtoolEnabled } from "../tokenDevtool/gate";import { createUsageCapturingFetch } from "../tokenDevtool/usageTap";@@ -47,6 +51,7 @@ export const LIVENESS_MS = 30_000;/** The load balancer cuts an SSE at 30 minutes; rotate before it does. */export const ROTATE_AFTER_MS = 25 * 60_000;const BACKOFF_MS = [1_000, 2_000, 4_000, 8_000, 16_000];+const TOKEN_RETRY_MS = 1_000;const ANOMALY_RETRY_MS = 30_000;const INDICATOR_AFTER_FAILURES = 2;const CATCHING_UP_AFTER_MS = 2_000;@@ -54,6 +59,10 @@ const TICK_MS = 5_000;const EMIT_THROTTLE_MS = 30;const FROZEN_POLL_MS = 10_000;const QUEUED_POLL_MS = 10_000;+// A tab away this long re-reads an idle chat on return, as the flag-off chat does.+const WAKE_REREAD_MS = 30_000;+// A phone often wakes before its network does.+const REREAD_RETRY_MS = [2_000, 4_000, 8_000];// The backend marks a queued turn running a moment before its stream exists;// past this, the stream is not coming.const QUEUE_START_GRACE_MS = 2 * 60_000;@@ -152,7 +161,8 @@ type Lost = Pick<type ConnectionEnd =| { kind: "closed" }| { kind: "refused"; status: number; body: unknown }- | { kind: "failed"; error: unknown };+ | { kind: "failed"; error: unknown }+ | { kind: "denied"; error: CopilotAuthError };interface QueueWatch {timer: ReturnType<typeof setTimeout> | null;@@ -178,6 +188,8 @@ export class TurnRuntime {private slot: Connection | null = null;private rotating: Connection | null = null;private failures = 0;+ // 401/403s since the last frame; the first gets a fresh token, the second ends the turn.+ private denials = 0;private anomalyShown = false;private notice: RuntimeNotice = null;private error: Error | null = null;@@ -208,6 +220,8 @@ export class TurnRuntime {private handlers: RuntimeHandlers = {};private boundFetchSession: (() => Promise<SessionView | null>) | null = null;private disposed = false;+ private hiddenAt: number | null = null;+ private rereadTimer: ReturnType<typeof setTimeout> | null = null;constructor(readonly sessionId: string,@@ -385,7 +399,9 @@ export class TurnRuntime {for (const timer of [this.tickTimer, this.frozenTimer]) {if (timer) clearInterval(timer);}- if (this.emitTimer) clearTimeout(this.emitTimer);+ for (const timer of [this.emitTimer, this.rereadTimer]) {+ if (timer) clearTimeout(timer);+ }if (typeof window !== "undefined") {document.removeEventListener("visibilitychange", this.onVisible);window.removeEventListener("pageshow", this.onVisible);@@ -456,7 +472,7 @@ export class TurnRuntime {this.emit();let end: ConnectionEnd;try {- const headers = await this.deps.headers();+ const headers = await this.authHeaders(conn);const result = await fetchSse(url,{@@ -472,11 +488,27 @@ export class TurnRuntime {? { kind: "closed" }: { kind: "refused", status: result.status, body: result.body };} catch (error) {- end = { kind: "failed", error };+ end =+ error instanceof CopilotAuthError+ ? { kind: "denied", error }+ : { kind: "failed", error };}this.onEnd(conn, end);}+ // The token action answers "no token" for a sign-out and for a failed lookup+ // alike, so a connection asks once more before it counts as signed out.+ private async authHeaders(conn: Connection) {+ try {+ return await this.deps.headers();+ } catch (error) {+ if (!(error instanceof CopilotAuthError)) throw error;+ await sleep(TOKEN_RETRY_MS);+ if (conn.controller.signal.aborted) throw error;+ return this.deps.headers();+ }+ }+private onFrame(conn: Connection, frame: SseFrame) {if (conn !== this.slot && conn !== this.rotating) return;conn.lastFrameAt = Date.now();@@ -555,6 +587,10 @@ export class TurnRuntime {if (conn.closedByClient) return;const seg = conn.turnId ? this.turnFor(conn.turnId) : null;if (seg && (seg.ended || seg.stopped || seg.frozen)) return;+ if (end.kind === "denied") {+ this.giveUp(end.error);+ return;+ }if (end.kind === "refused" && conn.kind === "post") {this.refusedSend(end);return;@@ -570,6 +606,8 @@ export class TurnRuntime {if (end.status === 409) void this.resync(seg.key, checkpointOf(end.body));else if (end.status === 410 || end.status === 204)void this.expire(seg.key);+ else if (end.status === 401 || end.status === 403) this.denied(seg, end);+ else if (end.status === 404) this.giveUp(new ChatUnavailableError());else this.retry(conn);return;}@@ -596,7 +634,7 @@ export class TurnRuntime {* rotation-age cuts resume silently; only a run of failures while the tab* is visible and online reaches the one alarming toast.*/- private retry(lost: Lost) {+ private retry(lost: Lost, end: ConnectionEnd = { kind: "closed" }) {const running = this.runningTurn();if (!running && lost.turnId !== null) return;const offline =@@ -605,7 +643,7 @@ export class TurnRuntime {lost.turnId === null &&(offline || document.visibilityState === "hidden")) {- this.unresolvedPost = { lost, end: { kind: "closed" } };+ this.unresolvedPost = { lost, end };}if (document.visibilityState === "hidden") return;if (offline) {@@ -628,24 +666,71 @@ export class TurnRuntime {this.retryTimer = setTimeout(() => {this.retryTimer = null;if (this.runningTurn()) this.ensureConnected();- else void this.recoverUnknownTurn(lost, { kind: "closed" });+ else void this.recoverUnknownTurn(lost, end);}, delay);this.emitNow();}private refusedSend(end: Extract<ConnectionEnd, { kind: "refused" }>) {- const text =- typeof end.body === "string" ? end.body : JSON.stringify(end.body);- this.error = new Error(text || `Request failed with status ${end.status}`);+ if (isMessageTooLong(end.body)) {+ this.error = new MessageTooLongError(refusalText(end), end.status);+ } else {+ this.reportIfUnexpected(end);+ this.error = new SendRefusedError(refusalText(end), end.status);+ }this.emitNow();this.handlers.onError?.(this.error, null);}+ // The first refusal may be a token that expired in flight; refused again,+ // a 401 means signed out and a 403 means no access.+ private denied(+ seg: TurnSegment,+ end: Extract<ConnectionEnd, { kind: "refused" }>,+ ) {+ this.denials += 1;+ if (this.denials === 1) this.resume(seg);+ else if (end.status === 401) this.giveUp(new CopilotAuthError());+ else {+ this.reportIfUnexpected(end);+ this.giveUp(new SendRefusedError(refusalText(end), end.status));+ }+ }++ // The banner tells the user we were notified of these.+ private reportIfUnexpected(end: Extract<ConnectionEnd, { kind: "refused" }>) {+ if (!isUnexpectedRefusal(end.status)) return;+ this.deps.report("refused", { status: end.status, body: end.body });+ }++ /** A refusal no retry can change: end the turn where it stands and say why. */+ private giveUp(error: Error) {+ const running = this.runningTurn();+ this.abortConnections();+ this.clearRetry();+ this.unresolvedPost = null;+ if (running) {+ this.updateTurn(running.key, (seg) => ({+ ...seg,+ ended: true,+ log: closeBlocks(seg.log),+ }));+ }+ this.resetFailures();+ this.error = error;+ this.emitNow();+ this.handlers.onError?.(error, null);+ }+// A send whose stream ended before naming its turn: the session view says// whether the turn runs, once the tab can ask.private findLostTurn(lost: Lost, end: ConnectionEnd) {const offline =typeof navigator !== "undefined" && navigator.onLine === false;+ if (offline) {+ this.notice = "offline";+ this.emitNow();+ }if (document.visibilityState === "hidden" || offline)this.unresolvedPost = { lost, end };else void this.recoverUnknownTurn(lost, end);@@ -657,7 +742,7 @@ export class TurnRuntime {for (let i = 0; i < CONTINUATION_PROBES; i++) {const view = await this.fetchView();if (!view) {- this.retry(lost);+ this.retry(lost, end);return;}const attaching = this.wouldAttach(view);@@ -667,22 +752,36 @@ export class TurnRuntime {return;}if (this.disposed || this.stopped) return;+ // The session reads "running" from before the prompt row is written+ // until the turn is released, so a landed prompt outside it is final.+ if (+ this.lostSendLanded(lost.prompt) &&+ (this.runningTurn() || view.chat_status !== "running")+ )+ break;await sleep(FINISH_PROBE_MS);}- // The view holds the prompt, so the send arrived; its rows say the rest.- if (this.lostSendLanded(lost.prompt)) return;- if (end.kind === "failed" || lost.syntheticError) {+ this.resetFailures();+ if (+ !this.lostSendLanded(lost.prompt) &&+ (end.kind === "failed" || lost.syntheticError)+ ) {this.error =end.kind === "failed" && end.error instanceof Error? end.error: new Error(lost.syntheticError ?? "The connection closed early.");- this.emitNow();}+ this.emitNow();}+ // The send arrived: its prompt took a row, or the turn after it is followed.private lostSendLanded(promptKey: string | null) {- const prompt = promptKey ? this.segmentByKey(promptKey) : null;- return prompt?.kind === "user" && prompt.sequence !== null;+ const index = this.segments.findIndex((s) => s.key === promptKey);+ const prompt = this.segments[index];+ if (prompt?.kind !== "user") return false;+ return (+ prompt.sequence !== null || this.segments[index + 1]?.kind === "turn"+ );}// ── The turn's lifecycle ───────────────────────────────────────────────@@ -707,6 +806,7 @@ export class TurnRuntime {start,);this.segments.push(seg);+ this.error = null;this.resume(seg);}@@ -1045,7 +1145,13 @@ export class TurnRuntime {// ── Plumbing ───────────────────────────────────────────────────────────private onVisible = () => {- if (document.visibilityState === "visible") this.wake();+ if (document.visibilityState === "hidden") {+ this.hiddenAt ??= Date.now();+ return;+ }+ const away = this.hiddenAt === null ? 0 : Date.now() - this.hiddenAt;+ this.hiddenAt = null;+ this.wake(away);};private onOnline = () => {@@ -1062,16 +1168,36 @@ export class TurnRuntime {}};- private wake() {+ private wake(away = 0) {const unresolved = this.unresolvedPost;this.unresolvedPost = null;if (unresolved && !this.runningTurn())void this.recoverUnknownTurn(unresolved.lost, unresolved.end);// A send still waiting for its turn is otherwise given up only at the next tick.else if (this.isPostPending()) this.dropIfSilent();+ else if (away > WAKE_REREAD_MS && this.isIdle() && !this.recovering)+ void this.reread();else this.ensureConnected();}+ // Another tab, device or the server may have moved an idle chat on meanwhile.+ private async reread(attempt = 0) {+ if (this.rereadTimer) clearTimeout(this.rereadTimer);+ this.rereadTimer = null;+ const view = await this.fetchView();+ if (this.disposed) return;+ if (view) {+ this.observe(view);+ return;+ }+ const delay = REREAD_RETRY_MS[attempt];+ if (delay === undefined) return;+ this.rereadTimer = setTimeout(() => {+ this.rereadTimer = null;+ if (this.isIdle()) void this.reread(attempt + 1);+ }, delay);+ }+private ensureTicking() {if (this.tickTimer) return;this.tickTimer = setInterval(() => this.tick(), TICK_MS);@@ -1185,6 +1311,7 @@ export class TurnRuntime {private resetFailures() {this.failures = 0;+ this.denials = 0;this.anomalyShown = false;if (this.notice === "reconnecting" || this.notice === "offline") {this.notice = null;@@ -1349,6 +1476,65 @@ function str(value: unknown): string {return typeof value === "string" ? value : "";}+// JSON stays as sent, since the error handler reads its detail; a proxy's+// HTML page or an empty body is replaced by words.+function refusalText({ status, body }: { status: number; body: unknown }) {+ if (body !== null && typeof body !== "string") return JSON.stringify(body);+ if (body && !body.trimStart().startsWith("<")) return body;+ return `Couldn't reach the server (HTTP ${status}).`;+}++/**+ * A 4xx the app never provokes on purpose: not a sign-in (401), a gone chat+ * (404), a usage limit (429), or a timeout or busy session a resend can pass.+ */+export function isUnexpectedRefusal(status: number) {+ return status >= 400 && status < 500 && !EXPECTED_4XX.has(status);+}++const EXPECTED_4XX = new Set([401, 404, 408, 409, 425, 429]);++/** A send the server refused; its status says whether a resend can help. */+export class SendRefusedError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = "SendRefusedError";+ }+}++// FastAPI's 422 for a message over the request model's max_length; the composer has no cap.+function isMessageTooLong(body: unknown) {+ const detail = (body as { detail?: unknown } | null)?.detail;+ return (+ Array.isArray(detail) &&+ detail.some(+ (item: { type?: unknown; loc?: unknown }) =>+ item?.type === "string_too_long" &&+ Array.isArray(item.loc) &&+ item.loc.at(-1) === "message",+ )+ );+}++/** A send refused because the message is longer than the server takes. */+export class MessageTooLongError extends SendRefusedError {+ constructor(message: string, status: number) {+ super(message, status);+ this.name = "MessageTooLongError";+ }+}++/** The session the chat follows is gone. */+export class ChatUnavailableError extends Error {+ constructor() {+ super("This chat is no longer available.");+ this.name = "ChatUnavailableError";+ }+}+function sleep(ms: number) {return new Promise((resolve) => setTimeout(resolve, ms));}diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.tsindex 1b2785b9af..b01381e6b4 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.ts+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertChatDrawer/useExpertChatDrawer.ts@@ -8,6 +8,7 @@ import {markKickoffPending,withKickoffLock,} from "@/app/(platform)/copilot/expertKickoff";+import { describeChatError } from "@/app/(platform)/copilot/chatErrorGuidance";import { convertChatSessionMessagesToUiMessages } from "@/app/(platform)/copilot/helpers/convertChatSessionToUiMessages";import { queueFollowUpMessage } from "@/app/(platform)/copilot/helpers/queueFollowUpMessage";import { latestExpertSessionParams } from "@/app/(platform)/copilot/expertSessionQuery";@@ -29,11 +30,13 @@ type UiMessages = UIMessage<unknown, UIDataTypes, UITools>[];class SessionStartingError extends Error {}-function notifyStartFailed() {+function notifyStartFailed(error: unknown) {toast({variant: "destructive",title: "Could not start the chat",- description: "Please try sending your message again.",+ description: describeChatError(+ error instanceof Error ? error : new Error(String(error)),+ ).title,});}@@ -452,7 +455,7 @@ export function useExpertChatDrawer({try {await onSend(message);} catch (err) {- if (!(err instanceof SessionStartingError)) notifyStartFailed();+ if (!(err instanceof SessionStartingError)) notifyStartFailed(err);throw err;}}