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): resolve auth before showing expired-session errors (#13357)
Lucas Ma66dc6d48b473
diff --git a/autogpt_platform/frontend/src/app/(platform)/error/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/error/__tests__/page.test.tsxnew file mode 100644index 0000000000..5406e38263--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/error/__tests__/page.test.tsx@@ -0,0 +1,137 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import ErrorPage from "../page";++let searchMessage: string | null = null;+let authState = {+ isUserLoading: false,+ isLoggedIn: false,+};+const replaceMock = vi.fn();++vi.mock("next/navigation", () => ({+ useSearchParams: () => ({+ get: (key: string) => (key === "message" ? searchMessage : null),+ }),+ useRouter: () => ({+ replace: replaceMock,+ }),+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => authState,+}));++describe("ErrorPage", () => {+ afterEach(() => {+ searchMessage = null;+ authState = {+ isUserLoading: false,+ isLoggedIn: false,+ };+ replaceMock.mockClear();+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("redirects logged-out users away from the session expired screen", async () => {+ searchMessage = "session-expired";++ render(<ErrorPage />);++ await waitFor(() => {+ expect(replaceMock).toHaveBeenCalledWith("/login");+ });+ });++ it("keeps the session expired screen for authenticated users", async () => {+ searchMessage = "session-expired";+ authState = {+ isUserLoading: false,+ isLoggedIn: true,+ };++ render(<ErrorPage />);++ await waitFor(() => {+ expect(screen.queryByText(/Your session has expired/)).not.toBeNull();+ });++ expect(replaceMock).not.toHaveBeenCalled();+ });++ it("waits for authentication before showing an expired session or redirecting", () => {+ searchMessage = "session-expired";+ authState = { isUserLoading: true, isLoggedIn: false };++ const { rerender } = render(<ErrorPage />);+ expect(screen.queryByText(/Your session has expired/)).toBeNull();+ expect(replaceMock).not.toHaveBeenCalled();++ authState = { isUserLoading: false, isLoggedIn: false };+ rerender(<ErrorPage />);+ expect(replaceMock).toHaveBeenCalledWith("/login");+ });++ it("preserves unrelated errors for logged-out users", () => {+ searchMessage = "server-error";+ render(<ErrorPage />);+ expect(+ screen.queryByText(/Our servers are experiencing issues/),+ ).not.toBeNull();+ expect(replaceMock).not.toHaveBeenCalled();+ });++ it.each([+ "session-expired",+ "auth-failed",+ "auth-token-invalid",+ "user-creation-failed",+ ])(+ "restarts authentication for %s when cached auth still says logged in",+ (message) => {+ const navigate = vi+ .spyOn(window.location, "replace")+ .mockImplementation(() => {});+ searchMessage = message;+ authState = { isUserLoading: false, isLoggedIn: true };+ render(<ErrorPage />);++ fireEvent.click(screen.getByRole("button", { name: "Try Again" }));++ expect(navigate).toHaveBeenCalledExactlyOnceWith("/login");+ expect(replaceMock).not.toHaveBeenCalled();+ },+ );++ it("returns home when retrying a general server error", () => {+ searchMessage = "server-error";+ render(<ErrorPage />);++ fireEvent.click(screen.getByRole("button", { name: "Try Again" }));++ expect(replaceMock).toHaveBeenCalledExactlyOnceWith("/");+ });++ it("waits before retrying a rate-limited request", () => {+ vi.useFakeTimers();+ const reload = vi+ .spyOn(window.location, "reload")+ .mockImplementation(() => {});+ searchMessage = "rate-limited";+ render(<ErrorPage />);++ fireEvent.click(screen.getByRole("button", { name: "Try Again" }));+ expect(reload).not.toHaveBeenCalled();+ act(() => vi.advanceTimersByTime(2000));++ expect(reload).toHaveBeenCalledTimes(1);+ expect(replaceMock).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/error/page.tsx b/autogpt_platform/frontend/src/app/(platform)/error/page.tsxindex 3cf68178ad..9f60a97f9b 100644--- a/autogpt_platform/frontend/src/app/(platform)/error/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/error/page.tsx@@ -1,38 +1,19 @@"use client";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";-import { useSearchParams } from "next/navigation";import { Suspense } from "react";-import { getErrorDetails } from "./helpers";+import { useErrorPage } from "./useErrorPage";function ErrorPageContent() {- const searchParams = useSearchParams();- const errorMessage = searchParams.get("message");- const errorDetails = getErrorDetails(errorMessage);+ const { errorDetails, hideSessionError, handleRetry } = useErrorPage();- function handleRetry() {- // Auth-related errors should redirect to login- if (- errorMessage === "user-creation-failed" ||- errorMessage === "auth-failed" ||- errorMessage === "auth-token-invalid" ||- errorMessage === "session-expired"- ) {- window.location.href = "/login";- } else if (errorMessage === "rate-limited") {- // For rate limiting, wait a moment then try again- setTimeout(() => {- window.location.reload();- }, 2000);- } else {- // For server/network errors, go to home- window.location.href = "/";- }+ if (hideSessionError) {+ return null;}return (<div className="flex min-h-screen items-center justify-center bg-gray-50 px-4 py-12 sm:px-6 lg:px-8">- <div className="relative w-full max-w-xl lg:bottom-[4rem]">+ <div className="relative w-full max-w-xl"><ErrorCardresponseError={errorDetails.responseError}context={errorDetails.context}@@ -48,7 +29,7 @@ export default function ErrorPage() {<Suspensefallback={<div className="flex min-h-screen items-center justify-center bg-gray-50 px-4 py-12 sm:px-6 lg:px-8">- <div className="relative w-full max-w-xl lg:-top-[4rem]">+ <div className="relative w-full max-w-xl"><ErrorCardresponseError={{ message: "Loading..." }}context="application"diff --git a/autogpt_platform/frontend/src/app/(platform)/error/useErrorPage.ts b/autogpt_platform/frontend/src/app/(platform)/error/useErrorPage.tsnew file mode 100644index 0000000000..71afed2a07--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/error/useErrorPage.ts@@ -0,0 +1,38 @@+import { useAuth } from "@/lib/auth/hooks/useAuth";+import { useRouter, useSearchParams } from "next/navigation";+import { useEffect } from "react";+import { getErrorDetails } from "./helpers";++export function useErrorPage() {+ const searchParams = useSearchParams();+ const router = useRouter();+ const { isLoggedIn, isUserLoading } = useAuth();+ const errorMessage = searchParams.get("message");+ const expiredSession = errorMessage === "session-expired";+ const redirectToLogin = expiredSession && !isUserLoading && !isLoggedIn;++ useEffect(() => {+ if (redirectToLogin) router.replace("/login");+ }, [router, redirectToLogin]);++ function handleRetry() {+ if (+ errorMessage === "user-creation-failed" ||+ errorMessage === "auth-failed" ||+ errorMessage === "auth-token-invalid" ||+ expiredSession+ ) {+ window.location.replace("/login");+ } else if (errorMessage === "rate-limited") {+ setTimeout(() => window.location.reload(), 2000);+ } else {+ router.replace("/");+ }+ }++ return {+ errorDetails: getErrorDetails(errorMessage),+ hideSessionError: expiredSession && (isUserLoading || !isLoggedIn),+ handleRetry,+ };+}