Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(notebooks): capture server-side notebook created event (#68342)

Sinan Kucukkoseler929f1221f7cb
diff --git a/frontend/src/models/notebooksModel.ts b/frontend/src/models/notebooksModel.ts
index 27cb73828bc7..8a494a16e7e5 100644
--- a/frontend/src/models/notebooksModel.ts
+++ b/frontend/src/models/notebooksModel.ts
@@ -126,7 +126,11 @@ export const notebooksModel = kea<notebooksModelType>([
onCreate?.(logic)
})
- posthog.capture(`notebook created`, {
+ // Client-scoped name on purpose: the server-side `notebook created` event
+ // (emitted for every creation path) is the source of truth for counts. This
+ // one keeps the browser/session context for UI-funnel analysis without
+ // double-counting UI creations.
+ posthog.capture(`notebook created (client)`, {
short_id: notebook.short_id,
is_markdown: useMarkdownNotebook,
})
diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
index 20a0f63bad78..49145f7f22eb 100644
--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
@@ -87,6 +87,51 @@
'''
# ---
# name: TestNotebooks.test_updates_notebook.10
+ '''
+ SELECT "posthog_user"."id",
+ "posthog_user"."password",
+ "posthog_user"."last_login",
+ "posthog_user"."first_name",
+ "posthog_user"."last_name",
+ "posthog_user"."is_staff",
+ "posthog_user"."date_joined",
+ "posthog_user"."uuid",
+ "posthog_user"."current_organization_id",
+ "posthog_user"."current_team_id",
+ "posthog_user"."email",
+ "posthog_user"."pending_email",
+ "posthog_user"."distinct_id",
+ "posthog_user"."is_email_verified",
+ "posthog_user"."credentials_reviewed_at",
+ "posthog_user"."requested_2fa_reset_at",
+ "posthog_user"."has_seen_product_intro_for",
+ "posthog_user"."strapi_id",
+ "posthog_user"."is_active",
+ "posthog_user"."role_at_organization",
+ "posthog_user"."theme_mode",
+ "posthog_user"."partial_notification_settings",
+ "posthog_user"."anonymize_data",
+ "posthog_user"."allow_impersonation",
+ "posthog_user"."toolbar_mode",
+ "posthog_user"."hedgehog_config",
+ "posthog_user"."allow_sidebar_suggestions",
+ "posthog_user"."shortcut_position",
+ "posthog_user"."passkeys_enabled_for_2fa",
+ "posthog_user"."hide_mcp_hints",
+ "posthog_user"."onboarding_skipped_at",
+ "posthog_user"."onboarding_skipped_reason",
+ "posthog_user"."onboarding_skipped_organization_id",
+ "posthog_user"."onboarding_delegated_to_invite_id",
+ "posthog_user"."onboarding_delegated_to_organization_id",
+ "posthog_user"."onboarding_delegation_accepted_at",
+ "posthog_user"."events_column_config",
+ "posthog_user"."email_opt_in"
+ FROM "posthog_user"
+ WHERE ("posthog_user"."is_active"
+ AND "posthog_user"."id" = 99999)
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.11
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -128,7 +173,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.11
+# name: TestNotebooks.test_updates_notebook.12
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -266,7 +311,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.12
+# name: TestNotebooks.test_updates_notebook.13
'''
SELECT "posthog_project"."updated_at",
"posthog_project"."id",
@@ -280,7 +325,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.13
+# name: TestNotebooks.test_updates_notebook.14
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -331,7 +376,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.14
+# name: TestNotebooks.test_updates_notebook.15
'''
SELECT "ee_accesscontrol"."id",
"ee_accesscontrol"."team_id",
@@ -355,7 +400,7 @@
AND "ee_accesscontrol"."team_id" = 99999))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.15
+# name: TestNotebooks.test_updates_notebook.16
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -404,7 +449,7 @@
WHERE "posthog_organizationmembership"."user_id" = 99999
'''
# ---
-# name: TestNotebooks.test_updates_notebook.16
+# name: TestNotebooks.test_updates_notebook.17
'''
SELECT "posthog_notebook"."id",
"posthog_notebook"."short_id",
@@ -612,7 +657,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.17
+# name: TestNotebooks.test_updates_notebook.18
'''
SELECT "posthog_notebook"."id",
"posthog_notebook"."short_id",
@@ -635,7 +680,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.18
+# name: TestNotebooks.test_updates_notebook.19
'''
SELECT "posthog_notebook"."id",
"posthog_notebook"."short_id",
@@ -660,7 +705,7 @@
UPDATE
'''
# ---
-# name: TestNotebooks.test_updates_notebook.19
+# name: TestNotebooks.test_updates_notebook.2
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -756,13 +801,49 @@
"posthog_team"."experiment_recalculation_time",
"posthog_team"."default_experiment_confidence_level",
"posthog_team"."default_experiment_stats_method",
- "posthog_team"."business_model"
+ "posthog_team"."business_model",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
FROM "posthog_team"
+ INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")
WHERE "posthog_team"."id" = 99999
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.2
+# name: TestNotebooks.test_updates_notebook.20
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -858,49 +939,13 @@
"posthog_team"."experiment_recalculation_time",
"posthog_team"."default_experiment_confidence_level",
"posthog_team"."default_experiment_stats_method",
- "posthog_team"."business_model",
- "posthog_organization"."id",
- "posthog_organization"."name",
- "posthog_organization"."slug",
- "posthog_organization"."logo_media_id",
- "posthog_organization"."created_at",
- "posthog_organization"."updated_at",
- "posthog_organization"."is_active",
- "posthog_organization"."is_not_active_reason",
- "posthog_organization"."session_cookie_age",
- "posthog_organization"."is_member_join_email_enabled",
- "posthog_organization"."is_ai_data_processing_approved",
- "posthog_organization"."is_ai_training_opted_in",
- "posthog_organization"."is_ai_training_locked",
- "posthog_organization"."is_ai_training_cta_shown",
- "posthog_organization"."enforce_2fa",
- "posthog_organization"."members_can_invite",
- "posthog_organization"."members_can_create_projects",
- "posthog_organization"."members_can_use_personal_api_keys",
- "posthog_organization"."allow_publicly_shared_resources",
- "posthog_organization"."default_role_id",
- "posthog_organization"."plugins_access_level",
- "posthog_organization"."for_internal_metrics",
- "posthog_organization"."default_experiment_stats_method",
- "posthog_organization"."default_anonymize_ips",
- "posthog_organization"."is_hipaa",
- "posthog_organization"."is_pending_deletion",
- "posthog_organization"."customer_id",
- "posthog_organization"."available_product_features",
- "posthog_organization"."usage",
- "posthog_organization"."never_drop_data",
- "posthog_organization"."customer_trust_scores",
- "posthog_organization"."setup_section_2_completed",
- "posthog_organization"."personalization",
- "posthog_organization"."domain_whitelist",
- "posthog_organization"."is_platform"
+ "posthog_team"."business_model"
FROM "posthog_team"
- INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")
WHERE "posthog_team"."id" = 99999
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.20
+# name: TestNotebooks.test_updates_notebook.21
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -925,7 +970,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.21
+# name: TestNotebooks.test_updates_notebook.22
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -948,7 +993,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.22
+# name: TestNotebooks.test_updates_notebook.23
'''
SELECT "posthog_sharingconfiguration"."id",
"posthog_sharingconfiguration"."team_id",
@@ -967,7 +1012,7 @@
WHERE "posthog_sharingconfiguration"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.23
+# name: TestNotebooks.test_updates_notebook.24
'''
SELECT "posthog_sharingconfiguration"."id",
"posthog_sharingconfiguration"."team_id",
@@ -986,7 +1031,7 @@
WHERE "posthog_sharingconfiguration"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.24
+# name: TestNotebooks.test_updates_notebook.25
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
@@ -996,7 +1041,7 @@
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.25
+# name: TestNotebooks.test_updates_notebook.26
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."notebook_id",
@@ -1006,7 +1051,7 @@
WHERE "posthog_resourcenotebook"."notebook_id" = '00000000000000000000000000000000'::uuid
'''
# ---
-# name: TestNotebooks.test_updates_notebook.26
+# name: TestNotebooks.test_updates_notebook.27
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -1052,7 +1097,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.27
+# name: TestNotebooks.test_updates_notebook.28
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."account_id"
@@ -1063,7 +1108,7 @@
LIMIT 1
'''
# ---
-# name: TestNotebooks.test_updates_notebook.28
+# name: TestNotebooks.test_updates_notebook.29
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -1108,7 +1153,21 @@
AND "posthog_user"."id" = 99999)
'''
# ---
-# name: TestNotebooks.test_updates_notebook.29
+# name: TestNotebooks.test_updates_notebook.3
+ '''
+ SELECT "posthog_project"."updated_at",
+ "posthog_project"."id",
+ "posthog_project"."organization_id",
+ "posthog_project"."name",
+ "posthog_project"."created_at",
+ "posthog_project"."product_description",
+ "posthog_project"."is_pending_deletion"
+ FROM "posthog_project"
+ WHERE "posthog_project"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.30
'''
SELECT "posthog_organization"."id",
"posthog_organization"."name",
@@ -1150,21 +1209,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.3
- '''
- SELECT "posthog_project"."updated_at",
- "posthog_project"."id",
- "posthog_project"."organization_id",
- "posthog_project"."name",
- "posthog_project"."created_at",
- "posthog_project"."product_description",
- "posthog_project"."is_pending_deletion"
- FROM "posthog_project"
- WHERE "posthog_project"."id" = 99999
- LIMIT 21
- '''
-# ---
-# name: TestNotebooks.test_updates_notebook.30
+# name: TestNotebooks.test_updates_notebook.31
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1302,7 +1347,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.31
+# name: TestNotebooks.test_updates_notebook.32
'''
SELECT "posthog_project"."updated_at",
"posthog_project"."id",
@@ -1316,7 +1361,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.32
+# name: TestNotebooks.test_updates_notebook.33
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -1367,7 +1412,7 @@
LIMIT 21
'''
# ---
-# name: TestNotebooks.test_updates_notebook.33
+# name: TestNotebooks.test_updates_notebook.34
'''
SELECT "ee_accesscontrol"."id",
"ee_accesscontrol"."team_id",
@@ -1391,7 +1436,7 @@
AND "ee_accesscontrol"."team_id" = 99999))
'''
# ---
-# name: TestNotebooks.test_updates_notebook.34
+# name: TestNotebooks.test_updates_notebook.35
'''
SELECT "posthog_organizationmembership"."id",
"posthog_organizationmembership"."organization_id",
@@ -1440,7 +1485,7 @@
WHERE "posthog_organizationmembership"."user_id" = 99999
'''
# ---
-# name: TestNotebooks.test_updates_notebook.35
+# name: TestNotebooks.test_updates_notebook.36
'''
SELECT COUNT(*) AS "__count"
FROM "posthog_activitylog"
@@ -1448,7 +1493,7 @@
AND "posthog_activitylog"."team_id" = 99999)
'''
# ---
-# name: TestNotebooks.test_updates_notebook.36
+# name: TestNotebooks.test_updates_notebook.37
'''
SELECT "posthog_activitylog"."id",
"posthog_activitylog"."team_id",
@@ -1660,6 +1705,108 @@
'''
# ---
# name: TestNotebooks.test_updates_notebook.8
+ '''
+ SELECT "posthog_team"."id",
+ "posthog_team"."uuid",
+ "posthog_team"."organization_id",
+ "posthog_team"."parent_team_id",
+ "posthog_team"."project_id",
+ "posthog_team"."api_token",
+ "posthog_team"."app_urls",
+ "posthog_team"."name",
+ "posthog_team"."slack_incoming_webhook",
+ "posthog_team"."created_at",
+ "posthog_team"."updated_at",
+ "posthog_team"."anonymize_ips",
+ "posthog_team"."completed_snippet_onboarding",
+ "posthog_team"."has_completed_onboarding_for",
+ "posthog_team"."onboarding_tasks",
+ "posthog_team"."ingested_event",
+ "posthog_team"."ingested_production_event",
+ "posthog_team"."ingested_production_event_last_checked_at",
+ "posthog_team"."person_processing_opt_out",
+ "posthog_team"."secret_api_token",
+ "posthog_team"."secret_api_token_backup",
+ "posthog_team"."session_recording_opt_in",
+ "posthog_team"."session_recording_sample_rate",
+ "posthog_team"."session_recording_minimum_duration_milliseconds",
+ "posthog_team"."session_recording_linked_flag",
+ "posthog_team"."session_recording_network_payload_capture_config",
+ "posthog_team"."session_recording_masking_config",
+ "posthog_team"."session_recording_url_trigger_config",
+ "posthog_team"."session_recording_url_blocklist_config",
+ "posthog_team"."session_recording_event_trigger_config",
+ "posthog_team"."session_recording_trigger_match_type_config",
+ "posthog_team"."session_recording_trigger_groups",
+ "posthog_team"."session_replay_config",
+ "posthog_team"."session_recording_retention_period",
+ "posthog_team"."event_retention_months",
+ "posthog_team"."conversations_enabled",
+ "posthog_team"."conversations_settings",
+ "posthog_team"."proactive_tasks_enabled",
+ "posthog_team"."survey_config",
+ "posthog_team"."surveys_opt_in",
+ "posthog_team"."product_tours_opt_in",
+ "posthog_team"."capture_console_log_opt_in",
+ "posthog_team"."capture_performance_opt_in",
+ "posthog_team"."capture_dead_clicks",
+ "posthog_team"."autocapture_opt_out",
+ "posthog_team"."autocapture_web_vitals_opt_in",
+ "posthog_team"."autocapture_web_vitals_allowed_metrics",
+ "posthog_team"."autocapture_exceptions_opt_in",
+ "posthog_team"."autocapture_exceptions_errors_to_ignore",
+ "posthog_team"."logs_settings",
+ "posthog_team"."llm_gateway_enabled_at",
+ "posthog_team"."llm_gateway_revoked_at",
+ "posthog_team"."llm_gateway_overspend_allowance_usd",
+ "posthog_team"."heatmaps_opt_in",
+ "posthog_team"."receive_org_level_activity_logs",
+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
+ "posthog_team"."web_analytics_pre_aggregated_tables_version",
+ "posthog_team"."flags_persistence_default",
+ "posthog_team"."feature_flag_confirmation_enabled",
+ "posthog_team"."feature_flag_confirmation_message",
+ "posthog_team"."default_evaluation_environments_enabled",
+ "posthog_team"."require_evaluation_environment_tags",
+ "posthog_team"."default_evaluation_contexts_enabled",
+ "posthog_team"."require_evaluation_contexts",
+ "posthog_team"."session_recording_version",
+ "posthog_team"."signup_token",
+ "posthog_team"."is_demo",
+ "posthog_team"."access_control",
+ "posthog_team"."week_start_day",
+ "posthog_team"."inject_web_apps",
+ "posthog_team"."test_account_filters",
+ "posthog_team"."test_account_filters_default_checked",
+ "posthog_team"."path_cleaning_filters",
+ "posthog_team"."timezone",
+ "posthog_team"."data_attributes",
+ "posthog_team"."person_display_name_properties",
+ "posthog_team"."live_events_columns",
+ "posthog_team"."recording_domains",
+ "posthog_team"."human_friendly_comparison_periods",
+ "posthog_team"."cookieless_server_hash_mode",
+ "posthog_team"."primary_dashboard_id",
+ "posthog_team"."default_data_theme",
+ "posthog_team"."extra_settings",
+ "posthog_team"."modifiers",
+ "posthog_team"."correlation_config",
+ "posthog_team"."session_recording_retention_period_days",
+ "posthog_team"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "posthog_team"."drop_events_older_than",
+ "posthog_team"."base_currency",
+ "posthog_team"."experiment_recalculation_time",
+ "posthog_team"."default_experiment_confidence_level",
+ "posthog_team"."default_experiment_stats_method",
+ "posthog_team"."business_model"
+ FROM "posthog_team"
+ WHERE "posthog_team"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestNotebooks.test_updates_notebook.9
'''
SELECT "posthog_resourcenotebook"."id",
"posthog_resourcenotebook"."account_id"
@@ -1670,48 +1817,3 @@
LIMIT 1
'''
# ---
-# name: TestNotebooks.test_updates_notebook.9
- '''
- SELECT "posthog_user"."id",
- "posthog_user"."password",
- "posthog_user"."last_login",
- "posthog_user"."first_name",
- "posthog_user"."last_name",
- "posthog_user"."is_staff",
- "posthog_user"."date_joined",
- "posthog_user"."uuid",
- "posthog_user"."current_organization_id",
- "posthog_user"."current_team_id",
- "posthog_user"."email",
- "posthog_user"."pending_email",
- "posthog_user"."distinct_id",
- "posthog_user"."is_email_verified",
- "posthog_user"."credentials_reviewed_at",
- "posthog_user"."requested_2fa_reset_at",
- "posthog_user"."has_seen_product_intro_for",
- "posthog_user"."strapi_id",
- "posthog_user"."is_active",
- "posthog_user"."role_at_organization",
- "posthog_user"."theme_mode",
- "posthog_user"."partial_notification_settings",
- "posthog_user"."anonymize_data",
- "posthog_user"."allow_impersonation",
- "posthog_user"."toolbar_mode",
- "posthog_user"."hedgehog_config",
- "posthog_user"."allow_sidebar_suggestions",
- "posthog_user"."shortcut_position",
- "posthog_user"."passkeys_enabled_for_2fa",
- "posthog_user"."hide_mcp_hints",
- "posthog_user"."onboarding_skipped_at",
- "posthog_user"."onboarding_skipped_reason",
- "posthog_user"."onboarding_skipped_organization_id",
- "posthog_user"."onboarding_delegated_to_invite_id",
- "posthog_user"."onboarding_delegated_to_organization_id",
- "posthog_user"."onboarding_delegation_accepted_at",
- "posthog_user"."events_column_config",
- "posthog_user"."email_opt_in"
- FROM "posthog_user"
- WHERE ("posthog_user"."is_active"
- AND "posthog_user"."id" = 99999)
- '''
-# ---
diff --git a/posthog/temporal/ai/anomaly_investigation/workflow.py b/posthog/temporal/ai/anomaly_investigation/workflow.py
index 5208eac543e7..7c5d1d4f6deb 100644
--- a/posthog/temporal/ai/anomaly_investigation/workflow.py
+++ b/posthog/temporal/ai/anomaly_investigation/workflow.py
@@ -153,6 +153,7 @@ async def investigate_anomaly_activity(inputs: AnomalyInvestigationWorkflowInput
text_content=result.report.summary,
created_by_id=user.id,
last_modified_by_id=user.id,
+ creation_source=notebooks.NotebookCreationSource.TEMPORAL_AGENT,
)
summary_for_list = _truncate_summary(result.report.summary)
diff --git a/products/notebooks/backend/analytics.py b/products/notebooks/backend/analytics.py
new file mode 100644
index 000000000000..9a3eabbe8999
--- /dev/null
+++ b/products/notebooks/backend/analytics.py
@@ -0,0 +1,88 @@
+"""Analytics capture for notebook lifecycle events.
+
+Single owner of the server-side `notebook created` event so every creation path — REST/MCP
+(via the serializer) and the AI/background paths (via the facade create functions) — emits one
+uniform event with an attributed `creation_source`.
+"""
+
+from typing import TYPE_CHECKING, Any
+
+from posthog.event_usage import report_user_action, report_user_or_team_action
+from posthog.models import Team, User
+
+if TYPE_CHECKING:
+ from rest_framework.request import Request
+
+NOTEBOOK_CREATED_EVENT = "notebook created"
+
+
+class NotebookCreationSource:
+ UI = "ui"
+ MCP = "mcp"
+ MAX_AI = "max_ai"
+ TEMPORAL_AGENT = "temporal_agent"
+ GROUP = "group"
+ # Neutral default for the generic facade create; real callers pass their own source.
+ SERVER = "server"
+ # The account-notebook path (max_account_notebook) is deferred; its source lands with it.
+
+
+def notebook_node_count(content: Any) -> int | None:
+ """Top-level node count of a ProseMirror `{type: doc, content: [...]}` document."""
+ if isinstance(content, dict):
+ nodes = content.get("content")
+ return len(nodes) if isinstance(nodes, list) else 0
+ return None
+
+
+def _created_properties(short_id: str, creation_source: str, extra: dict[str, Any]) -> dict[str, Any]:
+ props: dict[str, Any] = {"short_id": short_id, "creation_source": creation_source}
+ props.update({key: value for key, value in extra.items() if value is not None})
+ return props
+
+
+def capture_notebook_created(
+ *,
+ short_id: str,
+ creation_source: str,
+ team_id: int,
+ user: User | None = None,
+ created_by_id: int | None = None,
+ request: "Request | None" = None,
+ mcp_consumer: str | None = None,
+ mcp_oauth_client: str | None = None,
+ api_key_type: str | None = None,
+ conversation_id: str | None = None,
+ topic: str | None = None,
+ visibility: str | None = None,
+ node_count: int | None = None,
+) -> None:
+ """Emit `notebook created`. Pass ``request`` + ``user`` from the DRF serializer (REST/MCP);
+ the facade create functions pass ``team_id`` + ``created_by_id`` for the request-less
+ AI/background paths, where attribution falls back to the team when there is no user
+ (e.g. group auto-create)."""
+ props = _created_properties(
+ short_id,
+ creation_source,
+ {
+ "mcp_consumer": mcp_consumer,
+ "mcp_oauth_client": mcp_oauth_client,
+ "api_key_type": api_key_type,
+ "conversation_id": conversation_id,
+ "topic": topic,
+ "visibility": visibility,
+ "node_count": node_count,
+ },
+ )
+
+ if request is not None and user is not None:
+ report_user_action(user, NOTEBOOK_CREATED_EVENT, props, request=request)
+ return
+
+ resolved_user = user
+ if resolved_user is None and created_by_id is not None:
+ resolved_user = User.objects.filter(pk=created_by_id).first()
+ team = Team.objects.filter(pk=team_id).first()
+ if team is None:
+ return
+ report_user_or_team_action(NOTEBOOK_CREATED_EVENT, props, user=resolved_user, team=team)
diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.py
index 2a75355a6623..29c83b38fc87 100644
--- a/products/notebooks/backend/facade/api.py
+++ b/products/notebooks/backend/facade/api.py
@@ -16,7 +16,13 @@ from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from uuid import UUID
+from asgiref.sync import sync_to_async
+
from .. import logic, markdown_migration
+
+# NotebookCreationSource is re-exported here so cross-product callers can label their create
+# source (e.g. notebooks.NotebookCreationSource.TEMPORAL_AGENT) without importing internals.
+from ..analytics import NotebookCreationSource, capture_notebook_created, notebook_node_count
from ..models import Notebook, ResourceNotebook
from . import contracts
@@ -129,6 +135,9 @@ async def aupsert_notebook(
title: str,
content: dict[str, Any],
text_content: str | None = None,
+ creation_source: str = NotebookCreationSource.MAX_AI,
+ conversation_id: str | None = None,
+ topic: str | None = None,
) -> tuple[contracts.NotebookData, bool]:
notebook, created = await logic.aupsert_notebook(
team_id,
@@ -139,6 +148,17 @@ async def aupsert_notebook(
content=content,
text_content=text_content,
)
+ if created:
+ await sync_to_async(capture_notebook_created)(
+ short_id=notebook.short_id,
+ creation_source=creation_source,
+ team_id=team_id,
+ created_by_id=created_by_id,
+ conversation_id=conversation_id,
+ topic=topic,
+ visibility=notebook.visibility,
+ node_count=notebook_node_count(notebook.content),
+ )
return _to_notebook_data(notebook), created
@@ -151,6 +171,7 @@ def create_notebook(
created_by_id: int | None = None,
last_modified_by_id: int | None = None,
visibility: str = Notebook.Visibility.DEFAULT,
+ creation_source: str = NotebookCreationSource.SERVER,
) -> contracts.NotebookData:
notebook = logic.create_notebook(
team_id,
@@ -161,6 +182,14 @@ def create_notebook(
last_modified_by_id=last_modified_by_id,
visibility=visibility,
)
+ capture_notebook_created(
+ short_id=notebook.short_id,
+ creation_source=creation_source,
+ team_id=team_id,
+ created_by_id=created_by_id,
+ visibility=notebook.visibility,
+ node_count=notebook_node_count(notebook.content),
+ )
return _to_notebook_data(notebook)
@@ -193,7 +222,15 @@ def group_has_notebook(group_id: int) -> bool:
def create_group_notebook(team_id: int, group_id: int, *, title: str | None, content: Any) -> contracts.NotebookData:
- return _to_notebook_data(logic.create_group_notebook(team_id, group_id, title=title, content=content))
+ notebook = logic.create_group_notebook(team_id, group_id, title=title, content=content)
+ capture_notebook_created(
+ short_id=notebook.short_id,
+ creation_source=NotebookCreationSource.GROUP,
+ team_id=team_id,
+ visibility=notebook.visibility,
+ node_count=notebook_node_count(notebook.content),
+ )
+ return _to_notebook_data(notebook)
def create_account_notebook(
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 9efcb54db9b5..ab988ced012b 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -34,6 +34,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.streaming import sse_streaming_response
from posthog.api.utils import action
+from posthog.auth import SessionAuthentication
from posthog.exceptions import Conflict
from posthog.helpers.impersonation import is_impersonated
from posthog.models import User
@@ -48,6 +49,7 @@ from posthog.utils import relative_date_parse
from products.notebooks.backend import collab_stream, markdown_collab, presence
from products.notebooks.backend.activity_logging import log_notebook_activity
+from products.notebooks.backend.analytics import NotebookCreationSource, capture_notebook_created, notebook_node_count
from products.notebooks.backend.collab import submit_steps
from products.notebooks.backend.kernel_runtime import build_notebook_sandbox_config, get_kernel_runtime
from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun
@@ -89,6 +91,24 @@ def depluralize(string: str | None) -> str | None:
return string
+def classify_request_source(request: Request) -> tuple[str, dict[str, str | None]]:
+ """Classify a notebook request as a browser action (``ui``) vs a programmatic client (``mcp``/API).
+
+ Session-cookie requests are the browser; anything else (personal API key, OAuth app) is a
+ programmatic client. The PostHog MCP server forwards the client identity so PostHog Code can be
+ told apart from a customer's own MCP client: ``mcp_consumer`` is ``posthog-code``/``posthog-cli``
+ for first-party PostHog Code, and ``mcp_oauth_client`` is the OAuth app name (e.g. Claude) for
+ third-party clients. Shared by the create and read events."""
+ authenticator = getattr(request, "successful_authenticator", None)
+ if authenticator is None or isinstance(authenticator, SessionAuthentication):
+ return NotebookCreationSource.UI, {}
+ return NotebookCreationSource.MCP, {
+ "api_key_type": type(authenticator).__name__,
+ "mcp_consumer": request.META.get("HTTP_X_POSTHOG_MCP_CONSUMER"),
+ "mcp_oauth_client": request.META.get("HTTP_X_POSTHOG_MCP_OAUTH_CLIENT_NAME"),
+ }
+
+
_NOTEBOOK_FIELD_HELP_TEXTS = {
"id": {"help_text": "UUID of the notebook."},
"short_id": {"help_text": "Short alphanumeric identifier used in URLs and API lookups."},
@@ -222,6 +242,20 @@ class NotebookSerializer(NotebookMinimalSerializer):
was_impersonated=is_impersonated(request),
)
+ creation_source, source_props = classify_request_source(request)
+ capture_notebook_created(
+ short_id=notebook.short_id,
+ creation_source=creation_source,
+ team_id=team.id,
+ user=request.user,
+ request=request,
+ visibility=notebook.visibility,
+ node_count=notebook_node_count(notebook.content),
+ mcp_consumer=source_props.get("mcp_consumer"),
+ mcp_oauth_client=source_props.get("mcp_oauth_client"),
+ api_key_type=source_props.get("api_key_type"),
+ )
+
return notebook
def update(self, instance: Notebook, validated_data: dict, **kwargs) -> Notebook:
diff --git a/products/notebooks/backend/test/test_analytics.py b/products/notebooks/backend/test/test_analytics.py
new file mode 100644
index 000000000000..338644ec2c93
--- /dev/null
+++ b/products/notebooks/backend/test/test_analytics.py
@@ -0,0 +1,94 @@
+from typing import cast
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework.request import Request
+
+from posthog.auth import SessionAuthentication
+
+from products.notebooks.backend.analytics import (
+ NOTEBOOK_CREATED_EVENT,
+ NotebookCreationSource,
+ capture_notebook_created,
+ notebook_node_count,
+)
+from products.notebooks.backend.presentation.views.notebook import classify_request_source
+
+
+class _FakeKeyAuth:
+ pass
+
+
+class _FakeRequest:
+ def __init__(self, authenticator, mcp_consumer=None, mcp_oauth_client=None):
+ self.successful_authenticator = authenticator
+ self.META = {}
+ if mcp_consumer is not None:
+ self.META["HTTP_X_POSTHOG_MCP_CONSUMER"] = mcp_consumer
+ if mcp_oauth_client is not None:
+ self.META["HTTP_X_POSTHOG_MCP_OAUTH_CLIENT_NAME"] = mcp_oauth_client
+
+
+def _fake_request(authenticator, mcp_consumer=None, mcp_oauth_client=None) -> Request:
+ return cast(Request, _FakeRequest(authenticator, mcp_consumer, mcp_oauth_client))
+
+
+class TestNotebookAnalytics(BaseTest):
+ @parameterized.expand(
+ [
+ ("two_nodes", {"type": "doc", "content": [{}, {}]}, 2),
+ ("empty_doc", {"type": "doc", "content": []}, 0),
+ ("no_content_key", {"type": "doc"}, 0),
+ ("none", None, None),
+ ("not_a_dict", "just text", None),
+ ]
+ )
+ def test_notebook_node_count(self, _name, content, expected):
+ self.assertEqual(notebook_node_count(content), expected)
+
+ def test_classify_request_source_session_is_ui(self):
+ source, extra = classify_request_source(_fake_request(SessionAuthentication()))
+ self.assertEqual(source, NotebookCreationSource.UI)
+ self.assertEqual(extra, {})
+
+ def test_classify_request_source_api_key_captures_mcp_client_identity(self):
+ # The MCP server forwards mcp_consumer (posthog-code -> PostHog Code) and mcp_oauth_client
+ # (the OAuth app, e.g. Claude), which is how Q4 (PostHog Code) is split from Q5.
+ source, extra = classify_request_source(
+ _fake_request(_FakeKeyAuth(), mcp_consumer="posthog-code", mcp_oauth_client="Claude")
+ )
+ self.assertEqual(source, NotebookCreationSource.MCP)
+ self.assertEqual(
+ extra,
+ {"api_key_type": "_FakeKeyAuth", "mcp_consumer": "posthog-code", "mcp_oauth_client": "Claude"},
+ )
+
+ def test_classify_request_source_no_authenticator_defaults_to_ui(self):
+ source, extra = classify_request_source(_fake_request(None))
+ self.assertEqual(source, (NotebookCreationSource.UI))
+ self.assertEqual(extra, {})
+
+ @patch("products.notebooks.backend.analytics.report_user_action")
+ def test_request_path_captures_via_report_user_action_and_drops_none_props(self, mock_report):
+ capture_notebook_created(
+ short_id="abc123",
+ creation_source=NotebookCreationSource.UI,
+ team_id=self.team.id,
+ user=self.user,
+ request=_fake_request(SessionAuthentication()),
+ visibility="private",
+ node_count=3,
+ mcp_consumer=None,
+ api_key_type=None,
+ )
+ self.assertEqual(mock_report.call_count, 1)
+ args, kwargs = mock_report.call_args
+ self.assertEqual(args[0], self.user)
+ self.assertEqual(args[1], NOTEBOOK_CREATED_EVENT)
+ # None-valued optional props are dropped so they don't clutter the event.
+ self.assertEqual(
+ args[2],
+ {"short_id": "abc123", "creation_source": "ui", "visibility": "private", "node_count": 3},
+ )
diff --git a/products/notebooks/backend/test/test_facade.py b/products/notebooks/backend/test/test_facade.py
index 258677b42a73..c98417d39e59 100644
--- a/products/notebooks/backend/test/test_facade.py
+++ b/products/notebooks/backend/test/test_facade.py
@@ -1,11 +1,13 @@
import pytest
from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.apps import apps
from posthog.rbac.user_access_control import UserAccessControl
from products.notebooks.backend import logic
+from products.notebooks.backend.analytics import NotebookCreationSource
from products.notebooks.backend.facade import api, content
from products.notebooks.backend.models import Notebook, ResourceNotebook
@@ -71,12 +73,15 @@ class TestNotebooksFacade(BaseTest):
self.assertEqual(len(summary.recent), 1)
self.assertEqual(summary.recent[0].short_id, newer.short_id)
- def test_create_group_notebook_links_internal_notebook(self):
+ @patch("products.notebooks.backend.facade.api.capture_notebook_created")
+ def test_create_group_notebook_links_internal_notebook(self, mock_capture):
data = api.create_group_notebook(self.team.id, group_id=42, title="Notes", content=self._doc())
self.assertEqual(data.visibility, Notebook.Visibility.INTERNAL)
self.assertTrue(api.group_has_notebook(42))
self.assertEqual(api.get_group_notebook_short_id(42), data.short_id)
self.assertFalse(api.group_has_notebook(43))
+ mock_capture.assert_called_once()
+ self.assertEqual(mock_capture.call_args.kwargs["creation_source"], NotebookCreationSource.GROUP)
def test_create_account_notebook_and_list_notes(self):
account = _create_account(self.team)
@@ -141,7 +146,8 @@ class TestNotebooksFacadeAsync(BaseTest):
self.assertEqual(data.short_id, notebook.short_id)
@pytest.mark.asyncio
- async def test_aupsert_creates_then_overwrites_and_bumps_version(self):
+ @patch("products.notebooks.backend.facade.api.capture_notebook_created")
+ async def test_aupsert_creates_then_overwrites_and_bumps_version(self, mock_capture):
data, created = await api.aupsert_notebook(
self.team.id,
"abc123",
@@ -152,6 +158,9 @@ class TestNotebooksFacadeAsync(BaseTest):
)
self.assertTrue(created)
self.assertEqual(data.version, 0)
+ # Emits `notebook created` once, on the create, labelled max_ai.
+ mock_capture.assert_called_once()
+ self.assertEqual(mock_capture.call_args.kwargs["creation_source"], NotebookCreationSource.MAX_AI)
data2, created2 = await api.aupsert_notebook(
self.team.id,
@@ -165,6 +174,8 @@ class TestNotebooksFacadeAsync(BaseTest):
self.assertEqual(data2.id, data.id)
self.assertEqual(data2.title, "second")
self.assertEqual(data2.version, 1)
+ # The overwrite is an update, not a create — no second event (guards double-counting).
+ mock_capture.assert_called_once()
@pytest.mark.asyncio
async def test_aupdate_notebook_content_bumps_version(self):
diff --git a/pyproject.toml b/pyproject.toml
index 9048c3daa41a..00bf048cc63f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -571,6 +571,7 @@ ignore_imports = [
# directly. Thin it to parse -> facade -> serialize and delete each entry.
# backend:contract-check stays off until this list is empty.
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.activity_logging",
+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.analytics",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.collab",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.collab_stream",
"products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.kernel_runtime",