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): flag our team and admin impersonation in PostHog (#15852)

Krzysztof Czerwinski97eb1d22c2e9
diff --git a/autogpt_platform/backend/backend/api/features/user/routes.py b/autogpt_platform/backend/backend/api/features/user/routes.py
index d20caabaf8..81354816e1 100644
--- a/autogpt_platform/backend/backend/api/features/user/routes.py
+++ b/autogpt_platform/backend/backend/api/features/user/routes.py
@@ -24,6 +24,7 @@ from backend.data.user import (
update_user_timezone,
verify_preference_token,
)
+from backend.notifications.posthog_audience import mark_internal_on_sign_in
from backend.util.exceptions import NotFoundError
from backend.util.settings import Settings
@@ -64,6 +65,9 @@ async def get_or_create_user_route(
result = await get_or_create_user_with_status(user_data)
response.headers[USER_CREATED_HEADER] = str(result.was_created).lower()
user = result.user
+ if not result.was_created:
+ # A new account was just sent its properties, `is_internal` included.
+ mark_internal_on_sign_in(user.id, user.email, user_data.get("role"))
# Fire-and-forget: populate business understanding from Tally form.
age_seconds = (datetime.now(timezone.utc) - user.created_at).total_seconds()
diff --git a/autogpt_platform/backend/backend/api/features/user/routes_test.py b/autogpt_platform/backend/backend/api/features/user/routes_test.py
index d2618f37f0..c09af54aee 100644
--- a/autogpt_platform/backend/backend/api/features/user/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/user/routes_test.py
@@ -130,6 +130,28 @@ def test_get_or_create_user_route_reports_creation(
assert response.headers["X-AutoGPT-User-Created"] == "true"
[email protected]("was_created", [False, True])
+def test_get_or_create_user_route_flags_an_internal_sign_in(
+ mocker: pytest_mock.MockFixture, test_user_id: str, was_created: bool
+) -> None:
+ """A sign-in sets is_internal again; a new account was sent it already."""
+ mock_user = Mock(id=test_user_id, email="[email protected]")
+ mock_user.created_at = datetime(2020, 1, 1, tzinfo=timezone.utc)
+ mock_user.model_dump.return_value = {"id": test_user_id}
+ mocker.patch(
+ "backend.api.features.user.routes.get_or_create_user_with_status",
+ return_value=Mock(user=mock_user, was_created=was_created),
+ )
+ mark = mocker.patch("backend.api.features.user.routes.mark_internal_on_sign_in")
+
+ assert client.post("/auth/user").status_code == 200
+
+ if was_created:
+ mark.assert_not_called()
+ else:
+ mark.assert_called_once_with(test_user_id, "[email protected]", "user")
+
+
def test_get_or_create_user_route_documents_creation_header() -> None:
response_schema = app.openapi()["paths"]["/auth/user"]["post"]["responses"]["200"]
diff --git a/autogpt_platform/backend/backend/api/middleware/analytics.py b/autogpt_platform/backend/backend/api/middleware/analytics.py
new file mode 100644
index 0000000000..a7a8c68983
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/middleware/analytics.py
@@ -0,0 +1,53 @@
+import re
+
+from autogpt_libs.auth.dependencies import IMPERSONATION_HEADER_NAME
+from starlette.datastructures import Headers
+from starlette.types import ASGIApp, Receive, Scope, Send
+
+from backend.util import posthog_client
+
+# The browser's PostHog session id, sent only with analytics consent
+# (frontend `posthog-session-header.ts`).
+POSTHOG_SESSION_HEADER_NAME = "X-PostHog-Session-Id"
+
+# PostHog's session ids are UUIDv7s; anything else is dropped, not forwarded.
+_SESSION_ID = re.compile(
+ r"[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",
+ re.IGNORECASE,
+)
+
+
+class AnalyticsContextMiddleware:
+ """Tell the PostHog client who a request's events are for
+ (`posthog_client.capture`): whether an admin is acting as the user, and
+ which browser session the request came from.
+
+ The impersonation header is read as it is: the auth dependencies refuse it
+ from anyone but an admin, and a request that names it without being one
+ can only mark its own events.
+ """
+
+ def __init__(self, app: ASGIApp):
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http":
+ await self.app(scope, receive, send)
+ return
+ headers = Headers(scope=scope)
+ impersonated = posthog_client.set_impersonated(
+ bool(headers.get(IMPERSONATION_HEADER_NAME, "").strip())
+ )
+ session_id = posthog_client.set_session_id(
+ _valid_session_id(headers.get(POSTHOG_SESSION_HEADER_NAME))
+ )
+ try:
+ await self.app(scope, receive, send)
+ finally:
+ posthog_client.reset_session_id(session_id)
+ posthog_client.reset_impersonated(impersonated)
+
+
+def _valid_session_id(value: str | None) -> str | None:
+ value = (value or "").strip()
+ return value if _SESSION_ID.fullmatch(value) else None
diff --git a/autogpt_platform/backend/backend/api/middleware/analytics_test.py b/autogpt_platform/backend/backend/api/middleware/analytics_test.py
new file mode 100644
index 0000000000..8a3c33a67b
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/middleware/analytics_test.py
@@ -0,0 +1,82 @@
+"""A request's PostHog events say whether an admin made it as the user, and
+join the browser session it names; nothing carries over to the next request."""
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from backend.api.middleware.analytics import AnalyticsContextMiddleware
+from backend.util import posthog_client
+
+SESSION = "0192f0c4-5f4e-7b4c-9d6e-1a2b3c4d5e6f"
+
+
+def client() -> TestClient:
+ app = FastAPI()
+ app.add_middleware(AnalyticsContextMiddleware)
+
+ @app.get("/context")
+ async def context():
+ return {
+ "impersonated": posthog_client.is_impersonated(),
+ "session_id": posthog_client._session_id.get(),
+ }
+
+ @app.get("/sync-context")
+ def sync_context():
+ return {"impersonated": posthog_client.is_impersonated()}
+
+ return TestClient(app)
+
+
+def test_a_request_an_admin_makes_as_the_user_is_impersonated(client: TestClient):
+ response = client.get("/context", headers={"X-Act-As-User-Id": "user-1"})
+ assert response.json()["impersonated"] is True
+
+ # A sync route runs on a worker thread, which sees the mark too.
+ response = client.get("/sync-context", headers={"X-Act-As-User-Id": "user-1"})
+ assert response.json()["impersonated"] is True
+
+
+def test_a_users_own_request_is_not(client: TestClient):
+ assert client.get("/context").json() == {
+ "impersonated": False,
+ "session_id": None,
+ }
+ assert (
+ client.get("/context", headers={"X-Act-As-User-Id": " "}).json()["impersonated"]
+ is False
+ )
+
+
[email protected]("value", [SESSION, SESSION.upper()])
+def test_a_request_joins_the_browser_session_it_names(client: TestClient, value):
+ response = client.get("/context", headers={"X-PostHog-Session-Id": value})
+ assert response.json()["session_id"] == value
+
+
+ "value",
+ [
+ "",
+ "not a session",
+ "a" * 65,
+ "<script>",
+ # A UUIDv4, and a v7 with a bad variant.
+ "0192f0c4-5f4e-4b4c-9d6e-1a2b3c4d5e6f",
+ "0192f0c4-5f4e-7b4c-cd6e-1a2b3c4d5e6f",
+ ],
+)
+def test_a_malformed_session_id_is_dropped(client: TestClient, value: str):
+ response = client.get("/context", headers={"X-PostHog-Session-Id": value})
+ assert response.json()["session_id"] is None
+
+
+def test_nothing_carries_over_after_the_request(client: TestClient):
+ client.get(
+ "/context",
+ headers={"X-Act-As-User-Id": "user-1", "X-PostHog-Session-Id": SESSION},
+ )
+ assert posthog_client.is_impersonated() is False
+ assert posthog_client._session_id.get() is None
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 44c4513f20..a847d3c998 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -120,6 +120,7 @@ from backend.util.workspace_storage import shutdown_workspace_storage
from .external.fastapi_app import external_api
from .features.analytics import router as analytics_router
from .features.integrations.router import router as integrations_router
+from .middleware.analytics import AnalyticsContextMiddleware
from .middleware.security import SecurityHeadersMiddleware
from .utils.cors import build_cors_params
from .utils.openapi import sort_openapi
@@ -283,6 +284,9 @@ app = fastapi.FastAPI(
)
app.add_middleware(SecurityHeadersMiddleware)
+# Marks the PostHog events of an admin acting as a user, and joins a request's
+# events to the browser's PostHog session.
+app.add_middleware(AnalyticsContextMiddleware)
# Add GZip compression middleware for large responses (like /api/blocks)
app.add_middleware(GZipMiddleware, minimum_size=50_000) # 50KB threshold
diff --git a/autogpt_platform/backend/backend/cli/posthog_audience_backfill.py b/autogpt_platform/backend/backend/cli/posthog_audience_backfill.py
index 2491603334..5a3a584418 100644
--- a/autogpt_platform/backend/backend/cli/posthog_audience_backfill.py
+++ b/autogpt_platform/backend/backend/cli/posthog_audience_backfill.py
@@ -9,8 +9,9 @@ if TYPE_CHECKING:
_ACCOUNTS = """
SELECT u."id" AS user_id, u."email", u."createdAt" AS created_at,
- u."timezone", u."stripeCustomerId" AS stripe_customer_id
+ u."timezone", u."stripeCustomerId" AS stripe_customer_id, a."role"
FROM {schema_prefix}"User" u
+ LEFT JOIN {schema_prefix}"UserAuthIdentity" a ON a."id" = u."id"
"""
@@ -21,7 +22,8 @@ def posthog_audience_backfill_command(apply: bool, yes: bool):
"""Give existing accounts the PostHog person properties that mirror
MailerLite's segmentation (SECRT-2895).
- Every account gets email_type and signin_method. Every account with a
+ Every account gets email_type, signin_method and is_internal (true for
+ an admin or an @agpt.co email, SECRT-2728). Every account with a
Stripe Checkout Session also gets checkout_opened_at, country,
country_code, country_source and exclude_de_at, worked out as
mailerlite-checkout-backfill works them out: from the Stripe billing
@@ -98,6 +100,7 @@ def _report(plan: "AudiencePlan") -> None:
click.echo(f"Accounts: {len(plan.updates)}")
click.echo(f" email_type: {_counts(plan.email_types)}")
click.echo(f" signin_method: {_counts(plan.signin_methods)}")
+ click.echo(f" is_internal true: {plan.internal}")
click.echo(f"Checkout openers (a Stripe Checkout Session): {plan.openers}")
click.echo(f" country_source: {_counts(plan.country_sources)}")
click.echo(f" exclude_de_at yes: {plan.exclude_de_at}")
diff --git a/autogpt_platform/backend/backend/cli/posthog_audience_backfill_db_test.py b/autogpt_platform/backend/backend/cli/posthog_audience_backfill_db_test.py
index eca9825545..2140277c06 100644
--- a/autogpt_platform/backend/backend/cli/posthog_audience_backfill_db_test.py
+++ b/autogpt_platform/backend/backend/cli/posthog_audience_backfill_db_test.py
@@ -14,12 +14,17 @@ from backend.util.test import SpinTestServer
@pytest.fixture
async def account(server: SpinTestServer):
- """An account with an email sign-in, a browser timezone and a Stripe
- customer."""
+ """An admin account with an email sign-in, a browser timezone and a
+ Stripe customer."""
user_id = str(uuid4())
email = f"{user_id}@example.com"
await AuthUser.prisma().create(
- data={"id": user_id, "name": "PostHog backfill", "email": email}
+ data={
+ "id": user_id,
+ "name": "PostHog backfill",
+ "email": email,
+ "role": "admin",
+ }
)
await AuthAccount.prisma().create(
data={
@@ -51,6 +56,7 @@ async def test_every_account_is_read_with_what_its_plan_needs(account: str):
assert row.timezone == "Europe/Vienna"
assert row.stripe_customer_id == f"cus_{account}"
assert row.created_at is not None
+ assert row.role == "admin"
@pytest.mark.asyncio(loop_scope="session")
diff --git a/autogpt_platform/backend/backend/cli/posthog_audience_backfill_test.py b/autogpt_platform/backend/backend/cli/posthog_audience_backfill_test.py
index 9299e64cbf..bf8d4431bd 100644
--- a/autogpt_platform/backend/backend/cli/posthog_audience_backfill_test.py
+++ b/autogpt_platform/backend/backend/cli/posthog_audience_backfill_test.py
@@ -78,6 +78,7 @@ async def test_a_dry_run_reports_counts_and_sends_nothing(wired: AsyncMock, caps
assert "Accounts: 3" in out
assert "email_type: business=2, personal=1" in out
assert "signin_method: none=2, google=1" in out
+ assert "is_internal true: 0" in out
assert "Checkout openers (a Stripe Checkout Session): 1" in out
assert "country_source: stripe=1" in out
assert "exclude_de_at yes: 1" in out
diff --git a/autogpt_platform/backend/backend/copilot/llm_attribution.py b/autogpt_platform/backend/backend/copilot/llm_attribution.py
index 20e1370c9f..cee6003e2a 100644
--- a/autogpt_platform/backend/backend/copilot/llm_attribution.py
+++ b/autogpt_platform/backend/backend/copilot/llm_attribution.py
@@ -32,6 +32,7 @@ from typing import Any, Literal
from autogpt_libs.auth.dependencies import IMPERSONATION_HEADER_NAME
from fastapi import Request
+from backend.util import posthog_client
from backend.util.settings import Settings
settings = Settings()
@@ -42,10 +43,6 @@ _MAX_ID_CHARS = 128
GenerationName = Literal["copilot-title", "copilot-sdk", "copilot-baseline"]
-# Whether an admin impersonating the user started the running turn. The
-# executor sets it for every turn, so a value never carries over.
-_turn_impersonated: ContextVar[bool] = ContextVar("_turn_impersonated", default=False)
-
# The running turn's trace, sent as the trace id of every call it makes. The
# executor sets it for every turn, so a value never carries over; a call made
# outside a turn sends none.
@@ -80,12 +77,16 @@ def openrouter_attribution(
def set_turn_impersonated(impersonated: bool) -> None:
- """Mark the running turn as started by an impersonating admin, or not."""
- _turn_impersonated.set(impersonated)
+ """Mark the running turn as started by an impersonating admin, or not.
+
+ The mark is the PostHog client's, so every event the turn sends carries
+ it too. The executor sets it for every turn, so a value never carries
+ over."""
+ posthog_client.set_impersonated(impersonated)
def is_turn_impersonated() -> bool:
- return _turn_impersonated.get()
+ return posthog_client.is_impersonated()
def set_turn_trace_id(trace_id: str | None) -> None:
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.py
index 00b17bc490..bbd02ec3ba 100644
--- a/autogpt_platform/backend/backend/data/user.py
+++ b/autogpt_platform/backend/backend/data/user.py
@@ -136,7 +136,9 @@ async def _get_or_create_user(user_data: dict) -> UserCreationResult:
if was_created:
signup_method = await _signup_method(user.id, user_data)
track_signup_completed(user_id=user.id, signup_method=signup_method)
- set_account_properties(user.id, user.email, signup_method)
+ set_account_properties(
+ user.id, user.email, signup_method, user_data.get("role")
+ )
schedule_posthog_lifecycle_sync(user.id)
return UserCreationResult(user=User.from_db(user), was_created=was_created)
diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.py
index 0caa987786..56173d8632 100644
--- a/autogpt_platform/backend/backend/data/user_test.py
+++ b/autogpt_platform/backend/backend/data/user_test.py
@@ -1308,15 +1308,18 @@ class TestGetOrCreateUserStatus:
)
result = await user_module.get_or_create_user_with_status(
- {"sub": "user-hooked", "email": "[email protected]"}
+ {"sub": "user-hooked", "email": "[email protected]", "role": "admin"}
)
assert result.was_created is True
mock_prisma.user.create.assert_not_called()
posthog_sync.assert_called_once_with("user-hooked")
track.assert_called_once_with(user_id="user-hooked", signup_method="email")
- # The email type and sign-in method MailerLite segments on.
- person.assert_called_once_with("user-hooked", "[email protected]", "email")
+ # The email type and sign-in method MailerLite segments on, and the
+ # token's role, which flags our own team.
+ person.assert_called_once_with(
+ "user-hooked", "[email protected]", "email", "admin"
+ )
@pytest.mark.asyncio
async def test_a_row_created_concurrently_is_read_back_not_an_error(self):
diff --git a/autogpt_platform/backend/backend/notifications/posthog_audience.py b/autogpt_platform/backend/backend/notifications/posthog_audience.py
index ba66f8b426..fa7020a330 100644
--- a/autogpt_platform/backend/backend/notifications/posthog_audience.py
+++ b/autogpt_platform/backend/backend/notifications/posthog_audience.py
@@ -5,6 +5,9 @@ and GTM segments on it. PostHog gets the same values as person properties
(SECRT-2895), so funnels, retention and experiments split the same way:
- `email_type` and `signin_method`: every account, from signup;
+- `is_internal`: every account, from signup, and again at each sign-in of an
+ internal one (our team: an admin, or an @agpt.co email), so a project
+ filter can leave our own team out of every insight (PostHog only);
- `checkout_opened_at`, `country`, `country_code`, `country_source` and
`exclude_de_at`: every checkout opener. The open is an ISO-8601 UTC moment,
like the lifecycle dates, where MailerLite holds the day.
@@ -30,7 +33,7 @@ fills in what the person doesn't hold yet, keeps the same rules:
"""
import logging
-from collections.abc import Iterable
+from collections.abc import Iterable, Mapping
from datetime import datetime
from posthog import Posthog
@@ -50,6 +53,9 @@ from backend.util.posthog_events import PostHogEvent
logger = logging.getLogger(__name__)
CHECKOUT_OPENED_AT = "checkout_opened_at"
+IS_INTERNAL = "is_internal"
+
+_INTERNAL_EMAIL_DOMAIN = "@agpt.co"
# Always `$set`: the account's current values, under MailerLite's own keys.
_ALWAYS_SET = (SubscriberField.EMAIL_TYPE, SubscriberField.SIGNIN_METHOD)
@@ -85,10 +91,10 @@ class PersonUpdate(BaseModel):
"""One `$set` event: values that replace the person's, and values that
only fill in ones the person doesn't hold yet."""
- to_set: dict[str, str] = Field(default_factory=dict)
+ to_set: dict[str, str | bool] = Field(default_factory=dict)
to_set_once: dict[str, str] = Field(default_factory=dict)
- def properties(self) -> dict[str, dict[str, str]]:
+ def properties(self) -> dict[str, Mapping[str, str | bool]]:
return {
key: values
for key, values in (("$set", self.to_set), ("$set_once", self.to_set_once))
@@ -96,16 +102,36 @@ class PersonUpdate(BaseModel):
}
-def set_account_properties(user_id: str, email: str, signup_method: str | None) -> None:
- """A new account's email type and sign-in method. Never raises: analytics
- must not fail a signup."""
+def is_internal(email: str, role: str | None) -> bool:
+ """Whether the account is our own team's: an admin, or an @agpt.co
+ email."""
+ return role == "admin" or email.strip().lower().endswith(_INTERNAL_EMAIL_DOMAIN)
+
+
+def set_account_properties(
+ user_id: str, email: str, signup_method: str | None, role: str | None = None
+) -> None:
+ """A new account's email type, sign-in method and whether it is our
+ team's. `role` is the token's. Never raises: analytics must not fail a
+ signup."""
try:
providers = [signup_method] if signup_method else []
- send(user_id, account_update(email, providers))
+ send(user_id, account_update(email, providers, role))
except Exception:
logger.warning(f"Could not set the PostHog account properties of {user_id}")
+def mark_internal_on_sign_in(user_id: str, email: str, role: str | None) -> None:
+ """Set `is_internal` again when an internal account signs in, so one made
+ an admin after signup is flagged from their next sign-in. Nothing is sent
+ for anyone else. Never raises."""
+ try:
+ if is_internal(email, role):
+ send(user_id, PersonUpdate(to_set={IS_INTERNAL: True}))
+ except Exception:
+ logger.warning(f"Could not set is_internal on the PostHog person {user_id}")
+
+
def set_checkout_properties(
user_id: str, fields: Fields, opened_at: datetime | int | float | None
) -> None:
@@ -117,8 +143,15 @@ def set_checkout_properties(
logger.warning(f"Could not set the PostHog checkout properties of {user_id}")
-def account_update(email: str, signin_providers: Iterable[str]) -> PersonUpdate:
- update = PersonUpdate(to_set={SubscriberField.EMAIL_TYPE.value: email_type(email)})
+def account_update(
+ email: str, signin_providers: Iterable[str], role: str | None = None
+) -> PersonUpdate:
+ update = PersonUpdate(
+ to_set={
+ SubscriberField.EMAIL_TYPE.value: email_type(email),
+ IS_INTERNAL: is_internal(email, role),
+ }
+ )
if method := signin_method(signin_providers):
update.to_set[SubscriberField.SIGNIN_METHOD.value] = method
return update
diff --git a/autogpt_platform/backend/backend/notifications/posthog_audience_backfill.py b/autogpt_platform/backend/backend/notifications/posthog_audience_backfill.py
index a8043419ed..4e59734928 100644
--- a/autogpt_platform/backend/backend/notifications/posthog_audience_backfill.py
+++ b/autogpt_platform/backend/backend/notifications/posthog_audience_backfill.py
@@ -1,7 +1,7 @@
"""Give accounts from before SECRT-2895 the PostHog person properties the live
-code sends since (`posthog_audience`): every account its email type and
-sign-in method, and every checkout opener its first open, country and
-exclude_de_at.
+code sends since (`posthog_audience`): every account its email type, sign-in
+method and `is_internal` (SECRT-2728), and every checkout opener its first
+open, country and exclude_de_at.
An opener is an account whose Stripe customer has a Checkout Session, as for
`mailerlite-checkout-backfill`, and is worked out the same way
@@ -28,7 +28,12 @@ from pydantic import BaseModel
from backend.data.notifications import SubscriberField
from backend.notifications import posthog_audience
from backend.notifications.audience_enrichment import YES, checkout_fields
-from backend.notifications.posthog_audience import CHECKOUT_OPENED_AT, PersonUpdate
+from backend.notifications.posthog_audience import (
+ CHECKOUT_OPENED_AT,
+ IS_INTERNAL,
+ PersonUpdate,
+ is_internal,
+)
from backend.util.posthog_client import send_each
NONE = "none"
@@ -40,6 +45,8 @@ class Account(BaseModel):
created_at: datetime
timezone: str | None = None
stripe_customer_id: str | None = None
+ # The auth identity's role (`admin` for our admins).
+ role: str | None = None
class AccountUpdate(BaseModel):
@@ -55,6 +62,8 @@ class AudiencePlan(BaseModel):
# the person holds none yet, so these aren't what PostHog will hold.
email_types: dict[str, int]
signin_methods: dict[str, int]
+ # Accounts sent `is_internal` true.
+ internal: int
# Openers only.
country_sources: dict[str, int]
exclude_de_at: int
@@ -90,7 +99,7 @@ def _update(
billing_country: str | None,
) -> PersonUpdate:
if first_open is None:
- return posthog_audience.account_update(account.email, providers)
+ return posthog_audience.account_update(account.email, providers, account.role)
fields = checkout_fields(
email=account.email,
created_at=account.created_at,
@@ -99,22 +108,26 @@ def _update(
timezone=account.timezone,
stripe_country=billing_country,
)
- return posthog_audience.checkout_update(fields, first_open, first_open=True)
+ update = posthog_audience.checkout_update(fields, first_open, first_open=True)
+ update.to_set[IS_INTERNAL] = is_internal(account.email, account.role)
+ return update
def _tally(updates: list[AccountUpdate]) -> AudiencePlan:
email_types: Counter[str] = Counter()
signin_methods: Counter[str] = Counter()
sources: Counter[str] = Counter()
- openers = exclude_de_at = 0
+ openers = exclude_de_at = internal = 0
for change in updates:
values = {**change.update.to_set_once, **change.update.to_set}
- email_types[values.get(SubscriberField.EMAIL_TYPE.value, NONE)] += 1
- signin_methods[values.get(SubscriberField.SIGNIN_METHOD.value, NONE)] += 1
+ email_types[str(values.get(SubscriberField.EMAIL_TYPE.value, NONE))] += 1
+ signin_methods[str(values.get(SubscriberField.SIGNIN_METHOD.value, NONE))] += 1
+ if values.get(IS_INTERNAL) is True:
+ internal += 1
if CHECKOUT_OPENED_AT not in values:
continue
openers += 1
- sources[values.get(SubscriberField.COUNTRY_SOURCE.value, NONE)] += 1
+ sources[str(values.get(SubscriberField.COUNTRY_SOURCE.value, NONE))] += 1
if values.get(SubscriberField.EXCLUDE_DE_AT.value) == YES:
exclude_de_at += 1
return AudiencePlan(
@@ -122,6 +135,7 @@ def _tally(updates: list[AccountUpdate]) -> AudiencePlan:
openers=openers,
email_types=dict(email_types),
signin_methods=dict(signin_methods),
+ internal=internal,
country_sources=dict(sources),
exclude_de_at=exclude_de_at,
)
diff --git a/autogpt_platform/backend/backend/notifications/posthog_audience_backfill_test.py b/autogpt_platform/backend/backend/notifications/posthog_audience_backfill_test.py
index 52d9a786c8..f893749759 100644
--- a/autogpt_platform/backend/backend/notifications/posthog_audience_backfill_test.py
+++ b/autogpt_platform/backend/backend/notifications/posthog_audience_backfill_test.py
@@ -1,5 +1,5 @@
-"""The PostHog backfill gives every account its email type and sign-in method,
-and every checkout opener what the live checkout sends, by the same rules,
+"""The PostHog backfill gives every account its email type, sign-in method and
+whether it is our team's, and every checkout opener what the live checkout sends, by the same rules,
except that Stripe's first open is set outright."""
from collections.abc import Iterator
@@ -46,9 +46,17 @@ ACCOUNTS = [
created_at=CREATED,
timezone="Europe/Moscow",
),
+ Account(user_id="teammate", email="[email protected]", created_at=CREATED),
+ Account(
+ user_id="admin-opener",
+ created_at=CREATED,
+ stripe_customer_id="cus_4",
+ role="admin",
+ ),
]
PROVIDERS = {"billed": ["google", "credential"], "opened-only": ["credential"]}
-FIRST_OPENS = {"cus_1": OPENED, "cus_2": OPENED + 60}
+FIRST_OPENS = {"cus_1": OPENED, "cus_2": OPENED + 60, "cus_4": OPENED}
BILLING = {"cus_1": "US", "cus_3": "FR"}
@@ -59,8 +67,8 @@ def _plan():
def test_every_account_is_planned_and_only_openers_get_the_checkout_fields():
plan = _plan()
updates = {change.user_id: change.update for change in plan.updates}
- assert len(updates) == 4
- assert plan.openers == 2
+ assert len(updates) == 6
+ assert plan.openers == 3
billed = updates["billed"]
assert billed.to_set["country_code"] == "US"
@@ -74,17 +82,32 @@ def test_every_account_is_planned_and_only_openers_get_the_checkout_fields():
assert opened_only.to_set["exclude_de_at"] == "yes"
# A Stripe customer is not an opener without a Checkout Session.
- assert updates["customer-without-session"].to_set == {"email_type": "education"}
+ assert updates["customer-without-session"].to_set == {
+ "email_type": "education",
+ "is_internal": False,
+ }
assert updates["customer-without-session"].to_set_once == {}
# A signal in Russia keeps an account out of MailerLite, not PostHog.
- assert updates["never-a-customer"].to_set == {"email_type": "business"}
+ assert updates["never-a-customer"].to_set == {
+ "email_type": "business",
+ "is_internal": False,
+ }
+
+
+def test_our_team_is_planned_as_internal_with_or_without_a_checkout():
+ plan = _plan()
+ updates = {change.user_id: change.update for change in plan.updates}
+ assert updates["teammate"].to_set["is_internal"] is True
+ assert updates["admin-opener"].to_set["is_internal"] is True
+ assert updates["billed"].to_set["is_internal"] is False
+ assert plan.internal == 2
def test_the_plan_counts_what_the_accounts_end_up_with():
plan = _plan()
- assert plan.email_types == {"business": 2, "personal": 1, "education": 1}
- assert plan.signin_methods == {"google": 1, "email": 1, "none": 2}
- assert plan.country_sources == {"stripe": 1, "timezone": 1}
+ assert plan.email_types == {"business": 4, "personal": 1, "education": 1}
+ assert plan.signin_methods == {"google": 1, "email": 1, "none": 4}
+ assert plan.country_sources == {"stripe": 1, "timezone": 1, "none": 1}
assert plan.exclude_de_at == 1
@@ -105,6 +128,7 @@ def test_an_opener_gets_what_the_live_checkout_sends():
)
planned = next(c.update for c in _plan().updates if c.user_id == "billed")
assert planned.to_set.pop(CHECKOUT_OPENED_AT) == OPENED_ISO
+ assert planned.to_set.pop("is_internal") is False
assert live.to_set_once.pop(CHECKOUT_OPENED_AT) == OPENED_ISO
assert planned == live
diff --git a/autogpt_platform/backend/backend/notifications/posthog_audience_test.py b/autogpt_platform/backend/backend/notifications/posthog_audience_test.py
index 206cd08c5e..f5c7cb0cdc 100644
--- a/autogpt_platform/backend/backend/notifications/posthog_audience_test.py
+++ b/autogpt_platform/backend/backend/notifications/posthog_audience_test.py
@@ -75,14 +75,14 @@ def _person(*updates: PersonUpdate) -> dict[str, str]:
(
["credential"],
- {"email_type": "business", "signin_method": "email"},
+ {"email_type": "business", "signin_method": "email", "is_internal": False},
),
(
["credential", "google"],
- {"email_type": "personal", "signin_method": "google"},
+ {"email_type": "personal", "signin_method": "google", "is_internal": False},
),
- ("[email protected]", [], {"email_type": "education"}),
+ ("[email protected]", [], {"email_type": "education", "is_internal": False}),
],
)
def test_an_account_gets_its_email_type_and_sign_in_method(email, providers, expected):
@@ -106,6 +106,43 @@ def test_a_new_account_is_sent_from_its_signup_method(
assert person.get("signin_method") == expected
+# ── our own team ─────────────────────────────────────────────────────────────
+
+
+ "email, role, expected",
+ [
+ ("[email protected]", None, True),
+ ("[email protected] ", "authenticated", True),
+ ("[email protected]", "admin", True),
+ ("[email protected]", "authenticated", False),
+ ("[email protected]", None, False),
+ ("[email protected]", None, False),
+ ],
+)
+def test_an_admin_or_a_company_email_is_internal(email, role, expected):
+ assert posthog_audience.is_internal(email, role) is expected
+ update = posthog_audience.account_update(email, [], role)
+ assert update.to_set["is_internal"] is expected
+
+
+def test_a_new_admin_account_is_sent_as_internal(capture: Mock):
+ posthog_audience.set_account_properties("user-1", "[email protected]", "email", "admin")
+ assert capture.call_args.kwargs["properties"]["$set"]["is_internal"] is True
+
+
+def test_an_internal_sign_in_sets_is_internal_again(capture: Mock):
+ posthog_audience.mark_internal_on_sign_in("user-1", "[email protected]", "admin")
+ kwargs = capture.call_args.kwargs
+ assert kwargs["distinct_id"] == "user-1"
+ assert kwargs["properties"]["$set"] == {"is_internal": True}
+
+
+def test_anyone_else_signing_in_sends_nothing(capture: Mock):
+ posthog_audience.mark_internal_on_sign_in("user-1", "[email protected]", "authenticated")
+ capture.assert_not_called()
+
+
# ── checkout openers ─────────────────────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/util/posthog_client.py b/autogpt_platform/backend/backend/util/posthog_client.py
index 5702635aa4..5ca56643f8 100644
--- a/autogpt_platform/backend/backend/util/posthog_client.py
+++ b/autogpt_platform/backend/backend/util/posthog_client.py
@@ -8,12 +8,21 @@ treats a missing client as "analytics disabled" and never lets tracking
raise into the request or execution that produced the event. Every client
built here also stamps ``revision`` on everything it sends (see
:func:`revision_properties`).
+
+:func:`capture` also reads who the running work is for. An admin acting as
+the user (``X-Act-As-User-Id``, or a chat turn such an admin started) marks
+every event ``impersonated`` and sends no person properties, so the admin's
+clicks never land in the user's numbers or change their person. A request
+from the browser can name its PostHog session, which every event the request
+sends joins as ``$session_id``. ``api/middleware/analytics.py`` sets both
+for a request, the chat executor the first for a turn.
"""
import asyncio
import atexit
import logging
from collections.abc import Callable, Iterable, Mapping
+from contextvars import ContextVar, Token
from datetime import datetime
from functools import cache
from threading import Lock
@@ -113,6 +122,36 @@ async def send_each(sends: Iterable[Send]) -> int:
return len(failed)
+# Whether an admin acting as the user caused the work running now.
+_impersonated: ContextVar[bool] = ContextVar("posthog_impersonated", default=False)
+# The browser's PostHog session for the request running now.
+_session_id: ContextVar[str | None] = ContextVar("posthog_session_id", default=None)
+
+
+def set_impersonated(impersonated: bool) -> Token[bool]:
+ """Mark the work running now as done by an admin acting as the user, or
+ not. Returns the token that undoes it."""
+ return _impersonated.set(impersonated)
+
+
+def reset_impersonated(token: Token[bool]) -> None:
+ _impersonated.reset(token)
+
+
+def is_impersonated() -> bool:
+ return _impersonated.get()
+
+
+def set_session_id(session_id: str | None) -> Token[str | None]:
+ """Make *session_id* the browser session the running request's events
+ join. Returns the token that undoes it."""
+ return _session_id.set(session_id or None)
+
+
+def reset_session_id(token: Token[str | None]) -> None:
+ _session_id.reset(token)
+
+
@cache
def _environment() -> str:
return Settings().config.app_env.value
@@ -136,6 +175,12 @@ def capture(
nobody can merge. The base properties are applied last, so a caller can
never overwrite ``environment`` or ``source`` by accident.
+ Work an admin does as the user is sent with ``impersonated`` true, and its
+ ``$set_person_properties`` events are not sent at all: the person's
+ properties describe the user, not the admin acting for them. A request
+ that named its browser session adds ``$session_id``, unless the caller set
+ one.
+
``dedup_key`` is an idempotency key for a redelivery or requeue that can
send the same event twice; it is carried both as ``$insert_id`` and as a
deterministic event uuid, because PostHog's ingestion keys on the uuid,
@@ -149,6 +194,9 @@ def capture(
event_name = "<unknown>"
try:
event_name = event.value
+ impersonated = is_impersonated()
+ if impersonated and event is PostHogEvent.SET_PERSON_PROPERTIES:
+ return False
if client is None:
client = get_posthog_client()
if client is None:
@@ -158,6 +206,10 @@ def capture(
"environment": _environment(),
"source": source,
}
+ if impersonated:
+ payload["impersonated"] = True
+ if session_id := _session_id.get():
+ payload.setdefault("$session_id", session_id)
event_uuid = None
if dedup_key is not None:
payload["$insert_id"] = dedup_key
diff --git a/autogpt_platform/backend/backend/util/posthog_client_test.py b/autogpt_platform/backend/backend/util/posthog_client_test.py
index 0b2a0fc7f4..71f926cd0b 100644
--- a/autogpt_platform/backend/backend/util/posthog_client_test.py
+++ b/autogpt_platform/backend/backend/util/posthog_client_test.py
@@ -383,3 +383,65 @@ def test_capture_dedup_key_is_insert_id_and_a_stable_uuid(
assert kwargs["uuid"] == str(
uuid.uuid5(uuid.NAMESPACE_URL, "user-1:briefing_delivered:briefing:b-1")
)
+
+
+def shared_client(monkeypatch: pytest.MonkeyPatch) -> Mock:
+ client = Mock()
+ monkeypatch.setattr(posthog_client, "get_posthog_client", lambda: client)
+ monkeypatch.setattr(posthog_client, "_environment", lambda: "prod")
+ return client
+
+
+def test_an_event_an_admin_caused_as_the_user_is_marked(shared_client: Mock) -> None:
+ token = posthog_client.set_impersonated(True)
+ try:
+ posthog_client.capture(
+ "user-1", PostHogEvent.AGENT_RUN_STARTED, {"impersonated": False}
+ )
+ finally:
+ posthog_client.reset_impersonated(token)
+
+ assert shared_client.capture.call_args.kwargs["properties"]["impersonated"] is True
+
+
+def test_an_event_the_user_caused_carries_no_mark(shared_client: Mock) -> None:
+ posthog_client.capture("user-1", PostHogEvent.AGENT_RUN_STARTED)
+
+ assert "impersonated" not in shared_client.capture.call_args.kwargs["properties"]
+
+
+def test_an_admin_acting_as_the_user_never_sets_their_person(
+ shared_client: Mock,
+) -> None:
+ token = posthog_client.set_impersonated(True)
+ try:
+ queued = posthog_client.capture(
+ "user-1",
+ PostHogEvent.SET_PERSON_PROPERTIES,
+ {"$set": {"onboarding_role": "Other"}},
+ )
+ finally:
+ posthog_client.reset_impersonated(token)
+
+ assert queued is False
+ shared_client.capture.assert_not_called()
+
+
+def test_an_event_joins_the_browser_session_of_its_request(
+ shared_client: Mock,
+) -> None:
+ token = posthog_client.set_session_id("0192f0c4-5f4e-7b4c-9d6e-1a2b3c4d5e6f")
+ try:
+ posthog_client.capture("user-1", PostHogEvent.AGENT_RUN_STARTED)
+ posthog_client.capture(
+ "user-1", PostHogEvent.AGENT_RUN_STARTED, {"$session_id": "own"}
+ )
+ finally:
+ posthog_client.reset_session_id(token)
+ posthog_client.capture("user-1", PostHogEvent.AGENT_RUN_STARTED)
+
+ sent = [c.kwargs["properties"] for c in shared_client.capture.call_args_list]
+ assert sent[0]["$session_id"] == "0192f0c4-5f4e-7b4c-9d6e-1a2b3c4d5e6f"
+ assert sent[1]["$session_id"] == "own"
+ assert "$session_id" not in sent[2]
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
index f759c8414a..7f23b7b549 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/helpers.test.ts
@@ -32,8 +32,13 @@ vi.mock("@/lib/impersonation", () => ({
getSystemHeaders: vi.fn(),
}));
+vi.mock("@/services/analytics/posthog-request-context", () => ({
+ getPostHogSessionHeader: vi.fn(() => ({})),
+}));
+
import { getWebSocketToken } from "@/lib/auth/actions";
import { getSystemHeaders } from "@/lib/impersonation";
+import { getPostHogSessionHeader } from "@/services/analytics/posthog-request-context";
const mockGetWebSocketToken = vi.mocked(getWebSocketToken);
const mockGetSystemHeaders = vi.mocked(getSystemHeaders);
@@ -858,6 +863,23 @@ describe("getCopilotAuthHeaders", () => {
expect(headers).toEqual({ Authorization: "Bearer test-jwt-token" });
});
+ it("names the browser's PostHog session so the chat's events join it", async () => {
+ mockGetWebSocketToken.mockResolvedValue({
+ token: "test-jwt-token",
+ error: undefined,
+ });
+ vi.mocked(getPostHogSessionHeader).mockReturnValueOnce({
+ "X-PostHog-Session-Id": "posthog-session-1",
+ });
+
+ const headers = await getCopilotAuthHeaders();
+
+ expect(headers).toEqual({
+ Authorization: "Bearer test-jwt-token",
+ "X-PostHog-Session-Id": "posthog-session-1",
+ });
+ });
+
it("includes X-Act-As-User-Id header when impersonation is active", async () => {
mockGetWebSocketToken.mockResolvedValue({
token: "test-jwt-token",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
index 5c907d04c9..9647097579 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts
@@ -1,4 +1,5 @@
import { getSystemHeaders } from "@/lib/impersonation";
+import { getPostHogSessionHeader } from "@/services/analytics/posthog-request-context";
import { getWebSocketToken } from "@/lib/auth/actions";
import type { ChatStatus, UIMessage } from "ai";
@@ -25,6 +26,8 @@ export const COPILOT_COMPLETION_NOTIFICATION = {
* Returns HTTP headers required for direct backend requests from copilot:
* - Authorization Bearer token (JWT)
* - X-Act-As-User-Id impersonation header (if an admin is impersonating a user)
+ * - X-PostHog-Session-Id (with analytics consent), so the chat's backend
+ * events join the browser's PostHog session
*
* Use this for all direct-to-backend fetch/SSE calls so that admin user
* impersonation works consistently across the entire copilot feature.
@@ -38,6 +41,7 @@ export async function getCopilotAuthHeaders(): Promise<Record<string, string>> {
return {
Authorization: `Bearer ${token}`,
...getSystemHeaders(),
+ ...getPostHogSessionHeader(),
};
}
diff --git a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
index fef9eefac8..b6afa00de4 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
@@ -26,6 +26,10 @@ vi.mock("@/lib/autogpt-server-api/helpers", () => ({
getServerAuthToken: vi.fn(),
}));
+vi.mock("@/services/analytics/posthog-request-context", () => ({
+ getPostHogSessionHeader: vi.fn(() => ({})),
+}));
+
vi.mock("@sentry/nextjs", () => ({
getTraceData: vi.fn(() => ({})),
captureMessage: vi.fn(),
@@ -37,6 +41,7 @@ import { getSystemHeaders } from "@/lib/impersonation";
import { environment } from "@/services/environment";
import { IMPERSONATION_HEADER_NAME } from "@/lib/constants";
import * as Sentry from "@sentry/nextjs";
+import { getPostHogSessionHeader } from "@/services/analytics/posthog-request-context";
const mockIsClientSide = vi.mocked(environment.isClientSide);
const mockGetSystemHeaders = vi.mocked(getSystemHeaders);
@@ -70,6 +75,20 @@ describe("customMutator — impersonation header", () => {
expect(headers[IMPERSONATION_HEADER_NAME]).toBe("impersonated-user-abc");
});
+ it("names the browser's PostHog session", async () => {
+ vi.mocked(getPostHogSessionHeader).mockReturnValueOnce({
+ "X-PostHog-Session-Id": "posthog-session-1",
+ });
+
+ await customMutator("/test", { method: "GET" });
+
+ const headers = vi.mocked(fetch).mock.calls[0][1]?.headers as Record<
+ string,
+ string
+ >;
+ expect(headers["X-PostHog-Session-Id"]).toBe("posthog-session-1");
+ });
+
it("does not add impersonation header when no impersonation active", async () => {
mockGetSystemHeaders.mockReturnValue({});
diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
index 6ff9e9bc23..cd5ffb279c 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
@@ -11,6 +11,7 @@ import {
} from "@/lib/auth/account-banned";
import { getSystemHeaders } from "@/lib/impersonation";
import { getDatafastAttribution } from "@/services/analytics/datafast-attribution";
+import { getPostHogSessionHeader } from "@/services/analytics/posthog-request-context";
import { environment } from "@/services/environment";
import { transformDates } from "./date-transformer";
import {
@@ -85,6 +86,7 @@ export const customMutator = async <
}
Object.assign(headers, getSystemHeaders());
Object.assign(headers, getDatafastAttribution());
+ Object.assign(headers, getPostHogSessionHeader());
}
const isFormData = data instanceof FormData;
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
index fbf61be7de..919e678a95 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.test.ts
@@ -212,7 +212,7 @@ describe("proxy route — handler pass-through", () => {
expect(sentHeaders.get("baggage")).toBe("sentry-trace_id=abc123");
});
- it("forwards allowlisted DataFast attribution headers", async () => {
+ it("forwards allowlisted DataFast and PostHog session headers", async () => {
vi.mocked(fetch).mockResolvedValue(
new Response("{}", {
status: 200,
@@ -224,6 +224,7 @@ describe("proxy route — handler pass-through", () => {
headers: {
"x-datafast-visitor-id": "visitor-123",
"x-datafast-session-id": "session-456",
+ "x-posthog-session-id": "posthog-session-789",
},
});
await GET(req, makeParams(["api", "v1", "items"]));
@@ -231,6 +232,7 @@ describe("proxy route — handler pass-through", () => {
const sentHeaders = vi.mocked(fetch).mock.calls[0][1]!.headers as Headers;
expect(sentHeaders.get("x-datafast-visitor-id")).toBe("visitor-123");
expect(sentHeaders.get("x-datafast-session-id")).toBe("session-456");
+ expect(sentHeaders.get("x-posthog-session-id")).toBe("posthog-session-789");
});
it("sends the edge-observed country only as a signed token", async () => {
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
index c75c69c370..a7f55926f0 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.ts
@@ -53,6 +53,7 @@ const FORWARDED_REQUEST_HEADERS: ReadonlyArray<string> = [
"baggage",
"x-datafast-visitor-id",
"x-datafast-session-id",
+ "x-posthog-session-id",
];
// Browsers advertise `zstd` in Accept-Encoding, but undici (Node 22's fetch)
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 0cb93b31c5..46fd427445 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -6,6 +6,7 @@ import {
import { getWebSocketToken } from "@/lib/auth/actions";
import { ImpersonationState } from "@/lib/impersonation";
import { getDatafastAttribution } from "@/services/analytics/datafast-attribution";
+import { getPostHogSessionHeader } from "@/services/analytics/posthog-request-context";
import { environment } from "@/services/environment";
import { Key, storage } from "@/services/storage/local-storage";
import * as Sentry from "@sentry/nextjs";
@@ -902,6 +903,7 @@ export default class BackendAPI {
}
Object.assign(headers, getDatafastAttribution());
+ Object.assign(headers, getPostHogSessionHeader());
const response = await fetch(url, {
method,
diff --git a/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
index db31108ab8..e3c617803d 100644
--- a/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx
@@ -68,6 +68,19 @@ describe("PostHogProvider", () => {
);
});
+ it("marks the events an admin sends while acting as a user", async () => {
+ const { PostHogProvider } = await import("../posthog-provider");
+ const { markImpersonatedEvent } = await import(
+ "@/services/analytics/posthog-request-context"
+ );
+
+ render(<PostHogProvider>app</PostHogProvider>);
+
+ expect(posthog.init.mock.calls[0][1].before_send).toBe(
+ markImpersonatedEvent,
+ );
+ });
+
it("talks to a self-hosted PostHog directly", async () => {
credentials.host = "https://posthog.example.com";
const { PostHogProvider } = await import("../posthog-provider");
diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
index 78ee6a3287..f65116adab 100644
--- a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx
@@ -8,6 +8,7 @@ import {
} from "@/services/analytics/anonymous-id";
import { getPostHogBaseProperties } from "@/services/analytics/posthog-base-properties";
import { PageEvent } from "@/services/analytics/posthog-events";
+import { markImpersonatedEvent } from "@/services/analytics/posthog-request-context";
import { useConsent } from "@/services/consent/useConsent";
import { environment } from "@/services/environment";
import { usesPostHog } from "@/services/feature-flags/flag-backend";
@@ -48,6 +49,7 @@ export function PostHogProvider({ children }: { children: ReactNode }) {
bootstrap: { distinctID: anonymousID, isIdentifiedID: false },
}),
...getConsentGatedConfig(),
+ before_send: markImpersonatedEvent,
});
posthog.register(getPostHogBaseProperties());
unfollowConsent = followAnalyticsConsent();
diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-request-context.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-request-context.test.ts
new file mode 100644
index 0000000000..f859bf31c4
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-request-context.test.ts
@@ -0,0 +1,91 @@
+import { ImpersonationState } from "@/lib/impersonation";
+import {
+ configureCookiebot,
+ installCookiebot,
+ removeCookiebot,
+} from "@/tests/integrations/cookiebot";
+import type { CaptureResult } from "posthog-js";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { posthog } = vi.hoisted(() => ({
+ posthog: {
+ __loaded: true,
+ get_session_id: vi.fn(() => "0192f0c4-5f4e-7b4c-9d6e-1a2b3c4d5e6f"),
+ },
+}));
+
+vi.mock("posthog-js", () => ({ default: posthog }));
+
+import {
+ getPostHogSessionHeader,
+ markImpersonatedEvent,
+} from "../posthog-request-context";
+
+const SESSION = "0192f0c4-5f4e-7b4c-9d6e-1a2b3c4d5e6f";
+
+function event(): CaptureResult {
+ return {
+ uuid: "event-1",
+ event: "paywall_viewed",
+ properties: { surface: "billing" },
+ } as CaptureResult;
+}
+
+beforeEach(() => {
+ configureCookiebot();
+ posthog.__loaded = true;
+ ImpersonationState.clear();
+});
+
+afterEach(() => {
+ ImpersonationState.clear();
+ removeCookiebot();
+ vi.unstubAllEnvs();
+});
+
+describe("markImpersonatedEvent", () => {
+ it("marks every event an admin sends while acting as a user", () => {
+ ImpersonationState.set("user-1");
+
+ expect(markImpersonatedEvent(event())?.properties).toEqual({
+ surface: "billing",
+ impersonated: true,
+ impersonated_user_id: "user-1",
+ });
+ });
+
+ it("leaves everyone else's events as they are", () => {
+ expect(markImpersonatedEvent(event())).toEqual(event());
+ expect(markImpersonatedEvent(null)).toBeNull();
+ });
+});
+
+describe("getPostHogSessionHeader", () => {
+ it("names the PostHog session with analytics consent", () => {
+ installCookiebot({ statistics: true });
+
+ expect(getPostHogSessionHeader()).toEqual({
+ "X-PostHog-Session-Id": SESSION,
+ });
+ });
+
+ it("sends nothing without analytics consent", () => {
+ installCookiebot({ statistics: false });
+
+ expect(getPostHogSessionHeader()).toEqual({});
+ });
+
+ it("sends nothing while an admin acts as a user", () => {
+ installCookiebot({ statistics: true });
+ ImpersonationState.set("user-1");
+
+ expect(getPostHogSessionHeader()).toEqual({});
+ });
+
+ it("sends nothing before PostHog has loaded", () => {
+ installCookiebot({ statistics: true });
+ posthog.__loaded = false;
+
+ expect(getPostHogSessionHeader()).toEqual({});
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/analytics/posthog-request-context.ts b/autogpt_platform/frontend/src/services/analytics/posthog-request-context.ts
new file mode 100644
index 0000000000..9c57f1595f
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/analytics/posthog-request-context.ts
@@ -0,0 +1,40 @@
+import { ImpersonationState } from "@/lib/impersonation";
+import { hasConsentFor } from "@/services/consent/consent";
+import posthog, { type CaptureResult } from "posthog-js";
+
+export const POSTHOG_SESSION_HEADER_NAME = "X-PostHog-Session-Id";
+
+// PostHog `before_send` hook. While an admin acts as a user, the browser is
+// still the admin's (identified as the admin), so its events land on the
+// admin's person; the mark lets a project filter leave them out of every
+// insight. The backend marks the events it sends during impersonation the
+// same way. Nothing here sends an event: capture only runs with analytics
+// consent.
+export function markImpersonatedEvent(event: CaptureResult | null) {
+ if (!event) return event;
+ const impersonatedUserId = ImpersonationState.get();
+ if (!impersonatedUserId) return event;
+ return {
+ ...event,
+ properties: {
+ ...event.properties,
+ impersonated: true,
+ impersonated_user_id: impersonatedUserId,
+ },
+ };
+}
+
+// The browser's PostHog session as a request header, so the events the
+// backend sends for the request join the same session. Only with analytics
+// consent, and not while an admin acts as a user: the session is the admin's,
+// and the backend's events are the user's.
+export function getPostHogSessionHeader(): Record<string, string> {
+ if (typeof window === "undefined" || !posthog.__loaded) return {};
+ if (!hasConsentFor("analytics") || ImpersonationState.get()) return {};
+ try {
+ const sessionID = posthog.get_session_id();
+ return sessionID ? { [POSTHOG_SESSION_HEADER_NAME]: sessionID } : {};
+ } catch {
+ return {};
+ }
+}
diff --git a/docs/engineering/tracking-plan.md b/docs/engineering/tracking-plan.md
index 0377823c78..b3f1485b26 100644
--- a/docs/engineering/tracking-plan.md
+++ b/docs/engineering/tracking-plan.md
@@ -110,6 +110,46 @@ something else now use `hire_started.surface`,
display name are person properties set by `identify` and nowhere else.
(`expert_hired.name` is the expert's display name, not a person's.)
+### Our own team and impersonation
+
+Our team's clicks and an admin acting as a user would otherwise skew every
+chart, funnel and experiment, so both are marked and a project filter leaves
+them out (SECRT-2728):
+
+- **`is_internal`** is a person property: true for an admin (Better Auth role
+ `admin`) or an `@agpt.co` email, false for everyone else. The backend sets
+ it at signup with the other account properties, and again whenever an
+ internal account signs in (`POST /api/auth/user`), so someone made an admin
+ later is flagged from their next sign-in. `poetry run cli
+ posthog-audience-backfill` sets it on earlier accounts. Someone who stops
+ being an admin keeps it until that backfill runs again.
+- **`impersonated`** is an event property, true on every event an admin
+ caused while acting as a user (`X-Act-As-User-Id`). The backend sets it in
+ `posthog_client.capture` for every event a request sends with that header
+ (`api/middleware/analytics.py`) and every event of a chat turn such an admin
+ started; the AutoPilot events above carry it too. The browser stays the
+ admin's while impersonating, so its events land on the admin's person; a
+ PostHog `before_send` hook adds `impersonated` and `impersonated_user_id`
+ to them (`src/services/analytics/posthog-request-context.ts`).
+- **An admin acting as a user never changes the user's person.** The backend
+ drops `$set_person_properties` while impersonated (the onboarding role, the
+ checkout properties). The lifecycle sync still runs, since it mirrors the
+ stored trial and Stripe state rather than the admin's action.
+- **Session.** With analytics consent, and not while impersonating, the
+ browser sends its PostHog session id as `X-PostHog-Session-Id` on API
+ requests (`customMutator` through the proxy, and the chat's direct
+ requests), and the backend adds it
+ as `$session_id` to the events that request sends, so they join the
+ browser's session and its replay. Events sent later by the executor, the
+ scheduler or a webhook have no session.
+
+The project's "Filter out internal and test users" setting (PostHog project
+settings, Product analytics) holds the filter, applied to every insight that
+has "Filter out internal and test users" on:
+
+- person property `is_internal` is not `true`;
+- event property `impersonated` is not `true`.
+
## What counts as a task
The `analytics.*` views (`user_task_daily`, `user_lifecycle`,
@@ -516,14 +556,16 @@ The fields GTM segments checkout openers on in MailerLite are on the person
too (SECRT-2895, `backend/notifications/posthog_audience.py`). They are worked
out by the same code (`audience_enrichment.checkout_fields`) and named as in
MailerLite, except the checkout open, which is a moment here and a day there.
-Every account gets the first two at signup. Every checkout opener gets all of
-them from the checkout routes and the completed-checkout webhook. Unlike
+Every account gets `email_type`, `signin_method` and `is_internal` (PostHog
+only) at signup. Every checkout opener gets the MailerLite fields from the
+checkout routes and the completed-checkout webhook. Unlike
MailerLite, PostHog also gets accounts that opted out of marketing or that a
signal places in Iran or Russia: it is analytics, not marketing.
| Property | Value |
| --- | --- |
| `email_type` | `business`, `personal` (a webmail provider) or `education`. |
+| `is_internal` | `true` for our own team (an admin or an `@agpt.co` email), else `false`; see [Our own team and impersonation](#our-own-team-and-impersonation). Every account, not only openers. |
| `signin_method` | `google` or `email`; `google` wins for an account that has both. |
| `checkout_opened_at` | When the account first opened Stripe checkout. |
| `country` | The country's English name, from the strongest source seen (see `country_source`). |