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): keep checkout buttons busy until the page leaves for Stripe (SECRT-2932) (#15603)

Krzysztof Czerwinski47a6368ca852
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.tsx
index b12ccd6fb6..3239eaab3a 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
@@ -55,6 +55,7 @@ export function SubscriptionStep() {
...trial,
startTrial,
isStarting: trial.isStarting || saving,
+ isBlocked: trial.isBlocked || subscription.isUpdatingTier,
error: saveError ?? trial.error,
}}
/>
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.ts
index 34114d977b..0628b85e05 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
@@ -20,6 +20,7 @@ import {
TEAM_INTAKE_FORM_URL,
} from "@/components/molecules/PlanCard/plans";
import { useSubscriptionPricingExperiment } from "./useSubscriptionPricingExperiment";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
import { useMountEffect } from "@/hooks/useMountEffect";
import {
markPaywallCheckoutStarted,
@@ -72,7 +73,13 @@ export function useSubscriptionStep() {
// 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 checkoutRedirect = useCheckoutRedirect();
+ const isRequesting = isUpdatingTier || isSubmitting;
+ const isProcessing = isRequesting || checkoutRedirect.isRedirecting;
+ // Every checkout button on the page shares the redirect, so only this
+ // step's own request or redirect may spin its plan button.
+ const loadingPlan =
+ isRequesting || checkoutRedirect.isRedirectingHere ? selectedPlan : null;
const countryIdx = Math.max(
0,
@@ -141,6 +148,7 @@ export function useSubscriptionStep() {
// Navigating away — don't refetch (would set state on an
// unmounting component while Stripe Checkout takes over).
window.location.href = url;
+ checkoutRedirect.markRedirecting();
return;
}
await queryClient.invalidateQueries(
@@ -150,6 +158,7 @@ export function useSubscriptionStep() {
if (useOnboardingWizardStore.getState().userID !== ownerID) return;
nextStep();
} catch (error) {
+ setSelectedPlan(null);
toast({
title: "Couldn't start checkout",
description:
@@ -171,6 +180,6 @@ export function useSubscriptionStep() {
isYearly,
handlePlanSelect,
isUpdatingTier: isProcessing,
- selectedPlan,
+ selectedPlan: loadingPlan,
};
}
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.tsx
index 38519881a4..6a5af667f1 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
@@ -9,6 +9,7 @@ import {
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { server } from "@/mocks/mock-server";
import { environment } from "@/services/environment";
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
import {
installGtagShim,
removeGtagShim,
@@ -295,6 +296,35 @@ describe("SubscriptionStep", () => {
);
});
+ test("stays busy while Stripe loads, and is usable again after Back restores the page", async () => {
+ const location = stubLocation();
+ let posts = 0;
+ server.use(
+ http.post("*/api/credits/subscription", () => {
+ posts += 1;
+ return HttpResponse.json({
+ url: "https://checkout.stripe.com/pay/cs_test",
+ });
+ }),
+ );
+
+ render(<SubscriptionStep />);
+ const pro = screen.getByRole("button", { name: /Get Pro/i });
+ fireEvent.click(pro);
+ await waitFor(() =>
+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test"),
+ );
+ expect(pro.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(pro);
+ expect(posts).toBe(1);
+
+ restoreFromBackForwardCache();
+
+ expect(pro.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(pro);
+ await waitFor(() => expect(posts).toBe(2));
+ });
+
test.each(["https://checkout.stripe.com/pay/old_account", null])(
"ignores an old account's checkout response with URL %s",
async (url) => {
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx
index 4f1e3f2400..4f38e43e97 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx
@@ -5,6 +5,7 @@ import {
} from "@/app/api/__generated__/endpoints/trials/trials.msw";
import { server } from "@/mocks/mock-server";
import { environment } from "@/services/environment";
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
import {
installGtagShim,
removeGtagShim,
@@ -516,3 +517,51 @@ test("also flushes the draft from the standalone fallback trial card", async ()
expect(await card.findByRole("alert")).toBeDefined();
expect(checkoutLocation.assign).not.toHaveBeenCalled();
});
+
+test.each(["failed", "left with Back"])(
+ "a %s Pro checkout leaves no spinner on Pro once the trial redirects",
+ async (outcome) => {
+ mockStatus();
+ server.use(
+ http.post("*/api/credits/subscription", () =>
+ outcome === "failed"
+ ? HttpResponse.json({ detail: "Please try again" }, { status: 503 })
+ : HttpResponse.json({ url: "https://checkout.stripe.com/paid" }),
+ ),
+ getPostTrialsStartTrialCheckoutMockHandler200({
+ url: "https://checkout.stripe.com/trial",
+ }),
+ );
+ render(<SubscriptionStep />);
+ const card = within(
+ await screen.findByRole("region", { name: "Pro plan" }),
+ );
+ const start = await card.findByRole("button", {
+ name: "Start 7-day trial",
+ });
+ const pro = card.getByRole("button", { name: /^Get Pro/ });
+
+ fireEvent.click(pro);
+ if (outcome === "failed") {
+ await waitFor(() => expect(pro.hasAttribute("disabled")).toBe(false));
+ expect(useOnboardingWizardStore.getState().selectedPlan).toBeNull();
+ } else {
+ await waitFor(() =>
+ expect(checkoutLocation.href).toBe("https://checkout.stripe.com/paid"),
+ );
+ expect(pro.querySelector(".animate-spin")).not.toBeNull();
+ restoreFromBackForwardCache();
+ expect(pro.hasAttribute("disabled")).toBe(false);
+ }
+ expect(pro.querySelector(".animate-spin")).toBeNull();
+
+ fireEvent.click(start);
+ await waitFor(() =>
+ expect(checkoutLocation.assign).toHaveBeenCalledWith(
+ "https://checkout.stripe.com/trial",
+ ),
+ );
+ expect(pro.hasAttribute("disabled")).toBe(true);
+ expect(pro.querySelector(".animate-spin")).toBeNull();
+ },
+);
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts
index 228aae8d8b..600f34a99b 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts
@@ -101,7 +101,7 @@ interface OnboardingWizardState {
setOtherRole(otherRole: string): void;
togglePainPoint(painPoint: string): void;
setOtherPainPoint(otherPainPoint: string): void;
- setSelectedPlan(plan: string): void;
+ setSelectedPlan(plan: string | null): void;
setSelectedBilling(billing: "monthly" | "yearly"): void;
applyPricingExperimentBilling(billing: "monthly" | "yearly"): void;
setSelectedCountryCode(code: string): void;
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
index f6f852b198..2bdd48d44d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx
@@ -1,3 +1,4 @@
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
import {
installGtagShim,
removeGtagShim,
@@ -490,6 +491,35 @@ describe("PaywallModal — upgrade mutation", () => {
vi.unstubAllEnvs();
});
+ it("stays busy while Stripe loads, and is usable again after Back restores the page", async () => {
+ stubLocation();
+ const { mutateFn } = setupMocks({
+ mutateFn: vi.fn().mockResolvedValue({
+ status: 200,
+ data: { url: "https://checkout.stripe.com/pay/cs_test" },
+ }),
+ subscription: { tier: "NO_TIER", tier_costs: { PRO: 5000 } },
+ });
+
+ render(<PaywallModal />);
+ const upgrade = screen.getByRole("button", { name: /start pro/i });
+ fireEvent.click(upgrade);
+ await waitFor(() =>
+ expect(window.location.href).toBe(
+ "https://checkout.stripe.com/pay/cs_test",
+ ),
+ );
+ expect(upgrade.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(upgrade);
+ expect(mutateFn).toHaveBeenCalledTimes(1);
+
+ restoreFromBackForwardCache();
+
+ expect(upgrade.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(upgrade);
+ await waitFor(() => expect(mutateFn).toHaveBeenCalledTimes(2));
+ });
+
it("401 from updateTier routes to /login instead of toasting a dead-end error", async () => {
stubLocation();
const mutateFn = vi
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx
index ff6b7e7942..15e505995a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx
@@ -264,3 +264,69 @@ test("offers to switch billing cycle when the trial is priced on the other one",
await pro.findByRole("button", { name: "Start 7-day trial" }),
).toBeDefined();
});
+
+test("a plan checkout keeps the trial button disabled until the page leaves", async () => {
+ const updateTier = vi.fn().mockResolvedValue({
+ status: 200,
+ data: { url: "https://checkout.stripe.com/pay/cs_plan" },
+ });
+ mockUseUpdateSubscriptionTier.mockReturnValue({
+ mutateAsync: updateTier,
+ isPending: false,
+ });
+ const trialCheckout = vi.fn(() => ({
+ url: "https://checkout.stripe.com/trial",
+ }));
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(eligible()),
+ getPostTrialsStartTrialCheckoutMockHandler200(trialCheckout),
+ );
+
+ render(<PaywallModal />);
+
+ const max = within(await screen.findByRole("region", { name: "Max plan" }));
+ fireEvent.click(max.getByRole("button", { name: "Start Max" }));
+ await waitFor(() =>
+ expect(checkoutLocation.href).toBe(
+ "https://checkout.stripe.com/pay/cs_plan",
+ ),
+ );
+
+ const trial = screen.getByRole("button", { name: "Start 7-day trial" });
+ expect(trial.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(trial);
+ expect(trialCheckout).not.toHaveBeenCalled();
+ expect(checkoutLocation.assign).not.toHaveBeenCalled();
+ expect(updateTier).toHaveBeenCalledOnce();
+});
+
+test("a trial checkout keeps the plan buttons disabled until the page leaves", async () => {
+ const updateTier = vi.fn();
+ mockUseUpdateSubscriptionTier.mockReturnValue({
+ mutateAsync: updateTier,
+ isPending: false,
+ });
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(eligible()),
+ getPostTrialsStartTrialCheckoutMockHandler200({
+ url: "https://checkout.stripe.com/trial",
+ }),
+ );
+
+ render(<PaywallModal />);
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Start 7-day trial" }),
+ );
+ await waitFor(() =>
+ expect(checkoutLocation.assign).toHaveBeenCalledWith(
+ "https://checkout.stripe.com/trial",
+ ),
+ );
+
+ const max = within(screen.getByRole("region", { name: "Max plan" }));
+ const plan = max.getByRole("button", { name: "Start Max" });
+ expect(plan.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(plan);
+ expect(updateTier).not.toHaveBeenCalled();
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
index 64265d2459..7b8be49c4a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
@@ -8,6 +8,7 @@ import {
} from "@/app/api/__generated__/endpoints/credits/credits";
import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";
import { toast } from "@/components/molecules/Toast/use-toast";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
import { useMountEffect } from "@/hooks/useMountEffect";
import { ApiError } from "@/lib/autogpt-server-api/helpers";
import { useAuth } from "@/lib/auth/hooks/useAuth";
@@ -113,6 +114,8 @@ export function usePaywallModal() {
// saved card and looks like a no-op. Stage the target tier here and surface
// a confirmation dialog before firing the mutation.
const [pendingTier, setPendingTier] = useState<string | null>(null);
+ const checkoutRedirect = useCheckoutRedirect();
+ const [redirectingTier, setRedirectingTier] = useState<string | null>(null);
const country = COUNTRIES[0];
const isYearly = selectedCycle === "yearly";
@@ -133,7 +136,12 @@ export function usePaywallModal() {
// selectedTier spans the whole click: the request, the wait for the Ads
// conversion and the start of the redirect. isPending alone ends before the
// redirect, which left the plan buttons clickable for a second checkout.
- const isCheckingOut = isPending || selectedTier !== null;
+ // A trial checkout, or any other checkout leaving the page, holds them too.
+ const isCheckingOut =
+ isPending ||
+ selectedTier !== null ||
+ trial.isStarting ||
+ checkoutRedirect.isRedirecting;
const hasActiveStripeSubscription = Boolean(
subscription?.has_active_stripe_subscription,
@@ -169,6 +177,8 @@ export function usePaywallModal() {
value: apiValue ?? getSubscriptionValue(tier, cycle),
});
window.location.href = url;
+ setRedirectingTier(tier);
+ checkoutRedirect.markRedirecting();
}
} catch (error) {
// 401 means the paywall outlived its session: checkout can never
@@ -256,7 +266,9 @@ export function usePaywallModal() {
setSelectedCycle,
handleSelectPlan,
isPending: isCheckingOut,
- selectedTier,
+ selectedTier:
+ selectedTier ??
+ (checkoutRedirect.isRedirectingHere ? redirectingTier : null),
pendingTier,
pendingTierLabel,
confirmPendingTier,
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/__tests__/top-up.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/__tests__/top-up.test.tsx
new file mode 100644
index 0000000000..c4987adec4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/__tests__/top-up.test.tsx
@@ -0,0 +1,118 @@
+import { http, HttpResponse } from "msw";
+import { describe, expect, test, vi } from "vitest";
+
+import { server } from "@/mocks/mock-server";
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+
+import CreditsPage from "../page";
+
+const routerPush = vi.hoisted(() => vi.fn());
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: routerPush, replace: vi.fn(), prefetch: vi.fn() }),
+ usePathname: () => "/profile/credits",
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({}),
+}));
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >()),
+ useGetFlag: () => true,
+}));
+
+describe("legacy credits page top-up", () => {
+ test("keeps the top-up and plan buttons disabled while Stripe loads", async () => {
+ const checkoutURL = "https://checkout.stripe.com/pay/cs_top_up";
+ let topUps = 0;
+ server.use(
+ http.get("*/api/credits/subscription", () =>
+ HttpResponse.json({
+ tier: "BASIC",
+ monthly_cost: 0,
+ tier_costs: { BASIC: 0, PRO: 1999 },
+ tier_multipliers: { BASIC: 1, PRO: 5 },
+ proration_credit_cents: 0,
+ pending_tier: null,
+ pending_tier_effective_at: null,
+ }),
+ ),
+ http.post("*/api/credits", () => {
+ topUps += 1;
+ return HttpResponse.json({ checkout_url: checkoutURL });
+ }),
+ );
+
+ render(<CreditsPage />);
+ const upgrade = await screen.findByRole("button", {
+ name: /upgrade to pro/i,
+ });
+ const topUp = screen.getByRole("button", { name: "Top-up" });
+
+ fireEvent.click(topUp);
+ await waitFor(() => expect(routerPush).toHaveBeenCalledWith(checkoutURL));
+ await act(async () => {});
+
+ expect(topUp.hasAttribute("disabled")).toBe(true);
+ expect(upgrade.hasAttribute("disabled")).toBe(true);
+ fireEvent.submit(topUp.closest("form")!);
+ await act(async () => {});
+ expect(topUps).toBe(1);
+
+ restoreFromBackForwardCache();
+
+ expect(topUp.hasAttribute("disabled")).toBe(false);
+ expect(upgrade.hasAttribute("disabled")).toBe(false);
+ });
+
+ test.each(["fails", "returns a checkout"])(
+ "starts one checkout for a double click while the request is pending, and settles if it %s",
+ async (outcome) => {
+ const checkoutURL = "https://checkout.stripe.com/pay/cs_top_up";
+ let topUps = 0;
+ let finishTopUp = () => {};
+ const pending = new Promise<void>((resolve) => {
+ finishTopUp = resolve;
+ });
+ server.use(
+ http.post("*/api/credits", async () => {
+ topUps += 1;
+ await pending;
+ return outcome === "fails"
+ ? HttpResponse.json({ detail: "Please try again" }, { status: 503 })
+ : HttpResponse.json({ checkout_url: checkoutURL });
+ }),
+ );
+
+ render(<CreditsPage />);
+ const topUp = await screen.findByRole("button", { name: "Top-up" });
+ const form = topUp.closest("form")!;
+
+ fireEvent.submit(form);
+ fireEvent.submit(form);
+ await waitFor(() => expect(topUps).toBe(1));
+ expect(topUp.hasAttribute("disabled")).toBe(true);
+ fireEvent.submit(form);
+
+ finishTopUp();
+ if (outcome === "fails") {
+ await waitFor(() => expect(topUp.hasAttribute("disabled")).toBe(false));
+ } else {
+ await waitFor(() =>
+ expect(routerPush).toHaveBeenCalledWith(checkoutURL),
+ );
+ await act(async () => {});
+ expect(topUp.hasAttribute("disabled")).toBe(true);
+ }
+ expect(topUps).toBe(1);
+ },
+ );
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
index f2653dbeba..f3ff0fdee5 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/__tests__/SubscriptionTierSection.test.tsx
@@ -6,6 +6,7 @@ import {
cleanup,
} from "@/tests/integrations/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
import { SubscriptionTierSection } from "../SubscriptionTierSection";
// Mock next/navigation
@@ -308,6 +309,39 @@ describe("SubscriptionTierSection", () => {
vi.unstubAllGlobals();
});
+ it("stays busy while Stripe loads, and is usable again after Back restores the page", async () => {
+ const mockLocation = { href: "" };
+ vi.stubGlobal("location", mockLocation);
+ const mutateFn = vi.fn().mockResolvedValue({
+ status: 200,
+ data: { url: "https://checkout.stripe.com/pay/cs_test" },
+ });
+ setupMocks({ mutateFn });
+ render(<SubscriptionTierSection />);
+
+ const upgrade = screen.getByRole("button", { name: /upgrade to pro/i });
+ fireEvent.click(upgrade);
+ fireEvent.click(
+ screen.getByRole("button", { name: /continue to checkout/i }),
+ );
+ await waitFor(() =>
+ expect(mockLocation.href).toBe("https://checkout.stripe.com/pay/cs_test"),
+ );
+ expect(upgrade.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(upgrade);
+ expect(mutateFn).toHaveBeenCalledTimes(1);
+
+ restoreFromBackForwardCache();
+
+ expect(upgrade.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(upgrade);
+ fireEvent.click(
+ screen.getByRole("button", { name: /continue to checkout/i }),
+ );
+ await waitFor(() => expect(mutateFn).toHaveBeenCalledTimes(2));
+ vi.unstubAllGlobals();
+ });
+
it("shows an error alert when tier change fails", async () => {
const mutateFn = vi.fn().mockRejectedValue(new Error("Stripe unavailable"));
setupMocks({ mutateFn });
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts
index 2cf7ea5a83..f41bc2b7a2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/components/SubscriptionTierSection/useSubscriptionTierSection.ts
@@ -7,6 +7,7 @@ import {
import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";
import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";
import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { getTierLabel } from "./helpers";
import {
@@ -49,7 +50,9 @@ export function useSubscriptionTierSection() {
isPending: isUpdatePending,
variables,
} = useUpdateSubscriptionTier();
- const isPending = isUpdatePending || isChangingTier;
+ const checkoutRedirect = useCheckoutRedirect();
+ const isPending =
+ isUpdatePending || isChangingTier || checkoutRedirect.isRedirecting;
useEffect(() => {
if (subscriptionStatus === "success") {
@@ -96,6 +99,7 @@ export function useSubscriptionTierSection() {
value: getSubscriptionValue(tier, "monthly"),
});
window.location.href = result.data.url;
+ checkoutRedirect.markRedirecting();
return;
}
await refetch();
@@ -184,8 +188,10 @@ export function useSubscriptionTierSection() {
}
}
+ const isPendingHere =
+ isUpdatePending || isChangingTier || checkoutRedirect.isRedirectingHere;
const pendingTier =
- isPending && variables?.data?.tier ? variables.data.tier : null;
+ isPendingHere && variables?.data?.tier ? variables.data.tier : null;
return {
subscription: subscription ?? null,
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx
index 23ccf5f7af..837471b1d0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useState } from "react";
import { Button } from "@/components/__legacy__/ui/button";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
import useCredits from "@/hooks/useCredits";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
import { useSearchParams, useRouter } from "next/navigation";
@@ -87,6 +88,8 @@ export default function CreditsPage() {
const topupStatus = searchParams.get("topup") as "success" | "cancel" | null;
const { toast } = useToast();
const toastOnFail = useToastOnFail();
+ const checkoutRedirect = useCheckoutRedirect();
+ const [isRequestingTopUp, setIsRequestingTopUp] = useState(false);
const [isRefundModalOpen, setIsRefundModalOpen] = useState(false);
const [topUpTransactions, setTopUpTransactions] = useState<
@@ -132,10 +135,15 @@ export default function CreditsPage() {
const submitTopUp = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
+ if (isRequestingTopUp || checkoutRedirect.isRedirecting) return;
const form = e.currentTarget;
const amount =
parseInt(new FormData(form).get("topUpAmount") as string) * 100;
- requestTopUp(amount).catch(toastOnFail("request top-up"));
+ setIsRequestingTopUp(true);
+ requestTopUp(amount)
+ .then(() => checkoutRedirect.markRedirecting())
+ .catch(toastOnFail("request top-up"))
+ .finally(() => setIsRequestingTopUp(false));
};
const submitAutoTopUpConfig = (e: React.FormEvent<HTMLFormElement>) => {
@@ -202,7 +210,11 @@ export default function CreditsPage() {
/>
</div>
- <Button type="submit" className="w-full">
+ <Button
+ type="submit"
+ className="w-full"
+ disabled={isRequestingTopUp || checkoutRedirect.isRedirecting}
+ >
Top-up
</Button>
</form>
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
index 867cf9003d..12fd47fd32 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
@@ -1,4 +1,13 @@
-import { setTrialUser } from "@/tests/integrations/trial-fixtures";
+import {
+ getGetTrialsGetTrialStatusMockHandler200,
+ getPostTrialsStartTrialCheckoutMockHandler200,
+} from "@/app/api/__generated__/endpoints/trials/trials.msw";
+import { TopUpForm } from "@/components/layout/TopUpPrompt/TopUpForm/TopUpForm";
+import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
+import {
+ setTrialUser,
+ trialResponse,
+} from "@/tests/integrations/trial-fixtures";
/**
* Card-by-card integration tests for the Settings v2 billing page.
*
@@ -12,11 +21,12 @@ import { setTrialUser } from "@/tests/integrations/trial-fixtures";
* them a fresh `QueryClient`.
*/
-import { fireEvent } from "@testing-library/react";
+import { act, fireEvent } from "@testing-library/react";
import { http, HttpResponse, type JsonBodyType } from "msw";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { server } from "@/mocks/mock-server";
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
import {
installGtagShim,
removeGtagShim,
@@ -1412,6 +1422,75 @@ describe("YourPlanCard begin_checkout", () => {
expect(hits.post).toBe(1);
});
+ it("stays busy while Stripe loads, and is usable again after Back restores the page", async () => {
+ const location = stubLocation();
+ const hits = freeAccount("https://checkout.stripe.com/pay/cs_test");
+
+ render(<YourPlanCard />);
+ const upgrade = await screen.findByRole("button", { name: /start pro/i });
+ fireEvent.click(upgrade);
+ await waitFor(() =>
+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test"),
+ );
+ expect(upgrade.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(upgrade);
+ expect(hits.post).toBe(1);
+
+ restoreFromBackForwardCache();
+
+ expect(upgrade.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(upgrade);
+ await waitFor(() => expect(hits.post).toBe(2));
+ });
+
+ it("keeps the trial and top-up buttons disabled while a plan checkout leaves the page", async () => {
+ const location = stubLocation();
+ freeAccount("https://checkout.stripe.com/pay/cs_test");
+ const trialCheckout = vi.fn(() => ({
+ url: "https://checkout.stripe.com/c/pay/test_trial",
+ }));
+ let topUps = 0;
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({ eligible: true, active: false, status: null }),
+ ),
+ getPostTrialsStartTrialCheckoutMockHandler200(trialCheckout),
+ http.post("*/api/credits", () => {
+ topUps += 1;
+ return HttpResponse.json({
+ checkout_url: "https://checkout.stripe.com/pay/cs_top_up",
+ });
+ }),
+ );
+
+ render(
+ <>
+ <TrialCard />
+ <YourPlanCard />
+ <TopUpForm />
+ </>,
+ );
+ const trial = await screen.findByRole("button", {
+ name: /start 7-day trial/i,
+ });
+ fireEvent.change(screen.getByLabelText("Amount"), {
+ target: { value: "15" },
+ });
+ fireEvent.click(await screen.findByRole("button", { name: /start pro/i }));
+ await waitFor(() =>
+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test"),
+ );
+
+ const topUp = screen.getByRole("button", { name: "Top up" });
+ expect(trial.hasAttribute("disabled")).toBe(true);
+ expect(topUp.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(trial);
+ fireEvent.click(topUp);
+ await act(async () => {});
+ expect(trialCheckout).not.toHaveBeenCalled();
+ expect(topUps).toBe(0);
+ });
+
it("reports no begin_checkout when the tier changes in place", async () => {
vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");
@@ -1431,3 +1510,58 @@ describe("YourPlanCard begin_checkout", () => {
expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([]);
});
});
+
+describe("BalanceCard checkout", () => {
+ const originalLocation = window.location;
+
+ afterEach(() => {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+ });
+
+ it("stays busy while Stripe loads, and is usable again after Back restores the page", async () => {
+ const location = { href: "http://localhost/settings/billing" };
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: location,
+ });
+ let topUps = 0;
+ server.use(
+ jsonHandler("get", "/api/credits", { credits: 1000 }),
+ http.post("*/api/credits", () => {
+ topUps += 1;
+ return HttpResponse.json({
+ checkout_url: "https://checkout.stripe.com/pay/cs_top_up",
+ });
+ }),
+ );
+
+ render(<BalanceCard />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /add credits/i }),
+ );
+ fireEvent.change(screen.getByPlaceholderText(/amount/i), {
+ target: { value: "20" },
+ });
+ const checkout = screen.getByRole("button", {
+ name: /continue to checkout/i,
+ });
+ fireEvent.click(checkout);
+ await waitFor(() =>
+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_top_up"),
+ );
+ expect(checkout.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(checkout);
+ expect(topUps).toBe(1);
+
+ restoreFromBackForwardCache();
+
+ expect(checkout.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(checkout);
+ await waitFor(() => expect(topUps).toBe(2));
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx
index a54d4ab47b..e2490a368c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-actions.test.tsx
@@ -5,6 +5,7 @@ import {
} from "@/app/api/__generated__/endpoints/trials/trials.msw";
import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";
import { server } from "@/mocks/mock-server";
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
import {
installGtagShim,
removeGtagShim,
@@ -228,6 +229,36 @@ describe("trial billing actions", () => {
}
});
+ it("stays busy while Stripe loads, and is usable again after Back restores the page", async () => {
+ const assign = vi
+ .spyOn(window.location, "assign")
+ .mockImplementation(() => {});
+ const checkout = vi.fn(() => ({
+ url: "https://checkout.stripe.com/c/pay/test_trial",
+ }));
+ server.use(
+ getGetTrialsGetTrialStatusMockHandler200(
+ trialResponse({ eligible: true, active: false, status: null }),
+ ),
+ getPostTrialsStartTrialCheckoutMockHandler200(checkout),
+ );
+ render(<TrialCard />);
+ const button = await screen.findByRole("button", {
+ name: /start 7-day trial/i,
+ });
+ fireEvent.click(button);
+ await waitFor(() => expect(assign).toHaveBeenCalledOnce());
+ expect(button.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(button);
+ expect(checkout).toHaveBeenCalledOnce();
+
+ restoreFromBackForwardCache();
+
+ expect(button.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(button);
+ await waitFor(() => expect(checkout).toHaveBeenCalledTimes(2));
+ });
+
it("reports no begin_checkout when the trial checkout fails", async () => {
vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/BalanceCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/BalanceCard.tsx
index ba06a55ec3..d73d8e2939 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/BalanceCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/BalanceCard.tsx
@@ -33,6 +33,7 @@ export function BalanceCard({ index = 0 }: Props) {
setAmount,
isValid,
isAdding,
+ isRedirecting,
handleSubmit,
} = useBalanceCard();
@@ -109,7 +110,7 @@ export function BalanceCard({ index = 0 }: Props) {
type="button"
variant="primary"
size="small"
- disabled={!isValid || isAdding}
+ disabled={!isValid || isAdding || isRedirecting}
loading={isAdding}
onClick={handleSubmit}
data-fast-goal="credit_topup_checkout"
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.ts
index f9d0462450..a77b389508 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.ts
@@ -7,6 +7,7 @@ import {
usePostV1RequestCreditTopUp,
} from "@/app/api/__generated__/endpoints/credits/credits";
import { toast } from "@/components/molecules/Toast/use-toast";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
export function useBalanceCard() {
const {
@@ -23,8 +24,10 @@ export function useBalanceCard() {
},
});
- const { mutateAsync: requestTopUp, isPending: isAdding } =
+ const { mutateAsync: requestTopUp, isPending: isRequestingTopUp } =
usePostV1RequestCreditTopUp();
+ const checkoutRedirect = useCheckoutRedirect();
+ const isAdding = isRequestingTopUp || checkoutRedirect.isRedirectingHere;
const [open, setOpen] = useState(false);
const [amount, setAmount] = useState("");
@@ -38,7 +41,7 @@ export function useBalanceCard() {
numericAmount >= 5;
async function handleSubmit() {
- if (!isValid) return;
+ if (!isValid || isAdding || checkoutRedirect.isRedirecting) return;
try {
const result = await requestTopUp({
data: {
@@ -66,8 +69,8 @@ export function useBalanceCard() {
const url = body?.checkout_url;
if (url) {
- // Navigating away — don't touch React state on the unmounting tree.
window.location.href = url;
+ checkoutRedirect.markRedirecting();
return;
}
@@ -97,6 +100,8 @@ export function useBalanceCard() {
setAmount,
isValid,
isAdding,
+ // Any checkout on the page leaving for Stripe, not just this one.
+ isRedirecting: checkoutRedirect.isRedirecting,
handleSubmit: () => void handleSubmit(),
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingOffer.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingOffer.tsx
index 44d2f429ff..7fa5239425 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingOffer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/BillingOffer.tsx
@@ -127,7 +127,11 @@ export function BillingOffer({ controller }: Props) {
? () => activation.start("/settings/billing")
: controller?.onUpgrade
}
- disabled={isTrial ? activation.isBusy : controller?.isUpdatingTier}
+ disabled={
+ isTrial
+ ? activation.isBusy
+ : controller?.isUpdatingTier || controller?.isRedirecting
+ }
caption={
isTrial
? "Starting now ends your trial early. You’ll review the charge first."
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx
index 4ce1ecdd77..fef5da7796 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/YourPlanCard.tsx
@@ -35,6 +35,7 @@ export function YourPlanCard({ index = 0, showUsage = false }: Props) {
retry,
isLoading,
isUpdatingTier,
+ isRedirecting,
canManagePortal,
canUpgrade,
canDowngrade,
@@ -115,7 +116,7 @@ export function YourPlanCard({ index = 0, showUsage = false }: Props) {
<CycleToggle
value={selectedCycle}
onChange={onCycleChange}
- disabled={isUpdatingTier}
+ disabled={isUpdatingTier || isRedirecting}
/>
) : null}
</div>
@@ -166,7 +167,7 @@ export function YourPlanCard({ index = 0, showUsage = false }: Props) {
variant="primary"
size="small"
onClick={onResume}
- disabled={isUpdatingTier}
+ disabled={isUpdatingTier || isRedirecting}
loading={isUpdatingTier}
>
{plan.isPendingCancel
@@ -181,7 +182,7 @@ export function YourPlanCard({ index = 0, showUsage = false }: Props) {
variant="outline"
size="small"
onClick={onDowngrade}
- disabled={isUpdatingTier}
+ disabled={isUpdatingTier || isRedirecting}
loading={isUpdatingTier}
>
Downgrade to {plan.previousTierLabel}
@@ -206,7 +207,7 @@ export function YourPlanCard({ index = 0, showUsage = false }: Props) {
variant="primary"
size="small"
onClick={onUpgrade}
- disabled={isUpdatingTier}
+ disabled={isUpdatingTier || isRedirecting}
loading={isUpdatingTier && !plan.nextTierIsTeamLink}
data-fast-goal="subscription_upgrade_click"
data-fast-goal-from={plan.label}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts
index af162effce..9880dd07db 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts
@@ -17,6 +17,7 @@ import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models
import type { SubscriptionUpgradePreview } from "@/app/api/__generated__/models/subscriptionUpgradePreview";
import { ApiError } from "@/lib/autogpt-server-api/helpers";
import { toast } from "@/components/molecules/Toast/use-toast";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
import {
centsToUSD,
getSubscriptionValue,
@@ -100,7 +101,9 @@ export function useYourPlanCard() {
// The mutation settles before the Checkout redirect starts; this keeps the
// plan actions busy across the wait for the Ads conversion too.
const [isChangingTier, setIsChangingTier] = useState(false);
- const isUpdatingTier = isUpdatePending || isChangingTier;
+ const checkoutRedirect = useCheckoutRedirect();
+ const isUpdatingTier =
+ isUpdatePending || isChangingTier || checkoutRedirect.isRedirectingHere;
const effectiveTier = subscription.data?.tier ?? null;
const isPaid = effectiveTier !== null && effectiveTier !== "NO_TIER";
@@ -240,7 +243,7 @@ export function useYourPlanCard() {
billingCycle?: SubscriptionTierRequestBillingCycle,
preview?: SubscriptionUpgradePreview,
) {
- if (isUpdatingTier) return false;
+ if (isUpdatingTier || checkoutRedirect.isRedirecting) return false;
setIsChangingTier(true);
try {
return await requestTierChange(tier, billingCycle, preview);
@@ -287,6 +290,7 @@ export function useYourPlanCard() {
// Navigating away — don't refetch (would set state on an
// unmounting component while Stripe Checkout takes over).
window.location.href = url;
+ checkoutRedirect.markRedirecting();
return;
}
await Promise.all([
@@ -629,6 +633,8 @@ export function useYourPlanCard() {
: tierCosts[nextTierKey]
: undefined,
isUpdatingTier,
+ // Any checkout on the page leaving for Stripe, not just this one.
+ isRedirecting: checkoutRedirect.isRedirecting,
upgradeReview,
upgradeUsageMultiplier:
subscription.data?.tier_multipliers?.MAX &&
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/TopUpForm.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/TopUpForm.tsx
index a3eb97cbbf..79daa96ff4 100644
--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/TopUpForm.tsx
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/TopUpForm.tsx
@@ -9,7 +9,7 @@ interface Props {
}
export function TopUpForm({ submitLabel = "Top up", size = "normal" }: Props) {
- const { form, isLoading, submitTopUp } = useTopUpForm();
+ const { form, isLoading, isRedirecting, submitTopUp } = useTopUpForm();
const inputSize = size === "small" ? "small" : "medium";
const buttonSize = size === "small" ? "small" : "large";
@@ -31,7 +31,11 @@ export function TopUpForm({ submitLabel = "Top up", size = "normal" }: Props) {
/>
)}
/>
- <Button type="submit" disabled={isLoading} size={buttonSize}>
+ <Button
+ type="submit"
+ disabled={isLoading || isRedirecting}
+ size={buttonSize}
+ >
{isLoading ? "Redirecting…" : submitLabel}
</Button>
</Form>
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/__tests__/TopUpForm.test.tsx b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/__tests__/TopUpForm.test.tsx
index bdce65975c..7cb66aabc0 100644
--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/__tests__/TopUpForm.test.tsx
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/__tests__/TopUpForm.test.tsx
@@ -1,5 +1,7 @@
-import { describe, expect, test } from "vitest";
+import { http, HttpResponse } from "msw";
+import { describe, expect, test, vi } from "vitest";
import {
+ act,
render,
screen,
fireEvent,
@@ -7,9 +9,19 @@ import {
} from "@/tests/integrations/test-utils";
import { server } from "@/mocks/mock-server";
import { getPostV1RequestCreditTopUpMockHandler } from "@/app/api/__generated__/endpoints/credits/credits.msw";
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
import { TopUpForm } from "../TopUpForm";
+const routerPush = vi.hoisted(() => vi.fn());
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: routerPush, replace: vi.fn(), prefetch: vi.fn() }),
+ usePathname: () => "/copilot",
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({}),
+}));
+
function captureTopUpRequest() {
let body: unknown = null;
server.use(
@@ -68,4 +80,59 @@ describe("TopUpForm", () => {
const button = await screen.findByRole("button", { name: /redirecting/i });
expect((button as HTMLButtonElement).disabled).toBe(true);
});
+
+ test("stays busy while Stripe loads, and is usable again after Back restores the page", async () => {
+ const checkoutURL = "https://checkout.stripe.com/pay/cs_top_up";
+ let topUps = 0;
+ server.use(
+ http.post("*/api/credits", () => {
+ topUps += 1;
+ return HttpResponse.json({ checkout_url: checkoutURL });
+ }),
+ );
+
+ render(<TopUpForm />);
+
+ fireEvent.change(screen.getByLabelText("Amount"), {
+ target: { value: "15" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /top up/i }));
+ await waitFor(() => expect(routerPush).toHaveBeenCalledWith(checkoutURL));
+ await act(async () => {});
+
+ const busy = screen.getByRole("button", { name: /redirecting/i });
+ expect(busy.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(busy);
+ expect(topUps).toBe(1);
+
+ restoreFromBackForwardCache();
+
+ const topUp = screen.getByRole("button", { name: /top up/i });
+ expect(topUp.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(topUp);
+ await waitFor(() => expect(topUps).toBe(2));
+ });
+
+ test("releases the button without leaving when no checkout URL comes back", async () => {
+ let topUps = 0;
+ server.use(
+ http.post("*/api/credits", () => {
+ topUps += 1;
+ return HttpResponse.json({ checkout_url: "" });
+ }),
+ );
+
+ render(<TopUpForm />);
+
+ fireEvent.change(screen.getByLabelText("Amount"), {
+ target: { value: "15" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /top up/i }));
+ await waitFor(() => expect(topUps).toBe(1));
+ await act(async () => {});
+
+ const topUp = await screen.findByRole("button", { name: /top up/i });
+ expect(topUp.hasAttribute("disabled")).toBe(false);
+ expect(routerPush).not.toHaveBeenCalledWith("");
+ });
});
diff --git a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/useTopUpForm.ts b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/useTopUpForm.ts
index 8014b813d2..40a63abeae 100644
--- a/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/useTopUpForm.ts
+++ b/autogpt_platform/frontend/src/components/layout/TopUpPrompt/TopUpForm/useTopUpForm.ts
@@ -1,4 +1,5 @@
import { useToastOnFail } from "@/components/molecules/Toast/use-toast";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
import useCredits from "@/hooks/useCredits";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState } from "react";
@@ -16,22 +17,28 @@ export function useTopUpForm() {
const toastOnFail = useToastOnFail();
const { requestTopUp } = useCredits();
- const [isLoading, setIsLoading] = useState(false);
+ const [isRequesting, setIsRequesting] = useState(false);
+ const checkoutRedirect = useCheckoutRedirect();
+ const isLoading = isRequesting || checkoutRedirect.isRedirectingHere;
const form = useForm<z.infer<typeof topUpSchema>>({
resolver: zodResolver(topUpSchema),
});
async function submitTopUp(data: z.infer<typeof topUpSchema>) {
- setIsLoading(true);
+ if (isLoading || checkoutRedirect.isRedirecting) return;
+ setIsRequesting(true);
await requestTopUp(Math.round(data.amount * 100))
+ .then(() => checkoutRedirect.markRedirecting())
.catch(toastOnFail("request top-up"))
- .finally(() => setIsLoading(false));
+ .finally(() => setIsRequesting(false));
}
return {
form,
isLoading,
+ // Any checkout on the page leaving for Stripe, not just this one.
+ isRedirecting: checkoutRedirect.isRedirecting,
submitTopUp,
};
}
diff --git a/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/OfferActions.tsx b/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/OfferActions.tsx
index c0c92c0630..88ce9c83ed 100644
--- a/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/OfferActions.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/SubscriptionPlans/components/OfferActions.tsx
@@ -24,7 +24,7 @@ export function OfferActions(props: Props) {
size="small"
className="w-full"
loading={props.isStartingTrial}
- disabled={props.isStartingTrial}
+ disabled={props.isStartingTrial || props.isUpdatingTier}
onClick={props.onStartTrial}
>
{action}
@@ -58,6 +58,7 @@ function PaidPlanAction({
plan,
billing,
isUpdatingTier,
+ isStartingTrial,
selectedPlan,
onSelectPlan,
goalSurface,
@@ -76,7 +77,7 @@ function PaidPlanAction({
className={inline ? "h-auto min-w-0 p-0 text-xs text-zinc-500" : "w-full"}
unmask={!inline}
loading={isUpdatingTier && selectedPlan === plan.key}
- disabled={isUpdatingTier}
+ disabled={isUpdatingTier || isStartingTrial}
onClick={handleSelect}
data-fast-goal="plan_cta_click"
data-fast-goal-plan={plan.key.toLowerCase()}
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx
index 86a4ac41fd..8476e1534e 100644
--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialCard.tsx
@@ -30,6 +30,7 @@ export function TrialCardContent({
error,
retry,
isStarting,
+ isBlocked,
isCanceling,
isResuming,
startTrial,
@@ -63,6 +64,7 @@ export function TrialCardContent({
<TrialOffer
trial={trial}
isStarting={isStarting}
+ isBlocked={isBlocked}
onStart={startTrial}
/>
) : (
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx
index a92eadd149..a6d5906020 100644
--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/TrialOffer.tsx
@@ -7,10 +7,11 @@ import { TrialTitle } from "./TrialTitle/TrialTitle";
interface Props {
trial: TrialStatusResponse;
isStarting: boolean;
+ isBlocked: boolean;
onStart: () => void;
}
-export function TrialOffer({ trial, isStarting, onStart }: Props) {
+export function TrialOffer({ trial, isStarting, isBlocked, onStart }: Props) {
const offer = trial.offer;
if (!offer) return null;
return (
@@ -40,7 +41,7 @@ export function TrialOffer({ trial, isStarting, onStart }: Props) {
size="large"
onClick={onStart}
loading={isStarting}
- disabled={isStarting}
+ disabled={isStarting || isBlocked}
className="w-full shrink-0 md:w-auto md:min-w-[11rem]"
>
Start {offer.duration_days}-day trial
diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts
index 1f6f8c0e6e..7edac3804e 100644
--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts
+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts
@@ -1,4 +1,5 @@
import { usePostTrialsStartTrialCheckout } from "@/app/api/__generated__/endpoints/trials/trials";
+import { useCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
import { trackAdsConversionBeforeNavigation } from "@/services/analytics/google-ads";
import { markTrialCheckoutStarted } from "@/services/analytics/monetization-analytics";
@@ -21,12 +22,15 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {
// The mutation settles before the redirect, while the conversion is still
// going out; the button must stay busy until the page actually leaves.
const [isCheckingOut, setIsCheckingOut] = useState(false);
- const isStarting = isCheckoutPending || isCheckingOut;
+ const checkoutRedirect = useCheckoutRedirect();
+ const isStarting =
+ isCheckoutPending || isCheckingOut || checkoutRedirect.isRedirectingHere;
const offer = query.data?.eligible ? query.data.offer : null;
useTrialOfferViewed({ offer, userID, surface: returnTo });
async function startTrial() {
- if (!offer || !userID || isStarting) return;
+ if (!offer || !userID || isStarting || checkoutRedirect.isRedirecting)
+ return;
failure.clearFailure();
setIsCheckingOut(true);
try {
@@ -41,6 +45,7 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {
currency: offer.currency.toUpperCase(),
});
window.location.assign(response.data.url);
+ checkoutRedirect.markRedirecting();
} catch (error) {
failure.reportFailure({ userID, error, fallback: CHECKOUT_FAILED });
await query.refetch();
@@ -58,6 +63,8 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {
queryError: query.isError && !query.data,
retry: () => query.refetch(),
isStarting,
+ // Any checkout on the page leaving for Stripe, not just this one.
+ isBlocked: checkoutRedirect.isRedirecting,
startTrial,
...cancellation,
};
diff --git a/autogpt_platform/frontend/src/hooks/__tests__/useCheckoutRedirect.test.ts b/autogpt_platform/frontend/src/hooks/__tests__/useCheckoutRedirect.test.ts
new file mode 100644
index 0000000000..ad14985e90
--- /dev/null
+++ b/autogpt_platform/frontend/src/hooks/__tests__/useCheckoutRedirect.test.ts
@@ -0,0 +1,162 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { restoreFromBackForwardCache } from "@/tests/integrations/back-forward-cache";
+import {
+ resetCheckoutRedirect,
+ useCheckoutRedirect,
+} from "../useCheckoutRedirect";
+
+describe("useCheckoutRedirect", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ resetCheckoutRedirect();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ function renderTwoButtons() {
+ const first = renderHook(() => useCheckoutRedirect());
+ const second = renderHook(() => useCheckoutRedirect());
+ return { first, second };
+ }
+
+ test("a redirect from one button makes every button on the page busy", () => {
+ const { first, second } = renderTwoButtons();
+
+ act(() => first.result.current.markRedirecting());
+
+ expect(first.result.current.isRedirecting).toBe(true);
+ expect(second.result.current.isRedirecting).toBe(true);
+ expect(first.result.current.isRedirectingHere).toBe(true);
+ expect(second.result.current.isRedirectingHere).toBe(false);
+ });
+
+ test("a button mounted during a redirect starts out busy", () => {
+ const { first } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+
+ const late = renderHook(() => useCheckoutRedirect());
+
+ expect(late.result.current.isRedirecting).toBe(true);
+ });
+
+ test("stays busy after the button that started it unmounts", () => {
+ const { first, second } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+
+ first.unmount();
+
+ expect(second.result.current.isRedirecting).toBe(true);
+ });
+
+ test("listens for pageshow once, however many buttons are on the page", () => {
+ const addListener = vi.spyOn(window, "addEventListener");
+ const removeListener = vi.spyOn(window, "removeEventListener");
+ const { first, second } = renderTwoButtons();
+
+ act(() => first.result.current.markRedirecting());
+ act(() => second.result.current.markRedirecting());
+
+ const pageshow = addListener.mock.calls.filter(
+ ([type]) => type === "pageshow",
+ );
+ expect(pageshow).toHaveLength(1);
+
+ restoreFromBackForwardCache();
+
+ expect(removeListener).toHaveBeenCalledWith("pageshow", pageshow[0][1]);
+ });
+
+ test("stays busy until the page leaves", () => {
+ const { first, second } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+
+ act(() => {
+ vi.advanceTimersByTime(19_999);
+ });
+
+ expect(first.result.current.isRedirecting).toBe(true);
+ expect(second.result.current.isRedirecting).toBe(true);
+ });
+
+ test("lets every button go after 20 seconds if the page never leaves", () => {
+ const { first, second } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+
+ act(() => {
+ vi.advanceTimersByTime(20_000);
+ });
+
+ expect(first.result.current.isRedirecting).toBe(false);
+ expect(second.result.current.isRedirecting).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ test("lets every button go when Back restores the page from the back/forward cache", () => {
+ const { first, second } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+
+ restoreFromBackForwardCache();
+
+ expect(first.result.current.isRedirecting).toBe(false);
+ expect(second.result.current.isRedirecting).toBe(false);
+ expect(first.result.current.isRedirectingHere).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ test("stays busy on a pageshow that is not a back/forward cache restore", () => {
+ const { first } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+
+ act(() => {
+ window.dispatchEvent(new Event("pageshow"));
+ });
+
+ expect(first.result.current.isRedirecting).toBe(true);
+ });
+
+ test("a later redirect from another button is not this button's", () => {
+ const { first, second } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+ restoreFromBackForwardCache();
+
+ act(() => second.result.current.markRedirecting());
+
+ expect(first.result.current.isRedirectingHere).toBe(false);
+ expect(second.result.current.isRedirectingHere).toBe(true);
+ });
+
+ test("resetCheckoutRedirect clears the redirect, its timer and its listener", () => {
+ const removeListener = vi.spyOn(window, "removeEventListener");
+ const { first } = renderTwoButtons();
+ act(() => first.result.current.markRedirecting());
+
+ act(() => resetCheckoutRedirect());
+
+ expect(first.result.current.isRedirecting).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(removeListener).toHaveBeenCalledWith(
+ "pageshow",
+ expect.any(Function),
+ );
+ });
+});
+
+// The store outlives a test, so the global test setup resets it after each
+// one; without that, a redirect left by one test would disable the buttons of
+// the next.
+describe("useCheckoutRedirect between tests", () => {
+ test("a test can leave a redirect running", () => {
+ const { result } = renderHook(() => useCheckoutRedirect());
+ act(() => result.current.markRedirecting());
+ expect(result.current.isRedirecting).toBe(true);
+ });
+
+ test("the next test starts with no redirect", () => {
+ const { result } = renderHook(() => useCheckoutRedirect());
+ expect(result.current.isRedirecting).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/hooks/useCheckoutRedirect.ts b/autogpt_platform/frontend/src/hooks/useCheckoutRedirect.ts
new file mode 100644
index 0000000000..9ae3958ff3
--- /dev/null
+++ b/autogpt_platform/frontend/src/hooks/useCheckoutRedirect.ts
@@ -0,0 +1,78 @@
+import { useState, useSyncExternalStore } from "react";
+
+// No browser event says a navigation has committed, so a click after this
+// long on a page that still hasn't left is the residual window we accept.
+const CHECKOUT_REDIRECT_TIMEOUT_MS = 20_000;
+
+// One redirect per page, shared by every checkout button on it: a plan, trial
+// or top-up button that hands off to Stripe makes all of them busy until the
+// page leaves. The id tells the button that started it from the others.
+let redirectID: number | null = null;
+let lastRedirectID = 0;
+let timeout: ReturnType<typeof setTimeout> | undefined;
+const subscribers = new Set<() => void>();
+
+function notify() {
+ subscribers.forEach((subscriber) => subscriber());
+}
+
+function subscribe(subscriber: () => void) {
+ subscribers.add(subscriber);
+ return () => {
+ subscribers.delete(subscriber);
+ };
+}
+
+function getRedirectID() {
+ return redirectID;
+}
+
+function getServerRedirectID() {
+ return null;
+}
+
+// Back from Stripe restores this page from the back/forward cache with the
+// busy state intact, so a restore releases it.
+function onPageShow(event: PageTransitionEvent) {
+ if (event.persisted) resetCheckoutRedirect();
+}
+
+function startRedirect() {
+ if (redirectID === null) window.addEventListener("pageshow", onPageShow);
+ clearTimeout(timeout);
+ timeout = setTimeout(resetCheckoutRedirect, CHECKOUT_REDIRECT_TIMEOUT_MS);
+ lastRedirectID += 1;
+ redirectID = lastRedirectID;
+ notify();
+ return redirectID;
+}
+
+export function resetCheckoutRedirect() {
+ if (redirectID === null) return;
+ window.removeEventListener("pageshow", onPageShow);
+ clearTimeout(timeout);
+ timeout = undefined;
+ redirectID = null;
+ notify();
+}
+
+export function useCheckoutRedirect() {
+ const currentID = useSyncExternalStore(
+ subscribe,
+ getRedirectID,
+ getServerRedirectID,
+ );
+ const [ownID, setOwnID] = useState<number | null>(null);
+
+ // Call right after starting the navigation, so a navigation that throws
+ // never marks the page busy.
+ function markRedirecting() {
+ setOwnID(startRedirect());
+ }
+
+ return {
+ isRedirecting: currentID !== null,
+ isRedirectingHere: currentID !== null && currentID === ownID,
+ markRedirecting,
+ };
+}
diff --git a/autogpt_platform/frontend/src/hooks/useCredits.ts b/autogpt_platform/frontend/src/hooks/useCredits.ts
index de029901b4..7229a45acf 100644
--- a/autogpt_platform/frontend/src/hooks/useCredits.ts
+++ b/autogpt_platform/frontend/src/hooks/useCredits.ts
@@ -85,6 +85,9 @@ export default function useCredits({
const requestTopUp = useCallback(
async (credit_amount: number) => {
const response = await api.requestTopUp(credit_amount);
+ if (!response.checkout_url) {
+ throw new Error("Checkout didn't start. Please try again later.");
+ }
router.push(response.checkout_url);
},
[api, router],
diff --git a/autogpt_platform/frontend/src/tests/integrations/back-forward-cache.ts b/autogpt_platform/frontend/src/tests/integrations/back-forward-cache.ts
new file mode 100644
index 0000000000..866944ae2b
--- /dev/null
+++ b/autogpt_platform/frontend/src/tests/integrations/back-forward-cache.ts
@@ -0,0 +1,12 @@
+import { act } from "@testing-library/react";
+
+// What the browser fires when Back brings the page out of its back/forward
+// cache: the same document, with every React state exactly as it was left.
+// happy-dom's PageTransitionEvent is a plain Event, so `persisted` is set here.
+export function restoreFromBackForwardCache() {
+ const event = new Event("pageshow");
+ Object.defineProperty(event, "persisted", { value: true });
+ act(() => {
+ window.dispatchEvent(event);
+ });
+}
diff --git a/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx b/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx
index 291bf7f14e..4bca971764 100644
--- a/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx
+++ b/autogpt_platform/frontend/src/tests/integrations/vitest.setup.tsx
@@ -3,6 +3,7 @@ import { server } from "@/mocks/mock-server";
import { mockNextjsModules } from "./setup-nextjs-mocks";
import { mockAuthRequest } from "./mock-auth-request";
import { cleanup } from "@testing-library/react";
+import { resetCheckoutRedirect } from "@/hooks/useCheckoutRedirect";
// React 18.3 only ships `cache` under the `react-server` export condition.
// Vitest doesn't set that condition, so any module that imports `cache` from
@@ -26,5 +27,8 @@ beforeAll(() => {
afterEach(() => {
cleanup();
server.resetHandlers();
+ // The checkout redirect is page-wide state that outlives a render; a
+ // redirect left by one test would disable the next test's buttons.
+ resetCheckoutRedirect();
});
afterAll(() => server.close());