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(platform): one anonymous id across PostHog and LaunchDarkly, stored at signup (#14288)

Nicholas Tindleb9425ecc1ca3
diff --git a/autogpt_platform/backend/backend/api/features/analytics.py b/autogpt_platform/backend/backend/api/features/analytics.py
index 73a4590dcb..4e8ab352f9 100644
--- a/autogpt_platform/backend/backend/api/features/analytics.py
+++ b/autogpt_platform/backend/backend/api/features/analytics.py
@@ -9,11 +9,47 @@ from autogpt_libs.auth import get_user_id
from autogpt_libs.auth.dependencies import requires_user
import backend.data.analytics
+from backend.data import attribution as attribution_db
+from backend.data.attribution import UserAttribution, UserAttributionInput
router = fastapi.APIRouter(dependencies=[fastapi.Security(requires_user)])
logger = logging.getLogger(__name__)
+ path="/attribution",
+ summary="Report user attribution",
+ response_model=UserAttribution,
+)
+async def report_user_attribution(
+ user_id: Annotated[str, fastapi.Security(get_user_id)],
+ request: UserAttributionInput,
+ x_datafast_visitor_id: Annotated[
+ str | None, fastapi.Header(include_in_schema=False)
+ ] = None,
+ x_datafast_session_id: Annotated[
+ str | None, fastapi.Header(include_in_schema=False)
+ ] = None,
+) -> UserAttribution:
+ """Store where this user came from. Fields are only ever filled once.
+
+ The DataFast ids come from the request headers the frontend attaches to
+ every call, so the body never has to carry them.
+ """
+ merged = {
+ **request.model_dump(),
+ "datafast_visitor_id": request.datafast_visitor_id or x_datafast_visitor_id,
+ "datafast_session_id": request.datafast_session_id or x_datafast_session_id,
+ }
+ try:
+ # Re-validate so header-supplied ids meet the same length limits as
+ # the body; model_copy(update=...) would skip that check.
+ data = UserAttributionInput.model_validate(merged)
+ except pydantic.ValidationError as error:
+ raise fastapi.HTTPException(status_code=422, detail=error.errors()) from error
+ return await attribution_db.record_user_attribution(user_id, data)
+
+
class LogRawMetricRequest(pydantic.BaseModel):
metric_name: str = pydantic.Field(..., min_length=1)
metric_value: float = pydantic.Field(..., allow_inf_nan=False)
diff --git a/autogpt_platform/backend/backend/api/features/analytics_attribution_test.py b/autogpt_platform/backend/backend/api/features/analytics_attribution_test.py
new file mode 100644
index 0000000000..300303c8c9
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/analytics_attribution_test.py
@@ -0,0 +1,106 @@
+"""Tests for the user attribution endpoint."""
+
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock
+
+import fastapi
+import fastapi.testclient
+import pytest
+import pytest_mock
+
+from backend.data.attribution import UserAttribution, UserAttributionInput
+
+from .analytics import router as analytics_router
+
+app = fastapi.FastAPI()
+app.include_router(analytics_router)
+
+client = fastapi.testclient.TestClient(app)
+
+
[email protected](autouse=True)
+def setup_app_auth(mock_jwt_user):
+ from autogpt_libs.auth.jwt_utils import get_jwt_payload
+
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+ yield
+ app.dependency_overrides.clear()
+
+
+def _stored(user_id: str, data: UserAttributionInput) -> UserAttribution:
+ return UserAttribution(
+ user_id=user_id,
+ created_at=datetime(2026, 9, 2, tzinfo=UTC),
+ **data.model_dump(),
+ )
+
+
+def test_attribution_merges_datafast_headers_into_body(
+ mocker: pytest_mock.MockFixture, test_user_id: str
+) -> None:
+ record = mocker.patch(
+ "backend.api.features.analytics.attribution_db.record_user_attribution",
+ new_callable=AsyncMock,
+ side_effect=lambda user_id, data: _stored(user_id, data),
+ )
+
+ response = client.post(
+ "/attribution",
+ json={
+ "anonymous_id": "anon-1",
+ "landing_path": "/marketplace?utm_source=x",
+ "utm_source": "x",
+ "signup_method": "google",
+ },
+ headers={
+ "X-Datafast-Visitor-Id": "vis-1",
+ "X-Datafast-Session-Id": "ses-1",
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["user_id"] == test_user_id
+ assert body["datafast_visitor_id"] == "vis-1"
+ assert body["datafast_session_id"] == "ses-1"
+ assert body["anonymous_id"] == "anon-1"
+ assert body["signup_method"] == "google"
+ record.assert_awaited_once()
+ sent: UserAttributionInput = record.call_args.args[1]
+ assert sent.datafast_visitor_id == "vis-1"
+ assert sent.utm_source == "x"
+
+
+def test_attribution_body_wins_over_headers(
+ mocker: pytest_mock.MockFixture, test_user_id: str
+) -> None:
+ record = mocker.patch(
+ "backend.api.features.analytics.attribution_db.record_user_attribution",
+ new_callable=AsyncMock,
+ side_effect=lambda user_id, data: _stored(user_id, data),
+ )
+
+ response = client.post(
+ "/attribution",
+ json={"datafast_visitor_id": "vis-body"},
+ headers={"X-Datafast-Visitor-Id": "vis-header"},
+ )
+
+ assert response.status_code == 200, response.text
+ assert record.call_args.args[1].datafast_visitor_id == "vis-body"
+
+
+def test_attribution_rejects_oversized_fields() -> None:
+ response = client.post("/attribution", json={"utm_source": "x" * 300})
+ assert response.status_code == 422
+
+
+def test_attribution_rejects_an_oversized_datafast_header() -> None:
+ """The body parses; only the handler's re-validation of the merged input
+ can reject a header this long."""
+ response = client.post(
+ "/attribution",
+ json={"anonymous_id": "anon-1"},
+ headers={"X-Datafast-Visitor-Id": "v" * 200},
+ )
+ assert response.status_code == 422
diff --git a/autogpt_platform/backend/backend/data/attribution.py b/autogpt_platform/backend/backend/data/attribution.py
new file mode 100644
index 0000000000..43cc4ab913
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/attribution.py
@@ -0,0 +1,151 @@
+"""Where a user came from, captured once around signup.
+
+The browser reports the identities the analytics tools knew the user by
+before they had an account (our anonymous id, PostHog's device id, the
+DataFast visitor) plus the first landing page. Each field is written at most
+once: later reports only fill fields that are still empty, so a returning
+user's second device never rewrites the channel that actually brought them.
+
+Where the user came FROM is only accepted while the account is new. An older
+account reporting for the first time still contributes its analytics ids, so
+the join key works for everyone, but its landing page and UTM tags describe
+the session it happened to report in rather than a signup, and write-once
+would make that permanent.
+"""
+
+from datetime import datetime, timedelta, timezone
+from typing import cast
+
+import prisma.errors
+import prisma.models
+import prisma.types
+from pydantic import BaseModel, Field
+
+
+class UserAttributionInput(BaseModel):
+ anonymous_id: str | None = Field(default=None, max_length=128)
+ posthog_distinct_id: str | None = Field(default=None, max_length=128)
+ datafast_visitor_id: str | None = Field(default=None, max_length=128)
+ datafast_session_id: str | None = Field(default=None, max_length=128)
+ landing_path: str | None = Field(default=None, max_length=2048)
+ referrer: str | None = Field(default=None, max_length=2048)
+ utm_source: str | None = Field(default=None, max_length=256)
+ utm_medium: str | None = Field(default=None, max_length=256)
+ utm_campaign: str | None = Field(default=None, max_length=256)
+ signup_method: str | None = Field(default=None, max_length=32)
+
+
+class UserAttribution(UserAttributionInput):
+ user_id: str
+ created_at: datetime
+
+ @classmethod
+ def from_db(cls, row: prisma.models.UserAttribution) -> "UserAttribution":
+ return cls(
+ user_id=row.userId,
+ created_at=row.createdAt,
+ anonymous_id=row.anonymousId,
+ posthog_distinct_id=row.posthogDistinctId,
+ datafast_visitor_id=row.datafastVisitorId,
+ datafast_session_id=row.datafastSessionId,
+ landing_path=row.landingPath,
+ referrer=row.referrer,
+ utm_source=row.utmSource,
+ utm_medium=row.utmMedium,
+ utm_campaign=row.utmCampaign,
+ signup_method=row.signupMethod,
+ )
+
+
+_COLUMNS: dict[str, str] = {
+ "anonymous_id": "anonymousId",
+ "posthog_distinct_id": "posthogDistinctId",
+ "datafast_visitor_id": "datafastVisitorId",
+ "datafast_session_id": "datafastSessionId",
+ "landing_path": "landingPath",
+ "referrer": "referrer",
+ "utm_source": "utmSource",
+ "utm_medium": "utmMedium",
+ "utm_campaign": "utmCampaign",
+ "signup_method": "signupMethod",
+}
+
+# Where the user came from, as opposed to who they are. Only written while the
+# account is inside SIGNUP_ATTRIBUTION_WINDOW.
+_ACQUISITION_COLUMNS = frozenset(
+ {
+ "landingPath",
+ "referrer",
+ "utmSource",
+ "utmMedium",
+ "utmCampaign",
+ "signupMethod",
+ }
+)
+
+# Generous enough for a slow email verification or a retried report, far short
+# of the age of any account that predates this feature.
+SIGNUP_ATTRIBUTION_WINDOW = timedelta(days=7)
+
+
+async def record_user_attribution(
+ user_id: str, data: UserAttributionInput
+) -> UserAttribution:
+ """Create the row, or fill in fields that are still empty. Never overwrites."""
+ provided: dict[str, str] = {
+ column: value
+ for field, column in _COLUMNS.items()
+ if (value := getattr(data, field))
+ }
+ if any(column in _ACQUISITION_COLUMNS for column in provided) and not (
+ await _is_recent_signup(user_id)
+ ):
+ provided = {
+ column: value
+ for column, value in provided.items()
+ if column not in _ACQUISITION_COLUMNS
+ }
+ existing = await prisma.models.UserAttribution.prisma().find_unique(
+ where={"userId": user_id}
+ )
+ if existing is None:
+ # The columns are a closed set (see _COLUMNS); the cast only tells the
+ # type checker the dynamic key set is the generated input shape.
+ create_input = cast(
+ prisma.types.UserAttributionCreateInput,
+ {"userId": user_id, **provided},
+ )
+ try:
+ row = await prisma.models.UserAttribution.prisma().create(data=create_input)
+ return UserAttribution.from_db(row)
+ except prisma.errors.UniqueViolationError:
+ # Two tabs reported at once and the other one won the create;
+ # fall through and fill whatever it left empty.
+ existing = await prisma.models.UserAttribution.prisma().find_unique(
+ where={"userId": user_id}
+ )
+ if existing is None:
+ raise
+
+ missing = {
+ column: value
+ for column, value in provided.items()
+ if not getattr(existing, column)
+ }
+ if not missing:
+ return UserAttribution.from_db(existing)
+ update_input = cast(prisma.types.UserAttributionUpdateInput, missing)
+ row = await prisma.models.UserAttribution.prisma().update(
+ where={"userId": user_id}, data=update_input
+ )
+ return UserAttribution.from_db(row or existing)
+
+
+async def _is_recent_signup(user_id: str) -> bool:
+ user = await prisma.models.User.prisma().find_unique(where={"id": user_id})
+ if user is None:
+ return False
+ created_at = user.createdAt
+ if created_at.tzinfo is None:
+ created_at = created_at.replace(tzinfo=timezone.utc)
+ return datetime.now(timezone.utc) - created_at <= SIGNUP_ATTRIBUTION_WINDOW
diff --git a/autogpt_platform/backend/backend/data/attribution_test.py b/autogpt_platform/backend/backend/data/attribution_test.py
new file mode 100644
index 0000000000..7a17f25451
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/attribution_test.py
@@ -0,0 +1,226 @@
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock, MagicMock
+
+import prisma.errors
+import pytest
+import pytest_mock
+
+from backend.data.attribution import (
+ SIGNUP_ATTRIBUTION_WINDOW,
+ UserAttributionInput,
+ record_user_attribution,
+)
+
+_COLUMNS = (
+ "anonymousId",
+ "posthogDistinctId",
+ "datafastVisitorId",
+ "datafastSessionId",
+ "landingPath",
+ "referrer",
+ "utmSource",
+ "utmMedium",
+ "utmCampaign",
+ "signupMethod",
+)
+
+
+def _row(**values: str) -> MagicMock:
+ row = MagicMock()
+ row.userId = "user-1"
+ row.createdAt = datetime(2026, 9, 4, tzinfo=timezone.utc)
+ row.updatedAt = row.createdAt
+ for column in _COLUMNS:
+ setattr(row, column, values.get(column))
+ return row
+
+
+def _unique_violation() -> prisma.errors.UniqueViolationError:
+ return prisma.errors.UniqueViolationError(
+ {
+ "user_facing_error": {
+ "error_code": "P2002",
+ "message": "Unique constraint failed on the fields: (`userId`)",
+ }
+ }
+ )
+
+
[email protected](autouse=True)
+def account(mocker: pytest_mock.MockerFixture) -> MagicMock:
+ """A brand-new account, so acquisition fields are accepted by default."""
+ row = MagicMock()
+ row.createdAt = datetime.now(timezone.utc)
+ user_client = MagicMock()
+ user_client.find_unique = AsyncMock(return_value=row)
+ mocker.patch("prisma.models.User.prisma", return_value=user_client)
+ return row
+
+
+def client(mocker: pytest_mock.MockerFixture) -> MagicMock:
+ client = MagicMock()
+ client.find_unique = AsyncMock(return_value=None)
+ client.create = AsyncMock()
+ client.update = AsyncMock()
+ mocker.patch("prisma.models.UserAttribution.prisma", return_value=client)
+ return client
+
+
+async def test_first_report_creates_the_row(client: MagicMock) -> None:
+ client.create.return_value = _row(anonymousId="anon-1", landingPath="/pricing")
+
+ result = await record_user_attribution(
+ "user-1", UserAttributionInput(anonymous_id="anon-1", landing_path="/pricing")
+ )
+
+ client.create.assert_awaited_once_with(
+ data={"userId": "user-1", "anonymousId": "anon-1", "landingPath": "/pricing"}
+ )
+ client.update.assert_not_awaited()
+ assert result.anonymous_id == "anon-1"
+ assert result.landing_path == "/pricing"
+
+
+async def test_losing_a_concurrent_create_fills_the_winners_empty_fields(
+ client: MagicMock,
+) -> None:
+ winner = _row(anonymousId="anon-from-other-tab")
+ client.find_unique.side_effect = [None, winner]
+ client.create.side_effect = _unique_violation()
+ client.update.return_value = _row(
+ anonymousId="anon-from-other-tab", landingPath="/pricing"
+ )
+
+ result = await record_user_attribution(
+ "user-1",
+ UserAttributionInput(anonymous_id="anon-mine", landing_path="/pricing"),
+ )
+
+ client.create.assert_awaited_once()
+ # The winner's anonymous id stands; only the field it left empty is filled.
+ client.update.assert_awaited_once_with(
+ where={"userId": "user-1"}, data={"landingPath": "/pricing"}
+ )
+ assert result.anonymous_id == "anon-from-other-tab"
+ assert result.landing_path == "/pricing"
+
+
+async def test_a_second_report_never_overwrites_filled_fields(
+ client: MagicMock,
+) -> None:
+ client.find_unique.return_value = _row(anonymousId="anon-1", landingPath="/")
+
+ result = await record_user_attribution(
+ "user-1", UserAttributionInput(anonymous_id="anon-2", landing_path="/other")
+ )
+
+ client.create.assert_not_awaited()
+ client.update.assert_not_awaited()
+ assert result.anonymous_id == "anon-1"
+ assert result.landing_path == "/"
+
+
+async def test_an_account_older_than_the_window_records_no_signup_channel(
+ client: MagicMock, account: MagicMock
+) -> None:
+ account.createdAt = (
+ datetime.now(timezone.utc) - SIGNUP_ATTRIBUTION_WINDOW - timedelta(minutes=1)
+ )
+ client.create.return_value = _row(anonymousId="anon-1")
+
+ await record_user_attribution(
+ "user-1",
+ UserAttributionInput(
+ anonymous_id="anon-1",
+ landing_path="/pricing",
+ utm_source="newsletter",
+ signup_method="google",
+ ),
+ )
+
+ # The join key still lands; where they "came from" this session does not.
+ client.create.assert_awaited_once_with(
+ data={"userId": "user-1", "anonymousId": "anon-1"}
+ )
+
+
+async def test_an_account_inside_the_window_records_the_channel(
+ client: MagicMock, account: MagicMock
+) -> None:
+ account.createdAt = (
+ datetime.now(timezone.utc) - SIGNUP_ATTRIBUTION_WINDOW + timedelta(minutes=1)
+ )
+ client.create.return_value = _row(anonymousId="anon-1", utmSource="newsletter")
+
+ await record_user_attribution(
+ "user-1",
+ UserAttributionInput(anonymous_id="anon-1", utm_source="newsletter"),
+ )
+
+ client.create.assert_awaited_once_with(
+ data={"userId": "user-1", "anonymousId": "anon-1", "utmSource": "newsletter"}
+ )
+
+
+async def test_a_missing_account_row_records_no_signup_channel(
+ client: MagicMock, mocker: pytest_mock.MockerFixture
+) -> None:
+ user_client = MagicMock()
+ user_client.find_unique = AsyncMock(return_value=None)
+ mocker.patch("prisma.models.User.prisma", return_value=user_client)
+ client.create.return_value = _row(anonymousId="anon-1")
+
+ await record_user_attribution(
+ "user-1",
+ UserAttributionInput(anonymous_id="anon-1", landing_path="/pricing"),
+ )
+
+ client.create.assert_awaited_once_with(
+ data={"userId": "user-1", "anonymousId": "anon-1"}
+ )
+
+
+async def test_identity_only_reports_never_read_the_account(
+ client: MagicMock, mocker: pytest_mock.MockerFixture
+) -> None:
+ user_client = MagicMock()
+ user_client.find_unique = AsyncMock(return_value=None)
+ mocker.patch("prisma.models.User.prisma", return_value=user_client)
+ client.create.return_value = _row(anonymousId="anon-1")
+
+ await record_user_attribution("user-1", UserAttributionInput(anonymous_id="anon-1"))
+
+ user_client.find_unique.assert_not_awaited()
+
+
+async def test_the_update_path_also_withholds_the_signup_channel(
+ client: MagicMock, account: MagicMock
+) -> None:
+ """The filter runs before the create/update branch; pin it on both, so moving
+ it into the create branch alone cannot pass."""
+ account.createdAt = (
+ datetime.now(timezone.utc) - SIGNUP_ATTRIBUTION_WINDOW - timedelta(minutes=1)
+ )
+ client.find_unique.return_value = _row()
+ client.update.return_value = _row(anonymousId="anon-1")
+
+ await record_user_attribution(
+ "user-1",
+ UserAttributionInput(
+ anonymous_id="anon-1", landing_path="/pricing", utm_source="newsletter"
+ ),
+ )
+
+ client.create.assert_not_awaited()
+ client.update.assert_awaited_once_with(
+ where={"userId": "user-1"}, data={"anonymousId": "anon-1"}
+ )
diff --git a/autogpt_platform/backend/migrations/20260902120200_add_user_attribution/migration.sql b/autogpt_platform/backend/migrations/20260902120200_add_user_attribution/migration.sql
new file mode 100644
index 0000000000..50a6ef7dae
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260902120200_add_user_attribution/migration.sql
@@ -0,0 +1,27 @@
+-- CreateTable
+CREATE TABLE "UserAttribution" (
+ "userId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "anonymousId" TEXT,
+ "posthogDistinctId" TEXT,
+ "datafastVisitorId" TEXT,
+ "datafastSessionId" TEXT,
+ "landingPath" TEXT,
+ "referrer" TEXT,
+ "utmSource" TEXT,
+ "utmMedium" TEXT,
+ "utmCampaign" TEXT,
+ "signupMethod" TEXT,
+
+ CONSTRAINT "UserAttribution_pkey" PRIMARY KEY ("userId")
+);
+
+-- CreateIndex
+CREATE INDEX "UserAttribution_anonymousId_idx" ON "UserAttribution"("anonymousId");
+
+-- CreateIndex
+CREATE INDEX "UserAttribution_datafastVisitorId_idx" ON "UserAttribution"("datafastVisitorId");
+
+-- AddForeignKey
+ALTER TABLE "UserAttribution" ADD CONSTRAINT "UserAttribution_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 0b988fedc3..45057a5206 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -191,6 +191,7 @@ model User {
PlatformUserLinks PlatformUserLink[]
ExperimentAssignments ExperimentAssignment[]
+ Attribution UserAttribution?
}
// One row per (user, experiment): the arm a user was bucketed into the first
@@ -214,6 +215,36 @@ model ExperimentAssignment {
@@index([experimentKey, variant])
}
+// Where a user came from, captured once around signup. Holds the identities
+// the analytics tools know the user by before they had a user id, so the
+// database can join marketing attribution (DataFast), product analytics
+// (PostHog) and feature-flag bucketing (LaunchDarkly, via the shared
+// anonymous id) to activation and revenue. Fields are filled at most once.
+model UserAttribution {
+ userId String @id
+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ // First-party anonymous id shared with PostHog and LaunchDarkly pre-login.
+ anonymousId String?
+ // PostHog $device_id at the time of reporting, when it differs.
+ posthogDistinctId String?
+ datafastVisitorId String?
+ datafastSessionId String?
+
+ // First landing on the site, as seen by the browser that later signed up.
+ landingPath String?
+ referrer String?
+ utmSource String?
+ utmMedium String?
+ utmCampaign String?
+ // "email" | "google" when the account was created in this browser session.
+ signupMethod String?
+
+ @@index([anonymousId])
+ @@index([datafastVisitorId])
+}
enum ChatSessionStatus {
idle
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 21e6a3d3ac..4ad6f39242 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -2747,6 +2747,44 @@
}
}
},
+ "/api/analytics/attribution": {
+ "post": {
+ "tags": ["analytics"],
+ "summary": "Report user attribution",
+ "description": "Store where this user came from. Fields are only ever filled once.\n\nThe DataFast ids come from the request headers the frontend attaches to\nevery call, so the body never has to carry them.",
+ "operationId": "postAnalyticsReport user attribution",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/UserAttributionInput" }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/UserAttribution" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/analytics/log_raw_analytics": {
"post": {
"tags": ["analytics"],
@@ -31989,6 +32027,165 @@
"required": ["graph_id", "cost_cents", "run_count"],
"title": "UserAgentCostRollup"
},
+ "UserAttribution": {
+ "properties": {
+ "anonymous_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Anonymous Id"
+ },
+ "posthog_distinct_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Posthog Distinct Id"
+ },
+ "datafast_visitor_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Datafast Visitor Id"
+ },
+ "datafast_session_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Datafast Session Id"
+ },
+ "landing_path": {
+ "anyOf": [
+ { "type": "string", "maxLength": 2048 },
+ { "type": "null" }
+ ],
+ "title": "Landing Path"
+ },
+ "referrer": {
+ "anyOf": [
+ { "type": "string", "maxLength": 2048 },
+ { "type": "null" }
+ ],
+ "title": "Referrer"
+ },
+ "utm_source": {
+ "anyOf": [
+ { "type": "string", "maxLength": 256 },
+ { "type": "null" }
+ ],
+ "title": "Utm Source"
+ },
+ "utm_medium": {
+ "anyOf": [
+ { "type": "string", "maxLength": 256 },
+ { "type": "null" }
+ ],
+ "title": "Utm Medium"
+ },
+ "utm_campaign": {
+ "anyOf": [
+ { "type": "string", "maxLength": 256 },
+ { "type": "null" }
+ ],
+ "title": "Utm Campaign"
+ },
+ "signup_method": {
+ "anyOf": [
+ { "type": "string", "maxLength": 32 },
+ { "type": "null" }
+ ],
+ "title": "Signup Method"
+ },
+ "user_id": { "type": "string", "title": "User Id" },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Created At"
+ }
+ },
+ "type": "object",
+ "required": ["user_id", "created_at"],
+ "title": "UserAttribution"
+ },
+ "UserAttributionInput": {
+ "properties": {
+ "anonymous_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Anonymous Id"
+ },
+ "posthog_distinct_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Posthog Distinct Id"
+ },
+ "datafast_visitor_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Datafast Visitor Id"
+ },
+ "datafast_session_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Datafast Session Id"
+ },
+ "landing_path": {
+ "anyOf": [
+ { "type": "string", "maxLength": 2048 },
+ { "type": "null" }
+ ],
+ "title": "Landing Path"
+ },
+ "referrer": {
+ "anyOf": [
+ { "type": "string", "maxLength": 2048 },
+ { "type": "null" }
+ ],
+ "title": "Referrer"
+ },
+ "utm_source": {
+ "anyOf": [
+ { "type": "string", "maxLength": 256 },
+ { "type": "null" }
+ ],
+ "title": "Utm Source"
+ },
+ "utm_medium": {
+ "anyOf": [
+ { "type": "string", "maxLength": 256 },
+ { "type": "null" }
+ ],
+ "title": "Utm Medium"
+ },
+ "utm_campaign": {
+ "anyOf": [
+ { "type": "string", "maxLength": 256 },
+ { "type": "null" }
+ ],
+ "title": "Utm Campaign"
+ },
+ "signup_method": {
+ "anyOf": [
+ { "type": "string", "maxLength": 32 },
+ { "type": "null" }
+ ],
+ "title": "Signup Method"
+ }
+ },
+ "type": "object",
+ "title": "UserAttributionInput"
+ },
"UserCostSummary": {
"properties": {
"user_id": {
diff --git a/autogpt_platform/frontend/src/app/providers.tsx b/autogpt_platform/frontend/src/app/providers.tsx
index 830272e6c5..20f8ff1ba9 100644
--- a/autogpt_platform/frontend/src/app/providers.tsx
+++ b/autogpt_platform/frontend/src/app/providers.tsx
@@ -13,6 +13,7 @@ import {
PostHogUserTracker,
} from "@/providers/posthog/posthog-provider";
import { AdsConversionTracker } from "@/services/analytics/AdsConversionTracker";
+import { AttributionReporter } from "@/services/analytics/AttributionReporter";
import { LaunchDarklyProvider } from "@/services/feature-flags/feature-flag-provider";
import { QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider, ThemeProviderProps } from "next-themes";
@@ -31,6 +32,7 @@ export function Providers({ children, ...props }: ThemeProviderProps) {
<Suspense fallback={null}>
<SentryUserTracker />
<PostHogUserTracker />
+ <AttributionReporter />
<AdsConversionTracker />
<PostHogPageViewTracker />
</Suspense>
diff --git a/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.ts b/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.ts
index b03861aa4f..eabb532c4c 100644
--- a/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.ts
+++ b/autogpt_platform/frontend/src/lib/auth/hooks/useAuthStore.ts
@@ -1,6 +1,7 @@
"use client";
import type BackendAPI from "@/lib/autogpt-server-api/client";
+import { resetAnalyticsIdentity } from "@/services/analytics/reset-identity";
import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime";
import { create } from "zustand";
import { serverLogout, type ServerLogoutOptions } from "../actions";
@@ -292,3 +293,9 @@ export const useAuthStore = create<AuthStoreState>((set, get) => {
cleanup,
};
});
+
+useAuthStore.subscribe((state, previousState) => {
+ if (previousState.user && previousState.user.id !== state.user?.id) {
+ resetAnalyticsIdentity();
+ }
+});
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
index c635a63d39..3c0ff6a328 100644
--- a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
@@ -1,6 +1,10 @@
"use client";
import { useAuth } from "@/lib/auth/hooks/useAuth";
+import {
+ captureFirstLanding,
+ getAnonymousID,
+} from "@/services/analytics/anonymous-id";
import { environment } from "@/services/environment";
import { PostHogProvider as PHProvider } from "@posthog/react";
import { usePathname, useSearchParams } from "next/navigation";
@@ -13,14 +17,22 @@ export function PostHogProvider({ children }: { children: ReactNode }) {
useEffect(() => {
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.
+ const anonymousID = getAnonymousID();
posthog.init(postHogCredentials.key, {
api_host: postHogCredentials.host,
defaults: "2025-11-30",
capture_pageview: false,
capture_pageleave: true,
autocapture: true,
+ ...(anonymousID && {
+ bootstrap: { distinctID: anonymousID, isIdentifiedID: false },
+ }),
});
}
+ captureFirstLanding();
}, []);
if (!isPostHogEnabled) return <>{children}</>;
@@ -34,7 +46,11 @@ export function PostHogUserTracker() {
const isPostHogEnabled = environment.isPostHogEnabled();
useEffect(() => {
- if (isUserLoading || !isPostHogEnabled) return;
+ if (isUserLoading) return;
+ if (!isPostHogEnabled) {
+ previousUserIdRef.current = null;
+ return;
+ }
if (user) {
if (previousUserIdRef.current !== user.id) {
@@ -45,7 +61,6 @@ export function PostHogUserTracker() {
previousUserIdRef.current = user.id;
}
} else if (previousUserIdRef.current !== null) {
- posthog.reset();
previousUserIdRef.current = null;
}
}, [user, isUserLoading, isPostHogEnabled]);
diff --git a/autogpt_platform/frontend/src/services/analytics/AttributionReporter.tsx b/autogpt_platform/frontend/src/services/analytics/AttributionReporter.tsx
new file mode 100644
index 0000000000..b7ddccd4dc
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/AttributionReporter.tsx
@@ -0,0 +1,8 @@
+"use client";
+
+import { useReportAttribution } from "@/services/analytics/useReportAttribution";
+
+export function AttributionReporter() {
+ useReportAttribution();
+ return null;
+}
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
new file mode 100644
index 0000000000..8bfc07cffd
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/anonymous-id.test.ts
@@ -0,0 +1,216 @@
+import { consent } from "@/services/consent/cookies";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ captureFirstLanding,
+ getAnonymousID,
+ getPostHogDeviceID,
+ readFirstLanding,
+ resetAnonymousID,
+ resetAnonymousIDForTests,
+} from "../anonymous-id";
+
+function setAnalyticsConsent(analytics: boolean): void {
+ consent.save({
+ hasConsented: true,
+ timestamp: Date.now(),
+ analytics,
+ monitoring: false,
+ advertising: false,
+ });
+}
+
+function landOn(path: string, referrer = ""): void {
+ window.history.pushState({}, "", path);
+ Object.defineProperty(document, "referrer", {
+ value: referrer,
+ configurable: true,
+ });
+}
+
+const ANONYMOUS_ID_KEY = "agpt_anonymous_id";
+const FIRST_LANDING_KEY = "agpt_first_landing";
+
+beforeEach(() => {
+ window.localStorage.clear();
+ resetAnonymousIDForTests();
+ setAnalyticsConsent(true);
+ landOn("/");
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "phc_test");
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+describe("getAnonymousID", () => {
+ it("mints one id, persists it, and returns the same id afterwards", () => {
+ const first = getAnonymousID();
+
+ expect(first).toBeTruthy();
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBe(first);
+ expect(getAnonymousID()).toBe(first);
+
+ resetAnonymousIDForTests();
+ expect(getAnonymousID()).toBe(first);
+ });
+
+ it("adopts an existing PostHog device id so returning visitors keep history", () => {
+ window.localStorage.setItem(
+ "ph_phc_test_posthog",
+ JSON.stringify({ $device_id: "device-123" }),
+ );
+
+ expect(getAnonymousID()).toBe("device-123");
+ expect(getPostHogDeviceID()).toBe("device-123");
+ });
+
+ it("ignores unreadable PostHog persistence", () => {
+ window.localStorage.setItem("ph_phc_test_posthog", "not json");
+
+ expect(getPostHogDeviceID()).toBeNull();
+ expect(getAnonymousID()).not.toBe("not json");
+ });
+
+ it("keeps an in-memory id when storage is blocked", () => {
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("blocked");
+ });
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("blocked");
+ });
+
+ const id = getAnonymousID();
+
+ expect(id).toBeTruthy();
+ expect(getAnonymousID()).toBe(id);
+ });
+});
+
+describe("resetAnonymousID", () => {
+ it("forgets the id and first landing so the next visitor starts fresh", () => {
+ const first = getAnonymousID();
+ captureFirstLanding();
+ expect(readFirstLanding()).not.toBeNull();
+
+ resetAnonymousID();
+
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBe(
+ getAnonymousID(),
+ );
+ expect(readFirstLanding()).toBeNull();
+ expect(getAnonymousID()).not.toBe(first);
+ });
+
+ it("keeps the replacement identity after the in-memory cache is cleared", () => {
+ window.localStorage.setItem(
+ "ph_phc_test_posthog",
+ JSON.stringify({ $device_id: "old-device" }),
+ );
+ expect(getAnonymousID()).toBe("old-device");
+
+ resetAnonymousID("fresh-device");
+ resetAnonymousIDForTests();
+
+ expect(getAnonymousID()).toBe("fresh-device");
+ });
+});
+
+describe("first landing", () => {
+ it("records the first page once and reads it back", () => {
+ window.history.replaceState(
+ null,
+ "",
+ "/pricing?utm_source=x&utm_medium=cpc&utm_campaign=launch",
+ );
+
+ captureFirstLanding();
+ window.history.replaceState(null, "", "/somewhere-else");
+ captureFirstLanding();
+
+ const landing = readFirstLanding();
+ expect(landing?.path).toBe(
+ "/pricing?utm_source=x&utm_medium=cpc&utm_campaign=launch",
+ );
+ expect(landing?.utm_source).toBe("x");
+ expect(landing?.utm_medium).toBe("cpc");
+ expect(landing?.utm_campaign).toBe("launch");
+ expect(landing?.referrer).toBeNull();
+ expect(landing?.at).toBeTruthy();
+ });
+
+ it("returns null when nothing was captured or the record is corrupt", () => {
+ expect(readFirstLanding()).toBeNull();
+
+ window.localStorage.setItem(FIRST_LANDING_KEY, "{");
+ expect(readFirstLanding()).toBeNull();
+ });
+});
+
+describe("first landing redaction", () => {
+ it("records the route but never a one-time token from the path", () => {
+ landOn("/link/super-secret-invite-token");
+
+ captureFirstLanding();
+
+ const landing = readFirstLanding();
+ expect(landing?.path).toBe("/link");
+ expect(JSON.stringify(landing)).not.toContain("super-secret-invite-token");
+ });
+
+ it("drops sensitive query params while keeping campaign tags", () => {
+ landOn("/marketplace?utm_source=newsletter&code=oauth-code&token=secret");
+
+ captureFirstLanding();
+
+ const landing = readFirstLanding();
+ expect(landing?.path).toBe("/marketplace?utm_source=newsletter");
+ expect(landing?.utm_source).toBe("newsletter");
+ expect(JSON.stringify(landing)).not.toContain("oauth-code");
+ expect(JSON.stringify(landing)).not.toContain("secret");
+ });
+
+ it("redacts a same-origin referrer that carries a token", () => {
+ landOn(
+ "/marketplace",
+ `${window.location.origin}/share/secret-share-token`,
+ );
+
+ captureFirstLanding();
+
+ const landing = readFirstLanding();
+ expect(landing?.referrer).toBe(`${window.location.origin}/share`);
+ });
+
+ it("keeps an external referrer's origin and path, without its query", () => {
+ landOn("/marketplace", "https://news.example.com/post?session=abc");
+
+ captureFirstLanding();
+
+ expect(readFirstLanding()?.referrer).toBe("https://news.example.com/post");
+ });
+});
+
+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", () => {
+ setAnalyticsConsent(false);
+ landOn("/pricing?utm_source=newsletter");
+
+ captureFirstLanding();
+
+ expect(readFirstLanding()?.path).toBe("/pricing?utm_source=newsletter");
+ expect(readFirstLanding()?.utm_source).toBe("newsletter");
+ });
+
+ it("keeps the visitor identity when analytics consent is refused", () => {
+ const id = getAnonymousID();
+
+ setAnalyticsConsent(false);
+
+ expect(window.localStorage.getItem(ANONYMOUS_ID_KEY)).toBe(id);
+ expect(getAnonymousID()).toBe(id);
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/attribution-payload.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/attribution-payload.test.ts
new file mode 100644
index 0000000000..727c0a02fb
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/attribution-payload.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { buildAttributionPayload } from "../attribution-payload";
+
+const anonymous = vi.hoisted(() => ({
+ id: "anon-1" as string | null,
+ deviceID: "device-1" as string | null,
+ landing: null as null | {
+ path: string;
+ referrer: string | null;
+ utm_source: string | null;
+ utm_medium: string | null;
+ utm_campaign: string | null;
+ at: string;
+ },
+ signupMethod: null as string | null,
+}));
+
+vi.mock("@/services/analytics/anonymous-id", () => ({
+ getAnonymousID: () => anonymous.id,
+ getPostHogDeviceID: () => anonymous.deviceID,
+ readFirstLanding: () => anonymous.landing,
+}));
+
+vi.mock("@/services/analytics/account-created-cookie", () => ({
+ readAccountCreatedFlag: () => anonymous.signupMethod,
+}));
+
+beforeEach(() => {
+ anonymous.id = "anon-1";
+ anonymous.deviceID = "device-1";
+ anonymous.landing = null;
+ anonymous.signupMethod = null;
+});
+
+describe("buildAttributionPayload", () => {
+ it("sends nulls for everything the browser does not know", () => {
+ expect(buildAttributionPayload()).toEqual({
+ anonymous_id: "anon-1",
+ posthog_distinct_id: "device-1",
+ landing_path: null,
+ referrer: null,
+ utm_source: null,
+ utm_medium: null,
+ utm_campaign: null,
+ signup_method: null,
+ });
+ });
+
+ it("flattens the first landing and the signup method into the payload", () => {
+ anonymous.landing = {
+ path: "/pricing?utm_source=x",
+ referrer: "https://example.com/",
+ utm_source: "x",
+ utm_medium: "cpc",
+ utm_campaign: "launch",
+ at: "2026-09-04T00:00:00.000Z",
+ };
+ anonymous.signupMethod = "google";
+
+ expect(buildAttributionPayload()).toMatchObject({
+ landing_path: "/pricing?utm_source=x",
+ referrer: "https://example.com/",
+ utm_source: "x",
+ utm_medium: "cpc",
+ utm_campaign: "launch",
+ signup_method: "google",
+ });
+ });
+});
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
new file mode 100644
index 0000000000..d7d452b1ae
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/auth-identity.test.ts
@@ -0,0 +1,110 @@
+import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";
+import type { User } from "@/lib/auth/types";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ captureFirstLanding,
+ getAnonymousID,
+ readFirstLanding,
+ resetAnonymousIDForTests,
+} from "../anonymous-id";
+
+const posthog = vi.hoisted(() => ({
+ get_distinct_id: vi.fn<() => string | undefined>(),
+ reset: vi.fn(),
+}));
+
+vi.mock("posthog-js", () => ({ default: posthog }));
+vi.mock("@/lib/auth/actions", () => ({ serverLogout: vi.fn() }));
+vi.mock("@/lib/auth/helpers", () => ({
+ broadcastLogout: vi.fn(),
+ setWebSocketDisconnectIntent: vi.fn(),
+ setupSessionEventListeners: vi.fn(() => ({ cleanup: vi.fn() })),
+}));
+vi.mock("@/lib/auth/hooks/helpers", () => ({
+ fetchUser: vi.fn(),
+ handleStorageEvent: vi.fn(),
+ refreshSession: vi.fn(),
+ validateSession: vi.fn(),
+}));
+
+const userA = { id: "user-A", email: "[email protected]" } as User;
+const userB = { id: "user-B", email: "[email protected]" } as User;
+
+beforeEach(() => {
+ useAuthStore.setState({ user: null });
+ window.localStorage.clear();
+ resetAnonymousIDForTests();
+ vi.resetAllMocks();
+ vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "phc_test");
+});
+
+afterEach(() => {
+ useAuthStore.setState({ user: null });
+ vi.unstubAllEnvs();
+});
+
+describe("analytics identity on account transitions", () => {
+ it("rotates the visitor and landing on logout without an initialized PostHog client", () => {
+ window.localStorage.setItem(
+ "ph_phc_test_posthog",
+ JSON.stringify({ $device_id: "old-device" }),
+ );
+ expect(getAnonymousID()).toBe("old-device");
+ captureFirstLanding();
+ useAuthStore.setState({ user: userA });
+
+ useAuthStore.setState({ user: null });
+
+ expect(getAnonymousID()).not.toBe("old-device");
+ expect(readFirstLanding()).toBeNull();
+ expect(posthog.reset).not.toHaveBeenCalled();
+ });
+
+ it.each([null, userB])(
+ "shares the fresh PostHog identity before observers see the next account %j",
+ (nextUser) => {
+ posthog.get_distinct_id.mockReturnValue("user-A");
+ posthog.reset.mockImplementation(() => {
+ posthog.get_distinct_id.mockReturnValue("new-visitor");
+ });
+ useAuthStore.setState({ user: userA });
+ const observed: Array<string | null> = [];
+ const unsubscribe = useAuthStore.subscribe(() => {
+ observed.push(getAnonymousID());
+ });
+
+ try {
+ useAuthStore.setState({ user: nextUser });
+ } finally {
+ unsubscribe();
+ }
+
+ expect(posthog.reset).toHaveBeenCalledOnce();
+ expect(posthog.reset).toHaveBeenCalledWith(true);
+ expect(observed).toEqual(["new-visitor"]);
+ expect(getAnonymousID()).toBe(posthog.get_distinct_id());
+ },
+ );
+
+ it("keeps account changes working when the analytics client throws", () => {
+ useAuthStore.setState({ user: userA });
+ const previous = getAnonymousID();
+ posthog.get_distinct_id.mockImplementation(() => {
+ throw new Error("Analytics storage unavailable");
+ });
+
+ expect(() => useAuthStore.setState({ user: null })).not.toThrow();
+
+ expect(getAnonymousID()).not.toBe(previous);
+ expect(useAuthStore.getState().user).toBeNull();
+ });
+
+ it("preserves the anonymous identity through login and same-user refreshes", () => {
+ const previous = getAnonymousID();
+ useAuthStore.setState({ user: userA });
+ useAuthStore.setState({ user: { ...userA } });
+
+ expect(getAnonymousID()).toBe(previous);
+ expect(posthog.reset).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/useReportAttribution.test.tsx b/autogpt_platform/frontend/src/services/analytics/__tests__/useReportAttribution.test.tsx
new file mode 100644
index 0000000000..b941be701d
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/useReportAttribution.test.tsx
@@ -0,0 +1,119 @@
+import { server } from "@/mocks/mock-server";
+import { consent } from "@/services/consent/cookies";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ resetAttributionReportForTests,
+ useReportAttribution,
+} from "../useReportAttribution";
+
+const REPORTED_KEY = "agpt_attribution_reported";
+
+const auth = vi.hoisted(() => ({
+ user: null as { id: string } | null,
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({ user: auth.user, isUserLoading: false }),
+}));
+
+vi.mock("@/services/analytics/attribution-payload", () => ({
+ buildAttributionPayload: () => ({ anonymous_id: "anon-1" }),
+}));
+
+function wrapper({ children }: { children: ReactNode }) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
+
+function captureReports(status = 200) {
+ const bodies: unknown[] = [];
+ server.use(
+ http.post("*/api/analytics/attribution", async ({ request }) => {
+ bodies.push(await request.json());
+ if (status !== 200) return new HttpResponse(null, { status });
+ return HttpResponse.json({ user_id: "user-1", anonymous_id: "anon-1" });
+ }),
+ );
+ return bodies;
+}
+
+function setAnalyticsConsent(analytics: boolean): void {
+ consent.save({
+ hasConsented: true,
+ timestamp: Date.now(),
+ analytics,
+ monitoring: false,
+ advertising: false,
+ });
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ auth.user = { id: "user-1" };
+ setAnalyticsConsent(true);
+ resetAttributionReportForTests();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("useReportAttribution", () => {
+ it("reports once per user and remembers a successful report across loads", async () => {
+ const bodies = captureReports();
+
+ const { rerender } = renderHook(() => useReportAttribution(), { wrapper });
+ await waitFor(() => expect(bodies).toHaveLength(1));
+ expect(bodies[0]).toEqual({ anonymous_id: "anon-1" });
+ await waitFor(() =>
+ expect(window.localStorage.getItem(REPORTED_KEY)).toBe("user-1"),
+ );
+
+ rerender();
+ resetAttributionReportForTests();
+ renderHook(() => useReportAttribution(), { wrapper });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(bodies).toHaveLength(1);
+ });
+
+ it("reports under legitimate interest even when consent is refused", async () => {
+ const bodies = captureReports();
+ setAnalyticsConsent(false);
+
+ renderHook(() => useReportAttribution(), { wrapper });
+ await waitFor(() => expect(bodies).toHaveLength(1));
+
+ expect(bodies[0]).toEqual({ anonymous_id: "anon-1" });
+ });
+
+ it("does nothing while signed out", async () => {
+ const bodies = captureReports();
+ auth.user = null;
+
+ renderHook(() => useReportAttribution(), { wrapper });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(bodies).toHaveLength(0);
+ expect(window.localStorage.getItem(REPORTED_KEY)).toBeNull();
+ });
+
+ it("does not remember a failed report, so it can be retried", async () => {
+ const bodies = captureReports(500);
+
+ renderHook(() => useReportAttribution(), { wrapper });
+ await waitFor(() => expect(bodies).toHaveLength(1));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(window.localStorage.getItem(REPORTED_KEY)).toBeNull();
+
+ const retried = captureReports();
+ renderHook(() => useReportAttribution(), { wrapper });
+ await waitFor(() => expect(retried).toHaveLength(1));
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/anonymous-id.ts b/autogpt_platform/frontend/src/services/analytics/anonymous-id.ts
new file mode 100644
index 0000000000..bc3188f845
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/anonymous-id.ts
@@ -0,0 +1,191 @@
+/**
+ * One first-party anonymous identity for the whole analytics stack.
+ *
+ * PostHog and LaunchDarkly each mint their own visitor id, which is why
+ * LaunchDarkly could only bucket by user id (every logged-out visitor shared
+ * the literal key "anonymous") and nothing could tie a pre-signup flag arm
+ * to a post-signup PostHog person. This module owns that id instead:
+ *
+ * - PostHog is bootstrapped with it as the anonymous distinct id, so identify()
+ * merges it into the user as usual.
+ * - LaunchDarkly gets it as the anonymous user key before login and as a
+ * `device` context after login, so rules bucketed by device stay stable
+ * across signup.
+ * - 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
+ * visitors keep their history.
+ */
+
+const ANONYMOUS_ID_KEY = "agpt_anonymous_id";
+const FIRST_LANDING_KEY = "agpt_first_landing";
+
+// Routes that carry a one-time secret in the path itself. Landing on one
+// records the route and drops the rest, so an invite token never lands at rest.
+const REDACTED_PREFIXES = ["/link", "/share", "/auth", "/reset-password"];
+const SENSITIVE_PARAMS = [
+ "token",
+ "code",
+ "access_token",
+ "refresh_token",
+ "state",
+ "email",
+];
+
+export interface FirstLanding {
+ path: string;
+ referrer: string | null;
+ utm_source: string | null;
+ utm_medium: string | null;
+ utm_campaign: string | null;
+ at: string;
+}
+
+let memoryID: string | null = null;
+
+export function getAnonymousID(): string | null {
+ if (typeof window === "undefined") return null;
+ if (memoryID) return memoryID;
+
+ const stored = readStorage(ANONYMOUS_ID_KEY);
+ const id = stored ?? readPostHogDeviceID() ?? newID();
+ if (!stored) writeStorage(ANONYMOUS_ID_KEY, id);
+ memoryID = id;
+ return id;
+}
+
+/**
+ * Remember the first page this browser landed on, once. Captured under
+ * legitimate interest rather than analytics consent — to be revisited after GTM.
+ */
+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));
+}
+
+export function readFirstLanding(): FirstLanding | null {
+ const raw = readStorage(FIRST_LANDING_KEY);
+ if (!raw) return null;
+ try {
+ return JSON.parse(raw) as FirstLanding;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Rotate the browser identity and clear its first landing. Persist the new
+ * identity 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();
+ 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);
+}
+
+export function resetAnonymousIDForTests(): void {
+ memoryID = null;
+}
+
+/** PostHog's own device id, when its persistence exists in this browser. */
+export function getPostHogDeviceID(): string | null {
+ if (typeof window === "undefined") return null;
+ return readPostHogDeviceID();
+}
+
+function readPostHogDeviceID(): string | null {
+ const key = process.env.NEXT_PUBLIC_POSTHOG_KEY;
+ if (!key) return null;
+ const persistenceKey = `ph_${key}_posthog`;
+ const raw = readStorage(persistenceKey) ?? readCookie(persistenceKey);
+ if (!raw) return null;
+ try {
+ const parsed = JSON.parse(raw) as { $device_id?: unknown };
+ return typeof parsed.$device_id === "string" ? parsed.$device_id : null;
+ } catch {
+ return null;
+ }
+}
+
+function redactPath(pathname: string, search: string): string {
+ const prefix = REDACTED_PREFIXES.find(
+ (candidate) =>
+ pathname === candidate || pathname.startsWith(`${candidate}/`),
+ );
+ if (prefix) return prefix;
+
+ const params = new URLSearchParams(search);
+ SENSITIVE_PARAMS.forEach((name) => params.delete(name));
+ const query = params.toString();
+ return query ? `${pathname}?${query}` : pathname;
+}
+
+/** Same-origin referrers reach the same secret-bearing routes, so redact both. */
+function redactReferrer(referrer: string): string | null {
+ if (!referrer) return null;
+ try {
+ const url = new URL(referrer);
+ if (url.origin !== window.location.origin) return url.origin + url.pathname;
+ return url.origin + redactPath(url.pathname, url.search);
+ } catch {
+ return null;
+ }
+}
+
+function newID(): string {
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
+ return crypto.randomUUID();
+ }
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
+}
+
+function readStorage(key: string): string | null {
+ try {
+ return window.localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function writeStorage(key: string, value: string): void {
+ try {
+ window.localStorage.setItem(key, value);
+ } catch {
+ // Private mode or blocked storage: the in-memory id still holds for
+ // this page load.
+ }
+}
+
+function readCookie(name: string): string | null {
+ const prefix = `${name}=`;
+ const entry = document.cookie
+ .split("; ")
+ .find((part) => part.startsWith(prefix));
+ if (!entry) return null;
+ try {
+ return decodeURIComponent(entry.slice(prefix.length));
+ } catch {
+ return null;
+ }
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/attribution-payload.ts b/autogpt_platform/frontend/src/services/analytics/attribution-payload.ts
new file mode 100644
index 0000000000..d02f581495
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/attribution-payload.ts
@@ -0,0 +1,25 @@
+import type { UserAttributionInput } from "@/app/api/__generated__/models/userAttributionInput";
+import { readAccountCreatedFlag } from "@/services/analytics/account-created-cookie";
+import {
+ getAnonymousID,
+ getPostHogDeviceID,
+ readFirstLanding,
+} from "@/services/analytics/anonymous-id";
+
+/**
+ * Everything the browser knows about where this user came from. The DataFast
+ * ids travel as request headers (see the API mutator), so they are not here.
+ */
+export function buildAttributionPayload(): UserAttributionInput {
+ const landing = readFirstLanding();
+ return {
+ anonymous_id: getAnonymousID(),
+ posthog_distinct_id: getPostHogDeviceID(),
+ landing_path: landing?.path ?? null,
+ referrer: landing?.referrer ?? null,
+ utm_source: landing?.utm_source ?? null,
+ utm_medium: landing?.utm_medium ?? null,
+ utm_campaign: landing?.utm_campaign ?? null,
+ signup_method: readAccountCreatedFlag(),
+ };
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/reset-identity.ts b/autogpt_platform/frontend/src/services/analytics/reset-identity.ts
new file mode 100644
index 0000000000..57c426063f
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/reset-identity.ts
@@ -0,0 +1,15 @@
+import posthog from "posthog-js";
+import { resetAnonymousID } from "./anonymous-id";
+
+export function resetAnalyticsIdentity(): void {
+ let anonymousID: string | undefined;
+ try {
+ if (posthog.get_distinct_id()) {
+ posthog.reset(true);
+ anonymousID = posthog.get_distinct_id();
+ }
+ } catch {
+ anonymousID = undefined;
+ }
+ resetAnonymousID(anonymousID);
+}
diff --git a/autogpt_platform/frontend/src/services/analytics/useReportAttribution.ts b/autogpt_platform/frontend/src/services/analytics/useReportAttribution.ts
new file mode 100644
index 0000000000..9043c99e4e
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/useReportAttribution.ts
@@ -0,0 +1,60 @@
+"use client";
+
+import { usePostAnalyticsReportUserAttribution } from "@/app/api/__generated__/endpoints/analytics/analytics";
+import { useAuth } from "@/lib/auth/hooks/useAuth";
+import { buildAttributionPayload } from "@/services/analytics/attribution-payload";
+import { useEffect } from "react";
+
+const REPORTED_KEY = "agpt_attribution_reported";
+let reportedInMemory: string | null = null;
+
+/**
+ * Once per user per browser, tell the backend where this user came from.
+ * The backend only ever fills empty fields, so reporting from a second
+ * browser later is harmless.
+ */
+export function useReportAttribution() {
+ const { user } = useAuth();
+ const { mutate: reportAttribution } = usePostAnalyticsReportUserAttribution();
+ const userID = user?.id ?? null;
+
+ useEffect(() => {
+ if (!userID || !claimReport(userID)) return;
+ reportAttribution(
+ { data: buildAttributionPayload() },
+ {
+ // Only a report the backend accepted is remembered across loads; a
+ // failed one is released so the next render (or load) retries it.
+ onSuccess: () => markReported(userID),
+ onError: () => releaseReport(userID),
+ },
+ );
+ }, [userID, reportAttribution]);
+}
+
+function claimReport(userID: string): boolean {
+ if (reportedInMemory === userID) return false;
+ try {
+ if (window.localStorage.getItem(REPORTED_KEY) === userID) return false;
+ } catch {
+ // Storage blocked: the in-memory guard still prevents repeats this load.
+ }
+ reportedInMemory = userID;
+ return true;
+}
+
+function markReported(userID: string): void {
+ try {
+ window.localStorage.setItem(REPORTED_KEY, userID);
+ } catch {
+ // Storage blocked: the in-memory guard still prevents repeats this load.
+ }
+}
+
+function releaseReport(userID: string): void {
+ if (reportedInMemory === userID) reportedInMemory = null;
+}
+
+export function resetAttributionReportForTests(): void {
+ reportedInMemory = null;
+}
diff --git a/autogpt_platform/frontend/src/services/feature-flags/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/services/feature-flags/__tests__/helpers.test.ts
index f10696758c..7ca023cbd1 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/__tests__/helpers.test.ts
@@ -22,6 +22,33 @@ describe("buildLDContext", () => {
});
});
+ it("keys the anonymous context by the shared anonymous id when available", () => {
+ expect(buildLDContext(null, "anon-123")).toEqual({
+ kind: "user",
+ key: "anon-123",
+ anonymous: true,
+ });
+ });
+
+ it("adds a device context carrying the anonymous id for a signed-in user", () => {
+ const ctx = buildLDContext(userFixture(), "anon-123");
+
+ expect(ctx).toEqual({
+ kind: "multi",
+ user: {
+ kind: "user",
+ key: "00000000-0000-0000-0000-000000000001",
+ anonymous: false,
+ email: "[email protected]",
+ email_domain: "example.com",
+ role: "authenticated",
+ created_at: "2026-05-08T12:00:00Z",
+ custom: { role: "authenticated" },
+ },
+ device: { kind: "device", key: "anon-123", anonymous: true },
+ });
+ });
+
it("includes email, email_domain, role, created_at, and custom.role for a full user", () => {
const ctx = buildLDContext(userFixture());
diff --git a/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx b/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx
index 58d52483e7..a2a33314cf 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx
+++ b/autogpt_platform/frontend/src/services/feature-flags/feature-flag-provider.tsx
@@ -6,6 +6,7 @@ import * as Sentry from "@sentry/nextjs";
import { LDProvider } from "launchdarkly-react-client-sdk";
import type { ReactNode } from "react";
import { useMemo } from "react";
+import { getAnonymousID } from "../analytics/anonymous-id";
import { environment } from "../environment";
import { buildLDContext } from "./helpers";
@@ -18,7 +19,7 @@ export function LaunchDarklyProvider({ children }: { children: ReactNode }) {
const context = useMemo(() => {
if (isUserLoading) return;
- return buildLDContext(user);
+ return buildLDContext(user, getAnonymousID());
}, [user, isUserLoading]);
if (!envEnabled) {
diff --git a/autogpt_platform/frontend/src/services/feature-flags/helpers.ts b/autogpt_platform/frontend/src/services/feature-flags/helpers.ts
index 7f39e90c94..fc5c081bb6 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/helpers.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/helpers.ts
@@ -17,17 +17,41 @@ export type LDUserContext =
custom: { role?: string };
};
-// Mirror the context built by the backend
-// (feature_flag.py:_fetch_user_context_data) so LaunchDarkly targeting
-// rules evaluate identically on both sides.
+export interface LDDeviceContext {
+ kind: "device";
+ key: string;
+ anonymous: true;
+}
+
+export interface LDMultiContext {
+ kind: "multi";
+ user: LDUserContext;
+ device: LDDeviceContext;
+}
+
+export type LDContext = LDUserContext | LDMultiContext;
+
+// The `user` context mirrors the backend's
+// (feature_flag.py:_fetch_user_context_data), so rules on that kind evaluate
+// identically on both sides. The `device` context below is client-only.
//
// The auth session emits `Z`-suffixed ISO; backend emits `+00:00` — LD date matchers accept both.
-export function buildLDContext(user: User | null): LDUserContext {
+//
+// `anonymousID` is the first-party anonymous id shared with PostHog (see
+// services/analytics/anonymous-id.ts). Logged out, it is the user key, so
+// percentage rollouts are stable per visitor instead of identical for every
+// visitor. Logged in, it rides along as a `device` context so a rule that
+// buckets by device keeps the same arm across signup. Rules on the `user`
+// kind never see it.
+export function buildLDContext(
+ user: User | null,
+ anonymousID?: string | null,
+): LDContext {
if (!user) {
- return { kind: "user", key: "anonymous", anonymous: true };
+ return { kind: "user", key: anonymousID || "anonymous", anonymous: true };
}
- return {
+ const userContext: LDUserContext = {
kind: "user",
key: user.id,
anonymous: false,
@@ -41,4 +65,12 @@ export function buildLDContext(user: User | null): LDUserContext {
...(user.role && { role: user.role }),
},
};
+
+ if (!anonymousID) return userContext;
+
+ return {
+ kind: "multi",
+ user: userContext,
+ device: { kind: "device", key: anonymousID, anonymous: true },
+ };
}