Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend): fire Google Ads conversions across the signup-to-paid journey (#14165)

Ubbe1c7e3ecb138c
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 5a39bfd4ed..c980d5fedb 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -1207,7 +1207,10 @@ class UserCredit(UserCreditBase):
ui_mode="hosted",
payment_intent_data={"setup_future_usage": "off_session"},
saved_payment_method_options={"payment_method_save": "enabled"},
- success_url=base_url + "/settings/billing?topup=success",
+ # {CHECKOUT_SESSION_ID} is filled by Stripe; the return page uses
+ # it as the Google Ads dedup key so a refresh can't count twice.
+ success_url=base_url
+ + "/settings/billing?topup=success&session_id={CHECKOUT_SESSION_ID}",
cancel_url=base_url + "/settings/billing?topup=cancel",
allow_promotion_codes=True,
automatic_tax={"enabled": True},
diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.default
index f6c0d82517..2ddb6deadd 100644
--- a/autogpt_platform/frontend/.env.default
+++ b/autogpt_platform/frontend/.env.default
@@ -62,6 +62,12 @@ NEXT_PUBLIC_REACT_QUERY_DEVTOOL=true
NEXT_PUBLIC_TOKEN_DEVTOOL=true
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"
+NEXT_PUBLIC_GOOGLE_ADS_ID=
+NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS=
+
# Google Drive Picker
NEXT_PUBLIC_GOOGLE_CLIENT_ID=
NEXT_PUBLIC_GOOGLE_API_KEY=
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx
index e1b3268b75..30699fabeb 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx
@@ -7,6 +7,10 @@ import {
waitFor,
} from "@/tests/integrations/test-utils";
import { server } from "@/mocks/mock-server";
+import {
+ installGtagShim,
+ removeGtagShim,
+} from "@/tests/integrations/gtag-shim";
import { http, HttpResponse } from "msw";
import OnboardingPage from "../page";
import { useOnboardingWizardStore } from "../store";
@@ -130,13 +134,18 @@ beforeEach(() => {
mockRefreshSession.mockClear();
mockCompletedSteps = [];
routerReplace.mockClear();
- completeOnboardingStep.mockClear();
+ completeOnboardingStep.mockReset();
+ completeOnboardingStep.mockResolvedValue({ status: 200 });
useOnboardingWizardStore.getState().reset();
window.sessionStorage.removeItem(STEP_STORAGE_KEY);
});
afterEach(() => {
cleanup();
+ // Not at the end of each test body: an assertion that throws above would
+ // leak the shim and NEXT_PUBLIC_GOOGLE_ADS_ID into every later test here.
+ removeGtagShim();
+ vi.unstubAllEnvs();
});
describe("OnboardingPage — flag-gated SubscriptionStep", () => {
@@ -364,6 +373,55 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {
expect(window.sessionStorage.getItem(STEP_STORAGE_KEY)).toBeNull();
});
+ it("reports onboarding_complete to Google Ads when Preparing finishes", async () => {
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
+ vi.stubEnv(
+ "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",
+ "onboarding_complete=OC",
+ );
+ const gtagCalls = installGtagShim();
+ mockFlagValue = false;
+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");
+ currentSearchParams = new URLSearchParams("step=4");
+ render(<OnboardingPage />);
+ fireEvent.click(await screen.findByTestId("step-preparing"));
+ await waitFor(() => {
+ expect(routerReplace).toHaveBeenCalledWith("/copilot");
+ });
+
+ expect(gtagCalls).toContainEqual([
+ "event",
+ "conversion",
+ { send_to: "AW-123/OC" },
+ ]);
+ });
+
+ it("reports no onboarding_complete when the API never confirms", async () => {
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
+ vi.stubEnv(
+ "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",
+ "onboarding_complete=OC",
+ );
+ const gtagCalls = installGtagShim();
+ // All three attempts fail: the user still lands on the copilot, but the
+ // backend never recorded the milestone, so nothing converted.
+ completeOnboardingStep.mockRejectedValue(new Error("500"));
+ mockFlagValue = false;
+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");
+ currentSearchParams = new URLSearchParams("step=4");
+ render(<OnboardingPage />);
+ fireEvent.click(await screen.findByTestId("step-preparing"));
+ await waitFor(
+ () => {
+ expect(routerReplace).toHaveBeenCalledWith("/copilot");
+ },
+ { timeout: 5000 },
+ );
+
+ expect(completeOnboardingStep).toHaveBeenCalledTimes(3);
+ expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([]);
+ }, 10000);
+
it("preserves form data on mount (zustand persist; no reset-on-init)", async () => {
// Regression test for the 422 caused by init's old `reset()` wiping
// name/role on every mount. With zustand persist, refreshing mid-wizard
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 901e6a9b13..94fdd9a409 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts
@@ -1,6 +1,10 @@
import { useUpdateSubscriptionTier } 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 {
+ getSubscriptionValue,
+ trackAdsConversion,
+} from "@/services/analytics/google-ads";
import { environment } from "@/services/environment";
import { useState } from "react";
import { PAYWALL_FIRST_STEPS, useOnboardingWizardStore } from "../../store";
@@ -71,23 +75,31 @@ export function useSubscriptionStep() {
setSelectedPlan(planKey);
const tier = PLAN_TO_TIER[planKey];
+ const cycle = isYearly ? "yearly" : "monthly";
try {
// The paywall is the first step, so there's no profile to submit yet —
// name / role / pain points are collected after payment. On a successful
// checkout Stripe returns the user to Welcome to begin onboarding; on
- // cancel, back to this paywall.
+ // cancel, back to this paywall. Stripe fills {CHECKOUT_SESSION_ID}; plan
+ // and cycle let the return page report the subscription to Google Ads.
const baseUrl = `${window.location.origin}/onboarding`;
const result = await updateTier({
data: {
tier,
- success_url: `${baseUrl}?step=${PAYWALL_FIRST_STEPS.welcome}&subscription=success`,
+ success_url: `${baseUrl}?step=${PAYWALL_FIRST_STEPS.welcome}&subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${planKey}&cycle=${cycle}`,
cancel_url: `${baseUrl}?step=${PAYWALL_FIRST_STEPS.subscription}&subscription=cancelled`,
- billing_cycle: isYearly ? "yearly" : "monthly",
+ billing_cycle: cycle,
},
});
const url = (result?.data as CheckoutResponse | undefined)?.url;
if (url) {
+ // 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", {
+ value: getSubscriptionValue(planKey, cycle),
+ });
// Navigating away — don't refetch (would set state on an
// unmounting component while Stripe Checkout takes over).
window.location.href = url;
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 047a5043d6..8f988fb931 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx
@@ -1,6 +1,5 @@
import { http, HttpResponse } from "msw";
import {
- cleanup,
fireEvent,
render,
screen,
@@ -9,6 +8,10 @@ import {
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { server } from "@/mocks/mock-server";
import { environment } from "@/services/environment";
+import {
+ installGtagShim,
+ removeGtagShim,
+} from "@/tests/integrations/gtag-shim";
import { useOnboardingWizardStore } from "../../store";
import {
getSubscriptionPricingExperimentConfig,
@@ -34,7 +37,14 @@ vi.mock("@/components/atoms/AutoGPTLogo/AutoGPTLogo", () => ({
AutoGPTLogo: () => <span>AutoGPTLogo</span>,
}));
-afterEach(cleanup);
+afterEach(() => {
+ // Not at the end of each test body: an assertion that throws above would
+ // leak the shim, the location stub and NEXT_PUBLIC_GOOGLE_ADS_ID into every
+ // later test here.
+ restoreLocation();
+ removeGtagShim();
+ vi.unstubAllEnvs();
+});
beforeEach(() => {
postHog.variant = undefined;
@@ -46,6 +56,28 @@ beforeEach(() => {
vi.spyOn(environment, "isLocal").mockReturnValue(false);
});
+const originalLocation = window.location;
+
+// The success path hands off to Stripe via window.location.href; jsdom tears
+// the environment down on a real navigation, so swap in a plain object.
+function stubLocation() {
+ const location = { origin: "http://localhost", href: "http://localhost/" };
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: location,
+ });
+ return location;
+}
+
+function restoreLocation() {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+}
+
describe("subscription pricing experiment helpers", () => {
test("defaults to monthly billing with no highlighted plan (matches the paywall)", () => {
expect(getSubscriptionPricingExperimentConfig(undefined)).toMatchObject({
@@ -203,11 +235,63 @@ describe("SubscriptionStep", () => {
expect(capturedTierBody!.cancel_url).toContain(
"/onboarding?step=1&subscription=cancelled",
);
+ // Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page
+ // report the subscription value to Google Ads.
+ expect(capturedTierBody!.success_url).toContain(
+ "&session_id={CHECKOUT_SESSION_ID}&plan=PRO&cycle=monthly",
+ );
// Paywall-first: no profile data exists yet, so nothing is POSTed here —
// the Preparing step submits the profile at the end of onboarding.
expect(profileCalled).toBe(false);
});
+ test("reports begin_checkout with the plan price to Google Ads before redirecting", 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();
+ server.use(
+ http.post("*/api/credits/subscription", () =>
+ HttpResponse.json({ url: "https://checkout.stripe.com/pay/cs_test" }),
+ ),
+ );
+
+ render(<SubscriptionStep />);
+ fireEvent.click(screen.getByRole("button", { name: /Get Pro/i }));
+
+ await waitFor(() => {
+ expect(gtagCalls).toContainEqual([
+ "event",
+ "conversion",
+ { send_to: "AW-123/BC", value: 50, currency: "USD" },
+ ]);
+ });
+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test");
+ });
+
+ test("reports no begin_checkout when Stripe returns no Checkout URL", async () => {
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");
+ const gtagCalls = installGtagShim();
+ // The backend modified the subscription in place — no Checkout ever
+ // started, so counting it would inflate the funnel.
+ server.use(
+ http.post("*/api/credits/subscription", () =>
+ HttpResponse.json({ url: null }),
+ ),
+ );
+
+ render(<SubscriptionStep />);
+ fireEvent.click(screen.getByRole("button", { name: /Get Pro/i }));
+
+ await waitFor(() => {
+ expect(useOnboardingWizardStore.getState().currentStep).toBeGreaterThan(
+ 1,
+ );
+ });
+ expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([]);
+ });
+
test("switching to yearly + selecting Pro forwards billing_cycle=yearly", async () => {
let capturedTierBody: {
tier?: string;
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts
index 30f0d95a48..56bb1eba45 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts
@@ -7,6 +7,7 @@ import {
import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";
import { resolveResponse } from "@/app/api/helpers";
import { useAuth } from "@/lib/auth/hooks/useAuth";
+import { trackAdsConversion } from "@/services/analytics/google-ads";
import { environment } from "@/services/environment";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { useLDClient } from "launchdarkly-react-client-sdk";
@@ -55,7 +56,7 @@ function clearHighestStep() {
export function useOnboardingPage() {
const router = useRouter();
const searchParams = useSearchParams();
- const { isLoggedIn, isUserLoading, refreshSession } = useAuth();
+ const { isLoggedIn, isUserLoading, refreshSession, user } = useAuth();
const currentStep = useOnboardingWizardStore((s) => s.currentStep);
const goToStep = useOnboardingWizardStore((s) => s.goToStep);
@@ -242,6 +243,13 @@ export function useOnboardingPage() {
for (let attempt = 0; attempt < 3; attempt++) {
try {
await postV1CompleteOnboardingStep({ step: "ONBOARDING_COMPLETE" });
+ // Only a confirmed completion counts: the fall-through below still
+ // sends the user to the copilot after three failures, but the backend
+ // never recorded the milestone.
+ trackAdsConversion("onboarding_complete", {
+ transactionID: user?.id,
+ email: user?.email,
+ });
clearHighestStep();
useOnboardingWizardStore.persist.clearStorage();
router.replace("/copilot");
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts
index 38de41e9ef..3523bc8084 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts
@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({
rollbackSession: vi.fn(),
postV1GetOrCreateUser: vi.fn(),
scheduleAccountCreatedGoal: vi.fn(),
+ cookieSet: vi.fn(),
}));
vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({
@@ -24,6 +25,7 @@ vi.mock("@/lib/auth/server/rollbackSession", () => ({
}));
vi.mock("next/headers", () => ({
headers: vi.fn().mockResolvedValue(new Headers()),
+ cookies: vi.fn().mockResolvedValue({ set: mocks.cookieSet }),
}));
vi.mock("@/services/analytics/datafast-server", async (importOriginal) => {
const actual =
@@ -67,6 +69,13 @@ describe("email signup account creation tracking", () => {
expect(result.success).toBe(true);
expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledOnce();
expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledWith("email");
+ // The browser reports the Google Ads sign-up conversion from this flag on
+ // the next page it renders.
+ expect(mocks.cookieSet).toHaveBeenCalledWith(
+ "agpt_account_created",
+ "email",
+ expect.objectContaining({ maxAge: 600, path: "/" }),
+ );
});
it("does not track an account that already existed", async () => {
@@ -85,6 +94,7 @@ describe("email signup account creation tracking", () => {
expect(result.success).toBe(true);
expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();
+ expect(mocks.cookieSet).not.toHaveBeenCalled();
});
it("reports a thrown backend error instead of completing signup", async () => {
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
index ab9ffd1b2d..9d041ad35a 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts
@@ -4,6 +4,7 @@ import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/au
import { getOnboardingStatus } from "@/app/api/helpers";
import { auth } from "@/lib/auth/auth";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
+import { markAccountCreated } from "@/services/analytics/account-created-server";
import {
scheduleAccountCreatedGoal,
wasAccountCreated,
@@ -77,6 +78,7 @@ export async function signup(
const createUserResponse = await postV1GetOrCreateUser();
if (wasAccountCreated(createUserResponse)) {
await scheduleAccountCreatedGoal("email");
+ await markAccountCreated("email");
}
} catch (createUserError) {
console.error("Error creating user during signup:", createUserError);
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 1dbe5f0544..5fb3615fa8 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,7 @@
+import {
+ installGtagShim,
+ removeGtagShim,
+} from "@/tests/integrations/gtag-shim";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
render,
@@ -377,11 +381,51 @@ describe("PaywallModal — upgrade mutation", () => {
});
const [args] = mutateFn.mock.calls[0];
expect(args.data.cancel_url).toBe("https://app.test/copilot");
+ // Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page
+ // report the subscription to Google Ads.
expect(args.data.success_url).toBe(
- "https://app.test/profile/credits?subscription=success",
+ "https://app.test/profile/credits?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=PRO&cycle=monthly",
);
});
+ it("reports begin_checkout only once Stripe returns a Checkout URL", 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 = vi
+ .fn()
+ .mockResolvedValue({ status: 200, data: { url: null } });
+ setupMocks({
+ mutateFn,
+ subscription: { tier: "NO_TIER", tier_costs: { PRO: 5000 } },
+ });
+
+ render(<PaywallModal />);
+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));
+
+ await waitFor(() => {
+ expect(mutateFn).toHaveBeenCalledTimes(1);
+ });
+ expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([]);
+
+ mutateFn.mockResolvedValue({
+ status: 200,
+ data: { url: "https://checkout.stripe.com/pay/cs_test" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /upgrade to pro/i }));
+
+ await waitFor(() => {
+ expect(gtagCalls).toContainEqual([
+ "event",
+ "conversion",
+ { send_to: "AW-123/BC", value: 50, currency: "USD" },
+ ]);
+ });
+ removeGtagShim();
+ vi.unstubAllEnvs();
+ });
+
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/usePaywallModal.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
index ec75bf55eb..30c81978c6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts
@@ -18,6 +18,10 @@ import {
type PlanDef,
TEAM_INTAKE_FORM_URL,
} from "@/components/molecules/PlanCard/plans";
+import {
+ getSubscriptionValue,
+ trackAdsConversion,
+} from "@/services/analytics/google-ads";
interface CheckoutResponse {
url?: string;
@@ -99,21 +103,32 @@ export function usePaywallModal() {
async function fireUpdate(tier: string) {
setSelectedTier(tier);
+ const cycle = isYearly ? "yearly" : "monthly";
try {
const result = await updateTier({
data: {
tier: tier as SubscriptionTierRequestTier,
- success_url: `${window.location.origin}/profile/credits?subscription=success`,
+ // Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return
+ // page report the subscription to Google Ads.
+ success_url: `${window.location.origin}/profile/credits?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${tier}&cycle=${cycle}`,
// Backing out of Stripe Checkout must return to the page the user
// was on so the paywall re-gates immediately. /profile/* is
// paywall-exempt — landing there let users wander an app that
// looks unlocked until the next non-exempt navigation.
cancel_url: window.location.href,
- billing_cycle: isYearly ? "yearly" : "monthly",
+ billing_cycle: cycle,
},
});
const url = (result?.data as CheckoutResponse | undefined)?.url;
if (url) {
+ // `plans` carries tier_costs / tier_costs_yearly straight from
+ // /credits/subscription — what Stripe actually charges. The static
+ // 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", {
+ value: apiValue ?? getSubscriptionValue(tier, cycle),
+ });
window.location.href = url;
}
} catch (error) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts
index 288c05a1ed..98b17b4cde 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/__tests__/route.test.ts
@@ -5,6 +5,7 @@ const postV1GetOrCreateUserMock = vi.fn();
const getOnboardingStatusMock = vi.fn();
const revalidatePathMock = vi.fn();
const scheduleAccountCreatedGoalMock = vi.fn();
+const cookieSetMock = vi.fn();
vi.mock("@/lib/auth/server/getServerSession", () => ({
getServerSession: () => getServerSessionMock(),
@@ -29,6 +30,11 @@ vi.mock("@/app/api/helpers", () => ({
getOnboardingStatus: () => getOnboardingStatusMock(),
}));
+vi.mock("next/headers", () => ({
+ cookies: () => Promise.resolve({ set: cookieSetMock }),
+ headers: () => new Headers(),
+}));
+
vi.mock("next/cache", () => ({
revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),
}));
@@ -77,6 +83,7 @@ beforeEach(() => {
getOnboardingStatusMock.mockReset();
revalidatePathMock.mockReset();
scheduleAccountCreatedGoalMock.mockReset();
+ cookieSetMock.mockReset();
vi.spyOn(console, "error").mockImplementation(() => undefined);
});
@@ -137,6 +144,13 @@ describe("auth callback GET — account creation tracking", () => {
expect(response.headers.get("location")).toBe(`${origin}/copilot`);
expect(scheduleAccountCreatedGoalMock).toHaveBeenCalledOnce();
expect(scheduleAccountCreatedGoalMock).toHaveBeenCalledWith("google");
+ // The browser reports the Google Ads sign-up conversion from this flag on
+ // the page it lands on.
+ expect(cookieSetMock).toHaveBeenCalledWith(
+ "agpt_account_created",
+ "google",
+ expect.objectContaining({ maxAge: 600, path: "/" }),
+ );
});
it("does not track a returning Google user", async () => {
@@ -145,6 +159,7 @@ describe("auth callback GET — account creation tracking", () => {
await GET(makeCallbackRequest());
expect(scheduleAccountCreatedGoalMock).not.toHaveBeenCalled();
+ expect(cookieSetMock).not.toHaveBeenCalled();
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
index edd7f51f80..87629be919 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
@@ -3,6 +3,7 @@ import { getOnboardingStatus } from "@/app/api/helpers";
import { sanitizeAuthNext } from "@/lib/auth-redirect";
import { getServerSession } from "@/lib/auth/server/getServerSession";
import { rollbackSession } from "@/lib/auth/server/rollbackSession";
+import { markAccountCreated } from "@/services/analytics/account-created-server";
import {
scheduleAccountCreatedGoal,
wasAccountCreated,
@@ -43,6 +44,7 @@ export async function GET(request: Request) {
const createUserResponse = await postV1GetOrCreateUser();
if (wasAccountCreated(createUserResponse)) {
await scheduleAccountCreatedGoal("google");
+ await markAccountCreated("google");
}
const { shouldShowOnboarding } = await getOnboardingStatus();
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 8f0d39cad2..97d2464f63 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
@@ -9,6 +9,10 @@ import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models
import { useToast } from "@/components/molecules/Toast/use-toast";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { getTierLabel } from "./helpers";
+import {
+ getSubscriptionValue,
+ trackAdsConversion,
+} from "@/services/analytics/google-ads";
export type SubscriptionStatus = SubscriptionStatusResponse;
@@ -69,7 +73,10 @@ export function useSubscriptionTierSection() {
async function changeTier(tier: string) {
setTierError(null);
try {
- const successUrl = `${window.location.origin}${window.location.pathname}?subscription=success`;
+ // Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page
+ // report the subscription to Google Ads. This surface has no cycle
+ // toggle, so the backend default (monthly) is what gets charged.
+ const successUrl = `${window.location.origin}${window.location.pathname}?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${tier}&cycle=monthly`;
const cancelUrl = `${window.location.origin}${window.location.pathname}?subscription=cancelled`;
const result = await doUpdateTier({
data: {
@@ -79,6 +86,9 @@ export function useSubscriptionTierSection() {
},
});
if (result.status === 200 && result.data.url) {
+ trackAdsConversion("begin_checkout", {
+ value: getSubscriptionValue(tier, "monthly"),
+ });
window.location.href = result.data.url;
return;
}
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 2c683a4821..f8352f41ea 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
@@ -13,9 +13,13 @@
import { fireEvent } from "@testing-library/react";
import { http, HttpResponse, type JsonBodyType } from "msw";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { server } from "@/mocks/mock-server";
+import {
+ installGtagShim,
+ removeGtagShim,
+} from "@/tests/integrations/gtag-shim";
import { render, screen, waitFor } from "@/tests/integrations/test-utils";
import { AutoRefillCard } from "../components/AutomationCreditsTab/AutoRefillCard/AutoRefillCard";
@@ -363,7 +367,11 @@ describe("YourPlanCard cycle toggle", () => {
});
it("fires updateTier with billing_cycle on confirm", async () => {
- let capturedBody: { tier?: string; billing_cycle?: string } | null = null;
+ let capturedBody: {
+ tier?: string;
+ billing_cycle?: string;
+ success_url?: string;
+ } | null = null;
server.use(
jsonHandler("get", "/api/credits/subscription", {
tier: "PRO",
@@ -394,6 +402,11 @@ describe("YourPlanCard cycle toggle", () => {
expect(capturedBody).not.toBeNull();
expect(capturedBody?.tier).toBe("PRO");
expect(capturedBody?.billing_cycle).toBe("yearly");
+ // Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page
+ // report the subscription value to Google Ads.
+ expect(capturedBody?.success_url).toContain(
+ "?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=PRO&cycle=yearly",
+ );
});
});
@@ -1219,3 +1232,94 @@ describe("Card mutation flows", () => {
).toBeNull();
});
});
+
+describe("YourPlanCard begin_checkout", () => {
+ const originalLocation = window.location;
+
+ function stubLocation() {
+ const location = {
+ origin: "http://localhost",
+ pathname: "/settings/billing",
+ href: "http://localhost/settings/billing",
+ };
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: location,
+ });
+ return location;
+ }
+
+ afterEach(() => {
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+ removeGtagShim();
+ vi.unstubAllEnvs();
+ });
+
+ function freeAccount(checkoutURL: string | null) {
+ const hits = { get: 0, post: 0 };
+ server.use(
+ http.get("*/api/credits/subscription", () => {
+ hits.get += 1;
+ return HttpResponse.json({
+ tier: "NO_TIER",
+ monthly_cost: 0,
+ has_active_stripe_subscription: false,
+ status: "inactive",
+ // What Stripe actually charges, which is what Ads should bid on —
+ // deliberately not the $50 the plan card computes.
+ tier_costs: { PRO: 4900 },
+ });
+ }),
+ jsonHandler("get", "/api/credits/manage", { url: null }),
+ http.post("*/api/credits/subscription", () => {
+ hits.post += 1;
+ return HttpResponse.json({ url: checkoutURL });
+ }),
+ );
+ return hits;
+ }
+
+ it("reports begin_checkout with the authoritative price once Stripe returns a URL", 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();
+ freeAccount("https://checkout.stripe.com/pay/cs_test");
+
+ render(<YourPlanCard />);
+ fireEvent.click(await screen.findByRole("button", { name: /get pro/i }));
+
+ await waitFor(() => {
+ expect(gtagCalls).toContainEqual([
+ "event",
+ "conversion",
+ { send_to: "AW-123/BC", value: 49, currency: "USD" },
+ ]);
+ });
+ expect(location.href).toBe("https://checkout.stripe.com/pay/cs_test");
+ });
+
+ 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");
+ const gtagCalls = installGtagShim();
+ stubLocation();
+ const hits = freeAccount(null);
+
+ render(<YourPlanCard />);
+ await waitFor(() => expect(hits.get).toBe(1));
+ fireEvent.click(screen.getByRole("button", { name: /get pro/i }));
+
+ // The in-place branch refetches the subscription after the POST resolves,
+ // so a second GET is proof the whole path ran — not just that the request
+ // was sent.
+ await waitFor(() => expect(hits.post).toBe(1));
+ await waitFor(() => expect(hits.get).toBeGreaterThanOrEqual(2));
+ expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([]);
+ });
+});
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 27da6ce9f1..0b2db15204 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
@@ -13,6 +13,11 @@ import type { SubscriptionTierRequestBillingCycle } from "@/app/api/__generated_
import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";
import { ApiError } from "@/lib/autogpt-server-api/helpers";
import { toast } from "@/components/molecules/Toast/use-toast";
+import {
+ centsToUSD,
+ getSubscriptionValue,
+ trackAdsConversion,
+} from "@/services/analytics/google-ads";
import { formatCents, formatShortDate } from "../../../helpers";
@@ -187,7 +192,10 @@ export function useYourPlanCard() {
tier: SubscriptionTierRequestTier,
billingCycle?: SubscriptionTierRequestBillingCycle,
) {
- const successUrl = `${window.location.origin}${window.location.pathname}?subscription=success`;
+ const cycle = billingCycle ?? "monthly";
+ // Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page
+ // report the subscription to Google Ads.
+ const successUrl = `${window.location.origin}${window.location.pathname}?subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${tier}&cycle=${cycle}`;
const cancelUrl = `${window.location.origin}${window.location.pathname}?subscription=cancelled`;
try {
const result = await updateTier({
@@ -200,6 +208,16 @@ export function useYourPlanCard() {
});
const url = (result?.data as { url?: string } | undefined)?.url;
if (url) {
+ // A Checkout URL is the only proof that Stripe Checkout actually
+ // starts: paid users are modified in place and get no URL, which is
+ // not a checkout start.
+ // /credits/subscription returns what Stripe actually charges; the
+ // 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", {
+ value: centsToUSD(cents) ?? getSubscriptionValue(tier, cycle),
+ });
// Navigating away — don't refetch (would set state on an
// unmounting component while Stripe Checkout takes over).
window.location.href = url;
diff --git a/autogpt_platform/frontend/src/app/providers.tsx b/autogpt_platform/frontend/src/app/providers.tsx
index 6ed01cbd2b..830272e6c5 100644
--- a/autogpt_platform/frontend/src/app/providers.tsx
+++ b/autogpt_platform/frontend/src/app/providers.tsx
@@ -12,6 +12,7 @@ import {
PostHogProvider,
PostHogUserTracker,
} from "@/providers/posthog/posthog-provider";
+import { AdsConversionTracker } from "@/services/analytics/AdsConversionTracker";
import { LaunchDarklyProvider } from "@/services/feature-flags/feature-flag-provider";
import { QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider, ThemeProviderProps } from "next-themes";
@@ -25,9 +26,12 @@ export function Providers({ children, ...props }: ThemeProviderProps) {
<NuqsAdapter>
<PostHogProvider>
<BackendAPIProvider>
- <SentryUserTracker />
- <PostHogUserTracker />
+ {/* All four read useSearchParams (directly or via useAuth), which
+ bails out of static rendering unless it sits under Suspense. */}
<Suspense fallback={null}>
+ <SentryUserTracker />
+ <PostHogUserTracker />
+ <AdsConversionTracker />
<PostHogPageViewTracker />
</Suspense>
<CredentialsProvider>
diff --git a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/CookieConsentBanner.tsx b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/CookieConsentBanner.tsx
index 56e875038f..a9860021f0 100644
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/CookieConsentBanner.tsx
+++ b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/CookieConsentBanner.tsx
@@ -47,7 +47,8 @@ export function CookieConsentBanner() {
className="text-neutral-600 dark:text-neutral-400"
>
AutoGPT uses essential cookies for login and optional cookies
- for analytics and error tracking to improve our service.
+ for analytics, advertising measurement and error tracking to
+ improve our service.
</Text>
</div>
</div>
diff --git a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/__tests__/CookieConsentBanner.test.tsx b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/__tests__/CookieConsentBanner.test.tsx
index 7c35feedab..c48781bfc5 100644
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/__tests__/CookieConsentBanner.test.tsx
+++ b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/__tests__/CookieConsentBanner.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from "@/tests/integrations/test-utils";
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
import { beforeEach, describe, expect, test, vi } from "vitest";
let pathname = "/marketplace";
@@ -38,4 +38,15 @@ describe("CookieConsentBanner", () => {
await Promise.resolve();
expect(screen.queryByText("We use cookies")).toBeNull();
});
+
+ test("lets the visitor decide on advertising cookies separately", async () => {
+ pathname = "/marketplace";
+ render(<CookieConsentBanner />);
+ fireEvent.click(await screen.findByRole("button", { name: "Settings" }));
+
+ expect(
+ await screen.findByLabelText("Toggle advertising cookies"),
+ ).toBeDefined();
+ expect(screen.getByText("Advertising")).toBeDefined();
+ });
});
diff --git a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/CookieSettingsModal.tsx b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/CookieSettingsModal.tsx
index 88dd9f0d7a..e57ddcb434 100644
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/CookieSettingsModal.tsx
+++ b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/CookieSettingsModal.tsx
@@ -20,6 +20,8 @@ export function CookieSettingsModal({ isOpen, onClose }: Props) {
setAnalytics,
monitoring,
setMonitoring,
+ advertising,
+ setAdvertising,
handleSavePreferences,
handleAcceptAll,
handleRejectAll,
@@ -115,6 +117,32 @@ export function CookieSettingsModal({ isOpen, onClose }: Props) {
/>
</div>
</div>
+
+ <div className="border-t border-neutral-200 dark:border-neutral-800" />
+
+ <div className="space-y-2">
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex-1 space-y-1">
+ <Text
+ variant="body-medium"
+ className="text-neutral-900 dark:text-neutral-100"
+ >
+ {COOKIE_CATEGORIES.advertising.name}
+ </Text>
+ <Text
+ variant="body"
+ className="text-neutral-600 dark:text-neutral-400"
+ >
+ {COOKIE_CATEGORIES.advertising.description}
+ </Text>
+ </div>
+ <Switch
+ checked={advertising}
+ onCheckedChange={setAdvertising}
+ aria-label="Toggle advertising cookies"
+ />
+ </div>
+ </div>
</div>
<Dialog.Footer>
diff --git a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/useCookieSettingsModal.ts b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/useCookieSettingsModal.ts
index 9516406368..ef2c9529f9 100644
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/useCookieSettingsModal.ts
+++ b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/useCookieSettingsModal.ts
@@ -12,16 +12,19 @@ export function useCookieSettingsModal({ onClose }: Props) {
const [analytics, setAnalytics] = useState(consent.analytics);
const [monitoring, setMonitoring] = useState(consent.monitoring);
+ const [advertising, setAdvertising] = useState(consent.advertising);
useEffect(() => {
setAnalytics(consent.analytics);
setMonitoring(consent.monitoring);
- }, [consent.analytics, consent.monitoring]);
+ setAdvertising(consent.advertising);
+ }, [consent.analytics, consent.monitoring, consent.advertising]);
function handleSavePreferences() {
handleUpdateConsent({
analytics,
monitoring,
+ advertising,
});
onClose();
}
@@ -29,9 +32,11 @@ export function useCookieSettingsModal({ onClose }: Props) {
function handleAcceptAll() {
setAnalytics(true);
setMonitoring(true);
+ setAdvertising(true);
handleUpdateConsent({
analytics: true,
monitoring: true,
+ advertising: true,
});
onClose();
}
@@ -39,9 +44,11 @@ export function useCookieSettingsModal({ onClose }: Props) {
function handleRejectAll() {
setAnalytics(false);
setMonitoring(false);
+ setAdvertising(false);
handleUpdateConsent({
analytics: false,
monitoring: false,
+ advertising: false,
});
onClose();
}
@@ -51,6 +58,8 @@ export function useCookieSettingsModal({ onClose }: Props) {
setAnalytics,
monitoring,
setMonitoring,
+ advertising,
+ setAdvertising,
handleSavePreferences,
handleAcceptAll,
handleRejectAll,
diff --git a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsent.ts b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsent.ts
index 66159f9aef..09647a26bc 100644
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsent.ts
+++ b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsent.ts
@@ -40,6 +40,7 @@ export function useCookieConsent() {
handleUpdateConsent({
analytics: true,
monitoring: true,
+ advertising: true,
});
}, [handleUpdateConsent]);
@@ -47,6 +48,7 @@ export function useCookieConsent() {
handleUpdateConsent({
analytics: false,
monitoring: false,
+ advertising: false,
});
}, [handleUpdateConsent]);
diff --git a/autogpt_platform/frontend/src/services/analytics/AdsConversionTracker.tsx b/autogpt_platform/frontend/src/services/analytics/AdsConversionTracker.tsx
new file mode 100644
index 0000000000..4a237f5508
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/AdsConversionTracker.tsx
@@ -0,0 +1,8 @@
+"use client";
+
+import { useAdsConversionTracker } from "./useAdsConversionTracker";
+
+export function AdsConversionTracker() {
+ useAdsConversionTracker();
+ return null;
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/AdsConversionTracker.test.tsx b/autogpt_platform/frontend/src/services/analytics/__tests__/AdsConversionTracker.test.tsx
new file mode 100644
index 0000000000..21e9461515
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/AdsConversionTracker.test.tsx
@@ -0,0 +1,302 @@
+import { render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ installGtagShim,
+ removeGtagShim,
+} from "@/tests/integrations/gtag-shim";
+import { ACCOUNT_CREATED_COOKIE } from "../account-created-cookie";
+import { consent } from "@/services/consent/cookies";
+
+let pathname = "/copilot";
+vi.mock("next/navigation", () => ({
+ usePathname: () => pathname,
+}));
+
+const auth = vi.hoisted(() => ({
+ state: {
+ user: { id: "user-1", email: "[email protected]" } as {
+ id: string;
+ email: string;
+ } | null,
+ isUserLoading: false,
+ },
+}));
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => auth.state,
+}));
+
+import { AdsConversionTracker } from "../AdsConversionTracker";
+
+let pushed: unknown[][] = [];
+
+function conversions() {
+ return pushed.filter(([, name]) => name === "conversion");
+}
+
+function pageViews() {
+ return pushed.filter(([, name]) => name === "page_view");
+}
+
+describe("AdsConversionTracker", () => {
+ beforeEach(() => {
+ pushed = installGtagShim();
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=; Path=/; Max-Age=0`;
+ window.history.replaceState({}, "", "/copilot");
+ pathname = "/copilot";
+ auth.state = {
+ user: { id: "user-1", email: "[email protected]" },
+ isUserLoading: false,
+ };
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
+ vi.stubEnv(
+ "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",
+ "sign_up=SU,subscribe=SB,top_up=TU",
+ );
+ // Identifiers only ride along on an affirmative yes, so the cases below
+ // that assert them start from an answered banner.
+ consent.save({
+ hasConsented: true,
+ timestamp: 1,
+ analytics: true,
+ monitoring: true,
+ advertising: true,
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ removeGtagShim();
+ consent.clear();
+ });
+
+ it("fires sign_up once for a just-created account and clears the flag", () => {
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+
+ const { rerender } = render(<AdsConversionTracker />);
+ rerender(<AdsConversionTracker />);
+
+ expect(conversions()).toEqual([
+ [
+ "event",
+ "conversion",
+ {
+ send_to: "AW-123/SU",
+ transaction_id: "user-1",
+ user_data: { email: "[email protected]" },
+ },
+ ],
+ ]);
+ expect(document.cookie).not.toContain(`${ACCOUNT_CREATED_COOKIE}=email`);
+ });
+
+ it("waits for the session before firing sign_up", () => {
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=google; Path=/`;
+ auth.state = { user: null, isUserLoading: true };
+
+ const { rerender } = render(<AdsConversionTracker />);
+ expect(conversions()).toEqual([]);
+
+ auth.state = {
+ user: { id: "user-2", email: "[email protected]" },
+ isUserLoading: false,
+ };
+ rerender(<AdsConversionTracker />);
+
+ expect(conversions()).toHaveLength(1);
+ expect(conversions()[0][2]).toMatchObject({ transaction_id: "user-2" });
+ });
+
+ it("does not fire sign_up for a returning user", () => {
+ render(<AdsConversionTracker />);
+
+ expect(conversions()).toEqual([]);
+ });
+
+ it("picks up a flag set after mount on the next client-side navigation", () => {
+ const { rerender } = render(<AdsConversionTracker />);
+ expect(conversions()).toEqual([]);
+
+ // The email signup action sets the flag, then router.replace()s onward.
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+ pathname = "/onboarding";
+ rerender(<AdsConversionTracker />);
+
+ expect(conversions()).toHaveLength(1);
+ expect(conversions()[0][2]).toMatchObject({ send_to: "AW-123/SU" });
+ });
+
+ it("fires subscribe with the plan price when returning from Stripe", () => {
+ window.history.replaceState(
+ {},
+ "",
+ "/onboarding?step=2&subscription=success&session_id=cs_1&plan=MAX&cycle=yearly",
+ );
+
+ render(<AdsConversionTracker />);
+
+ expect(conversions()).toEqual([
+ [
+ "event",
+ "conversion",
+ {
+ send_to: "AW-123/SB",
+ value: 3264,
+ currency: "USD",
+ transaction_id: "cs_1",
+ user_data: { email: "[email protected]" },
+ },
+ ],
+ ]);
+ });
+
+ it("does not fire subscribe on a cancelled checkout", () => {
+ window.history.replaceState(
+ {},
+ "",
+ "/onboarding?step=1&subscription=cancelled",
+ );
+
+ render(<AdsConversionTracker />);
+
+ expect(conversions()).toEqual([]);
+ });
+
+ it("fires top_up with the Stripe session as the dedup key", () => {
+ window.history.replaceState(
+ {},
+ "",
+ "/settings/billing?topup=success&session_id=cs_top_1",
+ );
+
+ render(<AdsConversionTracker />);
+
+ expect(conversions()).toEqual([
+ [
+ "event",
+ "conversion",
+ {
+ send_to: "AW-123/TU",
+ transaction_id: "cs_top_1",
+ user_data: { email: "[email protected]" },
+ },
+ ],
+ ]);
+ });
+
+ it("reports nothing while the session is absent, even once loading is done", () => {
+ // The regression: on the post-signup client navigation the effect runs
+ // with isUserLoading already false but no user yet. Reporting there sends
+ // a conversion with no dedup id and no enhanced-conversion email.
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+ auth.state = { user: null, isUserLoading: false };
+
+ const { rerender } = render(<AdsConversionTracker />);
+ expect(conversions()).toEqual([]);
+ expect(document.cookie).toContain(`${ACCOUNT_CREATED_COOKIE}=email`);
+
+ auth.state = {
+ user: { id: "user-3", email: "[email protected]" },
+ isUserLoading: false,
+ };
+ rerender(<AdsConversionTracker />);
+
+ expect(conversions()).toHaveLength(1);
+ expect(conversions()[0][2]).toMatchObject({
+ transaction_id: "user-3",
+ user_data: { email: "[email protected]" },
+ });
+ });
+
+ it("keeps the account-created flag when the tag has not loaded yet", () => {
+ removeGtagShim();
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+
+ const { rerender } = render(<AdsConversionTracker />);
+ expect(document.cookie).toContain(`${ACCOUNT_CREATED_COOKIE}=email`);
+
+ // The tag loads afterInteractive; the next navigation retries.
+ pushed = installGtagShim();
+ pathname = "/library";
+ rerender(<AdsConversionTracker />);
+
+ expect(conversions()).toHaveLength(1);
+ expect(document.cookie).not.toContain(`${ACCOUNT_CREATED_COOKIE}=email`);
+ });
+
+ it("retries the checkout return until it reaches the tag", () => {
+ removeGtagShim();
+ window.history.replaceState(
+ {},
+ "",
+ "/settings/billing?subscription=success&session_id=cs_2&plan=PRO&cycle=monthly",
+ );
+
+ const { rerender } = render(<AdsConversionTracker />);
+
+ pushed = installGtagShim();
+ // The navigation that triggers the retry also strips the query — the
+ // snapshot taken at mount is what has to carry it.
+ window.history.replaceState({}, "", "/library");
+ pathname = "/library";
+ rerender(<AdsConversionTracker />);
+
+ expect(conversions()).toHaveLength(1);
+ expect(conversions()[0][2]).toMatchObject({
+ send_to: "AW-123/SB",
+ transaction_id: "cs_2",
+ });
+ });
+
+ it("drops the identifiers when the visitor rejected advertising", () => {
+ consent.save({
+ hasConsented: true,
+ timestamp: 1,
+ analytics: true,
+ monitoring: true,
+ advertising: false,
+ });
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+
+ render(<AdsConversionTracker />);
+
+ // The aggregate conversion still counts — Consent Mode keeps it
+ // cookieless — but nothing identifying rides along.
+ expect(conversions()).toEqual([
+ ["event", "conversion", { send_to: "AW-123/SU" }],
+ ]);
+ });
+
+ it("keeps the identifiers when the visitor accepted advertising", () => {
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+
+ render(<AdsConversionTracker />);
+
+ expect(conversions()[0][2]).toMatchObject({
+ transaction_id: "user-1",
+ user_data: { email: "[email protected]" },
+ });
+ });
+
+ it("drops the identifiers while the banner is unanswered", () => {
+ consent.clear();
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+
+ render(<AdsConversionTracker />);
+
+ expect(conversions()).toEqual([
+ ["event", "conversion", { send_to: "AW-123/SU" }],
+ ]);
+ });
+
+ it("sends a page_view to the Ads tag on client-side navigation only", () => {
+ const { rerender } = render(<AdsConversionTracker />);
+ expect(pageViews()).toEqual([]);
+
+ pathname = "/library";
+ rerender(<AdsConversionTracker />);
+
+ expect(pageViews()).toEqual([
+ ["event", "page_view", { send_to: "AW-123", page_path: "/library" }],
+ ]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/account-created-cookie.test.ts b/autogpt_platform/frontend/src/services/analytics/account-created-cookie.test.ts
new file mode 100644
index 0000000000..941d5bcc40
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/account-created-cookie.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ ACCOUNT_CREATED_COOKIE,
+ clearAccountCreatedFlag,
+ readAccountCreatedFlag,
+} from "./account-created-cookie";
+
+describe("account-created flag", () => {
+ beforeEach(() => {
+ clearAccountCreatedFlag();
+ });
+
+ it("reads the signup method without consuming it", () => {
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=google; Path=/`;
+
+ expect(readAccountCreatedFlag()).toBe("google");
+ // Reading twice still works: the flag survives until the conversion is
+ // actually reported.
+ expect(readAccountCreatedFlag()).toBe("google");
+ });
+
+ it("clears the flag so a reload cannot report twice", () => {
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
+
+ clearAccountCreatedFlag();
+
+ expect(readAccountCreatedFlag()).toBeNull();
+ expect(document.cookie).not.toContain(`${ACCOUNT_CREATED_COOKIE}=email`);
+ });
+
+ it("returns nothing when no account was just created", () => {
+ expect(readAccountCreatedFlag()).toBeNull();
+ });
+
+ it("discards a value that is not a known signup method", () => {
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=weird; Path=/`;
+
+ expect(readAccountCreatedFlag()).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/account-created-cookie.ts b/autogpt_platform/frontend/src/services/analytics/account-created-cookie.ts
new file mode 100644
index 0000000000..bc9f998003
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/account-created-cookie.ts
@@ -0,0 +1,33 @@
+export const ACCOUNT_CREATED_COOKIE = "agpt_account_created";
+export const ACCOUNT_CREATED_COOKIE_MAX_AGE_SECONDS = 600;
+
+export const SIGNUP_METHODS = ["email", "google"] as const;
+export type SignupMethod = (typeof SIGNUP_METHODS)[number];
+
+// The server sets this flag when it provisions a brand-new account (see
+// account-created-server.ts). Reading and clearing are separate on purpose:
+// the flag is the only record that a signup happened, so it must survive until
+// the conversion has actually reached the tag.
+export function readAccountCreatedFlag(): SignupMethod | null {
+ if (typeof document === "undefined") return null;
+
+ const prefix = `${ACCOUNT_CREATED_COOKIE}=`;
+ const entry = document.cookie
+ .split("; ")
+ .find((part) => part.startsWith(prefix));
+ if (!entry) return null;
+
+ const value = entry.slice(prefix.length);
+ return isSignupMethod(value) ? value : null;
+}
+
+// Called once the sign-up conversion is reported, so a reload can't report
+// twice.
+export function clearAccountCreatedFlag(): void {
+ if (typeof document === "undefined") return;
+ document.cookie = `${ACCOUNT_CREATED_COOKIE}=; Path=/; Max-Age=0`;
+}
+
+function isSignupMethod(value: string): value is SignupMethod {
+ return SIGNUP_METHODS.includes(value as SignupMethod);
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/account-created-server.ts b/autogpt_platform/frontend/src/services/analytics/account-created-server.ts
new file mode 100644
index 0000000000..c0f14af48a
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/account-created-server.ts
@@ -0,0 +1,31 @@
+import * as Sentry from "@sentry/nextjs";
+import { environment } from "@/services/environment";
+import { cookies } from "next/headers";
+import {
+ ACCOUNT_CREATED_COOKIE,
+ ACCOUNT_CREATED_COOKIE_MAX_AGE_SECONDS,
+ type SignupMethod,
+} from "./account-created-cookie";
+
+// Flags a brand-new account for the browser, which reports the Google Ads
+// sign-up conversion on the next page it renders (AdsConversionTracker).
+// Best effort: a tracking failure must never fail the signup itself.
+export async function markAccountCreated(method: SignupMethod): Promise<void> {
+ try {
+ const cookieStore = await cookies();
+ cookieStore.set(ACCOUNT_CREATED_COOKIE, method, {
+ path: "/",
+ maxAge: ACCOUNT_CREATED_COOKIE_MAX_AGE_SECONDS,
+ sameSite: "lax",
+ // Readable by the browser by design — that's how the conversion fires.
+ httpOnly: false,
+ // ...but not settable over plaintext by a sibling subdomain, which would
+ // forge a sign-up. Local stacks run on http.
+ secure: !environment.isLocal(),
+ });
+ } catch (error) {
+ Sentry.captureException(error, {
+ tags: { analytics_provider: "google_ads", analytics_goal: "signup" },
+ });
+ }
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/consent-mode.test.ts b/autogpt_platform/frontend/src/services/analytics/consent-mode.test.ts
new file mode 100644
index 0000000000..9b7c52470d
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/consent-mode.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import type { ConsentPreferences } from "@/services/consent/cookies";
+import {
+ buildConsentModeScript,
+ CONSENT_DENIED_BY_DEFAULT_REGIONS,
+} from "./consent-mode";
+
+function preferences(
+ overrides: Partial<ConsentPreferences> = {},
+): ConsentPreferences {
+ return {
+ hasConsented: true,
+ timestamp: 1,
+ analytics: false,
+ monitoring: false,
+ advertising: false,
+ ...overrides,
+ };
+}
+
+describe("buildConsentModeScript", () => {
+ it("grants by default, denies in the EEA, UK and Switzerland, and passes click IDs through URLs", () => {
+ const script = buildConsentModeScript(null);
+
+ expect(script).toContain(
+ `gtag('consent','default',{"ad_storage":"granted","ad_user_data":"granted","ad_personalization":"granted","analytics_storage":"granted"});`,
+ );
+ expect(script).toContain(
+ `gtag('consent','default',{"ad_storage":"denied","ad_user_data":"denied","ad_personalization":"denied","analytics_storage":"denied","region":${JSON.stringify(CONSENT_DENIED_BY_DEFAULT_REGIONS)}});`,
+ );
+ expect(CONSENT_DENIED_BY_DEFAULT_REGIONS).toEqual(
+ expect.arrayContaining(["DE", "FR", "ES", "GB", "CH", "NO", "IS", "LI"]),
+ );
+ expect(script).toContain(`gtag('set','url_passthrough',true);`);
+ expect(script).not.toContain("'update'");
+ });
+
+ it("sends no update while the visitor has not answered the banner", () => {
+ const script = buildConsentModeScript(
+ preferences({ hasConsented: false, analytics: true }),
+ );
+
+ expect(script).not.toContain("'update'");
+ });
+
+ it("updates every signal from the stored answer", () => {
+ const script = buildConsentModeScript(
+ preferences({ analytics: true, advertising: false }),
+ );
+
+ expect(script).toContain(
+ `gtag('consent','update',{"analytics_storage":"granted","ad_storage":"denied","ad_user_data":"denied","ad_personalization":"denied"});`,
+ );
+ });
+
+ it("grants the advertising signals once advertising is accepted", () => {
+ const script = buildConsentModeScript(
+ preferences({ analytics: false, advertising: true }),
+ );
+
+ expect(script).toContain(
+ `gtag('consent','update',{"analytics_storage":"denied","ad_storage":"granted","ad_user_data":"granted","ad_personalization":"granted"});`,
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/consent-mode.ts b/autogpt_platform/frontend/src/services/analytics/consent-mode.ts
new file mode 100644
index 0000000000..ca9eeae6a8
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/consent-mode.ts
@@ -0,0 +1,88 @@
+import type { ConsentPreferences } from "@/services/consent/cookies";
+
+const EU_MEMBER_STATES = [
+ "AT",
+ "BE",
+ "BG",
+ "HR",
+ "CY",
+ "CZ",
+ "DK",
+ "EE",
+ "FI",
+ "FR",
+ "DE",
+ "GR",
+ "HU",
+ "IE",
+ "IT",
+ "LV",
+ "LT",
+ "LU",
+ "MT",
+ "NL",
+ "PL",
+ "PT",
+ "RO",
+ "SK",
+ "SI",
+ "ES",
+ "SE",
+];
+
+// EEA (EU + IS, LI, NO), the UK and Switzerland start with every Google
+// signal denied until the visitor answers the banner; everywhere else the tag
+// runs with consent granted by default. Mirrored on agpt.co so a click ID
+// collected there is handled the same way here.
+export const CONSENT_DENIED_BY_DEFAULT_REGIONS = [
+ ...EU_MEMBER_STATES,
+ "IS",
+ "LI",
+ "NO",
+ "GB",
+ "CH",
+];
+
+type Signal = "granted" | "denied";
+
+function signal(granted: boolean): Signal {
+ return granted ? "granted" : "denied";
+}
+
+// Consent Mode v2 commands for the Google tag init script. Must run before
+// gtag('config', …) so the first hit already carries the right signals.
+export function buildConsentModeScript(
+ preferences: ConsentPreferences | null,
+): string {
+ const lines = [
+ `gtag('consent','default',${JSON.stringify({
+ ad_storage: "granted",
+ ad_user_data: "granted",
+ ad_personalization: "granted",
+ analytics_storage: "granted",
+ })});`,
+ `gtag('consent','default',${JSON.stringify({
+ ad_storage: "denied",
+ ad_user_data: "denied",
+ ad_personalization: "denied",
+ analytics_storage: "denied",
+ region: CONSENT_DENIED_BY_DEFAULT_REGIONS,
+ })});`,
+ // Carries the ad click ID across pages in the URL while cookies are denied.
+ `gtag('set','url_passthrough',true);`,
+ ];
+
+ if (preferences?.hasConsented) {
+ const ads = signal(preferences.advertising);
+ lines.push(
+ `gtag('consent','update',${JSON.stringify({
+ analytics_storage: signal(preferences.analytics),
+ ad_storage: ads,
+ ad_user_data: ads,
+ ad_personalization: ads,
+ })});`,
+ );
+ }
+
+ return lines.join("\n");
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts b/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts
new file mode 100644
index 0000000000..bb4db0450f
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts
@@ -0,0 +1,175 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ installGtagShim,
+ removeGtagShim,
+} from "@/tests/integrations/gtag-shim";
+import { consent } from "@/services/consent/cookies";
+import {
+ getSubscriptionValue,
+ parseConversionLabels,
+ trackAdsConversion,
+ trackAdsPageView,
+} from "./google-ads";
+
+function answerBanner(advertising: boolean) {
+ consent.save({
+ hasConsented: true,
+ timestamp: 1,
+ analytics: true,
+ monitoring: true,
+ advertising,
+ });
+}
+
+let pushed: unknown[][] = [];
+
+describe("trackAdsConversion", () => {
+ beforeEach(() => {
+ pushed = installGtagShim();
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
+ vi.stubEnv(
+ "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",
+ "sign_up=SIGNUP,subscribe=SUB",
+ );
+ answerBanner(true);
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ removeGtagShim();
+ consent.clear();
+ });
+
+ it("sends the conversion to the action label with value, dedup id and user data", () => {
+ const sent = trackAdsConversion("subscribe", {
+ value: 50,
+ transactionID: "cs_123",
+ email: "[email protected]",
+ });
+
+ expect(sent).toBe(true);
+ expect(pushed).toEqual([
+ [
+ "event",
+ "conversion",
+ {
+ send_to: "AW-123/SUB",
+ value: 50,
+ currency: "USD",
+ transaction_id: "cs_123",
+ user_data: { email: "[email protected]" },
+ },
+ ],
+ ]);
+ });
+
+ it("withholds the identifiers until the banner is answered", () => {
+ // Unanswered: Consent Mode denies ad_user_data in the EEA/UK/CH and the
+ // browser can't tell which region it's in, so nothing identifying goes out.
+ consent.clear();
+
+ trackAdsConversion("subscribe", {
+ value: 50,
+ transactionID: "cs_123",
+ email: "[email protected]",
+ });
+
+ expect(pushed).toEqual([
+ [
+ "event",
+ "conversion",
+ { send_to: "AW-123/SUB", value: 50, currency: "USD" },
+ ],
+ ]);
+ });
+
+ it("withholds the identifiers when advertising was rejected", () => {
+ answerBanner(false);
+
+ trackAdsConversion("subscribe", {
+ transactionID: "cs_123",
+ email: "[email protected]",
+ });
+
+ expect(pushed).toEqual([
+ ["event", "conversion", { send_to: "AW-123/SUB" }],
+ ]);
+ });
+
+ it("sends only the destination when no options are given", () => {
+ trackAdsConversion("sign_up");
+
+ expect(pushed).toEqual([
+ ["event", "conversion", { send_to: "AW-123/SIGNUP" }],
+ ]);
+ });
+
+ it("does nothing when the Google Ads tag is not configured", () => {
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "");
+
+ expect(trackAdsConversion("sign_up")).toBe(false);
+ expect(pushed).toEqual([]);
+ });
+
+ it("does nothing for an action without a label", () => {
+ expect(trackAdsConversion("top_up")).toBe(false);
+ expect(pushed).toEqual([]);
+ });
+});
+
+describe("trackAdsPageView", () => {
+ beforeEach(() => {
+ pushed = installGtagShim();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ removeGtagShim();
+ });
+
+ it("sends a page_view to the Ads tag only", () => {
+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");
+
+ trackAdsPageView("/library");
+
+ expect(pushed).toEqual([
+ ["event", "page_view", { send_to: "AW-123", page_path: "/library" }],
+ ]);
+ });
+
+ it("does nothing when the tag is not configured", () => {
+ expect(trackAdsPageView("/library")).toBe(false);
+ expect(pushed).toEqual([]);
+ });
+});
+
+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= ",
+ ),
+ ).toEqual({ sign_up: "AbC", subscribe: "DeF" });
+ });
+
+ it("returns nothing for an unset value", () => {
+ expect(parseConversionLabels("")).toEqual({});
+ });
+});
+
+describe("getSubscriptionValue", () => {
+ it("prices monthly plans at the monthly rate", () => {
+ expect(getSubscriptionValue("PRO", "monthly")).toBe(50);
+ expect(getSubscriptionValue("MAX", "monthly")).toBe(320);
+ });
+
+ it("prices yearly plans at the discounted annual total", () => {
+ expect(getSubscriptionValue("PRO", "yearly")).toBe(510);
+ expect(getSubscriptionValue("MAX", "yearly")).toBe(3264);
+ });
+
+ it("has no value for unknown plans", () => {
+ expect(getSubscriptionValue("TEAM", "monthly")).toBeUndefined();
+ expect(getSubscriptionValue(null, null)).toBeUndefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/google-ads.ts b/autogpt_platform/frontend/src/services/analytics/google-ads.ts
new file mode 100644
index 0000000000..d3576ef9fd
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/google-ads.ts
@@ -0,0 +1,128 @@
+import {
+ PLANS,
+ YEARLY_PRICE_FACTOR,
+} from "@/components/molecules/PlanCard/plans";
+import { consent } from "@/services/consent/cookies";
+import { environment } from "@/services/environment";
+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.
+export const ADS_CONVERSIONS = [
+ "sign_up",
+ "begin_checkout",
+ "subscribe",
+ "onboarding_complete",
+ "top_up",
+] as const;
+export type AdsConversion = (typeof ADS_CONVERSIONS)[number];
+
+interface ConversionOptions {
+ value?: number;
+ currency?: string;
+ // Google Ads counts one conversion per transaction_id, so a refresh of the
+ // page that fired it does not count twice.
+ transactionID?: string;
+ // Enhanced conversions: gtag hashes the address before it leaves the browser.
+ email?: string;
+}
+
+export function trackAdsConversion(
+ name: AdsConversion,
+ options: ConversionOptions = {},
+): boolean {
+ const adsID = environment.getGoogleAdsID();
+ if (!adsID) return false;
+ const label = conversionLabels()[name];
+ if (!label) return false;
+
+ const params: Record<string, unknown> = { send_to: `${adsID}/${label}` };
+ if (options.value !== undefined) {
+ params.value = options.value;
+ params.currency = options.currency ?? "USD";
+ }
+ // Identifiers ride along only on an affirmative yes. The aggregate
+ // (cookieless) conversion still counts either way.
+ if (mayReportIdentifiers()) {
+ if (options.transactionID) params.transaction_id = options.transactionID;
+ if (options.email) params.user_data = { email: options.email };
+ }
+
+ return gtag("event", "conversion", params);
+}
+
+// An unanswered banner is not a yes. Outside the EEA/UK/CH the Consent Mode
+// default is `granted`, but that gate lives in the tag's `region` parameter and
+// Google resolves it by IP — the browser has no region signal of its own. So
+// treating "no answer" as consent would hand Google an email it was told to
+// redact for every unanswered visitor in a denied-by-default region, which is
+// the vendor dependency this gate exists to remove.
+function mayReportIdentifiers(): boolean {
+ const preferences = consent.load();
+ return preferences.hasConsented && preferences.advertising;
+}
+
+// The labels come from a build-time env var; parse once per distinct value so
+// a conversion doesn't re-split the string every time.
+let cachedLabelsRaw: string | undefined;
+let cachedLabels: Partial<Record<AdsConversion, string>> = {};
+
+function conversionLabels(): Partial<Record<AdsConversion, string>> {
+ const raw = environment.getGoogleAdsConversionLabels();
+ if (raw !== cachedLabelsRaw) {
+ cachedLabelsRaw = raw;
+ cachedLabels = parseConversionLabels(raw);
+ }
+ return cachedLabels;
+}
+
+// Client-side navigations don't reload the tag, so the Ads destination gets
+// its page views from the router. GA4 is left alone on purpose.
+export function trackAdsPageView(path: string): boolean {
+ const adsID = environment.getGoogleAdsID();
+ if (!adsID) return false;
+ return gtag("event", "page_view", { send_to: adsID, page_path: path });
+}
+
+// "sign_up=AbCdEf,subscribe=GhIjKl" → { sign_up: "AbCdEf", subscribe: "GhIjKl" }
+export function parseConversionLabels(
+ raw: string,
+): Partial<Record<AdsConversion, string>> {
+ const labels: Partial<Record<AdsConversion, string>> = {};
+ for (const part of raw.split(",")) {
+ const [key, label] = part.split("=").map((piece) => piece.trim());
+ if (isAdsConversion(key) && label) labels[key] = label;
+ }
+ return labels;
+}
+
+function isAdsConversion(value: string | undefined): value is AdsConversion {
+ return ADS_CONVERSIONS.includes(value as AdsConversion);
+}
+
+// USD amount Stripe charges for a plan on the given cycle, for the
+// conversion's value. Unknown plans (Team, contact sales) have no value.
+export function getSubscriptionValue(
+ plan: string | null,
+ cycle: string | null,
+): number | undefined {
+ const definition = PLANS.find((candidate) => candidate.key === plan);
+ const monthly = definition?.usdMonthly;
+ if (!definition || monthly == null) return undefined;
+ if (cycle !== "yearly") return roundUSD(monthly);
+ // usdYearly is the amount Stripe actually charges wherever the surface knows
+ // it; the factor is only the fallback the pricing cards compute from
+ // (computePricing.ts). Bidding on the displayed number matters.
+ return roundUSD(definition.usdYearly ?? monthly * YEARLY_PRICE_FACTOR * 12);
+}
+
+// Stripe amounts arrive in cents; Ads wants the major unit.
+export function centsToUSD(cents: number | undefined): number | undefined {
+ if (cents == null) return undefined;
+ return roundUSD(cents / 100);
+}
+
+function roundUSD(amount: number): number {
+ return Math.round(amount * 100) / 100;
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/gtag.test.ts b/autogpt_platform/frontend/src/services/analytics/gtag.test.ts
new file mode 100644
index 0000000000..4bd4ba55f6
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/gtag.test.ts
@@ -0,0 +1,26 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { removeGtagShim } from "@/tests/integrations/gtag-shim";
+import { gtag } from "./gtag";
+
+describe("gtag", () => {
+ afterEach(() => {
+ removeGtagShim();
+ });
+
+ it("forwards the command to the tag's own shim", () => {
+ const shim = vi.fn();
+ window.gtag = shim;
+
+ expect(gtag("event", "conversion", { send_to: "AW-1/x" })).toBe(true);
+
+ expect(shim).toHaveBeenCalledWith("event", "conversion", {
+ send_to: "AW-1/x",
+ });
+ });
+
+ it("drops the command when the tag has not been set up", () => {
+ removeGtagShim();
+
+ expect(gtag("event", "conversion", { send_to: "AW-1/x" })).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/gtag.ts b/autogpt_platform/frontend/src/services/analytics/gtag.ts
new file mode 100644
index 0000000000..3b69baba85
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/gtag.ts
@@ -0,0 +1,18 @@
+export const DATA_LAYER_NAME = "dataLayer";
+
+declare global {
+ interface Window {
+ // The tag's own command shim, defined by the init script in SetupAnalytics.
+ // gtag.js only executes dataLayer entries that are real `arguments`
+ // objects, which only that shim can produce; everything routes through it.
+ gtag?: (...args: unknown[]) => void;
+ }
+}
+
+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;
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/index.test.ts b/autogpt_platform/frontend/src/services/analytics/index.test.ts
index ec91a4e299..cf5d5fcdeb 100644
--- a/autogpt_platform/frontend/src/services/analytics/index.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/index.test.ts
@@ -1,5 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { consent } from "@/services/consent/cookies";
+import {
+ installGtagShim,
+ removeGtagShim,
+} from "@/tests/integrations/gtag-shim";
import { analytics, flushDatafastQueue } from "./index";
vi.mock("@/services/consent/cookies", () => ({
@@ -157,3 +161,28 @@ describe("sendDatafastEvent", () => {
warn.mockRestore();
});
});
+
+describe("sendGAEvent", () => {
+ afterEach(() => {
+ removeGtagShim();
+ });
+
+ it("routes the command through the tag's own gtag shim", () => {
+ // Regression: the arguments used to be spread into the dataLayer as a
+ // plain array, and gtag.js only executes real `arguments` objects — so
+ // every custom GA event was silently dropped.
+ const calls = installGtagShim();
+
+ analytics.sendGAEvent("event", "tour_start", { scenario: "chat" });
+
+ expect(calls).toEqual([["event", "tour_start", { scenario: "chat" }]]);
+ });
+
+ it("drops the event when the tag never loaded", () => {
+ removeGtagShim();
+
+ expect(() =>
+ analytics.sendGAEvent("event", "tour_start", {}),
+ ).not.toThrow();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/index.tsx b/autogpt_platform/frontend/src/services/analytics/index.tsx
index 4d0f8a8705..18d536a07e 100644
--- a/autogpt_platform/frontend/src/services/analytics/index.tsx
+++ b/autogpt_platform/frontend/src/services/analytics/index.tsx
@@ -6,23 +6,22 @@
"use client";
import type { GAParams } from "@/types/google";
-import { consent } from "@/services/consent/cookies";
-import { usePathname } from "next/navigation";
+import { consent, type ConsentPreferences } from "@/services/consent/cookies";
import Script from "next/script";
-import { useEffect, useState } from "react";
import { environment } from "../environment";
+import { buildConsentModeScript } from "./consent-mode";
+import { DATA_LAYER_NAME, gtag } from "./gtag";
+import { isTourPath } from "./loading-policy";
+import { useSetupAnalytics } from "./useSetupAnalytics";
type DatafastEvent = [name: string, metadata: Record<string, unknown>];
declare global {
interface Window {
datafast?: (...event: DatafastEvent) => void;
- [key: string]: unknown[] | ((...args: unknown[]) => void) | unknown;
}
}
-let currDataLayerName: string | undefined = undefined;
-
type SetupProps = {
ga: GAParams;
host: string;
@@ -30,65 +29,29 @@ type SetupProps = {
export function SetupAnalytics(props: SetupProps) {
const { ga, host } = props;
- const { gaId, debugMode, dataLayerName = "dataLayer", nonce } = ga;
- const isProductionDomain = host.includes("platform.agpt.co");
-
- // Check for user consent
- const [hasAnalyticsConsent, setHasAnalyticsConsent] = useState(false);
-
- useEffect(() => {
- // Check consent on mount
- setHasAnalyticsConsent(consent.hasConsentFor("analytics"));
- }, []);
-
- // The public tour hides the cookie banner, so DataFast loads there without
- // the consent gate — otherwise tour funnel events would never fire for
- // first-touch visitors.
- const pathname = usePathname();
- const isPublicTourPage = isTourPath(pathname);
-
- // Datafa.st journey analytics only on production AND with consent
- const dataFastEnabled =
- isProductionDomain && (hasAnalyticsConsent || isPublicTourPage);
- // We collect analytics too for open source developers running the platform locally
- // BUT only with consent
- const googleAnalyticsEnabled =
- (environment.isLocal() || isProductionDomain) && hasAnalyticsConsent;
-
- if (currDataLayerName === undefined) {
- currDataLayerName = dataLayerName;
- }
-
- useEffect(() => {
- if (!googleAnalyticsEnabled) return;
-
- // Google Analytics: feature usage signal (same as original implementation)
- performance.mark("mark_feature_usage", {
- detail: {
- feature: "custom-ga",
- },
- });
- }, [googleAnalyticsEnabled]);
+ const { gaId, debugMode, nonce } = ga;
+ const adsID = environment.getGoogleAdsID();
+ const { preferences, googleTagEnabled, dataFastEnabled } =
+ useSetupAnalytics(host);
return (
<>
- {/* Google Analytics */}
- {googleAnalyticsEnabled ? (
+ {/* Google tag: GA4 + Google Ads */}
+ {googleTagEnabled ? (
<>
<Script
id="_custom-ga-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
- __html: `
- window['${dataLayerName}'] = window['${dataLayerName}'] || [];
- function gtag(){window['${dataLayerName}'].push(arguments);}
- gtag('js', new Date());
- gtag('config', '${gaId}' ${debugMode ? ",{ 'debug_mode': true }" : ""});
- `,
+ __html: buildGoogleTagInitScript({
+ GAID: gaId,
+ adsID,
+ debugMode,
+ preferences,
+ }),
}}
nonce={nonce}
/>
- {/* Google Tag Manager */}
<Script
id="_custom-ga"
strategy="afterInteractive"
@@ -112,23 +75,41 @@ export function SetupAnalytics(props: SetupProps) {
);
}
+interface InitScriptArgs {
+ GAID: string;
+ adsID: string;
+ debugMode?: boolean;
+ preferences: ConsentPreferences | null;
+}
+
+function buildGoogleTagInitScript({
+ GAID,
+ adsID,
+ debugMode,
+ preferences,
+}: InitScriptArgs): string {
+ // The IDs come from env vars and go into a nonce-bearing inline script, so
+ // they are escaped rather than interpolated raw: a stray quote in a misfilled
+ // env var would otherwise become CSP-blessed script.
+ return [
+ `window['${DATA_LAYER_NAME}'] = window['${DATA_LAYER_NAME}'] || [];`,
+ `function gtag(){window['${DATA_LAYER_NAME}'].push(arguments);}`,
+ buildConsentModeScript(preferences),
+ `gtag('js', new Date());`,
+ `gtag('config', ${JSON.stringify(GAID)}${debugMode ? ", { 'debug_mode': true }" : ""});`,
+ adsID
+ ? `gtag('config', ${JSON.stringify(adsID)}, { 'allow_enhanced_conversions': true });`
+ : "",
+ ].join("\n");
+}
+
export const analytics = {
sendGAEvent,
sendDatafastEvent,
};
function sendGAEvent(...args: unknown[]) {
- if (typeof window === "undefined") return;
- if (currDataLayerName === undefined) return;
-
- const dataLayer = window[currDataLayerName];
- if (!dataLayer) return;
-
- if (Array.isArray(dataLayer)) {
- dataLayer.push(...args);
- } else {
- console.warn(`Custom GA: dataLayer ${currDataLayerName} does not exist`);
- }
+ gtag(...args);
}
// Module scope means the queue survives client-side navigation: queued events
@@ -179,10 +160,3 @@ export function flushDatafastQueue() {
// overflows too.
datafastQueueOverflowWarned = false;
}
-
-// Segment-boundary match: /tourism must not inherit the tour's consent
-// exemption.
-function isTourPath(pathname: string | null): boolean {
- if (!pathname) return false;
- return pathname === "/tour" || pathname.startsWith("/tour/");
-}
diff --git a/autogpt_platform/frontend/src/services/analytics/loading-policy.test.ts b/autogpt_platform/frontend/src/services/analytics/loading-policy.test.ts
new file mode 100644
index 0000000000..ee1623d757
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/loading-policy.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it } from "vitest";
+import type { ConsentPreferences } from "@/services/consent/cookies";
+import { resolveAnalyticsLoading } from "./loading-policy";
+
+function preferences(
+ overrides: Partial<ConsentPreferences> = {},
+): ConsentPreferences {
+ return {
+ hasConsented: true,
+ timestamp: 1,
+ analytics: false,
+ monitoring: false,
+ advertising: false,
+ ...overrides,
+ };
+}
+
+const production = {
+ host: "platform.agpt.co",
+ pathname: "/marketplace",
+ isLocal: false,
+};
+
+describe("resolveAnalyticsLoading", () => {
+ it("loads the Google tag on production once preferences are known, even unanswered", () => {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ preferences: preferences({ hasConsented: false }),
+ });
+
+ expect(result.googleTag).toBe(true);
+ expect(result.dataFast).toBe(false);
+ });
+
+ it("waits for the stored preferences before loading anything", () => {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ preferences: null,
+ });
+
+ expect(result).toEqual({ googleTag: false, dataFast: false });
+ });
+
+ it("keeps the Google tag off non-production cloud domains", () => {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ host: "dev-builder.agpt.co",
+ preferences: preferences({ analytics: true, advertising: true }),
+ });
+
+ expect(result.googleTag).toBe(false);
+ });
+
+ it("rejects hostnames that merely contain the production host", () => {
+ const consented = preferences({ analytics: true, advertising: true });
+
+ for (const host of [
+ "platform.agpt.co.example.com",
+ "notplatform.agpt.co",
+ "platform.agpt.co.evil.co",
+ "agpt.co",
+ ]) {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ host,
+ preferences: consented,
+ });
+
+ expect({ host, ...result }).toEqual({
+ host,
+ googleTag: false,
+ dataFast: false,
+ });
+ }
+ });
+
+ it("accepts the production host with a port, odd casing or a trailing dot", () => {
+ const consented = preferences({ analytics: true, advertising: true });
+
+ for (const host of [
+ "platform.agpt.co:443",
+ "Platform.AGPT.co",
+ "platform.agpt.co.",
+ ]) {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ host,
+ preferences: consented,
+ });
+
+ expect({ host, ...result }).toEqual({
+ host,
+ googleTag: true,
+ dataFast: true,
+ });
+ }
+ });
+
+ it("loads the Google tag locally only with analytics consent", () => {
+ const local = { host: "localhost:3000", pathname: "/", isLocal: true };
+
+ expect(
+ resolveAnalyticsLoading({ ...local, preferences: preferences() })
+ .googleTag,
+ ).toBe(false);
+ expect(
+ resolveAnalyticsLoading({
+ ...local,
+ preferences: preferences({ analytics: true }),
+ }).googleTag,
+ ).toBe(true);
+ });
+
+ it("loads DataFast on production with analytics consent", () => {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ preferences: preferences({ analytics: true }),
+ });
+
+ expect(result.dataFast).toBe(true);
+ });
+
+ it("loads DataFast on the public tour without consent", () => {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ pathname: "/tour/chat",
+ preferences: preferences({ hasConsented: false }),
+ });
+
+ expect(result.dataFast).toBe(true);
+ });
+
+ it("does not treat /tourism as the tour", () => {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ pathname: "/tourism",
+ preferences: preferences({ hasConsented: false }),
+ });
+
+ expect(result.dataFast).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/loading-policy.ts b/autogpt_platform/frontend/src/services/analytics/loading-policy.ts
new file mode 100644
index 0000000000..a25faddc6e
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/loading-policy.ts
@@ -0,0 +1,51 @@
+import type { ConsentPreferences } from "@/services/consent/cookies";
+
+interface LoadingArgs {
+ host: string;
+ pathname: string | null;
+ isLocal: boolean;
+ preferences: ConsentPreferences | null;
+}
+
+export function resolveAnalyticsLoading({
+ host,
+ pathname,
+ isLocal,
+ preferences,
+}: LoadingArgs) {
+ // Stored consent is only readable in the browser; nothing loads until it is.
+ if (!preferences) return { googleTag: false, dataFast: false };
+
+ const isProductionDomain = isProductionHost(host);
+ const hasAnalyticsConsent = preferences.hasConsented && preferences.analytics;
+
+ return {
+ // Production loads the Google tag before the visitor answers: Consent Mode
+ // keeps it cookieless where consent is required (see consent-mode.ts).
+ // Open-source developers running locally only send analytics after opting in.
+ googleTag: isProductionDomain || (isLocal && hasAnalyticsConsent),
+ // The public tour hides the cookie banner, so DataFast loads there without
+ // the consent gate — otherwise tour funnel events would never fire for
+ // first-touch visitors.
+ dataFast:
+ isProductionDomain && (hasAnalyticsConsent || isTourPath(pathname)),
+ };
+}
+
+// Segment-boundary match: /tourism must not inherit the tour's consent
+// exemption.
+export function isTourPath(pathname: string | null): boolean {
+ if (!pathname) return false;
+ return pathname === "/tour" || pathname.startsWith("/tour/");
+}
+
+const PRODUCTION_HOST = "platform.agpt.co";
+
+// The Host header is client-controlled, so a substring match would hand the
+// production tag to `platform.agpt.co.example.com` (and to
+// `notplatform.agpt.co`). Compare the hostname exactly, minus the port, the
+// casing and the root-label dot a client can legally send.
+function isProductionHost(host: string): boolean {
+ const hostname = host.toLowerCase().split(":")[0].replace(/\.$/, "");
+ return hostname === PRODUCTION_HOST;
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/useAdsConversionTracker.ts b/autogpt_platform/frontend/src/services/analytics/useAdsConversionTracker.ts
new file mode 100644
index 0000000000..d202aebec0
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/useAdsConversionTracker.ts
@@ -0,0 +1,93 @@
+import { useAuth } from "@/lib/auth/hooks/useAuth";
+import { usePathname } from "next/navigation";
+import { useEffect, useRef } from "react";
+import {
+ clearAccountCreatedFlag,
+ readAccountCreatedFlag,
+} from "./account-created-cookie";
+import {
+ getSubscriptionValue,
+ trackAdsConversion,
+ trackAdsPageView,
+} from "./google-ads";
+
+export function useAdsConversionTracker() {
+ const { user, isUserLoading } = useAuth();
+ const pathname = usePathname();
+ const checkoutReportedRef = useRef(false);
+ const checkoutParamsRef = useRef<URLSearchParams | null>(null);
+ const lastTrackedPathRef = useRef<string | null>(null);
+
+ // Waits for the session itself, not just for loading to finish: on the
+ // post-signup client navigation the effect runs once with `user` still
+ // undefined, and a conversion sent then carries no id to dedup on and no
+ // email for enhanced conversions. Nothing here is reported without a user.
+ // Re-runs on navigation because the email signup sets the flag and then
+ // moves on client-side, without a reload.
+ useEffect(() => {
+ // Snapshot before the session guard. Stripe's result is only in the URL on
+ // the landing render, and a client-side navigation — including the credits
+ // page stripping its own query — can drop it before a retry runs, which
+ // would latch the ref on an empty query and lose the conversion for good.
+ const checkoutParams =
+ checkoutParamsRef.current ?? new URLSearchParams(window.location.search);
+ checkoutParamsRef.current = checkoutParams;
+
+ if (isUserLoading || !user) return;
+
+ if (!checkoutReportedRef.current) {
+ // Latch only once it actually reached the tag — the tag loads
+ // afterInteractive and may not exist yet on this pass.
+ checkoutReportedRef.current = trackCheckoutReturn(
+ checkoutParams,
+ user.email,
+ );
+ }
+
+ const method = readAccountCreatedFlag();
+ if (!method) return;
+ const reported = trackAdsConversion("sign_up", {
+ transactionID: user.id,
+ email: user.email,
+ });
+ // The flag is the only record that a signup happened; keep it until the
+ // conversion is really out, so the next navigation can retry.
+ if (reported) clearAccountCreatedFlag();
+ }, [user, isUserLoading, pathname]);
+
+ // The tag's own config call already reports the first page; only
+ // client-side navigations need a page_view from here.
+ useEffect(() => {
+ if (lastTrackedPathRef.current === null) {
+ lastTrackedPathRef.current = pathname;
+ return;
+ }
+ if (pathname === lastTrackedPathRef.current) return;
+ lastTrackedPathRef.current = pathname;
+ trackAdsPageView(pathname);
+ }, [pathname]);
+}
+
+// Returns whether the checkout result has been dealt with: true when there was
+// nothing to report, or when every conversion reached the tag.
+function trackCheckoutReturn(params: URLSearchParams, email?: string): boolean {
+ const sessionID = params.get("session_id") ?? undefined;
+ let handled = true;
+
+ if (params.get("subscription") === "success") {
+ handled =
+ trackAdsConversion("subscribe", {
+ value: getSubscriptionValue(params.get("plan"), params.get("cycle")),
+ transactionID: sessionID,
+ email,
+ }) && handled;
+ }
+
+ if (params.get("topup") === "success") {
+ handled =
+ trackAdsConversion("top_up", { transactionID: sessionID, email }) &&
+ handled;
+ }
+
+ return handled;
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/useSetupAnalytics.ts b/autogpt_platform/frontend/src/services/analytics/useSetupAnalytics.ts
new file mode 100644
index 0000000000..cc6b09dd13
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/useSetupAnalytics.ts
@@ -0,0 +1,44 @@
+"use client";
+
+import { useMountEffect } from "@/hooks/useMountEffect";
+import { consent, type ConsentPreferences } from "@/services/consent/cookies";
+import { usePathname } from "next/navigation";
+import { useEffect, useState } from "react";
+import { environment } from "../environment";
+import { resolveAnalyticsLoading } from "./loading-policy";
+
+export function useSetupAnalytics(host: string) {
+ // Stored consent is only readable in the browser; the tag waits for it so
+ // the init script can replay the visitor's answer through Consent Mode.
+ const [preferences, setPreferences] = useState<ConsentPreferences | null>(
+ null,
+ );
+ useMountEffect(() => {
+ setPreferences(consent.load());
+ });
+
+ const pathname = usePathname();
+ const { googleTag, dataFast } = resolveAnalyticsLoading({
+ host,
+ pathname,
+ isLocal: environment.isLocal(),
+ preferences,
+ });
+
+ useEffect(() => {
+ if (!googleTag) return;
+
+ // Google Analytics: feature usage signal (same as original implementation)
+ performance.mark("mark_feature_usage", {
+ detail: {
+ feature: "custom-ga",
+ },
+ });
+ }, [googleTag]);
+
+ return {
+ preferences,
+ googleTagEnabled: googleTag,
+ dataFastEnabled: dataFast,
+ };
+}
diff --git a/autogpt_platform/frontend/src/services/consent/cookies.test.ts b/autogpt_platform/frontend/src/services/consent/cookies.test.ts
index 9cf21fbfb9..5b51c2579f 100644
--- a/autogpt_platform/frontend/src/services/consent/cookies.test.ts
+++ b/autogpt_platform/frontend/src/services/consent/cookies.test.ts
@@ -10,6 +10,7 @@ function preferences(analytics: boolean): ConsentPreferences {
timestamp: Date.now(),
analytics,
monitoring: false,
+ advertising: false,
};
}
@@ -65,4 +66,28 @@ describe("analytics consent cookie", () => {
expect(document.cookie).not.toContain(`${COOKIE_NAME}=granted`);
});
+
+ it("keeps an answer stored before the advertising category existed, as advertising denied", () => {
+ localStorage.setItem(
+ Key.COOKIE_CONSENT,
+ JSON.stringify({
+ hasConsented: true,
+ timestamp: 1,
+ analytics: true,
+ monitoring: false,
+ }),
+ );
+
+ const loaded = consent.load();
+
+ expect(loaded.hasConsented).toBe(true);
+ expect(loaded.analytics).toBe(true);
+ expect(loaded.advertising).toBe(false);
+ });
+
+ it("persists advertising consent", () => {
+ consent.save({ ...preferences(true), advertising: true });
+
+ expect(consent.load().advertising).toBe(true);
+ });
});
diff --git a/autogpt_platform/frontend/src/services/consent/cookies.ts b/autogpt_platform/frontend/src/services/consent/cookies.ts
index 864d374dea..40298327ed 100644
--- a/autogpt_platform/frontend/src/services/consent/cookies.ts
+++ b/autogpt_platform/frontend/src/services/consent/cookies.ts
@@ -12,6 +12,7 @@ export interface ConsentPreferences {
timestamp: number;
analytics: boolean;
monitoring: boolean;
+ advertising: boolean;
}
export const DEFAULT_CONSENT: ConsentPreferences = {
@@ -19,6 +20,7 @@ export const DEFAULT_CONSENT: ConsentPreferences = {
timestamp: Date.now(),
analytics: false,
monitoring: false,
+ advertising: false,
};
export const COOKIE_CATEGORIES = {
@@ -39,6 +41,12 @@ export const COOKIE_CATEGORIES = {
"Record errors and user sessions to help us fix bugs faster (Sentry - includes screen recording)",
alwaysActive: false,
},
+ advertising: {
+ name: "Advertising",
+ description:
+ "Measure which ads bring people to AutoGPT so we only pay for the ones that work (Google Ads conversion tracking)",
+ alwaysActive: false,
+ },
} as const;
function load(): ConsentPreferences {
@@ -64,8 +72,18 @@ function load(): ConsentPreferences {
return DEFAULT_CONSENT;
}
- syncAnalyticsConsentCookie(parsed.hasConsented && parsed.analytics);
- return parsed;
+ // Answers stored before the advertising category existed count as a no
+ // for it rather than being thrown away and asked again.
+ const preferences: ConsentPreferences = {
+ ...parsed,
+ advertising:
+ typeof parsed.advertising === "boolean" ? parsed.advertising : false,
+ };
+
+ syncAnalyticsConsentCookie(
+ preferences.hasConsented && preferences.analytics,
+ );
+ return preferences;
} catch (error) {
syncAnalyticsConsentCookie(false);
Sentry.captureException(error);
diff --git a/autogpt_platform/frontend/src/services/environment/index.ts b/autogpt_platform/frontend/src/services/environment/index.ts
index 40b4d2049a..f564bbde9e 100644
--- a/autogpt_platform/frontend/src/services/environment/index.ts
+++ b/autogpt_platform/frontend/src/services/environment/index.ts
@@ -89,6 +89,14 @@ function getLaunchDarklyClientId() {
return process.env.NEXT_PUBLIC_LAUNCHDARKLY_CLIENT_ID;
}
+function getGoogleAdsID() {
+ return process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || "";
+}
+
+function getGoogleAdsConversionLabels() {
+ return process.env.NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS || "";
+}
+
function isProductionBuild() {
return process.env.NODE_ENV === "production";
}
@@ -151,6 +159,8 @@ export const environment = {
getPreviewStealingDev,
getPostHogCredentials,
getLaunchDarklyClientId,
+ getGoogleAdsID,
+ getGoogleAdsConversionLabels,
// Assertions
isServerSide,
isClientSide,
diff --git a/autogpt_platform/frontend/src/tests/integrations/gtag-shim.ts b/autogpt_platform/frontend/src/tests/integrations/gtag-shim.ts
new file mode 100644
index 0000000000..bc6453a4b7
--- /dev/null
+++ b/autogpt_platform/frontend/src/tests/integrations/gtag-shim.ts
@@ -0,0 +1,14 @@
+// Stands in for the `gtag()` shim the Google tag init script defines on
+// window, recording each command so tests can assert on what would reach the
+// dataLayer.
+export function installGtagShim(): unknown[][] {
+ const calls: unknown[][] = [];
+ window.gtag = (...args: unknown[]) => {
+ calls.push(args);
+ };
+ return calls;
+}
+
+export function removeGtagShim() {
+ delete window.gtag;
+}
diff --git a/autogpt_platform/frontend/src/types/google.ts b/autogpt_platform/frontend/src/types/google.ts
index c040b75a10..bd37149c59 100644
--- a/autogpt_platform/frontend/src/types/google.ts
+++ b/autogpt_platform/frontend/src/types/google.ts
@@ -26,7 +26,6 @@ export type GTMParams = {
export type GAParams = {
gaId: string;
- dataLayerName?: string;
debugMode?: boolean;
nonce?: string;
};