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): single PostHog event list and name constants (#14833)
Krzysztof Czerwinski4e0742c97a28
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.pyindex 19e20e96f7..1a21bb80a5 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py@@ -127,6 +127,7 @@ from backend.util.exceptions import ()from backend.util.feature_flag import Flag, is_feature_enabledfrom backend.util.funnel_analytics import emit_funnel_event+from backend.util.posthog_events import PostHogEventfrom backend.util.timezone_utils import get_user_timezone_or_utclogger = logging.getLogger(__name__)@@ -930,7 +931,7 @@ async def hire_expert(user_id: str, template_id: str, name: str | None) -> HireRexcept Exception:emit_funnel_event(user_id,- "hire_failed",+ PostHogEvent.HIRE_FAILED,{"template_id": template_id, "failed_preloads_count": 0},)raise@@ -1000,7 +1001,7 @@ async def _hire_expert_impl(elif state == "revived":emit_funnel_event(user_id,- "hire_completed",+ PostHogEvent.HIRE_COMPLETED,{"template_id": template.id, "failed_preloads_count": 0},)return HireResult(expert=_to_model(expert))@@ -1082,7 +1083,7 @@ async def _run_hire_setup(if count_hire:emit_funnel_event(user_id,- "hire_completed",+ PostHogEvent.HIRE_COMPLETED,{"template_id": template_id, "failed_preloads_count": len(failed_preloads)},)@@ -1895,7 +1896,9 @@ def _emit_writing_style_added(are silent, so the funnel measures personalisation rather than edits."""if (before or "").strip() or not (after or "").strip():return- emit_funnel_event(user_id, "writing_style_added", {"expert_id": expert_id})+ emit_funnel_event(+ user_id, PostHogEvent.WRITING_STYLE_ADDED, {"expert_id": expert_id}+ )async def _install_preloads(@@ -2071,7 +2074,7 @@ async def _install_library_workflow()emit_funnel_event(user_id,- "workflow_installed_on_expert",+ PostHogEvent.WORKFLOW_INSTALLED_ON_EXPERT,{"expert_id": expert_id,"source": "library",@@ -2120,7 +2123,7 @@ async def _install_marketplace_workflow(return _to_workflow_ref(raced)emit_funnel_event(user_id,- "workflow_installed_on_expert",+ PostHogEvent.WORKFLOW_INSTALLED_ON_EXPERT,{"expert_id": expert_id,"source": "marketplace",@@ -2286,7 +2289,7 @@ async def archive_expert(user_id: str, expert_id: str) -> None:raise ExpertNotFoundError(expert_id)# Re-archiving is an idempotent no-op; the funnel counts each firing once.return- emit_funnel_event(user_id, "expert_fired", {"expert_id": expert_id})+ emit_funnel_event(user_id, PostHogEvent.EXPERT_FIRED, {"expert_id": expert_id})try:await scheduling.detach_expert_triggers(user_id, expert_id)except Exception:diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate.py b/autogpt_platform/backend/backend/copilot/briefing/generate.pyindex af122b18b0..d31c69fe5d 100644--- a/autogpt_platform/backend/backend/copilot/briefing/generate.py+++ b/autogpt_platform/backend/backend/copilot/briefing/generate.py@@ -22,6 +22,7 @@ from backend.data.execution import ExecutionStatus, GraphExecutionMetafrom backend.util.clients import get_database_manager_async_clientfrom backend.util.feature_flag import Flag, evaluate_feature_flag, is_feature_enabledfrom backend.util.funnel_analytics import emit_funnel_event+from backend.util.posthog_events import PostHogEventfrom backend.util.timezone_utils import get_user_timezone_or_utcfrom .models import BriefingContent, BriefingDecisionItem, BriefingRunItem@@ -293,7 +294,7 @@ async def generate_and_deliver_briefing(user_id: str) -> BriefingResult:await client.mark_briefing_delivered(user_id, record.id)emit_funnel_event(user_id,- "briefing_generated",+ PostHogEvent.BRIEFING_GENERATED,{"run_count": 0, "decision_count": 0, "has_content": False},(f"briefing_generated:{record.id}"@@ -315,7 +316,7 @@ async def generate_and_deliver_briefing(user_id: str) -> BriefingResult:)emit_funnel_event(user_id,- "briefing_generated",+ PostHogEvent.BRIEFING_GENERATED,{"run_count": content.completed_total + content.failed_total,"decision_count": content.decision_total,@@ -339,7 +340,7 @@ async def generate_and_deliver_briefing(user_id: str) -> BriefingResult:await client.mark_briefing_delivered(user_id, record.id)emit_funnel_event(user_id,- "briefing_delivered",+ PostHogEvent.BRIEFING_DELIVERED,{"briefing_id": record.id},f"briefing_delivered:{record.id}",)diff --git a/autogpt_platform/backend/backend/copilot/tracking.py b/autogpt_platform/backend/backend/copilot/tracking.pyindex b2710ad864..4539c75fc2 100644--- a/autogpt_platform/backend/backend/copilot/tracking.py+++ b/autogpt_platform/backend/backend/copilot/tracking.py@@ -5,6 +5,7 @@ from typing import Anyfrom backend.util import product_analyticsfrom backend.util.posthog_client import get_posthog_client as _get_posthog_client+from backend.util.posthog_events import PostHogEventfrom backend.util.settings import Settingslogger = logging.getLogger(__name__)@@ -61,7 +62,7 @@ def track_user_message(}client.capture(distinct_id=user_id or f"anonymous_{session_id}",- event="copilot_message_sent",+ event=PostHogEvent.COPILOT_MESSAGE_SENT.value,properties=properties,)except Exception as e:@@ -101,7 +102,7 @@ def track_tool_called()client.capture(distinct_id=distinct_id,- event="copilot_tool_called",+ event=PostHogEvent.COPILOT_TOOL_CALLED.value,properties=properties,)except Exception as e:@@ -141,7 +142,7 @@ def track_agent_run_success(}client.capture(distinct_id=user_id,- event="copilot_agent_run_success",+ event=PostHogEvent.COPILOT_AGENT_RUN_SUCCESS.value,properties=properties,)except Exception as e:@@ -187,7 +188,7 @@ def track_agent_scheduled(}client.capture(distinct_id=user_id,- event="copilot_agent_scheduled",+ event=PostHogEvent.COPILOT_AGENT_SCHEDULED.value,properties=properties,)except Exception as e:@@ -223,7 +224,7 @@ def track_followup_scheduled(}client.capture(distinct_id=user_id,- event="copilot_followup_scheduled",+ event=PostHogEvent.COPILOT_FOLLOWUP_SCHEDULED.value,properties=properties,)except Exception as e:@@ -263,7 +264,7 @@ def track_trigger_setup(}client.capture(distinct_id=user_id,- event="copilot_trigger_setup",+ event=PostHogEvent.COPILOT_TRIGGER_SETUP.value,properties=properties,)except Exception as e:@@ -303,7 +304,7 @@ def track_library_check_outcome(}client.capture(distinct_id=user_id,- event="copilot_library_check_outcome",+ event=PostHogEvent.COPILOT_LIBRARY_CHECK_OUTCOME.value,properties=properties,)except Exception as e:diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex fe956ce3e9..9805bb5df6 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -51,6 +51,7 @@ from backend.util.feature_flag import Flag, get_feature_flag_valuefrom backend.util.json import SafeJson, dumpsfrom backend.util.metrics import DiscordChannel, discord_send_alertfrom backend.util.models import Pagination+from backend.util.posthog_events import PostHogEventfrom backend.util.retry import func_retryfrom backend.util.settings import Settings@@ -1165,7 +1166,7 @@ class UserCredit(UserCreditBase):# webhook/retry replays don't double-emit.if activation is not None and amount > 0:_track_billing_event(- "credit_topup_success",+ PostHogEvent.CREDIT_TOPUP_SUCCESS,user_id,{"amount_credits": amount,@@ -1308,7 +1309,7 @@ class UserCredit(UserCreditBase):)if activation is not None:_track_billing_event(- "credit_topup_success",+ PostHogEvent.CREDIT_TOPUP_SUCCESS,credit_transaction.userId,{"amount_credits": credit_transaction.amount,@@ -1675,7 +1676,7 @@ async def cancel_stripe_subscription(user_id: str) -> bool:get_pending_subscription_change.cache_delete(user_id)current_tier = user.subscription_tier or SubscriptionTier.NO_TIER_track_billing_event(- "subscription_cancellation_scheduled",+ PostHogEvent.SUBSCRIPTION_CANCELLATION_SCHEDULED,user_id,{"subscription_tier": current_tier.value},)@@ -2180,7 +2181,7 @@ async def modify_stripe_subscription_for_tier(# the DB flip fails, so gating here avoids double-firing on success.if db_flip_succeeded and is_tier_upgrade(current_tier, tier):_track_billing_event(- "subscription_upgraded",+ PostHogEvent.SUBSCRIPTION_UPGRADED,user_id,{"previous_subscription_tier": current_tier.value,@@ -2873,7 +2874,7 @@ async def sync_subscription_from_stripe(stripe_subscription: dict) -> None:metadata.get("billing_cycle") if isinstance(metadata, dict) else None)_track_billing_event(- "subscription_upgraded",+ PostHogEvent.SUBSCRIPTION_UPGRADED,user.id,{"previous_subscription_tier": current_tier.value,@@ -2947,7 +2948,9 @@ def _invoice_subscription_id(invoice: dict) -> str:return legacy if isinstance(legacy, str) and legacy else ""-TIER_RECONCILIATION_DISCREPANCY_EVENT = "subscription_tier_reconciliation_discrepancy"+TIER_RECONCILIATION_DISCREPANCY_EVENT = (+ PostHogEvent.SUBSCRIPTION_TIER_RECONCILIATION_DISCREPANCY+)def log_tier_reconciliation_discrepancy(@@ -3008,14 +3011,14 @@ async def alert_tier_reconciliation_discrepancy(message: str) -> None:def _track_billing_event(- event: str, distinct_id: str, properties: dict[str, Any]+ event: PostHogEvent, distinct_id: str, properties: dict[str, Any]) -> None:if not settings.secrets.posthog_api_key:returntry:posthog.capture(- event=event,+ event=event.value,distinct_id=distinct_id,properties=properties,)@@ -3043,7 +3046,7 @@ async def _track_subscription_payment_success(user: User, invoice: dict) -> None)posthog.capture(- event="subscription_payment_success",+ event=PostHogEvent.SUBSCRIPTION_PAYMENT_SUCCESS.value,distinct_id=user.id,properties={"subscription_tier": tier,diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.pyindex 26f1e98b4f..74a66ef69d 100644--- a/autogpt_platform/backend/backend/executor/manager.py+++ b/autogpt_platform/backend/backend/executor/manager.py@@ -81,6 +81,7 @@ from backend.util.file import clean_exec_filesfrom backend.util.funnel_analytics import emit_funnel_eventfrom backend.util.llm.saturation import set_executor_idfrom backend.util.logging import TruncatedLogger, configure_logging+from backend.util.posthog_events import PostHogEventfrom backend.util.process import AppProcess, set_service_namefrom backend.util.retry import (continuous_retry,@@ -1134,7 +1135,7 @@ class ExecutionProcessor:if run_event is not None:emit_funnel_event(graph_exec.user_id,- "expert_run_completed",+ PostHogEvent.EXPERT_RUN_COMPLETED,run_event,f"expert_run_completed:{graph_exec.graph_exec_id}",)diff --git a/autogpt_platform/backend/backend/notifications/trial.py b/autogpt_platform/backend/backend/notifications/trial.pyindex 62afe0d1ca..9b10e96e87 100644--- a/autogpt_platform/backend/backend/notifications/trial.py+++ b/autogpt_platform/backend/backend/notifications/trial.py@@ -24,6 +24,7 @@ from backend.data.subscription_trial import TrialStatefrom backend.notifications.dedupe import claim_once, release_claimfrom backend.notifications.lifecycle_plan import format_amountfrom backend.notifications.queue import queue_notification_async+from backend.util.posthog_events import PostHogEventlogger = logging.getLogger(__name__)TRIAL_REMINDER_WINDOW = timedelta(days=3)@@ -32,6 +33,16 @@ TrialNoticeKind = Literal["started", "ending", "canceled", "resumed", "ended", "converted", "payment_failed"]+TRIAL_NOTICE_EVENTS: dict[TrialNoticeKind, PostHogEvent] = {+ "started": PostHogEvent.SUBSCRIPTION_TRIAL_STARTED,+ "ending": PostHogEvent.SUBSCRIPTION_TRIAL_ENDING,+ "canceled": PostHogEvent.SUBSCRIPTION_TRIAL_CANCELED,+ "resumed": PostHogEvent.SUBSCRIPTION_TRIAL_RESUMED,+ "ended": PostHogEvent.SUBSCRIPTION_TRIAL_ENDED,+ "converted": PostHogEvent.SUBSCRIPTION_TRIAL_CONVERTED,+ "payment_failed": PostHogEvent.SUBSCRIPTION_TRIAL_PAYMENT_FAILED,+}+async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:metadata = subscription.get("metadata") or {}@@ -84,7 +95,7 @@ async def notify_trial(subscription: dict, kind: TrialNoticeKind) -> bool:await release_claim(claim)raise_track_billing_event(- f"subscription_trial_{kind}",+ TRIAL_NOTICE_EVENTS[kind],user_id,{"trial_id": trial.id,diff --git a/autogpt_platform/backend/backend/notifications/trial_test.py b/autogpt_platform/backend/backend/notifications/trial_test.pyindex 7995273952..7fb754b74f 100644--- a/autogpt_platform/backend/backend/notifications/trial_test.py+++ b/autogpt_platform/backend/backend/notifications/trial_test.py@@ -1,5 +1,6 @@from datetime import UTC, datetime, timedeltafrom types import SimpleNamespace+from typing import get_argsfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -167,6 +168,17 @@ async def test_notice_uses_shared_notification_queue(trial, outcome):else:release.assert_not_awaited()assert track.call_count == int(outcome == "sent")+ if outcome == "sent":+ assert track.call_args.args[0] == "subscription_trial_started"+++def test_every_trial_notice_kind_keeps_its_event_name():+ """The names used to be built as f"subscription_trial_{kind}"; the lookup+ must cover every kind and send exactly those strings."""+ kinds = get_args(notices.TrialNoticeKind)+ assert set(notices.TRIAL_NOTICE_EVENTS) == set(kinds)+ for kind in kinds:+ assert notices.TRIAL_NOTICE_EVENTS[kind].value == f"subscription_trial_{kind}"def test_canceled_trial_suppresses_late_ending_reminder(trial):diff --git a/autogpt_platform/backend/backend/util/funnel_analytics.py b/autogpt_platform/backend/backend/util/funnel_analytics.pyindex 65614847ce..c96f5d89f6 100644--- a/autogpt_platform/backend/backend/util/funnel_analytics.py+++ b/autogpt_platform/backend/backend/util/funnel_analytics.py@@ -13,12 +13,16 @@ from uuid import NAMESPACE_URL, uuid5import sentry_sdkfrom backend.util.posthog_client import get_posthog_client+from backend.util.posthog_events import PostHogEventlogger = logging.getLogger(__name__)def emit_funnel_event(- user_id: str, event: str, data: dict[str, Any], data_index: str | None = None+ user_id: str,+ event: PostHogEvent,+ data: dict[str, Any],+ data_index: str | None = None,) -> None:"""Record a funnel event without blocking or raising into the caller.@@ -32,13 +36,14 @@ def emit_funnel_event(emit the same event twice; it is carried both as ``$insert_id`` and as adeterministic event uuid."""+ event_name = event.value# Separate boundaries: a breadcrumb failure must not cost the capture.try:sentry_sdk.add_breadcrumb(- category="funnel", message=event, data=dict(data), level="info"+ category="funnel", message=event_name, data=dict(data), level="info")except Exception:- logger.exception(f"Failed to breadcrumb funnel event {event}")+ logger.exception(f"Failed to breadcrumb funnel event {event_name}")try:client = get_posthog_client()@@ -51,9 +56,14 @@ def emit_funnel_event(# ingestion keys on the event uuid, which the client otherwise# randomises per call, and $insert_id is what its docs name.properties["$insert_id"] = data_index- event_uuid = str(uuid5(NAMESPACE_URL, f"{user_id}:{event}:{data_index}"))+ event_uuid = str(+ uuid5(NAMESPACE_URL, f"{user_id}:{event_name}:{data_index}")+ )client.capture(- event=event, distinct_id=user_id, properties=properties, uuid=event_uuid+ event=event_name,+ distinct_id=user_id,+ properties=properties,+ uuid=event_uuid,)except Exception:- logger.exception(f"Failed to emit funnel event {event} for user {user_id}")+ logger.exception(f"Failed to emit funnel event {event_name} for user {user_id}")diff --git a/autogpt_platform/backend/backend/util/funnel_analytics_test.py b/autogpt_platform/backend/backend/util/funnel_analytics_test.pyindex dcfca5cc6a..4f13e7cf9f 100644--- a/autogpt_platform/backend/backend/util/funnel_analytics_test.py+++ b/autogpt_platform/backend/backend/util/funnel_analytics_test.py@@ -3,12 +3,15 @@ from unittest.mock import MagicMock, patchfrom backend.util import funnel_analyticsfrom backend.util.funnel_analytics import emit_funnel_event+from backend.util.posthog_events import PostHogEventdef test_captures_to_posthog_with_the_user_as_distinct_id():client = MagicMock()with patch.object(funnel_analytics, "get_posthog_client", return_value=client):- emit_funnel_event("user-1", "hire_completed", {"template_id": "tpl-1"})+ emit_funnel_event(+ "user-1", PostHogEvent.HIRE_COMPLETED, {"template_id": "tpl-1"}+ )client.capture.assert_called_once_with(event="hire_completed",@@ -23,7 +26,7 @@ def test_a_data_index_becomes_the_posthog_dedup_key():with patch.object(funnel_analytics, "get_posthog_client", return_value=client):emit_funnel_event("user-1",- "briefing_delivered",+ PostHogEvent.BRIEFING_DELIVERED,{"briefing_id": "b-1"},"briefing_delivered:b-1",)@@ -37,7 +40,7 @@ def test_a_data_index_becomes_the_posthog_dedup_key():def test_no_data_index_means_no_dedup_key():client = MagicMock()with patch.object(funnel_analytics, "get_posthog_client", return_value=client):- emit_funnel_event("user-1", "expert_fired", {"expert_id": "e-1"})+ emit_funnel_event("user-1", PostHogEvent.EXPERT_FIRED, {"expert_id": "e-1"})assert "$insert_id" not in client.capture.call_args.kwargs["properties"]@@ -48,7 +51,7 @@ def test_breadcrumb_carries_the_event_and_its_payload():patch.object(funnel_analytics, "get_posthog_client", return_value=client),patch.object(funnel_analytics.sentry_sdk, "add_breadcrumb") as crumb,):- emit_funnel_event("user-1", "hire_failed", {"template_id": "tpl-1"})+ emit_funnel_event("user-1", PostHogEvent.HIRE_FAILED, {"template_id": "tpl-1"})crumb.assert_called_once_with(category="funnel",@@ -71,7 +74,7 @@ def test_breadcrumb_is_added_before_the_capture():side_effect=lambda **_: calls.append("breadcrumb"),),):- emit_funnel_event("user-1", "expert_thread_created", {"expert_id": "e-1"})+ emit_funnel_event("user-1", PostHogEvent.EXPERT_FIRED, {"expert_id": "e-1"})assert calls == ["breadcrumb", "capture"]@@ -81,7 +84,7 @@ def test_a_disabled_posthog_still_leaves_a_breadcrumb():patch.object(funnel_analytics, "get_posthog_client", return_value=None),patch.object(funnel_analytics.sentry_sdk, "add_breadcrumb") as crumb,):- emit_funnel_event("user-1", "expert_fired", {"expert_id": "e-1"})+ emit_funnel_event("user-1", PostHogEvent.EXPERT_FIRED, {"expert_id": "e-1"})crumb.assert_called_once()@@ -97,7 +100,9 @@ def test_a_throwing_breadcrumb_still_lets_the_capture_through():side_effect=RuntimeError("sentry unavailable"),),):- emit_funnel_event("user-1", "hire_completed", {"template_id": "tpl-1"})+ emit_funnel_event(+ "user-1", PostHogEvent.HIRE_COMPLETED, {"template_id": "tpl-1"}+ )client.capture.assert_called_once()@@ -107,9 +112,13 @@ def test_a_data_index_also_becomes_a_deterministic_event_uuid():randomises per call, so a retry needs the same one."""client = MagicMock()with patch.object(funnel_analytics, "get_posthog_client", return_value=client):- emit_funnel_event("user-1", "briefing_delivered", {}, "briefing_delivered:b-1")+ emit_funnel_event(+ "user-1", PostHogEvent.BRIEFING_DELIVERED, {}, "briefing_delivered:b-1"+ )first = client.capture.call_args.kwargs["uuid"]- emit_funnel_event("user-1", "briefing_delivered", {}, "briefing_delivered:b-1")+ emit_funnel_event(+ "user-1", PostHogEvent.BRIEFING_DELIVERED, {}, "briefing_delivered:b-1"+ )second = client.capture.call_args.kwargs["uuid"]assert first and first == second@@ -119,9 +128,13 @@ def test_a_data_index_also_becomes_a_deterministic_event_uuid():def test_a_different_event_identity_gets_a_different_uuid():client = MagicMock()with patch.object(funnel_analytics, "get_posthog_client", return_value=client):- emit_funnel_event("user-1", "briefing_delivered", {}, "briefing_delivered:b-1")+ emit_funnel_event(+ "user-1", PostHogEvent.BRIEFING_DELIVERED, {}, "briefing_delivered:b-1"+ )a = client.capture.call_args.kwargs["uuid"]- emit_funnel_event("user-2", "briefing_delivered", {}, "briefing_delivered:b-1")+ emit_funnel_event(+ "user-2", PostHogEvent.BRIEFING_DELIVERED, {}, "briefing_delivered:b-1"+ )b = client.capture.call_args.kwargs["uuid"]assert a != b@@ -130,7 +143,7 @@ def test_a_different_event_identity_gets_a_different_uuid():def test_no_data_index_leaves_the_uuid_to_the_client():client = MagicMock()with patch.object(funnel_analytics, "get_posthog_client", return_value=client):- emit_funnel_event("user-1", "expert_fired", {"expert_id": "e-1"})+ emit_funnel_event("user-1", PostHogEvent.EXPERT_FIRED, {"expert_id": "e-1"})assert client.capture.call_args.kwargs["uuid"] is None@@ -139,7 +152,9 @@ def test_a_failing_capture_never_raises_into_the_caller():client = MagicMock()client.capture.side_effect = RuntimeError("posthog unreachable")with patch.object(funnel_analytics, "get_posthog_client", return_value=client):- emit_funnel_event("user-1", "hire_completed", {"template_id": "tpl-1"})+ emit_funnel_event(+ "user-1", PostHogEvent.HIRE_COMPLETED, {"template_id": "tpl-1"}+ )def test_a_failing_client_lookup_never_raises_into_the_caller():@@ -148,13 +163,37 @@ def test_a_failing_client_lookup_never_raises_into_the_caller():"get_posthog_client",side_effect=RuntimeError("settings unreadable"),):- emit_funnel_event("user-1", "hire_completed", {"template_id": "tpl-1"})+ emit_funnel_event(+ "user-1", PostHogEvent.HIRE_COMPLETED, {"template_id": "tpl-1"}+ )def test_the_payload_is_copied_not_shared_with_the_caller():client = MagicMock()payload = {"expert_id": "e-1"}with patch.object(funnel_analytics, "get_posthog_client", return_value=client):- emit_funnel_event("user-1", "expert_fired", payload, "expert_fired:e-1")+ emit_funnel_event(+ "user-1", PostHogEvent.EXPERT_FIRED, payload, "expert_fired:e-1"+ )assert payload == {"expert_id": "e-1"}+++def test_the_event_goes_out_as_its_plain_name_and_keeps_its_uuid():+ """Moving names into an enum must not change what PostHog receives: the+ name is the same plain string, and the dedup uuid derived from it matches+ the one events sent before the enum existed already carry."""+ client = MagicMock()+ with patch.object(funnel_analytics, "get_posthog_client", return_value=client):+ emit_funnel_event(+ "user-1", PostHogEvent.BRIEFING_DELIVERED, {}, "briefing_delivered:b-1"+ )++ kwargs = client.capture.call_args.kwargs+ assert type(kwargs["event"]) is str+ assert kwargs["event"] == "briefing_delivered"+ assert kwargs["uuid"] == str(+ uuid.uuid5(+ uuid.NAMESPACE_URL, "user-1:briefing_delivered:briefing_delivered:b-1"+ )+ )diff --git a/autogpt_platform/backend/backend/util/posthog_events.py b/autogpt_platform/backend/backend/util/posthog_events.pynew file mode 100644index 0000000000..1a3afa02c1--- /dev/null+++ b/autogpt_platform/backend/backend/util/posthog_events.py@@ -0,0 +1,83 @@+"""Every PostHog event name the backend sends, in one place.++``docs/platform/tracking-plan.md`` says what each event means, which side+sends it and which properties it carries. This module is the code half of+that plan: emitters take the name from here instead of spelling it out. The+funnel ``data_index`` keys (``briefing_generated:<id>``, ...) embed the name+as a string, so a rename has to update those too.++Never change the value of a member of ``PostHogEvent``. PostHog stores the+raw string, so a rename orphans every insight, funnel and cohort built on the+old name, and past events cannot be backfilled. ``posthog_events_test.py``+pins the values so an accidental rename fails CI.+"""++from enum import StrEnum+++class PostHogEvent(StrEnum):+ """Events the backend emits today."""++ # Activation: backend/util/product_analytics.py+ RUN_AGENT = "run_agent"+ RUN_AUTOPILOT = "run_autopilot"+ RUN_EXPERT = "run_expert"+ AGENT_RUN_COMPLETED = "agent_run_completed"+ AGENT_RUN_FAILED = "agent_run_failed"+ SCHEDULE_CREATED = "schedule_created"+ SCHEDULE_FIRED = "schedule_fired"+ TRIGGER_FIRED = "trigger_fired"+ EXPERT_HIRED = "expert_hired"+ INTEGRATION_CONNECTED = "integration_connected"++ # Experts loop: backend/util/funnel_analytics.py+ HIRE_FAILED = "hire_failed"+ HIRE_COMPLETED = "hire_completed"+ WRITING_STYLE_ADDED = "writing_style_added"+ WORKFLOW_INSTALLED_ON_EXPERT = "workflow_installed_on_expert"+ EXPERT_FIRED = "expert_fired"+ BRIEFING_GENERATED = "briefing_generated"+ BRIEFING_DELIVERED = "briefing_delivered"+ EXPERT_RUN_COMPLETED = "expert_run_completed"++ # Copilot: backend/copilot/tracking.py+ COPILOT_MESSAGE_SENT = "copilot_message_sent"+ COPILOT_TOOL_CALLED = "copilot_tool_called"+ COPILOT_AGENT_RUN_SUCCESS = "copilot_agent_run_success"+ COPILOT_AGENT_SCHEDULED = "copilot_agent_scheduled"+ COPILOT_FOLLOWUP_SCHEDULED = "copilot_followup_scheduled"+ COPILOT_LIBRARY_CHECK_OUTCOME = "copilot_library_check_outcome"+ # Dead: track_trigger_setup has no caller.+ COPILOT_TRIGGER_SETUP = "copilot_trigger_setup"++ # Billing: backend/data/credit.py+ CREDIT_TOPUP_SUCCESS = "credit_topup_success"+ SUBSCRIPTION_CANCELLATION_SCHEDULED = "subscription_cancellation_scheduled"+ SUBSCRIPTION_UPGRADED = "subscription_upgraded"+ SUBSCRIPTION_PAYMENT_SUCCESS = "subscription_payment_success"+ SUBSCRIPTION_TIER_RECONCILIATION_DISCREPANCY = (+ "subscription_tier_reconciliation_discrepancy"+ )++ # Trial lifecycle: backend/notifications/trial.py+ SUBSCRIPTION_TRIAL_STARTED = "subscription_trial_started"+ SUBSCRIPTION_TRIAL_ENDING = "subscription_trial_ending"+ SUBSCRIPTION_TRIAL_CANCELED = "subscription_trial_canceled"+ SUBSCRIPTION_TRIAL_RESUMED = "subscription_trial_resumed"+ SUBSCRIPTION_TRIAL_ENDED = "subscription_trial_ended"+ SUBSCRIPTION_TRIAL_CONVERTED = "subscription_trial_converted"+ SUBSCRIPTION_TRIAL_PAYMENT_FAILED = "subscription_trial_payment_failed"+++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.+ """++ SIGNUP_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"diff --git a/autogpt_platform/backend/backend/util/posthog_events_test.py b/autogpt_platform/backend/backend/util/posthog_events_test.pynew file mode 100644index 0000000000..2af8b97b8e--- /dev/null+++ b/autogpt_platform/backend/backend/util/posthog_events_test.py@@ -0,0 +1,69 @@+"""Pins every PostHog event name the backend sends.++A failure here means an event name changed. PostHog cannot backfill a rename,+so every insight built on the old name silently goes empty. Add new members+freely; never edit an existing string.+"""++from backend.util.posthog_events import PlannedPostHogEvent, PostHogEvent++LIVE_EVENT_NAMES = {+ "run_agent",+ "run_autopilot",+ "run_expert",+ "agent_run_completed",+ "agent_run_failed",+ "schedule_created",+ "schedule_fired",+ "trigger_fired",+ "expert_hired",+ "integration_connected",+ "hire_failed",+ "hire_completed",+ "writing_style_added",+ "workflow_installed_on_expert",+ "expert_fired",+ "briefing_generated",+ "briefing_delivered",+ "expert_run_completed",+ "copilot_message_sent",+ "copilot_tool_called",+ "copilot_agent_run_success",+ "copilot_agent_scheduled",+ "copilot_followup_scheduled",+ "copilot_library_check_outcome",+ "copilot_trigger_setup",+ "credit_topup_success",+ "subscription_cancellation_scheduled",+ "subscription_upgraded",+ "subscription_payment_success",+ "subscription_tier_reconciliation_discrepancy",+ "subscription_trial_started",+ "subscription_trial_ending",+ "subscription_trial_canceled",+ "subscription_trial_resumed",+ "subscription_trial_ended",+ "subscription_trial_converted",+ "subscription_trial_payment_failed",+}++PLANNED_EVENT_NAMES = {+ "signup_completed",+ "onboarding_completed",+ "checkout_started",+ "subscription_ended",+ "listing_added_to_library",+ "listing_downloaded",+}+++def test_live_event_names_are_pinned():+ assert {event.value for event in PostHogEvent} == LIVE_EVENT_NAMES+++def test_planned_event_names_are_pinned():+ assert {event.value for event in PlannedPostHogEvent} == PLANNED_EVENT_NAMES+++def test_a_planned_event_is_not_also_live():+ assert not LIVE_EVENT_NAMES & PLANNED_EVENT_NAMESdiff --git a/autogpt_platform/backend/backend/util/product_analytics.py b/autogpt_platform/backend/backend/util/product_analytics.pyindex 24adb07561..71941a001b 100644--- a/autogpt_platform/backend/backend/util/product_analytics.py+++ b/autogpt_platform/backend/backend/util/product_analytics.py@@ -28,15 +28,22 @@ Event vocabulary (PostHog event name -> SQL equivalent):- ``integration_connected`` a user connected a credential (OAuth or manual).IntegrationCredential rows by createdByUserId.+``run_agent`` is not the same as a "task": the ``analytics.*`` views count a+copilot-started run through the chat turn that asked for it, so a task is+``run_agent`` / ``run_expert`` with ``trigger`` other than ``copilot``, plus+every ``run_autopilot`` and chat-turn ``run_expert``. Event names live in+``backend.util.posthog_events``; the full list and the task filter are in+``docs/platform/tracking-plan.md``.+Every emitter is best-effort: tracking can never break the work it describes."""import loggingfrom datetime import datetime-from enum import StrEnumfrom typing import TYPE_CHECKING, Any, Literalfrom backend.util.posthog_client import get_posthog_client+from backend.util.posthog_events import PostHogEventfrom backend.util.settings import Settingsif TYPE_CHECKING:@@ -47,19 +54,6 @@ logger = logging.getLogger(__name__)settings = Settings()-class ActivationEvent(StrEnum):- RUN_AGENT = "run_agent"- RUN_AUTOPILOT = "run_autopilot"- RUN_EXPERT = "run_expert"- AGENT_RUN_COMPLETED = "agent_run_completed"- AGENT_RUN_FAILED = "agent_run_failed"- SCHEDULE_CREATED = "schedule_created"- SCHEDULE_FIRED = "schedule_fired"- TRIGGER_FIRED = "trigger_fired"- EXPERT_HIRED = "expert_hired"- INTEGRATION_CONNECTED = "integration_connected"--ScheduleTarget = Literal["agent", "autopilot", "expert"]# Triggers that mean "a person asked for this run now". Schedule and webhook@@ -74,7 +68,7 @@ def _enum_value(value: Any) -> Any:def track(user_id: str | None,- event: ActivationEvent,+ event: PostHogEvent,properties: dict[str, Any] | None = None,) -> None:"""Send one event for *user_id*. Silently no-ops when analytics is off."""@@ -122,11 +116,11 @@ def track_agent_run_started(if expert_id:track(user_id,- ActivationEvent.RUN_EXPERT,+ PostHogEvent.RUN_EXPERT,{**properties, "kind": "workflow_run"},)else:- track(user_id, ActivationEvent.RUN_AGENT, properties)+ track(user_id, PostHogEvent.RUN_AGENT, properties)def track_agent_run_finished(@@ -146,9 +140,9 @@ def track_agent_run_finished(returnstatus_value = _enum_value(status)if status_value == "COMPLETED":- event = ActivationEvent.AGENT_RUN_COMPLETED+ event = PostHogEvent.AGENT_RUN_COMPLETEDelif status_value == "FAILED":- event = ActivationEvent.AGENT_RUN_FAILED+ event = PostHogEvent.AGENT_RUN_FAILEDelse:returntrack(@@ -206,7 +200,7 @@ def track_chat_turn(returntrack(user_id,- ActivationEvent.RUN_EXPERT if expert_id else ActivationEvent.RUN_AUTOPILOT,+ PostHogEvent.RUN_EXPERT if expert_id else PostHogEvent.RUN_AUTOPILOT,{"session_id": session_id,"expert_id": expert_id,@@ -236,7 +230,7 @@ def track_schedule_created() -> None:track(user_id,- ActivationEvent.SCHEDULE_CREATED,+ PostHogEvent.SCHEDULE_CREATED,{"schedule_id": schedule_id,"target": target,@@ -262,7 +256,7 @@ def track_schedule_fired() -> None:track(user_id,- ActivationEvent.SCHEDULE_FIRED,+ PostHogEvent.SCHEDULE_FIRED,{"schedule_id": schedule_id,"target": target,@@ -285,7 +279,7 @@ def track_trigger_fired() -> None:track(user_id,- ActivationEvent.TRIGGER_FIRED,+ PostHogEvent.TRIGGER_FIRED,{"webhook_id": webhook_id,"graph_id": graph_id,@@ -306,7 +300,7 @@ def track_expert_hired() -> None:track(user_id,- ActivationEvent.EXPERT_HIRED,+ PostHogEvent.EXPERT_HIRED,{"expert_id": expert_id, "template_id": template_id, "name": name},)@@ -320,7 +314,7 @@ def track_integration_connected() -> None:track(user_id,- ActivationEvent.INTEGRATION_CONNECTED,+ PostHogEvent.INTEGRATION_CONNECTED,{"provider": _enum_value(provider),"credential_type": _enum_value(credential_type),diff --git a/autogpt_platform/backend/backend/util/product_analytics_test.py b/autogpt_platform/backend/backend/util/product_analytics_test.pyindex adffcb8213..a55b6ce227 100644--- a/autogpt_platform/backend/backend/util/product_analytics_test.py+++ b/autogpt_platform/backend/backend/util/product_analytics_test.py@@ -5,7 +5,7 @@ from unittest.mock import Mockimport pytestfrom backend.util import product_analytics-from backend.util.product_analytics import ActivationEvent+from backend.util.posthog_events import PostHogEventfrom backend.util.settings import AppEnvironment@@ -24,17 +24,17 @@ def _only_call(capture: Mock) -> tuple[str, dict]:def test_track_is_a_noop_without_client(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(product_analytics, "get_posthog_client", lambda: None)- product_analytics.track("user-1", ActivationEvent.RUN_AGENT, {"graph_id": "g"})+ product_analytics.track("user-1", PostHogEvent.RUN_AGENT, {"graph_id": "g"})def test_track_is_a_noop_without_user(capture: Mock) -> None:- product_analytics.track(None, ActivationEvent.RUN_AGENT, {"graph_id": "g"})+ product_analytics.track(None, PostHogEvent.RUN_AGENT, {"graph_id": "g"})capture.assert_not_called()def test_track_adds_base_properties_and_drops_nulls(capture: Mock) -> None:product_analytics.track(- "user-1", ActivationEvent.RUN_AGENT, {"graph_id": "g", "expert_id": None}+ "user-1", PostHogEvent.RUN_AGENT, {"graph_id": "g", "expert_id": None})event, properties = _only_call(capture)@@ -48,7 +48,7 @@ def test_track_adds_base_properties_and_drops_nulls(capture: Mock) -> None:def test_track_swallows_client_errors(capture: Mock) -> None:capture.side_effect = RuntimeError("posthog down")- product_analytics.track("user-1", ActivationEvent.RUN_AGENT)+ product_analytics.track("user-1", PostHogEvent.RUN_AGENT)@pytest.mark.parametrize("trigger", ["manual", "api", "copilot"])diff --git a/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.ts b/autogpt_platform/frontend/src/components/organisms/TrialCard/useTrialCard.tsindex 2f8603ca53..23fddf8225 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 { TrialEvent } from "@/services/analytics/posthog-events";import { useTrialStatus } from "@/services/trials/useTrialStatus";import { updateTrialStatusCache } from "@/services/trials/updateTrialStatusCache";import { useQueryClient } from "@tanstack/react-query";@@ -30,7 +31,7 @@ export function useTrialCard(returnTo: "onboarding" | "billing") {const identity = `${userID}:${offer.token}`;if (seenOffer.current === identity) return;seenOffer.current = identity;- posthog?.capture("subscription_trial_offer_viewed", {+ posthog?.capture(TrialEvent.SUBSCRIPTION_TRIAL_OFFER_VIEWED, {trial_offer_version: offer.version,subscription_tier: offer.tier,trial_duration_days: offer.duration_days,@@ -48,7 +49,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("subscription_trial_checkout_started", {+ posthog?.capture(TrialEvent.SUBSCRIPTION_TRIAL_CHECKOUT_STARTED, {trial_offer_version: offer.version,surface: returnTo,});diff --git a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsxindex 182351f14c..cc6f9870da 100644--- a/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx+++ b/autogpt_platform/frontend/src/providers/posthog/posthog-provider.tsx@@ -6,6 +6,7 @@ import {followAnalyticsConsentForIdentity,getAnonymousID,} from "@/services/analytics/anonymous-id";+import { PageEvent } from "@/services/analytics/posthog-events";import { useConsent } from "@/services/consent/useConsent";import { environment } from "@/services/environment";import { usesPostHog } from "@/services/feature-flags/flag-backend";@@ -107,7 +108,7 @@ export function PostHogPageViewTracker() {if (searchParams && searchParams.toString()) {url = url + `?${searchParams.toString()}`;}- posthog.capture("$pageview", { $current_url: url });+ posthog.capture(PageEvent.PAGEVIEW, { $current_url: url });}}, [pathname, searchParams, isPostHogEnabled, analytics]);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.tsnew file mode 100644index 0000000000..ccbf177a63--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/__tests__/posthog-events.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vitest";+import { PlannedPostHogEvent, PostHogEvent } from "../posthog-events";++// A failure here means an event name changed. PostHog cannot backfill a+// rename, so every insight built on the old name silently goes empty. Add+// new names freely; never edit an existing string.++const LIVE_EVENT_NAMES = [+ "$pageview",+ "brain_dump_canceled",+ "brain_dump_completed",+ "brain_dump_download",+ "brain_dump_permission_denied",+ "brain_dump_recovery_shown",+ "brain_dump_recovery_used",+ "brain_dump_restarted",+ "brain_dump_retry",+ "brain_dump_skipped",+ "brain_dump_started",+ "brain_dump_typed_fallback",+ "briefing_opened",+ "briefing_outcome_clicked",+ "capability_card_viewed",+ "capability_cards_completed",+ "capability_cards_skipped",+ "credential_card_never_rendered",+ "credential_oauth_flow_timed_out",+ "credential_oauth_popup_blocked",+ "credential_proceed_stuck_after_connect",+ "credential_scope_shortfall_blocked_selection",+ "experiment_exposed",+ "expert_profile_opened",+ "expert_recommendation_clicked",+ "expert_recommended",+ "expert_thread_created",+ "experts_section_viewed",+ "feature_flag_mismatch",+ "finalize_latency_ms",+ "hire_flow_abandoned",+ "hire_flow_completed",+ "hire_started",+ "hire_step_continued",+ "home_attention_actioned",+ "home_team_member_clicked",+ "home_viewed",+ "intro_card_dismissed",+ "intro_followup_sent",+ "intro_path",+ "intro_start_with_autopilot",+ "later_dump_completed",+ "onboarding_expert_hired",+ "raise_door_clicked",+ "subscription_trial_checkout_started",+ "subscription_trial_offer_viewed",+ "tab_intro_cta_clicked",+ "tab_intro_dismissed",+ "tab_intro_shown",+ "transcription_failed",+ "voice_first_sound_latency_ms",+ "voice_mode_error",+ "voice_mode_permission_denied",+ "voice_mode_started",+ "voice_mode_stopped",+ "voice_mode_timed_out",+ "voice_recording_downloaded",+ "voice_transcribe_latency_ms",+ "voice_transcribe_retried",+ "voice_turn_completed",+ "voice_turn_dropped",+ "voice_turn_sent",+ "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",+];++describe("PostHog event names", () => {+ it("keeps every live name exactly as PostHog already stores it", () => {+ expect(Object.values(PostHogEvent).sort()).toEqual(LIVE_EVENT_NAMES);+ });++ it("keeps the planned names that are not sent yet", () => {+ expect(Object.values(PlannedPostHogEvent).sort()).toEqual(+ PLANNED_EVENT_NAMES,+ );+ });++ it("never lists a planned name as live", () => {+ const live = new Set<string>(Object.values(PostHogEvent));+ expect(PLANNED_EVENT_NAMES.filter((name) => live.has(name))).toEqual([]);+ });+});diff --git a/autogpt_platform/frontend/src/services/analytics/posthog-events.ts b/autogpt_platform/frontend/src/services/analytics/posthog-events.tsnew file mode 100644index 0000000000..2406212278--- /dev/null+++ b/autogpt_platform/frontend/src/services/analytics/posthog-events.ts@@ -0,0 +1,189 @@+// Every PostHog event name the browser sends, in one place. What each one+// means, who sends it and which properties it carries is in+// docs/platform/tracking-plan.md; the backend's list is+// backend/util/posthog_events.py.+//+// Never change a value here. PostHog stores the raw string, so a rename+// orphans every insight and funnel built on the old name and cannot be+// backfilled. __tests__/posthog-events.test.ts pins the values.+//+// Plain `as const` objects rather than enums so a string literal at a call+// site still type-checks against the list. Call sites do pass literals, so+// a rename has to search for the old string beyond this file.++export const PageEvent = {+ PAGEVIEW: "$pageview",+} as const;++export const ExperimentEvent = {+ EXPERIMENT_EXPOSED: "experiment_exposed",+} as const;++// Ops signal from the dual flag backend, not a user action: LaunchDarkly and+// PostHog resolved the same flag to different values.+export const FeatureFlagEvent = {+ FEATURE_FLAG_MISMATCH: "feature_flag_mismatch",+} as const;++export const ExpertsFunnelEvent = {+ EXPERTS_SECTION_VIEWED: "experts_section_viewed",+ HOME_VIEWED: "home_viewed",+ BRIEFING_OPENED: "briefing_opened",+ EXPERT_PROFILE_OPENED: "expert_profile_opened",+ HIRE_STARTED: "hire_started",+ EXPERT_THREAD_CREATED: "expert_thread_created",+ BRIEFING_OUTCOME_CLICKED: "briefing_outcome_clicked",+ HOME_ATTENTION_ACTIONED: "home_attention_actioned",+ HOME_TEAM_MEMBER_CLICKED: "home_team_member_clicked",+} as const;++export const HireFlowEvent = {+ HIRE_FLOW_COMPLETED: "hire_flow_completed",+ HIRE_FLOW_ABANDONED: "hire_flow_abandoned",+} as const;++export const BrainDumpEvent = {+ BRAIN_DUMP_STARTED: "brain_dump_started",+ BRAIN_DUMP_COMPLETED: "brain_dump_completed",+ BRAIN_DUMP_CANCELED: "brain_dump_canceled",+ BRAIN_DUMP_SKIPPED: "brain_dump_skipped",+ BRAIN_DUMP_RECOVERY_SHOWN: "brain_dump_recovery_shown",+ BRAIN_DUMP_RECOVERY_USED: "brain_dump_recovery_used",+ BRAIN_DUMP_RETRY: "brain_dump_retry",+ BRAIN_DUMP_RESTARTED: "brain_dump_restarted",+ BRAIN_DUMP_DOWNLOAD: "brain_dump_download",+ BRAIN_DUMP_PERMISSION_DENIED: "brain_dump_permission_denied",+ BRAIN_DUMP_TYPED_FALLBACK: "brain_dump_typed_fallback",+ // Wall-clock of the whole finalize round trip — upload flush, virus+ // scan, storage, transcription and extraction. Named for what it+ // actually measures: the client cannot see the transcription step on+ // its own, so calling this "transcription latency" overstated it.+ FINALIZE_LATENCY_MS: "finalize_latency_ms",+ // The welcome dialog shown on first copilot landing was closed — the+ // greeting fetch and reveal animation start from this moment.+ WELCOME_DIALOG_CLOSED: "welcome_dialog_closed",+ // Capability-cards first-run funnel: which cards were reached and how+ // the modal ended (finished the deck vs skipped at card_index).+ CAPABILITY_CARD_VIEWED: "capability_card_viewed",+ CAPABILITY_CARDS_COMPLETED: "capability_cards_completed",+ CAPABILITY_CARDS_SKIPPED: "capability_cards_skipped",+ TRANSCRIPTION_FAILED: "transcription_failed",+ INTRO_PATH: "intro_path",+ // The user's first real message after seeing the intro card — the+ // signal that the card actually started a conversation. The suggested+ // prompts rendered beneath it are personalised from the same dump, so+ // this covers both a suggestion click and a typed reply.+ INTRO_FOLLOWUP_SENT: "intro_followup_sent",+ LATER_DUMP_COMPLETED: "later_dump_completed",+ // The team Otto proposed on the greeting page: one event per card+ // shown, then the doors out of it — hire, create your own, talk it+ // through, or skip straight to the builder.+ EXPERT_RECOMMENDED: "expert_recommended",+ EXPERT_RECOMMENDATION_CLICKED: "expert_recommendation_clicked",+ HIRE_STARTED: ExpertsFunnelEvent.HIRE_STARTED,+ // The wizard's hire step: a hire that landed from a card, and the step+ // being left — with how many of the proposed experts were hired, so the+ // funnel can tell "hired a team" from "skipped past it".+ ONBOARDING_EXPERT_HIRED: "onboarding_expert_hired",+ HIRE_STEP_CONTINUED: "hire_step_continued",+ // Declared but never sent; the tracking plan marks them for removal.+ INTRO_CARD_DISMISSED: "intro_card_dismissed",+ RAISE_DOOR_CLICKED: "raise_door_clicked",+ INTRO_START_WITH_AUTOPILOT: "intro_start_with_autopilot",+} as const;++export const TabIntroEvent = {+ TAB_INTRO_SHOWN: "tab_intro_shown",+ // The card's primary CTA was used, as opposed to any of the ways out+ // ("Got it", Escape, the backdrop) that all land on `tab_intro_dismissed`.+ TAB_INTRO_CTA_CLICKED: "tab_intro_cta_clicked",+ TAB_INTRO_DISMISSED: "tab_intro_dismissed",+} as const;++export const VoiceModeEvent = {+ // Enabled from the composer. `entry` says whether a chat already existed,+ // since starting one costs a session-creation round trip first.+ VOICE_MODE_STARTED: "voice_mode_started",+ // Left deliberately: the toggle, or Stop during a reply.+ VOICE_MODE_STOPPED: "voice_mode_stopped",+ // Closed by the silence timeout rather than by the user. A high share+ // here means the timeout is too short, which is exactly the complaint+ // that moved the VAD from 700 ms to 1540 ms.+ VOICE_MODE_TIMED_OUT: "voice_mode_timed_out",+ // A completed turn: heard, transcribed, sent. `turn_index` counts within+ // the session, so a histogram shows whether anyone gets past one.+ VOICE_TURN_SENT: "voice_turn_sent",+ // Heard something and threw it away — VAD misfire, or filler/hallucination+ // like Whisper's "Thank you." on silence. Splits by `reason`.+ VOICE_TURN_DROPPED: "voice_turn_dropped",+ // Speech end to transcript in hand. The spike measured 1.05 s on a+ // streaming session; this route uploads the whole clip, so it is the+ // number that decides whether streaming STT is worth building.+ VOICE_TRANSCRIBE_LATENCY_MS: "voice_transcribe_latency_ms",+ // Speech end to the first spoken word. The click answers "did it hear+ // me" instantly; this measures how long the answer itself takes.+ VOICE_FIRST_SOUND_LATENCY_MS: "voice_first_sound_latency_ms",+ // The mic reopened after a reply finished playing: a full loop closed.+ VOICE_TURN_COMPLETED: "voice_turn_completed",+ // The user asked for a failed transcription to be tried again. Against+ // `voice_turn_dropped{reason:transcribe_failed}` this says how many of those+ // dropped turns the user actually got back.+ VOICE_TRANSCRIBE_RETRIED: "voice_transcribe_retried",+ // Gave up on transcription and took the audio instead. Rare by design: a+ // run of these means retrying is not working.+ VOICE_RECORDING_DOWNLOADED: "voice_recording_downloaded",+ VOICE_MODE_PERMISSION_DENIED: "voice_mode_permission_denied",+ // Synthesis or the VAD failed. `stage` says which.+ VOICE_MODE_ERROR: "voice_mode_error",+} as const;++export const CredentialConnectionFailureEvent = {+ // The provider is absent from the loaded provider map, so the card's row+ // for it never renders at all.+ CREDENTIAL_CARD_NEVER_RENDERED: "credential_card_never_rendered",+ // Popup and the new-tab fallback were both blocked: there is no way in.+ CREDENTIAL_OAUTH_POPUP_BLOCKED: "credential_oauth_popup_blocked",+ CREDENTIAL_OAUTH_FLOW_TIMED_OUT: "credential_oauth_flow_timed_out",+ // Connected, stored, and then refused by the card because the provider+ // granted less than the block asked for.+ CREDENTIAL_SCOPE_SHORTFALL_BLOCKED_SELECTION:+ "credential_scope_shortfall_blocked_selection",+ // A sign-in completed on this card and the credential never reached it.+ CREDENTIAL_PROCEED_STUCK_AFTER_CONNECT:+ "credential_proceed_stuck_after_connect",+} as const;++export const TrialEvent = {+ SUBSCRIPTION_TRIAL_OFFER_VIEWED: "subscription_trial_offer_viewed",+ SUBSCRIPTION_TRIAL_CHECKOUT_STARTED: "subscription_trial_checkout_started",+} as const;++export const PostHogEvent = {+ ...PageEvent,+ ...ExperimentEvent,+ ...FeatureFlagEvent,+ ...ExpertsFunnelEvent,+ ...HireFlowEvent,+ ...BrainDumpEvent,+ ...TabIntroEvent,+ ...VoiceModeEvent,+ ...CredentialConnectionFailureEvent,+ ...TrialEvent,+} 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;++export type EventName<Group extends Record<string, string>> =+ Group[keyof Group];diff --git a/autogpt_platform/frontend/src/services/copilot/voice-mode-analytics.ts b/autogpt_platform/frontend/src/services/copilot/voice-mode-analytics.tsindex 78d23b69b7..4522d51074 100644--- a/autogpt_platform/frontend/src/services/copilot/voice-mode-analytics.ts+++ b/autogpt_platform/frontend/src/services/copilot/voice-mode-analytics.ts@@ -6,46 +6,16 @@// Lives in services/ alongside the brain-dump funnel because both measure// the same microphone path from different ends.+import {+ VoiceModeEvent,+ type EventName,+} from "@/services/analytics/posthog-events";import posthog from "posthog-js";-type VoiceModeEvent =- // Enabled from the composer. `entry` says whether a chat already existed,- // since starting one costs a session-creation round trip first.- | "voice_mode_started"- // Left deliberately: the toggle, or Stop during a reply.- | "voice_mode_stopped"- // Closed by the silence timeout rather than by the user. A high share- // here means the timeout is too short, which is exactly the complaint- // that moved the VAD from 700 ms to 1540 ms.- | "voice_mode_timed_out"- // A completed turn: heard, transcribed, sent. `turn_index` counts within- // the session, so a histogram shows whether anyone gets past one.- | "voice_turn_sent"- // Heard something and threw it away — VAD misfire, or filler/hallucination- // like Whisper's "Thank you." on silence. Splits by `reason`.- | "voice_turn_dropped"- // Speech end to transcript in hand. The spike measured 1.05 s on a- // streaming session; this route uploads the whole clip, so it is the- // number that decides whether streaming STT is worth building.- | "voice_transcribe_latency_ms"- // Speech end to the first spoken word. The click answers "did it hear- // me" instantly; this measures how long the answer itself takes.- | "voice_first_sound_latency_ms"- // The mic reopened after a reply finished playing: a full loop closed.- | "voice_turn_completed"- // The user asked for a failed transcription to be tried again. Against- // `voice_turn_dropped{reason:transcribe_failed}` this says how many of those- // dropped turns the user actually got back.- | "voice_transcribe_retried"- // Gave up on transcription and took the audio instead. Rare by design: a- // run of these means retrying is not working.- | "voice_recording_downloaded"- | "voice_mode_permission_denied"- // Synthesis or the VAD failed. `stage` says which.- | "voice_mode_error";+type VoiceModeEventName = EventName<typeof VoiceModeEvent>;export function trackVoiceMode(- event: VoiceModeEvent,+ event: VoiceModeEventName,properties?: Record<string, unknown>,) {try {diff --git a/autogpt_platform/frontend/src/services/credentials/connection-analytics.ts b/autogpt_platform/frontend/src/services/credentials/connection-analytics.tsindex 852beb503d..ed61be1d08 100644--- a/autogpt_platform/frontend/src/services/credentials/connection-analytics.ts+++ b/autogpt_platform/frontend/src/services/credentials/connection-analytics.ts@@ -6,27 +6,26 @@// `failure_class` matches the tag the backend puts on its own credential// failures, so one class number covers both halves of a path.+import {+ CredentialConnectionFailureEvent,+ type EventName,+} from "@/services/analytics/posthog-events";import posthog from "posthog-js";-type CredentialConnectionFailure =- // The provider is absent from the loaded provider map, so the card's row- // for it never renders at all.- | "credential_card_never_rendered"- // Popup and the new-tab fallback were both blocked: there is no way in.- | "credential_oauth_popup_blocked"- | "credential_oauth_flow_timed_out"- // Connected, stored, and then refused by the card because the provider- // granted less than the block asked for.- | "credential_scope_shortfall_blocked_selection"- // A sign-in completed on this card and the credential never reached it.- | "credential_proceed_stuck_after_connect";+type CredentialConnectionFailure = EventName<+ typeof CredentialConnectionFailureEvent+>;const FAILURE_CLASS: Record<CredentialConnectionFailure, string> = {- credential_card_never_rendered: "class_03_provider_unknown_to_frontend",- credential_oauth_popup_blocked: "class_05_browser_channel_broken",- credential_oauth_flow_timed_out: "class_05_browser_channel_broken",- credential_scope_shortfall_blocked_selection: "class_08_scopes_too_narrow",- credential_proceed_stuck_after_connect:+ [CredentialConnectionFailureEvent.CREDENTIAL_CARD_NEVER_RENDERED]:+ "class_03_provider_unknown_to_frontend",+ [CredentialConnectionFailureEvent.CREDENTIAL_OAUTH_POPUP_BLOCKED]:+ "class_05_browser_channel_broken",+ [CredentialConnectionFailureEvent.CREDENTIAL_OAUTH_FLOW_TIMED_OUT]:+ "class_05_browser_channel_broken",+ [CredentialConnectionFailureEvent.CREDENTIAL_SCOPE_SHORTFALL_BLOCKED_SELECTION]:+ "class_08_scopes_too_narrow",+ [CredentialConnectionFailureEvent.CREDENTIAL_PROCEED_STUCK_AFTER_CONNECT]:"class_11_credential_not_wired_to_card",};diff --git a/autogpt_platform/frontend/src/services/experiments/useLaunchDarklyExperiment.ts b/autogpt_platform/frontend/src/services/experiments/useLaunchDarklyExperiment.tsindex 7a9ba12d57..79f6faa7b5 100644--- a/autogpt_platform/frontend/src/services/experiments/useLaunchDarklyExperiment.ts+++ b/autogpt_platform/frontend/src/services/experiments/useLaunchDarklyExperiment.ts@@ -1,6 +1,7 @@"use client";import { useAuth } from "@/lib/auth/hooks/useAuth";+import { ExperimentEvent } from "@/services/analytics/posthog-events";import { environment } from "@/services/environment";import { useFlags, useLDClient } from "launchdarkly-react-client-sdk";import posthog from "posthog-js";@@ -63,7 +64,7 @@ export function useLaunchDarklyExperiment(flagKey: string) {if (!isResolved || !variant || !userID || !postHogEnabled) return;if (!claimExposure(userID, flagKey, variant)) return;try {- posthog.capture("experiment_exposed", {+ posthog.capture(ExperimentEvent.EXPERIMENT_EXPOSED, {experiment_key: flagKey,variant,provider: "launchdarkly",diff --git a/autogpt_platform/frontend/src/services/experts/experts-analytics.ts b/autogpt_platform/frontend/src/services/experts/experts-analytics.tsindex e6f63c7941..021339c024 100644--- a/autogpt_platform/frontend/src/services/experts/experts-analytics.ts+++ b/autogpt_platform/frontend/src/services/experts/experts-analytics.ts@@ -3,24 +3,29 @@// a home render. The breadcrumb puts the same step on the timeline of any// error Sentry records afterwards.+import {+ ExpertsFunnelEvent,+ HireFlowEvent,+ type EventName,+} from "@/services/analytics/posthog-events";import * as Sentry from "@sentry/nextjs";import posthog from "posthog-js";export type FunnelViewEvent =- | "experts_section_viewed"- | "home_viewed"- | "briefing_opened";+ | typeof ExpertsFunnelEvent.EXPERTS_SECTION_VIEWED+ | typeof ExpertsFunnelEvent.HOME_VIEWED+ | typeof ExpertsFunnelEvent.BRIEFING_OPENED;interface FunnelEventProperties {- expert_profile_opened: { template_id: string };- hire_started: { template_id: string };- expert_thread_created: { expert_id: string };- briefing_outcome_clicked: { status: string };- home_attention_actioned: {+ [ExpertsFunnelEvent.EXPERT_PROFILE_OPENED]: { template_id: string };+ [ExpertsFunnelEvent.HIRE_STARTED]: { template_id: string };+ [ExpertsFunnelEvent.EXPERT_THREAD_CREATED]: { expert_id: string };+ [ExpertsFunnelEvent.BRIEFING_OUTCOME_CLICKED]: { status: string };+ [ExpertsFunnelEvent.HOME_ATTENTION_ACTIONED]: {kind: string;action: "approve" | "decline";};- home_team_member_clicked: { expert_id: string };+ [ExpertsFunnelEvent.HOME_TEAM_MEMBER_CLICKED]: { expert_id: string };}type FunnelEvent = FunnelViewEvent | keyof FunnelEventProperties;@@ -54,7 +59,7 @@ export function trackFunnel(}}-type ExpertsEvent = "hire_flow_completed" | "hire_flow_abandoned";+type ExpertsEvent = EventName<typeof HireFlowEvent>;export function trackExperts(event: ExpertsEvent,diff --git a/autogpt_platform/frontend/src/services/feature-flags/backends/dual.ts b/autogpt_platform/frontend/src/services/feature-flags/backends/dual.tsindex d501fa1aae..dac1749169 100644--- a/autogpt_platform/frontend/src/services/feature-flags/backends/dual.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/backends/dual.ts@@ -1,5 +1,6 @@"use client";+import { FeatureFlagEvent } from "@/services/analytics/posthog-events";import { environment } from "@/services/environment";import { usePostHog } from "@posthog/react";import isEqual from "lodash/isEqual";@@ -54,6 +55,6 @@ function useReportMismatch(if (!comparable || agree) return;const mismatch = JSON.parse(record);console.warn("feature-flag mismatch", mismatch);- posthog?.capture("feature_flag_mismatch", mismatch);+ posthog?.capture(FeatureFlagEvent.FEATURE_FLAG_MISMATCH, mismatch);}, [comparable, agree, record, posthog]);}diff --git a/autogpt_platform/frontend/src/services/onboarding/brain-dump-analytics.ts b/autogpt_platform/frontend/src/services/onboarding/brain-dump-analytics.tsindex e5edec4f53..d97787ba5d 100644--- a/autogpt_platform/frontend/src/services/onboarding/brain-dump-analytics.ts+++ b/autogpt_platform/frontend/src/services/onboarding/brain-dump-analytics.ts@@ -8,58 +8,16 @@// dump), and a feature folder reaching into another feature's internals// is how import graphs rot.+import {+ BrainDumpEvent,+ type EventName,+} from "@/services/analytics/posthog-events";import posthog from "posthog-js";-type BrainDumpEvent =- | "brain_dump_started"- | "brain_dump_completed"- | "brain_dump_canceled"- | "brain_dump_skipped"- | "brain_dump_recovery_shown"- | "brain_dump_recovery_used"- | "brain_dump_retry"- | "brain_dump_restarted"- | "brain_dump_download"- | "brain_dump_permission_denied"- | "brain_dump_typed_fallback"- // Wall-clock of the whole finalize round trip — upload flush, virus- // scan, storage, transcription and extraction. Named for what it- // actually measures: the client cannot see the transcription step on- // its own, so calling this "transcription latency" overstated it.- | "finalize_latency_ms"- | "intro_card_dismissed"- // The welcome dialog shown on first copilot landing was closed — the- // greeting fetch and reveal animation start from this moment.- | "welcome_dialog_closed"- // Capability-cards first-run funnel: which cards were reached and how- // the modal ended (finished the deck vs skipped at card_index).- | "capability_card_viewed"- | "capability_cards_completed"- | "capability_cards_skipped"- | "transcription_failed"- | "intro_path"- // The user's first real message after seeing the intro card — the- // signal that the card actually started a conversation. The suggested- // prompts rendered beneath it are personalised from the same dump, so- // this covers both a suggestion click and a typed reply.- | "intro_followup_sent"- | "later_dump_completed"- // The team Otto proposed on the greeting page: one event per card- // shown, then the doors out of it — hire, create your own, talk it- // through, or skip straight to the builder.- | "expert_recommended"- | "expert_recommendation_clicked"- | "hire_started"- | "raise_door_clicked"- | "intro_start_with_autopilot"- // The wizard's hire step: a hire that landed from a card, and the step- // being left — with how many of the proposed experts were hired, so the- // funnel can tell "hired a team" from "skipped past it".- | "onboarding_expert_hired"- | "hire_step_continued";+type BrainDumpEventName = EventName<typeof BrainDumpEvent>;export function trackBrainDump(- event: BrainDumpEvent,+ event: BrainDumpEventName,properties?: Record<string, unknown>,) {try {diff --git a/autogpt_platform/frontend/src/services/onboarding/tab-intro-analytics.ts b/autogpt_platform/frontend/src/services/onboarding/tab-intro-analytics.tsindex 08136c87b5..7292ffe294 100644--- a/autogpt_platform/frontend/src/services/onboarding/tab-intro-analytics.ts+++ b/autogpt_platform/frontend/src/services/onboarding/tab-intro-analytics.ts@@ -9,17 +9,16 @@ import type {TabIntroCta,TabIntroTab,} from "@/app/(platform)/components/TabIntroCard/helpers";+import {+ TabIntroEvent,+ type EventName,+} from "@/services/analytics/posthog-events";import posthog from "posthog-js";-type TabIntroEvent =- | "tab_intro_shown"- // The card's primary CTA was used, as opposed to any of the ways out- // ("Got it", Escape, the backdrop) that all land on `tab_intro_dismissed`.- | "tab_intro_cta_clicked"- | "tab_intro_dismissed";+type TabIntroEventName = EventName<typeof TabIntroEvent>;export function trackTabIntro(- event: TabIntroEvent,+ event: TabIntroEventName,properties: { tab: TabIntroTab; cta?: TabIntroCta },) {try {diff --git a/docs/platform/SUMMARY.md b/docs/platform/SUMMARY.mdindex e176f80903..06a201e5af 100644--- a/docs/platform/SUMMARY.md+++ b/docs/platform/SUMMARY.md@@ -13,6 +13,7 @@* [Templates](templates.md)* [Credits & Billing](credits-and-billing.md)* [Activation Metrics & Experiments](activation-metrics.md)+* [PostHog Tracking Plan](tracking-plan.md)* [Integrations & Credentials](integrations-and-credentials.md)* [Data Flow & Execution](data-flow-and-execution.md)* [Sharing & Exporting Agents](sharing-and-exporting.md)diff --git a/docs/platform/activation-metrics.md b/docs/platform/activation-metrics.mdindex 4053a5ac77..435101c22f 100644--- a/docs/platform/activation-metrics.md+++ b/docs/platform/activation-metrics.md@@ -79,6 +79,8 @@ Every event carries `environment` and `source: "platform"`.The pre-existing copilot events (`copilot_message_sent`, `copilot_tool_called`,...) and billing events (`credit_topup_success`, `subscription_*`) are unchanged.+Every PostHog event, its sender, its properties and whether it is kept,+merged or planned is listed in the [PostHog Tracking Plan](tracking-plan.md).## SQL views (Looker)diff --git a/docs/platform/tracking-plan.md b/docs/platform/tracking-plan.mdnew file mode 100644index 0000000000..dc77422aed--- /dev/null+++ b/docs/platform/tracking-plan.md@@ -0,0 +1,333 @@+# PostHog Tracking Plan++The single list of PostHog events: for every user action, one event name, one+sender and one set of properties. [Activation Metrics & Experiments](activation-metrics.md)+explains how PostHog fits next to the SQL views, Looker, LaunchDarkly and+DataFast; this page is the event contract.++Event names follow the product analytics plan, *Every Second Counts* (owner:+Toran), section "What we will record". Where that plan names an event for an+action, this list uses its name; [Differences from the analytics plan](#differences-from-the-analytics-plan)+lists what is not aligned yet.++In code the names live in two modules. Browser call sites may still pass a+literal (`trackBrainDump("brain_dump_started")`), which is type-checked+against these modules, and backend funnel `data_index` keys embed the name+too (`briefing_generated:<id>`, `expert_run_completed:<graph_exec_id>`). A+rename therefore has to search for the old string, not just edit the modules:++| Sender | Module | Pin test |+| --- | --- | --- |+| Backend | `autogpt_platform/backend/backend/util/posthog_events.py` (`PostHogEvent`, `PlannedPostHogEvent`) | `posthog_events_test.py` |+| Browser | `autogpt_platform/frontend/src/services/analytics/posthog-events.ts` (`PostHogEvent` and its groups, `PlannedPostHogEvent`) | `__tests__/posthog-events.test.ts` |++## Rules++### Naming++- **Use the analytics plan's name.** When the plan names an event for an+ action, that is the name, even if we used to send something else.+- Otherwise the name is `object_action`, snake_case, action in the past+ tense: `signup_completed`, `checkout_started`, `paywall_viewed`.+- Chat (Autopilot) events start with `chat_`, never `copilot_`. The trial+ lifecycle is `trial_*`.+- **Rename once, then never again.** PostHog stores the raw string, so a+ rename empties every insight, funnel and cohort built on the old name, and+ past events cannot be backfilled. The live names that differ from the plan+ (status `rename → X`) are renamed together in SECRT-2722, which lists+ every old → new pair for the insights to update. After that, the pin tests+ fail on any change to a live name.+- Put a new name in `PlannedPostHogEvent` when it is agreed, and move it into+ the live list in the change that starts sending it.++### Who sends it++- **Outcomes are sent by the backend**: something was created, charged, run,+ hired or delivered. The backend sees every path (web, API, copilot, Slack,+ Telegram, webhooks), cannot be blocked by an ad blocker, and is what the+ `analytics.*` SQL views count.+- **Interactions are sent by the browser**: views, clicks, dismissals and+ client-side timings that the backend never sees.+- One action has **one** event. Where two emitters describe the same action,+ the backend event survives and the other is merged into it (status+ `merge`).++### Base properties++Every event must carry:++| Property | Value |+| --- | --- |+| `environment` | `settings.config.app_env` on the backend (`local`, `dev`, `prod`), the matching app environment in the browser. |+| `source` | Which emitter sent it. Existing values stay: `platform` (`product_analytics.py`), `chat_copilot` (`copilot/tracking.py`). Newly covered backend emitters use `platform`; the browser uses `web`, registered once as a PostHog super property. |++Today only `product_analytics.py` and `copilot/tracking.py` send them. The+funnel (`funnel_analytics.py`), billing (`data/credit.py`) and trial+(`notifications/trial.py`) events and every browser event carry neither;+SECRT-2722 adds them.++Three events already use `source` for something else and must move that+value to its own property before the base property is applied, or the two+will overwrite each other: `hire_started` (`source: onboarding_hire_step`),+`expert_recommended` (the team's `source`) and `workflow_installed_on_expert`+(`source: library | marketplace`).++### Identity++- **`distinct_id` is the platform user id** for every backend event, the same+ id the browser passes to `posthog.identify(user.id)`, so both halves land+ on one person.+- **Before login the browser uses the first-party anonymous id**+ (`src/services/analytics/anonymous-id.ts`), passed to `posthog.init` as the+ bootstrap `distinctID`. `identify` merges it into the user at login, and+ `resetAnalyticsIdentity` mints a fresh one at logout.+- **No synthetic ids.** A backend event with no user is dropped, as+ `product_analytics.track` already does. `copilot/tracking.py` still falls+ back to `anonymous_{session_id}` for `copilot_message_sent` and+ `copilot_tool_called`; each of those creates a person nobody can merge, and+ SECRT-2722 removes the fallback.+- **No email or name in event properties.** Identify ids only. The email and+ display name are person properties set by `identify` and nowhere else.+ (`expert_hired.name` is the expert's display name, not a person's.)++## What counts as a task++The `analytics.*` views (`user_task_daily`, `user_lifecycle`,+`retention_task_weekly`, `unit_economics_monthly`) define a task as a unit of+work a person asked for now:++- a top-level, non-dry-run agent run whose `triggerSource` is `manual` or+ `api` (or NULL, for rows older than the column), expert workflow runs+ included; **or**+- a `user` message in an Autopilot or expert chat whose session origin is not+ `automation` and whose kind is not `dream`.++A run the copilot started (`triggerSource = copilot`) is **not** a second+task: the chat turn that asked for it already counts. `run_agent` does fire+for copilot-started runs (with `trigger: copilot`), because it measures+human-initiated runs, not tasks. `user_lifecycle.agent_runs_human_total` is+its SQL twin and includes copilot runs too.++The same definition as a PostHog filter (with today's names; after+SECRT-2722 it reads `agent_run_started` and `chat_message_sent`):++```sql+event IN ('run_agent', 'run_expert', 'run_autopilot')+AND coalesce(properties.trigger, '') != 'copilot'+```++In the insight UI: events `run_agent`, `run_expert` and `run_autopilot`,+filtered by `trigger` "is not" `copilot`. Chat turns carry no `trigger`, so+the filter must keep events where it is unset. The emitters already leave+out dry runs, sub-graph runs, schedule and webhook runs, and automation-origin+turns.++Automated work is measured separately: `schedule_fired` and `trigger_fired`.++## Status legend++| Status | Meaning |+| --- | --- |+| `live` | Sent today under this name. Keep it. |+| `rename → X` | Sent today under an old name. SECRT-2722 renames it to `X`, the analytics plan's name. |+| `merge → X` | Sent today, duplicates `X`. SECRT-2722 stops sending it once dashboards read `X`; the name stays reserved. |+| `add` | Not sent yet. SECRT-2723 adds it; the name is already in `PlannedPostHogEvent`. |+| `remove` | Declared in code but never sent. SECRT-2722 deletes it. |++## Acquisition++| 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.++## 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. |+| `brain_dump_started` | browser | live | — | Recording starts. |+| `brain_dump_completed` | browser | live | `input_mode`, `duration_secs` (voice) or `chars` (typed) | A dump was accepted and the wizard advances. |+| `brain_dump_canceled` | browser | live | — | Recording is cancelled. |+| `brain_dump_skipped` | browser | live | — | The step is skipped. |+| `brain_dump_recovery_shown` | browser | live | `parts` | A saved partial recording is offered back. |+| `brain_dump_recovery_used` | browser | live | — | The saved recording is used. |+| `brain_dump_retry` | browser | live | `attempt` | A failed finalize is retried. |+| `brain_dump_restarted` | browser | live | — | Recording starts over. |+| `brain_dump_download` | browser | live | — | The recording is downloaded after a failure. |+| `brain_dump_permission_denied` | browser | live | — | Microphone permission is refused. |+| `brain_dump_typed_fallback` | browser | live | `reason` | The user types instead of speaking. |+| `transcription_failed` | browser | live | `error_code` | Finalize returns a failure. |+| `finalize_latency_ms` | browser | merge → `brain_dump_completed` | `ms`, `input_mode` | Finalize returns. Becomes a `finalize_latency_ms` property on `brain_dump_completed` and `transcription_failed`. |+| `welcome_dialog_closed` | browser | live | — | The first-landing welcome dialog closes. |+| `capability_card_viewed` | browser | live | `card_index`, `deck` | A capability card is shown. |+| `capability_cards_completed` | browser | live | `card_index`, `deck` | The deck is finished. |+| `capability_cards_skipped` | browser | live | `card_index`, `deck` | The deck is skipped. |+| `intro_path` | browser | live | `path` | The intro path (A/B) is chosen. |+| `intro_followup_sent` | browser | live | `chars` | First message after the intro card. |+| `later_dump_completed` | browser | live | — | A brain dump sent later from the composer. |+| `expert_recommended` | browser | live | `template_id`, `position`, `source` (see base properties) | A recommended expert card is shown. |+| `expert_recommendation_clicked` | browser | live | `template_id`, `position` | A recommended expert card is clicked. |+| `hire_step_continued` | browser | live | `hired`, `recommended` | The hire step is left. |+| `onboarding_expert_hired` | browser | merge → `expert_hired` | `template_id`, `position` | A hire lands from the onboarding hire step. |+| `intro_card_dismissed` | browser | remove | — | Never sent. |+| `raise_door_clicked` | browser | remove | — | Never sent. |+| `intro_start_with_autopilot` | browser | remove | — | Never sent. |+| `tab_intro_shown` | browser | live | `tab` | A tab intro card is shown. |+| `tab_intro_cta_clicked` | browser | live | `tab`, `cta` | Its primary CTA is used. |+| `tab_intro_dismissed` | browser | live | `tab` | It is dismissed any other way. |+| `integration_connected` | backend | live | `provider`, `credential_type`, `method` | A credential is stored (OAuth, key, device code). |+| `credential_card_never_rendered` | browser | live | `provider`, `failure_class` | A provider is missing from the provider map. |+| `credential_oauth_popup_blocked` | browser | live | `provider`, `failure_class` | Both the popup and the new tab were blocked. |+| `credential_oauth_flow_timed_out` | browser | live | `provider`, `failure_class` | The OAuth flow timed out. |+| `credential_scope_shortfall_blocked_selection` | browser | live | `provider`, `failure_class` | The granted scopes are narrower than required. |+| `credential_proceed_stuck_after_connect` | browser | live | `provider`, `failure_class` | A connected credential never reached the card. |++## Engagement++| Event | Sender | Status | Required properties | Fires when |+| --- | --- | --- | --- | --- |+| `run_agent` | backend | rename → `agent_run_started` | `graph_id`, `graph_exec_id`, `trigger` (`manual`, `api`, `copilot`), `trigger_ref`, `preset_id` | A person starts a non-expert agent run. |+| `run_autopilot` | backend | rename → `chat_message_sent` | `session_id`, `origin`, `surface`, `kind: chat_turn` | A person sends a message in an Autopilot chat. |+| `run_expert` | backend | rename → `chat_message_sent` (chat turn) / `agent_run_started` (workflow run) | `expert_id`, `kind` (`chat_turn` or `workflow_run`); chat: `session_id`, `origin`, `surface`; run: `graph_id`, `graph_exec_id`, `trigger` | A person messages an expert or starts an expert workflow. |+| `copilot_message_sent` | backend | merge → `chat_message_sent` | `session_id`, `message_length` | Same chat turn. `message_length` moves onto `chat_message_sent`. |+| `agent_run_completed` | backend | rename → `agent_run_finished` (`status: completed`) | `graph_id`, `graph_exec_id`, `trigger`, `expert_id`, `cost_cents`, `duration_seconds` | A run reaches COMPLETED (sub-graph and automated runs included). |+| `agent_run_failed` | backend | rename → `agent_run_finished` (`status: failed`) | as above plus `failure_reason` | A run reaches FAILED. |+| `expert_run_completed` | backend | merge → `agent_run_finished` | `expert_id`, `status`, `graph_exec_id` | A top-level expert run reaches COMPLETED or FAILED. Same as `agent_run_*` with `expert_id` set on a top-level run. |+| `copilot_agent_run_success` | backend | rename → `chat_outcome` (`outcome_type: agent_run_success`) | `session_id`, `graph_id`, `graph_name`, `execution_id`, `library_agent_id` | The copilot started a run for the user: a moment of value in the chat. |+| `schedule_created` | backend | live | `schedule_id`, `target` (`agent`, `autopilot`, `expert`), `expert_id`, `cron`, `is_recurring`, `run_at`, `graph_id`, `session_id` | Any schedule is registered, from any surface. |+| `copilot_agent_scheduled` | backend | rename → `chat_outcome` (`outcome_type: schedule_created`) | `session_id`, `graph_id`, `schedule_id`, `cron`, ... | The copilot scheduled an agent. `schedule_created` (`target: agent`) still counts the schedule itself. |+| `copilot_followup_scheduled` | backend | rename → `chat_outcome` (`outcome_type: schedule_created`) | `session_id`, `schedule_id`, `is_recurring` | The copilot scheduled its own follow-up. `schedule_created` (`target: autopilot` or `expert`) still counts the schedule itself. |+| `copilot_tool_called` | backend | rename → `chat_tool_called` | `session_id`, `tool_name`, `tool_call_id` | The copilot calls a tool. |+| `copilot_library_check_outcome` | backend | rename → `chat_library_check_outcome` | `session_id`, `outcome`, `matches_count`, `top_score` | The create-agent library check ends. |+| `copilot_trigger_setup` | backend | remove | — | `track_trigger_setup` has no caller. |+| `voice_mode_started` | browser | live | `entry` | Voice mode is switched on. |+| `voice_mode_stopped` | browser | live | `turns`, `state` | Switched off by the user. |+| `voice_mode_timed_out` | browser | live | `turns`, `state` | Closed by the silence timeout. |+| `voice_turn_sent` | browser | live | `turn_index`, `transcript_chars` | A spoken turn is sent. |+| `voice_turn_dropped` | browser | live | `reason` | A spoken turn is discarded. |+| `voice_turn_completed` | browser | live | `turn_index` | The mic reopens after the reply. |+| `voice_transcribe_retried` | browser | live | `turn_index` | A failed transcription is retried. |+| `voice_recording_downloaded` | browser | live | `turn_index` | The audio is downloaded instead. |+| `voice_mode_permission_denied` | browser | live | `stage` | Microphone permission is refused. |+| `voice_mode_error` | browser | live | `stage` | The VAD, synthesis or send failed. |+| `voice_transcribe_latency_ms` | browser | merge → `voice_turn_sent` | `ms` | Becomes a `transcribe_latency_ms` property on `voice_turn_sent` (and on `voice_turn_dropped` with `reason: filler_or_empty`). |+| `voice_first_sound_latency_ms` | browser | merge → `voice_turn_completed` | `ms` | Becomes a `first_sound_latency_ms` property on `voice_turn_completed`. |+| `experts_section_viewed` | browser | live | — | The marketplace experts shelf renders with results. |+| `expert_profile_opened` | browser | live | `template_id` | An expert profile page opens. |+| `hire_started` | browser | live | `template_id` | A hire button is clicked. Sent twice per click from the onboarding hire step (`useHireStep.ts`); SECRT-2722 keeps one. |+| `hire_flow_abandoned` | browser | live | `template_id`, `stage` | The hire dialog is closed before hiring. |+| `expert_hired` | backend | live | `expert_id`, `template_id`, `name` | An expert is hired. SECRT-2722 moves it into `hire_expert` so an idempotent re-hire of an active expert no longer fires, and adds `failed_preloads_count` and the hiring `surface`. |+| `hire_completed` | backend | merge → `expert_hired` | `template_id`, `failed_preloads_count` | Same hire, already skipping re-hires. |+| `hire_flow_completed` | browser | merge → `expert_hired` | `template_id`, `expert_id`, `elapsed_ms`, `voice_picked` | Same hire, from the marketplace hire dialog. |+| `hire_failed` | backend | live | `template_id`, `failed_preloads_count` | Hiring raised. |+| `expert_thread_created` | browser | live | `expert_id` | A new expert chat is created. |+| `writing_style_added` | backend | live | `expert_id` | A writing style is saved on an expert. |+| `workflow_installed_on_expert` | backend | live | `expert_id`, `source` (see base properties), `library_agent_id` or `store_listing_version_id` | A workflow is attached to an expert. |+| `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. |++## 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. |+| `subscription_trial_offer_viewed` | browser | rename → `trial_offer_viewed` | `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`. |+| `subscription_trial_started` | backend | rename → `trial_started` | `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. |+| `subscription_trial_ending` | backend | rename → `trial_ending` | as above | The reminder window opens. |+| `subscription_trial_canceled` | backend | rename → `trial_canceled` | as above | The trial is set to cancel. |+| `subscription_trial_resumed` | backend | rename → `trial_resumed` | as above | A cancelled trial is resumed. |+| `subscription_trial_payment_failed` | backend | rename → `payment_failed` | as above | The conversion charge fails. |+| `subscription_trial_converted` | backend | rename → `trial_converted` | as above | The trial converts to paid. |+| `subscription_trial_ended` | backend | rename → `trial_ended` | as above | The trial ends without converting. |+| `subscription_upgraded` | backend | rename → `subscription_changed` (`change_type: upgrade`) | `previous_subscription_tier`, `subscription_tier`, `billing_cycle` | A paid tier change takes effect. |+| `subscription_payment_success` | backend | rename → `payment_succeeded` | `subscription_tier`, `billing_cycle`; SECRT-2723 adds `amount_cents`, `currency` | A subscription invoice is paid. |+| `credit_topup_success` | backend | rename → `topup_completed` | `amount_credits`, `top_up_type`; SECRT-2723 adds `amount_cents`, `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_tier_reconciliation_discrepancy` | backend | rename → `subscription_tier_reconciled` | `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.++## Retention++| Event | Sender | Status | Required properties | Fires when |+| --- | --- | --- | --- | --- |+| `schedule_fired` | backend | live | `schedule_id`, `target`, `expert_id`, `graph_id`, `graph_exec_id` or `session_id` | A schedule produces work. |+| `trigger_fired` | backend | live | `webhook_id`, `graph_id`, `graph_exec_id`, `expert_id`, `preset_id`, `target` | A webhook produces a run. |+| `briefing_generated` | backend | live | `run_count`, `decision_count`, `has_content` | A morning briefing is composed (or found empty). |+| `briefing_delivered` | backend | live | `briefing_id` | It is posted to the user's thread. |+| `briefing_opened` | browser | live | — | The briefing renders on home. Not the plan's `briefing_opened_in_chat`, which is opening it in the chat thread. |+| `briefing_outcome_clicked` | browser | live | `status` | An outcome row in the briefing is clicked. |+| `expert_fired` | backend | live | `expert_id` | An expert is fired. |++Return visits are `$pageview`; account-level retention is computed in+`retention_task_weekly` and `user_lifecycle`, not sent as events.++## Experiments++| Event | Sender | Status | Required properties | Fires when |+| --- | --- | --- | --- | --- |+| `experiment_exposed` | browser | live | `experiment_key`, `variant`, `provider: launchdarkly`, `$feature/<flag>` | A LaunchDarkly-bucketed arm is shown to a signed-in user (`useLaunchDarklyExperiment`). |+| `$feature_flag_called` | browser (posthog-js) | live | set by PostHog | A PostHog flag is read (`useExperiment`). |+| `feature_flag_mismatch` | browser | rename → `feature_flag_mismatched` | `flag`, `launchdarkly` (`value`, `resolved`), `posthog` (`value`, `resolved`) | Ops signal: with both flag vendors configured, LaunchDarkly and PostHog resolved a flag to different values (`useDualFlag`). Not a user action; keep out of funnels. The analytics plan has no name for it; SECRT-2722 gives it the `object_action` past-tense form before it reaches production. |++Arms are also stored in the database (`analytics.experiment_assignment`),+so an experiment can be read in PostHog and Looker alike.++## Differences from the analytics plan++Left for follow-up changes, so this list and the plan can be compared line by+line:++- **Events the plan folds into others keep their names until that change.**+ The brain-dump events (`brain_dump_*`, `transcription_failed`,+ `later_dump_completed`) and the wizard's `intro_path` and+ `hire_step_continued` become properties of `onboarding_step_viewed` /+ `_completed` / `_skipped` / `_back`. Spoken turns (`voice_turn_sent`)+ become `chat_message_sent` with `input_mode: voice`.+- **Property names.** The plan's envelope says `chat_session_id` and `via`;+ chat events still send `session_id` and run events `trigger`.+- **`subscription_changed` covers upgrades only.** The plan also counts+ cancellations and downgrades there; `subscription_cancellation_scheduled`+ and `subscription_ended` stay separate events.+- **`chat_outcome` has two outcome types.** Only `agent_run_success` and+ `schedule_created` have an emitter. `agent_created`, `trigger_setup`,+ `artifact_created`, `file_produced` and `answer_only` do not.+- **Plan events we do not send yet** (`signup_started`, `chat_session_started`,+ `chat_response_completed`, `chat_blocked`, `screen_viewed`,+ `screen_engaged`, `milestone_reached`, the builder, library and email+ families, ...) come with the plan's phases, not with this list.+- **Events the plan has no name for keep their own**, e.g.+ `integration_connected`, `schedule_created`, `hire_started`,+ `billing_portal_opened`, `tour_*`, `tab_intro_*`, `voice_*` and+ `credential_*`. `briefing_opened` is the briefing shown on home, a+ different action from the plan's `briefing_opened_in_chat`.++## Events not in the constants modules++These are sent by PostHog or a third party, not by our code, and are listed+so nobody adds a duplicate:++- `$pageleave`, `$autocapture`, `$identify` and `$feature_flag_called`:+ posthog-js (`capture_pageleave` and `autocapture` are on).+- `$ai_generation`: OpenRouter's PostHog integration, for copilot title+ generation (`posthogDistinctId` in `copilot/service.py`).