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): connect onboarding SubscriptionStep to Stripe Checkout (#12978)
Ubbe68411854c5b2
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsxindex 1f46b967d4..4dde4c387a 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx@@ -63,11 +63,14 @@ vi.mock("launchdarkly-react-client-sdk", () => ({}),}));+const STEP_STORAGE_KEY = "autogpt:onboarding-highest-step";+beforeEach(() => {currentSearchParams = new URLSearchParams();mockFlagValue = false;routerReplace.mockClear();useOnboardingWizardStore.getState().reset();+ window.sessionStorage.removeItem(STEP_STORAGE_KEY);});afterEach(() => {@@ -92,6 +95,7 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {it("treats step 4 as Preparing when payments are gated off", async () => {mockFlagValue = false;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");currentSearchParams = new URLSearchParams("step=4");render(<OnboardingPage />);expect(await screen.findByTestId("step-preparing")).toBeDefined();@@ -100,6 +104,7 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {it("renders SubscriptionStep at step 4 when payments are enabled", async () => {mockFlagValue = true;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");currentSearchParams = new URLSearchParams("step=4");render(<OnboardingPage />);expect(await screen.findByTestId("step-subscription")).toBeDefined();@@ -108,12 +113,33 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {it("treats step 5 as Preparing when payments are enabled", async () => {mockFlagValue = true;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "5");currentSearchParams = new URLSearchParams("step=5");render(<OnboardingPage />);expect(await screen.findByTestId("step-preparing")).toBeDefined();expect(screen.queryByTestId("step-subscription")).toBeNull();});+ it("clamps ?step=5 to the user's highest reached step (no fast-forward)", async () => {+ mockFlagValue = true;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "2");+ currentSearchParams = new URLSearchParams("step=5");+ render(<OnboardingPage />);+ // Highest reached is 2 (RoleStep), so manually editing the URL to step=5+ // should land the user back on step 2, not let them skip ahead.+ expect(await screen.findByTestId("step-role")).toBeDefined();+ expect(screen.queryByTestId("step-preparing")).toBeNull();+ });++ it("resumes from the highest reached step when ?step= is omitted", async () => {+ mockFlagValue = true;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");+ // No step param — user navigated to /onboarding directly.+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-painpoints")).toBeDefined();+ expect(screen.queryByTestId("step-welcome")).toBeNull();+ });+it("rejects decimal step values and falls back to step 1", async () => {mockFlagValue = true;currentSearchParams = new URLSearchParams("step=2.5");@@ -128,4 +154,25 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {render(<OnboardingPage />);expect(await screen.findByTestId("step-welcome")).toBeDefined();});++ it("lets ?step=5&subscription=success bypass the highestStep ceiling", async () => {+ // Simulates returning from a successful Stripe checkout. The highest+ // reached step before the redirect was 4 (SubscriptionStep). Without the+ // success-bypass, ceiling=min(4,5)=4 would clamp the user back to step 4.+ mockFlagValue = true;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");+ currentSearchParams = new URLSearchParams("step=5&subscription=success");+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-preparing")).toBeDefined();+ expect(screen.queryByTestId("step-subscription")).toBeNull();+ });++ it("returns to SubscriptionStep on ?step=4&subscription=cancelled", async () => {+ mockFlagValue = true;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");+ currentSearchParams = new URLSearchParams("step=4&subscription=cancelled");+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-subscription")).toBeDefined();+ expect(useOnboardingWizardStore.getState().selectedPlan).toBeNull();+ });});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/components/ProgressBar.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/components/ProgressBar.tsxindex 71819d7d4c..5239f97a2c 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/components/ProgressBar.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/components/ProgressBar.tsx@@ -4,7 +4,11 @@ interface Props {}export function ProgressBar({ currentStep, totalSteps }: Props) {- const percent = (currentStep / totalSteps) * 100;+ // The progress bar tracks the user-interactive steps PLUS the trailing+ // Preparing step (which doesn't render the bar itself). Using+ // `totalSteps + 1` keeps the last interactive step (e.g. Subscription)+ // at 80% rather than maxing out at 100% before the user is actually done.+ const percent = (currentStep / (totalSteps + 1)) * 100;return (<div className="absolute left-0 top-0 h-[3px] w-full bg-neutral-200">diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/helpers.tsnew file mode 100644index 0000000000..59cb24e867--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/helpers.ts@@ -0,0 +1,36 @@+// Shared resolution of the wizard's "Other" / "Something else" sentinels into+// real values. Both `useSubscriptionStep` (pre-Stripe-redirect) and+// `useOnboardingPage` (Preparing-step submit) post the profile, and label or+// mapping changes must stay in sync across the two.++interface ProfileSource {+ name: string;+ role: string;+ otherRole: string;+ painPoints: string[];+ otherPainPoint: string;+}++interface NormalizedProfile {+ name: string;+ role: string;+ painPoints: string[];+}++export function normalizeOnboardingProfile(+ state: ProfileSource,+): NormalizedProfile {+ const resolvedRole = state.role === "Other" ? state.otherRole : state.role;+ const resolvedPainPoints = state.painPoints+ .filter((p) => p !== "Something else")+ .concat(+ state.painPoints.includes("Something else") && state.otherPainPoint.trim()+ ? [state.otherPainPoint.trim()]+ : [],+ );+ return {+ name: state.name,+ role: resolvedRole,+ painPoints: resolvedPainPoints,+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsxindex 6509470f8f..2493550e7e 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx@@ -47,7 +47,7 @@ export default function OnboardingPage() {</button>)}- <div className="flex flex-1 items-center py-16">+ <div className="flex flex-1 items-center pb-8 pt-16">{currentStep === 1 && <WelcomeStep />}{currentStep === 2 && <RoleStep />}{currentStep === 3 && <PainPointsStep />}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsxindex 68c5bd2413..00d574734f 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx@@ -18,12 +18,17 @@ export function SubscriptionStep() {country,isYearly,handlePlanSelect,+ isUpdatingTier,+ selectedPlan,} = useSubscriptionStep();return (<FadeIn>- <div className="-mt-[2.2rem] flex w-full flex-col items-center gap-4 px-4">- <AutoGPTLogo className="relative right-[2rem] h-14 w-[9rem]" hideText />+ <div className="-mt-[2rem] flex w-full flex-col items-center gap-4 px-4">+ <AutoGPTLogo+ className="relative right-[1.5rem] h-10 w-[6.5rem]"+ hideText+ /><div className="flex flex-col items-center gap-1 text-center"><Text@@ -41,55 +46,57 @@ export function SubscriptionStep() {</Text></div>- <div className="relative flex w-full max-w-[960px] flex-col items-center md:flex-row md:justify-center">- <div className="inline-flex rounded-full border border-[#d8d8d8] bg-zinc-100 p-[3px]">- {(["monthly", "yearly"] as const).map((cycle) => (- <button- key={cycle}- type="button"- onClick={() => setBilling(cycle)}+ <div className="inline-flex rounded-full border border-[#d8d8d8] bg-zinc-100 p-[3px]">+ {(["monthly", "yearly"] as const).map((cycle) => (+ <button+ key={cycle}+ type="button"+ onClick={() => setBilling(cycle)}+ className={cn(+ "rounded-full border-none px-4 py-1.5 text-xs font-medium transition-all",+ billing === cycle+ ? "bg-white text-zinc-900 shadow-sm"+ : "bg-transparent text-zinc-500 hover:text-zinc-700",+ )}+ >+ {cycle === "monthly" ? (+ "Monthly billing"+ ) : (+ <>+ Yearly billing{" "}+ <span className="ml-1.5 bg-gradient-to-r from-green-500 via-emerald-500 to-teal-500 bg-clip-text text-[11px] font-semibold text-transparent">+ Save 15%+ </span>+ </>+ )}+ </button>+ ))}+ </div>++ <div className="relative mt-2 w-full max-w-[75.625rem]">+ <div className="grid w-full grid-cols-1 gap-4 px-[1rem] md:grid-cols-3 md:px-0">+ {PLANS.map((plan) => (+ <PlanCard+ key={plan.key}+ plan={plan}+ country={country}+ isYearly={isYearly}+ onSelect={handlePlanSelect}+ loading={isUpdatingTier && selectedPlan === plan.key}+ disabled={isUpdatingTier && selectedPlan !== plan.key}className={cn(- "rounded-full border-none px-4 py-1.5 text-xs font-medium transition-all",- billing === cycle- ? "bg-white text-zinc-900 shadow-sm"- : "bg-transparent text-zinc-500 hover:text-zinc-700",+ plan.key === PLAN_KEYS.MAX && "order-1 md:order-none",+ plan.key === PLAN_KEYS.PRO && "order-2 md:order-none",+ plan.key === PLAN_KEYS.TEAM && "order-3 md:order-none",)}- >- {cycle === "monthly" ? (- "Monthly billing"- ) : (- <>- Yearly billing{" "}- <span className="ml-1.5 bg-gradient-to-r from-green-500 via-emerald-500 to-teal-500 bg-clip-text text-[11px] font-semibold text-transparent">- Save 15%- </span>- </>- )}- </button>+ />))}</div>- <div className="mb-0 mt-4 md:absolute md:right-0 md:my-0">+ <div className="mt-4 flex justify-center px-[1rem] md:fixed md:right-6 md:top-[14px] md:z-50 md:mt-0 md:px-0"><CountrySelector selected={countryIdx} onSelect={setCountryIdx} /></div></div>- <div className="mt-2 grid w-full max-w-[960px] grid-cols-1 gap-4 px-[1rem] md:grid-cols-3 md:px-0">- {PLANS.map((plan) => (- <PlanCard- key={plan.key}- plan={plan}- country={country}- isYearly={isYearly}- onSelect={handlePlanSelect}- className={cn(- plan.key === PLAN_KEYS.MAX && "order-1 md:order-none",- plan.key === PLAN_KEYS.PRO && "order-2 md:order-none",- plan.key === PLAN_KEYS.TEAM && "order-3 md:order-none",- )}- />- ))}- </div>-<Text variant="body" className="!text-zinc-500">Need something custom?{" "}<adiff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/PlanCard.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/PlanCard.tsxindex f688ed42ba..de40f147fa 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/PlanCard.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/components/PlanCard/PlanCard.tsx@@ -1,11 +1,13 @@"use client";+import { motion, useReducedMotion } from "framer-motion";+import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { cn } from "@/lib/utils";-import { Check, Info, Star } from "@phosphor-icons/react";+import { CheckIcon, StarIcon } from "@phosphor-icons/react";import { type Country, formatPrice } from "../../countries";-import { type PlanDef, type PlanKey } from "../../helpers";+import { PLAN_KEYS, type PlanDef, type PlanKey } from "../../helpers";import { computePlanPricing } from "./helpers";interface Props {@@ -14,6 +16,8 @@ interface Props {isYearly: boolean;onSelect: (key: PlanKey) => void;className?: string;+ loading?: boolean;+ disabled?: boolean;}export function PlanCard({@@ -22,6 +26,8 @@ export function PlanCard({isYearly,onSelect,className,+ loading = false,+ disabled = false,}: Props) {const { displayPrice, monthlyEquiv, perLabel } = computePlanPricing({plan,@@ -29,33 +35,67 @@ export function PlanCard({isYearly,});const hl = plan.highlighted;+ const isTeam = plan.key === PLAN_KEYS.TEAM;+ const reduceMotion = useReducedMotion();return (<div+ aria-disabled={disabled || undefined}className={cn(- "relative rounded-2xl p-px",+ "relative rounded-2xl p-px transition-opacity",hl? "bg-gradient-to-br from-purple-500 via-fuchsia-500 to-indigo-500 shadow-[0_10px_32px_-8px_rgba(119,51,245,0.25)]": "bg-gradient-to-br from-zinc-300 via-zinc-400 to-zinc-500 md:my-5",+ disabled && "pointer-events-none opacity-50",className,)}>{plan.badge && hl && (- <span className="absolute -top-3 right-5 z-10 inline-flex overflow-hidden rounded-full p-px shadow-[0_10px_28px_-6px_rgba(124,58,237,0.55)]">+ <motion.span+ className="absolute -top-3 right-5 z-10 inline-flex overflow-hidden rounded-full p-px shadow-[0_10px_28px_-6px_rgba(124,58,237,0.55)]"+ initial={reduceMotion ? false : { scale: 0, opacity: 0, rotate: -12 }}+ animate={+ reduceMotion ? undefined : { scale: 1, opacity: 1, rotate: 0 }+ }+ transition={+ reduceMotion+ ? undefined+ : { type: "spring", stiffness: 320, damping: 14, delay: 0.45 }+ }+ ><spanaria-hiddenclassName="absolute -inset-[150%] animate-[spin_4s_linear_infinite] bg-[conic-gradient(from_0deg,#a855f7,#7c3aed,#4f46e5,#1e40af,#4f46e5,#7c3aed,#a855f7)]"/><span className="relative inline-flex items-center gap-1 rounded-full bg-gradient-to-r from-indigo-600 via-blue-600 to-blue-500 px-2.5 py-1 text-[10px] font-semibold text-white">- <Star- size={10}- weight="fill"- aria-hidden="true"- className="text-yellow-300"- />+ <motion.span+ className="inline-flex"+ animate={+ reduceMotion+ ? undefined+ : { rotate: [0, 18, -10, 0], scale: [1, 1.25, 0.95, 1] }+ }+ transition={+ reduceMotion+ ? undefined+ : {+ duration: 1.2,+ repeat: Infinity,+ repeatDelay: 2.2,+ ease: "easeInOut",+ }+ }+ >+ <StarIcon+ size={10}+ weight="fill"+ aria-hidden="true"+ className="text-yellow-300"+ />+ </motion.span>{plan.badge}</span>- </span>+ </motion.span>)}<div@@ -126,7 +166,7 @@ export function PlanCard({) : (<spanclassName={cn(- "font-poppins font-medium leading-none text-zinc-800",+ "font-poppins font-medium leading-none tracking-[-1px] text-zinc-800",hl ? "text-[32px]" : "text-[26px]",)}>@@ -143,33 +183,53 @@ export function PlanCard({<div className="mb-4 flex flex-1 flex-col gap-2">{plan.features.map((f) => (- <div key={f} className="flex items-center justify-between">- <div className="flex items-center gap-2">- <span- aria-hidden="true"- className="flex h-4 w-4 items-center justify-center rounded-full bg-purple-50"- >- <Check- size={10}- weight="bold"- className="text-purple-500"- />- </span>- <span className="text-[13px] text-zinc-800">{f}</span>- </div>- <Info size={13} className="text-zinc-300" aria-hidden="true" />+ <div key={f} className="flex items-center gap-2">+ <span+ aria-hidden="true"+ className={cn(+ "flex h-4 w-4 items-center justify-center rounded-full",+ isTeam ? "bg-stone-100" : "bg-purple-50",+ )}+ >+ <CheckIcon+ size={10}+ weight="bold"+ className={isTeam ? "text-stone-500" : "text-purple-500"}+ />+ </span>+ <span className="text-[13px] text-zinc-800">{f}</span></div>))}</div>- <Button- variant={plan.buttonVariant}- size={hl ? "large" : "small"}- onClick={() => onSelect(plan.key)}- className="w-full"- >- {plan.cta}- </Button>+ <div className="relative isolate mt-5 w-full">+ {hl && (+ <motion.span+ aria-hidden+ className="pointer-events-none absolute -inset-0.5 -z-10 block rounded-[14px] bg-[linear-gradient(90deg,#a855f7,#7c3aed,#4f46e5,#6366f1,#a855f7)] bg-[length:200%_100%] opacity-25 blur-md"+ animate={+ reduceMotion+ ? undefined+ : { backgroundPosition: ["0% 50%", "100% 50%", "0% 50%"] }+ }+ transition={+ reduceMotion+ ? undefined+ : { duration: 8, repeat: Infinity, ease: "linear" }+ }+ />+ )}+ <Button+ variant={plan.buttonVariant}+ size={hl ? "large" : "small"}+ onClick={() => onSelect(plan.key)}+ className="w-full"+ loading={loading}+ disabled={disabled}+ >+ {plan.cta}+ </Button>+ </div></div></div></div>diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.tsindex 22155a4b8c..1481486360 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts@@ -1,7 +1,25 @@+import { useUpdateSubscriptionTier } from "@/app/api/__generated__/endpoints/credits/credits";+import { postV1SubmitOnboardingProfile } from "@/app/api/__generated__/endpoints/onboarding/onboarding";+import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";+import { toast } from "@/components/molecules/Toast/use-toast";+import { useState } from "react";+import { normalizeOnboardingProfile } from "../../helpers";import { useOnboardingWizardStore } from "../../store";import { COUNTRIES } from "./countries";import { PLAN_KEYS, type PlanKey, TEAM_INTAKE_FORM_URL } from "./helpers";+const PLAN_TO_TIER: Record<+ Exclude<PlanKey, typeof PLAN_KEYS.TEAM>,+ SubscriptionTierRequestTier+> = {+ PRO: "PRO",+ MAX: "MAX",+};++interface CheckoutResponse {+ url?: string;+}+export function useSubscriptionStep() {const billing = useOnboardingWizardStore((s) => s.selectedBilling);const setSelectedBilling = useOnboardingWizardStore(@@ -15,6 +33,15 @@ export function useSubscriptionStep() {);const setSelectedPlan = useOnboardingWizardStore((s) => s.setSelectedPlan);const nextStep = useOnboardingWizardStore((s) => s.nextStep);+ const selectedPlan = useOnboardingWizardStore((s) => s.selectedPlan);++ const { mutateAsync: updateTier, isPending: isUpdatingTier } =+ useUpdateSubscriptionTier();+ // Local guard that flips synchronously on first click so the profile-save+ // phase (which runs before `isUpdatingTier` becomes true) can't be+ // re-entered by a fast double-click queueing duplicate POSTs.+ const [isSubmitting, setIsSubmitting] = useState(false);+ const isProcessing = isUpdatingTier || isSubmitting;const countryIdx = Math.max(0,@@ -29,13 +56,65 @@ export function useSubscriptionStep() {setSelectedCountryCode(next.countryCode);}- function handlePlanSelect(planKey: PlanKey) {+ async function handlePlanSelect(planKey: PlanKey) {if (planKey === PLAN_KEYS.TEAM) {window.open(TEAM_INTAKE_FORM_URL, "_blank", "noopener,noreferrer");return;}+ if (isProcessing) return;+ setIsSubmitting(true);+setSelectedPlan(planKey);- nextStep();+ const tier = PLAN_TO_TIER[planKey];++ // Profile data lives in an in-memory zustand store, so persist it before+ // Stripe takes the user off-page — otherwise the user's name/role/pain+ // points are lost on the post-checkout redirect.+ const { name, role, painPoints } = normalizeOnboardingProfile(+ useOnboardingWizardStore.getState(),+ );++ try {+ // Profile must be persisted before Stripe takes over — the zustand+ // store is in-memory and the post-checkout return is a full page+ // navigation. Abort on failure rather than silently losing the user's+ // name / role / pain points.+ await postV1SubmitOnboardingProfile({+ user_name: name,+ user_role: role,+ pain_points: painPoints,+ });++ const baseUrl = `${window.location.origin}/onboarding`;+ const result = await updateTier({+ data: {+ tier,+ success_url: `${baseUrl}?step=5&subscription=success`,+ cancel_url: `${baseUrl}?step=4&subscription=cancelled`,+ },+ });+ const url = (result?.data as CheckoutResponse | undefined)?.url;+ if (url) {+ // Navigating away — don't refetch (would set state on an+ // unmounting component while Stripe Checkout takes over).+ window.location.href = url;+ return;+ }+ // Backend modified the subscription in place (no Checkout URL) —+ // proceed to the preparing step as if the user had clicked through.+ nextStep();+ } catch (error) {+ toast({+ title: "Couldn't start checkout",+ description:+ error instanceof Error+ ? error.message+ : "Stripe didn't accept the request. Please try again.",+ variant: "destructive",+ });+ } finally {+ setIsSubmitting(false);+ }}return {@@ -46,5 +125,7 @@ export function useSubscriptionStep() {country,isYearly,handlePlanSelect,+ isUpdatingTier: isProcessing,+ selectedPlan,};}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsxindex e528e9468b..71b9a6dbcc 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx@@ -1,10 +1,13 @@+import { http, HttpResponse } from "msw";import {cleanup,fireEvent,render,screen,+ waitFor,} from "@/tests/integrations/test-utils";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { server } from "@/mocks/mock-server";import { useOnboardingWizardStore } from "../../store";import { SubscriptionStep } from "../SubscriptionStep/SubscriptionStep";@@ -46,12 +49,78 @@ describe("SubscriptionStep", () => {expect(screen.getAllByText(/\/ year/i).length).toBeGreaterThan(0);});- test("selecting Pro persists selectedPlan and advances to step 5", () => {+ test("selecting Pro persists selectedPlan, submits the profile, and redirects to Stripe Checkout", async () => {+ useOnboardingWizardStore.getState().setName("Ada Lovelace");+ useOnboardingWizardStore.getState().setRole("Engineer");+ useOnboardingWizardStore.getState().togglePainPoint("Repetitive work");++ let capturedTierBody: {+ tier?: string;+ success_url?: string;+ cancel_url?: string;+ } | null = null;+ let capturedProfileBody: {+ user_name?: string;+ user_role?: string;+ pain_points?: string[];+ } | null = null;++ server.use(+ http.post("*/api/onboarding/profile", async ({ request }) => {+ capturedProfileBody =+ (await request.json()) as typeof capturedProfileBody;+ return HttpResponse.json({}, { status: 200 });+ }),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedTierBody = (await request.json()) as typeof capturedTierBody;+ // Return null url so the hook doesn't try to navigate window.location+ // (would tear down the test environment).+ return HttpResponse.json({ url: null });+ }),+ );+render(<SubscriptionStep />);fireEvent.click(screen.getByRole("button", { name: /Get Pro/i }));- const state = useOnboardingWizardStore.getState();- expect(state.selectedPlan).toBe("PRO");- expect(state.currentStep).toBe(5);++ await waitFor(() => {+ expect(capturedTierBody).not.toBeNull();+ });++ expect(useOnboardingWizardStore.getState().selectedPlan).toBe("PRO");+ expect(capturedTierBody!.tier).toBe("PRO");+ expect(capturedTierBody!.success_url).toContain(+ "/onboarding?step=5&subscription=success",+ );+ expect(capturedTierBody!.cancel_url).toContain(+ "/onboarding?step=4&subscription=cancelled",+ );+ expect(capturedProfileBody).not.toBeNull();+ expect(capturedProfileBody!.user_name).toBe("Ada Lovelace");+ expect(capturedProfileBody!.user_role).toBe("Engineer");+ expect(capturedProfileBody!.pain_points).toEqual(["Repetitive work"]);+ });++ test("selecting Max uses the MAX tier in the Stripe Checkout request", async () => {+ let capturedTierBody: { tier?: string } | null = null;++ server.use(+ http.post("*/api/onboarding/profile", () =>+ HttpResponse.json({}, { status: 200 }),+ ),+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedTierBody = (await request.json()) as typeof capturedTierBody;+ return HttpResponse.json({ url: null });+ }),+ );++ render(<SubscriptionStep />);+ fireEvent.click(screen.getByRole("button", { name: /Upgrade to Max/i }));++ await waitFor(() => {+ expect(capturedTierBody).not.toBeNull();+ });+ expect(capturedTierBody!.tier).toBe("MAX");+ expect(useOnboardingWizardStore.getState().selectedPlan).toBe("MAX");});test("selecting Team opens the intake form and does not advance", () => {@@ -78,4 +147,37 @@ describe("SubscriptionStep", () => {fireEvent.click(screen.getByRole("button", { name: /European Union/i }));expect(useOnboardingWizardStore.getState().selectedCountryCode).toBe("EU");});++ test("clicking a plan keeps the request in flight: clicked card spins, others lock", async () => {+ useOnboardingWizardStore.getState().setName("Ada");+ useOnboardingWizardStore.getState().setRole("Engineer");++ let resolveTier: (value: unknown) => void = () => undefined;+ server.use(+ http.post("*/api/onboarding/profile", () =>+ HttpResponse.json({}, { status: 200 }),+ ),+ http.post(+ "*/api/credits/subscription",+ () =>+ new Promise((resolve) => {+ resolveTier = () => resolve(HttpResponse.json({ url: null }));+ }),+ ),+ );++ render(<SubscriptionStep />);+ const proButton = screen.getByRole("button", { name: /Get Pro/i });+ const maxButton = screen.getByRole("button", { name: /Upgrade to Max/i });+ const teamButton = screen.getByRole("button", { name: /Contact sales/i });+ fireEvent.click(proButton);++ await waitFor(() => {+ expect(maxButton.hasAttribute("disabled")).toBe(true);+ expect(teamButton.hasAttribute("disabled")).toBe(true);+ });+ expect(useOnboardingWizardStore.getState().selectedPlan).toBe("PRO");++ resolveTier(null);+ });});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.tsindex f02b86ac3f..522766f619 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts@@ -10,14 +10,38 @@ import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { useLDClient } from "launchdarkly-react-client-sdk";import { useRouter, useSearchParams } from "next/navigation";import { useEffect, useRef, useState } from "react";+import { normalizeOnboardingProfile } from "./helpers";import { Step, useOnboardingWizardStore } from "./store";const LD_INIT_TIMEOUT_SECONDS = 5;-function parseStep(value: string | null, maxStep: number): Step {+// SessionStorage ceiling for the wizard. The backend's `completedSteps`+// only records VISIT_COPILOT at the very end (the 5 in-wizard steps aren't+// tracked individually), so resume / fast-forward guardrails are enforced+// client-side: the user can only land on a step they've previously reached.+const STEP_STORAGE_KEY = "autogpt:onboarding-highest-step";++function parseStepParam(value: string | null, maxStep: number): Step | null {const n = Number(value);if (Number.isInteger(n) && n >= 1 && n <= maxStep) return n as Step;- return 1;+ return null;+}++function readHighestStep(): number {+ if (typeof window === "undefined") return 1;+ const raw = window.sessionStorage.getItem(STEP_STORAGE_KEY);+ const n = Number(raw);+ return Number.isInteger(n) && n >= 1 ? n : 1;+}++function writeHighestStep(step: number) {+ if (typeof window === "undefined") return;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, String(step));+}++function clearHighestStep() {+ if (typeof window === "undefined") return;+ window.sessionStorage.removeItem(STEP_STORAGE_KEY);}export function useOnboardingPage() {@@ -70,22 +94,38 @@ export function useOnboardingPage() {const hasSubmitted = useRef(false);const hasInitialized = useRef(false);- // Initialise store from URL on mount, reset form data+ // Initialise store from URL on mount, reset form data, clamp ?step= to+ // the highest step the user has actually reached. No-step URL resumes from+ // the highest reached so refreshes don't drop the user back to step 1.useEffect(() => {if (!areFlagsReady || hasInitialized.current) return;hasInitialized.current = true;- const urlStep = parseStep(searchParams.get("step"), preparingStep);+ const urlStep = parseStepParam(searchParams.get("step"), preparingStep);+ // A successful Stripe checkout return is a trusted intent to advance to+ // Preparing — without this, the highestStep ceiling (capped at 4 before+ // redirect) clamps the user back to step 4 and onboarding deadlocks.+ const isSubscriptionSuccess =+ searchParams.get("subscription") === "success";+ const ceiling = isSubscriptionSuccess+ ? preparingStep+ : (Math.min(readHighestStep(), preparingStep) as Step);+ const target = (+ urlStep === null ? ceiling : Math.min(urlStep, ceiling)+ ) as Step;reset();- goToStep(urlStep);+ goToStep(target);}, [areFlagsReady, searchParams, reset, goToStep, preparingStep]);- // Sync store → URL when step changes+ // Sync store → URL when step changes; record the new ceiling.useEffect(() => {if (!areFlagsReady) return;- const urlStep = parseStep(searchParams.get("step"), preparingStep);+ const urlStep = parseStepParam(searchParams.get("step"), preparingStep);if (currentStep !== urlStep) {router.replace(`/onboarding?step=${currentStep}`, { scroll: false });}+ if (currentStep > readHighestStep()) {+ writeHighestStep(currentStep);+ }}, [areFlagsReady, currentStep, router, searchParams, preparingStep]);// Check if onboarding already completed@@ -96,6 +136,7 @@ export function useOnboardingPage() {try {const onboarding = await resolveResponse(getV1OnboardingState());if (onboarding.completedSteps.includes("VISIT_COPILOT")) {+ clearHighestStep();router.replace("/copilot");return;}@@ -113,36 +154,39 @@ export function useOnboardingPage() {if (currentStep !== preparingStep || hasSubmitted.current) return;hasSubmitted.current = true;- const { name, role, otherRole, painPoints, otherPainPoint } =- useOnboardingWizardStore.getState();- const resolvedRole = role === "Other" ? otherRole : role;- const resolvedPainPoints = painPoints- .filter((p) => p !== "Something else")- .concat(- painPoints.includes("Something else") && otherPainPoint.trim()- ? [otherPainPoint.trim()]- : [],- );+ const { name, role, painPoints } = normalizeOnboardingProfile(+ useOnboardingWizardStore.getState(),+ );++ // Profile is submitted before the Stripe Checkout redirect (the wizard+ // store is in-memory and doesn't survive the round-trip). Skip the+ // resubmit on return to avoid overwriting saved data with empties —+ // belt-and-suspenders: also skip when `name` is empty so that even if+ // the success query param gets stripped (manual edit, share link,+ // upstream proxy normalising URLs), we don't blank the saved profile.+ if (searchParams.get("subscription") === "success" || !name.trim()) return;postV1SubmitOnboardingProfile({user_name: name,- user_role: resolvedRole,- pain_points: resolvedPainPoints,+ user_role: role,+ pain_points: painPoints,}).catch(() => {// Best effort — profile data is non-critical for accessing copilot});- }, [currentStep, preparingStep]);+ }, [currentStep, preparingStep, searchParams]);async function handlePreparingComplete() {for (let attempt = 0; attempt < 3; attempt++) {try {await postV1CompleteOnboardingStep({ step: "VISIT_COPILOT" });+ clearHighestStep();router.replace("/copilot");return;} catch {if (attempt < 2) await new Promise((r) => setTimeout(r, 1000));}}+ clearHighestStep();router.replace("/copilot");}diff --git a/autogpt_platform/frontend/src/components/atoms/Emoji/Emoji.tsx b/autogpt_platform/frontend/src/components/atoms/Emoji/Emoji.tsxindex 8bf303a887..0ea5bf32b9 100644--- a/autogpt_platform/frontend/src/components/atoms/Emoji/Emoji.tsx+++ b/autogpt_platform/frontend/src/components/atoms/Emoji/Emoji.tsx@@ -5,23 +5,41 @@ interface Props {size?: number;}+// twemoji.parse passes non-emoji characters through verbatim and the official+// docs explicitly disclaim string sanitisation, so feeding raw `text` and+// dumping the result through dangerouslySetInnerHTML would be XSS-able if a+// caller ever passed user input. Escaping HTML metacharacters first keeps+// emoji codepoints (not metacharacters) untouched while neutering any+// embedded markup.+function escapeHtml(input: string) {+ return input+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'");+}+export function Emoji({ text, size = 24 }: Props) {+ // Strip the default alt (the emoji codepoint) so the browser doesn't flash+ // the small system-rendered emoji while the SVG loads from the CDN. The+ // twemoji API doesn't expose an alt override, hence the regex.+ const html = twemoji+ .parse(escapeHtml(text), {+ folder: "svg",+ ext: ".svg",+ attributes: () => ({+ width: String(size),+ height: String(size),+ }),+ })+ .replace(/\salt="[^"]*"/, ' alt=""');+return (<spanclassName="inline-flex items-center"style={{ width: size, height: size }}- dangerouslySetInnerHTML={{- // twemoji.parse only converts emoji codepoints to <img> tags- // pointing to Twitter's CDN SVGs — it does not inject arbitrary HTML- __html: twemoji.parse(text, {- folder: "svg",- ext: ".svg",- attributes: () => ({- width: String(size),- height: String(size),- }),- }),- }}+ dangerouslySetInnerHTML={{ __html: html }}/>);}