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): drop /signup → / hop that flashes /copilot before /onboarding (#13154)

Ubbe270cd1eeb558
diff --git a/autogpt_platform/frontend/src/app/(platform)/login/__tests__/auth-redirect.test.tsx b/autogpt_platform/frontend/src/app/(platform)/login/__tests__/auth-redirect.test.tsx
new file mode 100644
index 0000000000..8727b32f05
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/login/__tests__/auth-redirect.test.tsx
@@ -0,0 +1,65 @@
+import { render, waitFor } from "@testing-library/react";
+import { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import LoginPage from "../page";
+
+const routerReplace = vi.fn();
+const routerPush = vi.fn();
+let mockSearchParams = new URLSearchParams();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ replace: routerReplace,
+ push: routerPush,
+ refresh: vi.fn(),
+ }),
+ useSearchParams: () => mockSearchParams,
+ usePathname: () => "/login",
+}));
+
+let mockIsLoggedIn = true;
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({
+ supabase: {},
+ user: { id: "u" },
+ isUserLoading: false,
+ isLoggedIn: mockIsLoggedIn,
+ }),
+}));
+
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("../actions", () => ({
+ login: vi.fn(),
+}));
+
+describe("LoginPage auth-redirect useEffect", () => {
+ beforeEach(() => {
+ routerReplace.mockClear();
+ routerPush.mockClear();
+ mockSearchParams = new URLSearchParams();
+ mockIsLoggedIn = true;
+ });
+
+ test("with a safe ?next= deep link, redirects there via router.replace", async () => {
+ mockSearchParams = new URLSearchParams({ next: "/library" });
+ render(<LoginPage />);
+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/library"));
+ expect(routerPush).not.toHaveBeenCalled();
+ });
+
+ test("with no ?next=, defers to OnboardingProvider instead of bouncing through /", async () => {
+ render(<LoginPage />);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(routerReplace).not.toHaveBeenCalled();
+ expect(routerPush).not.toHaveBeenCalled();
+ });
+
+ test("an unsafe ?next= (absolute URL) is dropped — no redirect", async () => {
+ mockSearchParams = new URLSearchParams({ next: "//evil.site" });
+ render(<LoginPage />);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(routerReplace).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts b/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts
index ede01371ef..db44dcb34c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts
@@ -1,4 +1,5 @@
import { useToast } from "@/components/molecules/Toast/use-toast";
+import { sanitizeAuthNext } from "@/lib/auth-redirect";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { environment } from "@/services/environment";
import { loginFormSchema, LoginProvider } from "@/types/auth";
@@ -21,18 +22,18 @@ export function useLoginPage() {
const [showNotAllowedModal, setShowNotAllowedModal] = useState(false);
const isCloudEnv = environment.isCloud();
- // Get redirect destination from 'next' query parameter.
- // Only allow relative paths to prevent open redirect attacks
- // (e.g., /login?next=https://phishing.site).
- const rawNext = searchParams.get("next");
- const nextUrl =
- rawNext && rawNext.startsWith("/") && !rawNext.startsWith("//")
- ? rawNext
- : null;
+ // Same-origin redirect target; off-site values are dropped so a crafted
+ // `/login?next=https://phishing.site` cannot redirect users elsewhere.
+ const nextUrl = sanitizeAuthNext(searchParams.get("next"));
+ // Only honour explicit `?next=` deep links here. Generic "already logged in
+ // on /login, get me out" is handled by OnboardingProvider so the user lands
+ // straight on /onboarding or /copilot. Otherwise we'd bounce
+ // /login → / → /copilot → /onboarding, and each hop renders before the next
+ // redirect — that intermediate /copilot render is the flash users see.
useEffect(() => {
- if (isLoggedIn && !isLoggingIn) {
- router.push(nextUrl || "/");
+ if (isLoggedIn && !isLoggingIn && nextUrl) {
+ router.replace(nextUrl);
}
}, [isLoggedIn, isLoggingIn, nextUrl, router]);
diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/__tests__/auth-redirect.test.tsx b/autogpt_platform/frontend/src/app/(platform)/signup/__tests__/auth-redirect.test.tsx
new file mode 100644
index 0000000000..4acf0dcf16
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/signup/__tests__/auth-redirect.test.tsx
@@ -0,0 +1,70 @@
+import { render, waitFor } from "@testing-library/react";
+import { ReactNode } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import SignupPage from "../page";
+
+const routerReplace = vi.fn();
+const routerPush = vi.fn();
+let mockSearchParams = new URLSearchParams();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ replace: routerReplace,
+ push: routerPush,
+ refresh: vi.fn(),
+ }),
+ useSearchParams: () => mockSearchParams,
+ usePathname: () => "/signup",
+}));
+
+let mockIsLoggedIn = true;
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({
+ supabase: {},
+ user: { id: "u" },
+ isUserLoading: false,
+ isLoggedIn: mockIsLoggedIn,
+ }),
+}));
+
+// Keep OnboardingProvider out of this test — we're isolating the auth-redirect
+// useEffect here. Provider behaviour is covered in
+// `src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsx`.
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("../actions", () => ({
+ signup: vi.fn(),
+}));
+
+describe("SignupPage auth-redirect useEffect", () => {
+ beforeEach(() => {
+ routerReplace.mockClear();
+ routerPush.mockClear();
+ mockSearchParams = new URLSearchParams();
+ mockIsLoggedIn = true;
+ });
+
+ test("with a safe ?next= deep link, redirects there via router.replace", async () => {
+ mockSearchParams = new URLSearchParams({ next: "/library" });
+ render(<SignupPage />);
+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/library"));
+ expect(routerPush).not.toHaveBeenCalled();
+ });
+
+ test("with no ?next= the page stays put and defers to OnboardingProvider", async () => {
+ // Before this PR, this case pushed to "/" which bounced through /copilot
+ // before OnboardingProvider could redirect — the flash users reported.
+ render(<SignupPage />);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(routerReplace).not.toHaveBeenCalled();
+ expect(routerPush).not.toHaveBeenCalled();
+ });
+
+ test("an unsafe ?next= (absolute URL) is dropped — no redirect", async () => {
+ mockSearchParams = new URLSearchParams({ next: "https://phishing.site" });
+ render(<SignupPage />);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(routerReplace).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts b/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts
index 0a7c4f437d..3676ce5698 100644
--- a/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts
@@ -1,4 +1,5 @@
import { useToast } from "@/components/molecules/Toast/use-toast";
+import { sanitizeAuthNext } from "@/lib/auth-redirect";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { environment } from "@/services/environment";
import { LoginProvider, signupFormSchema } from "@/types/auth";
@@ -21,12 +22,18 @@ export function useSignupPage() {
const [showNotAllowedModal, setShowNotAllowedModal] = useState(false);
const isCloudEnv = environment.isCloud();
- // Get redirect destination from 'next' query parameter
- const nextUrl = searchParams.get("next");
+ // Same-origin redirect target; off-site values are dropped so a crafted
+ // `/signup?next=https://phishing.site` cannot redirect users elsewhere.
+ const nextUrl = sanitizeAuthNext(searchParams.get("next"));
+ // Only honour explicit `?next=` deep links here. Generic "already logged in
+ // on /signup, get me out" is handled by OnboardingProvider so the user lands
+ // straight on /onboarding or /copilot. Otherwise we'd bounce
+ // /signup → / → /copilot → /onboarding, and each hop renders before the next
+ // redirect — that intermediate /copilot render is the flash users see.
useEffect(() => {
- if (isLoggedIn && !isSigningUp) {
- router.push(nextUrl || "/");
+ if (isLoggedIn && !isSigningUp && nextUrl) {
+ router.replace(nextUrl);
}
}, [isLoggedIn, isSigningUp, nextUrl, router]);
diff --git a/autogpt_platform/frontend/src/lib/auth-redirect.test.ts b/autogpt_platform/frontend/src/lib/auth-redirect.test.ts
new file mode 100644
index 0000000000..8e645384d9
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth-redirect.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, test } from "vitest";
+import { sanitizeAuthNext } from "./auth-redirect";
+
+describe("sanitizeAuthNext", () => {
+ test("returns null when the param is missing or empty", () => {
+ expect(sanitizeAuthNext(null)).toBeNull();
+ expect(sanitizeAuthNext(undefined)).toBeNull();
+ expect(sanitizeAuthNext("")).toBeNull();
+ });
+
+ test("rejects absolute URLs and other off-site redirects", () => {
+ expect(sanitizeAuthNext("https://phishing.site")).toBeNull();
+ expect(sanitizeAuthNext("http://example.com/path")).toBeNull();
+ expect(sanitizeAuthNext("javascript:alert(1)")).toBeNull();
+ expect(sanitizeAuthNext("mailto:[email protected]")).toBeNull();
+ });
+
+ test("rejects protocol-relative paths so `//evil.com` cannot redirect off-site", () => {
+ expect(sanitizeAuthNext("//evil.com")).toBeNull();
+ expect(sanitizeAuthNext("//evil.com/foo")).toBeNull();
+ });
+
+ test("rejects paths that do not start with /", () => {
+ expect(sanitizeAuthNext("library")).toBeNull();
+ expect(sanitizeAuthNext("..\\evil")).toBeNull();
+ });
+
+ test("accepts same-origin relative paths verbatim", () => {
+ expect(sanitizeAuthNext("/library")).toBe("/library");
+ expect(sanitizeAuthNext("/onboarding?step=2")).toBe("/onboarding?step=2");
+ expect(sanitizeAuthNext("/copilot#section")).toBe("/copilot#section");
+ expect(sanitizeAuthNext("/")).toBe("/");
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/auth-redirect.ts b/autogpt_platform/frontend/src/lib/auth-redirect.ts
new file mode 100644
index 0000000000..d61ffc74b7
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/auth-redirect.ts
@@ -0,0 +1,19 @@
+/**
+ * Sanitize the `?next=` query parameter used by auth flows (`/login`, `/signup`)
+ * to redirect users after authentication.
+ *
+ * Only accept same-origin relative paths starting with a single `/`. Reject
+ * absolute URLs and protocol-relative paths (`//host`) so a crafted
+ * `/login?next=https://phishing.site` cannot redirect users off-site.
+ *
+ * Returns `null` when the value is missing, empty, or unsafe — callers should
+ * fall back to their default destination in that case.
+ */
+export function sanitizeAuthNext(
+ rawNext: string | null | undefined,
+): string | null {
+ if (!rawNext) return null;
+ if (!rawNext.startsWith("/")) return null;
+ if (rawNext.startsWith("//")) return null;
+ return rawNext;
+}
diff --git a/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsx b/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsx
new file mode 100644
index 0000000000..cd977675ca
--- /dev/null
+++ b/autogpt_platform/frontend/src/providers/onboarding/__tests__/onboarding-provider-routing.test.tsx
@@ -0,0 +1,157 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { render, waitFor } from "@testing-library/react";
+import OnboardingProvider from "../onboarding-provider";
+
+const routerReplace = vi.fn();
+let mockPathname = "/signup";
+let mockSearchParams = new URLSearchParams();
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ replace: routerReplace,
+ push: vi.fn(),
+ refresh: vi.fn(),
+ }),
+ useSearchParams: () => mockSearchParams,
+ usePathname: () => mockPathname,
+}));
+
+let mockIsLoggedIn = true;
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: () => ({
+ isLoggedIn: mockIsLoggedIn,
+ isUserLoading: false,
+ user: mockIsLoggedIn ? { id: "test-user", email: "[email protected]" } : null,
+ }),
+}));
+
+vi.mock("@/lib/autogpt-server-api/context", () => ({
+ useBackendAPI: () => ({
+ onWebSocketMessage: () => () => {},
+ connectWebSocket: () => {},
+ }),
+}));
+
+vi.mock("@/hooks/useOnboardingTimezoneDetection", () => ({
+ useOnboardingTimezoneDetection: () => undefined,
+}));
+
+let mockIsCompleted = false;
+const completedCallCount = { value: 0 };
+vi.mock("@/app/api/__generated__/endpoints/onboarding/onboarding", () => ({
+ getV1CheckIfOnboardingIsCompleted: () => {
+ completedCallCount.value += 1;
+ return Promise.resolve({
+ status: 200,
+ data: { is_completed: mockIsCompleted },
+ });
+ },
+ getV1OnboardingState: () =>
+ Promise.resolve({ status: 200, data: { completedSteps: [] } }),
+ patchV1UpdateOnboardingState: () => Promise.resolve({ status: 200 }),
+ postV1CompleteOnboardingStep: () => Promise.resolve({ status: 200 }),
+}));
+
+describe("OnboardingProvider routing — logged-in user", () => {
+ beforeEach(() => {
+ routerReplace.mockClear();
+ mockSearchParams = new URLSearchParams();
+ mockPathname = "/signup";
+ mockIsLoggedIn = true;
+ mockIsCompleted = false;
+ completedCallCount.value = 0;
+ });
+
+ test("incomplete user on /signup is redirected to /onboarding", async () => {
+ mockPathname = "/signup";
+ mockIsCompleted = false;
+
+ render(
+ <OnboardingProvider>
+ <div data-testid="child" />
+ </OnboardingProvider>,
+ );
+
+ await waitFor(() =>
+ expect(routerReplace).toHaveBeenCalledWith("/onboarding"),
+ );
+ });
+
+ test("completed user on /signup is redirected to /copilot", async () => {
+ mockPathname = "/signup";
+ mockIsCompleted = true;
+
+ render(
+ <OnboardingProvider>
+ <div data-testid="child" />
+ </OnboardingProvider>,
+ );
+
+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/copilot"));
+ });
+
+ test("completed user on /login is redirected to /copilot", async () => {
+ mockPathname = "/login";
+ mockIsCompleted = true;
+
+ render(
+ <OnboardingProvider>
+ <div data-testid="child" />
+ </OnboardingProvider>,
+ );
+
+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/copilot"));
+ });
+
+ test("a safe ?next= deep link defers to the auth page — no redirect from provider", async () => {
+ mockPathname = "/login";
+ mockSearchParams = new URLSearchParams({ next: "/library" });
+ mockIsCompleted = true;
+
+ render(
+ <OnboardingProvider>
+ <div data-testid="child" />
+ </OnboardingProvider>,
+ );
+
+ // Wait long enough for any pending async redirect to land
+ await new Promise((r) => setTimeout(r, 30));
+ expect(routerReplace).not.toHaveBeenCalled();
+ // The completion check should also be skipped — we never hit the API.
+ expect(completedCallCount.value).toBe(0);
+ });
+
+ test("an unsafe ?next= value is treated as no deep link and the provider routes normally", async () => {
+ // `sanitizeAuthNext` drops absolute URLs as null. Without the alignment
+ // fix, OnboardingProvider would defer (assuming the auth page handles it)
+ // while the auth page silently drops the value — deadlocking the user.
+ mockPathname = "/signup";
+ mockSearchParams = new URLSearchParams({ next: "https://phishing.site" });
+ mockIsCompleted = false;
+
+ render(
+ <OnboardingProvider>
+ <div data-testid="child" />
+ </OnboardingProvider>,
+ );
+
+ await waitFor(() =>
+ expect(routerReplace).toHaveBeenCalledWith("/onboarding"),
+ );
+ });
+
+ test("incomplete user already on /onboarding stays put", async () => {
+ mockPathname = "/onboarding";
+ mockIsCompleted = false;
+
+ render(
+ <OnboardingProvider>
+ <div data-testid="child" />
+ </OnboardingProvider>,
+ );
+
+ // Give async work time to resolve, then assert no redirect.
+ await new Promise((r) => setTimeout(r, 30));
+ expect(routerReplace).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/providers/onboarding/helpers.test.ts b/autogpt_platform/frontend/src/providers/onboarding/helpers.test.ts
new file mode 100644
index 0000000000..e4e3f36cdd
--- /dev/null
+++ b/autogpt_platform/frontend/src/providers/onboarding/helpers.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, test } from "vitest";
+import {
+ decideOnboardingRedirect,
+ shouldRedirectFromOnboarding,
+} from "./helpers";
+
+describe("shouldRedirectFromOnboarding", () => {
+ test("returns true once VISIT_COPILOT is completed", () => {
+ expect(shouldRedirectFromOnboarding(["VISIT_COPILOT"], "/onboarding")).toBe(
+ true,
+ );
+ });
+
+ test("returns false when VISIT_COPILOT is missing", () => {
+ expect(shouldRedirectFromOnboarding([], "/onboarding")).toBe(false);
+ });
+
+ test("does not redirect away from /onboarding/reset", () => {
+ expect(
+ shouldRedirectFromOnboarding(["VISIT_COPILOT"], "/onboarding/reset"),
+ ).toBe(false);
+ });
+});
+
+describe("decideOnboardingRedirect", () => {
+ // Defaults — most tests vary one bit at a time.
+ const base = {
+ isCompleted: false,
+ isOnOnboardingRoute: false,
+ isOnAuthRoute: false,
+ hasPendingAuthDeepLink: false,
+ };
+
+ test("pending deep link defers to the auth page (returns null)", () => {
+ // Both completed and incomplete users must yield — the auth page's
+ // `router.replace(nextUrl)` is in flight and we must not clobber it.
+ expect(
+ decideOnboardingRedirect({
+ ...base,
+ isOnAuthRoute: true,
+ hasPendingAuthDeepLink: true,
+ }),
+ ).toBeNull();
+ expect(
+ decideOnboardingRedirect({
+ ...base,
+ isCompleted: true,
+ isOnAuthRoute: true,
+ hasPendingAuthDeepLink: true,
+ }),
+ ).toBeNull();
+ });
+
+ test("incomplete user on any non-onboarding route is sent to /onboarding", () => {
+ // /signup, /login, /copilot, /library — all should funnel to /onboarding.
+ expect(decideOnboardingRedirect(base)).toBe("/onboarding");
+ expect(decideOnboardingRedirect({ ...base, isOnAuthRoute: true })).toBe(
+ "/onboarding",
+ );
+ });
+
+ test("incomplete user already on /onboarding stays put", () => {
+ expect(
+ decideOnboardingRedirect({ ...base, isOnOnboardingRoute: true }),
+ ).toBeNull();
+ });
+
+ test("completed user on /onboarding is sent to /copilot", () => {
+ expect(
+ decideOnboardingRedirect({
+ ...base,
+ isCompleted: true,
+ isOnOnboardingRoute: true,
+ }),
+ ).toBe("/copilot");
+ });
+
+ test("completed user on /signup or /login is sent to /copilot", () => {
+ expect(
+ decideOnboardingRedirect({
+ ...base,
+ isCompleted: true,
+ isOnAuthRoute: true,
+ }),
+ ).toBe("/copilot");
+ });
+
+ test("completed user already on the product is left alone", () => {
+ // E.g., /copilot, /library — no redirect needed.
+ expect(decideOnboardingRedirect({ ...base, isCompleted: true })).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/providers/onboarding/helpers.ts b/autogpt_platform/frontend/src/providers/onboarding/helpers.ts
index e4de39cd9c..6ddd71676a 100644
--- a/autogpt_platform/frontend/src/providers/onboarding/helpers.ts
+++ b/autogpt_platform/frontend/src/providers/onboarding/helpers.ts
@@ -41,6 +41,34 @@ export function shouldRedirectFromOnboarding(
);
}
+/**
+ * Decide where to route a logged-in user once we know their onboarding
+ * completion state.
+ *
+ * Returns the destination path, or `null` to leave the user where they are.
+ * `null` covers two distinct cases:
+ * 1. A pending `?next=…` deep link — the auth page will handle it, so we
+ * must not race it.
+ * 2. The user is already on the right surface (incomplete on /onboarding,
+ * completed on any non-auth/non-onboarding page).
+ */
+export function decideOnboardingRedirect({
+ isCompleted,
+ isOnOnboardingRoute,
+ isOnAuthRoute,
+ hasPendingAuthDeepLink,
+}: {
+ isCompleted: boolean;
+ isOnOnboardingRoute: boolean;
+ isOnAuthRoute: boolean;
+ hasPendingAuthDeepLink: boolean;
+}): "/onboarding" | "/copilot" | null {
+ if (hasPendingAuthDeepLink) return null;
+ if (!isCompleted && !isOnOnboardingRoute) return "/onboarding";
+ if (isCompleted && (isOnOnboardingRoute || isOnAuthRoute)) return "/copilot";
+ return null;
+}
+
export function updateOnboardingState(
prevState: UserOnboarding | null,
newState: LocalOnboardingStateUpdate,
diff --git a/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx b/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx
index 08e26871af..a1b6aef7f6 100644
--- a/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/onboarding/onboarding-provider.tsx
@@ -9,6 +9,7 @@ import { PostV1CompleteOnboardingStepStep } from "@/app/api/__generated__/models
import { resolveResponse } from "@/app/api/helpers";
import { useToast } from "@/components/molecules/Toast/use-toast";
import { useOnboardingTimezoneDetection } from "@/hooks/useOnboardingTimezoneDetection";
+import { sanitizeAuthNext } from "@/lib/auth-redirect";
import {
ApiError,
UserOnboarding,
@@ -16,7 +17,7 @@ import {
} from "@/lib/autogpt-server-api";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
-import { usePathname, useRouter } from "next/navigation";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
createContext,
ReactNode,
@@ -27,6 +28,7 @@ import {
useState,
} from "react";
import {
+ decideOnboardingRedirect,
fromBackendUserOnboarding,
LocalOnboardingStateUpdate,
shouldRedirectFromOnboarding,
@@ -90,6 +92,7 @@ export default function OnboardingProvider({
const api = useBackendAPI();
const pathname = usePathname();
+ const searchParams = useSearchParams();
const router = useRouter();
const { isLoggedIn } = useSupabase();
@@ -112,6 +115,19 @@ export default function OnboardingProvider({
}, []);
const isOnOnboardingRoute = pathname.startsWith("/onboarding");
+ // Logged-in users sitting on the auth pages need to be routed onward by us;
+ // otherwise the signup/login pages show their `isLoggedIn` loader forever.
+ // Handling them here (instead of in useSignupPage/useLoginPage) avoids the
+ // /signup → / → /copilot → /onboarding bounce that flashes /copilot.
+ const isOnAuthRoute = pathname === "/signup" || pathname === "/login";
+ // When `/login?next=/profile` is hit, useLoginPage/useSignupPage fires its
+ // own redirect to the requested target. Skip our redirect in that window so
+ // the deep link isn't clobbered by the awaited completion check. Sanitize
+ // with the same helper the auth pages use — otherwise an unsafe value (e.g.
+ // `?next=https://evil.site`) would defer us here while the auth page drops
+ // it as `null`, deadlocking the user on the auth loader.
+ const hasPendingAuthDeepLink =
+ isOnAuthRoute && sanitizeAuthNext(searchParams.get("next")) !== null;
const fetchOnboarding = useCallback(async () => {
const onboarding = await resolveResponse(getV1OnboardingState());
@@ -122,12 +138,30 @@ export default function OnboardingProvider({
return processedOnboarding;
}, []);
+ // If a logged-in user navigates back to /signup or /login after the
+ // initialize-once effect already ran (e.g., browser back from /onboarding,
+ // manual URL edit), the guard below would early-return and leave them
+ // stranded on the auth page's `isLoggedIn` loader. Reset the guard on
+ // re-entry so the main effect re-runs and routes them away.
+ useEffect(() => {
+ if (isLoggedIn && isOnAuthRoute) {
+ hasInitialized.current = false;
+ }
+ }, [isLoggedIn, isOnAuthRoute]);
+
useEffect(() => {
// Prevent multiple initializations
if (hasInitialized.current || !isLoggedIn) {
return;
}
+ // Defer to the auth-page's own deep-link redirect (`?next=…`) instead of
+ // racing it. Don't mark hasInitialized so the next pathname change
+ // (after the auth page redirects) gets us properly initialized.
+ if (hasPendingAuthDeepLink) {
+ return;
+ }
+
hasInitialized.current = true;
async function initializeOnboarding() {
@@ -136,11 +170,14 @@ export default function OnboardingProvider({
getV1CheckIfOnboardingIsCompleted(),
);
- if (!is_completed && !isOnOnboardingRoute) {
- router.replace("/onboarding");
- return;
- } else if (is_completed && isOnOnboardingRoute) {
- router.replace("/copilot");
+ const redirectTarget = decideOnboardingRedirect({
+ isCompleted: is_completed,
+ isOnOnboardingRoute,
+ isOnAuthRoute,
+ hasPendingAuthDeepLink,
+ });
+ if (redirectTarget) {
+ router.replace(redirectTarget);
return;
}
@@ -171,7 +208,15 @@ export default function OnboardingProvider({
}
initializeOnboarding();
- }, [api, isOnOnboardingRoute, router, isLoggedIn, pathname]);
+ }, [
+ api,
+ isOnOnboardingRoute,
+ isOnAuthRoute,
+ hasPendingAuthDeepLink,
+ router,
+ isLoggedIn,
+ pathname,
+ ]);
const handleOnboardingNotification = useCallback(
(notification: WebSocketNotification) => {