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.

feat: Frontend platform linking page (/link/{token}) (#12624)

Bently27624a6a1cfb
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..b254139ca2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/helpers.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "vitest";
+
+import { LinkType } from "@/app/api/__generated__/models/linkType";
+import {
+ getLoginRedirect,
+ getPlatformDisplayName,
+ isUserLink,
+ TOKEN_PATTERN,
+} from "../helpers";
+
+describe("platform linking helpers", () => {
+ test("accepts URL-safe token values up to the backend limit", () => {
+ expect(TOKEN_PATTERN.test("abc_123-XYZ")).toBe(true);
+ expect(TOKEN_PATTERN.test("a".repeat(64))).toBe(true);
+ });
+
+ test("rejects malformed token values", () => {
+ expect(TOKEN_PATTERN.test("")).toBe(false);
+ expect(TOKEN_PATTERN.test("a".repeat(65))).toBe(false);
+ expect(TOKEN_PATTERN.test("abc.123")).toBe(false);
+ expect(TOKEN_PATTERN.test("abc/123")).toBe(false);
+ });
+
+ test("formats known platforms and falls back for unknown values", () => {
+ expect(getPlatformDisplayName("discord")).toBe("Discord");
+ expect(getPlatformDisplayName("GITHUB")).toBe("GitHub");
+ expect(getPlatformDisplayName("matrix")).toBe("matrix");
+ expect(getPlatformDisplayName(null)).toBe("chat platform");
+ });
+
+ test("builds the login redirect for valid and missing tokens", () => {
+ expect(getLoginRedirect("token-123")).toBe(
+ "/login?next=%2Flink%2Ftoken-123",
+ );
+ expect(getLoginRedirect(null)).toBe("/login?next=%2F");
+ });
+
+ test("identifies user link token types", () => {
+ expect(isUserLink(LinkType.USER)).toBe(true);
+ expect(isUserLink(LinkType.SERVER)).toBe(false);
+ expect(isUserLink(undefined)).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx
new file mode 100644
index 0000000000..c4f36c4fa1
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx
@@ -0,0 +1,273 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { LinkType } from "@/app/api/__generated__/models/linkType";
+import {
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200,
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler401,
+ getPostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticatedMockHandler200,
+ getPostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticatedMockHandler401,
+ getPostPlatformLinkingConfirmAUserLinkTokenUserMustBeAuthenticatedMockHandler200,
+} from "@/app/api/__generated__/endpoints/platform-linking/platform-linking.msw";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import PlatformLinkPage from "../page";
+
+const mockUseParams = vi.hoisted(() => vi.fn());
+const mockUseSearchParams = vi.hoisted(() => vi.fn());
+const mockUseSupabase = vi.hoisted(() => vi.fn());
+const mockLogOut = vi.hoisted(() => vi.fn());
+
+vi.mock("next/navigation", () => ({
+ useParams: mockUseParams,
+ usePathname: () => "/link/token-123",
+ useRouter: () => ({
+ back: vi.fn(),
+ forward: vi.fn(),
+ prefetch: vi.fn(),
+ push: vi.fn(),
+ refresh: vi.fn(),
+ replace: vi.fn(),
+ }),
+ useSearchParams: mockUseSearchParams,
+}));
+
+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({
+ useSupabase: mockUseSupabase,
+}));
+
+function authenticate() {
+ mockUseSupabase.mockReturnValue({
+ user: {
+ id: "user-1",
+ email: "[email protected]",
+ app_metadata: {},
+ user_metadata: {},
+ aud: "authenticated",
+ created_at: "2026-01-01T00:00:00.000Z",
+ },
+ isLoggedIn: true,
+ isUserLoading: false,
+ logOut: mockLogOut,
+ supabase: {},
+ });
+}
+
+function setRoute(token = "token-123", platform = "discord") {
+ mockUseParams.mockReturnValue({ token });
+ mockUseSearchParams.mockReturnValue(new URLSearchParams({ platform }));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ authenticate();
+ setRoute();
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: { href: "http://localhost/link/token-123" },
+ });
+});
+
+describe("PlatformLinkPage", () => {
+ test("shows a malformed-token error without fetching link info", () => {
+ const infoHandler = vi.fn();
+ setRoute("bad.token");
+ server.use(
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200(() => {
+ infoHandler();
+ return {
+ platform: "DISCORD",
+ link_type: LinkType.SERVER,
+ server_name: "Guild",
+ };
+ }),
+ );
+
+ render(<PlatformLinkPage />);
+
+ expect(screen.getByText(/setup link is malformed/i)).toBeDefined();
+ expect(infoHandler).not.toHaveBeenCalled();
+ });
+
+ test("asks unauthenticated users to sign in without fetching link info", () => {
+ const infoHandler = vi.fn();
+ mockUseSupabase.mockReturnValue({
+ user: null,
+ isLoggedIn: false,
+ isUserLoading: false,
+ logOut: mockLogOut,
+ supabase: {},
+ });
+ server.use(
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200(() => {
+ infoHandler();
+ return {
+ platform: "DISCORD",
+ link_type: LinkType.SERVER,
+ server_name: "Guild",
+ };
+ }),
+ );
+
+ render(<PlatformLinkPage />);
+
+ expect(
+ screen.getByRole("heading", { name: /sign in to continue/i }),
+ ).toBeDefined();
+ expect(
+ screen.getByRole("link", { name: /^sign in$/i }).getAttribute("href"),
+ ).toBe("/login?next=%2Flink%2Ftoken-123");
+ expect(infoHandler).not.toHaveBeenCalled();
+ });
+
+ test("loads server link details and confirms the server link", async () => {
+ server.use(
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({
+ platform: "DISCORD",
+ link_type: LinkType.SERVER,
+ server_name: "Builders Guild",
+ }),
+ getPostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticatedMockHandler200(
+ {
+ success: true,
+ link_type: LinkType.SERVER,
+ platform: "DISCORD",
+ platform_server_id: "server-1",
+ server_name: "Builders Guild",
+ },
+ ),
+ );
+
+ render(<PlatformLinkPage />);
+
+ expect(
+ await screen.findByRole("heading", {
+ name: /set up autopilot for builders guild/i,
+ }),
+ ).toBeDefined();
+ expect(screen.getByText(/signed in as [email protected]/i)).toBeDefined();
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect discord to autogpt/i }),
+ );
+
+ expect(
+ await screen.findByRole("heading", { name: /autopilot is ready/i }),
+ ).toBeDefined();
+ expect(screen.getByText(/builders guild/i)).toBeDefined();
+ });
+
+ test("loads user link details and confirms the user link endpoint", async () => {
+ let serverConfirmCalls = 0;
+ let userConfirmCalls = 0;
+ server.use(
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({
+ platform: "TELEGRAM",
+ link_type: LinkType.USER,
+ server_name: null,
+ }),
+ getPostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticatedMockHandler200(
+ () => {
+ serverConfirmCalls += 1;
+ return {
+ success: true,
+ link_type: LinkType.SERVER,
+ platform: "TELEGRAM",
+ platform_server_id: "server-1",
+ server_name: null,
+ };
+ },
+ ),
+ getPostPlatformLinkingConfirmAUserLinkTokenUserMustBeAuthenticatedMockHandler200(
+ () => {
+ userConfirmCalls += 1;
+ return {
+ success: true,
+ link_type: LinkType.USER,
+ platform: "TELEGRAM",
+ platform_user_id: "platform-user-1",
+ };
+ },
+ ),
+ );
+
+ render(<PlatformLinkPage />);
+
+ expect(
+ await screen.findByRole("heading", { name: /link your telegram dms/i }),
+ ).toBeDefined();
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect my telegram dms/i }),
+ );
+
+ expect(
+ await screen.findByRole("heading", { name: /autopilot is ready/i }),
+ ).toBeDefined();
+ expect(userConfirmCalls).toBe(1);
+ expect(serverConfirmCalls).toBe(0);
+ });
+
+ test("shows an expired-link message when info loading fails", async () => {
+ server.use(
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler401(),
+ );
+
+ render(<PlatformLinkPage />);
+
+ expect(
+ await screen.findByText(/couldn't load setup details/i),
+ ).toBeDefined();
+ });
+
+ test("shows backend detail when confirmation fails", async () => {
+ server.use(
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({
+ platform: "DISCORD",
+ link_type: LinkType.SERVER,
+ server_name: "Builders Guild",
+ }),
+ getPostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticatedMockHandler401(
+ {
+ detail: "This setup link was already used.",
+ },
+ ),
+ );
+
+ render(<PlatformLinkPage />);
+
+ fireEvent.click(
+ await screen.findByRole("button", {
+ name: /connect discord to autogpt/i,
+ }),
+ );
+
+ expect(
+ await screen.findByText(/this setup link was already used/i),
+ ).toBeDefined();
+ });
+
+ test("signs out and redirects back through login when switching account", async () => {
+ mockLogOut.mockResolvedValue(undefined);
+ server.use(
+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({
+ platform: "DISCORD",
+ link_type: LinkType.SERVER,
+ server_name: "Builders Guild",
+ }),
+ );
+
+ render(<PlatformLinkPage />);
+
+ fireEvent.click(await screen.findByRole("button", { name: /not you/i }));
+
+ await waitFor(() => {
+ expect(mockLogOut).toHaveBeenCalledTimes(1);
+ expect(window.location.href).toBe("/login?next=%2Flink%2Ftoken-123");
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ErrorView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ErrorView.tsx
new file mode 100644
index 0000000000..e68303be7b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ErrorView.tsx
@@ -0,0 +1,28 @@
+import { Text } from "@/components/atoms/Text/Text";
+import { AuthCard } from "@/components/auth/AuthCard";
+import { LinkBreak } from "@phosphor-icons/react";
+
+interface Props {
+ message: string;
+}
+
+export function ErrorView({ message }: Props) {
+ return (
+ <AuthCard title="Setup failed">
+ <div className="flex w-full flex-col items-center gap-6">
+ <div className="flex h-16 w-16 items-center justify-center rounded-full bg-red-100">
+ <LinkBreak size={40} weight="bold" className="text-red-600" />
+ </div>
+ <Text
+ variant="body-medium"
+ className="text-center text-muted-foreground"
+ >
+ {message}
+ </Text>
+ <Text variant="small" className="text-center text-muted-foreground">
+ Go back to your chat and ask the bot for a new setup link.
+ </Text>
+ </div>
+ </AuthCard>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/LoadingView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/LoadingView.tsx
new file mode 100644
index 0000000000..6e30901e3f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/LoadingView.tsx
@@ -0,0 +1,24 @@
+import { Text } from "@/components/atoms/Text/Text";
+import { AuthCard } from "@/components/auth/AuthCard";
+import { Spinner } from "@phosphor-icons/react";
+
+interface Props {
+ title?: string;
+ message?: string;
+}
+
+export function LoadingView({
+ title = "Setting up AutoPilot",
+ message = "Loading...",
+}: Props) {
+ return (
+ <AuthCard title={title}>
+ <div className="flex flex-col items-center gap-4">
+ <Spinner size={48} className="animate-spin text-primary" />
+ <Text variant="body-medium" className="text-muted-foreground">
+ {message}
+ </Text>
+ </div>
+ </AuthCard>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/NotAuthenticatedView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/NotAuthenticatedView.tsx
new file mode 100644
index 0000000000..24d161b88b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/NotAuthenticatedView.tsx
@@ -0,0 +1,30 @@
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { AuthCard } from "@/components/auth/AuthCard";
+
+interface Props {
+ token: string;
+ loginRedirect: string;
+}
+
+export function NotAuthenticatedView({ token, loginRedirect }: Props) {
+ return (
+ <AuthCard title="Sign in to continue">
+ <div className="flex w-full flex-col items-center gap-6">
+ <Text
+ variant="body-medium"
+ className="text-center text-muted-foreground"
+ >
+ Sign in to your AutoGPT account to finish setting up AutoPilot.
+ </Text>
+ <Button as="NextLink" href={loginRedirect} className="w-full">
+ Sign in
+ </Button>
+ <AuthCard.BottomText
+ text="Don't have an account?"
+ link={{ text: "Sign up", href: `/signup?next=/link/${token}` }}
+ />
+ </div>
+ </AuthCard>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx
new file mode 100644
index 0000000000..d1cac69e6a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx
@@ -0,0 +1,103 @@
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { AuthCard } from "@/components/auth/AuthCard";
+import { LinkType } from "@/app/api/__generated__/models/linkType";
+import { isUserLink } from "../helpers";
+
+interface Props {
+ linkType: LinkType;
+ platform: string;
+ serverName: string | null;
+ userEmail: string | null;
+ isLinking: boolean;
+ onLink: () => void;
+ onSwitchAccount: () => void;
+}
+
+export function ReadyView({
+ linkType,
+ platform,
+ serverName,
+ userEmail,
+ isLinking,
+ onLink,
+ onSwitchAccount,
+}: Props) {
+ const forUser = isUserLink(linkType);
+ const title = buildTitle({ forUser, platform, serverName });
+ const contextLabel = forUser
+ ? `your ${platform} DMs`
+ : (serverName ?? `this ${platform} server`);
+
+ return (
+ <AuthCard title={title}>
+ <div className="flex w-full flex-col items-center gap-6">
+ <div className="w-full rounded-xl bg-muted p-5 text-left">
+ <Text variant="body-medium" className="font-medium">
+ What happens when you confirm:
+ </Text>
+ {forUser ? (
+ <ul className="mt-3 space-y-2 text-sm text-muted-foreground">
+ <li>{contextLabel} will be linked to your AutoGPT account</li>
+ <li>DMs with the bot run as your personal AutoPilot</li>
+ <li>All usage from those DMs is billed to your account</li>
+ </ul>
+ ) : (
+ <ul className="mt-3 space-y-2 text-sm text-muted-foreground">
+ <li>{contextLabel} will be connected to your AutoGPT account</li>
+ <li>Everyone in the server can chat with AutoPilot</li>
+ <li>Each person gets their own private conversation</li>
+ <li>
+ All usage from the server is billed to your AutoGPT account
+ </li>
+ </ul>
+ )}
+ </div>
+
+ <div className="w-full rounded-xl border border-border bg-muted p-4">
+ <Text variant="small" className="text-muted-foreground">
+ Usage from {contextLabel} will be billed to your AutoGPT account.
+ You can unlink at any time from your account settings.
+ </Text>
+ </div>
+
+ <Button
+ onClick={onLink}
+ loading={isLinking}
+ disabled={isLinking}
+ className="w-full"
+ >
+ {forUser
+ ? `Connect my ${platform} DMs`
+ : `Connect ${platform} to AutoGPT`}
+ </Button>
+
+ {userEmail && (
+ <div className="flex w-full items-center justify-between">
+ <Text variant="small" className="text-muted-foreground">
+ Signed in as {userEmail}
+ </Text>
+ <Button
+ variant="ghost"
+ size="small"
+ onClick={onSwitchAccount}
+ className="text-xs text-muted-foreground underline underline-offset-2"
+ >
+ Not you? Sign out
+ </Button>
+ </div>
+ )}
+ </div>
+ </AuthCard>
+ );
+}
+
+function buildTitle(args: {
+ forUser: boolean;
+ platform: string;
+ serverName: string | null;
+}): string {
+ if (args.forUser) return `Link your ${args.platform} DMs`;
+ if (args.serverName) return `Set up AutoPilot for ${args.serverName}`;
+ return `Set up AutoPilot for this ${args.platform} server`;
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx
new file mode 100644
index 0000000000..02b7afc6fe
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx
@@ -0,0 +1,41 @@
+import { Text } from "@/components/atoms/Text/Text";
+import { AuthCard } from "@/components/auth/AuthCard";
+import { LinkType } from "@/app/api/__generated__/models/linkType";
+import { CheckCircle } from "@phosphor-icons/react";
+import { isUserLink } from "../helpers";
+
+interface Props {
+ linkType: LinkType;
+ platform: string;
+ serverName: string | null;
+}
+
+export function SuccessView({ linkType, platform, serverName }: Props) {
+ const forUser = isUserLink(linkType);
+ const label =
+ forUser || !serverName ? `your ${platform} account` : serverName;
+ const detail = forUser
+ ? `You can now chat with AutoPilot in your ${platform} DMs.`
+ : `Everyone in the server can start using AutoPilot right away.`;
+
+ return (
+ <AuthCard title="AutoPilot is ready!">
+ <div className="flex w-full flex-col items-center gap-6">
+ <div className="flex h-16 w-16 items-center justify-center rounded-full bg-green-100">
+ <CheckCircle size={40} weight="fill" className="text-green-600" />
+ </div>
+ <Text
+ variant="body-medium"
+ className="text-center text-muted-foreground"
+ >
+ <strong>{label}</strong> is now connected to your AutoGPT account.
+ <br />
+ {detail}
+ </Text>
+ <Text variant="small" className="text-center text-muted-foreground">
+ You can close this page and go back to your chat.
+ </Text>
+ </div>
+ </AuthCard>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/helpers.ts
new file mode 100644
index 0000000000..02d5c9c5a8
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/helpers.ts
@@ -0,0 +1,29 @@
+import { LinkType } from "@/app/api/__generated__/models/linkType";
+
+export const PLATFORM_NAMES: Record<string, string> = {
+ DISCORD: "Discord",
+ TELEGRAM: "Telegram",
+ SLACK: "Slack",
+ TEAMS: "Teams",
+ WHATSAPP: "WhatsApp",
+ GITHUB: "GitHub",
+ LINEAR: "Linear",
+};
+
+// Matches backend's Path validation on /tokens/{token}/... — URL-safe base64
+// characters, bounded length. Keeps malformed params out of proxy fetches.
+export const TOKEN_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
+
+export function getPlatformDisplayName(raw: string | null | undefined): string {
+ if (!raw) return "chat platform";
+ return PLATFORM_NAMES[raw.toUpperCase()] ?? raw;
+}
+
+export function getLoginRedirect(token: string | null): string {
+ const next = token ? `/link/${token}` : "/";
+ return `/login?next=${encodeURIComponent(next)}`;
+}
+
+export function isUserLink(linkType: LinkType | undefined): boolean {
+ return linkType === LinkType.USER;
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/page.tsx
new file mode 100644
index 0000000000..0333ab58b9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/page.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { ErrorView } from "./components/ErrorView";
+import { LoadingView } from "./components/LoadingView";
+import { NotAuthenticatedView } from "./components/NotAuthenticatedView";
+import { ReadyView } from "./components/ReadyView";
+import { SuccessView } from "./components/SuccessView";
+import { usePlatformLinkingPage } from "./usePlatformLinkingPage";
+
+export default function PlatformLinkPage() {
+ const page = usePlatformLinkingPage();
+
+ return (
+ <div className="flex h-full min-h-[85vh] flex-col items-center justify-center py-10">
+ {page.status === "loading" && <LoadingView />}
+
+ {page.status === "not-authenticated" && page.token && (
+ <NotAuthenticatedView
+ token={page.token}
+ loginRedirect={page.loginRedirect}
+ />
+ )}
+
+ {page.status === "ready" && page.viewData && (
+ <ReadyView
+ linkType={page.viewData.linkType}
+ platform={page.viewData.platform}
+ serverName={page.viewData.serverName}
+ userEmail={page.userEmail}
+ isLinking={false}
+ onLink={page.handleLink}
+ onSwitchAccount={page.handleSwitchAccount}
+ />
+ )}
+
+ {page.status === "linking" && page.viewData && (
+ <ReadyView
+ linkType={page.viewData.linkType}
+ platform={page.viewData.platform}
+ serverName={page.viewData.serverName}
+ userEmail={page.userEmail}
+ isLinking
+ onLink={page.handleLink}
+ onSwitchAccount={page.handleSwitchAccount}
+ />
+ )}
+
+ {page.status === "success" && page.successData && (
+ <SuccessView
+ linkType={page.successData.linkType}
+ platform={page.successData.platform}
+ serverName={page.successData.serverName}
+ />
+ )}
+
+ {page.status === "error" && <ErrorView message={page.errorMessage} />}
+
+ <div className="mt-8 text-center text-xs text-muted-foreground">
+ <p>Powered by AutoGPT Platform</p>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts
new file mode 100644
index 0000000000..af78efc99a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/usePlatformLinkingPage.ts
@@ -0,0 +1,199 @@
+import {
+ useGetPlatformLinkingGetDisplayInfoForALinkToken,
+ usePostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticated,
+ usePostPlatformLinkingConfirmAUserLinkTokenUserMustBeAuthenticated,
+} from "@/app/api/__generated__/endpoints/platform-linking/platform-linking";
+import { ConfirmLinkResponse } from "@/app/api/__generated__/models/confirmLinkResponse";
+import { ConfirmUserLinkResponse } from "@/app/api/__generated__/models/confirmUserLinkResponse";
+import { LinkType } from "@/app/api/__generated__/models/linkType";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
+import { useParams, useSearchParams } from "next/navigation";
+import {
+ getLoginRedirect,
+ getPlatformDisplayName,
+ isUserLink,
+ TOKEN_PATTERN,
+} from "./helpers";
+
+export type PageStatus =
+ | "loading"
+ | "not-authenticated"
+ | "ready"
+ | "linking"
+ | "success"
+ | "error";
+
+interface ViewData {
+ linkType: LinkType;
+ platform: string;
+ serverName: string | null;
+}
+
+export function usePlatformLinkingPage() {
+ const params = useParams();
+ const searchParams = useSearchParams();
+ const rawToken = (params.token as string | undefined) ?? "";
+ const token = TOKEN_PATTERN.test(rawToken) ? rawToken : null;
+ const platformFromUrl = getPlatformDisplayName(searchParams.get("platform"));
+ const { user, isUserLoading, logOut } = useSupabase();
+
+ const {
+ data: info,
+ isLoading: isInfoLoading,
+ isError: isInfoError,
+ } = useGetPlatformLinkingGetDisplayInfoForALinkToken(token ?? "", {
+ query: {
+ enabled: Boolean(token) && Boolean(user),
+ select: (res) => (res && res.status === 200 ? res.data : undefined),
+ retry: false,
+ },
+ });
+
+ const serverConfirm =
+ usePostPlatformLinkingConfirmAServerLinkTokenUserMustBeAuthenticated();
+ const userConfirm =
+ usePostPlatformLinkingConfirmAUserLinkTokenUserMustBeAuthenticated();
+
+ const mutation =
+ info && isUserLink(info.link_type) ? userConfirm : serverConfirm;
+ const confirmResponse =
+ mutation.data && mutation.data.status >= 200 && mutation.data.status < 300
+ ? (mutation.data.data as ConfirmLinkResponse | ConfirmUserLinkResponse)
+ : undefined;
+
+ const status = resolveStatus({
+ hasToken: Boolean(token),
+ isUserLoading,
+ hasUser: Boolean(user),
+ isInfoLoading,
+ isInfoError,
+ isMutating: mutation.isPending,
+ isMutationSuccess: mutation.isSuccess,
+ isMutationError: mutation.isError,
+ });
+
+ function handleLink() {
+ if (!token || !info) return;
+ mutation.mutate({ token });
+ }
+
+ async function handleSwitchAccount() {
+ await logOut();
+ window.location.href = getLoginRedirect(token);
+ }
+
+ return {
+ status,
+ token,
+ loginRedirect: getLoginRedirect(token),
+ userEmail: user?.email ?? null,
+ viewData: buildViewData({ info, platformFromUrl }),
+ successData: buildSuccessData({
+ confirmResponse,
+ fallbackPlatform: platformFromUrl,
+ }),
+ errorMessage: buildErrorMessage({
+ hasToken: Boolean(token),
+ isInfoError,
+ mutation,
+ }),
+ handleLink,
+ handleSwitchAccount,
+ };
+}
+
+function resolveStatus(args: {
+ hasToken: boolean;
+ isUserLoading: boolean;
+ hasUser: boolean;
+ isInfoLoading: boolean;
+ isInfoError: boolean;
+ isMutating: boolean;
+ isMutationSuccess: boolean;
+ isMutationError: boolean;
+}): PageStatus {
+ if (!args.hasToken) return "error";
+ if (args.isUserLoading) return "loading";
+ if (!args.hasUser) return "not-authenticated";
+ if (args.isMutationSuccess) return "success";
+ if (args.isMutationError) return "error";
+ if (args.isMutating) return "linking";
+ if (args.isInfoLoading) return "loading";
+ if (args.isInfoError) return "error";
+ return "ready";
+}
+
+function buildViewData(args: {
+ info:
+ | { link_type: LinkType; platform: string; server_name?: string | null }
+ | undefined;
+ platformFromUrl: string;
+}): ViewData | null {
+ if (!args.info) return null;
+ return {
+ linkType: args.info.link_type,
+ platform:
+ getPlatformDisplayName(args.info.platform) || args.platformFromUrl,
+ serverName: args.info.server_name ?? null,
+ };
+}
+
+function buildSuccessData(args: {
+ confirmResponse: ConfirmLinkResponse | ConfirmUserLinkResponse | undefined;
+ fallbackPlatform: string;
+}): (ViewData & { platform: string }) | null {
+ if (!args.confirmResponse) return null;
+ const serverName =
+ "server_name" in args.confirmResponse
+ ? (args.confirmResponse.server_name ?? null)
+ : null;
+ return {
+ linkType: args.confirmResponse.link_type ?? LinkType.SERVER,
+ platform:
+ getPlatformDisplayName(args.confirmResponse.platform) ||
+ args.fallbackPlatform,
+ serverName,
+ };
+}
+
+function buildErrorMessage(args: {
+ hasToken: boolean;
+ isInfoError: boolean;
+ mutation: { error: unknown };
+}): string {
+ if (!args.hasToken) {
+ return "This setup link is malformed. Ask the bot for a new one.";
+ }
+ if (args.mutation.error) {
+ return extractDetail(args.mutation.error) ?? DEFAULT_MUTATION_ERROR;
+ }
+ if (args.isInfoError) {
+ return "Couldn't load setup details. The link may have expired.";
+ }
+ return DEFAULT_MUTATION_ERROR;
+}
+
+const DEFAULT_MUTATION_ERROR =
+ "Failed to complete setup. The link may have expired.";
+
+function extractDetail(error: unknown): string | undefined {
+ if (!error || typeof error !== "object") return undefined;
+ const responseDetail = extractDetailFromPayload(
+ (error as { response?: unknown }).response,
+ );
+ if (responseDetail) return responseDetail;
+
+ const dataDetail = extractDetailFromPayload(
+ (error as { data?: unknown }).data,
+ );
+ if (dataDetail) return dataDetail;
+
+ const message = (error as { message?: unknown }).message;
+ return typeof message === "string" ? message : undefined;
+}
+
+function extractDetailFromPayload(payload: unknown): string | undefined {
+ if (!payload || typeof payload !== "object") return undefined;
+ const detail = (payload as { detail?: unknown }).detail;
+ return typeof detail === "string" ? detail : undefined;
+}