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): say so when a chat link can't be opened on this account (#14975)
Reinier van der Leer0a6be7cb901b
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxindex 4b3b371a21..9d46e02863 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -42,6 +42,7 @@ export function CopilotChatHost({queuedMessages,isLoadingSession,isSessionError,+ isSessionNotFound,isCreatingSession,isUploadingFiles,pendingSend,@@ -87,6 +88,7 @@ export function CopilotChatHost({sessionAutopilotMode={sessionAutopilotMode}isLoadingSession={isLoadingSession}isSessionError={isSessionError}+ isSessionNotFound={isSessionNotFound}isCreatingSession={isCreatingSession}isReconnecting={isReconnecting}isFinishProbing={isFinishProbing}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/session-unavailable.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/session-unavailable.test.tsxnew file mode 100644index 0000000000..e7353f9fff--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/session-unavailable.test.tsx@@ -0,0 +1,87 @@+import { screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { resetCopilotChatRegistry } from "../copilotChatRegistry";+import { useCopilotStreamStore } from "../copilotStreamStore";+import {+ renderHost,+ TEST_BACKEND_BASE_URL,+ TEST_SESSION_ID,+} from "./sse-helpers";++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("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: { id: "test-user" },+ isUserLoading: false,+ isLoggedIn: true,+ }),+}));++vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => ({+ ...(await importActual<+ typeof import("@/services/feature-flags/use-get-flag")+ >()),+ useGetFlag: () => false,+}));++const UNAVAILABLE = /this chat isn't available on this account/i;++function sessionError(status: number) {+ let calls = 0;+ const handler = http.get(`*/api/chat/sessions/${TEST_SESSION_ID}`, () => {+ calls += 1;+ return HttpResponse.json(+ { detail: `Session ${TEST_SESSION_ID} not found.` },+ { status },+ );+ });+ return { handler, calls: () => calls };+}++beforeEach(() => {+ resetCopilotChatRegistry();+ useCopilotStreamStore.getState().resetAll();+});++afterEach(() => {+ resetCopilotChatRegistry();+ useCopilotStreamStore.getState().resetAll();+});++describe("a chat link the user cannot open", () => {+ it("says the chat is unavailable and offers a new chat on a 404", async () => {+ const { handler } = sessionError(404);+ renderHost({ sessionResponse: handler });++ expect(await screen.findByText(UNAVAILABLE)).toBeDefined();+ expect(+ screen.queryByPlaceholderText("What else can I help with?"),+ ).toBeNull();++ await userEvent.click(screen.getByRole("button", { name: /new chat/i }));+ await waitFor(() => expect(screen.queryByText(UNAVAILABLE)).toBeNull());+ });++ it("keeps a server error on the existing path rather than calling the chat unavailable", async () => {+ const { handler, calls } = sessionError(500);+ renderHost({ sessionResponse: handler });++ await waitFor(() => expect(calls()).toBeGreaterThan(0));+ expect(+ await screen.findByPlaceholderText("What else can I help with?"),+ ).toBeDefined();+ expect(screen.queryByText(UNAVAILABLE)).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsxindex 418aefdb87..ddaa0b76e3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx@@ -115,13 +115,15 @@ export function renderHost(searchParams?: string;/** Follow-ups the backend still holds in the session's pending buffer. */pendingMessages?: string[];+ /** Replaces the default session GET, e.g. to answer it with an error. */+ sessionResponse?: HttpHandler;/** Mount under React Strict Mode, as the dev server does: every effect* runs twice on mount, so load-time requests fire twice. */strictMode?: boolean;} = {},) {server.use(- sessionHandler(opts.sessionOverride),+ opts.sessionResponse ?? sessionHandler(opts.sessionOverride),getGetV2GetCopilotUsageMockHandler200({daily: {percent_used: 0,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.tsxindex 9ceec0dfe6..9fca6c8dbc 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@@ -24,6 +24,7 @@ import { getLatestTaskList } from "../TaskProgressBar/helpers";import { ContextPanelToggle } from "../ContextPanel/ContextPanelToggle";import { WorkspaceFileCards } from "../WorkspaceFileCards/WorkspaceFileCards";import { ArchivedExpertNotice } from "./components/ArchivedExpertNotice";+import { SessionNotFound } from "./components/SessionNotFound";import { SharedChatNotice } from "./components/SharedChatNotice";import { useAutoOpenArtifacts } from "./useAutoOpenArtifacts";import { VoiceModeBar } from "../../voice/components/VoiceModeBar";@@ -62,6 +63,7 @@ export interface ChatContainerProps {sessionAutopilotMode?: AutopilotMode | null;isLoadingSession: boolean;isSessionError?: boolean;+ isSessionNotFound?: boolean;isCreatingSession: boolean;/** True when backend has an active stream but we haven't reconnected yet. */isReconnecting?: boolean;@@ -134,6 +136,7 @@ export const ChatContainer = ({sessionAutopilotMode = null,isLoadingSession,isSessionError,+ isSessionNotFound,isCreatingSession,isReconnecting,isFinishProbing,@@ -322,7 +325,9 @@ export const ChatContainer = ({{/* The chat column runs full width: the max-w-3xl cap lives on themessage list and the input instead, so the expert thread headercan span edge to edge while staying aligned with the messages. */}- {sessionId ? (+ {sessionId && isSessionNotFound ? (+ <SessionNotFound />+ ) : sessionId ? (<div className="relative flex h-full min-h-0 w-full flex-col bg-[#fafafa]"><div className="absolute right-0 top-0 z-30"><ContextPanelToggle sessionId={sessionId} />diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SessionNotFound.stories.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SessionNotFound.stories.tsxnew file mode 100644index 0000000000..28838bdb04--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SessionNotFound.stories.tsx@@ -0,0 +1,21 @@+import type { Meta, StoryObj } from "@storybook/nextjs";+import { NuqsAdapter } from "nuqs/adapters/react";+import { SessionNotFound } from "./SessionNotFound";++const meta: Meta<typeof SessionNotFound> = {+ title: "Copilot/SessionNotFound",+ component: SessionNotFound,+ decorators: [+ (Story) => (+ <NuqsAdapter>+ <div style={{ height: "100vh" }}>+ <Story />+ </div>+ </NuqsAdapter>+ ),+ ],+ parameters: { layout: "fullscreen" },+};+export default meta;++export const Default: StoryObj<typeof SessionNotFound> = {};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SessionNotFound.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SessionNotFound.tsxnew file mode 100644index 0000000000..4397f2aad9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SessionNotFound.tsx@@ -0,0 +1,47 @@+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";+import { BubbleChatBlockedIcon } from "@hugeicons/core-free-icons";+import { parseAsString, useQueryState } from "nuqs";++export function SessionNotFound() {+ const [, setSessionId] = useQueryState("sessionId", parseAsString);+ const [, setExpertId] = useQueryState("expertId", parseAsString);++ function handleNewChat() {+ setSessionId(null);+ // Otherwise the ?expertId= deep-link adoption drops the user into that+ // expert's latest thread instead of a new chat.+ setExpertId(null);+ }++ return (+ <div className="flex h-full min-h-0 w-full items-center justify-center bg-[#fafafa] px-6">+ <div+ role="status"+ className="flex max-w-md flex-col items-center gap-3 text-center"+ >+ <Icon+ icon={BubbleChatBlockedIcon}+ size={28}+ className="text-muted-foreground"+ />+ <Text variant="large-medium" as="h2">+ This chat isn't available on this account+ </Text>+ <Text variant="body" className="text-muted-foreground">+ It may belong to another account you use, or it no longer exists.+ </Text>+ <Button+ type="button"+ variant="secondary"+ size="small"+ className="mt-2"+ onClick={handleNewChat}+ >+ Start a new chat+ </Button>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex e57d3ce4f7..bfbd83e993 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -9,6 +9,7 @@ import type { CreateSessionRequest } from "@/app/api/__generated__/models/createimport { SESSION_LIST_QUERY_KEY } from "./useSessionList";import { useCopilotUIStore } from "./store";import { toast } from "@/components/molecules/Toast/use-toast";+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { trackFunnel } from "@/services/experts/experts-analytics";import * as Sentry from "@sentry/nextjs";import { useQueryClient } from "@tanstack/react-query";@@ -63,6 +64,8 @@ export function useChatSession({refetchOnWindowFocus: false,refetchOnReconnect: true,refetchOnMount: true,+ retry: (failureCount, error) =>+ !isDefinitiveSessionFailure(error) && failureCount < 3,},});@@ -425,6 +428,8 @@ export function useChatSession({// flips back to ``true`` mid-refetch, silently dropping the message.isLoadingSession: sessionQuery.isLoading,isSessionError: sessionQuery.isError,+ // Another account's session and a missing one are the same 404 by design.+ isSessionNotFound: isDefinitiveSessionFailure(sessionQuery.error),createSession,isCreatingSession,refetchSession: sessionQuery.refetch,@@ -434,3 +439,9 @@ export function useChatSession({sessionAutopilotMode,};}++function isDefinitiveSessionFailure(error: unknown) {+ return (+ error instanceof ApiError && (error.status === 403 || error.status === 404)+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex 663fa4bc03..cb586b038d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -137,6 +137,7 @@ export function useCopilotPage() {oldestSequence,isLoadingSession,isSessionError,+ isSessionNotFound,createSession,isCreatingSession,refetchSession,@@ -415,6 +416,7 @@ export function useCopilotPage() {isUserStopping,isLoadingSession,isSessionError,+ isSessionNotFound,isCreatingSession,isUploadingFiles,pendingSend,