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): send Plan selected before the Stripe redirect and add a Trial started conversion (hotfix) (#15097)
Krzysztof Czerwinskid58d41bb289c
diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.defaultindex a544fdfce9..77c0e0f92b 100644--- a/autogpt_platform/frontend/.env.default+++ b/autogpt_platform/frontend/.env.default@@ -81,7 +81,7 @@ NEXT_PUBLIC_GA_MEASUREMENT_ID=G-FH2XK2W4GN# Google Ads conversion tracking (production only). The account's tag ID and# one label per conversion action, e.g.-# "sign_up=AbCdEf,begin_checkout=GhIjKl,subscribe=MnOpQr,onboarding_complete=StUvWx,top_up=YzAbCd"+# "sign_up=AbCdEf,begin_checkout=GhIjKl,subscribe=MnOpQr,onboarding_complete=StUvWx,top_up=YzAbCd,trial_started=EfGhIj"NEXT_PUBLIC_GOOGLE_ADS_ID=NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS=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 9240e90eb9..90f5759355 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@@ -3,7 +3,7 @@ import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/modelsimport { toast } from "@/components/molecules/Toast/use-toast";import {getSubscriptionValue,- trackAdsConversion,+ trackAdsConversionBeforeNavigation,} from "@/services/analytics/google-ads";import { environment } from "@/services/environment";import { useState } from "react";@@ -116,7 +116,7 @@ export function useSubscriptionStep() {// A Checkout URL is the only proof that Stripe Checkout actually// starts — reporting earlier would count the in-place and failed// paths as conversions.- trackAdsConversion("begin_checkout", {+ await trackAdsConversionBeforeNavigation("begin_checkout", {value: getSubscriptionValue(planKey, cycle),});// Navigating away — don't refetch (would set state on andiff --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 b60c9a065c..ad1d3f9128 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@@ -264,10 +264,17 @@ describe("SubscriptionStep", () => {expect(gtagCalls).toContainEqual(["event","conversion",- { send_to: "AW-123/BC", value: 50, currency: "USD" },+ {+ send_to: "AW-123/BC",+ value: 50,+ currency: "USD",+ event_callback: expect.any(Function),+ },]);});- expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test");+ await waitFor(() =>+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test"),+ );});test("reports no begin_checkout when Stripe returns no Checkout URL", async () => {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.tsxindex f8e59a64d0..28b235ddf0 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@@ -217,7 +217,12 @@ test("retains paid checkout, Google Ads value, and DataFast metadata while a triexpect(gtag).toContainEqual(["event","conversion",- { send_to: "AW-123/BC", value: 50, currency: "USD" },+ {+ send_to: "AW-123/BC",+ value: 50,+ currency: "USD",+ event_callback: expect.any(Function),+ },]);expect(checkoutLocation.assign).not.toHaveBeenCalled();});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.tsxindex 09dd366a00..3210638a35 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@@ -419,9 +419,53 @@ describe("PaywallModal — upgrade mutation", () => {expect(gtagCalls).toContainEqual(["event","conversion",- { send_to: "AW-123/BC", value: 50, currency: "USD" },+ {+ send_to: "AW-123/BC",+ value: 50,+ currency: "USD",+ event_callback: expect.any(Function),+ },]);});+ const conversion = gtagCalls.find((call) => call[1] === "conversion");+ (conversion?.[2] as { event_callback: () => void }).event_callback();+ await waitFor(() => {+ expect(window.location.href).toBe(+ "https://checkout.stripe.com/pay/cs_test",+ );+ });+ removeGtagShim();+ vi.unstubAllEnvs();+ });++ it("stays busy while the conversion goes out, so a second click starts no second checkout", async () => {+ stubLocation();+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");+ const gtagCalls = installGtagShim();+ 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: /upgrade to pro/i });+ fireEvent.click(upgrade);+ await waitFor(() =>+ expect(gtagCalls.some((call) => call[1] === "conversion")).toBe(true),+ );+ expect(upgrade.hasAttribute("disabled")).toBe(true);+ fireEvent.click(upgrade);++ await waitFor(() => {+ expect(window.location.href).toBe(+ "https://checkout.stripe.com/pay/cs_test",+ );+ });+ expect(mutateFn).toHaveBeenCalledTimes(1);removeGtagShim();vi.unstubAllEnvs();});diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.tsindex da79ecaa86..39c8aaef80 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts@@ -22,7 +22,7 @@ import { getEligibleTrialOffer } from "@/components/organisms/SubscriptionPlans/import { useTrialCard } from "@/components/organisms/TrialCard/useTrialCard";import {getSubscriptionValue,- trackAdsConversion,+ trackAdsConversionBeforeNavigation,} from "@/services/analytics/google-ads";interface CheckoutResponse {@@ -105,6 +105,11 @@ export function usePaywallModal() {const trial = useTrialCard("billing");const trialOffer = getEligibleTrialOffer(trial, plans);+ // 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;+const hasActiveStripeSubscription = Boolean(subscription?.has_active_stripe_subscription,);@@ -134,7 +139,7 @@ export function usePaywallModal() {// plan definition is only the fallback for a tier priced nowhere else.const plan = plans.find((candidate) => candidate.key === tier);const apiValue = isYearly ? plan?.usdYearly : plan?.usdMonthly;- trackAdsConversion("begin_checkout", {+ await trackAdsConversionBeforeNavigation("begin_checkout", {value: apiValue ?? getSubscriptionValue(tier, cycle),});window.location.href = url;@@ -160,7 +165,7 @@ export function usePaywallModal() {}async function handleSelectPlan(tier: string) {- if (isPending) return;+ if (isCheckingOut) return;// Team (BUSINESS) is contact-sales, not a self-serve Stripe Checkout —// divert to the intake form like onboarding + Settings billing do.// Without this, the POST hits the backend with tier=BUSINESS which 422s@@ -180,7 +185,7 @@ export function usePaywallModal() {}async function confirmPendingTier() {- if (!pendingTier) return;+ if (!pendingTier || isCheckingOut) return;const tier = pendingTier;await fireUpdate(tier);setPendingTier(null);@@ -215,7 +220,7 @@ export function usePaywallModal() {selectedCycle,setSelectedCycle,handleSelectPlan,- isPending,+ isPending: isCheckingOut,selectedTier,pendingTier,pendingTierLabel,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.tsindex 97d2464f63..2cf7ea5a83 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@@ -11,7 +11,7 @@ import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { getTierLabel } from "./helpers";import {getSubscriptionValue,- trackAdsConversion,+ trackAdsConversionBeforeNavigation,} from "@/services/analytics/google-ads";export type SubscriptionStatus = SubscriptionStatusResponse;@@ -29,6 +29,9 @@ export function useSubscriptionTierSection() {const [pendingUpgradeTier, setPendingUpgradeTier] = useState<string | null>(null,);+ // The mutation settles before the Checkout redirect starts; this keeps the+ // tier buttons busy across the wait for the Ads conversion too.+ const [isChangingTier, setIsChangingTier] = useState(false);const {data: subscription,@@ -43,9 +46,10 @@ export function useSubscriptionTierSection() {const {mutateAsync: doUpdateTier,- isPending,+ isPending: isUpdatePending,variables,} = useUpdateSubscriptionTier();+ const isPending = isUpdatePending || isChangingTier;useEffect(() => {if (subscriptionStatus === "success") {@@ -71,7 +75,9 @@ export function useSubscriptionTierSection() {}, [subscriptionStatus, refetch, toast, router, pathname]);async function changeTier(tier: string) {+ if (isPending) return;setTierError(null);+ setIsChangingTier(true);try {// Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page// report the subscription to Google Ads. This surface has no cycle@@ -86,7 +92,7 @@ export function useSubscriptionTierSection() {},});if (result.status === 200 && result.data.url) {- trackAdsConversion("begin_checkout", {+ await trackAdsConversionBeforeNavigation("begin_checkout", {value: getSubscriptionValue(tier, "monthly"),});window.location.href = result.data.url;@@ -111,6 +117,8 @@ export function useSubscriptionTierSection() {const msg =e instanceof Error ? e.message : "Failed to change subscription tier";setTierError(msg);+ } finally {+ setIsChangingTier(false);}}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.tsxindex d9e0cb3f06..2120e9e4f6 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@@ -1303,10 +1303,39 @@ describe("YourPlanCard begin_checkout", () => {expect(gtagCalls).toContainEqual(["event","conversion",- { send_to: "AW-123/BC", value: 49, currency: "USD" },+ {+ send_to: "AW-123/BC",+ value: 49,+ currency: "USD",+ event_callback: expect.any(Function),+ },]);});- expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test");+ await waitFor(() =>+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test"),+ );+ });++ it("stays busy while the conversion goes out, so a second click starts no second checkout", async () => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");+ const gtagCalls = installGtagShim();+ const location = stubLocation();+ const hits = freeAccount("https://checkout.stripe.com/pay/cs_test");++ render(<YourPlanCard />);+ const upgrade = await screen.findByRole("button", { name: /get pro/i });+ fireEvent.click(upgrade);+ await waitFor(() =>+ expect(gtagCalls.some((call) => call[1] === "conversion")).toBe(true),+ );+ expect(upgrade.hasAttribute("disabled")).toBe(true);+ fireEvent.click(upgrade);++ await waitFor(() =>+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test"),+ );+ expect(hits.post).toBe(1);});it("reports no begin_checkout when the tier changes in place", async () => {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.tsxindex 15213bee0e..a108158bda 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,10 @@ import {} from "@/app/api/__generated__/endpoints/trials/trials.msw";import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";import { server } from "@/mocks/mock-server";+import {+ installGtagShim,+ removeGtagShim,+} from "@/tests/integrations/gtag-shim";import {fireEvent,render,@@ -122,6 +126,134 @@ describe("trial billing actions", () => {},);+ it.each([+ { offer: trialOffer, value: 20, currency: "USD" },+ {+ offer: {+ ...trialOffer,+ billing_cycle: "yearly" as const,+ currency: "jpy",+ unit_amount: 30000,+ },+ value: 30000,+ currency: "JPY",+ },+ ])(+ "reports begin_checkout at the offer's $value $currency before redirecting",+ async ({ offer, value, currency }) => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv(+ "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",+ "begin_checkout=BC",+ );+ const gtagCalls = installGtagShim();+ const assign = vi+ .spyOn(window.location, "assign")+ .mockImplementation(() => {});+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({ eligible: true, active: false, status: null, offer }),+ ),+ getPostTrialsStartTrialCheckoutMockHandler200({+ url: "https://checkout.stripe.com/c/pay/test_trial",+ }),+ );+ try {+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: /start 7-day trial/i }),+ );+ await waitFor(() =>+ expect(assign).toHaveBeenCalledWith(+ "https://checkout.stripe.com/c/pay/test_trial",+ ),+ );+ expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([+ [+ "event",+ "conversion",+ {+ send_to: "AW-123/BC",+ value,+ currency,+ event_callback: expect.any(Function),+ },+ ],+ ]);+ } finally {+ removeGtagShim();+ vi.unstubAllEnvs();+ }+ },+ );++ it("stays busy while the conversion goes out, so a second click starts no second checkout", async () => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");+ const gtagCalls = installGtagShim();+ 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),+ );+ try {+ render(<TrialCard />);+ const button = await screen.findByRole("button", {+ name: /start 7-day trial/i,+ });+ fireEvent.click(button);+ await waitFor(() =>+ expect(gtagCalls.some((call) => call[1] === "conversion")).toBe(true),+ );+ expect(button.hasAttribute("disabled")).toBe(true);+ fireEvent.click(button);+ await waitFor(() => expect(assign).toHaveBeenCalledOnce());+ expect(checkout).toHaveBeenCalledOnce();+ expect(gtagCalls.filter((call) => call[1] === "conversion")).toHaveLength(+ 1,+ );+ } finally {+ removeGtagShim();+ vi.unstubAllEnvs();+ }+ });++ 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");+ const gtagCalls = installGtagShim();+ const assign = vi+ .spyOn(window.location, "assign")+ .mockImplementation(() => {});+ server.use(+ getGetTrialsGetTrialStatusMockHandler200(+ trialResponse({ eligible: true, active: false, status: null }),+ ),+ http.post("*/api/credits/trial", () =>+ HttpResponse.json({ detail: "Stripe is unavailable" }, { status: 502 }),+ ),+ );+ try {+ render(<TrialCard />);+ fireEvent.click(+ await screen.findByRole("button", { name: /start 7-day trial/i }),+ );+ await screen.findByRole("alert");+ expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([]);+ expect(assign).not.toHaveBeenCalled();+ } finally {+ removeGtagShim();+ vi.unstubAllEnvs();+ }+ });+it("refreshes an expired offer after checkout is rejected", async () => {let rejected = false;server.use(diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-confirmation.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-confirmation.test.tsxindex 0ed05e2b65..5e88eab54d 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-confirmation.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/trial-confirmation.test.tsx@@ -5,6 +5,15 @@ import {import { TrialCard } from "@/components/organisms/TrialCard/TrialCard";import { TrialCheckoutConfirmation } from "@/components/organisms/TrialCard/TrialCheckoutConfirmation";import { server } from "@/mocks/mock-server";+import {+ configureCookiebot,+ installCookiebot,+ removeCookiebot,+} from "@/tests/integrations/cookiebot";+import {+ installGtagShim,+ removeGtagShim,+} from "@/tests/integrations/gtag-shim";import {fireEvent,render,@@ -154,3 +163,114 @@ describe("trial Checkout return", () => {}});});++describe("trial start Google Ads conversion", () => {+ let gtagCalls: unknown[][] = [];++ beforeEach(() => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "trial_started=TS");+ configureCookiebot();+ installCookiebot({ statistics: true, marketing: true });+ gtagCalls = installGtagShim();+ window.history.replaceState(null, "", "/settings/billing?trial=success");+ searchParams = new URLSearchParams(window.location.search);+ });++ afterEach(() => {+ removeGtagShim();+ removeCookiebot();+ vi.unstubAllEnvs();+ window.history.replaceState(null, "", "/");+ });++ function conversions() {+ return gtagCalls.filter((call) => call[1] === "conversion");+ }++ it("reports one trial start per user, across re-renders and a reload", async () => {+ const confirm = vi.fn(() => trialResponse());+ server.use(getPostTrialsConfirmTrialMockHandler200(confirm));+ const { rerender, unmount } = renderTrialReturn();+ await screen.findByRole("button", { name: "Cancel trial" });+ rerender(+ <>+ <TrialCheckoutConfirmation />+ <TrialCard />+ </>,+ );+ expect(conversions()).toEqual([+ [+ "event",+ "conversion",+ {+ send_to: "AW-123/TS",+ transaction_id: "trial-user",+ user_data: { email: "[email protected]" },+ },+ ],+ ]);+ expect(window.location.search).toBe("");++ unmount();+ server.use(getGetTrialsGetTrialStatusMockHandler200(trialResponse()));+ searchParams = new URLSearchParams(window.location.search);+ renderTrialReturn();+ await screen.findByRole("button", { name: "Cancel trial" });+ expect(confirm).toHaveBeenCalledOnce();+ expect(conversions()).toHaveLength(1);+ });++ it("does not report a confirmation that leaves the trial inactive", async () => {+ server.use(+ getPostTrialsConfirmTrialMockHandler200(+ trialResponse({ active: false, status: "trialing" }),+ ),+ );+ renderTrialReturn();+ await screen.findByText(/Your trial is not active/);+ expect(conversions()).toEqual([]);+ expect(window.location.search).toBe("?trial=success");+ });++ it("does not report a failed confirmation", async () => {+ server.use(+ http.post("*/api/credits/trial/confirm", () =>+ HttpResponse.json(+ { detail: "Card setup is not complete yet" },+ { status: 409 },+ ),+ ),+ );+ renderTrialReturn();+ await screen.findByRole("button", { name: /try again/i });+ expect(conversions()).toEqual([]);+ });++ it("does not report a trial that already converted to paid", async () => {+ const confirm = vi.fn(() =>+ trialResponse({ active: false, converted: true, status: "active" }),+ );+ server.use(getPostTrialsConfirmTrialMockHandler200(confirm));+ renderTrialReturn();+ await waitFor(() => expect(confirm).toHaveBeenCalledOnce());+ await waitFor(() => expect(screen.queryByRole("status")).toBeNull());+ expect(conversions()).toEqual([]);+ });++ it("does not confirm again on reload when the tag could not take the conversion", async () => {+ removeGtagShim();+ const confirm = vi.fn(() => trialResponse());+ server.use(getPostTrialsConfirmTrialMockHandler200(confirm));+ const { unmount } = renderTrialReturn();+ await screen.findByRole("button", { name: "Cancel trial" });+ expect(window.location.search).toBe("");++ unmount();+ server.use(getGetTrialsGetTrialStatusMockHandler200(trialResponse()));+ searchParams = new URLSearchParams(window.location.search);+ renderTrialReturn();+ await screen.findByRole("button", { name: "Cancel trial" });+ expect(confirm).toHaveBeenCalledOnce();+ });+});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.tsindex 0b2db15204..181403cb3a 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@@ -16,7 +16,7 @@ import { toast } from "@/components/molecules/Toast/use-toast";import {centsToUSD,getSubscriptionValue,- trackAdsConversion,+ trackAdsConversionBeforeNavigation,} from "@/services/analytics/google-ads";import { formatCents, formatShortDate } from "../../../helpers";@@ -74,8 +74,12 @@ export function useYourPlanCard() {},});- const { mutateAsync: updateTier, isPending: isUpdatingTier } =+ const { mutateAsync: updateTier, isPending: isUpdatePending } =useUpdateSubscriptionTier();+ // 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 effectiveTier = subscription.data?.tier ?? null;const isPaid = effectiveTier !== null && effectiveTier !== "NO_TIER";@@ -191,6 +195,19 @@ export function useYourPlanCard() {async function changeTier(tier: SubscriptionTierRequestTier,billingCycle?: SubscriptionTierRequestBillingCycle,+ ) {+ if (isUpdatingTier) return false;+ setIsChangingTier(true);+ try {+ return await requestTierChange(tier, billingCycle);+ } finally {+ setIsChangingTier(false);+ }+ }++ async function requestTierChange(+ tier: SubscriptionTierRequestTier,+ billingCycle?: SubscriptionTierRequestBillingCycle,) {const cycle = billingCycle ?? "monthly";// Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page@@ -215,7 +232,7 @@ export function useYourPlanCard() {// plan-card figure is only the fallback when the tier isn't priced there.const cents =cycle === "yearly" ? tierCostsYearly[tier] : tierCosts[tier];- trackAdsConversion("begin_checkout", {+ await trackAdsConversionBeforeNavigation("begin_checkout", {value: centsToUSD(cents) ?? getSubscriptionValue(tier, cycle),});// Navigating away — don't refetch (would set state on andiff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.tsindex 8af6569a64..b8356d34fb 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/helpers.ts@@ -8,15 +8,25 @@ export const trialPlanLabels: Record<TrialOfferResponse["tier"], string> = {};export function formatTrialPrice(offer: TrialOfferResponse) {- const formatter = new Intl.NumberFormat("en-US", {- style: "currency",- currency: offer.currency,- });- const decimals = formatter.resolvedOptions().maximumFractionDigits ?? 2;- const amount = formatter.format(offer.unit_amount / 10 ** decimals);+ const amount = currencyFormatter(offer.currency).format(+ getTrialChargeAmount(offer),+ );return `${amount} / ${offer.billing_cycle === "yearly" ? "year" : "month"}`;}+// What Stripe charges per billing cycle once the trial ends, in major units.+// Zero-decimal currencies (JPY) carry no minor unit.+export function getTrialChargeAmount(offer: TrialOfferResponse) {+ const decimals =+ currencyFormatter(offer.currency).resolvedOptions().maximumFractionDigits ??+ 2;+ return offer.unit_amount / 10 ** decimals;+}++function currencyFormatter(currency: string) {+ return new Intl.NumberFormat("en-US", { style: "currency", currency });+}+export function formatTrialEnd(value: Date | string | null | undefined) {if (!value) return "the end of your trial";return new Date(value).toLocaleString(undefined, {diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.tsindex 23fddf8225..dd0bf24be7 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts@@ -3,12 +3,14 @@ import {usePostTrialsStartTrialCheckout,} from "@/app/api/__generated__/endpoints/trials/trials";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { trackAdsConversionBeforeNavigation } from "@/services/analytics/google-ads";import { TrialEvent } from "@/services/analytics/posthog-events";import { useTrialStatus } from "@/services/trials/useTrialStatus";import { updateTrialStatusCache } from "@/services/trials/updateTrialStatusCache";import { useQueryClient } from "@tanstack/react-query";import { usePostHog } from "@posthog/react";import { useEffect, useRef, useState } from "react";+import { getTrialChargeAmount } from "./helpers";export function useTrialCard(returnTo: "onboarding" | "billing") {const userID = useAuthStore((state) => state.user?.id);@@ -20,8 +22,12 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {message: string;} | null>(null);const query = useTrialStatus();- const { mutateAsync: checkout, isPending: isStarting } =+ const { mutateAsync: checkout, isPending: isCheckoutPending } =usePostTrialsStartTrialCheckout();+ // 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 { mutateAsync: cancel, isPending: isCanceling } =usePostTrialsCancelTrial();const offer = query.data?.eligible ? query.data.offer : null;@@ -42,6 +48,7 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {async function startTrial() {if (!offer || !userID || isStarting) return;setFailure(null);+ setIsCheckingOut(true);try {const response = await checkout({data: { offer_token: offer.token, return_to: returnTo },@@ -53,6 +60,10 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {trial_offer_version: offer.version,surface: returnTo,});+ await trackAdsConversionBeforeNavigation("begin_checkout", {+ value: getTrialChargeAmount(offer),+ currency: offer.currency.toUpperCase(),+ });window.location.assign(response.data.url);} catch (error) {setFailure({@@ -63,6 +74,8 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {: "Unable to start trial checkout.",});await query.refetch();+ } finally {+ setIsCheckingOut(false);}}diff --git a/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts b/autogpt_platform/frontend/src/services/analytics/google-ads.test.tsindex b3fe02be37..ca296e0a8a 100644--- a/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts+++ b/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts@@ -10,9 +10,11 @@ import {removeCookiebot,} from "@/tests/integrations/cookiebot";import {+ CONVERSION_SEND_TIMEOUT_MS,getSubscriptionValue,parseConversionLabels,trackAdsConversion,+ trackAdsConversionBeforeNavigation,trackAdsPageView,} from "./google-ads";@@ -28,7 +30,7 @@ describe("trackAdsConversion", () => {vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",- "sign_up=SIGNUP,subscribe=SUB",+ "sign_up=SIGNUP,subscribe=SUB,trial_started=TS",);configureCookiebot();installCookiebot();@@ -119,6 +121,25 @@ describe("trackAdsConversion", () => {]);});+ it("sends a trial start to its own action", () => {+ trackAdsConversion("trial_started", {+ transactionID: "user-1",+ email: "[email protected]",+ });++ expect(pushed).toEqual([+ [+ "event",+ "conversion",+ {+ send_to: "AW-123/TS",+ transaction_id: "user-1",+ user_data: { email: "[email protected]" },+ },+ ],+ ]);+ });+it("does nothing when the Google Ads tag is not configured", () => {vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "");@@ -132,6 +153,126 @@ describe("trackAdsConversion", () => {});});+describe("trackAdsConversionBeforeNavigation", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ pushed = installGtagShim();+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");+ configureCookiebot();+ installCookiebot();+ answerBanner(true);+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllEnvs();+ removeGtagShim();+ removeCookiebot();+ });++ function navigateAfterConversion() {+ const navigate = vi.fn();+ void trackAdsConversionBeforeNavigation("begin_checkout", {+ value: 50,+ transactionID: "cs_123",+ }).then(navigate);+ return navigate;+ }++ function sendCallback() {+ const params = pushed[0][2] as { event_callback: () => void };+ params.event_callback();+ }++ it("sends the same conversion as trackAdsConversion, plus a callback", () => {+ navigateAfterConversion();++ expect(pushed).toEqual([+ [+ "event",+ "conversion",+ {+ send_to: "AW-123/BC",+ value: 50,+ currency: "USD",+ transaction_id: "cs_123",+ event_callback: expect.any(Function),+ },+ ],+ ]);+ });++ it("navigates once the tag reports the hit sent", async () => {+ const navigate = navigateAfterConversion();+ await vi.advanceTimersByTimeAsync(0);+ expect(navigate).not.toHaveBeenCalled();++ sendCallback();+ await vi.advanceTimersByTimeAsync(0);+ expect(navigate).toHaveBeenCalledOnce();++ await vi.advanceTimersByTimeAsync(CONVERSION_SEND_TIMEOUT_MS);+ expect(navigate).toHaveBeenCalledOnce();+ });++ it("navigates after the timeout when the tag never reports back", async () => {+ const navigate = navigateAfterConversion();++ await vi.advanceTimersByTimeAsync(CONVERSION_SEND_TIMEOUT_MS - 1);+ expect(navigate).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(navigate).toHaveBeenCalledOnce();++ sendCallback();+ await vi.advanceTimersByTimeAsync(CONVERSION_SEND_TIMEOUT_MS);+ expect(navigate).toHaveBeenCalledOnce();+ });++ it("navigates straight away when the Ads tag is not configured", async () => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "");++ const navigate = navigateAfterConversion();+ await vi.advanceTimersByTimeAsync(0);++ expect(navigate).toHaveBeenCalledOnce();+ expect(pushed).toEqual([]);+ });++ it("navigates straight away for an action without a label", async () => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "sign_up=SIGNUP");++ const navigate = navigateAfterConversion();+ await vi.advanceTimersByTimeAsync(0);++ expect(navigate).toHaveBeenCalledOnce();+ expect(pushed).toEqual([]);+ });++ it("navigates straight away when gtag is not on the page", async () => {+ removeGtagShim();++ const navigate = navigateAfterConversion();+ await vi.advanceTimersByTimeAsync(0);++ expect(navigate).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("navigates straight away when the tag throws", async () => {+ window.gtag = () => {+ throw new Error("tag broke");+ };++ const navigate = navigateAfterConversion();+ await vi.advanceTimersByTimeAsync(0);++ expect(navigate).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ expect(trackAdsConversion("begin_checkout")).toBe(false);+ });+});+describe("trackAdsPageView", () => {beforeEach(() => {pushed = installGtagShim();@@ -162,9 +303,9 @@ describe("parseConversionLabels", () => {it("reads key=label pairs and ignores unknown or malformed parts", () => {expect(parseConversionLabels(- " sign_up=AbC , subscribe=DeF,unknown=X,,broken,top_up= ",+ " sign_up=AbC , subscribe=DeF,unknown=X,,broken,top_up= ,trial_started=GhI",),- ).toEqual({ sign_up: "AbC", subscribe: "DeF" });+ ).toEqual({ sign_up: "AbC", subscribe: "DeF", trial_started: "GhI" });});it("returns nothing for an unset value", () => {diff --git a/autogpt_platform/frontend/src/services/analytics/google-ads.ts b/autogpt_platform/frontend/src/services/analytics/google-ads.tsindex 4cac4ad7c1..361b16ac06 100644--- a/autogpt_platform/frontend/src/services/analytics/google-ads.ts+++ b/autogpt_platform/frontend/src/services/analytics/google-ads.ts@@ -8,13 +8,15 @@ import { gtag } from "./gtag";// One entry per conversion action in the Google Ads account. The action's// label comes from NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS so the account can-// be rewired without a deploy.+// be rewired without a code change. Next inlines the value at build time, so a+// new label still needs a rebuild.export const ADS_CONVERSIONS = ["sign_up","begin_checkout","subscribe","onboarding_complete","top_up",+ "trial_started",] as const;export type AdsConversion = (typeof ADS_CONVERSIONS)[number];@@ -32,10 +34,44 @@ export function trackAdsConversion(name: AdsConversion,options: ConversionOptions = {},): boolean {+ const params = conversionParams(name, options);+ if (!params) return false;+ return gtag("event", "conversion", params);+}++// gtag calls event_callback once the hit is out, but never when the tag is+// blocked or hasn't loaded, so the wait is capped.+export const CONVERSION_SEND_TIMEOUT_MS = 300;++// A conversion fired in the same tick as a full-page navigation is dropped+// with the page. Await this before leaving: it resolves once the tag reports+// the hit sent, when the timeout runs out, or straight away when nothing was+// sent. It never rejects.+export function trackAdsConversionBeforeNavigation(+ name: AdsConversion,+ options: ConversionOptions = {},+): Promise<void> {+ return new Promise((resolve) => {+ const params = conversionParams(name, options);+ if (!params) return resolve();+ const timeout = setTimeout(resolve, CONVERSION_SEND_TIMEOUT_MS);+ function sent() {+ clearTimeout(timeout);+ resolve();+ }+ if (!gtag("event", "conversion", { ...params, event_callback: sent }))+ sent();+ });+}++function conversionParams(+ name: AdsConversion,+ options: ConversionOptions,+): Record<string, unknown> | null {const adsID = environment.getGoogleAdsID();- if (!adsID) return false;+ if (!adsID) return null;const label = conversionLabels()[name];- if (!label) return false;+ if (!label) return null;const params: Record<string, unknown> = { send_to: `${adsID}/${label}` };if (options.value !== undefined) {@@ -48,8 +84,7 @@ export function trackAdsConversion(if (options.transactionID) params.transaction_id = options.transactionID;if (options.email) params.user_data = { email: options.email };}-- return gtag("event", "conversion", params);+ return params;}// An unanswered banner is not a yes. Consent Mode starts every visitor withdiff --git a/autogpt_platform/frontend/src/services/analytics/gtag.ts b/autogpt_platform/frontend/src/services/analytics/gtag.tsindex 3b69baba85..43e9062c55 100644--- a/autogpt_platform/frontend/src/services/analytics/gtag.ts+++ b/autogpt_platform/frontend/src/services/analytics/gtag.ts@@ -13,6 +13,11 @@ export function gtag(...args: unknown[]): boolean {if (typeof window === "undefined") return false;const tag = window.gtag;if (typeof tag !== "function") return false;- tag(...args);- return true;+ // Analytics must never break the caller, e.g. a checkout redirect.+ try {+ tag(...args);+ return true;+ } catch {+ return false;+ }}diff --git a/autogpt_platform/frontend/src/services/trials/useTrialCheckoutReturn.ts b/autogpt_platform/frontend/src/services/trials/useTrialCheckoutReturn.tsindex 3cb7553dfe..41ea0a3145 100644--- a/autogpt_platform/frontend/src/services/trials/useTrialCheckoutReturn.ts+++ b/autogpt_platform/frontend/src/services/trials/useTrialCheckoutReturn.ts@@ -1,6 +1,7 @@import { usePostTrialsConfirmTrial } from "@/app/api/__generated__/endpoints/trials/trials";import type { TrialStatusResponse } from "@/app/api/__generated__/models/trialStatusResponse";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { trackAdsConversion } from "@/services/analytics/google-ads";import { useQueryClient } from "@tanstack/react-query";import { useSearchParams } from "next/navigation";import { useEffect, useRef, useState } from "react";@@ -12,6 +13,7 @@ export function useTrialCheckoutReturn() {const isReturn = useRef(false);if (params.get("trial") === "success") isReturn.current = true;const requested = useRef<string | null>(null);+ const reportedTrialStart = useRef<string | null>(null);const [attempt, setAttempt] = useState(0);const [result, setResult] = useState<{userID: string;@@ -44,6 +46,10 @@ export function useTrialCheckoutReturn() {throw new Error("Your trial is not active. Review your card setup and try again.",);+ if (response.data.active && reportedTrialStart.current !== userID) {+ reportedTrialStart.current = userID;+ reportTrialStart(userID);+ }setResult({ userID, trial: response.data });}).catch((error: unknown) => {@@ -71,3 +77,28 @@ export function useTrialCheckoutReturn() {retry,};}++// The return URL carries no Checkout session id, and a user only ever gets one+// trial, so the user id is the dedup key. Google only receives it with+// advertising consent; for everyone else the latch and the dropped query param+// are what stop a re-render or a reload from counting twice. The param goes+// even when the tag couldn't take the hit: a reload won't unblock it, and+// would only confirm the trial again.+function reportTrialStart(userID: string) {+ trackAdsConversion("trial_started", {+ transactionID: userID,+ email: useAuthStore.getState().user?.email,+ });+ dropTrialReturnParam();+}++function dropTrialReturnParam() {+ const url = new URL(window.location.href);+ if (!url.searchParams.has("trial")) return;+ url.searchParams.delete("trial");+ window.history.replaceState(+ null,+ "",+ `${url.pathname}${url.search}${url.hash}`,+ );+}