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): send signup, onboarding, checkout and churn events to PostHog (#14836)
Krzysztof Czerwinski23175335f87c
diff --git a/autogpt_platform/backend/backend/api/features/billing/credits/routes.py b/autogpt_platform/backend/backend/api/features/billing/credits/routes.pyindex 2857a166f3..b351976a61 100644--- a/autogpt_platform/backend/backend/api/features/billing/credits/routes.py+++ b/autogpt_platform/backend/backend/api/features/billing/credits/routes.py@@ -23,6 +23,7 @@ from backend.data.credit import (get_credit_model,set_auto_top_up,)+from backend.util.product_analytics import track_checkout_started# All nine routes carry tags=["credits"] and only Security(requires_user), so# both live at the mount and the router rather than on each route.@@ -79,6 +80,9 @@ async def request_top_up(datafast_session_id=x_datafast_session_id,)if checkout_url:+ await track_checkout_started(+ user_id=user_id, checkout_kind="top_up", surface=request.surface+ )schedule_checkout_opened(user_id, ip_country=country)return {"checkout_url": checkout_url}diff --git a/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.py b/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.pyindex 1575c60ae9..eab27fe1e4 100644--- a/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/billing/credits/routes_test.py@@ -52,6 +52,15 @@ def setup_app_auth(mock_jwt_user, test_user_id):app.dependency_overrides.clear()[email protected](autouse=True)+def track_checkout_started(mocker: pytest_mock.MockFixture) -> AsyncMock:+ """Keep analytics off the network and let tests assert the event."""+ return mocker.patch(+ "backend.api.features.billing.credits.routes.track_checkout_started",+ new_callable=AsyncMock,+ )++EXPECTED_OPERATIONS = {("get", "/api/credits"),("post", "/api/credits"),@@ -183,6 +192,50 @@ def test_request_top_up()+def test_request_top_up_sends_checkout_started(+ mocker: pytest_mock.MockFixture,+ track_checkout_started: AsyncMock,+ test_user_id: str,+) -> None:+ mock_credit_model = Mock()+ mock_credit_model.top_up_intent = AsyncMock(+ return_value="https://checkout.example.com/session123"+ )+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.post(+ "/credits", json={"credit_amount": 500, "surface": "billing"}+ )++ assert response.status_code == 200+ track_checkout_started.assert_awaited_once_with(+ user_id=test_user_id, checkout_kind="top_up", surface="billing"+ )+++def test_request_top_up_without_a_checkout_sends_no_checkout_started(+ mocker: pytest_mock.MockFixture,+ track_checkout_started: AsyncMock,+) -> None:+ """With credits disabled there is no checkout session, so no checkout started."""+ mock_credit_model = Mock()+ mock_credit_model.top_up_intent = AsyncMock(return_value="")+ mocker.patch(+ "backend.api.features.billing.credits.routes.get_credit_model",+ return_value=mock_credit_model,+ )++ response = client.post(+ "/credits", json={"credit_amount": 500, "surface": "billing"}+ )++ assert response.status_code == 200+ track_checkout_started.assert_not_awaited()++def test_request_top_up_forwards_datafast_headers(mocker: pytest_mock.MockFixture,) -> None:diff --git a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.pyindex 8eee5729f0..1430637aae 100644--- a/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py+++ b/autogpt_platform/backend/backend/api/features/billing/subscriptions/routes.py@@ -59,6 +59,7 @@ from backend.notifications.queue import queue_pass_workfrom backend.notifications.trial import notify_trial, on_trial_invoicefrom backend.util.cache import cachedfrom backend.util.feature_flag import Flag, evaluate_feature_flag+from backend.util.product_analytics import track_checkout_startedfrom backend.util.settings import Settingslogger = logging.getLogger(__name__)@@ -74,6 +75,10 @@ class SubscriptionTierRequest(BaseModel):success_url: str = ""cancel_url: str = ""billing_cycle: Literal["monthly", "yearly"] = "monthly"+ surface: Optional[Literal["onboarding", "paywall_gate", "billing"]] = Field(+ default=None,+ description="Where the plan was picked; analytics only.",+ )class SubscriptionStatusResponse(BaseModel):@@ -642,6 +647,13 @@ async def update_subscription_tier("Please try again or contact support."),)+ await track_checkout_started(+ user_id=user_id,+ checkout_kind="subscription",+ surface=request.surface,+ subscription_tier=tier.value,+ billing_cycle=request.billing_cycle,+ )if url:checkout_audience.schedule_checkout_opened(user_id, ip_country=country)diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.pyindex 877c929da9..4c389ad7f4 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py@@ -1955,7 +1955,7 @@ async def _install_preloads(continuetry:library_agent = await library_db.add_store_agent_to_library(- preload.storeListingVersionId, user_id+ preload.storeListingVersionId, user_id, track_listing_added=False)row = await prisma.models.ExpertWorkflow.prisma().create(data={@@ -2123,7 +2123,7 @@ async def _install_marketplace_workflow(return _to_workflow_ref(existing)library_agent = await library_db.add_store_agent_to_library(- store_listing_version_id, user_id+ store_listing_version_id, user_id, track_listing_added=False)try:row = await prisma.models.ExpertWorkflow.prisma().create(diff --git a/autogpt_platform/backend/backend/api/features/experts/workflow_install_test.py b/autogpt_platform/backend/backend/api/features/experts/workflow_install_test.pynew file mode 100644index 0000000000..a0ae18647e--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/experts/workflow_install_test.py@@ -0,0 +1,53 @@+"""An expert installing a marketplace workflow is not the user adding a+listing to their library: neither install path may send+``listing_added_to_library``."""++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import prisma.models+import pytest++from backend.api.features.experts import experts_db+++async def test_hire_preloads_do_not_count_as_listing_adds():+ preload = prisma.models.ExpertWorkflow.model_construct(+ storeListingVersionId="slv-1", scheduleCron=None, StoreListingVersion=None+ )+ workflow_client = SimpleNamespace(+ create=AsyncMock(return_value=SimpleNamespace(id="workflow-1"))+ )+ add = AsyncMock(return_value=SimpleNamespace(id="library-agent-1"))+ with (+ patch.object(experts_db.library_db, "add_store_agent_to_library", add),+ patch.object(+ prisma.models.ExpertWorkflow, "prisma", return_value=workflow_client+ ),+ ):+ failed = await experts_db._install_preloads("expert-1", "user-1", [preload])++ assert failed == []+ add.assert_awaited_once_with("slv-1", "user-1", track_listing_added=False)+++async def test_marketplace_workflow_install_does_not_count_as_listing_add():+ workflow_client = SimpleNamespace(+ find_first=AsyncMock(return_value=None),+ create=AsyncMock(return_value=SimpleNamespace(id="workflow-1")),+ )+ add = AsyncMock(return_value=SimpleNamespace(id="library-agent-1"))+ with (+ patch.object(experts_db.library_db, "add_store_agent_to_library", add),+ patch.object(+ prisma.models.ExpertWorkflow, "prisma", return_value=workflow_client+ ),+ patch.object(experts_db, "_to_workflow_ref", MagicMock()),+ patch.object(experts_db, "emit_funnel_event") as emit,+ ):+ await experts_db._install_marketplace_workflow("user-1", "expert-1", "slv-1")++ add.assert_awaited_once_with("slv-1", "user-1", track_listing_added=False)+ assert emit.call_args.args[1] == "workflow_installed_on_expert"diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex 0852e6d65f..2fdcbd9ca7 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -37,6 +37,7 @@ from backend.util.clients import get_scheduler_clientfrom backend.util.exceptions import InvalidInputError, MissingConfigError, NotFoundErrorfrom backend.util.json import SafeJsonfrom backend.util.models import Pagination+from backend.util.product_analytics import track_listing_added_to_libraryfrom backend.util.settings import Configfrom . import model as library_model@@ -1221,13 +1222,25 @@ async def is_store_listing_version_available_for_install(async def add_store_agent_to_library(store_listing_version_id: str,user_id: str,+ *,+ track_listing_added: bool = True,) -> library_model.LibraryAgent:"""Adds a marketplace agent to the user’s library.+ ``track_listing_added`` sends ``listing_added_to_library`` on a first-time+ add. Pass ``False`` when the system installs the agent on the user's+ behalf (an expert's preloads or workflows), which is not the user adding+ a listing.+See also: `add_store_agent_to_library_as_admin()` which uses`get_graph_as_admin` to bypass marketplace status checks for admin review."""- return await _add_store_agent_to_library(store_listing_version_id, user_id, tx=None)+ return await _add_store_agent_to_library(+ store_listing_version_id,+ user_id,+ tx=None,+ track_listing_added=track_listing_added,+ )async def add_store_agent_to_library_in_transaction(@@ -1235,8 +1248,14 @@ async def add_store_agent_to_library_in_transaction(user_id: str,tx: prisma.Prisma,) -> library_model.LibraryAgent:- """Add a marketplace agent using the caller's transaction."""- return await _add_store_agent_to_library(store_listing_version_id, user_id, tx=tx)+ """Add a marketplace agent using the caller's transaction.++ Sends no ``listing_added_to_library``: the caller may still roll back, and+ the upsert cannot tell a first-time add from a restore.+ """+ return await _add_store_agent_to_library(+ store_listing_version_id, user_id, tx=tx, track_listing_added=False+ )async def _add_store_agent_to_library(@@ -1244,6 +1263,7 @@ async def _add_store_agent_to_library(user_id: str,*,tx: prisma.Prisma | None,+ track_listing_added: bool,) -> library_model.LibraryAgent:logger.debug("Adding agent from store listing version #%s to library for user #%s",@@ -1262,9 +1282,17 @@ async def _add_store_agent_to_library(graph_model = await resolve_graph_model_for_library(store_listing_version, user_id, admin=False)- return await add_graph_to_library(+ library_agent = await add_graph_to_library(graph_model, user_id, store_listing_version, tx=tx)+ if track_listing_added:+ track_listing_added_to_library(+ user_id=user_id,+ store_listing_version_id=store_listing_version.id,+ graph_id=graph_model.id,+ library_agent_id=library_agent.id,+ )+ return library_agentasync def add_store_agent_to_library_as_admin(diff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.pyindex 06e952b172..6604d7565d 100644--- a/autogpt_platform/backend/backend/api/features/library/db_test.py+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py@@ -399,6 +399,78 @@ async def test_add_agent_to_library_reuses_existing_without_loading_graph(mocker)+def add_to_library_steps(mocker) -> dict[str, MagicMock]:+ """Stub the resolve/restore/create helpers the add path is built from."""+ store_version = MagicMock(id="version123")+ graph = MagicMock(id="agent1", version=1)+ return {+ "resolve": mocker.patch.object(+ db,+ "resolve_store_version_for_library",+ AsyncMock(return_value=store_version),+ ),+ "restore": mocker.patch.object(+ db, "restore_existing_library_agent", AsyncMock(return_value=None)+ ),+ "graph": mocker.patch.object(+ db, "resolve_graph_model_for_library", AsyncMock(return_value=graph)+ ),+ "add": mocker.patch.object(+ db,+ "add_graph_to_library",+ AsyncMock(return_value=MagicMock(id="library-agent")),+ ),+ "track": mocker.patch.object(db, "track_listing_added_to_library"),+ }+++async def test_first_marketplace_add_sends_listing_added_to_library(+ add_to_library_steps,+):+ await db.add_store_agent_to_library("version123", "test-user")++ add_to_library_steps["track"].assert_called_once_with(+ user_id="test-user",+ store_listing_version_id="version123",+ graph_id="agent1",+ library_agent_id="library-agent",+ )+++async def test_re_adding_a_marketplace_agent_sends_nothing(add_to_library_steps):+ add_to_library_steps["restore"].return_value = MagicMock(id="library-agent")++ await db.add_store_agent_to_library("version123", "test-user")++ add_to_library_steps["track"].assert_not_called()+++async def test_system_install_of_a_listing_sends_nothing(add_to_library_steps):+ # An expert's preloads and workflows are installed for the user, not+ # picked by them; `workflow_installed_on_expert` covers those.+ library_agent = await db.add_store_agent_to_library(+ "version123", "test-user", track_listing_added=False+ )++ assert library_agent.id == "library-agent"+ add_to_library_steps["add"].assert_awaited_once()+ add_to_library_steps["track"].assert_not_called()+++async def test_transactional_marketplace_add_sends_nothing(add_to_library_steps):+ # The caller's transaction may still roll back; its own event covers it.+ await db.add_store_agent_to_library_in_transaction(+ "version123", "test-user", tx=MagicMock()+ )++ add_to_library_steps["track"].assert_not_called()++@pytest.mark.asyncioasync def test_restore_existing_library_agent_handles_deleted_update(mocker):from backend.api.features.library._add_to_library import (diff --git a/autogpt_platform/backend/backend/api/features/store/routes.py b/autogpt_platform/backend/backend/api/features/store/routes.pyindex dbbc658d10..7affe4679a 100644--- a/autogpt_platform/backend/backend/api/features/store/routes.py+++ b/autogpt_platform/backend/backend/api/features/store/routes.py@@ -15,6 +15,7 @@ import backend.util.jsonfrom backend.api.features.search import hybrid_search as search_enginefrom backend.util.exceptions import NotFoundErrorfrom backend.util.models import Pagination+from backend.util.product_analytics import track_listing_downloadedfrom . import cache as store_cachefrom . import categories as store_categories@@ -283,9 +284,15 @@ async def get_graph_meta_by_store_listing_version_id()async def download_agent_file(store_listing_version_id: str,+ user_id: str | None = Security(autogpt_libs.auth.get_optional_user_id),) -> fastapi.responses.Response:"""Download agent graph file for a specific marketplace listing version"""graph_data = await store_db.get_agent(store_listing_version_id)+ track_listing_downloaded(+ user_id=user_id,+ store_listing_version_id=store_listing_version_id,+ graph_id=graph_data.id,+ )file_name = f"agent_{graph_data.id}_v{graph_data.version or 'latest'}.json"return fastapi.responses.Response(diff --git a/autogpt_platform/backend/backend/api/features/store/routes_test.py b/autogpt_platform/backend/backend/api/features/store/routes_test.pyindex f137e103ab..5cd1ae55f7 100644--- a/autogpt_platform/backend/backend/api/features/store/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/store/routes_test.py@@ -6,6 +6,8 @@ import fastapi.testclientimport prisma.enumsimport pytestimport pytest_mock+from autogpt_libs.auth import get_optional_user_id+from pydantic import BaseModelfrom pytest_snapshot.plugin import Snapshotfrom backend.api.features.store.db import StoreAgentsSortOptions@@ -851,3 +853,39 @@ def test_get_submissions_malformed_request(mocker: pytest_mock.MockFixture):# Verify no DB calls were mademock_db_call = mocker.patch("backend.api.features.store.db.get_store_submissions")mock_db_call.assert_not_called()+++class _DownloadedGraph(BaseModel):+ id: str+ version: int+++def test_download_agent_file_sends_listing_downloaded(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.store.db.get_agent",+ mocker.AsyncMock(return_value=_DownloadedGraph(id="graph-1", version=3)),+ )+ track = mocker.patch("backend.api.features.store.routes.track_listing_downloaded")+ app.dependency_overrides[get_optional_user_id] = lambda: "test-user-id"++ response = client.get("/listings/versions/slv-1/graph/download")++ assert response.status_code == 200+ track.assert_called_once_with(+ user_id="test-user-id", store_listing_version_id="slv-1", graph_id="graph-1"+ )+++def test_signed_out_download_passes_no_user(mocker: pytest_mock.MockFixture) -> None:+ mocker.patch(+ "backend.api.features.store.db.get_agent",+ mocker.AsyncMock(return_value=_DownloadedGraph(id="graph-1", version=3)),+ )+ track = mocker.patch("backend.api.features.store.routes.track_listing_downloaded")++ response = client.get("/listings/versions/slv-1/graph/download")++ assert response.status_code == 200+ assert track.call_args.kwargs["user_id"] is Nonediff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.pyindex bc5adb1ac4..5398253566 100644--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py@@ -87,6 +87,15 @@ def _stub_pending_subscription_change(mocker: pytest_mock.MockFixture) -> None:)[email protected](autouse=True)+def track_checkout_started(mocker: pytest_mock.MockFixture) -> AsyncMock:+ """Keep analytics off the network and let tests assert the event."""+ return mocker.patch(+ "backend.api.features.billing.subscriptions.routes.track_checkout_started",+ new_callable=AsyncMock,+ )++_DEFAULT_TIER_PRICES: dict[SubscriptionTier, str | None] = {SubscriptionTier.BASIC: None, # Legacy: stripe-price-id-basic unset by default.SubscriptionTier.PRO: "price_pro",@@ -630,6 +639,89 @@ def test_update_subscription_tier_creates_checkout(assert response.json()["url"] == "https://checkout.stripe.com/pay/cs_test_abc"+def test_update_subscription_tier_checkout_sends_checkout_started(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+ track_checkout_started: AsyncMock,+) -> None:+ """A created Checkout Session is reported with its plan and surface."""+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.NO_TIER+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ _patch_payment_flag(mocker)+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=False,+ )+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",+ new_callable=AsyncMock,+ return_value="https://checkout.stripe.com/pay/cs_test_abc",+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "MAX",+ "billing_cycle": "yearly",+ "surface": "paywall_gate",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ },+ )++ assert response.status_code == 200+ track_checkout_started.assert_awaited_once_with(+ user_id=TEST_USER_ID,+ checkout_kind="subscription",+ surface="paywall_gate",+ subscription_tier="MAX",+ billing_cycle="yearly",+ )+++def test_update_subscription_tier_failed_checkout_sends_no_checkout_started(+ client: fastapi.testclient.TestClient,+ mocker: pytest_mock.MockFixture,+ track_checkout_started: AsyncMock,+) -> None:+ mock_user = Mock()+ mock_user.subscription_tier = SubscriptionTier.NO_TIER+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.get_user_by_id",+ new_callable=AsyncMock,+ return_value=mock_user,+ )+ _patch_payment_flag(mocker)+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.modify_stripe_subscription_for_tier",+ new_callable=AsyncMock,+ return_value=False,+ )+ mocker.patch(+ "backend.api.features.billing.subscriptions.routes.create_subscription_checkout",+ new_callable=AsyncMock,+ side_effect=stripe.StripeError("down"),+ )++ response = client.post(+ "/credits/subscription",+ json={+ "tier": "PRO",+ "success_url": f"{TEST_FRONTEND_ORIGIN}/success",+ "cancel_url": f"{TEST_FRONTEND_ORIGIN}/cancel",+ },+ )++ assert response.status_code == 502+ track_checkout_started.assert_not_awaited()++def test_update_subscription_tier_forwards_datafast_headers(client: fastapi.testclient.TestClient,mocker: pytest_mock.MockFixture,diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.pyindex bcfd7e4b12..fe37c3fc9a 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes.py@@ -1,3 +1,4 @@+import loggingfrom datetime import datetimefrom typing import Annotated, Literal@@ -31,8 +32,11 @@ from backend.data.subscription_trial_checkout import (from backend.data.subscription_trial_config import AcceptedTrialOffer, get_trial_offerfrom backend.data.subscription_trial_rejection import TrialRejectionReasonfrom backend.data.user import get_user_by_id+from backend.util.product_analytics import track_checkout_startedfrom backend.util.settings import Settings+logger = logging.getLogger(__name__)+router = APIRouter(prefix="/credits/trial",tags=["trials"],@@ -174,10 +178,27 @@ async def start_trial_checkout(raise HTTPException(409, str(exc)) from excexcept stripe.StripeError as exc:raise HTTPException(502, "Unable to start checkout. Please try again.") from exc+ await _track_trial_checkout_started(user_id, surface=body.return_to)schedule_checkout_opened(user_id, ip_country=country)return TrialCheckoutResponse(url=url)+async def _track_trial_checkout_started(user_id: str, *, surface: str) -> None:+ """Best-effort: the reserved trial names the plan the card is set up for."""+ try:+ trial = await get_subscription_trial(user_id)+ except Exception:+ logger.warning("Could not read the trial for checkout_started", exc_info=True)+ trial = None+ await track_checkout_started(+ user_id=user_id,+ checkout_kind="trial",+ surface=surface,+ subscription_tier=trial.offer.tier if trial else None,+ billing_cycle=trial.offer.billing_cycle if trial else None,+ )++@router.post("/cancel",responses={diff --git a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.pyindex 0a9f2be39e..8168929eb8 100644--- a/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/subscription_trial_routes_test.py@@ -23,6 +23,14 @@ def billing_return_origin(monkeypatch):monkeypatch.setattr(routes, "Settings", lambda: settings)[email protected](autouse=True)+def track_checkout_started(monkeypatch) -> AsyncMock:+ """Keep analytics off the network and let tests assert the event."""+ track = AsyncMock()+ monkeypatch.setattr(routes, "track_checkout_started", track)+ return track++@pytest.fixturedef trial() -> TrialState:now = datetime.now(UTC)@@ -146,6 +154,60 @@ async def test_checkout_uses_authenticated_identity_and_server_return_urls(trialassert params["metadata"]["datafast_visitor_id"] == "visitor-1"+async def test_checkout_sends_checkout_started_for_the_reserved_plan(+ trial, track_checkout_started+):+ with (+ patch.object(+ routes,+ "create_trial_checkout",+ AsyncMock(return_value="https://checkout.stripe.com/test"),+ ),+ patch.object(routes, "get_subscription_trial", AsyncMock(return_value=trial)),+ ):+ await routes.start_trial_checkout(+ routes.TrialCheckoutRequest(+ offer_token=trial.offer.token, return_to="onboarding"+ ),+ trial.user_id,+ )++ track_checkout_started.assert_awaited_once_with(+ user_id=trial.user_id,+ checkout_kind="trial",+ surface="onboarding",+ subscription_tier="PRO",+ billing_cycle="monthly",+ )+++async def test_checkout_started_survives_an_unreadable_trial(+ trial, track_checkout_started+):+ with (+ patch.object(+ routes,+ "create_trial_checkout",+ AsyncMock(return_value="https://checkout.stripe.com/test"),+ ),+ patch.object(+ routes,+ "get_subscription_trial",+ AsyncMock(side_effect=RuntimeError("db down")),+ ),+ ):+ response = await routes.start_trial_checkout(+ routes.TrialCheckoutRequest(offer_token=trial.offer.token),+ trial.user_id,+ )++ assert response.url == "https://checkout.stripe.com/test"+ assert track_checkout_started.await_args.kwargs["subscription_tier"] is None+ assert track_checkout_started.await_args.kwargs["surface"] == "billing"++@pytest.mark.asyncioasync def test_unavailable_offer_is_conflict_not_success(trial):with patch.object(diff --git a/autogpt_platform/backend/backend/api/model.py b/autogpt_platform/backend/backend/api/model.pyindex b69340cc44..094bc7412e 100644--- a/autogpt_platform/backend/backend/api/model.py+++ b/autogpt_platform/backend/backend/api/model.py@@ -50,6 +50,9 @@ class SetGraphActiveVersion(pydantic.BaseModel):class RequestTopUp(pydantic.BaseModel):credit_amount: int+ surface: Optional[Literal["billing"]] = pydantic.Field(+ default=None, description="Where the top-up was started; analytics only."+ )class CloudStorageUploadResponse(pydantic.BaseModel):diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex fdf284a5d5..d0de36dcad 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -1122,6 +1122,7 @@ class UserCredit(UserCreditBase):successful_transaction = Nonenew_transaction_key = None+ charged: stripe.PaymentIntent | None = Nonefor payment_method in payment_methods:if transaction_type == CreditTransactionType.CARD_CHECK:setup_intent = await stripe_call(@@ -1159,6 +1160,7 @@ class UserCredit(UserCreditBase):{"payment_intent": payment_intent})new_transaction_key = payment_intent.id+ charged = payment_intentbreakif not successful_transaction:@@ -1182,6 +1184,8 @@ class UserCredit(UserCreditBase):{"amount_credits": amount,"top_up_type": top_up_type.value,+ "amount_cents": charged.amount if charged else None,+ "currency": charged.currency if charged else None,},)@@ -1325,6 +1329,8 @@ class UserCredit(UserCreditBase):{"amount_credits": credit_transaction.amount,"top_up_type": "CHECKOUT",+ "amount_cents": checkout_session.amount_total,+ "currency": checkout_session.currency,},)@@ -1589,10 +1595,18 @@ def invalidate_subscription_caches(user_id: str) -> None:get_pending_subscription_change.cache_delete(user_id)+# Stripe stamps ``cancellation_details.reason = "cancellation_requested"`` on+# any cancel made through the API, including ours after a failed renewal the+# balance could not cover. This comment on that cancel is what lets the+# ``customer.subscription.deleted`` handler report it as involuntary churn.+PAYMENT_FAILURE_CANCELLATION_COMMENT = "autogpt:payment_failed"++async def _cancel_customer_subscriptions(customer_id: str,exclude_sub_id: str | None = None,at_period_end: bool = False,+ cancellation_comment: str | None = None,) -> int:"""Cancel all billable Stripe subscriptions for a customer, optionally excluding one.@@ -1606,6 +1620,9 @@ async def _cancel_customer_subscriptions(Uses the async Stripe client. Raises stripe.StripeError on list/cancel failure so callersthat need strict consistency can react; cleanup callers can catch and log instead.+ ``cancellation_comment`` is set as ``cancellation_details.comment`` on an+ immediate cancel, where the subscription's deletion webhook can read it.+Returns the number of subscriptions cancelled/scheduled for cancellation."""# Query active and trialing separately; Stripe's list API accepts a single status@@ -1649,16 +1666,33 @@ async def _cancel_customer_subscriptions(canceled = await stripe_call(stripe.Subscription.cancel_async,sub_id,- invoice_now=False,- prorate=False,+ **_cancel_params(cancellation_comment, trial=True),)if (sub.get("metadata") or {}).get("trial_enrollment_id"):await sync_subscription_from_stripe(dict(canceled))else:- await stripe_call(stripe.Subscription.cancel_async, sub_id)+ await stripe_call(+ stripe.Subscription.cancel_async,+ sub_id,+ **_cancel_params(cancellation_comment, trial=False),+ )return len(seen_ids)+def _cancel_params(+ cancellation_comment: str | None, *, trial: bool+) -> stripe.Subscription.CancelParams:+ """A trial ends without an invoice or proration; a comment, when given,+ becomes ``cancellation_details.comment``."""+ params: stripe.Subscription.CancelParams = {}+ if trial:+ params["invoice_now"] = False+ params["prorate"] = False+ if cancellation_comment:+ params["cancellation_details"] = {"comment": cancellation_comment}+ return params++async def cancel_stripe_subscription(user_id: str) -> bool:"""Cancel trials immediately and paid subscriptions at period end.@@ -3050,11 +3084,15 @@ async def alert_tier_reconciliation_discrepancy(message: str) -> None:def _track_billing_event(- event: PostHogEvent, distinct_id: str, properties: dict[str, Any]+ event: PostHogEvent,+ distinct_id: str,+ properties: dict[str, Any],+ *,+ dedup_key: str | None = None,) -> None:# The shared client, never the posthog module's globals: another library# (graphiti-core) configures those for its own telemetry (SECRT-2710).- posthog_client.capture(distinct_id, event, properties)+ posthog_client.capture(distinct_id, event, properties, dedup_key=dedup_key)async def _track_subscription_payment_success(user: User, invoice: dict) -> None:@@ -3074,7 +3112,17 @@ async def _track_subscription_payment_success(user: User, invoice: dict) -> None_track_billing_event(PostHogEvent.PAYMENT_SUCCEEDED,user.id,- {"subscription_tier": tier, "billing_cycle": billing_cycle},+ {+ "subscription_tier": tier,+ "billing_cycle": billing_cycle,+ "amount_cents": invoice.get("amount_paid"),+ "currency": invoice.get("currency"),+ },+ # One invoice is one payment: Stripe delivers both+ # invoice.payment_succeeded and invoice_payment.paid for it, and+ # redelivers either on a failed handler, so the revenue sum would+ # count it twice without this.+ dedup_key=invoice.get("id") or None,)except Exception:logger.warning(@@ -3206,7 +3254,9 @@ async def handle_subscription_payment_failure(invoice: dict) -> None:sub_id,)try:- await _cancel_customer_subscriptions(customer_id)+ await _cancel_customer_subscriptions(+ customer_id, cancellation_comment=PAYMENT_FAILURE_CANCELLATION_COMMENT+ )except stripe.StripeError:logger.warning("handle_subscription_payment_failure: failed to cancel Stripe sub %s"diff --git a/autogpt_platform/backend/backend/data/credit_subscription_test.py b/autogpt_platform/backend/backend/data/credit_subscription_test.pyindex 3194076cc6..b4cfb564ee 100644--- a/autogpt_platform/backend/backend/data/credit_subscription_test.py+++ b/autogpt_platform/backend/backend/data/credit_subscription_test.py@@ -12,6 +12,7 @@ from prisma.errors import PrismaError, UniqueViolationErrorfrom prisma.models import Userfrom backend.data.credit import (+ PAYMENT_FAILURE_CANCELLATION_COMMENT,UserCredit,_get_active_subscription_cached,_is_stripe_reconcilable,@@ -30,6 +31,7 @@ from backend.data.credit import (sync_subscription_from_stripe,sync_subscription_schedule_from_stripe,)+from backend.util.exceptions import InsufficientBalanceErrorclass _CacheClearable(Protocol):@@ -1884,6 +1886,61 @@ async def test_handle_subscription_payment_failure_passes_invoice_id_as_transactassert kwargs.get("transaction_key") == "in_idempotency_test"+async def test_handle_subscription_payment_failure_marks_its_cancel_as_payment_failed():+ """Stripe stamps our API cancel ``cancellation_requested``; the comment is+ what lets the deletion webhook report it as involuntary churn."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)+ invoice = {+ "id": "in_uncovered",+ "customer": "cus_123",+ "subscription": "sub_abc123",+ "amount_due": 2000,+ }+ active_subs = MagicMock()+ active_subs.data = [+ stripe.Subscription.construct_from(+ {"id": "sub_abc123", "schedule": None}, "sk_test"+ )+ ]+ active_subs.has_more = False+ no_subs = MagicMock()+ no_subs.data = []+ no_subs.has_more = False++ def list_side_effect(*args, **kwargs):+ return no_subs if kwargs.get("status") == "trialing" else active_subs++ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.data.credit.UserCredit._add_transaction",+ new_callable=AsyncMock,+ side_effect=InsufficientBalanceError(+ message="no balance", user_id="user-1", balance=0, amount=2000+ ),+ ),+ patch(+ "backend.data.credit.stripe.Subscription.list_async",+ side_effect=list_side_effect,+ ),+ patch(+ "backend.data.credit.stripe.Subscription.cancel_async",+ new_callable=AsyncMock,+ ) as mock_cancel,+ patch("backend.data.credit.set_subscription_tier", new_callable=AsyncMock),+ ):+ await handle_subscription_payment_failure(invoice)++ mock_cancel.assert_called_once_with(+ "sub_abc123",+ cancellation_details={"comment": PAYMENT_FAILURE_CANCELLATION_COMMENT},+ )++def _patch_credit_grant_config(enabled: bool):"""Patch ``settings.config.enable_subscription_credit_grant`` for thesuccess handler's gate check.@@ -1982,6 +2039,7 @@ async def test_handle_subscription_payment_success_tracks_paid_plan_when_grants_"customer": "cus_123","subscription": "sub_abc123","amount_paid": 5000,+ "currency": "usd","subscription_details": {"metadata": {"tier": "PRO",@@ -2016,6 +2074,52 @@ async def test_handle_subscription_payment_success_tracks_paid_plan_when_grants_assert kwargs["distinct_id"] == "user-1"assert kwargs["properties"]["subscription_tier"] == "PRO"assert kwargs["properties"]["billing_cycle"] == "yearly"+ # Revenue is what the invoice actually charged, in the minor unit.+ assert kwargs["properties"]["amount_cents"] == 5000+ assert kwargs["properties"]["currency"] == "usd"+++async def test_handle_subscription_payment_success_is_deduplicated_per_invoice():+ """invoice.payment_succeeded and invoice_payment.paid both deliver the+ same invoice, and Stripe redelivers on a failed handler: every send for+ one invoice must carry the same event uuid so revenue is counted once."""+ mock_user = _make_user(user_id="user-1", tier=SubscriptionTier.PRO)++ def invoice(invoice_id: str) -> dict:+ return {+ "id": invoice_id,+ "customer": "cus_123",+ "subscription": "sub_abc123",+ "amount_paid": 5000,+ "currency": "usd",+ "subscription_details": {+ "metadata": {"tier": "PRO", "billing_cycle": "monthly"}+ },+ }++ track_mock = MagicMock()+ with (+ patch(+ "backend.data.credit.User.prisma",+ return_value=MagicMock(find_first=AsyncMock(return_value=mock_user)),+ ),+ patch(+ "backend.util.posthog_client.get_posthog_client",+ return_value=MagicMock(capture=track_mock),+ ),+ patch("backend.util.posthog_client._environment", return_value="test"),+ _patch_credit_grant_config(False),+ ):+ await handle_subscription_payment_success(invoice("in_1"))+ await handle_subscription_payment_success(invoice("in_1"))+ await handle_subscription_payment_success(invoice("in_2"))++ first, redelivery, next_invoice = track_mock.call_args_list+ assert first.kwargs["uuid"] is not None+ assert first.kwargs["uuid"] == redelivery.kwargs["uuid"]+ assert first.kwargs["properties"]["$insert_id"] == "in_1"+ assert next_invoice.kwargs["uuid"] != first.kwargs["uuid"]@pytest.mark.asyncio@@ -2485,6 +2589,8 @@ async def test_top_up_credits_tracks_success():payment_intent = MagicMock()payment_intent.status = "succeeded"payment_intent.id = "pi_123"+ payment_intent.amount = 500+ payment_intent.currency = "usd"track_mock = MagicMock()with (@@ -2528,6 +2634,8 @@ async def test_top_up_credits_tracks_success():assert kwargs["properties"] == {"amount_credits": 500,"top_up_type": "UNCATEGORIZED",+ "amount_cents": 500,+ "currency": "usd",**BASE_PROPERTIES,}@@ -2543,6 +2651,8 @@ async def test_fulfill_checkout_tracks_credit_topup_success():{"id": "cs_test_topup","payment_status": "paid",+ "amount_total": 2750,+ "currency": "usd","payment_intent": stripe.PaymentIntent.construct_from({"id": "pi_test_topup"}, "k"),@@ -2578,9 +2688,13 @@ async def test_fulfill_checkout_tracks_credit_topup_success():_, kwargs = track_mock.call_argsassert kwargs["event"] == "topup_completed"assert kwargs["distinct_id"] == "user-1"+ # amount_cents is the session total actually charged (tax included), not+ # the credit amount.assert kwargs["properties"] == {"amount_credits": 2500,"top_up_type": "CHECKOUT",+ "amount_cents": 2750,+ "currency": "usd",**BASE_PROPERTIES,}diff --git a/autogpt_platform/backend/backend/data/onboarding.py b/autogpt_platform/backend/backend/data/onboarding.pyindex 94b48e7e4d..1deb5b08c6 100644--- a/autogpt_platform/backend/backend/data/onboarding.py+++ b/autogpt_platform/backend/backend/data/onboarding.py@@ -23,6 +23,7 @@ from backend.data.subscription_trial import get_subscription_trialfrom backend.data.user import get_user_by_idfrom backend.util.cache import cachedfrom backend.util.json import SafeJson+from backend.util.product_analytics import track_onboarding_completedfrom backend.util.timezone_utils import get_user_timezone_or_utc# Mapping from user reason id to categories to search for when choosing agent to show@@ -185,6 +186,8 @@ async def complete_onboarding_step(user_id: str, step: OnboardingStep):"completedSteps": list(set(onboarding.completedSteps + [str(step)])),},)+ if step == OnboardingStep.ONBOARDING_COMPLETE:+ track_onboarding_completed(user_id=user_id)await _reward_user(user_id, onboarding, step)await _send_onboarding_notification(user_id, step)diff --git a/autogpt_platform/backend/backend/data/onboarding_test.py b/autogpt_platform/backend/backend/data/onboarding_test.pyindex 197b1224d1..2807ea8eb2 100644--- a/autogpt_platform/backend/backend/data/onboarding_test.py+++ b/autogpt_platform/backend/backend/data/onboarding_test.py@@ -7,6 +7,7 @@ import pytest_mockfrom backend.data.onboarding import (OnboardingStep,_reward_user,+ complete_onboarding_step,format_onboarding_for_extraction,)@@ -162,3 +163,60 @@ def test_onboarding_step_values_are_plain_strings():# Legacy values that have been retired (e.g. VISIT_COPILOT) must not appear# in the active set — existing rows containing them remain inert strings.assert "VISIT_COPILOT" not in {step.value for step in OnboardingStep}+++def onboarding_writes(mocker: pytest_mock.MockFixture) -> Mock:+ mocker.patch("backend.data.onboarding._reward_user", AsyncMock())+ mocker.patch("backend.data.onboarding._send_onboarding_notification", AsyncMock())+ prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ prisma.return_value.update = AsyncMock()+ return mocker.patch("backend.data.onboarding.track_onboarding_completed")+++def _onboarding(completed: list[str]) -> Mock:+ onboarding = Mock()+ onboarding.completedSteps = completed+ return onboarding++[email protected](loop_scope="function")+async def test_completing_onboarding_sends_onboarding_completed(+ mocker: pytest_mock.MockFixture, onboarding_writes: Mock+):+ mocker.patch(+ "backend.data.onboarding.get_user_onboarding",+ AsyncMock(return_value=_onboarding([])),+ )++ await complete_onboarding_step("user-1", OnboardingStep.ONBOARDING_COMPLETE)++ onboarding_writes.assert_called_once_with(user_id="user-1")++[email protected](loop_scope="function")+async def test_onboarding_completed_is_sent_once_per_user(+ mocker: pytest_mock.MockFixture, onboarding_writes: Mock+):+ mocker.patch(+ "backend.data.onboarding.get_user_onboarding",+ AsyncMock(return_value=_onboarding([OnboardingStep.ONBOARDING_COMPLETE])),+ )++ await complete_onboarding_step("user-1", OnboardingStep.ONBOARDING_COMPLETE)++ onboarding_writes.assert_not_called()++[email protected](loop_scope="function")+async def test_other_onboarding_steps_send_no_onboarding_completed(+ mocker: pytest_mock.MockFixture, onboarding_writes: Mock+):+ mocker.patch(+ "backend.data.onboarding.get_user_onboarding",+ AsyncMock(return_value=_onboarding([])),+ )++ await complete_onboarding_step("user-1", OnboardingStep.MARKETPLACE_ADD_AGENT)++ onboarding_writes.assert_not_called()diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.pyindex 76c37de307..dd02979b3d 100644--- a/autogpt_platform/backend/backend/data/user.py+++ b/autogpt_platform/backend/backend/data/user.py@@ -13,7 +13,7 @@ from autogpt_libs.auth.models import DEFAULT_USER_IDfrom fastapi import HTTPExceptionfrom prisma.enums import BriefingFrequency, SubscriptionTierfrom prisma.errors import UniqueViolationError-from prisma.models import AuthUser+from prisma.models import AuthAccount, AuthUserfrom prisma.models import User as PrismaUserfrom prisma.types import (JsonFilter,@@ -40,6 +40,7 @@ from backend.util.cache import cachedfrom backend.util.encryption import JSONCryptorfrom backend.util.exceptions import DatabaseError, NotFoundErrorfrom backend.util.json import SafeJson+from backend.util.product_analytics import track_signup_completedfrom backend.util.settings import Settingsif TYPE_CHECKING:@@ -88,6 +89,9 @@ async def _get_or_create_user(user_data: dict) -> UserCreationResult:))was_created = True+ track_signup_completed(+ user_id=user.id, signup_method=await _signup_method(user.id, user_data)+ )else:was_created = False@@ -125,6 +129,42 @@ async def _get_or_create_user(user_data: dict) -> UserCreationResult:) from e+# Better Auth's providerId for an email + password account.+_BETTER_AUTH_EMAIL_PROVIDER = "credential"+++async def _signup_method(user_id: str, user_data: dict) -> str | None:+ """The auth provider the account was created with (``email``, ``google``, ...).++ Better Auth's token carries no provider, so it is read from the user's+ first ``AuthAccount`` row, which Better Auth writes before it issues the+ token. A Supabase token carries it in ``app_metadata`` instead; that is+ the fallback for a user with no account row.+ """+ try:+ account = await AuthAccount.prisma().find_first(+ where={"userId": user_id}, order={"createdAt": "asc"}+ )+ except Exception:+ # Analytics only: a failed lookup must not fail the signup.+ logger.warning("Failed to read the auth account of %s", user_id, exc_info=True)+ account = None+ if account is not None and account.providerId:+ if account.providerId == _BETTER_AUTH_EMAIL_PROVIDER:+ return "email"+ return account.providerId+ return _legacy_signup_method(user_data)+++def _legacy_signup_method(user_data: dict) -> str | None:+ """The provider from a Supabase token's ``app_metadata``."""+ app_metadata = user_data.get("app_metadata")+ if not isinstance(app_metadata, dict):+ return None+ provider = app_metadata.get("provider")+ return provider if isinstance(provider, str) and provider else None++# Word lists mirror the legacy generate_username() SQL function so that app-# and DB-generated handles look consistent._PROFILE_USERNAME_ADJECTIVES = (diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.pyindex 765589df3b..6c1b995b00 100644--- a/autogpt_platform/backend/backend/data/user_test.py+++ b/autogpt_platform/backend/backend/data/user_test.py@@ -398,6 +398,111 @@ class TestGetOrCreateUserStatus:assert result.was_created is Falsemock_prisma.user.create.assert_not_called()+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "provider_id,expected", [("google", "google"), ("credential", "email")]+ )+ async def test_new_user_sends_signup_completed_with_the_better_auth_provider(+ self, provider_id: str, expected: str+ ):+ # A Better Auth token has no app_metadata; the account row has it.+ db_user = MagicMock(id="user-new", email="[email protected]", name=None)++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(user_module, "AuthAccount") as auth_account,+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-new", "[email protected]"),+ ),+ patch.object(user_module, "track_signup_completed") as track,+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=None)+ mock_prisma.user.create = AsyncMock(return_value=db_user)+ find_first = AsyncMock(return_value=MagicMock(providerId=provider_id))+ auth_account.prisma.return_value.find_first = find_first++ await user_module.get_or_create_user_with_status(+ {"sub": "user-new", "email": "[email protected]"}+ )++ assert find_first.await_args.kwargs["where"] == {"userId": "user-new"}+ # The user id only: email and name never go into event properties.+ track.assert_called_once_with(user_id="user-new", signup_method=expected)++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "lookup",+ [+ AsyncMock(return_value=None),+ AsyncMock(side_effect=RuntimeError("auth tables unreachable")),+ ],+ )+ async def test_new_user_without_an_auth_account_falls_back_to_the_token(+ self, lookup: AsyncMock+ ):+ db_user = MagicMock(id="user-new", email="[email protected]", name=None)++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(user_module, "AuthAccount") as auth_account,+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-new", "[email protected]"),+ ),+ patch.object(user_module, "track_signup_completed") as track,+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=None)+ mock_prisma.user.create = AsyncMock(return_value=db_user)+ auth_account.prisma.return_value.find_first = lookup++ result = await user_module.get_or_create_user_with_status(+ {+ "sub": "user-new",+ "email": "[email protected]",+ "app_metadata": {"provider": "google", "providers": ["google"]},+ }+ )++ assert result.was_created is True+ track.assert_called_once_with(user_id="user-new", signup_method="google")++ @pytest.mark.asyncio+ async def test_existing_user_sends_no_signup_completed(self):+ db_user = MagicMock(id="user-existing", email="[email protected]", name=None)++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(+ user_module.User,+ "from_db",+ return_value=_application_user("user-existing", "[email protected]"),+ ),+ patch.object(user_module, "track_signup_completed") as track,+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=db_user)++ await user_module.get_or_create_user_with_status(+ {"sub": "user-existing", "email": "[email protected]"}+ )++ track.assert_not_called()+++ "user_data,expected",+ [+ ({"app_metadata": {"provider": "email"}}, "email"),+ ({"app_metadata": {"provider": ""}}, None),+ ({"app_metadata": "not-a-dict"}, None),+ ({}, None),+ ],+)+def test_legacy_signup_method_reads_the_supabase_provider(user_data: dict, expected):+ assert user_module._legacy_signup_method(user_data) == expected+class TestGetOrCreateUserProfile:"""get_or_create_user must guarantee a marketplace Profile exists, sincediff --git a/autogpt_platform/backend/backend/notifications/lifecycle.py b/autogpt_platform/backend/backend/notifications/lifecycle.pyindex 77c4b4c4a3..af67486cb8 100644--- a/autogpt_platform/backend/backend/notifications/lifecycle.py+++ b/autogpt_platform/backend/backend/notifications/lifecycle.py@@ -14,6 +14,7 @@ from datetime import datetime, timezoneimport stripefrom prisma.enums import NotificationType+from backend.data.credit import PAYMENT_FAILURE_CANCELLATION_COMMENTfrom backend.data.notifications import (AudienceAction,NotificationEventModel,@@ -34,12 +35,14 @@ from backend.notifications.lifecycle_plan import (format_date,plan_from_invoice,plan_from_subscription,+ tier_and_cycle_from_subscription,)from backend.notifications.queue import queue_audience_change, queue_notification_asyncfrom backend.notifications.subscriber_fields import audience_eventfrom backend.notifications.trial import notify_trial, on_trial_subscription_updatedfrom backend.util.clients import get_database_manager_async_clientfrom backend.util.logging import TruncatedLogger+from backend.util.product_analytics import track_subscription_endedfrom backend.util.settings import Settingslogger = TruncatedLogger(logging.getLogger(__name__), prefix="[Lifecycle]")@@ -297,7 +300,7 @@ async def on_subscription_deleted(subscription: dict) -> None:if not await claim_once(claim_key):return- reason = (subscription.get("cancellation_details") or {}).get("reason")+ reason = _churn_reason(subscription)plan = await plan_from_subscription(subscription)await _publish(NotificationEventModel[SubscriptionEndedData](@@ -312,6 +315,12 @@ async def on_subscription_deleted(subscription: dict) -> None:),claim_key,)+ # After the claim and the publish, so a Stripe replay cannot count the+ # same churn twice.+ tier, cycle = await tier_and_cycle_from_subscription(subscription)+ track_subscription_ended(+ user_id=user.id, subscription_tier=tier, billing_cycle=cycle, reason=reason+ )# Churned users get win-back only, never the monthly update.event = audience_event(AudienceAction.REMOVE_CHANGELOG,@@ -323,6 +332,15 @@ async def on_subscription_deleted(subscription: dict) -> None:await queue_audience_change(event)+def _churn_reason(subscription: dict) -> str | None:+ """Stripe's ``cancellation_details.reason``, except that our own cancel+ after a failed renewal is involuntary churn, not a requested one."""+ details = subscription.get("cancellation_details") or {}+ if details.get("comment") == PAYMENT_FAILURE_CANCELLATION_COMMENT:+ return "payment_failed"+ return details.get("reason")++async def _user_for(customer_id: object) -> BillingEmailRecipient | None:"""Skip deleted or unknown accounts rather than emailing into the void."""if not customer_id or not isinstance(customer_id, str):diff --git a/autogpt_platform/backend/backend/notifications/lifecycle_plan.py b/autogpt_platform/backend/backend/notifications/lifecycle_plan.pyindex 5d0defbb65..9393987c96 100644--- a/autogpt_platform/backend/backend/notifications/lifecycle_plan.py+++ b/autogpt_platform/backend/backend/notifications/lifecycle_plan.py@@ -10,6 +10,8 @@ import loggingfrom datetime import datetime, timezonefrom typing import Literal+from prisma.enums import SubscriptionTier+from backend.data.credit import build_price_to_tier_mapfrom backend.data.notifications import CardDetails, SubscriptionPlanfrom backend.notifications.stripe_payloads import StripeInvoice@@ -66,6 +68,15 @@ async def plan_from_invoice(invoice: dict) -> SubscriptionPlan:)+async def tier_and_cycle_from_subscription(+ subscription: dict,+) -> tuple[str | None, Literal["monthly", "yearly"]]:+ """The tier key (``PRO``) and cycle, in the form analytics reports them."""+ price = _first_price(subscription)+ tier = await _tier(price.get("id"))+ return (tier.value if tier else None), _cycle(price)++def card_from_invoice(invoice: dict) -> CardDetails:"""Card brand and last four for the "Card ···· 4242" row.@@ -110,11 +121,15 @@ def _cycle(price: dict) -> Literal["monthly", "yearly"]:async def _tier_name(price_id: str | None) -> str:+ tier = await _tier(price_id)+ return tier.value.title() if tier else "AutoGPT"+++async def _tier(price_id: str | None) -> SubscriptionTier | None:if not price_id:- return "AutoGPT"+ return Nonetry:- tier = (await build_price_to_tier_map()).get(price_id)+ return (await build_price_to_tier_map()).get(price_id)except Exception:logger.warning(f"Could not resolve tier for price {price_id}", exc_info=True)- return "AutoGPT"- return tier.value.title() if tier else "AutoGPT"+ return Nonediff --git a/autogpt_platform/backend/backend/notifications/lifecycle_test.py b/autogpt_platform/backend/backend/notifications/lifecycle_test.pyindex 89554668c3..2ca03952a6 100644--- a/autogpt_platform/backend/backend/notifications/lifecycle_test.py+++ b/autogpt_platform/backend/backend/notifications/lifecycle_test.py@@ -11,8 +11,9 @@ from datetime import datetime, timezonefrom unittest.mock import AsyncMock, patchimport pytest-from prisma.enums import NotificationType+from prisma.enums import NotificationType, SubscriptionTier+from backend.data.credit import PAYMENT_FAILURE_CANCELLATION_COMMENTfrom backend.data.notifications import (AudienceAction,NotificationResult,@@ -20,7 +21,7 @@ from backend.data.notifications import (SubscriptionPlan,SubscriptionStatus,)-from backend.notifications import lifecycle, subscriber_fields+from backend.notifications import lifecycle, lifecycle_plan, subscriber_fieldsfrom backend.notifications.lifecycle_plan import card_from_invoiceCUSTOMER = "cus_1"@@ -114,6 +115,11 @@ def _context(user, claim=True, audience_ok=True):return_value=NotificationResult(success=audience_ok, message="test")),),+ patch(+ "backend.notifications.lifecycle.tier_and_cycle_from_subscription",+ AsyncMock(return_value=("PRO", "monthly")),+ ),+ patch("backend.notifications.lifecycle.track_subscription_ended"),]@@ -122,7 +128,12 @@ async def _run(coro_factory, user, claim=True, audience_ok=True):started = [p.start() for p in patches]try:await coro_factory()- return {"notify": started[4], "audience": started[5], "claim": started[3]}+ return {+ "notify": started[4],+ "audience": started[5],+ "claim": started[3],+ "ended": started[7],+ }finally:for p in patches:p.stop()@@ -307,6 +318,93 @@ async def test_the_ended_email_branches_on_which_road_they_took():assert calls["notify"].await_args.args[0].data.due_to_payment is False+async def test_a_subscription_end_is_sent_to_analytics_once():+ calls = await _run(+ lambda: lifecycle.on_subscription_deleted(+ _subscription(cancellation_details={"reason": "payment_failed"})+ ),+ _User(),+ )+ calls["ended"].assert_called_once_with(+ user_id="user-1",+ subscription_tier="PRO",+ billing_cycle="monthly",+ reason="payment_failed",+ )++ # A Stripe replay finds the claim spent: no second churn.+ replay = await _run(+ lambda: lifecycle.on_subscription_deleted(_subscription()),+ _User(),+ claim=False,+ )+ replay["ended"].assert_not_called()+++async def test_our_own_cancel_after_a_failed_renewal_is_involuntary_churn():+ # Stripe stamps any API cancel "cancellation_requested"; the comment+ # handle_subscription_payment_failure leaves is what tells them apart.+ calls = await _run(+ lambda: lifecycle.on_subscription_deleted(+ _subscription(+ cancellation_details={+ "reason": "cancellation_requested",+ "comment": PAYMENT_FAILURE_CANCELLATION_COMMENT,+ }+ )+ ),+ _User(),+ )+ calls["ended"].assert_called_once_with(+ user_id="user-1",+ subscription_tier="PRO",+ billing_cycle="monthly",+ reason="payment_failed",+ )+ assert calls["notify"].await_args.args[0].data.due_to_payment is True+++async def test_a_failed_ended_email_sends_no_analytics_event():+ patches = _context(_User())+ started = [p.start() for p in patches]+ started[4].return_value = NotificationResult(success=False, message="down")+ with patch("backend.notifications.lifecycle.release_claim", AsyncMock()):+ try:+ with pytest.raises(RuntimeError):+ await lifecycle.on_subscription_deleted(_subscription())+ started[7].assert_not_called()+ finally:+ for p in patches:+ p.stop()+++async def test_tier_and_cycle_come_from_the_subscription_price():+ with patch.object(+ lifecycle_plan,+ "build_price_to_tier_map",+ AsyncMock(return_value={"price_1": SubscriptionTier.MAX}),+ ):+ yearly = _subscription()+ yearly["items"]["data"][0]["price"]["recurring"] = {"interval": "year"}+ assert await lifecycle_plan.tier_and_cycle_from_subscription(yearly) == (+ "MAX",+ "yearly",+ )++ with patch.object(+ lifecycle_plan,+ "build_price_to_tier_map",+ AsyncMock(side_effect=RuntimeError("LD down")),+ ):+ assert await lifecycle_plan.tier_and_cycle_from_subscription(+ _subscription()+ ) == (None, "monthly")++def test_the_platform_does_not_listen_for_trials():assert not hasattr(lifecycle, "on_trial_will_end")assert not any(name.endswith("TRIAL_ENDING") for name in dir(NotificationType))diff --git a/autogpt_platform/backend/backend/util/posthog_client.py b/autogpt_platform/backend/backend/util/posthog_client.pyindex 036b74979d..a4d210d4d8 100644--- a/autogpt_platform/backend/backend/util/posthog_client.py+++ b/autogpt_platform/backend/backend/util/posthog_client.py@@ -78,8 +78,9 @@ def capture("""if not distinct_id:return- event_name = event.value+ event_name = "<unknown>"try:+ event_name = event.valueclient = get_posthog_client()if client is None:returndiff --git a/autogpt_platform/backend/backend/util/posthog_client_test.py b/autogpt_platform/backend/backend/util/posthog_client_test.pyindex ebf540054f..75c9544dbe 100644--- a/autogpt_platform/backend/backend/util/posthog_client_test.py+++ b/autogpt_platform/backend/backend/util/posthog_client_test.py@@ -172,6 +172,15 @@ def test_capture_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:posthog_client.capture("user-1", PostHogEvent.CHAT_TOOL_CALLED)+def test_capture_never_raises_on_a_bad_event(monkeypatch: pytest.MonkeyPatch) -> None:+ client = Mock()+ monkeypatch.setattr(posthog_client, "get_posthog_client", lambda: client)++ posthog_client.capture("user-1", "chat_tool_called") # type: ignore[arg-type]++ client.capture.assert_not_called()++def test_capture_dedup_key_is_insert_id_and_a_stable_uuid(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/autogpt_platform/backend/backend/util/posthog_events.py b/autogpt_platform/backend/backend/util/posthog_events.pyindex c1074f6291..0c6cd6d16f 100644--- a/autogpt_platform/backend/backend/util/posthog_events.py+++ b/autogpt_platform/backend/backend/util/posthog_events.py@@ -66,16 +66,17 @@ class PostHogEvent(StrEnum):# person-update event, not a user action; keep it out of funnels.SET_PERSON_PROPERTIES = "$set"--class PlannedPostHogEvent(StrEnum):- """Planned in the tracking plan and NOT emitted yet (SECRT-2723).-- Move a member into ``PostHogEvent`` in the change that starts sending it.- """-+ # Key moments (SECRT-2723): backend/util/product_analytics.pySIGNUP_COMPLETED = "signup_completed"ONBOARDING_COMPLETED = "onboarding_completed"CHECKOUT_STARTED = "checkout_started"SUBSCRIPTION_ENDED = "subscription_ended"LISTING_ADDED_TO_LIBRARY = "listing_added_to_library"LISTING_DOWNLOADED = "listing_downloaded"+++class PlannedPostHogEvent(StrEnum):+ """Planned in the tracking plan and NOT emitted yet.++ Move a member into ``PostHogEvent`` in the change that starts sending it.+ """diff --git a/autogpt_platform/backend/backend/util/posthog_events_test.py b/autogpt_platform/backend/backend/util/posthog_events_test.pyindex 0fd768d150..1cca68c21c 100644--- a/autogpt_platform/backend/backend/util/posthog_events_test.py+++ b/autogpt_platform/backend/backend/util/posthog_events_test.py@@ -41,9 +41,6 @@ LIVE_EVENT_NAMES = {"trial_converted","payment_failed","$set",-}--PLANNED_EVENT_NAMES = {"signup_completed","onboarding_completed","checkout_started",@@ -52,6 +49,8 @@ PLANNED_EVENT_NAMES = {"listing_downloaded",}+PLANNED_EVENT_NAMES: set[str] = set()+# No longer sent, or renamed (SECRT-2722). The names stay reserved: reusing one would# splice a different action onto the history PostHog already holds for it.RETIRED_EVENT_NAMES = {diff --git a/autogpt_platform/backend/backend/util/product_analytics.py b/autogpt_platform/backend/backend/util/product_analytics.pyindex 4803225d1f..898ea2774f 100644--- a/autogpt_platform/backend/backend/util/product_analytics.py+++ b/autogpt_platform/backend/backend/util/product_analytics.py@@ -53,6 +53,7 @@ from collections.abc import Iterablefrom datetime import datetimefrom typing import TYPE_CHECKING, Any, Literal+from backend.data.experiments import list_assignmentsfrom backend.util import posthog_clientfrom backend.util.posthog_events import PostHogEvent@@ -336,6 +337,110 @@ def track_integration_connected()+CheckoutKind = Literal["subscription", "top_up", "trial"]+++def track_signup_completed(*, user_id: str, signup_method: str | None) -> None:+ """The user row was just created. ``signup_method`` is the auth provider."""+ track(user_id, PostHogEvent.SIGNUP_COMPLETED, {"signup_method": signup_method})+++def track_onboarding_completed(*, user_id: str) -> None:+ track(user_id, PostHogEvent.ONBOARDING_COMPLETED)+++async def track_checkout_started(+ *,+ user_id: str,+ checkout_kind: CheckoutKind,+ surface: str | None = None,+ subscription_tier: str | None = None,+ billing_cycle: str | None = None,+) -> None:+ """A Stripe Checkout session was created and the user is sent to it.++ Carries the user's recorded experiment arms as ``$feature/<key>``, the+ property PostHog experiments read, so the pricing test can use this+ server-side event as a goal just like the browser's own events.+ """+ try:+ arms = await _experiment_arm_properties(user_id)+ except Exception:+ logger.warning("Failed to read experiment arms for user %s", user_id)+ arms = {}+ track(+ user_id,+ PostHogEvent.CHECKOUT_STARTED,+ {+ **arms,+ "checkout_kind": checkout_kind,+ "surface": surface,+ "subscription_tier": _enum_value(subscription_tier),+ "billing_cycle": billing_cycle,+ },+ )+++async def _experiment_arm_properties(user_id: str) -> dict[str, str]:+ return {+ f"$feature/{assignment.experiment_key}": assignment.variant+ for assignment in await list_assignments(user_id)+ }+++def track_subscription_ended(+ *,+ user_id: str,+ subscription_tier: str | None,+ billing_cycle: str | None,+ reason: str | None,+) -> None:+ track(+ user_id,+ PostHogEvent.SUBSCRIPTION_ENDED,+ {+ "subscription_tier": subscription_tier,+ "billing_cycle": billing_cycle,+ "reason": reason,+ },+ )+++def track_listing_added_to_library(+ *,+ user_id: str,+ store_listing_version_id: str,+ graph_id: str,+ library_agent_id: str,+) -> None:+ """Deduplicated on the library entry: two concurrent adds of the same+ listing both reach here, the loser having restored the winner's row."""+ track(+ user_id,+ PostHogEvent.LISTING_ADDED_TO_LIBRARY,+ {+ "store_listing_version_id": store_listing_version_id,+ "graph_id": graph_id,+ "library_agent_id": library_agent_id,+ },+ dedup_key=library_agent_id,+ )+++def track_listing_downloaded(+ *,+ user_id: str | None,+ store_listing_version_id: str,+ graph_id: str,+) -> None:+ """A signed-out download has no user, so ``track`` drops it."""+ track(+ user_id,+ PostHogEvent.LISTING_DOWNLOADED,+ {"store_listing_version_id": store_listing_version_id, "graph_id": graph_id},+ )++def track_credential_oauth_started(*, user_id: str, provider: str) -> None:track(user_id,diff --git a/autogpt_platform/backend/backend/util/product_analytics_test.py b/autogpt_platform/backend/backend/util/product_analytics_test.pyindex fb2cb5708e..eeada29c44 100644--- a/autogpt_platform/backend/backend/util/product_analytics_test.py+++ b/autogpt_platform/backend/backend/util/product_analytics_test.py@@ -1,10 +1,12 @@"""Tests for the activation event vocabulary and its emitters."""import time+from datetime import datetime, timezonefrom unittest.mock import Mockimport pytest+from backend.data.experiments import ExperimentAssignmentfrom backend.util import posthog_client, product_analyticsfrom backend.util.posthog_events import PostHogEvent@@ -350,6 +352,142 @@ def test_trigger_fired(capture: Mock) -> None:assert properties["target"] == "expert"+def test_signup_completed_carries_the_auth_provider(capture: Mock) -> None:+ product_analytics.track_signup_completed(user_id="user-1", signup_method="google")++ event, properties = _only_call(capture)+ assert capture.call_args.kwargs["distinct_id"] == "user-1"+ assert event == "signup_completed"+ assert properties["signup_method"] == "google"+++def test_signup_completed_without_a_known_provider_omits_it(capture: Mock) -> None:+ product_analytics.track_signup_completed(user_id="user-1", signup_method=None)++ _, properties = _only_call(capture)+ assert "signup_method" not in properties+++def test_onboarding_completed(capture: Mock) -> None:+ product_analytics.track_onboarding_completed(user_id="user-1")++ event, properties = _only_call(capture)+ assert event == "onboarding_completed"+ assert properties["source"] == "platform"+++async def test_checkout_started_carries_plan_surface_and_experiment_arms(+ capture: Mock, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def arms(user_id: str) -> dict[str, str]:+ assert user_id == "user-1"+ return {"$feature/subscription-pricing-page-initial-state": "yearly-pro"}++ monkeypatch.setattr(product_analytics, "_experiment_arm_properties", arms)++ await product_analytics.track_checkout_started(+ user_id="user-1",+ checkout_kind="subscription",+ surface="onboarding",+ subscription_tier="PRO",+ billing_cycle="yearly",+ )++ event, properties = _only_call(capture)+ assert event == "checkout_started"+ assert properties["checkout_kind"] == "subscription"+ assert properties["surface"] == "onboarding"+ assert properties["subscription_tier"] == "PRO"+ assert properties["billing_cycle"] == "yearly"+ assert (+ properties["$feature/subscription-pricing-page-initial-state"] == "yearly-pro"+ )+++async def test_checkout_started_still_sends_when_arms_cannot_be_read(+ capture: Mock, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def broken(user_id: str) -> dict[str, str]:+ raise RuntimeError("db down")++ monkeypatch.setattr(product_analytics, "_experiment_arm_properties", broken)++ await product_analytics.track_checkout_started(+ user_id="user-1", checkout_kind="top_up", surface="billing"+ )++ event, properties = _only_call(capture)+ assert event == "checkout_started"+ assert properties["checkout_kind"] == "top_up"+ assert "subscription_tier" not in properties+ assert not any(key.startswith("$feature/") for key in properties)+++async def test_experiment_arms_become_feature_properties(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def list_assignments(user_id: str) -> list[ExperimentAssignment]:+ return [+ ExperimentAssignment(+ experiment_key="subscription-pricing-page-initial-state",+ variant="monthly-max",+ source="posthog",+ assigned_at=datetime.now(timezone.utc),+ )+ ]++ monkeypatch.setattr(product_analytics, "list_assignments", list_assignments)++ assert await product_analytics._experiment_arm_properties("user-1") == {+ "$feature/subscription-pricing-page-initial-state": "monthly-max"+ }+++def test_subscription_ended(capture: Mock) -> None:+ product_analytics.track_subscription_ended(+ user_id="user-1",+ subscription_tier="MAX",+ billing_cycle="monthly",+ reason="payment_failed",+ )++ event, properties = _only_call(capture)+ assert event == "subscription_ended"+ assert properties["subscription_tier"] == "MAX"+ assert properties["billing_cycle"] == "monthly"+ assert properties["reason"] == "payment_failed"+++def test_listing_added_to_library_and_downloaded(capture: Mock) -> None:+ product_analytics.track_listing_added_to_library(+ user_id="user-1",+ store_listing_version_id="slv-1",+ graph_id="graph-1",+ library_agent_id="lib-1",+ )+ product_analytics.track_listing_downloaded(+ user_id="user-1", store_listing_version_id="slv-1", graph_id="graph-1"+ )++ added, downloaded = capture.call_args_list+ assert added.kwargs["event"] == "listing_added_to_library"+ assert added.kwargs["properties"]["library_agent_id"] == "lib-1"+ assert added.kwargs["properties"]["$insert_id"] == "lib-1"+ assert downloaded.kwargs["event"] == "listing_downloaded"+ assert downloaded.kwargs["properties"]["store_listing_version_id"] == "slv-1"+++def test_signed_out_download_is_not_tracked(capture: Mock) -> None:+ product_analytics.track_listing_downloaded(+ user_id=None, store_listing_version_id="slv-1", graph_id="graph-1"+ )++ capture.assert_not_called()++def test_credential_oauth_started(capture: Mock, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.tsindex e0706107e7..33cca00a54 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.ts@@ -8,6 +8,11 @@ vi.mock("@/services/analytics", () => ({analytics: { sendDatafastEvent },}));+const { posthog } = vi.hoisted(() => ({+ posthog: { __loaded: true, is_capturing: () => true, capture: vi.fn() },+}));+vi.mock("posthog-js", () => ({ default: posthog }));+import {buildStepLayout,NO_PAYWALL_STEPS,@@ -65,9 +70,35 @@ describe("trackOnboardingStep", () => {beforeEach(() => {vi.restoreAllMocks();sendDatafastEvent.mockReset();+ posthog.capture.mockReset();sessionStorage.clear();});+ // PostHog gets one event with the step as a property; DataFast keeps its+ // goal per step.+ it("reports each step to PostHog once, as onboarding_step_viewed", () => {+ trackOnboardingStep("role");+ trackOnboardingStep("role");+ trackOnboardingStep("hire");++ expect(posthog.capture.mock.calls).toEqual([+ ["onboarding_step_viewed", { step: "role" }],+ ["onboarding_step_viewed", { step: "hire" }],+ ]);+ });++ it("still reports to PostHog when the DataFast script throws", () => {+ sendDatafastEvent.mockImplementation(() => {+ throw new Error("datafast unavailable");+ });++ trackOnboardingStep("team");++ expect(posthog.capture).toHaveBeenCalledWith("onboarding_step_viewed", {+ step: "team",+ });+ });+it("reports one goal per step name", () => {trackOnboardingStep("role");trackOnboardingStep("pain_points");diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/__tests__/tracking.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/__tests__/tracking.test.tsindex 46664035e0..ac9282201f 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/__tests__/tracking.test.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/__tests__/tracking.test.ts@@ -8,7 +8,65 @@ vi.mock("@/services/analytics", () => ({analytics: { sendDatafastEvent },}));-import { trackPaywallView } from "../tracking";+const { posthog } = vi.hoisted(() => ({+ posthog: { __loaded: true, is_capturing: () => true, capture: vi.fn() },+}));+vi.mock("posthog-js", () => ({ default: posthog }));++import {+ markPaywallCheckoutStarted,+ trackPaywallCheckoutCancelled,+ trackPaywallView,+} from "../tracking";++describe("PostHog paywall funnel", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ sendDatafastEvent.mockReset();+ posthog.capture.mockReset();+ sessionStorage.clear();+ });++ it("reports the onboarding paywall view once per tab", () => {+ trackPaywallView();+ trackPaywallView();++ expect(posthog.capture.mock.calls).toEqual([+ ["paywall_viewed", { surface: "onboarding" }],+ ]);+ });++ it("reports the return from Stripe without paying as checkout_abandoned", () => {+ trackPaywallCheckoutCancelled();+ trackPaywallCheckoutCancelled();++ expect(posthog.capture.mock.calls).toEqual([+ [+ "checkout_abandoned",+ { checkout_kind: "subscription", surface: "onboarding" },+ ],+ ]);+ });++ it("counts a second abandonment after a new checkout starts", () => {+ trackPaywallCheckoutCancelled();+ markPaywallCheckoutStarted();+ trackPaywallCheckoutCancelled();+ // The refresh after the second return is still guarded.+ trackPaywallCheckoutCancelled();++ expect(posthog.capture.mock.calls).toEqual([+ [+ "checkout_abandoned",+ { checkout_kind: "subscription", surface: "onboarding" },+ ],+ [+ "checkout_abandoned",+ { checkout_kind: "subscription", surface: "onboarding" },+ ],+ ]);+ });+});describe("trackPaywallView", () => {beforeEach(() => {diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/helpers.tsindex 7ed9a083c3..20bd011546 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/helpers.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/helpers.ts@@ -77,6 +77,19 @@ export function getSubscriptionPricingExperimentConfig(return DEFAULT_EXPERIMENT_CONFIG;}+// The arm to report on `plan_selected`: only one PostHog actually assigned.+// Unresolved flags and users outside the rollout render the control layout+// but are not in the control arm, so reporting "control" for them would+// inflate it.+export function getReportedPricingVariant(+ variant: string | null,+ isResolved: boolean,+) {+ if (!isResolved || variant === null) return undefined;+ if (variant !== "control" && !isExperimentVariant(variant)) return undefined;+ return variant;+}+export function getSubscriptionPricingExperimentPlans(highlightedPlan: HighlightedPlanKey | null,plans: PlanDef[] = PLANS,diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/tracking.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/tracking.tsindex 3c4f2b2dc1..9c6e91c695 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/tracking.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/tracking.ts@@ -1,4 +1,8 @@import { analytics } from "@/services/analytics";+import {+ trackCheckoutAbandoned,+ trackPaywallViewed,+} from "@/services/analytics/monetization-analytics";const PAYWALL_VIEW_SESSION_KEY = "paywall_view_tracked";@@ -23,6 +27,10 @@ const PAYWALL_VIEW_SESSION_KEY = "paywall_view_tracked";* the key unset and reports normally.*/export function trackPaywallView() {+ // PostHog keeps its own once-per-tab guard, marked only once the event is+ // sent or dropped for lack of consent, not while it waits for the answer.+ trackPaywallViewed("onboarding");+try {if (sessionStorage.getItem(PAYWALL_VIEW_SESSION_KEY)) return;sessionStorage.setItem(PAYWALL_VIEW_SESSION_KEY, "1");@@ -42,6 +50,21 @@ export function trackPaywallView() {}const CHECKOUT_CANCELLED_SESSION_KEY = "paywall_checkout_cancelled_tracked";+const POSTHOG_CHECKOUT_CANCELLED_KEY =+ "posthog_checkout_abandoned_onboarding_subscription";++/**+ * Re-arms the PostHog abandonment guard when a new Checkout starts, so a second+ * real abandonment in the same tab still counts; a refresh after the return+ * stays guarded.+ */+export function markPaywallCheckoutStarted() {+ try {+ sessionStorage.removeItem(POSTHOG_CHECKOUT_CANCELLED_KEY);+ } catch {+ // In-app browsers may block sessionStorage; the guard is then unset anyway.+ }+}/*** Reports that the user reached Stripe Checkout and came back without paying.@@ -56,6 +79,11 @@ const CHECKOUT_CANCELLED_SESSION_KEY = "paywall_checkout_cancelled_tracked";* would otherwise report the same abandonment again.*/export function trackPaywallCheckoutCancelled() {+ trackCheckoutAbandoned(+ { checkout_kind: "subscription", surface: "onboarding" },+ POSTHOG_CHECKOUT_CANCELLED_KEY,+ );+try {if (sessionStorage.getItem(CHECKOUT_CANCELLED_SESSION_KEY)) return;sessionStorage.setItem(CHECKOUT_CANCELLED_SESSION_KEY, "1");diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionPricingExperiment.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionPricingExperiment.tsindex 287d45168a..dd4ee0b364 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionPricingExperiment.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionPricingExperiment.ts@@ -4,6 +4,7 @@ import { useExperiment } from "@/services/experiments/useExperiment";import { useEffect } from "react";import { useOnboardingWizardStore } from "../../store";import {+ getReportedPricingVariant,getSubscriptionPricingExperimentConfig,getSubscriptionPricingExperimentPlans,SUBSCRIPTION_PRICING_EXPERIMENT_FLAG,@@ -33,7 +34,7 @@ export function useSubscriptionPricingExperiment() {return {billing: hasUserSelectedBilling ? selectedBilling : config.billing,plans: getSubscriptionPricingExperimentPlans(config.highlightedPlan),- variant: config.variant,+ pricingVariant: getReportedPricingVariant(variant, isResolved),isResolved,};}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.tsindex 9240e90eb9..9afb472366 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts@@ -17,7 +17,12 @@ import {} from "@/components/molecules/PlanCard/plans";import { useSubscriptionPricingExperiment } from "./useSubscriptionPricingExperiment";import { useMountEffect } from "@/hooks/useMountEffect";-import { trackPaywallCheckoutCancelled, trackPaywallView } from "./tracking";+import {+ markPaywallCheckoutStarted,+ trackPaywallCheckoutCancelled,+ trackPaywallView,+} from "./tracking";+import { trackPlanSelected } from "@/services/analytics/monetization-analytics";const PLAN_TO_TIER: Record<Exclude<PlanKey, typeof PLAN_KEYS.TEAM | typeof PLAN_KEYS.BUSINESS>,@@ -46,7 +51,7 @@ export function useSubscriptionStep() {const { mutateAsync: updateTier, isPending: isUpdatingTier } =useUpdateSubscriptionTier();- const { billing, plans } = useSubscriptionPricingExperiment();+ const { billing, plans, pricingVariant } = useSubscriptionPricingExperiment();const searchParams = useSearchParams();// This step only mounts once the paywall is genuinely on screen, so mount is@@ -73,13 +78,24 @@ export function useSubscriptionStep() {const country = COUNTRIES[countryIdx];const isYearly = billing === "yearly";+ function reportPlanSelected(planKey: PlanKey) {+ trackPlanSelected({+ subscription_tier: planKey === PLAN_KEYS.TEAM ? "BUSINESS" : planKey,+ billing_cycle: isYearly ? "yearly" : "monthly",+ surface: "onboarding",+ ...(pricingVariant && { pricing_variant: pricingVariant }),+ });+ }+async function handlePlanSelect(planKey: PlanKey) {if (planKey === PLAN_KEYS.TEAM) {+ reportPlanSelected(planKey);window.open(TEAM_INTAKE_FORM_URL, "_blank", "noopener,noreferrer");return;}if (planKey === PLAN_KEYS.BUSINESS) return;if (isProcessing) return;+ reportPlanSelected(planKey);setIsSubmitting(true);// Local dev: backend has no Stripe wiring, so skip the checkout@@ -109,6 +125,7 @@ export function useSubscriptionStep() {success_url: `${baseUrl}?step=${(steps.subscription ?? currentStep) + 1}&subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${planKey}&cycle=${cycle}`,cancel_url: `${baseUrl}?step=${steps.subscription ?? currentStep}&subscription=cancelled`,billing_cycle: cycle,+ surface: "onboarding",},});const url = (result?.data as CheckoutResponse | undefined)?.url;@@ -119,6 +136,7 @@ export function useSubscriptionStep() {trackAdsConversion("begin_checkout", {value: getSubscriptionValue(planKey, cycle),});+ markPaywallCheckoutStarted();// Navigating away — don't refetch (would set state on an// unmounting component while Stripe Checkout takes over).window.location.href = url;diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsxindex b60c9a065c..707c40237e 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx@@ -14,6 +14,7 @@ import {} from "@/tests/integrations/gtag-shim";import { useOnboardingWizardStore } from "../../store";import {+ getReportedPricingVariant,getSubscriptionPricingExperimentConfig,getSubscriptionPricingExperimentPlans,} from "../SubscriptionStep/helpers";@@ -28,6 +29,13 @@ vi.mock("@posthog/react", () => ({usePostHog: () => undefined,}));+const posthogJS = vi.hoisted(() => ({+ __loaded: true,+ is_capturing: () => true,+ capture: vi.fn(),+}));+vi.mock("posthog-js", () => ({ default: posthogJS }));+vi.mock("@/components/atoms/FadeIn/FadeIn", () => ({FadeIn: ({ children }: { children: React.ReactNode }) => (<div>{children}</div>@@ -49,6 +57,8 @@ afterEach(() => {beforeEach(() => {postHog.variant = undefined;+ posthogJS.capture.mockClear();+ sessionStorage.clear();useOnboardingWizardStore.getState().reset();// The paywall is the last interactive step (step 3), before Preparing.useOnboardingWizardStore.getState().goToStep(3);@@ -136,6 +146,15 @@ describe("subscription pricing experiment helpers", () => {buttonVariant: "primary",});});++ test("reports a pricing arm only once PostHog has assigned a real one", () => {+ expect(getReportedPricingVariant("yearly-max", true)).toBe("yearly-max");+ expect(getReportedPricingVariant("control", true)).toBe("control");+ // Still loading flags, not enrolled, or an arm this page does not know.+ expect(getReportedPricingVariant("yearly-max", false)).toBeUndefined();+ expect(getReportedPricingVariant(null, true)).toBeUndefined();+ expect(getReportedPricingVariant("annual-team", true)).toBeUndefined();+ });});describe("SubscriptionStep", () => {@@ -364,6 +383,62 @@ describe("SubscriptionStep", () => {expect(useOnboardingWizardStore.getState().selectedPlan).toBe("MAX");});+ test("reports the paywall view and the picked plan with its pricing arm to PostHog", async () => {+ postHog.variant = "yearly-max";+ let capturedTierBody: { surface?: string } | null = null;+ server.use(+ http.post("*/api/credits/subscription", async ({ request }) => {+ capturedTierBody = (await request.json()) as typeof capturedTierBody;+ return HttpResponse.json({ url: null });+ }),+ );++ render(<SubscriptionStep />);+ await waitFor(() => {+ expect(useOnboardingWizardStore.getState().selectedBilling).toBe(+ "yearly",+ );+ });+ fireEvent.click(screen.getByRole("button", { name: /Upgrade to Max/i }));++ await waitFor(() => {+ expect(capturedTierBody).not.toBeNull();+ });+ // The backend reads `surface` for its checkout_started event.+ expect(capturedTierBody!.surface).toBe("onboarding");+ expect(posthogJS.capture).toHaveBeenCalledWith("paywall_viewed", {+ surface: "onboarding",+ });+ expect(posthogJS.capture).toHaveBeenCalledWith("plan_selected", {+ subscription_tier: "MAX",+ billing_cycle: "yearly",+ surface: "onboarding",+ pricing_variant: "yearly-max",+ });+ });++ // PostHog answers `false` for a user outside the rollout. They see the+ // control layout but are not in the control arm.+ test("reports no pricing arm for a user the experiment did not enrol", async () => {+ postHog.variant = false;+ server.use(+ http.post("*/api/credits/subscription", () =>+ HttpResponse.json({ url: null }),+ ),+ );++ render(<SubscriptionStep />);+ fireEvent.click(screen.getByRole("button", { name: /Upgrade to Max/i }));++ await waitFor(() => {+ expect(posthogJS.capture).toHaveBeenCalledWith("plan_selected", {+ subscription_tier: "MAX",+ billing_cycle: "monthly",+ surface: "onboarding",+ });+ });+ });+test("selecting Team opens the intake form and does not advance", () => {const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);try {diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsxindex c3348214d0..1e14e64eed 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx@@ -109,14 +109,38 @@ test.each([offer_token: trialOffer.token,return_to: "onboarding",});- expect(posthog.capture).toHaveBeenCalledWith(+ // The backend sends checkout_started (checkout_kind: trial) once the+ // Checkout session exists, so the browser sends no checkout event.+ expect(posthog.capture).not.toHaveBeenCalledWith("subscription_trial_checkout_started",- { trial_offer_version: trialOffer.version, surface: "onboarding" },+ expect.anything(),);expect(useOnboardingWizardStore.getState().selectedPlan).toBeNull();},);+test("re-arms trial abandonment tracking when a new trial checkout starts", async () => {+ // Left by an earlier abandonment in this tab: without clearing it, backing+ // out of this checkout too would go unreported.+ sessionStorage.setItem("posthog_trial_checkout_abandoned_onboarding", "1");+ mockStatus();+ server.use(+ getPostTrialsStartTrialCheckoutMockHandler200({+ url: "https://checkout.stripe.com/trial",+ }),+ );+ render(<SubscriptionStep />);+ const card = within(await screen.findByRole("region", { name: "Pro plan" }));+ fireEvent.click(+ await card.findByRole("button", { name: "Start 7-day trial" }),+ );++ await waitFor(() => expect(checkoutLocation.assign).toHaveBeenCalled());+ expect(+ sessionStorage.getItem("posthog_trial_checkout_abandoned_onboarding"),+ ).toBeNull();+});+test("uses the server's duration, currency, renewal cycle, and terms", async () => {mockStatus(eligible({diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/tracking.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/tracking.tsindex 2e4f8b5e30..c26c8eb413 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/tracking.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/tracking.ts@@ -1,4 +1,6 @@import { analytics } from "@/services/analytics";+import { capturePostHogEvent } from "@/services/analytics/posthog-capture";+import { OnboardingEvent } from "@/services/analytics/posthog-events";import type { StepLayout } from "./store";export type OnboardingStepKey =@@ -11,6 +13,7 @@ export type OnboardingStepKey =| "preparing";const SENT_KEY_PREFIX = "onboarding_step_sent_";+const POSTHOG_SENT_KEY_PREFIX = "posthog_onboarding_step_viewed_";/*** Maps a wizard step number to a stable key.@@ -47,6 +50,16 @@ export function onboardingStepKey(* ordered funnel.*/export function trackOnboardingStep(key: OnboardingStepKey) {+ // PostHog funnels order steps by their filter, so one event with a `step`+ // property serves where DataFast needs a goal per step. Its once-per-tab+ // guard is its own, marked only once the event is sent or dropped for lack+ // of consent, not while it waits for the answer.+ capturePostHogEvent(+ OnboardingEvent.ONBOARDING_STEP_VIEWED,+ { step: key },+ { oncePerTabKey: `${POSTHOG_SENT_KEY_PREFIX}${key}` },+ );+const sentKey = `${SENT_KEY_PREFIX}${key}`;try {if (sessionStorage.getItem(sentKey)) return;diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.tsindex 818f4499e7..fa26953882 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts@@ -8,6 +8,7 @@ import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/import { resolveResponse } from "@/app/api/helpers";import { useAuth } from "@/lib/auth/hooks/useAuth";import { trackAdsConversion } from "@/services/analytics/google-ads";+import { trackTrialCheckoutAbandoned } from "@/services/analytics/monetization-analytics";import { environment } from "@/services/environment";import { useTrialCheckoutReturn } from "@/services/trials/useTrialCheckoutReturn";import {@@ -162,6 +163,10 @@ export function useOnboardingPage() {useEffect(() => {if (!isReady || hasInitialized.current) return;hasInitialized.current = true;+ // Read before the URL sync below rewrites the query to `?step=N`.+ if (searchParams.get("trial") === "cancelled") {+ trackTrialCheckoutAbandoned("onboarding");+ }const urlStep = parseStepParam(searchParams.get("step"), preparingStep);// The paywall is the first step, so a successful Stripe checkout return// is a trusted intent to advance past it onto the step after it and startdiff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsxindex 09dd366a00..0acf0f8d7c 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.test.tsx@@ -2,7 +2,7 @@ import {installGtagShim,removeGtagShim,} from "@/tests/integrations/gtag-shim";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {render,screen,@@ -19,6 +19,13 @@ vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({useUpdateSubscriptionTier: () => mockUseUpdateSubscriptionTier(),}));+const posthog = vi.hoisted(() => ({+ __loaded: true,+ is_capturing: () => true,+ capture: vi.fn(),+}));+vi.mock("posthog-js", () => ({ default: posthog }));+const mockToast = vi.fn();vi.mock("@/components/molecules/Toast/use-toast", () => ({toast: (args: unknown) => mockToast(args),@@ -380,7 +387,11 @@ describe("PaywallModal — upgrade mutation", () => {expect(mutateFn).toHaveBeenCalledTimes(1);});const [args] = mutateFn.mock.calls[0];- expect(args.data.cancel_url).toBe("https://app.test/copilot");+ // Same page, plus the marker that reports the abandoned checkout.+ expect(args.data.cancel_url).toBe(+ "https://app.test/copilot?paywall_checkout=cancelled",+ );+ expect(args.data.surface).toBe("paywall_gate");// Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page// report the subscription to Google Ads.expect(args.data.success_url).toBe(@@ -663,3 +674,90 @@ describe("PaywallModal — empty / loading states", () => {).toBeNull();});});++describe("PaywallModal — PostHog paywall funnel", () => {+ const originalLocation = window.location;++ beforeEach(() => {+ // paywall_viewed is once per tab; earlier renders in this file set it.+ sessionStorage.clear();+ });++ afterEach(() => {+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: originalLocation,+ });+ posthog.capture.mockClear();+ sessionStorage.clear();+ });++ function eventsNamed(name: string) {+ return posthog.capture.mock.calls.filter(([event]) => event === name);+ }++ it("reports the paywall view and the picked plan", async () => {+ const { mutateFn } = setupMocks({+ subscription: { tier: "NO_TIER", tier_costs: { PRO: 5000, MAX: 32000 } },+ });++ render(<PaywallModal />);+ fireEvent.click(screen.getByRole("button", { name: /upgrade to max/i }));++ await waitFor(() => {+ expect(mutateFn).toHaveBeenCalledTimes(1);+ });+ expect(eventsNamed("paywall_viewed")).toEqual([+ ["paywall_viewed", { surface: "paywall_gate" }],+ ]);+ expect(eventsNamed("plan_selected")).toEqual([+ [+ "plan_selected",+ {+ subscription_tier: "MAX",+ billing_cycle: "monthly",+ surface: "paywall_gate",+ },+ ],+ ]);+ expect(eventsNamed("checkout_abandoned")).toEqual([]);+ });++ // Backing out of Stripe lands on the same page with the marker the cancel+ // URL carried; it is reported once and removed so a refresh stays quiet.+ it("reports the return from Stripe without paying and drops the marker", () => {+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: {+ origin: "https://app.test",+ href: "https://app.test/copilot?paywall_checkout=cancelled",+ },+ });+ const historySpy = vi+ .spyOn(window.history, "replaceState")+ .mockImplementation(() => {});+ setupMocks({+ subscription: { tier: "NO_TIER", tier_costs: { PRO: 5000 } },+ });++ try {+ render(<PaywallModal />);++ expect(eventsNamed("checkout_abandoned")).toEqual([+ [+ "checkout_abandoned",+ { checkout_kind: "subscription", surface: "paywall_gate" },+ ],+ ]);+ expect(historySpy).toHaveBeenCalledTimes(1);+ // Null, not Next's own state: with it Next skips syncing its router URL+ // and writes the marker back on its next update.+ expect(historySpy.mock.calls[0][0]).toBeNull();+ expect(historySpy.mock.calls[0][2]).toBe("/copilot");+ } finally {+ historySpy.mockRestore();+ }+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsxindex 50667b62ba..5917234f84 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/__tests__/PaywallModal.trial.test.tsx@@ -165,9 +165,11 @@ test.each([offer_token: trialOffer.token,return_to: "billing",});- expect(posthog.capture).toHaveBeenCalledWith(+ // The backend sends checkout_started (checkout_kind: trial) once the+ // Checkout session exists, so the browser sends no checkout event.+ expect(posthog.capture).not.toHaveBeenCalledWith("subscription_trial_checkout_started",- { trial_offer_version: trialOffer.version, surface: "billing" },+ expect.anything(),);},);diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/helpers.tsnew file mode 100644index 0000000000..df27abae05--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/helpers.ts@@ -0,0 +1,40 @@+const CHECKOUT_CANCELLED_PARAM = "paywall_checkout";+const CHECKOUT_CANCELLED_VALUE = "cancelled";++// Backing out of Stripe must land on the page the user was on, so the gate+// re-applies. The marker is the only way that return is told apart from any+// other visit to the same page. It only feeds analytics, so an unparseable+// URL falls back to the plain page rather than blocking checkout.+export function buildPaywallCancelUrl(href: string) {+ try {+ const url = new URL(href);+ url.searchParams.set(CHECKOUT_CANCELLED_PARAM, CHECKOUT_CANCELLED_VALUE);+ return url.toString();+ } catch {+ return href;+ }+}++// Reads the marker once and drops it from the address bar, so a refresh or a+// shared link does not report the same abandonment again. The state is null+// on purpose: Next's own history state would make it skip syncing its router+// URL, and its next update would write the marker back.+export function consumePaywallCheckoutCancel() {+ try {+ const url = new URL(window.location.href);+ if (+ url.searchParams.get(CHECKOUT_CANCELLED_PARAM) !==+ CHECKOUT_CANCELLED_VALUE+ )+ return false;+ url.searchParams.delete(CHECKOUT_CANCELLED_PARAM);+ window.history.replaceState(+ null,+ "",+ `${url.pathname}${url.search}${url.hash}`,+ );+ return true;+ } catch {+ return false;+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.tsindex da79ecaa86..a1e65a8d04 100644--- a/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts+++ b/autogpt_platform/frontend/src/app/(platform)/PaywallGate/usePaywallModal.ts@@ -24,6 +24,12 @@ import {getSubscriptionValue,trackAdsConversion,} from "@/services/analytics/google-ads";+import {+ trackCheckoutAbandoned,+ trackPaywallViewed,+ trackPlanSelected,+} from "@/services/analytics/monetization-analytics";+import { buildPaywallCancelUrl, consumePaywallCheckoutCancel } from "./helpers";interface CheckoutResponse {url?: string;@@ -79,6 +85,13 @@ export function usePaywallModal() {// calls can only 401.useMountEffect(() => {void validateSession();+ trackPaywallViewed("paywall_gate");+ if (consumePaywallCheckoutCancel()) {+ trackCheckoutAbandoned({+ checkout_kind: "subscription",+ surface: "paywall_gate",+ });+ }});const [selectedCycle, setSelectedCycle] = useState<"monthly" | "yearly">("monthly",@@ -123,8 +136,9 @@ export function usePaywallModal() {// was on so the paywall re-gates immediately. /profile/* is// paywall-exempt — landing there let users wander an app that// looks unlocked until the next non-exempt navigation.- cancel_url: window.location.href,+ cancel_url: buildPaywallCancelUrl(window.location.href),billing_cycle: cycle,+ surface: "paywall_gate",},});const url = (result?.data as CheckoutResponse | undefined)?.url;@@ -161,6 +175,11 @@ export function usePaywallModal() {async function handleSelectPlan(tier: string) {if (isPending) return;+ trackPlanSelected({+ subscription_tier: tier,+ billing_cycle: selectedCycle,+ surface: "paywall_gate",+ });// Team (BUSINESS) is contact-sales, not a self-serve Stripe Checkout —// divert to the intake form like onboarding + Settings billing do.// Without this, the POST hits the backend with tier=BUSINESS which 422sdiff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsxindex 3edcb093fc..077cdd617f 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-hooks.test.tsx@@ -85,7 +85,7 @@ describe("useBalanceCard", () => {});it("handleSubmit POSTs the integer-cents amount when isValid", async () => {- let capturedBody: { credit_amount: number } | null = null;+ let capturedBody: { credit_amount: number; surface?: string } | null = null;server.use(jsonHandler("get", "/api/credits", { credits: 1000 }),http.post("*/api/credits", async ({ request }) => {@@ -110,7 +110,8 @@ describe("useBalanceCard", () => {await waitFor(() => expect(result.current.isAdding).toBe(false));// Hook treats a no-checkout_url response as an error → modal stays open.- expect(capturedBody).toEqual({ credit_amount: 2500 });+ // `surface` feeds the backend's checkout_started event.+ expect(capturedBody).toEqual({ credit_amount: 2500, surface: "billing" });});it("handleSubmit catches API failures and stops the spinner", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-posthog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-posthog.test.tsxnew file mode 100644index 0000000000..951f1d0bde--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-posthog.test.tsx@@ -0,0 +1,215 @@+import { TooltipProvider } from "@/components/atoms/Tooltip/BaseTooltip";+import { server } from "@/mocks/mock-server";+import { render, waitFor } from "@/tests/integrations/test-utils";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, renderHook } from "@testing-library/react";+import { http, HttpResponse, type JsonBodyType } from "msw";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { usePaymentMethodCard } from "../components/SubscriptionTab/PaymentMethodCard/usePaymentMethodCard";+import { useYourPlanCard } from "../components/SubscriptionTab/YourPlanCard/useYourPlanCard";+import SettingsBillingPage from "../page";++const posthog = vi.hoisted(() => ({+ __loaded: true,+ is_capturing: () => true,+ capture: vi.fn(),+}));+vi.mock("posthog-js", () => ({ default: posthog }));++const mockSearchParams = { current: new URLSearchParams() };+vi.mock("next/navigation", async (importOriginal) => {+ const actual = await importOriginal<typeof import("next/navigation")>();+ return {+ ...actual,+ useSearchParams: () => mockSearchParams.current,+ useRouter: () => ({+ push: vi.fn(),+ replace: vi.fn(),+ prefetch: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ refresh: vi.fn(),+ }),+ usePathname: () => "/settings/billing",+ useParams: () => ({}),+ };+});++const PORTAL_URL = "https://billing.stripe.com/p/test";+const originalLocation = window.location;++function jsonHandler(method: "get" | "post", path: string, body: JsonBodyType) {+ return http[method](`*${path}`, () => HttpResponse.json(body));+}++function useBillingHandlers(tier = "PRO") {+ server.use(+ jsonHandler("get", "/api/credits/subscription", {+ tier,+ monthly_cost: tier === "MAX" ? 32000 : 5000,+ has_active_stripe_subscription: true,+ status: "active",+ }),+ jsonHandler("get", "/api/credits/manage", { url: PORTAL_URL }),+ jsonHandler("get", "/api/credits", { credits: 1234 }),+ jsonHandler("get", "/api/credits/transactions", {+ transactions: [],+ next_transaction_time: null,+ }),+ jsonHandler("get", "/api/credits/auto-top-up", { amount: 0, threshold: 0 }),+ jsonHandler("get", "/api/credits/invoices", []),+ jsonHandler("get", "/api/v2/chat/copilot-usage", {+ daily: { percent_used: 0, resets_at: null },+ weekly: { percent_used: 0, resets_at: null },+ }),+ );+}++function makeWrapper() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>+ <TooltipProvider>{children}</TooltipProvider>+ </QueryClientProvider>+ );+ }+ return Wrapper;+}++// Opening the portal navigates away; swap in a plain object so the test+// environment survives the assignment.+function stubLocation() {+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: { origin: "https://app.test", href: "https://app.test/" },+ });+}++function eventsNamed(name: string) {+ return posthog.capture.mock.calls.filter(([event]) => event === name);+}++beforeEach(() => {+ posthog.capture.mockClear();+ sessionStorage.clear();+});++afterEach(() => {+ mockSearchParams.current = new URLSearchParams();+ Object.defineProperty(window, "location", {+ configurable: true,+ writable: true,+ value: originalLocation,+ });+});++describe("billing page — abandoned Stripe checkouts", () => {+ it.each([+ [{ topup: "cancel" }, "top_up"],+ [{ subscription: "cancelled" }, "subscription"],+ [{ trial: "cancelled" }, "trial"],+ ])("reports %o as checkout_abandoned (%s)", async (params, checkoutKind) => {+ useBillingHandlers();+ mockSearchParams.current = new URLSearchParams(params);++ render(<SettingsBillingPage />);++ await waitFor(() =>+ expect(eventsNamed("checkout_abandoned")).toEqual([+ [+ "checkout_abandoned",+ { checkout_kind: checkoutKind, surface: "billing" },+ ],+ ]),+ );+ });++ it("reports nothing on a successful return", async () => {+ useBillingHandlers();+ mockSearchParams.current = new URLSearchParams({ subscription: "success" });++ render(<SettingsBillingPage />);++ await waitFor(() => expect(eventsNamed("paywall_viewed")).toHaveLength(1));+ expect(eventsNamed("checkout_abandoned")).toEqual([]);+ });+});++describe("billing page — plan picker and portal", () => {+ it("reports the billing plan picker once its data loads", async () => {+ useBillingHandlers();++ renderHook(() => useYourPlanCard(), { wrapper: makeWrapper() });++ await waitFor(() =>+ expect(eventsNamed("paywall_viewed")).toEqual([+ ["paywall_viewed", { surface: "billing" }],+ ]),+ );+ });++ it("reports the upgrade target as plan_selected", async () => {+ useBillingHandlers("MAX");+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);++ const { result } = renderHook(() => useYourPlanCard(), {+ wrapper: makeWrapper(),+ });+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ await act(async () => {+ result.current.onUpgrade();+ });++ expect(eventsNamed("plan_selected")).toEqual([+ [+ "plan_selected",+ {+ subscription_tier: "BUSINESS",+ billing_cycle: "monthly",+ surface: "billing",+ },+ ],+ ]);+ openSpy.mockRestore();+ });++ it("reports the billing portal from the plan card", async () => {+ useBillingHandlers();++ const { result } = renderHook(() => useYourPlanCard(), {+ wrapper: makeWrapper(),+ });+ await waitFor(() => expect(result.current.canManagePortal).toBe(true));+ stubLocation();++ act(() => result.current.onManage());++ expect(eventsNamed("billing_portal_opened")).toEqual([+ ["billing_portal_opened", { surface: "billing" }],+ ]);+ expect(window.location.href).toBe(PORTAL_URL);+ });++ it("reports the billing portal from the payment method card", async () => {+ useBillingHandlers();++ const { result } = renderHook(() => usePaymentMethodCard(), {+ wrapper: makeWrapper(),+ });+ await waitFor(() => expect(result.current.canManage).toBe(true));+ stubLocation();++ act(() => result.current.onManage());++ expect(eventsNamed("billing_portal_opened")).toEqual([+ ["billing_portal_opened", { surface: "billing_payment_method" }],+ ]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.tsindex ecfb8e300d..f9d0462450 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/BalanceCard/useBalanceCard.ts@@ -41,7 +41,10 @@ export function useBalanceCard() {if (!isValid) return;try {const result = await requestTopUp({- data: { credit_amount: Math.round(numericAmount * 100) },+ data: {+ credit_amount: Math.round(numericAmount * 100),+ surface: "billing",+ },});const status = (result as { status?: number } | undefined)?.status;const body = result?.data asdiff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/usePaymentMethodCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/usePaymentMethodCard.tsindex 0d7a86b640..131f043f36 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/usePaymentMethodCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/PaymentMethodCard/usePaymentMethodCard.ts@@ -4,6 +4,7 @@ import { useState } from "react";import { useGetV1ManagePaymentMethods } from "@/app/api/__generated__/endpoints/credits/credits";import type { GetV1ManagePaymentMethods200 } from "@/app/api/__generated__/models/getV1ManagePaymentMethods200";+import { trackBillingPortalOpened } from "@/services/analytics/monetization-analytics";export function usePaymentMethodCard() {const [isOpening, setIsOpening] = useState(false);@@ -28,6 +29,7 @@ export function usePaymentMethodCard() {// browser starting the cross-origin navigation to Stripe — without// it the button looks unresponsive on slower networks.setIsOpening(true);+ trackBillingPortalOpened("billing_payment_method");window.location.href = portalUrl;},};diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.tsindex ddaf085e36..2d1812acde 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/SubscriptionTab/YourPlanCard/useYourPlanCard.ts@@ -18,6 +18,11 @@ import {getSubscriptionValue,trackAdsConversion,} from "@/services/analytics/google-ads";+import {+ trackBillingPortalOpened,+ trackPaywallViewed,+ trackPlanSelected,+} from "@/services/analytics/monetization-analytics";import { formatCents, formatShortDate } from "../../../helpers";@@ -112,6 +117,11 @@ export function useYourPlanCard() {setSelectedCycle(serverCycle);}, [serverCycle]);+ const hasSubscriptionData = Boolean(subscription.data);+ useEffect(() => {+ if (hasSubscriptionData) trackPaywallViewed("billing");+ }, [hasSubscriptionData]);+// ENTERPRISE sits above every self-serve tier, so it has no upgrade target// and no self-serve downgrade (getNextTier would otherwise fall back to// PRO and offer a downgrade labelled "Upgrade").@@ -222,6 +232,7 @@ export function useYourPlanCard() {success_url: successUrl,cancel_url: cancelUrl,...(billingCycle ? { billing_cycle: billingCycle } : {}),+ surface: "billing",},});const url = (result?.data as { url?: string } | undefined)?.url;@@ -593,6 +604,11 @@ export function useYourPlanCard() {onCancelTierDowngrade: cancelTierDowngrade,onUpgrade: () => {if (!plan?.nextTier) return;+ trackPlanSelected({+ subscription_tier: plan.nextTier,+ billing_cycle: plan.isPaidPlan ? serverCycle : selectedCycle,+ surface: "billing",+ });// Team (BUSINESS) tier is contact-sales — divert to marketing page// instead of POSTing a Checkout the user can't self-serve.if (plan.nextTierIsTeamLink) {@@ -611,13 +627,20 @@ export function useYourPlanCard() {},onDowngrade: () => {if (!plan?.previousTier) return;+ trackPlanSelected({+ subscription_tier: plan.previousTier,+ billing_cycle: serverCycle,+ surface: "billing",+ });setPendingTierDowngrade(plan.previousTier);},onResume: () => {void resumeSubscription();},onManage: () => {- if (paymentPortal.data) window.location.href = paymentPortal.data;+ if (!paymentPortal.data) return;+ trackBillingPortalOpened("billing");+ window.location.href = paymentPortal.data;},};}diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsxindex a82ecafb8b..b7d5ec16d1 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/page.tsx@@ -17,6 +17,11 @@ import {usePatchV1FulfillCheckoutSession,} from "@/app/api/__generated__/endpoints/credits/credits";+import {+ trackCheckoutAbandoned,+ trackTrialCheckoutAbandoned,+} from "@/services/analytics/monetization-analytics";+import { AutomationCreditsTab } from "./components/AutomationCreditsTab/AutomationCreditsTab";import { SubscriptionTab } from "./components/SubscriptionTab/SubscriptionTab";@@ -42,6 +47,7 @@ export default function SettingsBillingPage() {const queryClient = useQueryClient();const topupStatus = searchParams.get("topup");const subscriptionStatus = searchParams.get("subscription");+ const trialStatus = searchParams.get("trial");const { mutateAsync: fulfillCheckout } = usePatchV1FulfillCheckoutSession();const handledTopupRef = useRef<string | null>(null);const handledSubscriptionRef = useRef<string | null>(null);@@ -76,6 +82,7 @@ export default function SettingsBillingPage() {// so a failure here is non-blocking.});} else if (topupStatus === "cancel") {+ trackCheckoutAbandoned({ checkout_kind: "top_up", surface: "billing" });toast({title: "Payment cancelled",description: "Your payment method was not charged.",@@ -104,6 +111,10 @@ export default function SettingsBillingPage() {queryKey: getGetSubscriptionStatusQueryKey(),});} else if (subscriptionStatus === "cancelled") {+ trackCheckoutAbandoned({+ checkout_kind: "subscription",+ surface: "billing",+ });toast({title: "Checkout cancelled",description: "Your plan was not changed.",@@ -116,6 +127,13 @@ export default function SettingsBillingPage() {[subscriptionStatus, queryClient, router],);+ useEffect(+ function reportTrialCheckoutCancelled() {+ if (trialStatus === "cancelled") trackTrialCheckoutAbandoned("billing");+ },+ [trialStatus],+ );+return (<div className="flex flex-col gap-4 pb-8 sm:gap-6"><Text variant="h4" as="h1" className="pl-4 leading-[28px] text-textBlack">diff --git a/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsx b/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsxindex 3a2ce6d315..0c61cbf539 100644--- a/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsx+++ b/autogpt_platform/frontend/src/app/(public)/tour/chat/__tests__/tracking.test.tsx@@ -15,6 +15,11 @@ vi.mock("@/components/ui/dot-distortion-shader", () => ({import { configureCookiebot } from "@/tests/integrations/cookiebot";+const { posthog } = vi.hoisted(() => ({+ posthog: { __loaded: true, is_capturing: () => true, capture: vi.fn() },+}));+vi.mock("posthog-js", () => ({ default: posthog }));+import TourChatPage from "../page";import { DEFAULT_SCENARIO_ID } from "../script/tourScenarios";import { useTourStore } from "../tourStore";@@ -58,6 +63,7 @@ describe("Tour DataFast tracking", () => {window.history.pushState({}, "", "/tour/chat");window.datafast = datafast;datafast.mockClear();+ posthog.capture.mockClear();sessionStorage.clear();useTourStore.setState({activeScenarioId: DEFAULT_SCENARIO_ID,@@ -129,4 +135,25 @@ describe("Tour DataFast tracking", () => {{ label: "another-scenario", placement: "end-card" },]);});++ // The tour is public and pre-signup: the PostHog mirror carries the same+ // metadata as DataFast and nothing that identifies the visitor.+ test("mirrors the tour funnel to PostHog under its PostHog names", async () => {+ render(<TourChatPage />);+ await advanceThroughTurn();+ await pressEnterToSend();+ fireEvent.click(screen.getByText("Make this agent yours"));++ const events = posthog.capture.mock.calls.map(([name, properties]) => [+ name,+ properties,+ ]);+ // Child effects run first, so the scenario starts before the tour does.+ expect(events).toEqual([+ ["tour_scenario_started", { scenario: DEFAULT_SCENARIO_ID }],+ ["tour_started", {}],+ ["tour_scenario_completed", { scenario: DEFAULT_SCENARIO_ID }],+ ["tour_cta_clicked", { label: "pricing", placement: "end-card" }],+ ]);+ });});diff --git a/autogpt_platform/frontend/src/app/(public)/tour/chat/tracking.ts b/autogpt_platform/frontend/src/app/(public)/tour/chat/tracking.tsindex c492bbe457..d02894e871 100644--- a/autogpt_platform/frontend/src/app/(public)/tour/chat/tracking.ts+++ b/autogpt_platform/frontend/src/app/(public)/tour/chat/tracking.ts@@ -1,4 +1,9 @@import { analytics } from "@/services/analytics";+import { capturePostHogEvent } from "@/services/analytics/posthog-capture";+import { TourEvent } from "@/services/analytics/posthog-events";++// Each tour step goes to DataFast and, under its PostHog name, to PostHog.+// The tour is public and pre-signup: nothing here may carry an identifier.export type TourCtaLabel =| "pricing"@@ -7,8 +12,16 @@ export type TourCtaLabel =| "share";const TOUR_START_SESSION_KEY = "tour_start_tracked";+const POSTHOG_TOUR_START_KEY = "posthog_tour_started";export function trackTourStart() {+ // PostHog's guard is marked only once the event is sent or dropped for lack+ // of consent, not while it waits for the answer.+ capturePostHogEvent(+ TourEvent.TOUR_STARTED,+ {},+ { oncePerTabKey: POSTHOG_TOUR_START_KEY },+ );try {if (sessionStorage.getItem(TOUR_START_SESSION_KEY)) return;sessionStorage.setItem(TOUR_START_SESSION_KEY, "1");@@ -21,12 +34,18 @@ export function trackTourStart() {export function trackTourScenarioStart(scenarioId: string) {analytics.sendDatafastEvent("tour_scenario_start", { scenario: scenarioId });+ capturePostHogEvent(TourEvent.TOUR_SCENARIO_STARTED, {+ scenario: scenarioId,+ });}export function trackTourScenarioComplete(scenarioId: string) {analytics.sendDatafastEvent("tour_scenario_complete", {scenario: scenarioId,});+ capturePostHogEvent(TourEvent.TOUR_SCENARIO_COMPLETED, {+ scenario: scenarioId,+ });}export function trackTourCtaClick(@@ -34,4 +53,5 @@ export function trackTourCtaClick(metadata: Record<string, unknown> = {},) {analytics.sendDatafastEvent("tour_cta_click", { label, ...metadata });+ capturePostHogEvent(TourEvent.TOUR_CTA_CLICKED, { label, ...metadata });}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 3754f0f2b4..110371bf5e 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15244,6 +15244,7 @@"summary": "Download agent file","description": "Download agent graph file for a specific marketplace listing version","operationId": "getV2Download agent file",+ "security": [{ "HTTPBearer": [] }],"parameters": [{"name": "store_listing_version_id",@@ -28418,7 +28419,15 @@},"RequestTopUp": {"properties": {- "credit_amount": { "type": "integer", "title": "Credit Amount" }+ "credit_amount": { "type": "integer", "title": "Credit Amount" },+ "surface": {+ "anyOf": [+ { "type": "string", "const": "billing" },+ { "type": "null" }+ ],+ "title": "Surface",+ "description": "Where the top-up was started; analytics only."+ }},"type": "object","required": ["credit_amount"],@@ -30636,6 +30645,17 @@"enum": ["monthly", "yearly"],"title": "Billing Cycle","default": "monthly"+ },+ "surface": {+ "anyOf": [+ {+ "type": "string",+ "enum": ["onboarding", "paywall_gate", "billing"]+ },+ { "type": "null" }+ ],+ "title": "Surface",+ "description": "Where the plan was picked; analytics only."}},"type": "object",diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.tsindex 72946e4d30..5b8bba5c4e 100644--- a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts+++ b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts@@ -3,6 +3,7 @@ import {usePostTrialsStartTrialCheckout,} from "@/app/api/__generated__/endpoints/trials/trials";import { useAuthStore } from "@/lib/auth/hooks/useAuthStore";+import { markTrialCheckoutStarted } from "@/services/analytics/monetization-analytics";import { TrialEvent } from "@/services/analytics/posthog-events";import { useTrialStatus } from "@/services/trials/useTrialStatus";import { updateTrialStatusCache } from "@/services/trials/updateTrialStatusCache";@@ -49,10 +50,7 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {if (useAuthStore.getState().user?.id !== userID) return;if (response.status !== 200)throw new Error("Unable to start trial checkout.");- posthog?.capture(TrialEvent.SUBSCRIPTION_TRIAL_CHECKOUT_STARTED, {- trial_offer_version: offer.version,- surface: returnTo,- });+ markTrialCheckoutStarted(returnTo);window.location.assign(response.data.url);} catch (error) {setFailure({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.tsxnew file mode 100644index 0000000000..2b2378a544--- /dev/null+++ b/autogpt_platform/frontend/src/providers/posthog/__tests__/posthog-provider.test.tsx@@ -0,0 +1,77 @@+import { render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const posthog = vi.hoisted(() => ({+ init: vi.fn(),+ register: vi.fn(),+}));+const credentials = vi.hoisted(() => ({ key: "phc_test" as string }));++vi.mock("posthog-js", () => ({ default: posthog }));++vi.mock("@posthog/react", () => ({+ PostHogProvider: ({ children }: { children: React.ReactNode }) => children,+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isUserLoading: true, user: null }),+}));++vi.mock("@/services/environment", () => ({+ environment: {+ isPostHogEnabled: () => true,+ getPostHogCredentials: () => ({+ key: credentials.key,+ host: "https://eu.i.posthog.com",+ }),+ },+}));++vi.mock("@/services/analytics/posthog-base-properties", () => ({+ getPostHogBaseProperties: () => ({ source: "web", environment: "dev" }),+}));++vi.mock("@/services/analytics/anonymous-id", () => ({+ captureFirstLanding: vi.fn(),+ followAnalyticsConsentForIdentity: () => () => {},+ getAnonymousID: () => null,+}));++vi.mock("../posthog-consent", () => ({+ followAnalyticsConsent: () => () => {},+ forgetPostHogStorageWithoutConsent: vi.fn(),+ getConsentGatedConfig: () => ({}),+}));++describe("PostHogProvider", () => {+ beforeEach(() => {+ posthog.init.mockClear();+ posthog.register.mockClear();+ credentials.key = "phc_test";+ });++ it("registers the base properties once PostHog is initialised", async () => {+ const { PostHogProvider } = await import("../posthog-provider");++ render(<PostHogProvider>app</PostHogProvider>);++ expect(posthog.register).toHaveBeenCalledOnce();+ expect(posthog.register).toHaveBeenCalledWith({+ source: "web",+ environment: "dev",+ });+ expect(posthog.init.mock.invocationCallOrder[0]).toBeLessThan(+ posthog.register.mock.invocationCallOrder[0],+ );+ });++ it("registers nothing without a PostHog key", async () => {+ credentials.key = "";+ const { PostHogProvider } = await import("../posthog-provider");++ render(<PostHogProvider>app</PostHogProvider>);++ expect(posthog.init).not.toHaveBeenCalled();+ expect(posthog.register).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/monetization-analytics.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/monetization-analytics.test.tsnew file mode 100644index 0000000000..bff8ff9425--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/monetization-analytics.test.ts@@ -0,0 +1,90 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const { posthog } = vi.hoisted(() => ({+ posthog: { __loaded: true, is_capturing: () => true, capture: vi.fn() },+}));++vi.mock("posthog-js", () => ({ default: posthog }));++import {+ markTrialCheckoutStarted,+ trackBillingPortalOpened,+ trackCheckoutAbandoned,+ trackPaywallViewed,+ trackPlanSelected,+ trackTrialCheckoutAbandoned,+} from "../monetization-analytics";++function eventsNamed(name: string) {+ return posthog.capture.mock.calls.filter(([event]) => event === name);+}++describe("monetization analytics", () => {+ beforeEach(() => {+ posthog.capture.mockReset();+ sessionStorage.clear();+ });++ it("reports a paywall view once per tab for each surface", () => {+ trackPaywallViewed("paywall_gate");+ trackPaywallViewed("paywall_gate");+ trackPaywallViewed("billing");++ expect(eventsNamed("paywall_viewed")).toEqual([+ ["paywall_viewed", { surface: "paywall_gate" }],+ ["paywall_viewed", { surface: "billing" }],+ ]);+ });++ it("reports the picked plan with its cycle, surface and pricing arm", () => {+ trackPlanSelected({+ subscription_tier: "MAX",+ billing_cycle: "yearly",+ surface: "onboarding",+ pricing_variant: "yearly-max",+ });++ expect(posthog.capture).toHaveBeenCalledWith("plan_selected", {+ subscription_tier: "MAX",+ billing_cycle: "yearly",+ surface: "onboarding",+ pricing_variant: "yearly-max",+ });+ });++ it("reports the billing portal and abandoned checkouts", () => {+ trackBillingPortalOpened("billing_payment_method");+ trackCheckoutAbandoned({ checkout_kind: "top_up", surface: "billing" });++ expect(posthog.capture).toHaveBeenCalledWith("billing_portal_opened", {+ surface: "billing_payment_method",+ });+ expect(posthog.capture).toHaveBeenCalledWith("checkout_abandoned", {+ checkout_kind: "top_up",+ surface: "billing",+ });+ });++ // `?trial=cancelled` stays in the URL, so a refresh must not count twice.+ it("reports an abandoned trial checkout once per tab", () => {+ trackTrialCheckoutAbandoned("billing");+ trackTrialCheckoutAbandoned("billing");++ expect(eventsNamed("checkout_abandoned")).toEqual([+ ["checkout_abandoned", { checkout_kind: "trial", surface: "billing" }],+ ]);+ });++ it("counts a second trial abandonment after a new checkout starts", () => {+ trackTrialCheckoutAbandoned("billing");+ markTrialCheckoutStarted("billing");+ trackTrialCheckoutAbandoned("billing");+ // The refresh after the second return is still guarded.+ trackTrialCheckoutAbandoned("billing");++ expect(eventsNamed("checkout_abandoned")).toEqual([+ ["checkout_abandoned", { checkout_kind: "trial", surface: "billing" }],+ ["checkout_abandoned", { checkout_kind: "trial", surface: "billing" }],+ ]);+ });+});diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-capture.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-capture.test.tsnew file mode 100644index 0000000000..482cc131db--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-capture.test.ts@@ -0,0 +1,234 @@+import {+ answerCookiebot,+ configureCookiebot,+ installCookiebot,+ removeCookiebot,+} from "@/tests/integrations/cookiebot";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { posthog } = vi.hoisted(() => ({+ posthog: {+ __loaded: false,+ capturing: false,+ capture: vi.fn(),+ is_capturing() {+ return this.capturing;+ },+ },+}));++vi.mock("posthog-js", () => ({ default: posthog }));++import {+ capturePostHogEvent,+ resetPostHogCaptureQueueForTests,+} from "../posthog-capture";++const ONCE_KEY = "posthog_tour_started";++function storeConsentCookie(statistics: boolean) {+ const answer = `{necessary:true,preferences:false,statistics:${statistics},marketing:false}`;+ document.cookie = `CookieConsent=${encodeURIComponent(answer)}; Path=/`;+}++/** posthog.init has run and followAnalyticsConsent opted it in. */+function startCapturing() {+ posthog.__loaded = true;+ posthog.capturing = true;+}++function fire(event: string) {+ window.dispatchEvent(new Event(event));+}++describe("capturePostHogEvent", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ configureCookiebot();+ posthog.__loaded = false;+ posthog.capturing = false;+ posthog.capture.mockReset();+ sessionStorage.clear();+ resetPostHogCaptureQueueForTests();+ });++ afterEach(() => {+ resetPostHogCaptureQueueForTests();+ removeCookiebot();+ vi.unstubAllEnvs();+ vi.useRealTimers();+ });++ it("sends straight away while PostHog captures", () => {+ startCapturing();++ capturePostHogEvent("paywall_viewed", { surface: "billing" });++ expect(posthog.capture).toHaveBeenCalledWith("paywall_viewed", {+ surface: "billing",+ });+ });++ // A page's mount effect runs before the provider's init effect on a full+ // page load; posthog-js would silently drop the event.+ it("holds an event from a consented visitor until PostHog opts in, then sends it with its own time", () => {+ storeConsentCookie(true);+ const happenedAt = new Date("2026-09-23T10:00:00Z");+ vi.setSystemTime(happenedAt);++ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });+ // Loaded but still opted out: posthog-js would drop it.+ posthog.__loaded = true;+ vi.advanceTimersByTime(1_000);+ expect(posthog.capture).not.toHaveBeenCalled();+ expect(sessionStorage.getItem(ONCE_KEY)).toBeNull();++ posthog.capturing = true;+ vi.advanceTimersByTime(250);++ expect(posthog.capture).toHaveBeenCalledExactlyOnceWith(+ "tour_started",+ {},+ { timestamp: happenedAt },+ );+ expect(sessionStorage.getItem(ONCE_KEY)).toBe("1");+ });++ it("sends a held event once Cookiebot auto-consents after uc.js loads", () => {+ capturePostHogEvent("tour_started");+ vi.advanceTimersByTime(250);++ // A region that needs no consent: uc.js loads with an answer, no banner.+ installCookiebot({ statistics: true, marketing: true, preferences: true });+ fire("CookiebotOnConsentReady");+ startCapturing();+ vi.advanceTimersByTime(250);++ expect(posthog.capture).toHaveBeenCalledTimes(1);+ expect(posthog.capture.mock.calls[0][0]).toBe("tour_started");+ });++ // Between uc.js loading and its region check the API has no answer yet;+ // that is not the banner.+ it("keeps holding while uc.js is still deciding whether to ask", () => {+ capturePostHogEvent("tour_started");+ installCookiebot();+ vi.advanceTimersByTime(500);++ answerCookiebot({ statistics: true });+ startCapturing();+ vi.advanceTimersByTime(250);++ expect(posthog.capture).toHaveBeenCalledTimes(1);+ });++ it("drops the event of a visitor who declined analytics", () => {+ storeConsentCookie(false);+ startCapturing();+ posthog.capturing = false;++ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });+ vi.advanceTimersByTime(20_000);++ expect(posthog.capture).not.toHaveBeenCalled();+ // Deliberately dropped: the tab does not try again.+ expect(sessionStorage.getItem(ONCE_KEY)).toBe("1");+ });++ it("drops held events when the visitor declines on load", () => {+ capturePostHogEvent("tour_started");+ installCookiebot();+ answerCookiebot({ statistics: false });++ startCapturing();+ vi.advanceTimersByTime(1_000);++ expect(posthog.capture).not.toHaveBeenCalled();+ });++ // Consent given on the banner covers what happens after it, never what+ // was held before it.+ it("drops held events when the banner asks, and does not replay them on accept", () => {+ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });+ installCookiebot();+ fire("CookiebotOnDialogInit");++ expect(sessionStorage.getItem(ONCE_KEY)).toBe("1");+ answerCookiebot({ statistics: true });+ startCapturing();+ vi.advanceTimersByTime(1_000);++ expect(posthog.capture).not.toHaveBeenCalled();+ });++ it("drops held events once the banner has been up past the grace, even without its dialog event", () => {+ capturePostHogEvent("tour_started");+ installCookiebot();+ vi.advanceTimersByTime(2_000);++ answerCookiebot({ statistics: true });+ startCapturing();+ vi.advanceTimersByTime(1_000);++ expect(posthog.capture).not.toHaveBeenCalled();+ });++ it("drops an event captured while the banner is already asking", () => {+ installCookiebot();++ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });+ answerCookiebot({ statistics: true });+ startCapturing();+ vi.advanceTimersByTime(1_000);++ expect(posthog.capture).not.toHaveBeenCalled();+ expect(sessionStorage.getItem(ONCE_KEY)).toBe("1");+ });++ it("drops events when there is no consent manager to ask", () => {+ vi.unstubAllEnvs();+ vi.stubEnv("NEXT_PUBLIC_COOKIEBOT_CBID", "");++ capturePostHogEvent("tour_started");+ startCapturing();+ posthog.capturing = false;+ vi.advanceTimersByTime(1_000);++ expect(posthog.capture).not.toHaveBeenCalled();+ });++ it("gives up on held events when nothing resolves", () => {+ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });++ vi.advanceTimersByTime(60_000);+ storeConsentCookie(true);+ startCapturing();+ vi.advanceTimersByTime(1_000);++ expect(posthog.capture).not.toHaveBeenCalled();+ expect(sessionStorage.getItem(ONCE_KEY)).toBe("1");+ });++ it("holds a once-per-tab event only once, and leaves its guard unset while held", () => {+ storeConsentCookie(true);++ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });+ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });+ expect(sessionStorage.getItem(ONCE_KEY)).toBeNull();++ startCapturing();+ vi.advanceTimersByTime(250);+ capturePostHogEvent("tour_started", {}, { oncePerTabKey: ONCE_KEY });++ expect(posthog.capture).toHaveBeenCalledTimes(1);+ });++ it("never throws when posthog-js does", () => {+ startCapturing();+ posthog.capture.mockImplementation(() => {+ throw new Error("blocked");+ });++ expect(() => capturePostHogEvent("plan_selected")).not.toThrow();+ });+});diff --git a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.tsindex 585b11721a..e144aafb79 100644--- a/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts@@ -7,6 +7,7 @@ import { PlannedPostHogEvent, PostHogEvent } from "../posthog-events";const LIVE_EVENT_NAMES = ["$pageview",+ "billing_portal_opened","brain_dump_canceled","brain_dump_completed","brain_dump_download",@@ -23,6 +24,7 @@ const LIVE_EVENT_NAMES = ["capability_card_viewed","capability_cards_completed","capability_cards_skipped",+ "checkout_abandoned","credential_card_never_rendered","credential_oauth_flow_timed_out","credential_oauth_popup_blocked",@@ -43,10 +45,16 @@ const LIVE_EVENT_NAMES = ["intro_followup_sent","intro_path","later_dump_completed",- "subscription_trial_checkout_started",+ "onboarding_step_viewed",+ "paywall_viewed",+ "plan_selected","tab_intro_cta_clicked","tab_intro_dismissed","tab_intro_shown",+ "tour_cta_clicked",+ "tour_scenario_completed",+ "tour_scenario_started",+ "tour_started","transcription_failed","trial_offer_viewed","voice_mode_error",@@ -62,17 +70,7 @@ const LIVE_EVENT_NAMES = ["welcome_dialog_closed",];-const PLANNED_EVENT_NAMES = [- "billing_portal_opened",- "checkout_abandoned",- "onboarding_step_viewed",- "paywall_viewed",- "plan_selected",- "tour_cta_clicked",- "tour_scenario_completed",- "tour_scenario_started",- "tour_started",-];+const PLANNED_EVENT_NAMES: string[] = [];// No longer sent, or renamed (SECRT-2722). The names stay reserved: reusing one would// splice a different action onto the history PostHog already holds for it.@@ -86,6 +84,8 @@ const RETIRED_EVENT_NAMES = ["intro_start_with_autopilot","onboarding_expert_hired","raise_door_clicked",+ // Folded into the backend's checkout_started{checkout_kind: trial}.+ "subscription_trial_checkout_started",// Renamed to the analytics plan's trial_offer_viewed."subscription_trial_offer_viewed","voice_first_sound_latency_ms",diff --git a/autogpt_platform/frontend/src/services/analytics/monetization-analytics.ts b/autogpt_platform/frontend/src/services/analytics/monetization-analytics.tsnew file mode 100644index 0000000000..1513123314--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/monetization-analytics.ts@@ -0,0 +1,84 @@+// The paywall funnel in PostHog: a plan picker is seen, a plan is picked,+// Checkout opens (`checkout_started`, sent by the backend when it creates the+// Stripe session) and is either paid or abandoned. The billing portal is the+// way out to cancel. The pricing arm rides along as PostHog's own+// `$feature/<flag>` properties.++import {+ MonetizationEvent,+ type EventName,+} from "@/services/analytics/posthog-events";+import { capturePostHogEvent } from "./posthog-capture";++export type PaywallSurface = "onboarding" | "paywall_gate" | "billing";+export type CheckoutKind = "subscription" | "top_up" | "trial";+export type BillingPortalSurface = "billing" | "billing_payment_method";++type MonetizationEventName = EventName<typeof MonetizationEvent>;++const PAYWALL_VIEWED_KEY_PREFIX = "posthog_paywall_viewed_";++// Once per tab per surface: the onboarding paywall remounts on the return+// from Stripe, and the billing page re-renders on every refetch.+export function trackPaywallViewed(surface: PaywallSurface) {+ capture(+ MonetizationEvent.PAYWALL_VIEWED,+ { surface },+ `${PAYWALL_VIEWED_KEY_PREFIX}${surface}`,+ );+}++type PlanSelectedProperties = {+ subscription_tier: string;+ billing_cycle: "monthly" | "yearly";+ surface: PaywallSurface;+ pricing_variant?: string;+};++export function trackPlanSelected(properties: PlanSelectedProperties) {+ capture(MonetizationEvent.PLAN_SELECTED, properties);+}++export function trackBillingPortalOpened(surface: BillingPortalSurface) {+ capture(MonetizationEvent.BILLING_PORTAL_OPENED, { surface });+}++/** `oncePerTabKey` guards a cancel URL that survives a refresh. */+export function trackCheckoutAbandoned(+ properties: {+ checkout_kind: CheckoutKind;+ surface: PaywallSurface;+ },+ oncePerTabKey?: string,+) {+ capture(MonetizationEvent.CHECKOUT_ABANDONED, properties, oncePerTabKey);+}++const TRIAL_ABANDONED_KEY_PREFIX = "posthog_trial_checkout_abandoned_";++// The trial's cancel URL (`?trial=cancelled`) is not cleaned up after the+// return, so a refresh must not report the same abandonment twice. Starting+// another trial checkout clears the guard (`markTrialCheckoutStarted`), so a+// second real abandonment in the same tab still counts.+export function trackTrialCheckoutAbandoned(surface: PaywallSurface) {+ trackCheckoutAbandoned(+ { checkout_kind: "trial", surface },+ `${TRIAL_ABANDONED_KEY_PREFIX}${surface}`,+ );+}++export function markTrialCheckoutStarted(surface: PaywallSurface) {+ try {+ sessionStorage.removeItem(`${TRIAL_ABANDONED_KEY_PREFIX}${surface}`);+ } catch {+ // In-app browsers may block sessionStorage; the guard is then unset anyway.+ }+}++function capture(+ event: MonetizationEventName,+ properties: Record<string, unknown>,+ oncePerTabKey?: string,+) {+ capturePostHogEvent(event, properties, { oncePerTabKey });+}diff --git a/autogpt_platform/frontend/src/services/analytics/posthog-capture.ts b/autogpt_platform/frontend/src/services/analytics/posthog-capture.tsnew file mode 100644index 0000000000..08523cf47d--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/posthog-capture.ts@@ -0,0 +1,188 @@+import {+ getConsentAnswer,+ isAwaitingConsentAnswer,+ isConsentManagerConfigured,+ subscribeToConsent,+ subscribeToConsentPrompt,+} from "@/services/consent/consent";+import posthog from "posthog-js";++// PostHog starts opted out and is opted in once the visitor's analytics+// consent is known (providers/posthog/posthog-consent.ts). An event captured+// before that, e.g. from a page's mount effect on a full page load, would be+// dropped by posthog-js, so it is held here until the consent is resolved:+//+// - analytics granted (an earlier answer, or a region Cookiebot auto-consents+// once uc.js loads): sent with the time it happened once PostHog captures;+// - denied, no consent manager, or the banner asking: dropped. An answer+// given on the banner covers what happens after it, never what was held+// before it.+//+// The queue is bounded, and dropped after a few seconds if nothing resolves+// (uc.js blocked, or PostHog disabled or blocked).+const MAX_QUEUED_EVENTS = 50;+const FLUSH_INTERVAL_MS = 250;+const MAX_FLUSH_ATTEMPTS = 40;+// Between uc.js loading and it deciding whether this visitor needs a banner,+// the API is there without an answer. Past this grace it is the banner, even+// if its dialog events never reached us.+const PROMPT_GRACE_ATTEMPTS = 4;++interface CaptureOptions {+ /**+ * Send at most once per tab. Marked when the event is sent or deliberately+ * dropped, so an event lost while held is tried again on the next mount.+ */+ oncePerTabKey?: string;+}++interface QueuedEvent {+ event: string;+ properties: Record<string, unknown>;+ timestamp: Date;+ oncePerTabKey?: string;+}++type Decision = "send" | "hold" | "drop";++let queue: QueuedEvent[] = [];+let flushTimer: ReturnType<typeof setInterval> | null = null;+let flushAttempts = 0;+let awaitingAnswerAttempts = 0;+let promptShown = false;+let stopFollowingConsent: (() => void) | null = null;++export function capturePostHogEvent(+ event: string,+ properties: Record<string, unknown> = {},+ { oncePerTabKey }: CaptureOptions = {},+) {+ try {+ if (oncePerTabKey && isAlreadyHandled(oncePerTabKey)) return;+ const decision = decideNow();+ if (decision === "send") {+ posthog.capture(event, properties);+ markHandled(oncePerTabKey);+ return;+ }+ if (decision === "drop") {+ markHandled(oncePerTabKey);+ return;+ }+ if (queue.length >= MAX_QUEUED_EVENTS) return;+ queue.push({ event, properties, timestamp: new Date(), oncePerTabKey });+ startHolding();+ } catch {+ // Analytics must never break the screen that reports it.+ }+}++function isCapturing() {+ return Boolean(posthog.__loaded && posthog.is_capturing());+}++// For an event captured now. The banner already asking means the visitor+// has not answered; anything after this capture is their fresh decision.+function decideNow(): Decision {+ if (isCapturing()) return "send";+ const answer = getConsentAnswer();+ if (answer) return answer.analytics ? "hold" : "drop";+ if (!isConsentManagerConfigured() || isAwaitingConsentAnswer()) return "drop";+ return "hold";+}++// For the held queue: Cookiebot was not loaded when it started, so an API+// without an answer may still be deciding whether this visitor needs asking.+function decideHeld(): Decision {+ if (isCapturing()) return "send";+ const answer = getConsentAnswer();+ if (answer) return answer.analytics ? "hold" : "drop";+ if (promptShown || !isConsentManagerConfigured()) return "drop";+ if (isAwaitingConsentAnswer()) {+ awaitingAnswerAttempts += 1;+ return awaitingAnswerAttempts > PROMPT_GRACE_ATTEMPTS ? "drop" : "hold";+ }+ // uc.js not loaded yet. A blocked one never answers; the timeout drops.+ return "hold";+}++function startHolding() {+ if (flushTimer) return;+ flushAttempts = 0;+ awaitingAnswerAttempts = 0;+ promptShown = false;+ flushTimer = setInterval(onFlushTick, FLUSH_INTERVAL_MS);+ const stopConsent = subscribeToConsent(resolveHeld);+ const stopPrompt = subscribeToConsentPrompt(onPrompt);+ stopFollowingConsent = () => {+ stopConsent();+ stopPrompt();+ };+}++function onPrompt() {+ promptShown = true;+ resolveHeld();+}++function onFlushTick() {+ flushAttempts += 1;+ resolveHeld();+ if (queue.length && flushAttempts >= MAX_FLUSH_ATTEMPTS) finish("drop");+}++function resolveHeld() {+ try {+ const decision = decideHeld();+ if (decision !== "hold") finish(decision);+ } catch {+ finish("drop");+ }+}++function finish(decision: Exclude<Decision, "hold">) {+ const pending = queue;+ queue = [];+ stopHolding();+ for (const { event, properties, timestamp, oncePerTabKey } of pending) {+ if (decision === "send") {+ try {+ posthog.capture(event, properties, { timestamp });+ } catch {+ // Keep sending the rest.+ }+ }+ markHandled(oncePerTabKey);+ }+}++function stopHolding() {+ if (flushTimer) clearInterval(flushTimer);+ flushTimer = null;+ stopFollowingConsent?.();+ stopFollowingConsent = null;+}++function isAlreadyHandled(key: string) {+ if (queue.some((queued) => queued.oncePerTabKey === key)) return true;+ try {+ return Boolean(sessionStorage.getItem(key));+ } catch {+ // In-app browsers may block sessionStorage; double-counting beats dropping.+ return false;+ }+}++function markHandled(key: string | undefined) {+ if (!key) return;+ try {+ sessionStorage.setItem(key, "1");+ } catch {+ // See isAlreadyHandled.+ }+}++export function resetPostHogCaptureQueueForTests() {+ queue = [];+ stopHolding();+}diff --git a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts b/autogpt_platform/frontend/src/services/analytics/posthog-events.tsindex 205e6a5a62..d551cbfb63 100644--- a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts+++ b/autogpt_platform/frontend/src/services/analytics/posthog-events.ts@@ -140,7 +140,24 @@ export const CredentialConnectionFailureEvent = {export const TrialEvent = {TRIAL_OFFER_VIEWED: "trial_offer_viewed",- SUBSCRIPTION_TRIAL_CHECKOUT_STARTED: "subscription_trial_checkout_started",+} as const;++export const TourEvent = {+ TOUR_STARTED: "tour_started",+ TOUR_SCENARIO_STARTED: "tour_scenario_started",+ TOUR_SCENARIO_COMPLETED: "tour_scenario_completed",+ TOUR_CTA_CLICKED: "tour_cta_clicked",+} as const;++export const OnboardingEvent = {+ ONBOARDING_STEP_VIEWED: "onboarding_step_viewed",+} as const;++export const MonetizationEvent = {+ PAYWALL_VIEWED: "paywall_viewed",+ PLAN_SELECTED: "plan_selected",+ BILLING_PORTAL_OPENED: "billing_portal_opened",+ CHECKOUT_ABANDONED: "checkout_abandoned",} as const;export const PostHogEvent = {@@ -153,21 +170,14 @@ export const PostHogEvent = {...VoiceModeEvent,...CredentialConnectionFailureEvent,...TrialEvent,+ ...TourEvent,+ ...OnboardingEvent,+ ...MonetizationEvent,} as const;-// In the tracking plan and NOT sent yet (SECRT-2723). Move a name into its-// group above in the change that starts sending it.-export const PlannedPostHogEvent = {- ONBOARDING_STEP_VIEWED: "onboarding_step_viewed",- PAYWALL_VIEWED: "paywall_viewed",- PLAN_SELECTED: "plan_selected",- BILLING_PORTAL_OPENED: "billing_portal_opened",- CHECKOUT_ABANDONED: "checkout_abandoned",- TOUR_STARTED: "tour_started",- TOUR_SCENARIO_STARTED: "tour_scenario_started",- TOUR_SCENARIO_COMPLETED: "tour_scenario_completed",- TOUR_CTA_CLICKED: "tour_cta_clicked",-} as const;+// In the tracking plan and NOT sent yet. Move a name into its group above in+// the change that starts sending it.+export const PlannedPostHogEvent: Record<string, string> = {};export type EventName<Group extends Record<string, string>> =Group[keyof Group];diff --git a/autogpt_platform/frontend/src/services/consent/consent.ts b/autogpt_platform/frontend/src/services/consent/consent.tsindex 2ab348041d..91f379d5a8 100644--- a/autogpt_platform/frontend/src/services/consent/consent.ts+++ b/autogpt_platform/frontend/src/services/consent/consent.ts@@ -1,6 +1,7 @@import { environment } from "@/services/environment";import {COOKIEBOT_CONSENT_EVENTS,+ COOKIEBOT_DIALOG_EVENTS,COOKIEBOT_SCRIPT_ID,getCookiebotAPI,parseCookieConsentHeader,@@ -79,6 +80,27 @@ export function subscribeToConsent(listener: () => void): () => void {);}+/** Calls `listener` when the banner is about to ask the visitor. */+export function subscribeToConsentPrompt(listener: () => void): () => void {+ if (typeof window === "undefined") return () => {};+ COOKIEBOT_DIALOG_EVENTS.forEach((event) =>+ window.addEventListener(event, listener),+ );+ return () =>+ COOKIEBOT_DIALOG_EVENTS.forEach((event) =>+ window.removeEventListener(event, listener),+ );+}++/**+ * Whether the consent manager has loaded without an answer from the visitor,+ * so the banner is asking (or about to). An answer given after this is a+ * fresh decision, not one that covers what happened before it.+ */+export function isAwaitingConsentAnswer(): boolean {+ return getCookiebotAPI() !== null && getConsentAnswer() === null;+}+export function openConsentSettings(): void {if (typeof window === "undefined") return;getCookiebotAPI()?.renew();diff --git a/autogpt_platform/frontend/src/services/consent/cookiebot.ts b/autogpt_platform/frontend/src/services/consent/cookiebot.tsindex 1645acc1a9..f17f7aacfe 100644--- a/autogpt_platform/frontend/src/services/consent/cookiebot.ts+++ b/autogpt_platform/frontend/src/services/consent/cookiebot.ts@@ -15,6 +15,13 @@ export const COOKIEBOT_CONSENT_EVENTS = ["CookiebotOnLoad",] as const;+// Fired when the banner is about to ask, i.e. the visitor has no answer yet.+// A visitor outside every consent region gets no banner and no such event.+export const COOKIEBOT_DIALOG_EVENTS = [+ "CookiebotOnDialogInit",+ "CookiebotOnDialogDisplay",+] as const;+export interface CookiebotConsent {necessary: boolean;preferences: boolean;diff --git a/docs/platform/activation-metrics.md b/docs/platform/activation-metrics.mdindex 02cb7d2a88..213db75cbc 100644--- a/docs/platform/activation-metrics.md+++ b/docs/platform/activation-metrics.md@@ -65,14 +65,14 @@ Every event carries `environment` and `source: "platform"`.| GTM asked for | Event | Fires when | Key properties || --- | --- | --- | --- |-| run_agent | `agent_run_started` without `expert_id` | A person starts an agent run (UI, API key, copilot tool). Not schedules, webhooks, sub-graphs or dry runs. | `trigger`, `trigger_ref`, `graph_id`, `graph_exec_id` |-| run_autopilot | `chat_message_sent` without `expert_id` | A person sends a message in an Autopilot chat. | `session_id`, `surface` (web chat, slack, telegram, discord) |+| run_agent | `agent_run_started` without `expert_id` | A person starts an agent run (UI, API key, copilot tool). Not schedules, webhooks, sub-graphs or dry runs. | `via`, `via_ref`, `graph_id`, `graph_exec_id` |+| run_autopilot | `chat_message_sent` without `expert_id` | A person sends a message in an Autopilot chat. | `chat_session_id`, `origin` (`web`, `slack`, `telegram`, `discord`) || run_expert | `chat_message_sent` / `agent_run_started` with `expert_id` | A person sends a message in an expert chat or starts an expert workflow run (`kind: workflow_run`). | `expert_id`, `kind` || schedule_agent_run / schedule_autopilot_run / schedule_expert_run | `schedule_created` | Any schedule is registered, from any surface. | `target`: `agent` / `autopilot` / `expert`, `cron`, `is_recurring`, `schedule_id` |-| schedule_agent_ran / schedule_autopilot_ran / schedule_expert_ran | `schedule_fired` | A schedule produced work. | `target`, `schedule_id`, `graph_exec_id` or `session_id` |+| schedule_agent_ran / schedule_autopilot_ran / schedule_expert_ran | `schedule_fired` | A schedule produced work. | `target`, `schedule_id`, `graph_exec_id` or `chat_session_id` || (trigger) | `trigger_fired` | A webhook produced a run. | `webhook_id`, `graph_exec_id`, `target` |-| agent_fail | `agent_run_finished` with `status: failed` | A run reaches FAILED. | `trigger`, `failure_reason`, `expert_id` |-| — | `agent_run_finished` with `status: completed` | A run reaches COMPLETED. | `trigger`, `cost_cents`, `duration_seconds` |+| agent_fail | `agent_run_finished` with `status: failed` | A run reaches FAILED. | `via`, `failure_reason`, `expert_id` |+| — | `agent_run_finished` with `status: completed` | A run reaches COMPLETED. | `via`, `cost_cents`, `duration_seconds` || — | `expert_hired` | A user hires an expert from a template, from any surface. | `expert_id`, `template_id`, `surface` || — | `integration_connected` | A user connects a credential, by OAuth or by pasting a key. | `provider`, `credential_type`, `method` || — | `credential_oauth_started` | The backend issues an OAuth login URL (`GET /api/integrations/{provider}/login`). Not Codex, which signs in with a device login. | `provider` |diff --git a/docs/platform/tracking-plan.md b/docs/platform/tracking-plan.mdindex a2aeafa007..b0dc021594 100644--- a/docs/platform/tracking-plan.md+++ b/docs/platform/tracking-plan.md@@ -79,6 +79,11 @@ something else now use `hire_started.surface`,(`src/services/analytics/anonymous-id.ts`), passed to `posthog.init` as thebootstrap `distinctID`. `identify` merges it into the user at login, and`resetAnalyticsIdentity` mints a fresh one at logout.+- **The browser waits for analytics consent** (Cookiebot,+ `src/providers/posthog/posthog-consent.ts`). PostHog starts opted out:+ without consent, browser events are dropped, `identify` is not called and+ the anonymous id lasts only for the page load. Backend events do not+ depend on it.- **No synthetic ids.** A backend event with no user is dropped(`posthog_client.capture` does it for every emitter), since a made-up idcreates a person nobody can merge.@@ -124,7 +129,7 @@ Automated work is measured separately: `schedule_fired` and `trigger_fired`.| Status | Meaning || --- | --- || `live` | Sent today under this name. Keep it. |-| `add` | Not sent yet. SECRT-2723 adds it; the name is already in `PlannedPostHogEvent`. |+| `add` | Not sent yet; the name is in `PlannedPostHogEvent` until the change that starts sending it. |Events that are no longer sent are listed under [Removed](#removed), withwhat replaced them.@@ -134,21 +139,26 @@ what replaced them.| Event | Sender | Status | Required properties | Fires when || --- | --- | --- | --- | --- || `$pageview` | browser | live | `$current_url` | A route or query string changes (`PostHogPageViewTracker`). |-| `tour_started` | browser | add | — | The public `/tour` page is opened (once per tab). |-| `tour_scenario_started` | browser | add | `scenario` | A tour scenario starts playing. |-| `tour_scenario_completed` | browser | add | `scenario` | A tour scenario reaches its end. |-| `tour_cta_clicked` | browser | add | `label` (`pricing`, `another-scenario`, `self-host`, `share`) | A tour call to action is clicked. |-| `signup_completed` | backend | add | `signup_method` | The user row is created. |--The tour funnel is sent to DataFast today (`tour_start`, `tour_scenario_start`,-`tour_scenario_complete`, `tour_cta_click`); the PostHog events mirror it.+| `tour_started` | browser | live | — | The public `/tour` page is opened (once per tab). |+| `tour_scenario_started` | browser | live | `scenario` | A tour scenario starts playing. |+| `tour_scenario_completed` | browser | live | `scenario` | A tour scenario reaches its end. |+| `tour_cta_clicked` | browser | live | `label` (`pricing`, `another-scenario`, `self-host`, `share`), `placement` where the CTA has one | A tour call to action is clicked. |+| `signup_completed` | backend | live | `signup_method` (the auth provider, e.g. `email`, `google`: from the user's first Better Auth account row, where `credential` is reported as `email`, else from a Supabase token's `app_metadata.provider`; omitted when neither has it) | The user row is created (`data/user.py`), whichever request creates it. |++The tour funnel also goes to DataFast (`tour_start`, `tour_scenario_start`,+`tour_scenario_complete`, `tour_cta_click`); the PostHog events mirror it with+the same properties and nothing identifying in them: `/tour` is public and+pre-signup, so they land on the visitor's anonymous id. `/tour` sends the+DataFast goals without consent (SECRT-2713), but the PostHog events wait for+analytics consent like every browser event, so the two funnels count+differently.## Onboarding and activation| Event | Sender | Status | Required properties | Fires when || --- | --- | --- | --- | --- |-| `onboarding_step_viewed` | browser | add | `step` (`team`, `autopilot`, `role`, `pain_points`, `connect`, `hire`, `preparing`) | A wizard step is shown (once per tab, same keys as the DataFast `onboarding_<step>` goals). |-| `onboarding_completed` | backend | add | — | The onboarding is marked complete. |+| `onboarding_step_viewed` | browser | live | `step` (`team`, `autopilot`, `role`, `pain_points`, `connect`, `hire`, `preparing`) | A wizard step is shown (once per tab, same keys as the DataFast `onboarding_<step>` goals). The paywall step reports `paywall_viewed` instead. |+| `onboarding_completed` | backend | live | — | `ONBOARDING_COMPLETE` is first recorded for the user (`complete_onboarding_step`). || `brain_dump_started` | browser | live | — | Recording starts. || `brain_dump_completed` | browser | live | `input_mode`, `duration_secs` and `finalize_latency_ms` (voice) or `chars` (typed) | A dump was accepted and the wizard advances. `finalize_latency_ms` is the `finalizeBrainDump()` round trip, timed after the upload flush. || `brain_dump_canceled` | browser | live | — | Recording is cancelled. |@@ -216,20 +226,19 @@ The tour funnel is sent to DataFast today (`tour_start`, `tour_scenario_start`,| `home_viewed` | browser | live | — | The home dashboard renders with data. || `home_attention_actioned` | browser | live | `kind`, `action` | A "needs you" item is approved or declined. || `home_team_member_clicked` | browser | live | `expert_id` | A team member row is clicked. |-| `listing_added_to_library` | backend | add | `store_listing_version_id`, `graph_id`, `library_agent_id` | A marketplace agent is added to the library for the first time. |-| `listing_downloaded` | backend | add | `store_listing_version_id`, `graph_id` | A marketplace agent is downloaded. |+| `listing_added_to_library` | backend | live | `store_listing_version_id`, `graph_id`, `library_agent_id` | A marketplace agent is added to the library for the first time. Only a user adding a listing counts (the library route and the add-to-library block). Restoring an entry the user already had does not, and neither does a system install: an add inside another write's transaction, an expert's hire preloads, or attaching a marketplace workflow to an expert (that is `workflow_installed_on_expert`). |+| `listing_downloaded` | backend | live | `store_listing_version_id`, `graph_id` | A signed-in user downloads a marketplace agent file. Signed-out downloads have no user and are not sent. |## Monetization| Event | Sender | Status | Required properties | Fires when || --- | --- | --- | --- | --- |-| `paywall_viewed` | browser | add | `surface` (`onboarding`, `paywall_gate`, `billing`) | A paywall or plan picker is shown (once per tab per surface). The pricing arm comes from PostHog's own `$feature/...` properties. |-| `plan_selected` | browser | add | `subscription_tier`, `billing_cycle`, `surface` | A plan is picked on any paywall or on the billing page. |-| `billing_portal_opened` | browser | add | `surface` | The Stripe billing portal is opened. |-| `checkout_started` | backend | add | `checkout_kind` (`subscription`, `top_up`), `subscription_tier`, `billing_cycle`, `surface` | A Stripe Checkout session is created. |-| `checkout_abandoned` | browser | add | `checkout_kind`, `surface` | The user returns from Stripe Checkout without paying (the cancel URL). Browser-sent: Stripe only reports the expiry a day later. |+| `paywall_viewed` | browser | live | `surface` (`onboarding`, `paywall_gate`, `billing`) | A paywall or plan picker is shown (once per tab per surface): the onboarding subscription step, the in-app paywall modal, the billing page's plan card. The pricing arm comes from PostHog's own `$feature/...` properties. |+| `plan_selected` | browser | live | `subscription_tier` (`PRO`, `MAX`, `BUSINESS` for Team), `billing_cycle`, `surface`; `pricing_variant` on `onboarding`, only when PostHog has assigned an arm (omitted while flags load and for users outside the rollout, who are not in `control`) | A plan is picked: a plan card on either paywall, or Upgrade / Downgrade on the billing page. |+| `billing_portal_opened` | browser | live | `surface` (`billing` for the plan card, `billing_payment_method` for the payment method card) | The Stripe billing portal is opened. |+| `checkout_started` | backend | live | `checkout_kind` (`subscription`, `top_up`, `trial`), `subscription_tier`, `billing_cycle`, `surface` (sent by the client; unset for the low-credit top-up dialog and the legacy `/profile/credits` page), `$feature/<experiment>` for every recorded experiment arm | A Stripe Checkout session is created and its URL returned (subscription, credit top-up or trial card setup). A paid plan changed in place opens no Checkout and sends nothing. |+| `checkout_abandoned` | browser | live | `checkout_kind`, `surface` | The user returns from Stripe Checkout without paying (the cancel URL: `subscription=cancelled`, `topup=cancel`, `trial=cancelled`, or the paywall modal's `paywall_checkout=cancelled` marker). Browser-sent: Stripe only reports the expiry a day later. A trial abandonment is sent once per tab per surface until the next trial checkout starts, so a refresh on the cancel URL does not count twice but a second real abandonment does. || `trial_offer_viewed` | browser | live | `trial_offer_version`, `subscription_tier`, `trial_duration_days`, `surface` | A trial offer card is shown. |-| `subscription_trial_checkout_started` | browser | live | `trial_offer_version`, `surface` | Trial checkout is opened. Once `checkout_started` ships, fold this in as `checkout_kind: trial`. || `trial_started` | backend | live | `trial_id`, `trial_offer_version`, `subscription_tier`, `billing_cycle`, `trial_duration_days` | The trial starts. Like every trial lifecycle event, it is sent only when its notification email is queued. || `trial_ending` | backend | live | as above | The reminder window opens. || `trial_canceled` | backend | live | as above | The trial is set to cancel. |@@ -238,15 +247,29 @@ The tour funnel is sent to DataFast today (`tour_start`, `tour_scenario_start`,| `trial_converted` | backend | live | as above | The trial converts to paid. || `trial_ended` | backend | live | as above | The trial ends without converting. || `subscription_changed` | backend | live | `change_type: upgrade`, `previous_subscription_tier`, `subscription_tier`, `billing_cycle` | A paid tier upgrade takes effect. Downgrades and cancellations are not sent here yet. |-| `payment_succeeded` | backend | live | `subscription_tier`, `billing_cycle`; SECRT-2723 adds `amount_cents`, `currency` | A subscription invoice is paid. |-| `topup_completed` | backend | live | `amount_credits`, `top_up_type`; SECRT-2723 adds `amount_cents`, `currency` | Credits are bought. |+| `payment_succeeded` | backend | live | `subscription_tier`, `billing_cycle`, `amount_cents` (the invoice's `amount_paid`), `currency` | A subscription invoice is paid. Deduplicated on the invoice id: Stripe delivers both `invoice.payment_succeeded` and `invoice_payment.paid` for one invoice, and redelivers either, so revenue is counted once. |+| `topup_completed` | backend | live | `amount_credits`, `top_up_type`, `amount_cents` (the Checkout total or the auto top-up charge), `currency` | Credits are bought. || `subscription_cancellation_scheduled` | backend | live | `subscription_tier` | A paid plan is set to cancel at period end. |-| `subscription_ended` | backend | add | `subscription_tier`, `billing_cycle`, `reason` | A paid subscription ends (Stripe `customer.subscription.deleted`). |+| `subscription_ended` | backend | live | `subscription_tier`, `billing_cycle`, `reason` (Stripe `cancellation_details.reason`: `cancellation_requested`, `payment_failed`, `payment_disputed`; `payment_failed` too when our own payment-failure handler cancelled the subscription because the balance could not cover a failed renewal, which Stripe would stamp `cancellation_requested`) | A paid subscription ends (Stripe `customer.subscription.deleted`), once per subscription, alongside the ended email. A trial that ends unconverted is `trial_ended` instead. || `subscription_tier_reconciled` | backend | live | `direction`, `previous_subscription_tier`, `subscription_tier`, `via` | Ops signal: Stripe and the stored tier disagreed. Not a user action; keep out of funnels. |-The onboarding paywall's `paywall_view`, `paywall_checkout_cancelled` and-`hire_completed` goals go to DataFast only, which is why the paywall has no-PostHog funnel yet.+The paywall funnel in PostHog is `paywall_viewed` → `plan_selected` →+`checkout_started` → `payment_succeeded`, with `checkout_abandoned`+as the way out. The onboarding paywall's DataFast goals (`paywall_view`,+`paywall_checkout_cancelled`) keep firing alongside.++Browser events captured before PostHog captures (a page's mount effect on a+full page load, such as the return from Stripe, runs before `posthog.init`+and before the consent opt-in) are held by+`src/services/analytics/posthog-capture.ts` while the consent answer is+unknown. With analytics granted (an earlier answer, or a region where+Cookiebot consents on its own once `uc.js` loads) they are sent, with the+time they happened, once PostHog is opted in. When analytics is declined,+there is no consent manager, or the banner is asking, they are dropped: an+answer given on the banner covers what happens after it, not what was held+before it. The once-per-tab guards on `paywall_viewed`, `checkout_abandoned`,+`onboarding_step_viewed` and `tour_started` are set only when the event is+sent or dropped this way, not while it is held.## Retention@@ -298,12 +321,13 @@ null.## Removed-No longer sent (SECRT-2722). The names stay reserved: the pin tests fail if+No longer sent (SECRT-2722, SECRT-2723). The names stay reserved: the pin tests fail ifone comes back, because reusing it would splice a different action onto thehistory PostHog already holds.| Event | Was sent by | Read instead || --- | --- | --- |+| `subscription_trial_checkout_started` | browser | `checkout_started` with `checkout_kind: trial`, sent by the backend once the trial's Checkout session exists; `surface` is the same `onboarding` / `billing`. `trial_offer_version` is dropped; `trial_started` carries it. || `hire_completed` | backend | `expert_hired` (same hire; it now also skips idempotent re-hires). The DataFast `hire_completed` goal is unchanged. || `hire_flow_completed` | browser | `expert_hired` with `surface: expert_page`. `elapsed_ms` is PostHog's time to convert from `hire_started`; `voice_picked` is dropped. || `onboarding_expert_hired` | browser | `expert_hired` with `surface: onboarding`. The card `position` is on `expert_recommendation_clicked`. |