AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(platform): track account creation in DataFast (#13580)
Toran Bruce Richards0d62d52b7a04
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex fd6ea2f6c8..0428212289 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -123,6 +123,7 @@ from backend.data.understanding import ()from backend.data.user import (get_or_create_user,+ get_or_create_user_with_status,get_user_by_id,get_user_notification_preference,update_user_email,@@ -184,21 +185,34 @@ v1_router = APIRouter()_tally_background_tasks: set[asyncio.Task] = set()+USER_CREATED_HEADER = "X-AutoGPT-User-Created"@v1_router.post("/auth/user",summary="Get or create user",tags=["auth"],+ responses={+ 200: {+ "description": "Successful Response",+ "headers": {+ USER_CREATED_HEADER: {+ "description": "Whether this request created a new user",+ "schema": {"type": "string", "enum": ["true", "false"]},+ }+ },+ }+ },dependencies=[Security(requires_user)],)-async def get_or_create_user_route(user_data: dict = Security(get_jwt_payload)):- user = await get_or_create_user(user_data)+async def get_or_create_user_route(+ response: Response, user_data: dict = Security(get_jwt_payload)+):+ result = await get_or_create_user_with_status(user_data)+ response.headers[USER_CREATED_HEADER] = str(result.was_created).lower()+ user = result.user# Fire-and-forget: populate business understanding from Tally form.- # We use created_at proximity instead of an is_new flag because- # get_or_create_user is cached — a separate is_new return value would be- # unreliable on repeated calls within the cache TTL.age_seconds = (datetime.now(timezone.utc) - user.created_at).total_seconds()if age_seconds < 30:try:diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex e5a0510754..ccec8c2c66 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -98,15 +98,17 @@ def test_get_or_create_user_route("email": "[email protected]","name": "Test User",}+ mock_result = Mock(user=mock_user, was_created=False)mocker.patch(- "backend.api.features.v1.get_or_create_user",- return_value=mock_user,+ "backend.api.features.v1.get_or_create_user_with_status",+ return_value=mock_result,)response = client.post("/auth/user")assert response.status_code == 200+ assert response.headers["X-AutoGPT-User-Created"] == "false"response_data = response.json()configured_snapshot.assert_match(@@ -115,6 +117,37 @@ def test_get_or_create_user_route()+def test_get_or_create_user_route_reports_creation(+ mocker: pytest_mock.MockFixture,+ test_user_id: str,+) -> None:+ mock_user = Mock()+ mock_user.created_at = datetime(2020, 1, 1, tzinfo=timezone.utc)+ mock_user.model_dump.return_value = {+ "id": test_user_id,+ "email": "[email protected]",+ }++ mocker.patch(+ "backend.api.features.v1.get_or_create_user_with_status",+ return_value=Mock(user=mock_user, was_created=True),+ )++ response = client.post("/auth/user")++ assert response.status_code == 200+ assert response.headers["X-AutoGPT-User-Created"] == "true"+++def test_get_or_create_user_route_documents_creation_header() -> None:+ response_schema = app.openapi()["paths"]["/auth/user"]["post"]["responses"]["200"]++ assert response_schema["headers"]["X-AutoGPT-User-Created"] == {+ "description": "Whether this request created a new user",+ "schema": {"type": "string", "enum": ["true", "false"]},+ }++def test_update_user_email_route(mocker: pytest_mock.MockFixture,snapshot: Snapshot,diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.pyindex 3e5a3269eb..ee027406fc 100644--- a/autogpt_platform/backend/backend/data/user.py+++ b/autogpt_platform/backend/backend/data/user.py@@ -20,6 +20,7 @@ from prisma.types import (UserCreateInput,UserUpdateInput,)+from pydantic import BaseModel, ConfigDictfrom backend.data.db import prismafrom backend.data.model import (@@ -47,8 +48,23 @@ settings = Settings()cache_user_lookup = cached(maxsize=1000, ttl_seconds=300, shared_cache=True)+class UserCreationResult(BaseModel):+ model_config = ConfigDict(frozen=True)++ user: User+ was_created: bool++@cache_user_lookupasync def get_or_create_user(user_data: dict) -> User:+ return (await _get_or_create_user(user_data)).user+++async def get_or_create_user_with_status(user_data: dict) -> UserCreationResult:+ return await _get_or_create_user(user_data)+++async def _get_or_create_user(user_data: dict) -> UserCreationResult:try:user_id = user_data.get("sub")if not user_id:@@ -67,6 +83,9 @@ async def get_or_create_user(user_data: dict) -> User:name=user_data.get("user_metadata", {}).get("name"),))+ was_created = True+ else:+ was_created = False# Ensure every user has a marketplace Profile (required to publish# agents). Best-effort: a failure must not block user resolution — the@@ -88,7 +107,7 @@ async def get_or_create_user(user_data: dict) -> User:# race-safe (see ensure_personal_org).await ensure_personal_org(user.id)- return User.from_db(user)+ return UserCreationResult(user=User.from_db(user), was_created=was_created)except Exception as e:raise DatabaseError(f"Failed to get or create user {user_data}: {e}") from ediff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.pyindex 7683197ec5..caf1f20753 100644--- a/autogpt_platform/backend/backend/data/user_test.py+++ b/autogpt_platform/backend/backend/data/user_test.py@@ -1,6 +1,7 @@"""Unit tests for helpers in backend.data.user."""import asyncio+from datetime import datetime, timezonefrom unittest.mock import AsyncMock, MagicMock, patchimport prisma.errors@@ -11,6 +12,16 @@ from backend.data.user import update_user_timezonefrom backend.util.exceptions import DatabaseError+def _application_user(user_id: str, email: str) -> user_module.User:+ now = datetime.now(timezone.utc)+ return user_module.User(+ id=user_id,+ email=email,+ created_at=now,+ updated_at=now,+ )++class TestUpdateUserTimezone:@pytest.mark.asyncioasync def test_invalidates_all_three_user_caches(self):@@ -252,6 +263,58 @@ class TestTableBackedCredentials:await set_user_credentials("u1", [new])+class TestGetOrCreateUserStatus:+ @pytest.fixture(autouse=True)+ def stub_user_provisioning(self):+ with (+ patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),+ patch.object(user_module, "ensure_personal_org", new_callable=AsyncMock),+ ):+ yield++ @pytest.mark.asyncio+ async def test_reports_newly_created_user(self):+ db_user = MagicMock(id="user-new", email="[email protected]", name=None)++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-new", "[email protected]"),+ ),+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=None)+ mock_prisma.user.create = AsyncMock(return_value=db_user)++ result = await user_module.get_or_create_user_with_status(+ {"sub": "user-new", "email": "[email protected]"}+ )++ assert result.was_created is True++ @pytest.mark.asyncio+ async def test_reports_existing_user(self):+ db_user = MagicMock(id="user-existing", email="[email protected]", name=None)++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-existing", "[email protected]"),+ ),+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=db_user)++ result = await user_module.get_or_create_user_with_status(+ {"sub": "user-existing", "email": "[email protected]"}+ )++ assert result.was_created is False+ mock_prisma.user.create.assert_not_called()++class TestGetOrCreateUserProfile:"""get_or_create_user must guarantee a marketplace Profile exists, sincethe auth.users trigger that used to do this is unreliable."""@@ -275,7 +338,11 @@ class TestGetOrCreateUserProfile:with (patch.object(user_module, "prisma") as mock_prisma,- patch.object(user_module.User, "from_db", return_value=MagicMock()),+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-new", "[email protected]"),+ ),):mock_prisma.user.find_unique = AsyncMock(return_value=db_user)# No existing profile, and the generated username is free.@@ -300,7 +367,11 @@ class TestGetOrCreateUserProfile:with (patch.object(user_module, "prisma") as mock_prisma,- patch.object(user_module.User, "from_db", return_value=MagicMock()),+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-has", "[email protected]"),+ ),):mock_prisma.user.find_unique = AsyncMock(return_value=db_user)mock_prisma.profile.find_unique = AsyncMock(return_value=MagicMock())@@ -318,7 +389,7 @@ class TestGetOrCreateUserProfile:is still resolved so login/auth isn't broken."""user_module.get_or_create_user.cache_clear()db_user = MagicMock(id="user-err", email="[email protected]", name=None)- sentinel_user = MagicMock()+ sentinel_user = _application_user("user-err", "[email protected]")with (patch.object(user_module, "prisma") as mock_prisma,@@ -347,7 +418,11 @@ class TestGetOrCreateUserProfile:with (patch.object(user_module, "prisma") as mock_prisma,- patch.object(user_module.User, "from_db", return_value=MagicMock()),+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-clash", "[email protected]"),+ ),):mock_prisma.user.find_unique = AsyncMock(return_value=db_user)# userId never resolves to a Profile (so the clash is on username),@@ -380,7 +455,11 @@ class TestGetOrCreateUserPersonalOrg:with (patch.object(user_module, "prisma") as mock_prisma,- patch.object(user_module.User, "from_db", return_value=MagicMock()),+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-org", "[email protected]"),+ ),patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),patch.object(user_module, "ensure_personal_org", new_callable=AsyncMockdiff --git a/autogpt_platform/frontend/.env.default b/autogpt_platform/frontend/.env.defaultindex ca663b054d..593755240b 100644--- a/autogpt_platform/frontend/.env.default+++ b/autogpt_platform/frontend/.env.default@@ -35,6 +35,9 @@ NEXT_PUBLIC_PREVIEW_STEALING_DEV=NEXT_PUBLIC_POSTHOG_KEY=NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com+# DataFast server-side goal tracking (Website Settings > API, df_ key)+DATAFAST_API_KEY=+# Web Push VAPID public key (same as backend VAPID_PUBLIC_KEY)NEXT_PUBLIC_VAPID_PUBLIC_KEY=BBg49iVTWthVbRYphwmZNvZyiSJDqtSO4nmLxDzLKe3Oo9jbtu0Usa14xX4HQQNLUeiEfzD42zWSlrvY1PR12bsdiff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.tsnew file mode 100644index 0000000000..5ae1f49fbb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/actions.test.ts@@ -0,0 +1,107 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { signup } from "../actions";++const mocks = vi.hoisted(() => ({+ captureException: vi.fn(),+ getOnboardingStatus: vi.fn(),+ getServerSupabase: vi.fn(),+ postV1GetOrCreateUser: vi.fn(),+ scheduleAccountCreatedGoal: vi.fn(),+}));++vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({+ postV1GetOrCreateUser: mocks.postV1GetOrCreateUser,+}));+vi.mock("@/app/api/helpers", () => ({+ getOnboardingStatus: mocks.getOnboardingStatus,+}));+vi.mock("@/lib/supabase/server/getServerSupabase", () => ({+ getServerSupabase: mocks.getServerSupabase,+}));+vi.mock("@/services/analytics/datafast-server", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/analytics/datafast-server")+ >();+ return {+ ...actual,+ scheduleAccountCreatedGoal: mocks.scheduleAccountCreatedGoal,+ };+});+vi.mock("@sentry/nextjs", () => ({+ captureException: mocks.captureException,+}));++describe("email signup account creation tracking", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getServerSupabase.mockResolvedValue({+ auth: {+ signUp: vi.fn().mockResolvedValue({+ data: { session: { access_token: "token" } },+ error: null,+ }),+ setSession: vi.fn().mockResolvedValue(undefined),+ },+ });+ mocks.getOnboardingStatus.mockResolvedValue({+ shouldShowOnboarding: true,+ });+ });++ it("tracks only a newly created backend account", async () => {+ mocks.postV1GetOrCreateUser.mockResolvedValue({+ status: 200,+ data: {},+ headers: new Headers({ "X-AutoGPT-User-Created": "true" }),+ });++ const result = await signup(+ "[email protected]",+ "ValidPassword123!",+ "ValidPassword123!",+ true,+ );++ expect(result.success).toBe(true);+ expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledOnce();+ expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledWith("email");+ });++ it("does not track an account that already existed", async () => {+ mocks.postV1GetOrCreateUser.mockResolvedValue({+ status: 200,+ data: {},+ headers: new Headers({ "X-AutoGPT-User-Created": "false" }),+ });++ const result = await signup(+ "[email protected]",+ "ValidPassword123!",+ "ValidPassword123!",+ true,+ );++ expect(result.success).toBe(true);+ expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();+ });++ it("reports a resolved backend error instead of completing signup", async () => {+ mocks.postV1GetOrCreateUser.mockResolvedValue({+ status: 500,+ data: {},+ headers: new Headers(),+ });++ const result = await signup(+ "[email protected]",+ "ValidPassword123!",+ "ValidPassword123!",+ true,+ );++ expect(result.success).toBe(false);+ expect(mocks.captureException).toHaveBeenCalledOnce();+ expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts b/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.tsindex 8dbe556259..255ea3763a 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/actions.ts@@ -1,8 +1,12 @@"use server";import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/auth";-import { getOnboardingStatus, resolveResponse } from "@/app/api/helpers";+import { getOnboardingStatus } from "@/app/api/helpers";import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";+import {+ scheduleAccountCreatedGoal,+ wasAccountCreated,+} from "@/services/analytics/datafast-server";import { signupFormSchema } from "@/types/auth";import * as Sentry from "@sentry/nextjs";import { isWaitlistError, logWaitlistError } from "../../api/auth/utils";@@ -59,7 +63,10 @@ export async function signup(}try {- await resolveResponse(postV1GetOrCreateUser());+ const createUserResponse = await postV1GetOrCreateUser();+ if (wasAccountCreated(createUserResponse)) {+ await scheduleAccountCreatedGoal("email");+ }} catch (createUserError) {console.error("Error creating user during signup:", createUserError);Sentry.captureException(createUserError);diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.test.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.test.tsnew file mode 100644index 0000000000..2b8c75ef64--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.test.ts@@ -0,0 +1,91 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { GET } from "./route";++const mocks = vi.hoisted(() => ({+ getOnboardingStatus: vi.fn(),+ getServerSupabase: vi.fn(),+ postV1GetOrCreateUser: vi.fn(),+ revalidatePath: vi.fn(),+ scheduleAccountCreatedGoal: vi.fn(),+}));++vi.mock("@/app/api/__generated__/endpoints/auth/auth", () => ({+ postV1GetOrCreateUser: mocks.postV1GetOrCreateUser,+}));+vi.mock("@/app/api/helpers", () => ({+ getOnboardingStatus: mocks.getOnboardingStatus,+}));+vi.mock("@/lib/supabase/server/getServerSupabase", () => ({+ getServerSupabase: mocks.getServerSupabase,+}));+vi.mock("@/services/analytics/datafast-server", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/analytics/datafast-server")+ >();+ return {+ ...actual,+ scheduleAccountCreatedGoal: mocks.scheduleAccountCreatedGoal,+ };+});+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));++describe("OAuth callback account creation tracking", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv("NODE_ENV", "development");+ mocks.getServerSupabase.mockResolvedValue({+ auth: {+ exchangeCodeForSession: vi.fn().mockResolvedValue({ error: null }),+ },+ });+ mocks.getOnboardingStatus.mockResolvedValue({+ shouldShowOnboarding: false,+ });+ });++ it("tracks a newly created Google account", async () => {+ mocks.postV1GetOrCreateUser.mockResolvedValue({+ status: 200,+ data: {},+ headers: new Headers({ "X-AutoGPT-User-Created": "true" }),+ });++ const response = await GET(+ new Request("http://localhost/auth/callback?code=valid"),+ );++ expect(response.headers.get("location")).toBe("http://localhost/copilot");+ expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledOnce();+ expect(mocks.scheduleAccountCreatedGoal).toHaveBeenCalledWith("google");+ });++ it("does not track a returning Google user", async () => {+ mocks.postV1GetOrCreateUser.mockResolvedValue({+ status: 200,+ data: {},+ headers: new Headers({ "X-AutoGPT-User-Created": "false" }),+ });++ await GET(new Request("http://localhost/auth/callback?code=valid"));++ expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();+ });++ it("redirects a resolved backend error without tracking", async () => {+ mocks.postV1GetOrCreateUser.mockResolvedValue({+ status: 500,+ data: {},+ headers: new Headers(),+ });++ const response = await GET(+ new Request("http://localhost/auth/callback?code=valid"),+ );++ expect(response.headers.get("location")).toBe(+ "http://localhost/error?message=server-error",+ );+ expect(mocks.scheduleAccountCreatedGoal).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.tsindex ad40af0bf5..6edbc33e81 100644--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts@@ -1,6 +1,10 @@+import { postV1GetOrCreateUser } from "@/app/api/__generated__/endpoints/auth/auth";import { getOnboardingStatus } from "@/app/api/helpers";-import BackendAPI from "@/lib/autogpt-server-api";import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";+import {+ scheduleAccountCreatedGoal,+ wasAccountCreated,+} from "@/services/analytics/datafast-server";import { revalidatePath } from "next/cache";import { NextResponse } from "next/server";@@ -22,8 +26,10 @@ export async function GET(request: Request) {if (!error) {try {- const api = new BackendAPI();- await api.createUser();+ const createUserResponse = await postV1GetOrCreateUser();+ if (wasAccountCreated(createUserResponse)) {+ await scheduleAccountCreatedGoal("google");+ }const { shouldShowOnboarding } = await getOnboardingStatus();next = shouldShowOnboarding ? "/onboarding" : "/copilot";diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex abbd12a4ee..d7bdb39cdf 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -2577,6 +2577,12 @@"responses": {"200": {"description": "Successful Response",+ "headers": {+ "X-AutoGPT-User-Created": {+ "description": "Whether this request created a new user",+ "schema": { "type": "string", "enum": ["true", "false"] }+ }+ },"content": { "application/json": { "schema": {} } }},"401": {diff --git a/autogpt_platform/frontend/src/services/analytics/datafast-server.test.ts b/autogpt_platform/frontend/src/services/analytics/datafast-server.test.tsnew file mode 100644index 0000000000..37b7791636--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/datafast-server.test.ts@@ -0,0 +1,169 @@+import * as Sentry from "@sentry/nextjs";+import { cookies } from "next/headers";+import { after } from "next/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ scheduleAccountCreatedGoal,+ wasAccountCreated,+} from "./datafast-server";++vi.mock("next/headers", () => ({ cookies: vi.fn() }));+vi.mock("next/server", () => ({ after: vi.fn() }));+vi.mock("@sentry/nextjs", () => ({ captureException: vi.fn() }));++const VISITOR_ID = "a3ab2331-989f-4cfa-91c6-2461c9e3c6bd";++describe("DataFast server-side account creation tracking", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ 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.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(new Response(null, { status: 200 })),+ );+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it("sends the signup goal after the response completes", async () => {+ let callback: (() => Promise<void>) | undefined;+ vi.mocked(after).mockImplementation((next) => {+ callback = next as () => Promise<void>;+ });++ await scheduleAccountCreatedGoal("email");+ expect(after).toHaveBeenCalledOnce();++ await callback?.();++ expect(fetch).toHaveBeenCalledWith(+ "https://datafa.st/api/v1/goals",+ expect.objectContaining({+ method: "POST",+ headers: {+ Authorization: "Bearer df_test",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ datafast_visitor_id: VISITOR_ID,+ name: "signup",+ metadata: { method: "email" },+ }),+ }),+ );+ });++ it("does not schedule tracking without analytics consent", async () => {+ vi.mocked(cookies).mockResolvedValue({+ get: vi.fn(() => undefined),+ } as never);++ await scheduleAccountCreatedGoal("google");++ expect(after).not.toHaveBeenCalled();+ expect(fetch).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);++ await scheduleAccountCreatedGoal("google");++ expect(after).not.toHaveBeenCalled();+ });++ it("does not report a missing website API key outside cloud", async () => {+ vi.stubEnv("DATAFAST_API_KEY", "");++ await scheduleAccountCreatedGoal("email");++ expect(after).not.toHaveBeenCalled();+ expect(Sentry.captureException).not.toHaveBeenCalled();+ });++ it("reports a missing website API key in cloud", async () => {+ vi.stubEnv("DATAFAST_API_KEY", "");+ vi.stubEnv("NEXT_PUBLIC_BEHAVE_AS", "CLOUD");++ await scheduleAccountCreatedGoal("email");++ expect(after).not.toHaveBeenCalled();+ expect(Sentry.captureException).toHaveBeenCalledOnce();+ });++ it("reports a malformed configured website API key", async () => {+ vi.stubEnv("DATAFAST_API_KEY", "invalid-key");++ await scheduleAccountCreatedGoal("email");++ expect(after).not.toHaveBeenCalled();+ expect(Sentry.captureException).toHaveBeenCalledOnce();+ });++ it("isolates request-context failures from account creation", async () => {+ vi.mocked(cookies).mockRejectedValue(new Error("request context closed"));++ await expect(scheduleAccountCreatedGoal("email")).resolves.toBeUndefined();++ expect(Sentry.captureException).toHaveBeenCalledOnce();+ expect(after).not.toHaveBeenCalled();+ });++ it("reports DataFast failures without rejecting the post-response task", async () => {+ let callback: (() => Promise<void>) | undefined;+ vi.mocked(after).mockImplementation((next) => {+ callback = next as () => Promise<void>;+ });+ vi.mocked(fetch).mockResolvedValue(new Response(null, { status: 503 }));++ await scheduleAccountCreatedGoal("google");+ await expect(callback?.()).resolves.toBeUndefined();++ expect(Sentry.captureException).toHaveBeenCalledOnce();+ });+});++describe("wasAccountCreated", () => {+ it("only accepts the explicit backend creation header", () => {+ expect(+ wasAccountCreated({+ status: 200,+ headers: new Headers({ "X-AutoGPT-User-Created": "true" }),+ }),+ ).toBe(true);+ expect(+ wasAccountCreated({+ status: 200,+ headers: new Headers({ "X-AutoGPT-User-Created": "false" }),+ }),+ ).toBe(false);+ expect(wasAccountCreated({ status: 200, headers: new Headers() })).toBe(+ false,+ );+ });++ it("throws a status-bearing error for a resolved backend failure", () => {+ expect.assertions(2);++ try {+ wasAccountCreated({ status: 500, headers: new Headers() });+ } catch (error) {+ expect(error).toMatchObject({ status: 500 });+ expect(error).toBeInstanceOf(Error);+ }+ });+});diff --git a/autogpt_platform/frontend/src/services/analytics/datafast-server.ts b/autogpt_platform/frontend/src/services/analytics/datafast-server.tsnew file mode 100644index 0000000000..149b0ef083--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/datafast-server.ts@@ -0,0 +1,114 @@+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 { environment } from "@/services/environment";++const DATAFAST_GOALS_URL = "https://datafa.st/api/v1/goals";+const DATAFAST_VISITOR_COOKIE = "datafast_visitor_id";+const USER_CREATED_HEADER = "X-AutoGPT-User-Created";+const VISITOR_ID_PATTERN =+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++type SignupMethod = "email" | "google";++interface GoalContext {+ apiKey: string;+ method: SignupMethod;+ visitorID: string;+}++interface AccountCreationResponse {+ headers: Headers;+ status: number;+}++export function wasAccountCreated(response: AccountCreationResponse) {+ if (response.status !== 200) {+ throw Object.assign(+ new Error(`Unexpected account creation status ${response.status}`),+ { status: response.status },+ );+ }++ return response.headers.get(USER_CREATED_HEADER) === "true";+}++export async function scheduleAccountCreatedGoal(method: SignupMethod) {+ try {+ const context = await getGoalContext(method);+ if (!context) return;++ after(async () => {+ try {+ await sendAccountCreatedGoal(context);+ } catch (error) {+ reportTrackingError(error);+ }+ });+ } catch (error) {+ reportTrackingError(error);+ }+}++function reportTrackingError(error: unknown) {+ try {+ Sentry.captureException(error, {+ tags: { analytics_provider: "datafast", analytics_goal: "signup" },+ });+ } catch {+ console.error("Failed to report DataFast signup goal error");+ }+}++async function getGoalContext(+ method: SignupMethod,+): Promise<GoalContext | 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;++ const apiKey = process.env.DATAFAST_API_KEY?.trim();+ if (!apiKey) {+ if (!environment.isCloud()) return null;++ throw new Error("DATAFAST_API_KEY must be configured in cloud");+ }++ if (!apiKey.startsWith("df_")) {+ throw new Error("DATAFAST_API_KEY must use a df_ website key");+ }++ return { apiKey, method, visitorID };+}++async function sendAccountCreatedGoal(context: GoalContext) {+ const response = await fetch(DATAFAST_GOALS_URL, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${context.apiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ datafast_visitor_id: context.visitorID,+ name: "signup",+ metadata: { method: context.method },+ }),+ cache: "no-store",+ signal: AbortSignal.timeout(5_000),+ });++ if (!response.ok) {+ throw new Error(+ `DataFast signup goal failed with status ${response.status}`,+ );+ }+}diff --git a/autogpt_platform/frontend/src/services/consent/constants.ts b/autogpt_platform/frontend/src/services/consent/constants.tsnew file mode 100644index 0000000000..7b1de4de5c--- /dev/null+++ b/autogpt_platform/frontend/src/services/consent/constants.ts@@ -0,0 +1,2 @@+export const ANALYTICS_CONSENT_COOKIE = "agpt_analytics_consent";+export const ANALYTICS_CONSENT_GRANTED = "granted";diff --git a/autogpt_platform/frontend/src/services/consent/cookies.test.ts b/autogpt_platform/frontend/src/services/consent/cookies.test.tsnew file mode 100644index 0000000000..9cf21fbfb9--- /dev/null+++ b/autogpt_platform/frontend/src/services/consent/cookies.test.ts@@ -0,0 +1,68 @@+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,+ };+}++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`);+ });+});diff --git a/autogpt_platform/frontend/src/services/consent/cookies.ts b/autogpt_platform/frontend/src/services/consent/cookies.tsindex 02d480ca67..864d374dea 100644--- a/autogpt_platform/frontend/src/services/consent/cookies.ts+++ b/autogpt_platform/frontend/src/services/consent/cookies.ts@@ -1,5 +1,11 @@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;@@ -39,6 +45,7 @@ function load(): ConsentPreferences {try {const stored = storage.get(Key.COOKIE_CONSENT);if (!stored) {+ syncAnalyticsConsentCookie(false);return DEFAULT_CONSENT;}@@ -53,11 +60,14 @@ function load(): ConsentPreferences {console.warn("Invalid consent data in localStorage, resetting to defaults",);+ syncAnalyticsConsentCookie(false);return DEFAULT_CONSENT;}+ syncAnalyticsConsentCookie(parsed.hasConsented && parsed.analytics);return parsed;} catch (error) {+ syncAnalyticsConsentCookie(false);Sentry.captureException(error);console.error("Failed to load consent preferences:", error);return DEFAULT_CONSENT;@@ -67,6 +77,9 @@ function load(): ConsentPreferences {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);@@ -76,6 +89,7 @@ function save(preferences: ConsentPreferences): void {function clear(): void {try {storage.clean(Key.COOKIE_CONSENT);+ syncAnalyticsConsentCookie(false);} catch (error) {Sentry.captureException(error);console.error("Failed to clear consent preferences:", error);@@ -101,3 +115,15 @@ export const consent = {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" : "";+}