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): replace the cookie banner with Cookiebot and put PostHog behind consent (#14838)

Krzysztof Czerwinski5abfda1ddb54
diff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.default
index 0d7ca01e1a..75bba4f017 100644
--- a/autogpt_platform/frontend/.env.default
+++ b/autogpt_platform/frontend/.env.default
@@ -73,6 +73,18 @@ NEXT_PUBLIC_GA_MEASUREMENT_ID=G-FH2XK2W4GN
NEXT_PUBLIC_GOOGLE_ADS_ID=
NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS=
+# Cookiebot consent banner (Settings > Your scripts > "Domain group ID").
+# Leave empty to run without a banner: every optional cookie category
+# (analytics, monitoring, advertising) is then treated as denied, so no
+# GA/Ads/DataFast/Vercel Analytics/session replay loads.
+NEXT_PUBLIC_COOKIEBOT_CBID=
+# Optional: other Cookiebot domain groups for specific regions, passed
+# verbatim as the script's data-georegions attribute. Visitors elsewhere get
+# the NEXT_PUBLIC_COOKIEBOT_CBID group. Region codes are ISO 3166 (e.g. NL,
+# US, or US-06 for California), e.g.
+# {'region':'US-06','cbid':'<domain group id>'},{'region':'US','cbid':'<domain group id>'}
+NEXT_PUBLIC_COOKIEBOT_GEOREGIONS=
+
# Google Drive Picker
NEXT_PUBLIC_GOOGLE_CLIENT_ID=
NEXT_PUBLIC_GOOGLE_API_KEY=
diff --git a/autogpt_platform/frontend/instrumentation-client.ts b/autogpt_platform/frontend/instrumentation-client.ts
index a7808e5365..d9756ab8f1 100644
--- a/autogpt_platform/frontend/instrumentation-client.ts
+++ b/autogpt_platform/frontend/instrumentation-client.ts
@@ -2,15 +2,12 @@
// The config you add here will be used whenever a users loads a page in their browser.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
-import { consent } from "@/services/consent/cookies";
+import { setupSessionReplay } from "@/lib/session-replay";
import { environment } from "@/services/environment";
import * as Sentry from "@sentry/nextjs";
const shouldEnable = environment.isSentryEnabled();
-// Check for monitoring consent (includes session replay)
-const hasMonitoringConsent = consent.hasConsentFor("monitoring");
-
Sentry.init({
dsn: "https://fe4e4aa4a283391808a5da396da20159@o4505260022104064.ingest.us.sentry.io/4507946746380288",
@@ -34,10 +31,8 @@ Sentry.init({
Sentry.browserProfilingIntegration(),
Sentry.httpClientIntegration(),
Sentry.launchDarklyIntegration(),
- Sentry.replayIntegration({
- unmask: [".sentry-unmask, [data-sentry-unmask]"],
- }),
- Sentry.replayCanvasIntegration(),
+ // GDPR: session replay only once the visitor consents to monitoring
+ ...setupSessionReplay(),
Sentry.reportingObserverIntegration(),
// Sentry.feedbackIntegration({
// // Additional SDK configuration goes in here, for example:
@@ -59,12 +54,11 @@ Sentry.init({
// Define how likely Replay events are sampled.
// This sets the sample rate to be 10%. You may want this to be 100% while
// in development and sample at a lower rate in production
- // GDPR: Only enable if user has consented to monitoring
- replaysSessionSampleRate: hasMonitoringConsent ? 0.1 : 0,
+ // Inert until setupSessionReplay installs the replay integration.
+ replaysSessionSampleRate: 0.1,
// Define how likely Replay events are sampled when an error occurs.
- // GDPR: Only enable if user has consented to monitoring
- replaysOnErrorSampleRate: hasMonitoringConsent ? 1.0 : 0,
+ replaysOnErrorSampleRate: 1.0,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
diff --git a/autogpt_platform/frontend/playwright.config.ts b/autogpt_platform/frontend/playwright.config.ts
index 0805443035..e9871775dd 100644
--- a/autogpt_platform/frontend/playwright.config.ts
+++ b/autogpt_platform/frontend/playwright.config.ts
@@ -7,7 +7,6 @@ import { defineConfig, devices } from "@playwright/test";
import dotenv from "dotenv";
import fs from "fs";
import path from "path";
-import { buildCookieConsentStorageState } from "./src/playwright/credentials/storage-state";
dotenv.config({ path: path.resolve(__dirname, ".env") });
dotenv.config({ path: path.resolve(__dirname, "../backend/.env") });
@@ -16,7 +15,6 @@ const configuredBaseURL =
process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:3000";
const parsedBaseURL = new URL(configuredBaseURL);
const baseURL = parsedBaseURL.toString().replace(/\/$/, "");
-const baseOrigin = parsedBaseURL.origin;
const jsonReporterOutputFile = process.env.PLAYWRIGHT_JSON_OUTPUT_FILE;
const configuredWorkers = process.env.PLAYWRIGHT_WORKERS
? Number(process.env.PLAYWRIGHT_WORKERS)
@@ -121,9 +119,6 @@ export default defineConfig({
/* Helps debugging failures */
trace: process.env.CI ? "on-first-retry" : "retain-on-failure",
video: process.env.CI ? "off" : "retain-on-failure",
-
- /* Auto-accept cookies in all tests to prevent banner interference */
- storageState: buildCookieConsentStorageState(baseOrigin),
},
/* Maximum time one test can run for */
timeout: 25000,
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsx
index 0e1ef3aac2..c53c714c94 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/HireStep/__tests__/HireStep.test.tsx
@@ -5,7 +5,12 @@ import { server } from "@/mocks/mock-server";
import { render, screen, waitFor } from "@/tests/integrations/test-utils";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useOnboardingWizardStore } from "../../../store";
import { HireStep } from "../HireStep";
@@ -191,6 +196,8 @@ describe("HireStep — hiring", () => {
it("sends the funnel start and the DataFast hire goal", async () => {
// The backend emits this hire's hire_completed, so without the start the
// funnel's completion rate is unreadable for onboarding hires.
+ configureCookiebot();
+ installCookiebot({ statistics: true });
const datafast = vi.fn();
(window as unknown as { datafast: typeof datafast }).datafast = datafast;
mockTeam(TEAM);
@@ -338,3 +345,8 @@ it("stops waiting after the deadline if transient errors persist", async () => {
await new Promise((resolve) => setTimeout(resolve, 3000));
expect(calls).toBe(stoppedAt);
}, 26000);
+
+afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/install-on-expert.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/install-on-expert.test.tsx
index e51672e06a..e7213d3ffb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/install-on-expert.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/install-on-expert.test.tsx
@@ -13,7 +13,12 @@ import { Toaster } from "@/components/molecules/Toast/toaster";
import { server } from "@/mocks/mock-server";
import { render, screen, waitFor } from "@/tests/integrations/test-utils";
import userEvent from "@testing-library/user-event";
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { MainAgentPage } from "../components/MainAgentPage/MainAgentPage";
const mockUseAuth = vi.hoisted(() => vi.fn());
@@ -94,6 +99,8 @@ const datafast = vi.fn();
describe("Install on Expert from marketplace detail", () => {
beforeEach(() => {
+ configureCookiebot();
+ installCookiebot({ statistics: true });
datafast.mockReset();
(window as unknown as { datafast: typeof datafast }).datafast = datafast;
mockUseAuth.mockReturnValue({
@@ -102,6 +109,11 @@ describe("Install on Expert from marketplace detail", () => {
});
});
+ afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
+ });
+
test("shows the action and installs on the selected expert", async () => {
let installBody: unknown = null;
let installExpertId: string | null = null;
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
index c54b42cff9..7ab9b11d9c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from "react";
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
getGetV1GetNotificationPreferencesMockHandler,
@@ -14,12 +14,19 @@ import { http, HttpResponse } from "msw";
import { server } from "@/mocks/mock-server";
import {
+ act,
fireEvent,
render,
screen,
waitFor,
} from "@/tests/integrations/test-utils";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+
import SettingsPreferencesPage from "../page";
const mockUseAuth = vi.hoisted(() => vi.fn());
@@ -472,4 +479,79 @@ describe("SettingsPreferencesPage", () => {
expect(screen.queryByRole("combobox", { name: "Briefing" })).toBeNull();
expect(screen.queryAllByRole("switch")).toHaveLength(0);
});
+ describe("Cookie settings", () => {
+ afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ test("opens the Cookiebot dialog from the Cookies card", async () => {
+ configureCookiebot();
+ const { renew } = installCookiebot({ statistics: true });
+ setupBaseHandlers();
+
+ render(<SettingsPreferencesPage />);
+
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Cookie settings" }),
+ );
+
+ expect(renew).toHaveBeenCalledOnce();
+ });
+
+ test("explains why cookie settings are missing when Cookiebot could not load", async () => {
+ configureCookiebot();
+ vi.spyOn(document, "readyState", "get").mockReturnValue("complete");
+ setupBaseHandlers();
+
+ render(<SettingsPreferencesPage />);
+
+ expect(
+ await screen.findByText(/cookie settings couldn.t load/i),
+ ).toBeDefined();
+ expect(
+ screen.queryByRole("button", { name: "Cookie settings" }),
+ ).toBeNull();
+ });
+
+ test("offers the button once Cookiebot finishes loading", async () => {
+ configureCookiebot();
+ const readyState = vi
+ .spyOn(document, "readyState", "get")
+ .mockReturnValue("interactive");
+ setupBaseHandlers();
+
+ render(<SettingsPreferencesPage />);
+
+ const button = await screen.findByRole("button", {
+ name: "Cookie settings",
+ });
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+
+ const { renew } = installCookiebot();
+ readyState.mockReturnValue("complete");
+ act(() => {
+ window.dispatchEvent(new Event("load"));
+ });
+
+ await waitFor(() =>
+ expect((button as HTMLButtonElement).disabled).toBe(false),
+ );
+ fireEvent.click(button);
+ expect(renew).toHaveBeenCalledOnce();
+ });
+
+ test("hides the Cookies card when no consent banner is configured", async () => {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+ setupBaseHandlers();
+
+ render(<SettingsPreferencesPage />);
+
+ expect(await screen.findByText("Time zone")).toBeDefined();
+ expect(
+ screen.queryByRole("button", { name: "Cookie settings" }),
+ ).toBeNull();
+ });
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/components/CookieSettingsCard/CookieSettingsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/CookieSettingsCard/CookieSettingsCard.tsx
new file mode 100644
index 0000000000..d1e4475c4f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/CookieSettingsCard/CookieSettingsCard.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import { motion, useReducedMotion } from "framer-motion";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { openConsentSettings } from "@/services/consent/consent";
+import { useConsentManagerStatus } from "@/services/consent/useConsent";
+
+import { EASE_OUT } from "../../helpers";
+
+interface Props {
+ index?: number;
+}
+
+export function CookieSettingsCard({ index = 0 }: Props) {
+ const reduceMotion = useReducedMotion();
+ const status = useConsentManagerStatus();
+
+ return (
+ <motion.section
+ initial={reduceMotion ? false : { opacity: 0, y: 12 }}
+ animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}
+ transition={
+ reduceMotion
+ ? undefined
+ : {
+ duration: 0.32,
+ ease: EASE_OUT,
+ delay: 0.04 + index * 0.05,
+ }
+ }
+ className="flex w-full flex-col"
+ >
+ <div className="flex items-center justify-between gap-4 rounded-[18px] border border-zinc-200 bg-white px-4 py-4 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Cookies
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ Choose which optional cookies AutoGPT may use.
+ </Text>
+ </div>
+
+ {status === "unavailable" ? (
+ <Text
+ variant="small"
+ as="span"
+ role="status"
+ className="max-w-64 text-right text-zinc-500"
+ >
+ Cookie settings couldn&apos;t load. A content blocker may be
+ stopping them.
+ </Text>
+ ) : (
+ <Button
+ type="button"
+ size="small"
+ variant="secondary"
+ disabled={status !== "ready"}
+ onClick={openConsentSettings}
+ >
+ Cookie settings
+ </Button>
+ )}
+ </div>
+ </motion.section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
index 6530017f5e..56dbff28c0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
@@ -3,11 +3,13 @@
import { useEffect } from "react";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
+import { isConsentManagerConfigured } from "@/services/consent/consent";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { AccountCard } from "./components/AccountCard/AccountCard";
import { NotificationsCard } from "./components/NotificationsCard/NotificationsCard";
import { PreferencesHeader } from "./components/PreferencesHeader/PreferencesHeader";
+import { CookieSettingsCard } from "./components/CookieSettingsCard/CookieSettingsCard";
import { PreferencesSkeleton } from "./components/PreferencesSkeleton/PreferencesSkeleton";
import { SaveBar } from "./components/SaveBar/SaveBar";
import { TimezoneCard } from "./components/TimezoneCard/TimezoneCard";
@@ -77,6 +79,8 @@ export default function SettingsPreferencesPage() {
/>
) : null}
+ {isConsentManagerConfigured() ? <CookieSettingsCard index={3} /> : null}
+
<SaveBar
visible={dirty}
saving={isSaving}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.test.tsx
index feea27ed7e..67e9fddcc7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/FireExpertDialog/useFireExpertDialog.test.tsx
@@ -13,7 +13,12 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, renderHook, waitFor } from "@testing-library/react";
import { http, HttpResponse } from "msw";
import type { ReactNode } from "react";
-import { describe, expect, it, vi } from "vitest";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { useFireExpertDialog } from "./useFireExpertDialog";
type Props = {
@@ -59,6 +64,8 @@ describe("useFireExpertDialog invalidation", () => {
const client = makeClient();
const invalidateSpy = vi.spyOn(client, "invalidateQueries");
const onFired = vi.fn();
+ configureCookiebot();
+ installCookiebot({ statistics: true });
const datafast = vi.fn();
(window as unknown as { datafast: typeof datafast }).datafast = datafast;
@@ -178,3 +185,8 @@ describe("useFireExpertDialog invalidation", () => {
await waitFor(() => expect(archiveSpy).toHaveBeenCalledTimes(1));
});
});
+
+afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
+});
diff --git a/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/share.test.tsx b/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/share.test.tsx
index 25cf1b8c8b..b4c9f1c44e 100644
--- a/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/share.test.tsx
+++ b/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/share.test.tsx
@@ -13,6 +13,8 @@ vi.mock("@/components/ui/dot-distortion-shader", () => ({
DotDistortionShader: () => null,
}));
+import { configureCookiebot } from "@/tests/integrations/cookiebot";
+
import TourChatPage from "../page";
import { DEFAULT_SCENARIO_ID } from "../script/tourScenarios";
import { useTourStore } from "../tourStore";
@@ -29,6 +31,10 @@ describe("Tour share button", () => {
});
clipboardWrite.mockClear();
clipboardWrite.mockImplementation(async () => {});
+ // /tour sends DataFast events without consent, but only on the tour
+ // itself and only when a consent banner is configured.
+ configureCookiebot();
+ window.history.pushState({}, "", "/tour/chat");
window.datafast = datafast;
datafast.mockClear();
sessionStorage.clear();
@@ -44,6 +50,8 @@ describe("Tour share button", () => {
afterEach(() => {
vi.runOnlyPendingTimers();
vi.useRealTimers();
+ vi.unstubAllEnvs();
+ window.history.pushState({}, "", "/");
});
test("copies the tour URL with share attribution and flips to 'Link copied'", async () => {
diff --git a/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsx b/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsx
index 7c6220941b..3a2ce6d315 100644
--- a/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsx
+++ b/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsx
@@ -13,6 +13,8 @@ vi.mock("@/components/ui/dot-distortion-shader", () => ({
DotDistortionShader: () => null,
}));
+import { configureCookiebot } from "@/tests/integrations/cookiebot";
+
import TourChatPage from "../page";
import { DEFAULT_SCENARIO_ID } from "../script/tourScenarios";
import { useTourStore } from "../tourStore";
@@ -50,6 +52,10 @@ async function pressEnterToSend() {
describe("Tour DataFast tracking", () => {
beforeEach(() => {
vi.useFakeTimers();
+ // /tour sends DataFast events without consent, but only on the tour
+ // itself and only when a consent banner is configured.
+ configureCookiebot();
+ window.history.pushState({}, "", "/tour/chat");
window.datafast = datafast;
datafast.mockClear();
sessionStorage.clear();
@@ -65,6 +71,8 @@ describe("Tour DataFast tracking", () => {
afterEach(() => {
vi.runOnlyPendingTimers();
vi.useRealTimers();
+ vi.unstubAllEnvs();
+ window.history.pushState({}, "", "/");
});
test("fires tour_start once per session and tour_scenario_start per scenario run", async () => {
diff --git a/autogpt_platform/frontend/src/app/__tests__/layout.test.tsx b/autogpt_platform/frontend/src/app/__tests__/layout.test.tsx
new file mode 100644
index 0000000000..3b8d6cb42f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/__tests__/layout.test.tsx
@@ -0,0 +1,109 @@
+import Script from "next/script";
+import { isValidElement, type ReactElement, type ReactNode } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import RootLayout from "../layout";
+
+vi.mock("@/components/styles/fonts", () => ({
+ fonts: {
+ poppins: { variable: "" },
+ sans: { variable: "" },
+ mono: { variable: "" },
+ },
+}));
+
+// Only the layout's own markup is under test; the app shell it wraps pulls in
+// Next.js internals that need the React canary Next.js vendors.
+vi.mock("@/app/providers", () => ({
+ Providers: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@/components/molecules/ErrorBoundary/ErrorBoundary", () => ({
+ ErrorBoundary: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock("@/components/molecules/TallyPoup/TallyPopup", () => ({
+ default: () => null,
+}));
+vi.mock("@/components/molecules/Toast/toaster", () => ({
+ Toaster: () => null,
+}));
+vi.mock("@/services/analytics", () => ({ SetupAnalytics: () => null }));
+vi.mock("@/services/analytics/VercelAnalyticsWrapper", () => ({
+ VercelAnalyticsWrapper: () => null,
+}));
+vi.mock("@/components/AgentationDevtool", () => ({ default: () => null }));
+vi.mock("@tanstack/react-query-devtools", () => ({
+ ReactQueryDevtools: () => null,
+}));
+
+interface ScriptProps {
+ id?: string;
+ src?: string;
+ strategy?: string;
+ "data-cbid"?: string;
+ "data-georegions"?: string;
+ "data-blockingmode"?: string;
+ "data-cookieconsent"?: string;
+ dangerouslySetInnerHTML?: { __html: string };
+}
+
+// The layout is an async server component, so its element tree is inspected
+// directly instead of being rendered into the DOM.
+function findScripts(node: ReactNode): ScriptProps[] {
+ if (Array.isArray(node)) return node.flatMap(findScripts);
+ if (!isValidElement(node)) return [];
+ const element = node as ReactElement<{ children?: ReactNode }>;
+ if (element.type === Script) return [element.props as ScriptProps];
+ return findScripts(element.props.children);
+}
+
+async function renderedScripts() {
+ return findScripts(await RootLayout({ children: null }));
+}
+
+describe("RootLayout consent scripts", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("loads no banner and no Consent Mode defaults without a Cookiebot domain group", async () => {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+
+ expect(await renderedScripts()).toEqual([]);
+ });
+
+ it("queues the Consent Mode defaults before hydration and loads Cookiebot after it", async () => {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "test-cbid");
+
+ const [defaults, cookiebot, ...rest] = await renderedScripts();
+
+ expect(rest).toEqual([]);
+ expect(defaults).toMatchObject({
+ id: "google-consent-defaults",
+ strategy: "beforeInteractive",
+ "data-cookieconsent": "ignore",
+ });
+ expect(defaults.dangerouslySetInnerHTML?.__html).toContain(
+ "gtag('consent','default'",
+ );
+ expect(cookiebot).toEqual({
+ id: "Cookiebot",
+ src: "https://consent.cookiebot.com/uc.js",
+ "data-cbid": "test-cbid",
+ "data-blockingmode": "manual",
+ strategy: "afterInteractive",
+ });
+ expect(cookiebot["data-georegions"]).toBeUndefined();
+ });
+
+ it("passes regional domain groups through verbatim", async () => {
+ const geoRegions =
+ "{'region':'US-06','cbid':'11111111-1111-1111-1111-111111111111'},{'region':'US','cbid':'22222222-2222-2222-2222-222222222222'}";
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "test-cbid");
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_GEOREGIONS", geoRegions);
+
+ const cookiebot = (await renderedScripts()).find(
+ (script) => script.id === "Cookiebot",
+ );
+
+ expect(cookiebot?.["data-georegions"]).toBe(geoRegions);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/layout.tsx b/autogpt_platform/frontend/src/app/layout.tsx
index 7769e256b6..4e6cc74c37 100644
--- a/autogpt_platform/frontend/src/app/layout.tsx
+++ b/autogpt_platform/frontend/src/app/layout.tsx
@@ -5,16 +5,22 @@ import React from "react";
import "./globals.css";
import { Providers } from "@/app/providers";
-import { CookieConsentBanner } from "@/components/molecules/CookieConsentBanner/CookieConsentBanner";
import { ErrorBoundary } from "@/components/molecules/ErrorBoundary/ErrorBoundary";
import TallyPopupSimple from "@/components/molecules/TallyPoup/TallyPopup";
import { Toaster } from "@/components/molecules/Toast/toaster";
import { SetupAnalytics } from "@/services/analytics";
+import { buildConsentDefaultsScript } from "@/services/analytics/consent-mode";
import { VercelAnalyticsWrapper } from "@/services/analytics/VercelAnalyticsWrapper";
+import { ConsentWithdrawalReload } from "@/services/consent/ConsentWithdrawalReload";
+import {
+ COOKIEBOT_SCRIPT_ID,
+ COOKIEBOT_SCRIPT_URL,
+} from "@/services/consent/cookiebot";
import { environment } from "@/services/environment";
import AgentationDevtool from "@/components/AgentationDevtool";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { headers } from "next/headers";
+import Script from "next/script";
import { getSiteUrl } from "@/lib/metadata";
const isDev = environment.isDev();
@@ -58,6 +64,8 @@ export default async function RootLayout({
}>) {
const headersList = await headers();
const host = headersList.get("host") || "";
+ const cookiebotCBID = environment.getCookiebotCBID();
+ const cookiebotGeoRegions = environment.getCookiebotGeoRegions();
return (
<html
@@ -66,6 +74,32 @@ export default async function RootLayout({
suppressHydrationWarning
>
<body className="min-h-screen">
+ {/* Without a Cookiebot domain group there is no banner and every
+ optional category stays denied. With one, the Consent Mode
+ defaults are queued before anything else can reach the Google
+ tag. Cookiebot itself loads after hydration so a slow CDN cannot
+ hold the app back: blocking stays manual (the tools we gate are
+ bundled npm SDKs its auto-blocking cannot see), every one of them
+ asks services/consent, and until uc.js arrives that reads the same
+ stored answer uc.js reads when it starts. */}
+ {cookiebotCBID ? (
+ <>
+ <Script
+ id="google-consent-defaults"
+ strategy="beforeInteractive"
+ data-cookieconsent="ignore"
+ dangerouslySetInnerHTML={{ __html: buildConsentDefaultsScript() }}
+ />
+ <Script
+ id={COOKIEBOT_SCRIPT_ID}
+ src={COOKIEBOT_SCRIPT_URL}
+ data-cbid={cookiebotCBID}
+ data-georegions={cookiebotGeoRegions || undefined}
+ data-blockingmode="manual"
+ strategy="afterInteractive"
+ />
+ </>
+ ) : null}
<ErrorBoundary context="application">
<Providers
attribute="class"
@@ -95,7 +129,7 @@ export default async function RootLayout({
)}
</div>
<Toaster />
- <CookieConsentBanner />
+ <ConsentWithdrawalReload />
{(isLocal || isDev) && <AgentationDevtool />}
</Providers>
</ErrorBoundary>
diff --git a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/CookieConsentBanner.tsx b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/CookieConsentBanner.tsx
deleted file mode 100644
index a9860021f0..0000000000
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/CookieConsentBanner.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-"use client";
-
-import { Button } from "@/components/atoms/Button/Button";
-import { Text } from "@/components/atoms/Text/Text";
-import { useCookieConsentBanner } from "./useCookieConsentBanner";
-import { CookieSettingsModal } from "./components/CookieSettingsModal/CookieSettingsModal";
-import { CookieIcon } from "@hugeicons/core-free-icons";
-import { Icon } from "@/components/atoms/Icon/Icon";
-
-export function CookieConsentBanner() {
- const {
- shouldShowBanner,
- showSettings,
- handleAcceptAll,
- handleRejectAll,
- handleOpenSettings,
- handleCloseSettings,
- } = useCookieConsentBanner();
-
- if (!shouldShowBanner) {
- return null;
- }
-
- return (
- <>
- <div className="fixed bottom-0 left-0 right-0 z-50 px-10 pb-4">
- <div
- className="mx-auto max-w-6xl rounded-lg border border-neutral-200 bg-white p-4 shadow-lg dark:border-neutral-800 dark:bg-neutral-950"
- role="dialog"
- aria-label="Cookie consent banner"
- >
- <div className="flex flex-col items-start gap-4 md:flex-row md:items-center md:justify-between">
- <div className="flex flex-1 items-start gap-3">
- <Icon
- icon={CookieIcon}
- className="mt-0.5 h-5 w-5 shrink-0 text-neutral-700 dark:text-neutral-300"
- />
- <div className="flex-1">
- <Text
- variant="body-medium"
- className="mb-1 text-neutral-900 dark:text-neutral-100"
- >
- We use cookies
- </Text>
- <Text
- variant="body"
- className="text-neutral-600 dark:text-neutral-400"
- >
- AutoGPT uses essential cookies for login and optional cookies
- for analytics, advertising measurement and error tracking to
- improve our service.
- </Text>
- </div>
- </div>
-
- <div className="flex w-full flex-col gap-2 md:w-auto md:flex-row md:items-center">
- <Button
- variant="ghost"
- size="small"
- onClick={handleRejectAll}
- className="w-full md:w-auto"
- >
- Reject All
- </Button>
- <Button
- variant="ghost"
- size="small"
- onClick={handleOpenSettings}
- className="w-full md:w-auto"
- >
- Settings
- </Button>
- <Button
- variant="primary"
- size="small"
- onClick={handleAcceptAll}
- className="w-full md:w-auto"
- >
- Accept All
- </Button>
- </div>
- </div>
- </div>
- </div>
-
- {showSettings && (
- <CookieSettingsModal
- isOpen={showSettings}
- onClose={handleCloseSettings}
- />
- )}
- </>
- );
-}
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
deleted file mode 100644
index c48781bfc5..0000000000
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/__tests__/CookieConsentBanner.test.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-
-let pathname = "/marketplace";
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({
- push: vi.fn(),
- replace: vi.fn(),
- prefetch: vi.fn(),
- back: vi.fn(),
- forward: vi.fn(),
- refresh: vi.fn(),
- }),
- usePathname: () => pathname,
- useSearchParams: () => new URLSearchParams(),
- useParams: () => ({}),
-}));
-
-import { CookieConsentBanner } from "../CookieConsentBanner";
-
-describe("CookieConsentBanner", () => {
- beforeEach(() => {
- localStorage.clear();
- });
-
- test("shows for a visitor without consent", async () => {
- pathname = "/marketplace";
- render(<CookieConsentBanner />);
- expect(await screen.findByText("We use cookies")).toBeDefined();
- });
-
- test("stays hidden on the public tour pages", async () => {
- pathname = "/tour/chat";
- render(<CookieConsentBanner />);
- // The banner renders after a consent-load effect; give it the same beat
- // the positive case needs before asserting absence.
- 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
deleted file mode 100644
index e57ddcb434..0000000000
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/CookieSettingsModal.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-"use client";
-
-import { Button } from "@/components/atoms/Button/Button";
-import { Switch } from "@/components/atoms/Switch/Switch";
-import { Text } from "@/components/atoms/Text/Text";
-import { Dialog } from "@/components/molecules/Dialog/Dialog";
-import { COOKIE_CATEGORIES } from "@/services/consent/cookies";
-import { useCookieSettingsModal } from "./useCookieSettingsModal";
-import { Tick02Icon } from "@hugeicons/core-free-icons";
-import { Icon } from "@/components/atoms/Icon/Icon";
-
-interface Props {
- isOpen: boolean;
- onClose: () => void;
-}
-
-export function CookieSettingsModal({ isOpen, onClose }: Props) {
- const {
- analytics,
- setAnalytics,
- monitoring,
- setMonitoring,
- advertising,
- setAdvertising,
- handleSavePreferences,
- handleAcceptAll,
- handleRejectAll,
- } = useCookieSettingsModal({ onClose });
-
- return (
- <Dialog
- title="Cookie Settings"
- controlled={{
- isOpen,
- set: (open) => {
- if (!open) onClose();
- },
- }}
- >
- <Dialog.Content>
- <div className="space-y-6 pb-6">
- <div className="space-y-2">
- <div className="flex items-start justify-between gap-4">
- <div className="flex-1 space-y-1">
- <div className="flex items-center gap-2">
- <Text
- variant="body-medium"
- className="text-neutral-900 dark:text-neutral-100"
- >
- {COOKIE_CATEGORIES.essential.name}
- </Text>
- <span className="rounded-full bg-neutral-100 px-2 py-0.5 text-xs font-medium text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400">
- Always Active
- </span>
- </div>
- <Text
- variant="body"
- className="text-neutral-600 dark:text-neutral-400"
- >
- {COOKIE_CATEGORIES.essential.description}
- </Text>
- </div>
- <div className="flex items-center">
- <Icon icon={Tick02Icon} className="h-5 w-5 text-green-600" />
- </div>
- </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.analytics.name}
- </Text>
- <Text
- variant="body"
- className="text-neutral-600 dark:text-neutral-400"
- >
- {COOKIE_CATEGORIES.analytics.description}
- </Text>
- </div>
- <Switch
- checked={analytics}
- onCheckedChange={setAnalytics}
- aria-label="Toggle analytics cookies"
- />
- </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.monitoring.name}
- </Text>
- <Text
- variant="body"
- className="text-neutral-600 dark:text-neutral-400"
- >
- {COOKIE_CATEGORIES.monitoring.description}
- </Text>
- </div>
- <Switch
- checked={monitoring}
- onCheckedChange={setMonitoring}
- aria-label="Toggle monitoring cookies"
- />
- </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>
- <div className="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
- <Button variant="ghost" size="small" onClick={handleRejectAll}>
- Reject All
- </Button>
- <Button variant="ghost" size="small" onClick={handleAcceptAll}>
- Accept All
- </Button>
- <Button
- variant="primary"
- size="small"
- onClick={handleSavePreferences}
- >
- Save Preferences
- </Button>
- </div>
- </Dialog.Footer>
- </Dialog.Content>
- </Dialog>
- );
-}
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
deleted file mode 100644
index ef2c9529f9..0000000000
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/components/CookieSettingsModal/useCookieSettingsModal.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-"use client";
-
-import { useState, useEffect } from "react";
-import { useCookieConsent } from "../../useCookieConsent";
-
-interface Props {
- onClose: () => void;
-}
-
-export function useCookieSettingsModal({ onClose }: Props) {
- const { consent, handleUpdateConsent } = useCookieConsent();
-
- 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);
- setAdvertising(consent.advertising);
- }, [consent.analytics, consent.monitoring, consent.advertising]);
-
- function handleSavePreferences() {
- handleUpdateConsent({
- analytics,
- monitoring,
- advertising,
- });
- onClose();
- }
-
- function handleAcceptAll() {
- setAnalytics(true);
- setMonitoring(true);
- setAdvertising(true);
- handleUpdateConsent({
- analytics: true,
- monitoring: true,
- advertising: true,
- });
- onClose();
- }
-
- function handleRejectAll() {
- setAnalytics(false);
- setMonitoring(false);
- setAdvertising(false);
- handleUpdateConsent({
- analytics: false,
- monitoring: false,
- advertising: false,
- });
- onClose();
- }
-
- return {
- analytics,
- 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
deleted file mode 100644
index 09647a26bc..0000000000
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsent.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-"use client";
-
-import { useState, useEffect, useCallback } from "react";
-import {
- consent,
- ConsentPreferences,
- DEFAULT_CONSENT,
-} from "@/services/consent/cookies";
-
-export function useCookieConsent() {
- const [consentState, setConsentState] =
- useState<ConsentPreferences>(DEFAULT_CONSENT);
- const [isLoaded, setIsLoaded] = useState(false);
-
- useEffect(() => {
- const stored = consent.load();
- setConsentState(stored);
- setIsLoaded(true);
- }, []);
-
- const handleUpdateConsent = useCallback(
- (updates: Partial<ConsentPreferences>) => {
- const newConsent: ConsentPreferences = {
- ...consentState,
- ...updates,
- hasConsented: true,
- timestamp: Date.now(),
- };
- setConsentState(newConsent);
- consent.save(newConsent);
-
- if (typeof window !== "undefined") {
- window.location.reload();
- }
- },
- [consentState],
- );
-
- const handleAcceptAll = useCallback(() => {
- handleUpdateConsent({
- analytics: true,
- monitoring: true,
- advertising: true,
- });
- }, [handleUpdateConsent]);
-
- const handleRejectAll = useCallback(() => {
- handleUpdateConsent({
- analytics: false,
- monitoring: false,
- advertising: false,
- });
- }, [handleUpdateConsent]);
-
- const handleResetConsent = useCallback(() => {
- setConsentState(DEFAULT_CONSENT);
- consent.save(DEFAULT_CONSENT);
- }, []);
-
- return {
- consent: consentState,
- isLoaded,
- handleUpdateConsent,
- handleAcceptAll,
- handleRejectAll,
- handleResetConsent,
- };
-}
diff --git a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsentBanner.ts b/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsentBanner.ts
deleted file mode 100644
index c1f900a1db..0000000000
--- a/autogpt_platform/frontend/src/components/molecules/CookieConsentBanner/useCookieConsentBanner.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-"use client";
-
-import { usePathname } from "next/navigation";
-import { useState } from "react";
-import { useCookieConsent } from "./useCookieConsent";
-
-export function useCookieConsentBanner() {
- const { consent, isLoaded, handleAcceptAll, handleRejectAll } =
- useCookieConsent();
- const [showSettings, setShowSettings] = useState(false);
- const pathname = usePathname();
-
- // The public tour demo keeps the banner out of the way — DataFast loads
- // there without the consent gate instead (see SetupAnalytics).
- const isPublicTourPage = pathname?.startsWith("/tour") ?? false;
-
- const shouldShowBanner =
- isLoaded && !consent.hasConsented && !isPublicTourPage;
-
- function handleAcceptAllClick() {
- handleAcceptAll();
- }
-
- function handleRejectAllClick() {
- handleRejectAll();
- }
-
- function handleOpenSettings() {
- setShowSettings(true);
- }
-
- function handleCloseSettings() {
- setShowSettings(false);
- }
-
- return {
- shouldShowBanner,
- showSettings,
- handleAcceptAll: handleAcceptAllClick,
- handleRejectAll: handleRejectAllClick,
- handleOpenSettings,
- handleCloseSettings,
- };
-}
diff --git a/autogpt_platform/frontend/src/lib/__tests__/session-replay.test.ts b/autogpt_platform/frontend/src/lib/__tests__/session-replay.test.ts
new file mode 100644
index 0000000000..2d3bc99c9b
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/__tests__/session-replay.test.ts
@@ -0,0 +1,71 @@
+import * as Sentry from "@sentry/nextjs";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import { setupSessionReplay } from "../session-replay";
+
+vi.mock("@sentry/nextjs", () => ({
+ addIntegration: vi.fn(),
+ replayIntegration: vi.fn(() => ({ name: "Replay" })),
+ replayCanvasIntegration: vi.fn(() => ({ name: "ReplayCanvas" })),
+}));
+
+function integrationNames(integrations: { name: string }[]) {
+ return integrations.map((integration) => integration.name);
+}
+
+function addedIntegrationNames() {
+ return vi
+ .mocked(Sentry.addIntegration)
+ .mock.calls.map(([integration]) => integration.name);
+}
+
+describe("setupSessionReplay", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ configureCookiebot();
+ });
+
+ afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
+ });
+
+ it("installs replay at init when monitoring consent is already stored", () => {
+ installCookiebot({ statistics: true });
+
+ expect(integrationNames(setupSessionReplay())).toEqual([
+ "ReplayCanvas",
+ "Replay",
+ ]);
+ });
+
+ it("records nothing before consent, then adds replay once it is granted", () => {
+ installCookiebot();
+
+ expect(setupSessionReplay()).toEqual([]);
+ expect(Sentry.addIntegration).not.toHaveBeenCalled();
+
+ answerCookiebot({ marketing: true });
+ expect(Sentry.addIntegration).not.toHaveBeenCalled();
+
+ answerCookiebot({ statistics: true });
+ expect(addedIntegrationNames()).toEqual(["ReplayCanvas", "Replay"]);
+
+ answerCookiebot({ statistics: true, marketing: true });
+ expect(Sentry.addIntegration).toHaveBeenCalledTimes(2);
+ });
+
+ it("never installs replay without a consent banner", () => {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+ installCookiebot({ statistics: true });
+
+ expect(setupSessionReplay()).toEqual([]);
+ answerCookiebot({ statistics: true });
+ expect(Sentry.addIntegration).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/session-replay.ts b/autogpt_platform/frontend/src/lib/session-replay.ts
new file mode 100644
index 0000000000..add036cb79
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/session-replay.ts
@@ -0,0 +1,31 @@
+import { hasConsentFor, subscribeToConsent } from "@/services/consent/consent";
+import * as Sentry from "@sentry/nextjs";
+
+function createReplayIntegrations() {
+ // Canvas first: Replay looks it up by name when it sets up.
+ return [
+ Sentry.replayCanvasIntegration(),
+ Sentry.replayIntegration({
+ unmask: [".sentry-unmask, [data-sentry-unmask]"],
+ }),
+ ];
+}
+
+/**
+ * Session replay records the screen, so it only exists once the visitor has
+ * consented to monitoring. With consent already stored the integrations go
+ * into Sentry.init; otherwise they are added the moment consent is granted,
+ * without a reload, and nothing is recorded before that.
+ */
+export function setupSessionReplay() {
+ if (hasConsentFor("monitoring")) return createReplayIntegrations();
+
+ const unsubscribe = subscribeToConsent(() => {
+ if (!hasConsentFor("monitoring")) return;
+ unsubscribe();
+ createReplayIntegrations().forEach((integration) =>
+ Sentry.addIntegration(integration),
+ );
+ });
+ return [];
+}
diff --git a/autogpt_platform/frontend/src/playwright/credentials/storage-state.ts b/autogpt_platform/frontend/src/playwright/credentials/storage-state.ts
deleted file mode 100644
index 1dbaaa1616..0000000000
--- a/autogpt_platform/frontend/src/playwright/credentials/storage-state.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-export function buildCookieConsentStorageState(
- origin: string = "http://localhost:3000",
-) {
- return {
- cookies: [],
- origins: [
- {
- origin,
- localStorage: [
- {
- name: "autogpt_cookie_consent",
- value: JSON.stringify({
- hasConsented: true,
- timestamp: Date.now(),
- analytics: true,
- monitoring: true,
- }),
- },
- ],
- },
- ],
- };
-}
diff --git a/autogpt_platform/frontend/src/playwright/utils/auth.ts b/autogpt_platform/frontend/src/playwright/utils/auth.ts
index d83d099699..e59070daef 100644
--- a/autogpt_platform/frontend/src/playwright/utils/auth.ts
+++ b/autogpt_platform/frontend/src/playwright/utils/auth.ts
@@ -7,7 +7,6 @@ import {
SEEDED_TEST_USERS,
getAuthStatePath,
} from "../credentials/accounts";
-import { buildCookieConsentStorageState } from "../credentials/storage-state";
import { signupTestUser } from "./signup";
import { getBrowser } from "./get-browser";
import { skipOnboardingIfPresent } from "./onboarding";
@@ -41,19 +40,6 @@ export async function createTestUser(
const context = await browser.newContext();
const page = await context.newPage();
- // Auto-accept cookies in test environment to prevent banner from appearing
- await page.addInitScript(() => {
- window.localStorage.setItem(
- "autogpt_cookie_consent",
- JSON.stringify({
- hasConsented: true,
- timestamp: Date.now(),
- analytics: true,
- monitoring: true,
- }),
- );
- });
-
try {
const testUser = await signupTestUser(
page,
@@ -275,11 +261,7 @@ async function attemptCreateAuthState(
try {
const { email, password } = SEEDED_TEST_ACCOUNTS[accountKey];
- const origin = new URL(baseURL).origin;
- const context = await browser.newContext({
- baseURL,
- storageState: buildCookieConsentStorageState(origin),
- });
+ const context = await browser.newContext({ baseURL });
const page = await context.newPage();
const loginPage = new LoginPage(page);
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-consent.ts b/autogpt_platform/frontend/src/providers/posthog/posthog-consent.ts
new file mode 100644
index 0000000000..ec3bfcabde
--- /dev/null
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-consent.ts
@@ -0,0 +1,110 @@
+import { hasConsentFor, subscribeToConsent } from "@/services/consent/consent";
+import posthog, { type PostHogConfig } from "posthog-js";
+
+const POSTHOG_CONSENT_KEY = "agpt_posthog_consent";
+const PERSISTENT_STORAGE = "localStorage+cookie";
+
+/**
+ * PostHog starts opted out: capture() drops events instead of queueing them
+ * and session replay stays off. Without analytics consent it also keeps its
+ * state in memory, and forgetPostHogStorageWithoutConsent has deleted
+ * anything an earlier visit stored. Feature flags still evaluate, so
+ * experiments keep working for visitors who decline.
+ */
+export function getConsentGatedConfig() {
+ return {
+ persistence: hasConsentFor("analytics") ? PERSISTENT_STORAGE : "memory",
+ opt_out_capturing_by_default: true,
+ opt_out_persistence_by_default: true,
+ opt_out_capturing_persistence_type: "localStorage",
+ consent_persistence_name: POSTHOG_CONSENT_KEY,
+ disable_session_recording: true,
+ } satisfies Partial<PostHogConfig>;
+}
+
+/**
+ * Cookiebot is the source of truth. Run before init: without analytics
+ * consent, delete what PostHog stored on an earlier visit (its identity,
+ * which may belong to an identified user, and its own opt-in), since memory
+ * persistence only stops it being read.
+ */
+export function forgetPostHogStorageWithoutConsent(token: string) {
+ if (hasConsentFor("analytics")) return;
+ clearPostHogStorage(token);
+}
+
+/** Call once posthog.init has run; returns the unsubscribe. */
+export function followAnalyticsConsent() {
+ syncPostHogConsent();
+ return subscribeToConsent(syncPostHogConsent);
+}
+
+/**
+ * Bring PostHog in line with the current answer. Idempotent, so it is also
+ * safe to re-run after posthog.reset(), which drops PostHog's own opt-in.
+ */
+export function syncPostHogConsent() {
+ if (!hasConsentFor("analytics")) {
+ // Withdrawal also reloads the page; stop and drop PostHog's storage now,
+ // whatever PostHog itself believes its opt-in to be.
+ posthog.stopSessionRecording();
+ posthog.clear_opt_in_out_capturing();
+ clearPostHogStorage(posthog.config.token);
+ return;
+ }
+
+ if (!posthog.has_opted_in_capturing()) {
+ posthog.opt_in_capturing({ captureEventName: false });
+ }
+ if (posthog.config.persistence !== PERSISTENT_STORAGE) {
+ posthog.set_config({ persistence: PERSISTENT_STORAGE });
+ }
+ if (posthog.config.disable_session_recording) {
+ posthog.startSessionRecording();
+ }
+}
+
+// PostHog keeps ph_<token>_posthog in a cookie and localStorage, and
+// ph_<token>_window_id / _primary_window_exists in sessionStorage.
+function clearPostHogStorage(token: string) {
+ if (typeof window === "undefined" || !token) return;
+ const prefix = `ph_${token}_`;
+ clearStorage(() => window.localStorage, prefix);
+ clearStorage(() => window.sessionStorage, prefix);
+ try {
+ window.localStorage.removeItem(POSTHOG_CONSENT_KEY);
+ } catch {
+ // Storage blocked: PostHog cannot have stored an opt-in either.
+ }
+ document.cookie
+ .split(";")
+ .map((part) => part.trim().split("=")[0])
+ .filter((name) => name.startsWith(prefix))
+ .forEach(deleteCookie);
+}
+
+function clearStorage(getStorage: () => Storage, prefix: string) {
+ try {
+ const storage = getStorage();
+ const keys = Array.from({ length: storage.length }, (_, index) =>
+ storage.key(index),
+ );
+ keys
+ .filter((key): key is string => Boolean(key?.startsWith(prefix)))
+ .forEach((key) => storage.removeItem(key));
+ } catch {
+ // Storage blocked: nothing was stored there.
+ }
+}
+
+// PostHog sets its cookie on the widest domain it can (.agpt.co from
+// platform.agpt.co), so delete the host-only cookie and every parent
+// domain's.
+function deleteCookie(name: string) {
+ const expired = `${name}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;
+ document.cookie = expired;
+ const labels = window.location.hostname.split(".");
+ for (let index = 0; index < labels.length - 1; index++) {
+ document.cookie = `${expired}; Domain=.${labels.slice(index).join(".")}`;
+ }
+}
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
index 3c0ff6a328..acd97a0008 100644
--- a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
@@ -3,24 +3,36 @@
import { useAuth } from "@/lib/auth/hooks/useAuth";
import {
captureFirstLanding,
+ followAnalyticsConsentForIdentity,
getAnonymousID,
} from "@/services/analytics/anonymous-id";
+import { useConsent } from "@/services/consent/useConsent";
import { environment } from "@/services/environment";
import { PostHogProvider as PHProvider } from "@posthog/react";
import { usePathname, useSearchParams } from "next/navigation";
import posthog from "posthog-js";
import { ReactNode, useEffect, useRef } from "react";
+import {
+ followAnalyticsConsent,
+ forgetPostHogStorageWithoutConsent,
+ getConsentGatedConfig,
+} from "./posthog-consent";
export function PostHogProvider({ children }: { children: ReactNode }) {
const isPostHogEnabled = environment.isPostHogEnabled();
const postHogCredentials = environment.getPostHogCredentials();
useEffect(() => {
+ captureFirstLanding();
+ const unfollowIdentity = followAnalyticsConsentForIdentity();
+ let unfollowConsent = () => {};
if (postHogCredentials.key) {
// Seed PostHog's anonymous identity with the first-party anonymous id
// LaunchDarkly and the backend also use, so pre-signup activity from
- // every tool lands on the same person once identify() runs.
+ // every tool lands on the same person once identify() runs. Without
+ // analytics consent that id only lives for this page load.
const anonymousID = getAnonymousID();
+ forgetPostHogStorageWithoutConsent(postHogCredentials.key);
posthog.init(postHogCredentials.key, {
api_host: postHogCredentials.host,
defaults: "2025-11-30",
@@ -30,9 +42,14 @@ export function PostHogProvider({ children }: { children: ReactNode }) {
...(anonymousID && {
bootstrap: { distinctID: anonymousID, isIdentifiedID: false },
}),
+ ...getConsentGatedConfig(),
});
+ unfollowConsent = followAnalyticsConsent();
}
- captureFirstLanding();
+ return () => {
+ unfollowConsent();
+ unfollowIdentity();
+ };
}, []);
if (!isPostHogEnabled) return <>{children}</>;
@@ -42,12 +59,15 @@ export function PostHogProvider({ children }: { children: ReactNode }) {
export function PostHogUserTracker() {
const { user, isUserLoading } = useAuth();
+ const { analytics } = useConsent();
const previousUserIdRef = useRef<string | null>(null);
const isPostHogEnabled = environment.isPostHogEnabled();
useEffect(() => {
if (isUserLoading) return;
- if (!isPostHogEnabled) {
+ // Identifying hands PostHog the user id, email and name (flag evaluation
+ // sends them even while capture is opted out), so it waits for consent.
+ if (!isPostHogEnabled || !analytics) {
previousUserIdRef.current = null;
return;
}
@@ -63,7 +83,7 @@ export function PostHogUserTracker() {
} else if (previousUserIdRef.current !== null) {
previousUserIdRef.current = null;
}
- }, [user, isUserLoading, isPostHogEnabled]);
+ }, [user, isUserLoading, isPostHogEnabled, analytics]);
return null;
}
@@ -71,17 +91,18 @@ export function PostHogUserTracker() {
export function PostHogPageViewTracker() {
const pathname = usePathname();
const searchParams = useSearchParams();
+ const { analytics } = useConsent();
const isPostHogEnabled = environment.isPostHogEnabled();
useEffect(() => {
- if (pathname && isPostHogEnabled) {
+ if (pathname && isPostHogEnabled && analytics) {
let url = window.origin + pathname;
if (searchParams && searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
posthog.capture("$pageview", { $current_url: url });
}
- }, [pathname, searchParams, isPostHogEnabled]);
+ }, [pathname, searchParams, isPostHogEnabled, analytics]);
return null;
}
diff --git a/autogpt_platform/frontend/src/services/analytics/GoogleConsentModeSync.tsx b/autogpt_platform/frontend/src/services/analytics/GoogleConsentModeSync.tsx
new file mode 100644
index 0000000000..f96369a4d7
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/GoogleConsentModeSync.tsx
@@ -0,0 +1,11 @@
+"use client";
+
+import { useEffect } from "react";
+import { followConsentForGoogleTag } from "./consent-mode";
+
+// Rendered ahead of the Google tag's scripts: sibling effects run in order, so
+// a returning visitor's stored answer is queued before the tag's config.
+export function GoogleConsentModeSync() {
+ useEffect(() => followConsentForGoogleTag(), []);
+ return null;
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/VercelAnalyticsWrapper.tsx b/autogpt_platform/frontend/src/services/analytics/VercelAnalyticsWrapper.tsx
index ef6a96503b..5a209b014f 100644
--- a/autogpt_platform/frontend/src/services/analytics/VercelAnalyticsWrapper.tsx
+++ b/autogpt_platform/frontend/src/services/analytics/VercelAnalyticsWrapper.tsx
@@ -1,18 +1,13 @@
"use client";
-import { consent } from "@/services/consent/cookies";
+import { useConsent } from "@/services/consent/useConsent";
import { Analytics } from "@vercel/analytics/next";
import { SpeedInsights } from "@vercel/speed-insights/next";
-import { useEffect, useState } from "react";
export function VercelAnalyticsWrapper() {
- const [hasAnalyticsConsent, setHasAnalyticsConsent] = useState(false);
+ const { analytics } = useConsent();
- useEffect(() => {
- setHasAnalyticsConsent(consent.hasConsentFor("analytics"));
- }, []);
-
- if (!hasAnalyticsConsent) {
+ if (!analytics) {
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
index 21e9461515..c42d9523ce 100644
--- a/autogpt_platform/frontend/src/services/analytics/__tests__/AdsConversionTracker.test.tsx
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/AdsConversionTracker.test.tsx
@@ -5,7 +5,11 @@ import {
removeGtagShim,
} from "@/tests/integrations/gtag-shim";
import { ACCOUNT_CREATED_COOKIE } from "../account-created-cookie";
-import { consent } from "@/services/consent/cookies";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
let pathname = "/copilot";
vi.mock("next/navigation", () => ({
@@ -54,19 +58,14 @@ describe("AdsConversionTracker", () => {
);
// 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,
- });
+ configureCookiebot();
+ installCookiebot({ statistics: true, marketing: true });
});
afterEach(() => {
vi.unstubAllEnvs();
removeGtagShim();
- consent.clear();
+ removeCookiebot();
});
it("fires sign_up once for a just-created account and clears the flag", () => {
@@ -248,13 +247,7 @@ describe("AdsConversionTracker", () => {
});
it("drops the identifiers when the visitor rejected advertising", () => {
- consent.save({
- hasConsented: true,
- timestamp: 1,
- analytics: true,
- monitoring: true,
- advertising: false,
- });
+ installCookiebot({ statistics: true, marketing: false });
document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
render(<AdsConversionTracker />);
@@ -278,7 +271,8 @@ describe("AdsConversionTracker", () => {
});
it("drops the identifiers while the banner is unanswered", () => {
- consent.clear();
+ removeCookiebot();
+ installCookiebot();
document.cookie = `${ACCOUNT_CREATED_COOKIE}=email; Path=/`;
render(<AdsConversionTracker />);
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/anonymous-id.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/anonymous-id.test.ts
index 8bfc07cffd..c5e20a7458 100644
--- a/autogpt_platform/frontend/src/services/analytics/__tests__/anonymous-id.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/anonymous-id.test.ts
@@ -1,7 +1,13 @@
-import { consent } from "@/services/consent/cookies";
+import {
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
captureFirstLanding,
+ followAnalyticsConsentForIdentity,
getAnonymousID,
getPostHogDeviceID,
readFirstLanding,
@@ -10,13 +16,8 @@ import {
} from "../anonymous-id";
function setAnalyticsConsent(analytics: boolean): void {
- consent.save({
- hasConsented: true,
- timestamp: Date.now(),
- analytics,
- monitoring: false,
- advertising: false,
- });
+ configureCookiebot();
+ installCookiebot({ statistics: analytics });
}
function landOn(path: string, referrer = ""): void {
@@ -39,6 +40,7 @@ beforeEach(() => {
});
afterEach(() => {
+ removeCookiebot();
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
@@ -191,26 +193,112 @@ describe("first landing redaction", () => {
});
});
-describe("analytics consent", () => {
- // Attribution is collected under legitimate interest, not the analytics
- // consent category. Pinned so re-gating it is a deliberate change, not a
- // drive-by one; see the follow-up issue on revisiting this after GTM.
- it("still records the landing when analytics consent is refused", () => {
+describe("without analytics consent", () => {
+ beforeEach(() => {
setAnalyticsConsent(false);
+ });
+
+ it("mints a fresh id per page load and never stores it", () => {
+ const first = getAnonymousID();
+
+ expect(first).toBeTruthy();
+ expect(getAnonymousID()).toBe(first);
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBeNull();
+
+ resetAnonymousIDForTests();
+ expect(getAnonymousID()).not.toBe(first);
+ });
+
+ it("neither reads a stored id nor adopts a leftover PostHog device id", () => {
+ const getItem = vi.spyOn(Storage.prototype, "getItem");
+ window.localStorage.setItem(ANONYMOUS_ID_KEY, "stored-id");
+ window.localStorage.setItem(
+ "ph_phc_test_posthog",
+ JSON.stringify({ $device_id: "device-123" }),
+ );
+ document.cookie = `ph_phc_test_posthog=${encodeURIComponent(
+ JSON.stringify({ $device_id: "cookie-device" }),
+ )}; Path=/`;
+
+ const id = getAnonymousID();
+
+ expect(["stored-id", "device-123", "cookie-device"]).not.toContain(id);
+ expect(getPostHogDeviceID()).toBeNull();
+ expect(getItem).not.toHaveBeenCalled();
+ document.cookie = "ph_phc_test_posthog=; Path=/; Max-Age=0";
+ });
+
+ it("keeps the landing in memory instead of storing it", () => {
+ window.localStorage.setItem(
+ FIRST_LANDING_KEY,
+ JSON.stringify({ path: "/stored" }),
+ );
landOn("/pricing?utm_source=newsletter");
captureFirstLanding();
+ expect(window.localStorage.getItem(FIRST_LANDING_KEY)).toBe(
+ JSON.stringify({ path: "/stored" }),
+ );
expect(readFirstLanding()?.path).toBe("/pricing?utm_source=newsletter");
expect(readFirstLanding()?.utm_source).toBe("newsletter");
});
- it("keeps the visitor identity when analytics consent is refused", () => {
+ it("deletes what a visit with consent stored", () => {
+ window.localStorage.setItem(ANONYMOUS_ID_KEY, "stored-id");
+ window.localStorage.setItem(FIRST_LANDING_KEY, "{}");
+
+ followAnalyticsConsentForIdentity()();
+
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBeNull();
+ expect(window.localStorage.getItem(FIRST_LANDING_KEY)).toBeNull();
+ });
+});
+
+describe("following analytics consent", () => {
+ it("persists this page's id and landing on a grant, without a reload", () => {
+ configureCookiebot();
+ installCookiebot();
+ landOn("/pricing?utm_source=newsletter");
const id = getAnonymousID();
+ captureFirstLanding();
+ const unfollow = followAnalyticsConsentForIdentity();
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBeNull();
- setAnalyticsConsent(false);
+ answerCookiebot({ statistics: true });
expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBe(id);
expect(getAnonymousID()).toBe(id);
+ expect(
+ JSON.parse(window.localStorage.getItem(FIRST_LANDING_KEY) ?? "{}").path,
+ ).toBe("/pricing?utm_source=newsletter");
+ unfollow();
+ });
+
+ it("deletes the stored id and landing when consent is withdrawn", () => {
+ const id = getAnonymousID();
+ captureFirstLanding();
+ const unfollow = followAnalyticsConsentForIdentity();
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBe(id);
+ expect(window.localStorage.getItem(FIRST_LANDING_KEY)).not.toBeNull();
+
+ answerCookiebot({});
+
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBeNull();
+ expect(window.localStorage.getItem(FIRST_LANDING_KEY)).toBeNull();
+ unfollow();
+ });
+
+ it("keeps a first landing stored on an earlier visit", () => {
+ window.localStorage.setItem(
+ FIRST_LANDING_KEY,
+ JSON.stringify({ path: "/earlier" }),
+ );
+ landOn("/later");
+
+ captureFirstLanding();
+ followAnalyticsConsentForIdentity()();
+
+ expect(readFirstLanding()?.path).toBe("/earlier");
});
});
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/auth-identity.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/auth-identity.test.ts
index d7d452b1ae..6a737b42a7 100644
--- a/autogpt_platform/frontend/src/services/analytics/__tests__/auth-identity.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/auth-identity.test.ts
@@ -1,5 +1,10 @@
import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
import type { User } from "@/lib/auth/types";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
captureFirstLanding,
@@ -40,11 +45,14 @@ beforeEach(() => {
afterEach(() => {
useAuthStore.setState({ user: null });
+ removeCookiebot();
vi.unstubAllEnvs();
});
describe("analytics identity on account transitions", () => {
it("rotates the visitor and landing on logout without an initialized PostHog client", () => {
+ configureCookiebot();
+ installCookiebot({ statistics: true });
window.localStorage.setItem(
"ph_phc_test_posthog",
JSON.stringify({ $device_id: "old-device" }),
@@ -57,9 +65,24 @@ describe("analytics identity on account transitions", () => {
expect(getAnonymousID()).not.toBe("old-device");
expect(readFirstLanding()).toBeNull();
+ expect(window.localStorage.getItem("agpt_anonymous_id")).toBe(
+ getAnonymousID(),
+ );
expect(posthog.reset).not.toHaveBeenCalled();
});
+ it("rotates the visitor on logout without storing it when analytics is declined", () => {
+ configureCookiebot();
+ installCookiebot({ statistics: false });
+ const previous = getAnonymousID();
+ useAuthStore.setState({ user: userA });
+
+ useAuthStore.setState({ user: null });
+
+ expect(getAnonymousID()).not.toBe(previous);
+ expect(window.localStorage.getItem("agpt_anonymous_id")).toBeNull();
+ });
+
it.each([null, userB])(
"shares the fresh PostHog identity before observers see the next account %j",
(nextUser) => {
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/consent-consumers.test.tsx b/autogpt_platform/frontend/src/services/analytics/__tests__/consent-consumers.test.tsx
new file mode 100644
index 0000000000..dad3173e7a
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/consent-consumers.test.tsx
@@ -0,0 +1,264 @@
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import { ConsentWithdrawalReload } from "@/services/consent/ConsentWithdrawalReload";
+import { SetupAnalytics } from "../index";
+import { VercelAnalyticsWrapper } from "../VercelAnalyticsWrapper";
+
+vi.mock("next/script", () => ({
+ default: ({
+ id,
+ src,
+ strategy,
+ dangerouslySetInnerHTML: _inline,
+ onLoad: _onLoad,
+ ...attributes
+ }: {
+ id?: string;
+ src?: string;
+ strategy?: string;
+ dangerouslySetInnerHTML?: unknown;
+ onLoad?: unknown;
+ }) => (
+ <div
+ data-testid={`script:${id ?? src}`}
+ data-src={src}
+ data-strategy={strategy}
+ {...attributes}
+ />
+ ),
+}));
+
+vi.mock("@vercel/analytics/next", () => ({
+ Analytics: () => <div data-testid="vercel-analytics" />,
+}));
+vi.mock("@vercel/speed-insights/next", () => ({
+ SpeedInsights: () => <div data-testid="vercel-speed-insights" />,
+}));
+
+const GA = { gaId: "G-TEST" };
+const DATAFAST_SRC = "https://datafa.st/js/script.js";
+
+function queryScript(name: string) {
+ return screen.queryByTestId(`script:${name}`);
+}
+
+beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+});
+
+afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
+});
+
+describe("without NEXT_PUBLIC_COOKIEBOT_CBID", () => {
+ it("loads no analytics, even for a browser holding an old answer", () => {
+ installCookiebot({ statistics: true, marketing: true });
+
+ render(
+ <>
+ <SetupAnalytics host="platform.agpt.co" ga={GA} />
+ <VercelAnalyticsWrapper />
+ </>,
+ );
+
+ expect(queryScript("_custom-ga")).toBeNull();
+ expect(queryScript(DATAFAST_SRC)).toBeNull();
+ expect(screen.queryByTestId("vercel-analytics")).toBeNull();
+ });
+
+ it("keeps the Google tag off locally even for an opted-in browser", () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");
+ installCookiebot({ statistics: true });
+
+ render(<SetupAnalytics host="localhost:3000" ga={GA} />);
+
+ expect(queryScript("_custom-ga")).toBeNull();
+ });
+});
+
+describe("with NEXT_PUBLIC_COOKIEBOT_CBID", () => {
+ beforeEach(() => {
+ configureCookiebot();
+ });
+
+ it("loads the Google tag on production before the visitor answers", () => {
+ installCookiebot();
+
+ render(<SetupAnalytics host="platform.agpt.co" ga={GA} />);
+
+ expect(queryScript("_custom-ga")).not.toBeNull();
+ expect(queryScript(DATAFAST_SRC)).toBeNull();
+ });
+
+ it("sends the answer to the Google tag as a Consent Mode update", () => {
+ installCookiebot();
+ render(<SetupAnalytics host="platform.agpt.co" ga={GA} />);
+
+ act(() => answerCookiebot({ statistics: true }));
+
+ const dataLayer = (window as unknown as { dataLayer?: IArguments[] })
+ .dataLayer;
+ expect(dataLayer?.map((entry) => Array.from(entry))).toContainEqual([
+ "consent",
+ "update",
+ {
+ analytics_storage: "granted",
+ ad_storage: "denied",
+ ad_user_data: "denied",
+ ad_personalization: "denied",
+ },
+ ]);
+ delete (window as unknown as { dataLayer?: unknown }).dataLayer;
+ });
+
+ it("starts DataFast and Vercel Analytics when the visitor accepts, without a reload", () => {
+ installCookiebot();
+ render(
+ <>
+ <SetupAnalytics host="platform.agpt.co" ga={GA} />
+ <VercelAnalyticsWrapper />
+ </>,
+ );
+ expect(queryScript(DATAFAST_SRC)).toBeNull();
+ expect(screen.queryByTestId("vercel-analytics")).toBeNull();
+
+ act(() => answerCookiebot({ statistics: true }));
+
+ expect(queryScript(DATAFAST_SRC)).not.toBeNull();
+ expect(screen.getByTestId("vercel-analytics")).toBeDefined();
+ });
+
+ it("loads the Google tag locally once the visitor accepts statistics", () => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");
+ installCookiebot();
+ render(<SetupAnalytics host="localhost:3000" ga={GA} />);
+ expect(queryScript("_custom-ga")).toBeNull();
+
+ act(() => answerCookiebot({ marketing: true }));
+ expect(queryScript("_custom-ga")).toBeNull();
+
+ act(() => answerCookiebot({ statistics: true }));
+ expect(queryScript("_custom-ga")).not.toBeNull();
+ });
+
+ it("stops rendering Vercel Analytics when the visitor declines", () => {
+ installCookiebot({ statistics: true });
+ render(<VercelAnalyticsWrapper />);
+ expect(screen.getByTestId("vercel-analytics")).toBeDefined();
+
+ act(() => answerCookiebot({}));
+
+ expect(screen.queryByTestId("vercel-analytics")).toBeNull();
+ });
+});
+
+describe("DataFast loaded under the tour exemption", () => {
+ const reload = vi.fn<() => void>();
+ let loaded: HTMLScriptElement | null = null;
+
+ function loadDataFast({ exempt }: { exempt: boolean }) {
+ loaded = document.createElement("script");
+ loaded.src = DATAFAST_SRC;
+ if (exempt) loaded.dataset.consentExempt = "true";
+ document.head.appendChild(loaded);
+ }
+
+ beforeEach(() => {
+ configureCookiebot();
+ reload.mockReset();
+ vi.spyOn(window.location, "reload").mockImplementation(() => reload());
+ });
+
+ afterEach(() => {
+ loaded?.remove();
+ loaded = null;
+ vi.restoreAllMocks();
+ });
+
+ it("reloads to shed the script once the visitor leaves the tour without consent", () => {
+ loadDataFast({ exempt: true });
+ installCookiebot();
+
+ render(<SetupAnalytics host="platform.agpt.co" ga={GA} />);
+
+ expect(reload).toHaveBeenCalledOnce();
+ });
+
+ it("keeps the script when the visitor has consented", () => {
+ loadDataFast({ exempt: true });
+ installCookiebot({ statistics: true });
+
+ render(<SetupAnalytics host="platform.agpt.co" ga={GA} />);
+
+ expect(reload).not.toHaveBeenCalled();
+ });
+
+ it("waits for the visitor's reply when Cookiebot asks again about a script loaded with consent", () => {
+ loadDataFast({ exempt: false });
+ installCookiebot();
+
+ render(<SetupAnalytics host="platform.agpt.co" ga={GA} />);
+
+ expect(reload).not.toHaveBeenCalled();
+ });
+});
+
+describe("ConsentWithdrawalReload", () => {
+ const reload = vi.fn<() => void>();
+
+ beforeEach(() => {
+ configureCookiebot();
+ reload.mockReset();
+ vi.spyOn(window.location, "reload").mockImplementation(() => reload());
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("reloads when a granted category is taken back", () => {
+ installCookiebot({ statistics: true, marketing: true });
+ render(<ConsentWithdrawalReload />);
+
+ act(() => answerCookiebot({ statistics: true }));
+
+ expect(reload).toHaveBeenCalledOnce();
+ });
+
+ it("does not reload when Cookiebot invalidates a stale granting cookie, only on the visitor's reply", () => {
+ const stale =
+ "{stamp:'abc',necessary:true,preferences:false,statistics:true,marketing:false,method:'explicit',ver:1,utc:1,region:'de'}";
+ document.cookie = `CookieConsent=${encodeURIComponent(stale)}; Path=/`;
+ render(<ConsentWithdrawalReload />);
+
+ act(() => {
+ installCookiebot();
+ window.dispatchEvent(new Event("CookiebotOnLoad"));
+ });
+
+ expect(reload).not.toHaveBeenCalled();
+
+ act(() => answerCookiebot({}));
+
+ expect(reload).toHaveBeenCalledOnce();
+ });
+
+ it("does not reload when the visitor grants more, or repeats the same answer", () => {
+ installCookiebot();
+ render(<ConsentWithdrawalReload />);
+
+ act(() => answerCookiebot({ statistics: true }));
+ act(() => answerCookiebot({ statistics: true }));
+ act(() => answerCookiebot({ statistics: true, marketing: true }));
+
+ expect(reload).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-consent.test.tsx b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-consent.test.tsx
new file mode 100644
index 0000000000..5961f938a5
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-consent.test.tsx
@@ -0,0 +1,472 @@
+import type { User } from "@/lib/auth/types";
+import { server } from "@/mocks/mock-server";
+import {
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import { act, render } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { PostHog } from "posthog-js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Runs the real posthog-js client against a stubbed PostHog host, so these
+// assertions cover what the SDK itself stores and sends, not our calls to it.
+
+const POSTHOG_HOST = "https://posthog.test";
+const POSTHOG_KEY = "phc_test";
+const EVENT_PATHS = ["/e/", "/i/v0/e/", "/batch/", "/capture/", "/s/"];
+
+const FLAGS_RESPONSE = {
+ flags: {
+ "pricing-test": {
+ key: "pricing-test",
+ enabled: true,
+ variant: "yearly",
+ metadata: { id: 1, version: 1 },
+ },
+ },
+};
+
+const CORS_HEADERS = {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Headers": "*",
+ "Access-Control-Allow-Methods": "*",
+};
+
+const USER = {
+ id: "user-1",
+ email: "[email protected]",
+ user_metadata: { name: "Ada" },
+} as unknown as User;
+
+interface FlagsRequest {
+ distinct_id?: string;
+ $device_id?: string;
+ $anon_distinct_id?: string;
+ person_properties?: Record<string, unknown>;
+}
+
+let requests: string[] = [];
+let flagsRequests: FlagsRequest[] = [];
+let captured: string[] = [];
+
+interface RenderOptions {
+ user?: User | null;
+}
+
+// Each call is a fresh page load: a new client (init() is a no-op on one that
+// already ran) and fresh modules, so in-memory ids start over too.
+async function renderPostHog({ user = null }: RenderOptions = {}) {
+ vi.resetModules();
+ const client = new PostHog();
+ vi.doMock("posthog-js", () => ({
+ default: client,
+ posthog: client,
+ PostHog,
+ }));
+ vi.doMock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ user, isUserLoading: false }),
+ }));
+ const [provider, { trackTabIntro }, { resetAnalyticsIdentity }] =
+ await Promise.all([
+ import("@/providers/posthog/posthog-provider"),
+ import("@/services/onboarding/tab-intro-analytics"),
+ import("@/services/analytics/reset-identity"),
+ ]);
+ const startSessionRecording = vi.spyOn(client, "startSessionRecording");
+ const identify = vi.spyOn(client, "identify");
+ const { PostHogProvider, PostHogPageViewTracker, PostHogUserTracker } =
+ provider;
+ render(
+ <PostHogProvider>
+ <PostHogUserTracker />
+ <PostHogPageViewTracker />
+ </PostHogProvider>,
+ );
+ client.on("eventCaptured", (event) => {
+ captured.push(event.event);
+ });
+ return {
+ posthog: client,
+ trackTabIntro,
+ startSessionRecording,
+ identify,
+ resetAnalyticsIdentity,
+ };
+}
+
+function sentEvents() {
+ return requests.filter((path) =>
+ EVENT_PATHS.some((prefix) => path.startsWith(prefix)),
+ );
+}
+
+// Everything this browser holds for analytics, our own agpt_ keys included.
+function storedPostHogKeys() {
+ const storage = [window.localStorage, window.sessionStorage].flatMap(
+ (store) => Object.keys(store),
+ );
+ return [...storage, ...cookieNames()].filter(
+ (key) => key !== "CookieConsent",
+ );
+}
+
+function setPageURL(url: string) {
+ const { happyDOM } = window as unknown as {
+ happyDOM?: { setURL: (url: string) => void };
+ };
+ happyDOM?.setURL(url);
+}
+
+// Records every cookie write while still applying it.
+function recordCookieWrites(): string[] {
+ let proto: object | null = document;
+ let descriptor: PropertyDescriptor | undefined;
+ while (proto && !descriptor?.set) {
+ descriptor = Object.getOwnPropertyDescriptor(proto, "cookie");
+ proto = Object.getPrototypeOf(proto);
+ }
+ if (!descriptor?.get || !descriptor.set)
+ throw new Error("no cookie accessor");
+ const { get, set } = descriptor;
+ const writes: string[] = [];
+ Object.defineProperty(document, "cookie", {
+ configurable: true,
+ get: () => get.call(document),
+ set: (value: string) => {
+ writes.push(value);
+ set.call(document, value);
+ },
+ });
+ return writes;
+}
+
+async function readFlagsBody(request: Request): Promise<FlagsRequest> {
+ const body = await request.text();
+ const data = new URLSearchParams(body).get("data");
+ const json = data ? Buffer.from(data, "base64").toString("utf8") : body;
+ return JSON.parse(json) as FlagsRequest;
+}
+
+function seedEarlierVisit() {
+ const earlier = JSON.stringify({
+ distinct_id: "user-1",
+ $device_id: "old-device",
+ });
+ window.localStorage.setItem("agpt_anonymous_id", "stored-id");
+ window.localStorage.setItem("agpt_first_landing", '{"path":"/earlier"}');
+ window.localStorage.setItem(`ph_${POSTHOG_KEY}_posthog`, earlier);
+ window.sessionStorage.setItem(`ph_${POSTHOG_KEY}_window_id`, '"window"');
+ window.sessionStorage.setItem(
+ `ph_${POSTHOG_KEY}_primary_window_exists`,
+ "true",
+ );
+ document.cookie = `ph_${POSTHOG_KEY}_posthog=${encodeURIComponent(earlier)}; Path=/`;
+}
+
+function cookieNames() {
+ return document.cookie
+ .split(";")
+ .map((part) => part.trim().split("=")[0])
+ .filter(Boolean);
+}
+
+beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", POSTHOG_KEY);
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_HOST", POSTHOG_HOST);
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+ // posthog-js tries a script tag for remote config first; happy-dom refuses
+ // to load scripts and reports it, before the SDK falls back to fetch.
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ // PostHog drops events from browsers it takes for bots, HappyDOM included.
+ vi.spyOn(navigator, "webdriver", "get").mockReturnValue(false);
+ requests = [];
+ flagsRequests = [];
+ captured = [];
+ server.use(
+ http.options(
+ `${POSTHOG_HOST}/*`,
+ () => new HttpResponse(null, { status: 204, headers: CORS_HEADERS }),
+ ),
+ http.all(`${POSTHOG_HOST}/*`, async ({ request }) => {
+ const path = new URL(request.url).pathname;
+ requests.push(path);
+ if (path === "/flags/") flagsRequests.push(await readFlagsBody(request));
+ return HttpResponse.json(path === "/flags/" ? FLAGS_RESPONSE : {}, {
+ headers: CORS_HEADERS,
+ });
+ }),
+ );
+});
+
+afterEach(() => {
+ removeCookiebot();
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ cookieNames().forEach((name) => {
+ document.cookie = `${name}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;
+ });
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+});
+
+describe("PostHog before analytics consent", () => {
+ beforeEach(() => {
+ configureCookiebot();
+ installCookiebot();
+ });
+
+ it("captures nothing, stores nothing and records nothing", async () => {
+ const { posthog, trackTabIntro, startSessionRecording } =
+ await renderPostHog();
+
+ posthog.capture("custom_event");
+ trackTabIntro("tab_intro_shown", { tab: "agents" });
+
+ expect(posthog.has_opted_out_capturing()).toBe(true);
+ expect(posthog.config.disable_session_recording).toBe(true);
+ expect(startSessionRecording).not.toHaveBeenCalled();
+ expect(captured).toEqual([]);
+ expect(storedPostHogKeys()).toEqual([]);
+ await vi.waitFor(() => expect(requests).toContain("/flags/"));
+ expect(sentEvents()).toEqual([]);
+ });
+
+ it("still evaluates feature flags for visitors who decline", async () => {
+ const { posthog } = await renderPostHog();
+ act(() => answerCookiebot({}));
+
+ await vi.waitFor(() =>
+ expect(posthog.getFeatureFlag("pricing-test")).toBe("yearly"),
+ );
+ expect(captured).toEqual([]);
+ expect(storedPostHogKeys()).toEqual([]);
+ });
+
+ it("ignores an opt-in PostHog stored before consent was withdrawn", async () => {
+ window.localStorage.setItem("agpt_posthog_consent", "1");
+
+ const { posthog } = await renderPostHog();
+ posthog.capture("custom_event");
+
+ expect(posthog.has_opted_out_capturing()).toBe(true);
+ expect(captured).toEqual([]);
+ expect(storedPostHogKeys()).toEqual([]);
+ });
+
+ it("deletes what an earlier visit stored before PostHog starts", async () => {
+ seedEarlierVisit();
+
+ await renderPostHog();
+
+ expect(storedPostHogKeys()).toEqual([]);
+ });
+
+ it("sends /flags a fresh id for each page load, never a stored one", async () => {
+ seedEarlierVisit();
+
+ await renderPostHog();
+ await vi.waitFor(() => expect(flagsRequests).toHaveLength(1));
+ const [first] = flagsRequests;
+
+ expect(first.distinct_id).toBeTruthy();
+ expect(["stored-id", "user-1", "old-device"]).not.toContain(
+ first.distinct_id,
+ );
+ expect(first.$device_id).toBe(first.distinct_id);
+ expect(first.person_properties).toEqual({});
+
+ seedEarlierVisit();
+ await renderPostHog();
+ await vi.waitFor(() => expect(flagsRequests).toHaveLength(2));
+
+ expect(flagsRequests[1].distinct_id).not.toBe(first.distinct_id);
+ expect(["stored-id", "user-1", "old-device"]).not.toContain(
+ flagsRequests[1].distinct_id,
+ );
+ });
+
+ it("holds identify until consent, then identifies on a late grant", async () => {
+ const { posthog, identify } = await renderPostHog({ user: USER });
+ await vi.waitFor(() => expect(flagsRequests).toHaveLength(1));
+
+ expect(identify).not.toHaveBeenCalled();
+ expect(posthog.get_distinct_id()).not.toBe(USER.id);
+ expect(JSON.stringify(flagsRequests)).not.toContain(USER.id);
+ expect(JSON.stringify(flagsRequests)).not.toContain("[email protected]");
+
+ act(() => answerCookiebot({ statistics: true }));
+
+ expect(identify).toHaveBeenCalledOnce();
+ expect(identify).toHaveBeenCalledWith(USER.id, {
+ email: USER.email,
+ name: "Ada",
+ });
+ expect(posthog.get_distinct_id()).toBe(USER.id);
+ await vi.waitFor(() =>
+ expect(flagsRequests.map((body) => body.distinct_id)).toContain(USER.id),
+ );
+ });
+
+ it("does not identify a visitor who declines", async () => {
+ const { identify } = await renderPostHog({ user: USER });
+
+ act(() => answerCookiebot({}));
+ await vi.waitFor(() => expect(flagsRequests.length).toBeGreaterThan(0));
+
+ expect(identify).not.toHaveBeenCalled();
+ expect(JSON.stringify(flagsRequests)).not.toContain(USER.id);
+ });
+});
+
+describe("PostHog when analytics consent is granted", () => {
+ beforeEach(() => {
+ configureCookiebot();
+ });
+
+ it("opts in, persists and starts replay without a reload", async () => {
+ installCookiebot();
+ const { posthog, startSessionRecording } = await renderPostHog();
+ expect(posthog.has_opted_out_capturing()).toBe(true);
+ const pageID = posthog.get_distinct_id();
+
+ act(() => answerCookiebot({ statistics: true }));
+ posthog.capture("custom_event");
+
+ expect(posthog.has_opted_in_capturing()).toBe(true);
+ expect(startSessionRecording).toHaveBeenCalledOnce();
+ expect(posthog.config.disable_session_recording).toBe(false);
+ expect(posthog.config.persistence).toBe("localStorage+cookie");
+ expect(window.localStorage.getItem(`ph_${POSTHOG_KEY}_posthog`)).not.toBe(
+ null,
+ );
+ expect(window.localStorage.getItem("agpt_anonymous_id")).toBe(pageID);
+ expect(window.localStorage.getItem("agpt_first_landing")).not.toBeNull();
+ expect(captured).toEqual(["$pageview", "custom_event"]);
+ });
+
+ it("drops events captured before consent instead of sending them later", async () => {
+ installCookiebot();
+ const { posthog, trackTabIntro } = await renderPostHog();
+ posthog.capture("before_consent");
+ trackTabIntro("tab_intro_shown", { tab: "agents" });
+
+ act(() => answerCookiebot({ statistics: true }));
+ posthog.capture("after_consent");
+
+ expect(captured).toEqual(["$pageview", "after_consent"]);
+ });
+
+ it("starts opted in for a visitor who consented earlier", async () => {
+ installCookiebot({ statistics: true });
+ const { posthog, startSessionRecording } = await renderPostHog();
+
+ posthog.capture("custom_event");
+
+ expect(posthog.has_opted_in_capturing()).toBe(true);
+ expect(startSessionRecording).toHaveBeenCalledOnce();
+ expect(captured).toContain("custom_event");
+ });
+
+ it("opts back out and deletes its storage when the visitor withdraws", async () => {
+ installCookiebot({ statistics: true });
+ const { posthog } = await renderPostHog();
+ posthog.capture("before_withdrawal");
+ expect(captured).toContain("before_withdrawal");
+ expect(storedPostHogKeys()).toEqual(
+ expect.arrayContaining([
+ `ph_${POSTHOG_KEY}_posthog`,
+ "agpt_anonymous_id",
+ "agpt_first_landing",
+ ]),
+ );
+
+ act(() => answerCookiebot({}));
+ posthog.capture("after_withdrawal");
+
+ expect(posthog.has_opted_out_capturing()).toBe(true);
+ expect(captured).not.toContain("after_withdrawal");
+ expect(storedPostHogKeys()).toEqual([]);
+ });
+
+ it("keeps a consenting visitor opted in after logout", async () => {
+ installCookiebot({ statistics: true });
+ const { posthog, resetAnalyticsIdentity } = await renderPostHog({
+ user: USER,
+ });
+ const before = posthog.get_distinct_id();
+
+ resetAnalyticsIdentity();
+ posthog.capture("after_logout");
+
+ expect(posthog.get_distinct_id()).not.toBe(before);
+ expect(posthog.has_opted_in_capturing()).toBe(true);
+ expect(captured).toContain("after_logout");
+ expect(window.localStorage.getItem("agpt_anonymous_id")).toBe(
+ posthog.get_distinct_id(),
+ );
+ });
+
+ it("still deletes its storage when the visitor withdraws after a logout", async () => {
+ installCookiebot({ statistics: true });
+ const { posthog, resetAnalyticsIdentity } = await renderPostHog({
+ user: USER,
+ });
+ resetAnalyticsIdentity();
+ posthog.capture("after_logout");
+ expect(storedPostHogKeys()).toContain(`ph_${POSTHOG_KEY}_posthog`);
+
+ act(() => answerCookiebot({}));
+
+ expect(posthog.has_opted_out_capturing()).toBe(true);
+ expect(storedPostHogKeys()).toEqual([]);
+ });
+});
+
+describe("PostHog storage on a parent domain", () => {
+ afterEach(() => {
+ Reflect.deleteProperty(document, "cookie");
+ setPageURL("http://localhost:3000/");
+ });
+
+ it("deletes the host cookie and every parent-domain variant", async () => {
+ setPageURL("https://platform.agpt.co/");
+ configureCookiebot();
+ installCookiebot();
+ const { forgetPostHogStorageWithoutConsent } = await import(
+ "@/providers/posthog/posthog-consent"
+ );
+ document.cookie = `ph_${POSTHOG_KEY}_posthog=x; Path=/; Domain=.agpt.co`;
+ const writes = recordCookieWrites();
+
+ forgetPostHogStorageWithoutConsent(POSTHOG_KEY);
+
+ const deletions = writes.filter((value) =>
+ value.startsWith(`ph_${POSTHOG_KEY}_posthog=;`),
+ );
+ expect(deletions).toEqual(
+ expect.arrayContaining([
+ expect.not.stringContaining("Domain="),
+ expect.stringContaining("Domain=.platform.agpt.co"),
+ expect.stringContaining("Domain=.agpt.co"),
+ ]),
+ );
+ expect(cookieNames()).not.toContain(`ph_${POSTHOG_KEY}_posthog`);
+ });
+});
+
+describe("PostHog without NEXT_PUBLIC_COOKIEBOT_CBID", () => {
+ it("stays opted out even for a browser holding an old answer", async () => {
+ installCookiebot({ statistics: true });
+ const { posthog } = await renderPostHog();
+
+ posthog.capture("custom_event");
+
+ expect(posthog.has_opted_out_capturing()).toBe(true);
+ expect(captured).toEqual([]);
+ expect(storedPostHogKeys()).toEqual([]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/useReportAttribution.test.tsx b/autogpt_platform/frontend/src/services/analytics/__tests__/useReportAttribution.test.tsx
index b941be701d..dd59e37bd8 100644
--- a/autogpt_platform/frontend/src/services/analytics/__tests__/useReportAttribution.test.tsx
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/useReportAttribution.test.tsx
@@ -1,5 +1,9 @@
import { server } from "@/mocks/mock-server";
-import { consent } from "@/services/consent/cookies";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { http, HttpResponse } from "msw";
@@ -44,13 +48,8 @@ function captureReports(status = 200) {
}
function setAnalyticsConsent(analytics: boolean): void {
- consent.save({
- hasConsented: true,
- timestamp: Date.now(),
- analytics,
- monitoring: false,
- advertising: false,
- });
+ configureCookiebot();
+ installCookiebot({ statistics: analytics });
}
beforeEach(() => {
@@ -61,6 +60,8 @@ beforeEach(() => {
});
afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
vi.restoreAllMocks();
});
diff --git a/autogpt_platform/frontend/src/services/analytics/anonymous-id.ts b/autogpt_platform/frontend/src/services/analytics/anonymous-id.ts
index bc3188f845..edb50205e1 100644
--- a/autogpt_platform/frontend/src/services/analytics/anonymous-id.ts
+++ b/autogpt_platform/frontend/src/services/analytics/anonymous-id.ts
@@ -14,10 +14,16 @@
* - The backend stores it on the user at signup (`UserAttribution`), which is
* the join key for everything else.
*
- * An existing PostHog device id is adopted rather than replaced, so returning
+ * It only outlives the page with analytics consent. Without it the id is
+ * minted fresh for each page load and kept in memory, nothing an earlier
+ * visit stored is read, and the first landing stays in memory too. Granting
+ * persists both without a reload; withdrawing deletes them. With consent an
+ * existing PostHog device id is adopted rather than replaced, so returning
* visitors keep their history.
*/
+import { hasConsentFor, subscribeToConsent } from "@/services/consent/consent";
+
const ANONYMOUS_ID_KEY = "agpt_anonymous_id";
const FIRST_LANDING_KEY = "agpt_first_landing";
@@ -43,11 +49,16 @@ export interface FirstLanding {
}
let memoryID: string | null = null;
+let pageLanding: FirstLanding | null = null;
export function getAnonymousID(): string | null {
if (typeof window === "undefined") return null;
if (memoryID) return memoryID;
+ if (!hasConsentFor("analytics")) {
+ memoryID = newID();
+ return memoryID;
+ }
const stored = readStorage(ANONYMOUS_ID_KEY);
const id = stored ?? readPostHogDeviceID() ?? newID();
if (!stored) writeStorage(ANONYMOUS_ID_KEY, id);
@@ -56,61 +67,90 @@ export function getAnonymousID(): string | null {
}
/**
- * Remember the first page this browser landed on, once. Captured under
- * legitimate interest rather than analytics consent — to be revisited after GTM.
+ * Remember the page this visit landed on. It is stored as the browser's first
+ * landing only with analytics consent (once, on the first visit that has it);
+ * otherwise it stays in memory for this page load.
*/
export function captureFirstLanding(): void {
if (typeof window === "undefined") return;
- if (readStorage(FIRST_LANDING_KEY)) return;
-
- const params = new URLSearchParams(window.location.search);
- const landing: FirstLanding = {
- path: redactPath(window.location.pathname, window.location.search),
- referrer: redactReferrer(document.referrer),
- utm_source: params.get("utm_source"),
- utm_medium: params.get("utm_medium"),
- utm_campaign: params.get("utm_campaign"),
- at: new Date().toISOString(),
- };
- writeStorage(FIRST_LANDING_KEY, JSON.stringify(landing));
+ pageLanding ??= describeLanding();
+ if (hasConsentFor("analytics")) persistFirstLanding();
}
export function readFirstLanding(): FirstLanding | null {
+ if (typeof window === "undefined") return null;
+ if (!hasConsentFor("analytics")) return pageLanding;
const raw = readStorage(FIRST_LANDING_KEY);
- if (!raw) return null;
+ if (!raw) return pageLanding;
try {
return JSON.parse(raw) as FirstLanding;
} catch {
- return null;
+ return pageLanding;
}
}
/**
- * Rotate the browser identity and clear its first landing. Persist the new
- * identity immediately so old PostHog storage cannot restore the last visitor.
+ * Keep the stored identity in step with analytics consent: persist this page's
+ * id and landing on a grant, delete them otherwise (also clearing whatever a
+ * visit with consent left behind). Returns the unsubscribe.
*/
-export function resetAnonymousID(nextID?: string): void {
- if (typeof window === "undefined") {
- memoryID = null;
+export function followAnalyticsConsentForIdentity(): () => void {
+ if (typeof window === "undefined") return () => {};
+ syncStoredIdentity();
+ return subscribeToConsent(syncStoredIdentity);
+}
+
+function syncStoredIdentity(): void {
+ if (!hasConsentFor("analytics")) {
+ forgetStoredIdentity();
return;
}
- memoryID = nextID || newID();
+ const id = getAnonymousID();
+ if (id && readStorage(ANONYMOUS_ID_KEY) !== id) {
+ writeStorage(ANONYMOUS_ID_KEY, id);
+ }
+ persistFirstLanding();
+}
+
+function persistFirstLanding(): void {
+ if (!pageLanding || readStorage(FIRST_LANDING_KEY)) return;
+ writeStorage(FIRST_LANDING_KEY, JSON.stringify(pageLanding));
+}
+
+function forgetStoredIdentity(): void {
try {
window.localStorage.removeItem(ANONYMOUS_ID_KEY);
window.localStorage.removeItem(FIRST_LANDING_KEY);
} catch {
// Storage blocked: nothing persisted to clear.
}
- writeStorage(ANONYMOUS_ID_KEY, memoryID);
+}
+
+/**
+ * Rotate the browser identity and clear its first landing. With consent the
+ * new identity is persisted immediately so old PostHog storage cannot restore
+ * the last visitor.
+ */
+export function resetAnonymousID(nextID?: string): void {
+ if (typeof window === "undefined") {
+ memoryID = null;
+ return;
+ }
+ memoryID = nextID || newID();
+ pageLanding = null;
+ forgetStoredIdentity();
+ if (hasConsentFor("analytics")) writeStorage(ANONYMOUS_ID_KEY, memoryID);
}
export function resetAnonymousIDForTests(): void {
memoryID = null;
+ pageLanding = null;
}
-/** PostHog's own device id, when its persistence exists in this browser. */
+/** PostHog's own device id, when it may be read and exists in this browser. */
export function getPostHogDeviceID(): string | null {
if (typeof window === "undefined") return null;
+ if (!hasConsentFor("analytics")) return null;
return readPostHogDeviceID();
}
@@ -128,6 +168,18 @@ function readPostHogDeviceID(): string | null {
}
}
+function describeLanding(): FirstLanding {
+ const params = new URLSearchParams(window.location.search);
+ return {
+ path: redactPath(window.location.pathname, window.location.search),
+ referrer: redactReferrer(document.referrer),
+ utm_source: params.get("utm_source"),
+ utm_medium: params.get("utm_medium"),
+ utm_campaign: params.get("utm_campaign"),
+ at: new Date().toISOString(),
+ };
+}
+
function redactPath(pathname: string, search: string): string {
const prefix = REDACTED_PREFIXES.find(
(candidate) =>
diff --git a/autogpt_platform/frontend/src/services/analytics/consent-mode.test.ts b/autogpt_platform/frontend/src/services/analytics/consent-mode.test.ts
index 9b7c52470d..b71f7a9992 100644
--- a/autogpt_platform/frontend/src/services/analytics/consent-mode.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/consent-mode.test.ts
@@ -1,65 +1,193 @@
-import { describe, expect, it } from "vitest";
-import type { ConsentPreferences } from "@/services/consent/cookies";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
- buildConsentModeScript,
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import {
+ buildConsentDefaultsScript,
CONSENT_DENIED_BY_DEFAULT_REGIONS,
+ followConsentForGoogleTag,
} from "./consent-mode";
-function preferences(
- overrides: Partial<ConsentPreferences> = {},
-): ConsentPreferences {
- return {
- hasConsented: true,
- timestamp: 1,
- analytics: false,
- monitoring: false,
- advertising: false,
- ...overrides,
- };
+type DataLayerWindow = Window & { dataLayer?: IArguments[] };
+
+function dataLayerEntries(): unknown[][] {
+ return ((window as DataLayerWindow).dataLayer ?? []).map((entry) =>
+ Array.from(entry),
+ );
}
-describe("buildConsentModeScript", () => {
- it("grants by default, denies in the EEA, UK and Switzerland, and passes click IDs through URLs", () => {
- const script = buildConsentModeScript(null);
+function consentUpdates() {
+ return dataLayerEntries().filter(
+ ([command, action]) => command === "consent" && action === "update",
+ );
+}
- 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)}});`,
- );
+function update(analytics: boolean, advertising: boolean) {
+ const ads = advertising ? "granted" : "denied";
+ return [
+ "consent",
+ "update",
+ {
+ analytics_storage: analytics ? "granted" : "denied",
+ ad_storage: ads,
+ ad_user_data: ads,
+ ad_personalization: ads,
+ },
+ ];
+}
+
+function runDefaultsScript(): unknown[][] {
+ new Function(buildConsentDefaultsScript())();
+ return ((window as DataLayerWindow).dataLayer ?? []).map((entry) =>
+ Array.from(entry),
+ );
+}
+
+describe("buildConsentDefaultsScript", () => {
+ afterEach(() => {
+ delete (window as DataLayerWindow).dataLayer;
+ delete window.gtag;
+ });
+
+ it("grants by default, denies in the EEA, UK and Switzerland, and passes click IDs through URLs", () => {
+ expect(runDefaultsScript()).toEqual([
+ [
+ "consent",
+ "default",
+ {
+ ad_storage: "granted",
+ ad_user_data: "granted",
+ ad_personalization: "granted",
+ analytics_storage: "granted",
+ },
+ ],
+ [
+ "consent",
+ "default",
+ {
+ ad_storage: "denied",
+ ad_user_data: "denied",
+ ad_personalization: "denied",
+ analytics_storage: "denied",
+ region: CONSENT_DENIED_BY_DEFAULT_REGIONS,
+ wait_for_update: 500,
+ },
+ ],
+ ["set", "url_passthrough", true],
+ ]);
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 }),
- );
+ it("only sets defaults; updates come from the visitor's answer", () => {
+ expect(buildConsentDefaultsScript()).not.toContain("'update'");
+ });
- expect(script).not.toContain("'update'");
+ it("queues real arguments objects without defining window.gtag", () => {
+ runDefaultsScript();
+
+ const [first] = (window as DataLayerWindow).dataLayer ?? [];
+ expect(Object.prototype.toString.call(first)).toBe("[object Arguments]");
+ expect(window.gtag).toBeUndefined();
});
- it("updates every signal from the stored answer", () => {
- const script = buildConsentModeScript(
- preferences({ analytics: true, advertising: false }),
- );
+ it("keeps entries already in the dataLayer", () => {
+ (window as DataLayerWindow).dataLayer = [];
+ const existing = (window as DataLayerWindow).dataLayer;
- expect(script).toContain(
- `gtag('consent','update',{"analytics_storage":"granted","ad_storage":"denied","ad_user_data":"denied","ad_personalization":"denied"});`,
- );
+ runDefaultsScript();
+
+ expect((window as DataLayerWindow).dataLayer).toBe(existing);
});
+});
- it("grants the advertising signals once advertising is accepted", () => {
- const script = buildConsentModeScript(
- preferences({ analytics: false, advertising: true }),
- );
+describe("followConsentForGoogleTag", () => {
+ afterEach(() => {
+ delete (window as DataLayerWindow).dataLayer;
+ removeCookiebot();
+ vi.unstubAllEnvs();
+ });
- expect(script).toContain(
- `gtag('consent','update',{"analytics_storage":"denied","ad_storage":"granted","ad_user_data":"granted","ad_personalization":"granted"});`,
- );
+ it("sends a stored answer straight away, as real arguments objects", () => {
+ configureCookiebot();
+ installCookiebot({ statistics: true });
+
+ const unfollow = followConsentForGoogleTag();
+
+ expect(consentUpdates()).toEqual([update(true, false)]);
+ const [entry] = (window as DataLayerWindow).dataLayer ?? [];
+ expect(Object.prototype.toString.call(entry)).toBe("[object Arguments]");
+ unfollow();
+ });
+
+ it("leaves the region defaults alone until the visitor answers", () => {
+ configureCookiebot();
+ installCookiebot();
+
+ const unfollow = followConsentForGoogleTag();
+ expect(consentUpdates()).toEqual([]);
+
+ answerCookiebot({ statistics: true, marketing: true });
+ expect(consentUpdates()).toEqual([update(true, true)]);
+ unfollow();
+ });
+
+ it("sends a denial, and every later change, once per change", () => {
+ configureCookiebot();
+ installCookiebot({ statistics: true, marketing: true });
+ const unfollow = followConsentForGoogleTag();
+
+ answerCookiebot({});
+ window.dispatchEvent(new Event("CookiebotOnLoad"));
+ answerCookiebot({ marketing: true });
+
+ expect(consentUpdates()).toEqual([
+ update(true, true),
+ update(false, false),
+ update(false, true),
+ ]);
+ unfollow();
+ });
+
+ it("denies an answer Cookiebot has since withdrawn", () => {
+ configureCookiebot();
+ installCookiebot({ statistics: true });
+ const unfollow = followConsentForGoogleTag();
+
+ const cookiebot = window.Cookiebot;
+ if (!cookiebot) throw new Error("Cookiebot missing");
+ cookiebot.hasResponse = false;
+ window.dispatchEvent(new Event("CookiebotOnLoad"));
+
+ expect(consentUpdates()).toEqual([
+ update(true, false),
+ update(false, false),
+ ]);
+ unfollow();
+ });
+
+ it("stops after unsubscribe", () => {
+ configureCookiebot();
+ installCookiebot();
+ followConsentForGoogleTag()();
+
+ answerCookiebot({ statistics: true });
+
+ expect(consentUpdates()).toEqual([]);
+ });
+
+ it("sends nothing without a Cookiebot domain group", () => {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+ installCookiebot({ statistics: true });
+
+ const unfollow = followConsentForGoogleTag();
+ answerCookiebot({ statistics: true, marketing: true });
+
+ expect(consentUpdates()).toEqual([]);
+ unfollow();
});
});
diff --git a/autogpt_platform/frontend/src/services/analytics/consent-mode.ts b/autogpt_platform/frontend/src/services/analytics/consent-mode.ts
index ca9eeae6a8..b0376ff9cc 100644
--- a/autogpt_platform/frontend/src/services/analytics/consent-mode.ts
+++ b/autogpt_platform/frontend/src/services/analytics/consent-mode.ts
@@ -1,4 +1,11 @@
-import type { ConsentPreferences } from "@/services/consent/cookies";
+import {
+ getConsentAnswer,
+ isConsentManagerConfigured,
+ NO_CONSENT,
+ subscribeToConsent,
+ type ConsentState,
+} from "@/services/consent/consent";
+import { DATA_LAYER_NAME } from "./gtag";
const EU_MEMBER_STATES = [
"AT",
@@ -43,18 +50,19 @@ export const CONSENT_DENIED_BY_DEFAULT_REGIONS = [
"CH",
];
-type Signal = "granted" | "denied";
-
-function signal(granted: boolean): Signal {
- return granted ? "granted" : "denied";
-}
+// How long the tag holds its first hit for the banner's stored answer, so a
+// returning visitor's first page view already carries it.
+const WAIT_FOR_UPDATE_MS = 500;
-// 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 = [
+// Consent Mode v2 defaults, rendered as a beforeInteractive script ahead of
+// Cookiebot and the Google tag. The updates come from followConsentForGoogleTag
+// below. The shim stays local so it doesn't define window.gtag: that global is
+// how the rest of the app knows the tag itself loaded.
+export function buildConsentDefaultsScript(): string {
+ return [
+ `window['${DATA_LAYER_NAME}'] = window['${DATA_LAYER_NAME}'] || [];`,
+ `(function(){`,
+ `function gtag(){window['${DATA_LAYER_NAME}'].push(arguments);}`,
`gtag('consent','default',${JSON.stringify({
ad_storage: "granted",
ad_user_data: "granted",
@@ -67,22 +75,64 @@ export function buildConsentModeScript(
ad_personalization: "denied",
analytics_storage: "denied",
region: CONSENT_DENIED_BY_DEFAULT_REGIONS,
+ wait_for_update: WAIT_FOR_UPDATE_MS,
})});`,
// Carries the ad click ID across pages in the URL while cookies are denied.
`gtag('set','url_passthrough',true);`,
- ];
+ `})();`,
+ ].join("\n");
+}
+
+type Signal = "granted" | "denied";
+
+function signal(granted: boolean): Signal {
+ return granted ? "granted" : "denied";
+}
+
+export function buildConsentUpdate(consent: ConsentState) {
+ const ads = signal(consent.advertising);
+ return {
+ analytics_storage: signal(consent.analytics),
+ ad_storage: ads,
+ ad_user_data: ads,
+ ad_personalization: ads,
+ };
+}
- 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,
- })});`,
- );
+/**
+ * Sends the visitor's answer to the Google tag as a Consent Mode update, now
+ * and whenever it changes. Cookiebot's own Consent Mode integration sends the
+ * same signals; this keeps a denial reaching the tag even if that integration
+ * is switched off in the Cookiebot admin. Until there is an answer the region
+ * defaults stand; an answer Cookiebot later withdraws is sent as a denial.
+ * Returns the unsubscribe.
+ */
+export function followConsentForGoogleTag(): () => void {
+ if (typeof window === "undefined" || !isConsentManagerConfigured()) {
+ return () => {};
}
+ let sent: string | null = null;
+
+ function sync() {
+ const answer = getConsentAnswer() ?? (sent ? NO_CONSENT : null);
+ if (!answer) return;
+ const update = buildConsentUpdate(answer);
+ const key = JSON.stringify(update);
+ if (key === sent) return;
+ sent = key;
+ queueGtagCommand("consent", "update", update);
+ }
+
+ sync();
+ return subscribeToConsent(sync);
+}
- return lines.join("\n");
+// Queued straight onto the dataLayer so the update lands whether or not the
+// tag has loaded yet. gtag.js only runs entries that are real `arguments`
+// objects, hence the rest parameter goes unused.
+function queueGtagCommand(..._command: unknown[]) {
+ const scope = window as unknown as Record<string, unknown[] | undefined>;
+ const dataLayer = (scope[DATA_LAYER_NAME] ??= []);
+ // eslint-disable-next-line prefer-rest-params
+ dataLayer.push(arguments);
}
diff --git a/autogpt_platform/frontend/src/services/analytics/datafast-server.test.ts b/autogpt_platform/frontend/src/services/analytics/datafast-server.test.ts
index 40bc25e774..233d187cdc 100644
--- a/autogpt_platform/frontend/src/services/analytics/datafast-server.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/datafast-server.test.ts
@@ -1,5 +1,5 @@
import * as Sentry from "@sentry/nextjs";
-import { cookies } from "next/headers";
+import { cookies, headers } from "next/headers";
import { after } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
@@ -8,11 +8,37 @@ import {
wasAccountCreated,
} from "./datafast-server";
-vi.mock("next/headers", () => ({ cookies: vi.fn() }));
+vi.mock("next/headers", () => ({ cookies: vi.fn(), headers: vi.fn() }));
vi.mock("next/server", () => ({ after: vi.fn() }));
vi.mock("@sentry/nextjs", () => ({ captureException: vi.fn() }));
const VISITOR_ID = "a3ab2331-989f-4cfa-91c6-2461c9e3c6bd";
+const STATISTICS_GRANTED =
+ "{stamp:%27abc==%27%2Cnecessary:true%2Cpreferences:false%2Cstatistics:true%2Cmarketing:false%2Cmethod:%27explicit%27%2Cver:1%2Cutc:1724770548958%2Cregion:%27de%27}";
+const STATISTICS_DENIED = STATISTICS_GRANTED.replace(
+ "statistics:true",
+ "statistics:false",
+);
+
+// Mirrors a request: cookies() keeps the last of two same-named cookies,
+// while the raw Cookie header carries every copy.
+function mockRequestCookies(entries: Array<[name: string, value: string]>) {
+ vi.mocked(cookies).mockResolvedValue({
+ get: vi.fn((name: string) => {
+ const entry = entries.findLast(([key]) => key === name);
+ return entry ? { value: entry[1] } : undefined;
+ }),
+ } as never);
+ vi.mocked(headers).mockResolvedValue(
+ new Headers(
+ entries.length
+ ? {
+ cookie: entries.map(([key, value]) => `${key}=${value}`).join("; "),
+ }
+ : {},
+ ) as never,
+ );
+}
describe("DataFast server-side account creation tracking", () => {
beforeEach(() => {
@@ -20,13 +46,11 @@ describe("DataFast server-side account creation tracking", () => {
resetConfigErrorReportingForTests();
vi.stubEnv("DATAFAST_API_KEY", "df_test");
vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "LOCAL");
- vi.mocked(cookies).mockResolvedValue({
- get: vi.fn((name: string) => {
- if (name === "agpt_analytics_consent") return { value: "granted" };
- if (name === "datafast_visitor_id") return { value: VISITOR_ID };
- return undefined;
- }),
- } as never);
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "test-cbid");
+ mockRequestCookies([
+ ["CookieConsent", STATISTICS_GRANTED],
+ ["datafast_visitor_id", VISITOR_ID],
+ ]);
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(new Response(null, { status: 200 })),
@@ -66,9 +90,7 @@ describe("DataFast server-side account creation tracking", () => {
});
it("does not schedule tracking without analytics consent", async () => {
- vi.mocked(cookies).mockResolvedValue({
- get: vi.fn(() => undefined),
- } as never);
+ mockRequestCookies([]);
await scheduleAccountCreatedGoal("google");
@@ -76,12 +98,44 @@ describe("DataFast server-side account creation tracking", () => {
expect(fetch).not.toHaveBeenCalled();
});
+ it("does not schedule tracking when the visitor declined statistics", async () => {
+ mockRequestCookies([
+ ["CookieConsent", STATISTICS_DENIED],
+ ["datafast_visitor_id", VISITOR_ID],
+ ]);
+
+ await scheduleAccountCreatedGoal("email");
+
+ expect(after).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["granting copy first", [STATISTICS_GRANTED, STATISTICS_DENIED]],
+ ["granting copy last", [STATISTICS_DENIED, STATISTICS_GRANTED]],
+ ])(
+ "does not schedule tracking when duplicate consent cookies disagree (%s)",
+ async (_, answers) => {
+ mockRequestCookies([
+ ...answers.map((value): [string, string] => ["CookieConsent", value]),
+ ["datafast_visitor_id", VISITOR_ID],
+ ]);
+
+ await scheduleAccountCreatedGoal("email");
+
+ expect(after).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not schedule tracking without a consent banner, whatever the cookie says", async () => {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+
+ await scheduleAccountCreatedGoal("email");
+
+ expect(after).not.toHaveBeenCalled();
+ });
+
it("does not schedule tracking without a valid visitor ID", async () => {
- vi.mocked(cookies).mockResolvedValue({
- get: vi.fn((name: string) =>
- name === "agpt_analytics_consent" ? { value: "granted" } : undefined,
- ),
- } as never);
+ mockRequestCookies([["CookieConsent", STATISTICS_GRANTED]]);
await scheduleAccountCreatedGoal("google");
@@ -119,6 +173,7 @@ describe("DataFast server-side account creation tracking", () => {
});
it("isolates request-context failures from account creation", async () => {
+ vi.mocked(headers).mockRejectedValue(new Error("request context closed"));
vi.mocked(cookies).mockRejectedValue(new Error("request context closed"));
await expect(scheduleAccountCreatedGoal("email")).resolves.toBeUndefined();
diff --git a/autogpt_platform/frontend/src/services/analytics/datafast-server.ts b/autogpt_platform/frontend/src/services/analytics/datafast-server.ts
index 8eda204b51..777dd20257 100644
--- a/autogpt_platform/frontend/src/services/analytics/datafast-server.ts
+++ b/autogpt_platform/frontend/src/services/analytics/datafast-server.ts
@@ -1,10 +1,7 @@
import * as Sentry from "@sentry/nextjs";
import { cookies } from "next/headers";
import { after } from "next/server";
-import {
- ANALYTICS_CONSENT_COOKIE,
- ANALYTICS_CONSENT_GRANTED,
-} from "@/services/consent/constants";
+import { requestHasConsentFor } from "@/services/consent/consent-server";
import { environment } from "@/services/environment";
const DATAFAST_GOALS_URL = "https://datafa.st/api/v1/goals";
@@ -83,11 +80,8 @@ function reportTrackingError(error: unknown) {
async function getGoalContext(
method: SignupMethod,
): Promise<GoalContext | null> {
+ if (!(await requestHasConsentFor("analytics"))) return null;
const cookieStore = await cookies();
- const hasConsent =
- cookieStore.get(ANALYTICS_CONSENT_COOKIE)?.value ===
- ANALYTICS_CONSENT_GRANTED;
- if (!hasConsent) return null;
const visitorID = cookieStore.get(DATAFAST_VISITOR_COOKIE)?.value;
if (!visitorID || !VISITOR_ID_PATTERN.test(visitorID)) return null;
diff --git a/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts b/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts
index bb4db0450f..d51423986b 100644
--- a/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/google-ads.test.ts
@@ -3,7 +3,12 @@ import {
installGtagShim,
removeGtagShim,
} from "@/tests/integrations/gtag-shim";
-import { consent } from "@/services/consent/cookies";
+import {
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
import {
getSubscriptionValue,
parseConversionLabels,
@@ -11,14 +16,8 @@ import {
trackAdsPageView,
} from "./google-ads";
-function answerBanner(advertising: boolean) {
- consent.save({
- hasConsented: true,
- timestamp: 1,
- analytics: true,
- monitoring: true,
- advertising,
- });
+function answerBanner(marketing: boolean) {
+ answerCookiebot({ statistics: true, marketing });
}
let pushed: unknown[][] = [];
@@ -31,13 +30,15 @@ describe("trackAdsConversion", () => {
"NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",
"sign_up=SIGNUP,subscribe=SUB",
);
+ configureCookiebot();
+ installCookiebot();
answerBanner(true);
});
afterEach(() => {
vi.unstubAllEnvs();
removeGtagShim();
- consent.clear();
+ removeCookiebot();
});
it("sends the conversion to the action label with value, dedup id and user data", () => {
@@ -66,7 +67,8 @@ describe("trackAdsConversion", () => {
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();
+ removeCookiebot();
+ installCookiebot();
trackAdsConversion("subscribe", {
value: 50,
@@ -96,6 +98,19 @@ describe("trackAdsConversion", () => {
]);
});
+ it("withholds the identifiers when no banner is configured", () => {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+
+ 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");
diff --git a/autogpt_platform/frontend/src/services/analytics/google-ads.ts b/autogpt_platform/frontend/src/services/analytics/google-ads.ts
index d3576ef9fd..e550fea701 100644
--- a/autogpt_platform/frontend/src/services/analytics/google-ads.ts
+++ b/autogpt_platform/frontend/src/services/analytics/google-ads.ts
@@ -2,7 +2,7 @@ import {
PLANS,
YEARLY_PRICE_FACTOR,
} from "@/components/molecules/PlanCard/plans";
-import { consent } from "@/services/consent/cookies";
+import { hasConsentFor } from "@/services/consent/consent";
import { environment } from "@/services/environment";
import { gtag } from "./gtag";
@@ -54,13 +54,13 @@ export function trackAdsConversion(
// 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.
+// Google resolves it by IP. 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. Cookiebot's own answer (including "no consent required here") is
+// what counts.
function mayReportIdentifiers(): boolean {
- const preferences = consent.load();
- return preferences.hasConsented && preferences.advertising;
+ return hasConsentFor("advertising");
}
// The labels come from a build-time env var; parse once per distinct value so
diff --git a/autogpt_platform/frontend/src/services/analytics/index.test.ts b/autogpt_platform/frontend/src/services/analytics/index.test.ts
index cf5d5fcdeb..93428d8968 100644
--- a/autogpt_platform/frontend/src/services/analytics/index.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/index.test.ts
@@ -1,13 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { consent } from "@/services/consent/cookies";
+import { hasConsentFor } from "@/services/consent/consent";
+import { configureCookiebot } from "@/tests/integrations/cookiebot";
import {
installGtagShim,
removeGtagShim,
} from "@/tests/integrations/gtag-shim";
import { analytics, flushDatafastQueue } from "./index";
-vi.mock("@/services/consent/cookies", () => ({
- consent: { hasConsentFor: vi.fn() },
+vi.mock("@/services/consent/consent", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/services/consent/consent")>()),
+ hasConsentFor: vi.fn(),
}));
function drainQueue() {
@@ -19,12 +21,13 @@ function drainQueue() {
describe("sendDatafastEvent", () => {
beforeEach(() => {
drainQueue();
- vi.mocked(consent.hasConsentFor).mockReturnValue(true);
+ vi.mocked(hasConsentFor).mockReturnValue(true);
window.history.pushState({}, "", "/");
});
afterEach(() => {
drainQueue();
+ vi.unstubAllEnvs();
});
it("sends immediately when the DataFast script has loaded", () => {
@@ -93,7 +96,7 @@ describe("sendDatafastEvent", () => {
});
it("does not queue pre-consent events outside the tour", () => {
- vi.mocked(consent.hasConsentFor).mockReturnValue(false);
+ vi.mocked(hasConsentFor).mockReturnValue(false);
analytics.sendDatafastEvent("run_agent", { agent_name: "x" });
@@ -104,8 +107,23 @@ describe("sendDatafastEvent", () => {
expect(datafast).not.toHaveBeenCalled();
});
+ it("does not send without consent once the script has loaded", () => {
+ // DataFast loaded under the tour exemption stays on window after the
+ // visitor navigates away from /tour.
+ vi.mocked(hasConsentFor).mockReturnValue(false);
+ configureCookiebot();
+ window.history.pushState({}, "", "/marketplace");
+ const datafast = vi.fn();
+ window.datafast = datafast;
+
+ analytics.sendDatafastEvent("run_agent", { agent_name: "x" });
+
+ expect(datafast).not.toHaveBeenCalled();
+ });
+
it("queues pre-consent events on the consent-exempt tour pages", () => {
- vi.mocked(consent.hasConsentFor).mockReturnValue(false);
+ vi.mocked(hasConsentFor).mockReturnValue(false);
+ configureCookiebot();
window.history.pushState({}, "", "/tour/chat");
analytics.sendDatafastEvent("tour_start", {});
@@ -117,8 +135,34 @@ describe("sendDatafastEvent", () => {
expect(datafast).toHaveBeenCalledWith("tour_start", {});
});
+ it("sends tour events without consent once the script has loaded", () => {
+ vi.mocked(hasConsentFor).mockReturnValue(false);
+ configureCookiebot();
+ window.history.pushState({}, "", "/tour");
+ const datafast = vi.fn();
+ window.datafast = datafast;
+
+ analytics.sendDatafastEvent("tour_start", {});
+
+ expect(datafast).toHaveBeenCalledWith("tour_start", {});
+ });
+
+ it("does not exempt the tour without a consent banner", () => {
+ vi.mocked(hasConsentFor).mockReturnValue(false);
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");
+ window.history.pushState({}, "", "/tour/chat");
+
+ analytics.sendDatafastEvent("tour_start", {});
+
+ const datafast = vi.fn();
+ window.datafast = datafast;
+ flushDatafastQueue();
+
+ expect(datafast).not.toHaveBeenCalled();
+ });
+
it("does not treat /tourism as a consent-exempt tour page", () => {
- vi.mocked(consent.hasConsentFor).mockReturnValue(false);
+ vi.mocked(hasConsentFor).mockReturnValue(false);
window.history.pushState({}, "", "/tourism");
analytics.sendDatafastEvent("tour_start", {});
diff --git a/autogpt_platform/frontend/src/services/analytics/index.tsx b/autogpt_platform/frontend/src/services/analytics/index.tsx
index 18d536a07e..0dca9709da 100644
--- a/autogpt_platform/frontend/src/services/analytics/index.tsx
+++ b/autogpt_platform/frontend/src/services/analytics/index.tsx
@@ -6,12 +6,15 @@
"use client";
import type { GAParams } from "@/types/google";
-import { consent, type ConsentPreferences } from "@/services/consent/cookies";
+import {
+ hasConsentFor,
+ isConsentManagerConfigured,
+} from "@/services/consent/consent";
import Script from "next/script";
import { environment } from "../environment";
-import { buildConsentModeScript } from "./consent-mode";
+import { GoogleConsentModeSync } from "./GoogleConsentModeSync";
import { DATA_LAYER_NAME, gtag } from "./gtag";
-import { isTourPath } from "./loading-policy";
+import { DATAFAST_SCRIPT_SRC, isDataFastConsentExempt } from "./loading-policy";
import { useSetupAnalytics } from "./useSetupAnalytics";
type DatafastEvent = [name: string, metadata: Record<string, unknown>];
@@ -31,7 +34,7 @@ export function SetupAnalytics(props: SetupProps) {
const { ga, host } = props;
const { gaId, debugMode, nonce } = ga;
const adsID = environment.getGoogleAdsID();
- const { preferences, googleTagEnabled, dataFastEnabled } =
+ const { googleTagEnabled, dataFastEnabled, dataFastWithoutConsent } =
useSetupAnalytics(host);
return (
@@ -39,6 +42,7 @@ export function SetupAnalytics(props: SetupProps) {
{/* Google tag: GA4 + Google Ads */}
{googleTagEnabled ? (
<>
+ <GoogleConsentModeSync />
<Script
id="_custom-ga-init"
strategy="afterInteractive"
@@ -47,7 +51,6 @@ export function SetupAnalytics(props: SetupProps) {
GAID: gaId,
adsID,
debugMode,
- preferences,
}),
}}
nonce={nonce}
@@ -67,7 +70,8 @@ export function SetupAnalytics(props: SetupProps) {
strategy="afterInteractive"
data-website-id="dfid_g5wtBIiHUwSkWKcGz80lu"
data-domain="agpt.co"
- src="https://datafa.st/js/script.js"
+ src={DATAFAST_SCRIPT_SRC}
+ data-consent-exempt={dataFastWithoutConsent ? "true" : undefined}
onLoad={flushDatafastQueue}
/>
) : null}
@@ -79,14 +83,14 @@ interface InitScriptArgs {
GAID: string;
adsID: string;
debugMode?: boolean;
- preferences: ConsentPreferences | null;
}
+// The root layout queued the Consent Mode defaults before anything else, and
+// GoogleConsentModeSync (with Cookiebot's own integration) sends the answer.
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
@@ -94,7 +98,6 @@ function buildGoogleTagInitScript({
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
@@ -123,6 +126,15 @@ let datafastQueueOverflowWarned = false;
function sendDatafastEvent(name: string, metadata: Record<string, unknown>) {
if (typeof window === "undefined") return;
+ // Checked on every event, not only before the script loads: a script the
+ // tour loaded stays on window after navigating away from it, and must not
+ // carry events the visitor never agreed to. Pre-consent events must not
+ // queue either — they would be replayed once consent is granted.
+ const consentExempt = isDataFastConsentExempt(
+ window.location.pathname,
+ isConsentManagerConfigured(),
+ );
+ if (!consentExempt && !hasConsentFor("analytics")) return;
if (window.datafast) {
// Self-heal if the Script's onLoad never fired (e.g. consent toggle
// remounted it after the script had already loaded): replay the backlog
@@ -133,11 +145,7 @@ function sendDatafastEvent(name: string, metadata: Record<string, unknown>) {
}
// The script loads afterInteractive, so mount-time events (tour_start,
// tour_scenario_start) fire before window.datafast exists. Queue them and
- // flush from the Script's onLoad instead of dropping them. Pre-consent
- // events must not queue — they would be replayed once consent is granted.
- // /tour is exempt: it loads DataFast without consent by design.
- const consentExempt = isTourPath(window.location.pathname);
- if (!consentExempt && !consent.hasConsentFor("analytics")) return;
+ // flush from the Script's onLoad instead of dropping them.
if (datafastQueue.length >= MAX_QUEUED_DATAFAST_EVENTS) {
if (!datafastQueueOverflowWarned) {
datafastQueueOverflowWarned = true;
diff --git a/autogpt_platform/frontend/src/services/analytics/loading-policy.test.ts b/autogpt_platform/frontend/src/services/analytics/loading-policy.test.ts
index ee1623d757..07b4def351 100644
--- a/autogpt_platform/frontend/src/services/analytics/loading-policy.test.ts
+++ b/autogpt_platform/frontend/src/services/analytics/loading-policy.test.ts
@@ -1,58 +1,51 @@
import { describe, expect, it } from "vitest";
-import type { ConsentPreferences } from "@/services/consent/cookies";
+import { NO_CONSENT, type ConsentState } from "@/services/consent/consent";
import { resolveAnalyticsLoading } from "./loading-policy";
-function preferences(
- overrides: Partial<ConsentPreferences> = {},
-): ConsentPreferences {
- return {
- hasConsented: true,
- timestamp: 1,
- analytics: false,
- monitoring: false,
- advertising: false,
- ...overrides,
- };
+function consent(overrides: Partial<ConsentState> = {}): ConsentState {
+ return { ...NO_CONSENT, ...overrides };
}
const production = {
host: "platform.agpt.co",
pathname: "/marketplace",
isLocal: false,
+ isConsentManaged: true,
};
describe("resolveAnalyticsLoading", () => {
- it("loads the Google tag on production once preferences are known, even unanswered", () => {
+ it("loads the Google tag on production before the visitor answers", () => {
const result = resolveAnalyticsLoading({
...production,
- preferences: preferences({ hasConsented: false }),
+ consent: consent(),
});
expect(result.googleTag).toBe(true);
expect(result.dataFast).toBe(false);
});
- it("waits for the stored preferences before loading anything", () => {
+ it("keeps the Google tag off production when no banner is configured", () => {
const result = resolveAnalyticsLoading({
...production,
- preferences: null,
+ isConsentManaged: false,
+ consent: consent(),
});
- expect(result).toEqual({ googleTag: false, dataFast: false });
+ expect(result.googleTag).toBe(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 }),
+ consent: consent({ 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 });
+ const consented = consent({ analytics: true, advertising: true });
for (const host of [
"platform.agpt.co.example.com",
@@ -63,7 +56,7 @@ describe("resolveAnalyticsLoading", () => {
const result = resolveAnalyticsLoading({
...production,
host,
- preferences: consented,
+ consent: consented,
});
expect({ host, ...result }).toEqual({
@@ -75,7 +68,7 @@ describe("resolveAnalyticsLoading", () => {
});
it("accepts the production host with a port, odd casing or a trailing dot", () => {
- const consented = preferences({ analytics: true, advertising: true });
+ const consented = consent({ analytics: true, advertising: true });
for (const host of [
"platform.agpt.co:443",
@@ -85,7 +78,7 @@ describe("resolveAnalyticsLoading", () => {
const result = resolveAnalyticsLoading({
...production,
host,
- preferences: consented,
+ consent: consented,
});
expect({ host, ...result }).toEqual({
@@ -97,16 +90,20 @@ describe("resolveAnalyticsLoading", () => {
});
it("loads the Google tag locally only with analytics consent", () => {
- const local = { host: "localhost:3000", pathname: "/", isLocal: true };
+ const local = {
+ host: "localhost:3000",
+ pathname: "/",
+ isLocal: true,
+ isConsentManaged: true,
+ };
expect(
- resolveAnalyticsLoading({ ...local, preferences: preferences() })
- .googleTag,
+ resolveAnalyticsLoading({ ...local, consent: consent() }).googleTag,
).toBe(false);
expect(
resolveAnalyticsLoading({
...local,
- preferences: preferences({ analytics: true }),
+ consent: consent({ analytics: true }),
}).googleTag,
).toBe(true);
});
@@ -114,7 +111,7 @@ describe("resolveAnalyticsLoading", () => {
it("loads DataFast on production with analytics consent", () => {
const result = resolveAnalyticsLoading({
...production,
- preferences: preferences({ analytics: true }),
+ consent: consent({ analytics: true }),
});
expect(result.dataFast).toBe(true);
@@ -124,17 +121,28 @@ describe("resolveAnalyticsLoading", () => {
const result = resolveAnalyticsLoading({
...production,
pathname: "/tour/chat",
- preferences: preferences({ hasConsented: false }),
+ consent: consent(),
});
expect(result.dataFast).toBe(true);
});
+ it("keeps DataFast off the tour when no banner is configured", () => {
+ const result = resolveAnalyticsLoading({
+ ...production,
+ pathname: "/tour",
+ isConsentManaged: false,
+ consent: consent(),
+ });
+
+ expect(result).toEqual({ googleTag: false, dataFast: false });
+ });
+
it("does not treat /tourism as the tour", () => {
const result = resolveAnalyticsLoading({
...production,
pathname: "/tourism",
- preferences: preferences({ hasConsented: false }),
+ consent: consent(),
});
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
index a25faddc6e..ee2e4dfc52 100644
--- a/autogpt_platform/frontend/src/services/analytics/loading-policy.ts
+++ b/autogpt_platform/frontend/src/services/analytics/loading-policy.ts
@@ -1,40 +1,54 @@
-import type { ConsentPreferences } from "@/services/consent/cookies";
+import type { ConsentState } from "@/services/consent/consent";
+
+export const DATAFAST_SCRIPT_SRC = "https://datafa.st/js/script.js";
interface LoadingArgs {
host: string;
pathname: string | null;
isLocal: boolean;
- preferences: ConsentPreferences | null;
+ isConsentManaged: boolean;
+ consent: ConsentState;
}
export function resolveAnalyticsLoading({
host,
pathname,
isLocal,
- preferences,
+ isConsentManaged,
+ consent,
}: 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.
+ // keeps it cookieless where consent is required (see consent-mode.ts) and
+ // Cookiebot sends the answer once there is one. Without a banner nothing
+ // could ever answer, so the tag stays off. Open-source developers running
+ // locally only send analytics after opting in.
+ googleTag:
+ (isProductionDomain && isConsentManaged) ||
+ (isLocal && consent.analytics),
dataFast:
- isProductionDomain && (hasAnalyticsConsent || isTourPath(pathname)),
+ isProductionDomain &&
+ (consent.analytics ||
+ isDataFastConsentExempt(pathname, isConsentManaged)),
};
}
+// TODO(SECRT-2713): the public tour loads DataFast without the consent gate
+// so tour funnel events fire for first-touch visitors. The old banner stayed
+// hidden on /tour; Cookiebot's does not, so revisit this exemption there.
+// Without a banner nothing optional loads, the tour included.
+export function isDataFastConsentExempt(
+ pathname: string | null,
+ isConsentManaged: boolean,
+): boolean {
+ return isConsentManaged && isTourPath(pathname);
+}
+
// Segment-boundary match: /tourism must not inherit the tour's consent
// exemption.
-export function isTourPath(pathname: string | null): boolean {
+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/reset-identity.ts b/autogpt_platform/frontend/src/services/analytics/reset-identity.ts
index 57c426063f..6cd1f1edc5 100644
--- a/autogpt_platform/frontend/src/services/analytics/reset-identity.ts
+++ b/autogpt_platform/frontend/src/services/analytics/reset-identity.ts
@@ -1,15 +1,27 @@
+import { syncPostHogConsent } from "@/providers/posthog/posthog-consent";
import posthog from "posthog-js";
import { resetAnonymousID } from "./anonymous-id";
export function resetAnalyticsIdentity(): void {
let anonymousID: string | undefined;
+ let didReset = false;
try {
if (posthog.get_distinct_id()) {
posthog.reset(true);
+ didReset = true;
anonymousID = posthog.get_distinct_id();
}
} catch {
anonymousID = undefined;
}
resetAnonymousID(anonymousID);
+ // reset() also drops PostHog's own opt-in, which opts a consenting visitor
+ // out until the next page load unless it is restored here.
+ if (didReset) {
+ try {
+ syncPostHogConsent();
+ } catch {
+ // Analytics must never block an account change.
+ }
+ }
}
diff --git a/autogpt_platform/frontend/src/services/analytics/useSetupAnalytics.ts b/autogpt_platform/frontend/src/services/analytics/useSetupAnalytics.ts
index cc6b09dd13..93b9d71247 100644
--- a/autogpt_platform/frontend/src/services/analytics/useSetupAnalytics.ts
+++ b/autogpt_platform/frontend/src/services/analytics/useSetupAnalytics.ts
@@ -1,30 +1,34 @@
"use client";
-import { useMountEffect } from "@/hooks/useMountEffect";
-import { consent, type ConsentPreferences } from "@/services/consent/cookies";
+import { isConsentManagerConfigured } from "@/services/consent/consent";
+import { useConsent } from "@/services/consent/useConsent";
import { usePathname } from "next/navigation";
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import { environment } from "../environment";
-import { resolveAnalyticsLoading } from "./loading-policy";
+import { DATAFAST_SCRIPT_SRC, 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 consent = useConsent();
const pathname = usePathname();
const { googleTag, dataFast } = resolveAnalyticsLoading({
host,
pathname,
isLocal: environment.isLocal(),
- preferences,
+ isConsentManaged: isConsentManagerConfigured(),
+ consent,
});
+ useEffect(() => {
+ // DataFast's script tracks client-side navigation on its own and can't be
+ // unloaded, so once the tour's exemption no longer covers it (the visitor
+ // navigated into the app without consenting) the page reloads to shed it.
+ // The element stays after unmount, even while still downloading, and is
+ // only marked when the exemption loaded it: a script loaded with consent
+ // that Cookiebot is asking about again waits for the visitor's reply.
+ if (dataFast || !isDataFastLoadedWithoutConsent()) return;
+ window.location.reload();
+ }, [dataFast]);
+
useEffect(() => {
if (!googleTag) return;
@@ -37,8 +41,16 @@ export function useSetupAnalytics(host: string) {
}, [googleTag]);
return {
- preferences,
googleTagEnabled: googleTag,
dataFastEnabled: dataFast,
+ dataFastWithoutConsent: dataFast && !consent.analytics,
};
}
+
+function isDataFastLoadedWithoutConsent() {
+ return Boolean(
+ document.querySelector(
+ `script[src="${DATAFAST_SCRIPT_SRC}"][data-consent-exempt]`,
+ ),
+ );
+}
diff --git a/autogpt_platform/frontend/src/services/consent/ConsentWithdrawalReload.tsx b/autogpt_platform/frontend/src/services/consent/ConsentWithdrawalReload.tsx
new file mode 100644
index 0000000000..91ca6df7da
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/consent/ConsentWithdrawalReload.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { useEffect } from "react";
+import {
+ getConsent,
+ getConsentAnswer,
+ subscribeToConsent,
+ type ConsentCategory,
+ type ConsentState,
+} from "./consent";
+
+// A script that already ran (DataFast, Vercel Analytics, session replay)
+// cannot be unloaded, so taking a category back reloads the page to shed it.
+// Granting needs no reload: consumers pick it up through useConsent.
+export function ConsentWithdrawalReload() {
+ useEffect(() => {
+ let previous = getConsent();
+ return subscribeToConsent(() => {
+ // No answer means Cookiebot is asking again (a stored answer it
+ // invalidated, or a region change). Reloading then would loop, since
+ // the stale cookie grants again on the next load until the visitor
+ // replies; their reply reloads if it takes anything back.
+ const next = getConsentAnswer();
+ if (!next) return;
+ const withdrawn = wasWithdrawn(previous, next);
+ previous = next;
+ if (withdrawn) window.location.reload();
+ });
+ }, []);
+
+ return null;
+}
+
+function wasWithdrawn(previous: ConsentState, next: ConsentState): boolean {
+ return (Object.keys(previous) as ConsentCategory[]).some(
+ (category) => previous[category] && !next[category],
+ );
+}
diff --git a/autogpt_platform/frontend/src/services/consent/consent-server.ts b/autogpt_platform/frontend/src/services/consent/consent-server.ts
new file mode 100644
index 0000000000..7962c73ef5
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/consent/consent-server.ts
@@ -0,0 +1,29 @@
+import { headers } from "next/headers";
+import {
+ isConsentManagerConfigured,
+ NO_CONSENT,
+ toConsentState,
+ type ConsentCategory,
+ type ConsentState,
+} from "./consent";
+import { parseCookieConsentHeader } from "./cookiebot";
+
+/** The visitor's consent as sent with the current request, for route handlers and server actions. */
+export async function getRequestConsent(): Promise<ConsentState> {
+ // The raw header rather than cookies(): that keeps only the last of two
+ // same-named cookies, and the client weighs every copy.
+ return readConsentFromCookieHeader((await headers()).get("cookie"));
+}
+
+export async function requestHasConsentFor(
+ category: ConsentCategory,
+): Promise<boolean> {
+ return (await getRequestConsent())[category];
+}
+
+export function readConsentFromCookieHeader(
+ cookieHeader: string | null | undefined,
+): ConsentState {
+ if (!isConsentManagerConfigured()) return NO_CONSENT;
+ return toConsentState(parseCookieConsentHeader(cookieHeader));
+}
diff --git a/autogpt_platform/frontend/src/services/consent/consent.test.ts b/autogpt_platform/frontend/src/services/consent/consent.test.ts
new file mode 100644
index 0000000000..f2af62c5a8
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/consent/consent.test.ts
@@ -0,0 +1,296 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ answerCookiebot,
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import {
+ getConsent,
+ getConsentAnswer,
+ getConsentManagerStatus,
+ hasConsentFor,
+ isConsentManagerConfigured,
+ NO_CONSENT,
+ openConsentSettings,
+ subscribeToConsent,
+ subscribeToConsentManagerStatus,
+ toConsentState,
+} from "./consent";
+import { readConsentFromCookieHeader } from "./consent-server";
+
+const STATISTICS_ONLY =
+ "{stamp:'abc',necessary:true,preferences:false,statistics:true,marketing:false,method:'explicit',ver:1,utc:1,region:'de'}";
+
+const STATISTICS_DENIED = STATISTICS_ONLY.replace(
+ "statistics:true",
+ "statistics:false",
+);
+
+function storeCookie(value: string) {
+ document.cookie = `CookieConsent=${encodeURIComponent(value)}; Path=/`;
+}
+
+afterEach(() => {
+ removeCookiebot();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+describe("category mapping", () => {
+ it("maps analytics and monitoring to statistics, advertising to marketing", () => {
+ expect(
+ toConsentState({
+ necessary: true,
+ preferences: true,
+ statistics: true,
+ marketing: false,
+ }),
+ ).toEqual({ analytics: true, monitoring: true, advertising: false });
+ expect(
+ toConsentState({
+ necessary: true,
+ preferences: true,
+ statistics: false,
+ marketing: true,
+ }),
+ ).toEqual({ analytics: false, monitoring: false, advertising: true });
+ });
+
+ it("denies everything without an answer", () => {
+ expect(toConsentState(null)).toEqual(NO_CONSENT);
+ });
+});
+
+describe("without a Cookiebot domain group", () => {
+ it("denies every category, whatever the browser holds", () => {
+ installCookiebot({ statistics: true, marketing: true });
+ storeCookie("-1");
+
+ expect(isConsentManagerConfigured()).toBe(false);
+ expect(getConsent()).toEqual(NO_CONSENT);
+ expect(hasConsentFor("analytics")).toBe(false);
+ });
+
+ it("denies every category on the server too", () => {
+ expect(readConsentFromCookieHeader("CookieConsent=-1")).toEqual(NO_CONSENT);
+ });
+});
+
+describe("with a Cookiebot domain group", () => {
+ it("reads a stored answer before Cookiebot has loaded", () => {
+ configureCookiebot();
+ storeCookie(STATISTICS_ONLY);
+
+ expect(getConsent()).toEqual({
+ analytics: true,
+ monitoring: true,
+ advertising: false,
+ });
+ });
+
+ it("follows the loaded script once the visitor has answered", () => {
+ configureCookiebot();
+ storeCookie(STATISTICS_ONLY);
+ installCookiebot({ statistics: false, marketing: true });
+
+ expect(getConsent()).toEqual({
+ analytics: false,
+ monitoring: false,
+ advertising: true,
+ });
+ });
+
+ it("denies everything until the visitor answers", () => {
+ configureCookiebot();
+ installCookiebot();
+
+ expect(getConsent()).toEqual(NO_CONSENT);
+ expect(getConsentAnswer()).toBeNull();
+ });
+
+ it("ignores a stored grant the loaded script no longer accepts", () => {
+ // Cookiebot withdraws an answer after a banner version bump, an expiry
+ // or a region change and asks again, leaving the old cookie in place
+ // until the visitor answers.
+ configureCookiebot();
+ storeCookie(STATISTICS_ONLY);
+ installCookiebot();
+
+ expect(getConsent()).toEqual(NO_CONSENT);
+ expect(getConsentAnswer()).toBeNull();
+ expect(hasConsentFor("analytics")).toBe(false);
+ });
+
+ it("falls back to the stored answer only while the script is absent", () => {
+ configureCookiebot();
+ storeCookie(STATISTICS_ONLY);
+
+ expect(hasConsentFor("analytics")).toBe(true);
+
+ installCookiebot();
+ expect(hasConsentFor("analytics")).toBe(false);
+
+ removeCookiebot();
+ storeCookie(STATISTICS_ONLY);
+ expect(hasConsentFor("analytics")).toBe(true);
+ });
+
+ it("reports the answer, or null when there is none", () => {
+ configureCookiebot();
+ expect(getConsentAnswer()).toBeNull();
+
+ storeCookie(STATISTICS_DENIED);
+ expect(getConsentAnswer()).toEqual(NO_CONSENT);
+
+ installCookiebot({ marketing: true });
+ expect(getConsentAnswer()).toEqual({
+ analytics: false,
+ monitoring: false,
+ advertising: true,
+ });
+ });
+
+ it("notifies subscribers on accept and decline, and stops after unsubscribe", () => {
+ configureCookiebot();
+ installCookiebot();
+ const listener = vi.fn();
+ const unsubscribe = subscribeToConsent(listener);
+
+ answerCookiebot({ statistics: true });
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(hasConsentFor("analytics")).toBe(true);
+
+ answerCookiebot({});
+ expect(listener).toHaveBeenCalledTimes(2);
+ expect(hasConsentFor("analytics")).toBe(false);
+
+ unsubscribe();
+ answerCookiebot({ statistics: true });
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+
+ it("opens the Cookiebot dialog to change the answer", () => {
+ configureCookiebot();
+ const { renew } = installCookiebot();
+
+ openConsentSettings();
+
+ expect(renew).toHaveBeenCalledOnce();
+ });
+
+ it("does nothing when the Cookiebot script never loaded", () => {
+ configureCookiebot();
+
+ expect(() => openConsentSettings()).not.toThrow();
+ });
+
+ it("reads the request cookie on the server", () => {
+ configureCookiebot();
+ const header = `theme=dark; CookieConsent=${encodeURIComponent(STATISTICS_ONLY)}`;
+
+ expect(readConsentFromCookieHeader(header)).toEqual({
+ analytics: true,
+ monitoring: true,
+ advertising: false,
+ });
+ expect(readConsentFromCookieHeader("theme=dark")).toEqual(NO_CONSENT);
+ expect(readConsentFromCookieHeader(null)).toEqual(NO_CONSENT);
+ });
+
+ it.each([
+ ["the granting copy first", [STATISTICS_ONLY, STATISTICS_DENIED]],
+ ["the granting copy last", [STATISTICS_DENIED, STATISTICS_ONLY]],
+ ])(
+ "denies on client and server alike when duplicate cookies disagree (%s)",
+ (_, [first, second]) => {
+ configureCookiebot();
+ const header = `CookieConsent=${encodeURIComponent(first)}; CookieConsent=${encodeURIComponent(second)}`;
+ vi.spyOn(document, "cookie", "get").mockReturnValue(header);
+
+ expect(getConsent()).toEqual(NO_CONSENT);
+ expect(readConsentFromCookieHeader(header)).toEqual(NO_CONSENT);
+ },
+ );
+
+ it("grants what duplicate cookies agree on", () => {
+ configureCookiebot();
+ const header = `CookieConsent=${encodeURIComponent(STATISTICS_ONLY)}; CookieConsent=-1`;
+ vi.spyOn(document, "cookie", "get").mockReturnValue(header);
+
+ expect(getConsent()).toEqual({
+ analytics: true,
+ monitoring: true,
+ advertising: false,
+ });
+ expect(readConsentFromCookieHeader(header)).toEqual(getConsent());
+ });
+});
+
+describe("consent manager status", () => {
+ it("is ready once the Cookiebot script has loaded", () => {
+ configureCookiebot();
+ installCookiebot();
+
+ expect(getConsentManagerStatus()).toBe("ready");
+ });
+
+ it("is unavailable when the page finished loading without it", () => {
+ configureCookiebot();
+ vi.spyOn(document, "readyState", "get").mockReturnValue("complete");
+
+ expect(getConsentManagerStatus()).toBe("unavailable");
+ });
+
+ it("is still loading while the page is", () => {
+ configureCookiebot();
+ vi.spyOn(document, "readyState", "get").mockReturnValue("interactive");
+
+ expect(getConsentManagerStatus()).toBe("loading");
+ });
+
+ it("notifies when the Cookiebot script loads or fails", () => {
+ const script = document.createElement("script");
+ script.id = "Cookiebot";
+ document.body.append(script);
+ const listener = vi.fn();
+
+ const unsubscribe = subscribeToConsentManagerStatus(listener);
+ script.dispatchEvent(new Event("load"));
+ script.dispatchEvent(new Event("error"));
+ window.dispatchEvent(new Event("load"));
+ unsubscribe();
+ script.dispatchEvent(new Event("load"));
+
+ expect(listener).toHaveBeenCalledTimes(3);
+ script.remove();
+ });
+});
+
+describe("before uc.js replaces the Cookiebot script element", () => {
+ // Browsers expose elements by id on window, so the <script id="Cookiebot">
+ // tag is window.Cookiebot until the script runs.
+ let element: HTMLScriptElement;
+
+ beforeEach(() => {
+ configureCookiebot();
+ element = document.createElement("script");
+ (window as unknown as { Cookiebot: unknown }).Cookiebot = element;
+ });
+
+ afterEach(() => {
+ delete window.Cookiebot;
+ vi.unstubAllEnvs();
+ });
+
+ it("reads the stored answer instead of treating the element as no answer", () => {
+ storeCookie(STATISTICS_ONLY);
+
+ expect(hasConsentFor("analytics")).toBe(true);
+ });
+
+ it("isn't reported as ready, and opening the settings doesn't throw", () => {
+ expect(getConsentManagerStatus()).not.toBe("ready");
+ expect(() => openConsentSettings()).not.toThrow();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/consent/consent.ts b/autogpt_platform/frontend/src/services/consent/consent.ts
new file mode 100644
index 0000000000..2ab348041d
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/consent/consent.ts
@@ -0,0 +1,126 @@
+import { environment } from "@/services/environment";
+import {
+ COOKIEBOT_CONSENT_EVENTS,
+ COOKIEBOT_SCRIPT_ID,
+ getCookiebotAPI,
+ parseCookieConsentHeader,
+ type CookiebotConsent,
+} from "./cookiebot";
+
+export type ConsentCategory = "analytics" | "monitoring" | "advertising";
+export type ConsentState = Readonly<Record<ConsentCategory, boolean>>;
+
+export const NO_CONSENT: ConsentState = Object.freeze({
+ analytics: false,
+ monitoring: false,
+ advertising: false,
+});
+
+const COOKIEBOT_CATEGORY: Record<
+ ConsentCategory,
+ Exclude<keyof CookiebotConsent, "necessary">
+> = {
+ analytics: "statistics",
+ monitoring: "statistics",
+ advertising: "marketing",
+};
+
+/**
+ * Without a Cookiebot domain group (self-hosted and local installs) there is
+ * no banner, and every optional category stays denied.
+ */
+export function isConsentManagerConfigured(): boolean {
+ return Boolean(environment.getCookiebotCBID());
+}
+
+export function toConsentState(
+ cookiebot: CookiebotConsent | null,
+): ConsentState {
+ if (!cookiebot) return NO_CONSENT;
+ return {
+ analytics: cookiebot[COOKIEBOT_CATEGORY.analytics],
+ monitoring: cookiebot[COOKIEBOT_CATEGORY.monitoring],
+ advertising: cookiebot[COOKIEBOT_CATEGORY.advertising],
+ };
+}
+
+export function getConsent(): ConsentState {
+ return getConsentAnswer() ?? NO_CONSENT;
+}
+
+/** The visitor's answer, or null while there is none to act on. */
+export function getConsentAnswer(): ConsentState | null {
+ if (typeof window === "undefined") return null;
+ if (!isConsentManagerConfigured()) return null;
+ const answer = readBrowserConsent();
+ return answer ? toConsentState(answer) : null;
+}
+
+export function hasConsentFor(category: ConsentCategory): boolean {
+ return getConsent()[category];
+}
+
+export function isSameConsent(a: ConsentState, b: ConsentState): boolean {
+ return (
+ a.analytics === b.analytics &&
+ a.monitoring === b.monitoring &&
+ a.advertising === b.advertising
+ );
+}
+
+export function subscribeToConsent(listener: () => void): () => void {
+ if (typeof window === "undefined") return () => {};
+ COOKIEBOT_CONSENT_EVENTS.forEach((event) =>
+ window.addEventListener(event, listener),
+ );
+ return () =>
+ COOKIEBOT_CONSENT_EVENTS.forEach((event) =>
+ window.removeEventListener(event, listener),
+ );
+}
+
+export function openConsentSettings(): void {
+ if (typeof window === "undefined") return;
+ getCookiebotAPI()?.renew();
+}
+
+export type ConsentManagerStatus = "loading" | "ready" | "unavailable";
+
+/**
+ * Whether the consent dialog can be opened. The script loads after the page
+ * becomes interactive; once the page has finished loading without it, a
+ * content blocker (or a network failure) stopped it.
+ */
+export function getConsentManagerStatus(): ConsentManagerStatus {
+ if (typeof window === "undefined") return "loading";
+ if (getCookiebotAPI()) return "ready";
+ return document.readyState === "complete" ? "unavailable" : "loading";
+}
+
+export function subscribeToConsentManagerStatus(
+ listener: () => void,
+): () => void {
+ if (typeof window === "undefined") return () => {};
+ const script = document.getElementById(COOKIEBOT_SCRIPT_ID);
+ window.addEventListener("load", listener);
+ script?.addEventListener("load", listener);
+ script?.addEventListener("error", listener);
+ const unsubscribe = subscribeToConsent(listener);
+ return () => {
+ window.removeEventListener("load", listener);
+ script?.removeEventListener("load", listener);
+ script?.removeEventListener("error", listener);
+ unsubscribe();
+ };
+}
+
+// Once loaded, the script is authoritative: it also withdraws a stored answer
+// it no longer accepts (a new banner version, an expired answer, a region
+// change) and asks again, while the old cookie stays behind until the visitor
+// answers. Only before it loads, or when a blocker stops it, does the stored
+// cookie speak for the visitor.
+function readBrowserConsent(): CookiebotConsent | null {
+ const cookiebot = getCookiebotAPI();
+ if (cookiebot) return cookiebot.hasResponse ? cookiebot.consent : null;
+ return parseCookieConsentHeader(document.cookie);
+}
diff --git a/autogpt_platform/frontend/src/services/consent/constants.ts b/autogpt_platform/frontend/src/services/consent/constants.ts
deleted file mode 100644
index 7b1de4de5c..0000000000
--- a/autogpt_platform/frontend/src/services/consent/constants.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export const ANALYTICS_CONSENT_COOKIE = "agpt_analytics_consent";
-export const ANALYTICS_CONSENT_GRANTED = "granted";
diff --git a/autogpt_platform/frontend/src/services/consent/cookiebot.test.ts b/autogpt_platform/frontend/src/services/consent/cookiebot.test.ts
new file mode 100644
index 0000000000..61f9ac83c5
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/consent/cookiebot.test.ts
@@ -0,0 +1,190 @@
+import { describe, expect, it } from "vitest";
+import { parseCookieConsent, parseCookieConsentHeader } from "./cookiebot";
+
+const ANSWER =
+ "{stamp:'VLZnHUKBPLqZCJyClLLmnGglmUPeZsGxrmiAEZ48i7UH39ptKHY4MA==',necessary:true,preferences:false,statistics:true,marketing:false,method:'explicit',ver:1,utc:1724770548958,region:'de'}";
+
+describe("parseCookieConsent", () => {
+ it("reads each category from the stored answer", () => {
+ expect(parseCookieConsent(ANSWER)).toEqual({
+ necessary: true,
+ preferences: false,
+ statistics: true,
+ marketing: false,
+ });
+ });
+
+ it("reads the URL-encoded form browsers send to the server", () => {
+ expect(parseCookieConsent(encodeURIComponent(ANSWER))).toEqual(
+ parseCookieConsent(ANSWER),
+ );
+ });
+
+ it("reads the partially encoded form Cookiebot writes", () => {
+ const partial = ANSWER.replaceAll("'", "%27").replaceAll(",", "%2C");
+
+ expect(parseCookieConsent(partial)?.statistics).toBe(true);
+ });
+
+ it('treats "-1" (no consent required in the visitor\'s region) as everything accepted', () => {
+ expect(parseCookieConsent("-1")).toEqual({
+ necessary: true,
+ preferences: true,
+ statistics: true,
+ marketing: true,
+ });
+ });
+
+ it("reads the answer Cookiebot stores for a region that needs no consent", () => {
+ const implied =
+ "{stamp:'-1',necessary:true,preferences:true,statistics:true,marketing:true,ver:2147483647,utc:1646127963403}";
+
+ expect(parseCookieConsent(implied)?.marketing).toBe(true);
+ });
+
+ it('treats the legacy "0" answer as declined', () => {
+ expect(parseCookieConsent("0")).toEqual({
+ necessary: true,
+ preferences: false,
+ statistics: false,
+ marketing: false,
+ });
+ });
+
+ it("returns null when there is no answer", () => {
+ expect(parseCookieConsent(undefined)).toBeNull();
+ expect(parseCookieConsent(null)).toBeNull();
+ expect(parseCookieConsent("")).toBeNull();
+ });
+
+ it("returns null for values it cannot read", () => {
+ for (const value of ["granted", "{}", "{stamp:'x'}", "[1,2]", "%E0%A4%A"]) {
+ expect({ value, parsed: parseCookieConsent(value) }).toEqual({
+ value,
+ parsed: null,
+ });
+ }
+ });
+
+ it("only grants a category on a literal true", () => {
+ const parsed = parseCookieConsent(
+ "{necessary:true,preferences:1,statistics:'yes',marketing:TRUE}",
+ );
+
+ expect(parsed).toEqual({
+ necessary: true,
+ preferences: false,
+ statistics: false,
+ marketing: false,
+ });
+ });
+
+ it("accepts quoted booleans and extra whitespace", () => {
+ const parsed = parseCookieConsent(
+ " { necessary : true , statistics : \"true\" , marketing : 'true' } ",
+ );
+
+ expect(parsed?.statistics).toBe(true);
+ expect(parsed?.marketing).toBe(true);
+ expect(parsed?.preferences).toBe(false);
+ });
+
+ it("is not fooled by category names inside quoted values", () => {
+ const parsed = parseCookieConsent(
+ "{stamp:'statistics:true',necessary:true,statistics:false,marketing:false}",
+ );
+
+ expect(parsed?.statistics).toBe(false);
+ });
+
+ it("only reads top-level keys, not ones nested inside other objects", () => {
+ const parsed = parseCookieConsent(
+ "{stamp:'x',necessary:true,preferences:false,statistics:false,marketing:false,consentmode:{statistics:true,marketing:true},ver:1}",
+ );
+
+ expect(parsed).toEqual({
+ necessary: true,
+ preferences: false,
+ statistics: false,
+ marketing: false,
+ });
+ });
+
+ it("reads top-level keys that come after a nested object", () => {
+ const parsed = parseCookieConsent(
+ "{consentmode:{statistics:false,list:[1,{a:2}]},necessary:true,statistics:true,marketing:false}",
+ );
+
+ expect(parsed?.statistics).toBe(true);
+ expect(parsed?.marketing).toBe(false);
+ });
+
+ it("does not grant a category nested only inside another object", () => {
+ expect(
+ parseCookieConsent(
+ "{necessary:true,preferences:false,consentmode:{statistics:true}}",
+ )?.statistics,
+ ).toBe(false);
+ });
+
+ it("only grants a repeated top-level key when every copy does", () => {
+ expect(
+ parseCookieConsent(
+ "{necessary:true,statistics:false,marketing:false,statistics:true}",
+ )?.statistics,
+ ).toBe(false);
+ });
+
+ it("returns null when braces or quotes do not balance", () => {
+ for (const value of [
+ "{necessary:true,statistics:true,consentmode:{a:1}",
+ "{necessary:true,statistics:true}}",
+ "{stamp:'open,necessary:true,statistics:true}",
+ ]) {
+ expect({ value, parsed: parseCookieConsent(value) }).toEqual({
+ value,
+ parsed: null,
+ });
+ }
+ });
+});
+
+describe("parseCookieConsentHeader", () => {
+ const granted = encodeURIComponent(ANSWER);
+ const denied = encodeURIComponent(
+ ANSWER.replace("statistics:true", "statistics:false"),
+ );
+
+ it("finds the answer among other cookies", () => {
+ expect(
+ parseCookieConsentHeader(`a=1; CookieConsent=${granted}; b=2`)
+ ?.statistics,
+ ).toBe(true);
+ });
+
+ it("returns null without a CookieConsent cookie", () => {
+ expect(parseCookieConsentHeader("a=1; NotCookieConsent=-1")).toBeNull();
+ expect(parseCookieConsentHeader("")).toBeNull();
+ expect(parseCookieConsentHeader(null)).toBeNull();
+ });
+
+ it("denies a category whichever duplicate copy denies it", () => {
+ for (const header of [
+ `CookieConsent=${granted}; CookieConsent=${denied}`,
+ `CookieConsent=${denied}; CookieConsent=${granted}`,
+ ]) {
+ expect(parseCookieConsentHeader(header)?.statistics).toBe(false);
+ }
+ });
+
+ it("treats an unreadable duplicate as a denial", () => {
+ expect(
+ parseCookieConsentHeader(`CookieConsent=-1; CookieConsent=garbage`),
+ ).toEqual({
+ necessary: true,
+ preferences: false,
+ statistics: false,
+ marketing: false,
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/consent/cookiebot.ts b/autogpt_platform/frontend/src/services/consent/cookiebot.ts
new file mode 100644
index 0000000000..1645acc1a9
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/consent/cookiebot.ts
@@ -0,0 +1,199 @@
+// Everything Cookiebot-specific lives in this file and the consent module
+// around it; the rest of the app only sees `ConsentState`.
+// https://www.cookiebot.com/en/developer/
+
+export const COOKIEBOT_CONSENT_COOKIE = "CookieConsent";
+export const COOKIEBOT_SCRIPT_URL = "https://consent.cookiebot.com/uc.js";
+export const COOKIEBOT_SCRIPT_ID = "Cookiebot";
+
+// OnAccept/OnDecline also fire on page load for a visitor who answered on an
+// earlier visit; OnConsentReady fires once the stored state is known.
+export const COOKIEBOT_CONSENT_EVENTS = [
+ "CookiebotOnConsentReady",
+ "CookiebotOnAccept",
+ "CookiebotOnDecline",
+ "CookiebotOnLoad",
+] as const;
+
+export interface CookiebotConsent {
+ necessary: boolean;
+ preferences: boolean;
+ statistics: boolean;
+ marketing: boolean;
+}
+
+interface CookiebotAPI {
+ consent: CookiebotConsent;
+ consented: boolean;
+ declined: boolean;
+ hasResponse: boolean;
+ renew: () => void;
+}
+
+declare global {
+ interface Window {
+ Cookiebot?: CookiebotAPI;
+ }
+}
+
+/**
+ * The script tag carries `id="Cookiebot"`, and browsers expose elements by id
+ * on `window`, so until uc.js replaces it `window.Cookiebot` is that element.
+ * Only an object with the API's methods counts as the loaded consent manager.
+ */
+export function getCookiebotAPI(): CookiebotAPI | null {
+ if (typeof window === "undefined") return null;
+ const candidate: unknown = window.Cookiebot;
+ if (
+ typeof candidate === "object" &&
+ candidate !== null &&
+ "renew" in candidate &&
+ typeof candidate.renew === "function"
+ ) {
+ return candidate as CookiebotAPI;
+ }
+ return null;
+}
+
+const ALL_GRANTED: CookiebotConsent = {
+ necessary: true,
+ preferences: true,
+ statistics: true,
+ marketing: true,
+};
+
+const NECESSARY_ONLY: CookiebotConsent = {
+ necessary: true,
+ preferences: false,
+ statistics: false,
+ marketing: false,
+};
+
+// Cookiebot writes "-1" when the visitor is outside every region its
+// configuration requires consent for (all categories accepted), and older
+// versions wrote "0" for "declined, necessary cookies only".
+const NO_CONSENT_REQUIRED = "-1";
+const LEGACY_DECLINED = "0";
+
+// The answer itself is a JavaScript object literal, not JSON, usually
+// URL-encoded:
+// {stamp:'…',necessary:true,preferences:false,statistics:true,marketing:false,method:'explicit',ver:1,utc:1724770548958,region:'de'}
+// Newer versions nest more objects inside it (e.g. consentmode:{…}), which can
+// repeat the category names, so only top-level keys count.
+const KEY_PATTERN = /^\s*([A-Za-z_$][\w$]*)\s*:([\s\S]*)$/;
+
+const CATEGORIES = ["preferences", "statistics", "marketing"] as const;
+
+/**
+ * Parses the `CookieConsent` cookie Cookiebot stores the visitor's answer in.
+ * Returns null when there is no usable answer, which callers treat as "only
+ * necessary cookies".
+ */
+export function parseCookieConsent(
+ raw: string | null | undefined,
+): CookiebotConsent | null {
+ if (!raw) return null;
+ const value = decodeCookieValue(raw).trim();
+
+ if (value === NO_CONSENT_REQUIRED) return ALL_GRANTED;
+ if (value === LEGACY_DECLINED) return NECESSARY_ONLY;
+ if (!value.startsWith("{") || !value.endsWith("}")) return null;
+
+ const entries = readTopLevelEntries(value.slice(1, -1));
+ if (!entries) return null;
+ if (!CATEGORIES.some((category) => entries.has(category))) return null;
+
+ // A key repeated at the top level only grants when every copy does.
+ const granted = (category: (typeof CATEGORIES)[number]) =>
+ entries.get(category)?.every((entry) => entry === "true") ?? false;
+
+ return {
+ necessary: true,
+ preferences: granted("preferences"),
+ statistics: granted("statistics"),
+ marketing: granted("marketing"),
+ };
+}
+
+/**
+ * Reads every `CookieConsent` entry in a Cookie header or `document.cookie`.
+ * A host-only cookie left beside a domain-wide one after a domain change
+ * sends both; the client and the server both resolve that to whatever every
+ * copy agrees on, so a stale copy can only ever deny.
+ */
+export function parseCookieConsentHeader(
+ cookieHeader: string | null | undefined,
+): CookiebotConsent | null {
+ if (!cookieHeader) return null;
+ const prefix = `${COOKIEBOT_CONSENT_COOKIE}=`;
+ const answers = cookieHeader
+ .split(";")
+ .map((part) => part.trim())
+ .filter((part) => part.startsWith(prefix))
+ .map((part) => parseCookieConsent(part.slice(prefix.length)));
+
+ if (!answers.some(Boolean)) return null;
+ return answers.reduce<CookiebotConsent>(
+ (combined, answer) => {
+ const next = answer ?? NECESSARY_ONLY;
+ return {
+ necessary: true,
+ preferences: combined.preferences && next.preferences,
+ statistics: combined.statistics && next.statistics,
+ marketing: combined.marketing && next.marketing,
+ };
+ },
+ { ...ALL_GRANTED },
+ );
+}
+
+// Splits the object literal's body on the commas outside nested objects,
+// arrays and quoted strings. Returns null when the braces or quotes do not
+// balance.
+function readTopLevelEntries(body: string): Map<string, string[]> | null {
+ const parts: string[] = [];
+ let depth = 0;
+ let quote: string | null = null;
+ let start = 0;
+
+ for (let index = 0; index < body.length; index++) {
+ const char = body[index];
+ if (quote) {
+ if (char === "\\") index++;
+ else if (char === quote) quote = null;
+ } else if (char === "'" || char === '"') {
+ quote = char;
+ } else if (char === "{" || char === "[") {
+ depth++;
+ } else if (char === "}" || char === "]") {
+ depth--;
+ if (depth < 0) return null;
+ } else if (char === "," && depth === 0) {
+ parts.push(body.slice(start, index));
+ start = index + 1;
+ }
+ }
+ if (quote || depth !== 0) return null;
+ parts.push(body.slice(start));
+
+ const entries = new Map<string, string[]>();
+ for (const part of parts) {
+ const match = KEY_PATTERN.exec(part);
+ if (!match) continue;
+ const [, key, entry] = match;
+ entries.set(key, [...(entries.get(key) ?? []), unquote(entry.trim())]);
+ }
+ return entries;
+}
+
+function unquote(entry: string): string {
+ return /^(['"]).*\1$/.test(entry) ? entry.slice(1, -1) : entry;
+}
+
+function decodeCookieValue(raw: string): string {
+ try {
+ return decodeURIComponent(raw);
+ } catch {
+ return raw;
+ }
+}
diff --git a/autogpt_platform/frontend/src/services/consent/cookies.test.ts b/autogpt_platform/frontend/src/services/consent/cookies.test.ts
deleted file mode 100644
index 5b51c2579f..0000000000
--- a/autogpt_platform/frontend/src/services/consent/cookies.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { beforeEach, describe, expect, it } from "vitest";
-import { Key } from "../storage/local-storage";
-import { consent, ConsentPreferences } from "./cookies";
-
-const COOKIE_NAME = "agpt_analytics_consent";
-
-function preferences(analytics: boolean): ConsentPreferences {
- return {
- hasConsented: true,
- timestamp: Date.now(),
- analytics,
- monitoring: false,
- advertising: false,
- };
-}
-
-describe("analytics consent cookie", () => {
- beforeEach(() => {
- localStorage.clear();
- document.cookie = `${COOKIE_NAME}=; Path=/; Max-Age=0`;
- });
-
- it("mirrors granted analytics consent for server-side tracking", () => {
- consent.save(preferences(true));
-
- expect(document.cookie).toContain(`${COOKIE_NAME}=granted`);
- });
-
- it("removes server-readable consent when analytics is denied", () => {
- document.cookie = `${COOKIE_NAME}=granted; Path=/`;
-
- consent.save(preferences(false));
-
- expect(document.cookie).not.toContain(`${COOKIE_NAME}=granted`);
- });
-
- it("migrates existing localStorage consent when it is loaded", () => {
- localStorage.setItem(Key.COOKIE_CONSENT, JSON.stringify(preferences(true)));
-
- consent.load();
-
- expect(document.cookie).toContain(`${COOKIE_NAME}=granted`);
- });
-
- it("revokes a stale server cookie when no stored consent exists", () => {
- document.cookie = `${COOKIE_NAME}=granted; Path=/`;
-
- consent.load();
-
- expect(document.cookie).not.toContain(`${COOKIE_NAME}=granted`);
- });
-
- it("revokes a stale server cookie when stored consent is invalid", () => {
- document.cookie = `${COOKIE_NAME}=granted; Path=/`;
- localStorage.setItem(Key.COOKIE_CONSENT, "invalid-json");
-
- consent.load();
-
- expect(document.cookie).not.toContain(`${COOKIE_NAME}=granted`);
- });
-
- it("removes the server-readable consent cookie when consent is cleared", () => {
- consent.save(preferences(true));
-
- consent.clear();
-
- 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
deleted file mode 100644
index 40298327ed..0000000000
--- a/autogpt_platform/frontend/src/services/consent/cookies.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import * as Sentry from "@sentry/nextjs";
-import { Key, storage } from "../storage/local-storage";
-import {
- ANALYTICS_CONSENT_COOKIE,
- ANALYTICS_CONSENT_GRANTED,
-} from "./constants";
-
-const CONSENT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;
-
-export interface ConsentPreferences {
- hasConsented: boolean;
- timestamp: number;
- analytics: boolean;
- monitoring: boolean;
- advertising: boolean;
-}
-
-export const DEFAULT_CONSENT: ConsentPreferences = {
- hasConsented: false,
- timestamp: Date.now(),
- analytics: false,
- monitoring: false,
- advertising: false,
-};
-
-export const COOKIE_CATEGORIES = {
- essential: {
- name: "Essential Cookies",
- description: "Required for login, authentication, and core functionality",
- alwaysActive: true,
- },
- analytics: {
- name: "Analytics & Performance",
- description:
- "Help us understand how you use AutoGPT to improve our service (Google Analytics, Vercel Analytics, Datafa.st)",
- alwaysActive: false,
- },
- monitoring: {
- name: "Error Monitoring & Session Replay",
- description:
- "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 {
- try {
- const stored = storage.get(Key.COOKIE_CONSENT);
- if (!stored) {
- syncAnalyticsConsentCookie(false);
- return DEFAULT_CONSENT;
- }
-
- const parsed = JSON.parse(stored) as ConsentPreferences;
-
- if (
- typeof parsed.hasConsented !== "boolean" ||
- typeof parsed.timestamp !== "number" ||
- typeof parsed.analytics !== "boolean" ||
- typeof parsed.monitoring !== "boolean"
- ) {
- console.warn(
- "Invalid consent data in localStorage, resetting to defaults",
- );
- syncAnalyticsConsentCookie(false);
- return DEFAULT_CONSENT;
- }
-
- // 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);
- console.error("Failed to load consent preferences:", error);
- return DEFAULT_CONSENT;
- }
-}
-
-function save(preferences: ConsentPreferences): void {
- try {
- storage.set(Key.COOKIE_CONSENT, JSON.stringify(preferences));
- syncAnalyticsConsentCookie(
- preferences.hasConsented && preferences.analytics,
- );
- } catch (error) {
- Sentry.captureException(error);
- console.error("Failed to save consent preferences:", error);
- }
-}
-
-function clear(): void {
- try {
- storage.clean(Key.COOKIE_CONSENT);
- syncAnalyticsConsentCookie(false);
- } catch (error) {
- Sentry.captureException(error);
- console.error("Failed to clear consent preferences:", error);
- }
-}
-
-function hasConsented(): boolean {
- const preferences = load();
- return preferences.hasConsented;
-}
-
-function hasConsentFor(
- category: keyof Omit<ConsentPreferences, "hasConsented" | "timestamp">,
-): boolean {
- const preferences = load();
- return preferences.hasConsented && preferences[category];
-}
-
-export const consent = {
- load,
- save,
- clear,
- hasConsented,
- hasConsentFor,
-};
-
-function syncAnalyticsConsentCookie(hasConsent: boolean): void {
- if (typeof document === "undefined") return;
-
- const maxAge = hasConsent ? CONSENT_COOKIE_MAX_AGE_SECONDS : 0;
- const value = hasConsent ? ANALYTICS_CONSENT_GRANTED : "";
- document.cookie = `${ANALYTICS_CONSENT_COOKIE}=${value}; Path=/; Max-Age=${maxAge}; SameSite=Lax${secureCookieAttribute()}`;
-}
-
-function secureCookieAttribute(): string {
- return window.location.protocol === "https:" ? "; Secure" : "";
-}
diff --git a/autogpt_platform/frontend/src/services/consent/useConsent.ts b/autogpt_platform/frontend/src/services/consent/useConsent.ts
new file mode 100644
index 0000000000..ca37d5b17f
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/consent/useConsent.ts
@@ -0,0 +1,44 @@
+"use client";
+
+import { useSyncExternalStore } from "react";
+import {
+ getConsent,
+ getConsentManagerStatus,
+ isSameConsent,
+ NO_CONSENT,
+ subscribeToConsent,
+ subscribeToConsentManagerStatus,
+ type ConsentManagerStatus,
+ type ConsentState,
+} from "./consent";
+
+let snapshot: ConsentState = NO_CONSENT;
+
+// useSyncExternalStore needs the same object back while nothing changed.
+function getSnapshot(): ConsentState {
+ const next = getConsent();
+ if (!isSameConsent(snapshot, next)) snapshot = next;
+ return snapshot;
+}
+
+function getServerSnapshot(): ConsentState {
+ return NO_CONSENT;
+}
+
+/** Current consent; re-renders when the visitor answers or changes the banner. */
+export function useConsent() {
+ return useSyncExternalStore(
+ subscribeToConsent,
+ getSnapshot,
+ getServerSnapshot,
+ );
+}
+
+/** Whether the consent dialog can be opened; see getConsentManagerStatus. */
+export function useConsentManagerStatus() {
+ return useSyncExternalStore(
+ subscribeToConsentManagerStatus,
+ getConsentManagerStatus,
+ (): ConsentManagerStatus => "loading",
+ );
+}
diff --git a/autogpt_platform/frontend/src/services/environment/index.ts b/autogpt_platform/frontend/src/services/environment/index.ts
index 5007e49932..4e44e8bb1e 100644
--- a/autogpt_platform/frontend/src/services/environment/index.ts
+++ b/autogpt_platform/frontend/src/services/environment/index.ts
@@ -100,6 +100,14 @@ function getGoogleAdsConversionLabels() {
return process.env.NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS || "";
}
+function getCookiebotCBID() {
+ return process.env.NEXT_PUBLIC_COOKIEBOT_CBID?.trim() || "";
+}
+
+function getCookiebotGeoRegions() {
+ return process.env.NEXT_PUBLIC_COOKIEBOT_GEOREGIONS?.trim() || "";
+}
+
function isProductionBuild() {
return process.env.NODE_ENV === "production";
}
@@ -172,6 +180,8 @@ export const environment = {
getLaunchDarklyClientId,
getGoogleAdsID,
getGoogleAdsConversionLabels,
+ getCookiebotCBID,
+ getCookiebotGeoRegions,
// Assertions
isServerSide,
isClientSide,
diff --git a/autogpt_platform/frontend/src/services/storage/local-storage.ts b/autogpt_platform/frontend/src/services/storage/local-storage.ts
index 04fb72a0c3..e96a662855 100644
--- a/autogpt_platform/frontend/src/services/storage/local-storage.ts
+++ b/autogpt_platform/frontend/src/services/storage/local-storage.ts
@@ -9,7 +9,6 @@ export enum Key {
WALLET_LAST_SEEN_CREDITS = "wallet-last-seen-credits",
LIBRARY_AGENTS_CACHE = "library-agents-cache",
CHAT_SESSION_ID = "chat_session_id",
- COOKIE_CONSENT = "autogpt_cookie_consent",
AI_AGENT_SAFETY_POPUP_SHOWN = "ai-agent-safety-popup-shown",
COPILOT_SOUND_ENABLED = "copilot-sound-enabled",
COPILOT_NOTIFICATIONS_ENABLED = "copilot-notifications-enabled",
diff --git a/autogpt_platform/frontend/src/tests/integrations/cookiebot.ts b/autogpt_platform/frontend/src/tests/integrations/cookiebot.ts
new file mode 100644
index 0000000000..316b4f5a62
--- /dev/null
+++ b/autogpt_platform/frontend/src/tests/integrations/cookiebot.ts
@@ -0,0 +1,63 @@
+import { vi } from "vitest";
+
+// Stands in for Cookiebot's uc.js: a configured domain group, the
+// window.Cookiebot API and the events it fires when the visitor answers.
+
+interface Answer {
+ statistics?: boolean;
+ marketing?: boolean;
+ preferences?: boolean;
+}
+
+export const TEST_COOKIEBOT_CBID = "00000000-0000-4000-8000-000000000000";
+
+export function configureCookiebot() {
+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", TEST_COOKIEBOT_CBID);
+}
+
+export function installCookiebot(answer?: Answer) {
+ const renew = vi.fn();
+ window.Cookiebot = {
+ consent: consentFrom(answer ?? {}),
+ consented: false,
+ declined: false,
+ hasResponse: false,
+ renew,
+ };
+ if (answer) setCookiebotAnswer(answer);
+ return { renew };
+}
+
+/** The visitor answers the banner: updates the API, then fires the event. */
+export function answerCookiebot(answer: Answer) {
+ setCookiebotAnswer(answer);
+ const accepted = Boolean(answer.statistics || answer.marketing);
+ window.dispatchEvent(
+ new Event(accepted ? "CookiebotOnAccept" : "CookiebotOnDecline"),
+ );
+}
+
+export function removeCookiebot() {
+ delete window.Cookiebot;
+ document.cookie = "CookieConsent=; Path=/; Max-Age=0";
+}
+
+function setCookiebotAnswer(answer: Answer) {
+ const cookiebot = window.Cookiebot;
+ if (!cookiebot) throw new Error("installCookiebot() first");
+ const consent = consentFrom(answer);
+ const accepted = consent.statistics || consent.marketing;
+ cookiebot.consent = consent;
+ cookiebot.hasResponse = true;
+ cookiebot.consented = accepted;
+ cookiebot.declined = !accepted;
+}
+
+function consentFrom(answer: Answer) {
+ return {
+ necessary: true,
+ preferences: answer.preferences ?? false,
+ statistics: answer.statistics ?? false,
+ marketing: answer.marketing ?? false,
+ };
+}