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(onboarding): offer role-tailored weekly AI reports as an experiment (#76755)

Joe Martinee8c9033129c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 12c9f18fbb13..75f862bf7d4f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7702,6 +7702,22 @@ snapshots:
hash: v1.k794b7964.aaff710f4f8a004ff7bc73a2709377bd3ac83bccafec478086396c0beae1e832.jqsB3nXBYy8WbHSVAPz-o8Vu46etxe4uDx3zXbtlf-U
scenes-other-onboarding-legacy-product-selection--base--light:
hash: v1.k794b7964.d5a6e4d5e44b84e7a1b0a9eb095fb62a08eea227968860911c9e23757eb99d33.mrMEqKjXZgfMivqJdaamdN2nJVc-I_8Sccv6XXQylg8
+ scenes-other-onboarding-legacy-weekly-reports--engineering-report--dark:
+ hash: v1.k794b7964.5000ffcd0d6aabaac809d9a7635d4d3412ca0e3b4badccc48c31b5745fb3cdb0.fbrer1o3cGzKNcw4qqczs-F9_vacS5pDBHt8J__BIQM
+ scenes-other-onboarding-legacy-weekly-reports--engineering-report--light:
+ hash: v1.k794b7964.1d033ccaadfb5f96bc956c8534b019a32506f6980c8e692dfa165eb5cc7f043f.0yObLHtn7WRQJ1LPi0kS6D1Q2ZmFl1M7xZgzMWpoR4s
+ scenes-other-onboarding-legacy-weekly-reports--generic-report-without-role--dark:
+ hash: v1.k794b7964.f2de67ec965bc3d5b2196b70d73059af776f86c5c914ee032342e61582431ab6._wpybB79QCwmZCODvVgRkOBYptEI8khDRqffCCTRwtk
+ scenes-other-onboarding-legacy-weekly-reports--generic-report-without-role--light:
+ hash: v1.k794b7964.704912a40bd58c35f1f7aaf6ee48839df5d4a1b701a78f7e52b21fe3708c04dd.S-cqR_RG8f_M8MhhhjfM2qr9qH5PeciS8LgUcvdMW68
+ scenes-other-onboarding-legacy-weekly-reports--leadership-report--dark:
+ hash: v1.k794b7964.b4ff1a961b6b197d885a86847ab9284de9a6c9830f0a2e258cc7dedc27798657.sqaP5G7VHsoPm1rAHPAfAKF3_NUzFbDe8hYSdqCCsts
+ scenes-other-onboarding-legacy-weekly-reports--leadership-report--light:
+ hash: v1.k794b7964.a9a113d0f2e990d64744da3270aa89214fb12721e51c3959cf79a22aaee0f906.FZSSbp9g0joCSMGugwtARVHG6bS5n_Mo6a4bhVLovPk
+ scenes-other-onboarding-legacy-weekly-reports--marketing-report--dark:
+ hash: v1.k794b7964.000a1ac36e3d4a36f800e888ef2b21721eee0122e9a10f20c7da21214e2375fa.2eiPdwSJ15FNVd183gSPvbFq-ywaCwnSkIS9Q_L3Mrw
+ scenes-other-onboarding-legacy-weekly-reports--marketing-report--light:
+ hash: v1.k794b7964.0e2a8e49d86bf85201eab7a83383dc110b5bfa4e375cdd115d31aceec6851ace.mbj1QmZoty5ZryyE-hjsIp-VqV-X05nlVS0S_5Z3UP8
scenes-other-onboarding-shared-installation-progress--all-states--dark:
hash: v1.k794b7964.701a00d919735a8e926d138dbf37d3f999ffe860a38366ffad441d2ea9007dc3.At1SVb1kbXJdi1oQ6SNRG2h9FaXngLNhQiIfeDfBvag
scenes-other-onboarding-shared-installation-progress--all-states--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 90fee12109af..554adde9ca6b 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -401,6 +401,7 @@ export const FEATURE_FLAGS = {
NEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analytics
NOTEBOOK_PYTHON: 'notebook-python', // owner: #team-data-tools
NOTEBOOK_SHARING: 'notebook-sharing', // owner: @reecejones #team-platform-features
+ ONBOARDING_AI_REPORTS: 'onboarding-role-notifications', // owner: @joethreepwood #team-growth multivariate=control,test — offers a role-tailored weekly AI report step at the end of onboarding; code additionally gates on AI subscriptions being available, so keep the flag at 100% rollout (key predates the AI-reports naming; it's bound to the live experiment)
ONBOARDING_DATA_WAREHOUSE_VALUE_PROP: 'onboarding-data-warehouse-value-prop', // owner: @fercgomes #team-growth multivariate=control,table,query
ONBOARDING_FLOW_VARIANT: 'onboarding-flow-variant', // owner: @fercgomes #team-growth multivariate=control,self-driving — selects the whole onboarding experience; control is the existing flow (the historical `legacy` value is an alias of control)
ONBOARDING_HIDE_BREADCRUMBS: 'onboarding-hide-breadcrumbs', // owner: @fercgomes #team-growth, multivariate=true, hides breadcrumbs during onboarding to reduce distractions
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 9d79274ac396..0d0ff4c3d39f 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1501,6 +1501,24 @@ export interface eventUsageLogicActions {
isAIFirst: boolean
itemCount: number
}
+ reportOnboardingAIReportRemoved: (
+ role: string | null,
+ reportKey: string,
+ experimentArm: string | null
+ ) => {
+ experimentArm: string | null
+ reportKey: string
+ role: string | null
+ }
+ reportOnboardingAIReportSubscribed: (
+ role: string | null,
+ reportKey: string,
+ experimentArm: string | null
+ ) => {
+ experimentArm: string | null
+ reportKey: string
+ role: string | null
+ }
reportOnboardingCompleted: (productKey: string) => {
productKey: string
}
@@ -2616,6 +2634,16 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
stepKey,
productKey,
}),
+ reportOnboardingAIReportSubscribed: (role: string | null, reportKey: string, experimentArm: string | null) => ({
+ role,
+ reportKey,
+ experimentArm,
+ }),
+ reportOnboardingAIReportRemoved: (role: string | null, reportKey: string, experimentArm: string | null) => ({
+ role,
+ reportKey,
+ experimentArm,
+ }),
reportOnboardingCompleted: (productKey: string) => ({ productKey }),
reportOnboardingUseCaseSelected: (useCase: string, recommendedProducts: readonly string[]) => ({
useCase,
@@ -3985,6 +4013,22 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
...LEGACY_ONBOARDING_EVENT_PROPS,
})
},
+ reportOnboardingAIReportSubscribed: ({ role, reportKey, experimentArm }) => {
+ posthog.capture('onboarding ai report subscribed', {
+ role,
+ report_key: reportKey,
+ experiment_arm: experimentArm,
+ ...LEGACY_ONBOARDING_EVENT_PROPS,
+ })
+ },
+ reportOnboardingAIReportRemoved: ({ role, reportKey, experimentArm }) => {
+ posthog.capture('onboarding ai report removed', {
+ role,
+ report_key: reportKey,
+ experiment_arm: experimentArm,
+ ...LEGACY_ONBOARDING_EVENT_PROPS,
+ })
+ },
reportOnboardingCompleted: ({ productKey }) => {
posthog.capture('onboarding completed', {
product_key: productKey,
diff --git a/frontend/src/scenes/onboarding/legacy/notifications/OnboardingAIReports.stories.tsx b/frontend/src/scenes/onboarding/legacy/notifications/OnboardingAIReports.stories.tsx
new file mode 100644
index 000000000000..9876596881f7
--- /dev/null
+++ b/frontend/src/scenes/onboarding/legacy/notifications/OnboardingAIReports.stories.tsx
@@ -0,0 +1,100 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { Meta, StoryObj } from '@storybook/react'
+import { useActions, useMountedLogic } from 'kea'
+import { router } from 'kea-router'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { App } from 'scenes/App'
+import { availableOnboardingProducts } from 'scenes/onboarding/shared/utils'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator, useStorybookMocks } from '~/mocks/browser'
+import { billingJson } from '~/mocks/fixtures/_billing'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey, UserRole } from '~/types'
+
+import { onboardingLogic } from '../onboardingLogic'
+
+const meta: Meta = {
+ title: 'Scenes-Other/Onboarding/Legacy/Weekly reports',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2023-05-25',
+ featureFlags: {
+ [FEATURE_FLAGS.ONBOARDING_AI_REPORTS]: 'test',
+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true,
+ },
+ testOptions: { waitForSelector: '[data-attr="onboarding-ai-report-subscribe"]' },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/_preflight': {
+ ...preflightJson,
+ cloud: true,
+ realm: 'cloud',
+ },
+ '/api/billing/': {
+ ...billingJson,
+ },
+ },
+ post: {
+ '/api/projects/:team_id/subscriptions/': () => [201, { id: 123 }],
+ },
+ patch: {
+ '/api/environments/:team_id/add_product_intent/': {},
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+function StepForRole({ role }: { role: UserRole | null }): JSX.Element {
+ useMountedLogic(onboardingLogic)
+ const { setProduct } = useActions(onboardingLogic)
+
+ useStorybookMocks({
+ get: {
+ '/api/users/@me/': () => [200, { ...MOCK_DEFAULT_USER, role_at_organization: role }],
+ },
+ })
+
+ useDelayedOnMountEffect(() => {
+ setProduct(availableOnboardingProducts[ProductKey.PRODUCT_ANALYTICS])
+ router.actions.push(
+ urls.onboarding({
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ // Namespaced id so currentFlowStep resolves via exact match — the step is
+ // appended by a flag-gated flow rebuild (same race as the billing step).
+ step: `${OnboardingStepKey.AI_REPORTS}:${ProductKey.PRODUCT_ANALYTICS}`,
+ })
+ )
+ })
+
+ return <App />
+}
+
+// One story per report family, not per role: founder/engineering share a report, and the
+// remaining roles differ only in card copy drawn from aiReportDefinitions.
+
+export const EngineeringReport: Story = {
+ render: () => <StepForRole role={UserRole.Engineering} />,
+}
+
+export const MarketingReport: Story = {
+ render: () => <StepForRole role={UserRole.Marketing} />,
+}
+
+export const LeadershipReport: Story = {
+ render: () => <StepForRole role={UserRole.Leadership} />,
+}
+
+export const GenericReportWithoutRole: Story = {
+ render: () => <StepForRole role={null} />,
+}
diff --git a/frontend/src/scenes/onboarding/legacy/notifications/OnboardingAIReports.tsx b/frontend/src/scenes/onboarding/legacy/notifications/OnboardingAIReports.tsx
new file mode 100644
index 000000000000..1f6dbafeaec4
--- /dev/null
+++ b/frontend/src/scenes/onboarding/legacy/notifications/OnboardingAIReports.tsx
@@ -0,0 +1,81 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheckCircle } from '@posthog/icons'
+import { LemonButton, LemonCard, LemonCollapse } from '@posthog/lemon-ui'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { OnboardingStepKey } from '~/types'
+
+import { OnboardingStepComponentType } from '../onboardingLogic'
+import { OnboardingStep } from '../OnboardingStep'
+import { onboardingAIReportsLogic } from './onboardingAIReportsLogic'
+
+export const OnboardingAIReports: OnboardingStepComponentType = () => {
+ const { user } = useValues(userLogic)
+ const { report, createdSubscriptionId, createdSubscriptionIdLoading } = useValues(onboardingAIReportsLogic)
+ const { createReportSubscription, removeReportSubscription } = useActions(onboardingAIReportsLogic)
+
+ const subscribed = createdSubscriptionId !== null
+
+ return (
+ <OnboardingStep
+ title="Get a weekly report"
+ subtitle="We can email you a written summary every week, based on what you told us you do. Reports start once your data is flowing, so it's fine to set this up before you've sent any events."
+ stepKey={OnboardingStepKey.AI_REPORTS}
+ continueText={subscribed ? undefined : 'Skip for now'}
+ >
+ <LemonCard hoverEffect={false} className="flex flex-col gap-2 p-4">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <h3 className="m-0 text-base font-semibold">{report.headline}</h3>
+ <p className="m-0 text-sm text-muted">{report.lead}</p>
+ </div>
+ {!subscribed && (
+ <LemonButton
+ type="primary"
+ onClick={() => createReportSubscription()}
+ loading={createdSubscriptionIdLoading}
+ data-attr="onboarding-ai-report-subscribe"
+ >
+ Email me this weekly
+ </LemonButton>
+ )}
+ </div>
+
+ {subscribed ? (
+ <div className="flex items-center justify-between gap-2 rounded border bg-surface-primary p-2">
+ <div className="flex items-center gap-2">
+ <IconCheckCircle className="text-success shrink-0 text-lg" />
+ <span className="text-sm">
+ Done. Your first report arrives next week at {user?.email}. You can change or cancel it
+ anytime in Notifications &amp; alerts.
+ </span>
+ </div>
+ <LemonButton
+ size="small"
+ onClick={() => removeReportSubscription()}
+ loading={createdSubscriptionIdLoading}
+ data-attr="onboarding-ai-report-undo"
+ >
+ Undo
+ </LemonButton>
+ </div>
+ ) : (
+ <LemonCollapse
+ size="small"
+ panels={[
+ {
+ key: 'prompt',
+ header: 'What it covers',
+ content: <p className="m-0 text-sm">{report.prompt}</p>,
+ },
+ ]}
+ />
+ )}
+ </LemonCard>
+ </OnboardingStep>
+ )
+}
+
+OnboardingAIReports.stepKey = OnboardingStepKey.AI_REPORTS
diff --git a/frontend/src/scenes/onboarding/legacy/notifications/aiReportDefinitions.test.ts b/frontend/src/scenes/onboarding/legacy/notifications/aiReportDefinitions.test.ts
new file mode 100644
index 000000000000..184781c215f3
--- /dev/null
+++ b/frontend/src/scenes/onboarding/legacy/notifications/aiReportDefinitions.test.ts
@@ -0,0 +1,32 @@
+import { UserRole } from '~/types'
+
+import { AI_REPORTS_BY_ROLE, reportForRole } from './aiReportDefinitions'
+
+describe('aiReportDefinitions', () => {
+ // Catches a new UserRole enum value silently losing its mapping at runtime (the Record type
+ // enforces it at compile time, but `reportForRole` takes an untyped string from the user object).
+ it.each([...Object.values(UserRole), null, undefined, 'not-a-role'])(
+ 'returns a complete definition for role %s',
+ (role) => {
+ const report = reportForRole(role)
+ expect(report.key).toBeTruthy()
+ expect(report.title).toBeTruthy()
+ expect(report.headline).toBeTruthy()
+ expect(report.prompt.length).toBeGreaterThan(100)
+ }
+ )
+
+ it('gives founders and engineers the same revenue and growth report', () => {
+ expect(AI_REPORTS_BY_ROLE[UserRole.Founder]).toBe(AI_REPORTS_BY_ROLE[UserRole.Engineering])
+ })
+
+ // "Self-driving" is an existing onboarding variant and brand term; this copy must never be
+ // mistaken for it (explicit request from the feature discussion).
+ it('never uses the term self-driving in any user-facing string', () => {
+ for (const report of Object.values(AI_REPORTS_BY_ROLE)) {
+ for (const text of [report.headline, report.lead, report.title, report.prompt]) {
+ expect(text.toLowerCase()).not.toContain('self-driving')
+ }
+ }
+ })
+})
diff --git a/frontend/src/scenes/onboarding/legacy/notifications/aiReportDefinitions.ts b/frontend/src/scenes/onboarding/legacy/notifications/aiReportDefinitions.ts
new file mode 100644
index 000000000000..37c19d009f2e
--- /dev/null
+++ b/frontend/src/scenes/onboarding/legacy/notifications/aiReportDefinitions.ts
@@ -0,0 +1,156 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+import { UserRole } from '~/types'
+
+export interface AIReportDefinition {
+ key: string
+ headline: string
+ lead: string
+ title: string
+ /**
+ * Handed to the AI-subscription planner, which writes and runs its own HogQL. Names concrete
+ * event properties so it queries the right ones rather than guessing, and tells it to say so
+ * plainly when the project doesn't have the data yet (most subscribers set this up before
+ * they've instrumented anything).
+ */
+ prompt: string
+}
+
+// Founders and engineers get the same report: per the role mapping decision, both care most
+// about whether the business is growing, not about a role-specific slice.
+const REVENUE_SIGNUPS: AIReportDefinition = {
+ key: 'revenue-signups',
+ headline: 'Revenue and sign-up growth',
+ lead: 'New sign-ups and revenue movement this week, compared with last week.',
+ title: 'Weekly revenue and sign-up growth',
+ prompt: [
+ 'Summarize business growth for the last 7 days compared with the previous 7 days.',
+ 'Count new sign-ups: persons whose first event ever was in the last 7 days, plus any',
+ 'explicit sign-up events if the project has them (event names containing "sign" or "register").',
+ 'If the project has revenue or payment events (names containing "purchase", "payment",',
+ '"subscription" or "checkout"), report their volume and unique payers week over week.',
+ 'If none exist, say so plainly and skip revenue rather than inventing numbers.',
+ 'Close with the single most important growth change and a plausible reason for it.',
+ ].join(' '),
+}
+
+const GENERIC_USAGE_DIGEST: AIReportDefinition = {
+ key: 'usage-digest',
+ headline: 'How your product was used',
+ lead: 'Active users, top pages and top events for the week, with what moved.',
+ title: 'Weekly product usage digest',
+ prompt: [
+ 'Summarize product usage for the last 7 days using this project’s events.',
+ 'Report weekly active users (unique persons), total events, and $pageview volume,',
+ 'each compared with the previous 7 days.',
+ 'List the top 10 pages by $pageview count using the $pathname property,',
+ 'and the top custom events (exclude event names starting with $).',
+ 'Call out anything that moved more than 20% week over week,',
+ 'and finish with the single most notable change and a plausible reason for it.',
+ 'If the project has little or no data yet, say so plainly instead of inventing numbers.',
+ ].join(' '),
+}
+
+export const AI_REPORTS_BY_ROLE: Record<UserRole, AIReportDefinition> = {
+ [UserRole.Leadership]: {
+ key: 'aarrr-funnel',
+ headline: 'Your funnel at a glance',
+ lead: 'Acquisition, activation, retention, referral and revenue for the week.',
+ title: 'Weekly funnel summary',
+ prompt: [
+ 'Produce an AARRR summary for the last 7 days, each stage compared with the previous 7 days.',
+ 'Acquisition: unique persons with a $pageview, and the top $referring_domain values.',
+ 'Activation: persons whose first event ever was this week who then performed any custom',
+ 'event (names not starting with $).',
+ 'Retention: share of persons active in the previous 7 days who returned this week.',
+ 'Referral: events or UTM parameters (utm_source on $pageview) suggesting shared or referred traffic.',
+ 'Revenue: volume of purchase, payment or subscription events if the project has them.',
+ 'For any stage where the project has no data yet, say so plainly rather than inventing numbers.',
+ 'End with the weakest stage this week and one suggestion to investigate it.',
+ ].join(' '),
+ },
+ [UserRole.Marketing]: {
+ key: 'traffic-pages',
+ headline: 'What people visited and how traffic changed',
+ lead: 'Most popular pages this week and shifts in where visitors come from.',
+ title: 'Weekly pages and traffic changes',
+ prompt: [
+ 'Report on web traffic for the last 7 days compared with the previous 7 days using $pageview events.',
+ 'List the top 10 pages by $pathname with unique visitors and week-over-week change.',
+ 'Break down traffic sources using $referring_domain and utm_source, and call out any source',
+ 'that moved more than 20%.',
+ 'Note changes in bounce-like behavior: persons with exactly one $pageview in a session.',
+ 'If the project has little or no traffic data yet, say so plainly instead of inventing numbers.',
+ 'Finish with the most notable traffic shift and a plausible cause.',
+ ].join(' '),
+ },
+ [UserRole.Sales]: {
+ key: 'new-signups',
+ headline: 'Who signed up this week',
+ lead: 'New sign-ups this week, where they came from, and how the pace is trending.',
+ title: 'Weekly new sign-ups',
+ prompt: [
+ 'Report new sign-ups for the last 7 days compared with the previous 7 days.',
+ 'Count persons whose first event ever was in the last 7 days, plus explicit sign-up events',
+ 'if the project has them (event names containing "sign" or "register").',
+ 'Show sign-ups per day to reveal the trend, and the top acquisition sources for new persons',
+ 'using $referring_domain and utm_source on their first $pageview.',
+ 'If the project has no sign-up data yet, say so plainly instead of inventing numbers.',
+ 'Close with whether the sign-up pace is accelerating or slowing and by how much.',
+ ].join(' '),
+ },
+ [UserRole.Founder]: REVENUE_SIGNUPS,
+ [UserRole.Engineering]: REVENUE_SIGNUPS,
+ [UserRole.Product]: {
+ key: 'feature-retention',
+ headline: 'Feature usage and retention',
+ lead: 'Which features got used this week and whether users are coming back.',
+ title: 'Weekly feature usage and retention',
+ prompt: [
+ 'Summarize feature usage for the last 7 days compared with the previous 7 days.',
+ 'Rank the top 10 custom events (names not starting with $) by unique persons, with change.',
+ 'Report retention: share of persons active in the previous 7 days who returned this week,',
+ 'and the same for persons whose first event ever was in the previous week.',
+ 'Call out any feature whose unique users moved more than 20% week over week.',
+ 'If the project has little or no data yet, say so plainly instead of inventing numbers.',
+ 'End with the feature most worth attention this week and why.',
+ ].join(' '),
+ },
+ [UserRole.Data]: {
+ key: 'events-volume',
+ headline: 'Top events and volume changes',
+ lead: 'The biggest event streams and what moved week over week.',
+ title: 'Weekly event volume changes',
+ prompt: [
+ 'Compare event volume for the last 7 days against the previous 7 days for every event name',
+ 'in this project, excluding internal events starting with $ (but keep $pageview).',
+ 'Rank the top 10 events by volume, and separately the five fastest-growing and five',
+ 'fastest-declining by relative change, ignoring events under 100 occurrences in both windows.',
+ 'For each big mover, note whether unique persons moved with volume, since volume rising on',
+ 'flat users means heavier use rather than more reach.',
+ 'If the project has little or no data yet, say so plainly instead of inventing numbers.',
+ 'Close with anything that looks like an instrumentation problem, such as an event that',
+ 'vanished or spiked.',
+ ].join(' '),
+ },
+ [UserRole.Student]: GENERIC_USAGE_DIGEST,
+ [UserRole.Other]: GENERIC_USAGE_DIGEST,
+}
+
+/** An unset or unrecognized role gets the generic digest, so the step never dead-ends on role. */
+export function reportForRole(role: string | null | undefined): AIReportDefinition {
+ return AI_REPORTS_BY_ROLE[role as UserRole] ?? GENERIC_USAGE_DIGEST
+}
+
+export type AIReportsExperimentArm = 'control' | 'test'
+
+/**
+ * The user's experiment arm, or null when they are not enrolled: an unset/boolean flag value (not
+ * rolled out, targeting excludes them, flags not loaded yet) must NOT be collapsed into `control`,
+ * or never-enrolled users pollute the control cohort and bias the readout toward "no effect".
+ */
+export function resolveAIReportsArm(featureFlags: FeatureFlagsSet): AIReportsExperimentArm | null {
+ const value = featureFlags[FEATURE_FLAGS.ONBOARDING_AI_REPORTS]
+ return value === 'test' || value === 'control' ? value : null
+}
diff --git a/frontend/src/scenes/onboarding/legacy/notifications/onboardingAIReportsLogic.test.ts b/frontend/src/scenes/onboarding/legacy/notifications/onboardingAIReportsLogic.test.ts
new file mode 100644
index 000000000000..ef06daf3a2cc
--- /dev/null
+++ b/frontend/src/scenes/onboarding/legacy/notifications/onboardingAIReportsLogic.test.ts
@@ -0,0 +1,91 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import { initKeaTests } from '~/test/init'
+
+import { subscriptionsCreate, subscriptionsPartialUpdate } from 'products/subscriptions/frontend/generated/api'
+
+import { onboardingAIReportsLogic } from './onboardingAIReportsLogic'
+
+jest.mock('products/subscriptions/frontend/generated/api', () => ({
+ subscriptionsCreate: jest.fn(),
+ subscriptionsPartialUpdate: jest.fn(),
+}))
+
+const mockedCreate = jest.mocked(subscriptionsCreate)
+const mockedPartialUpdate = jest.mocked(subscriptionsPartialUpdate)
+
+describe('onboardingAIReportsLogic', () => {
+ let logic: ReturnType<typeof onboardingAIReportsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ mockedCreate.mockReset().mockResolvedValue({ id: 123 } as any)
+ mockedPartialUpdate.mockReset().mockResolvedValue({ id: 123 } as any)
+ jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')
+
+ logic = onboardingAIReportsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ // Catches payload drift the backend would reject at runtime (dropping `interval`), and
+ // `send_test_now` flipping back to its server default of true, which would immediately
+ // mail an AI report over a project that likely has no events yet.
+ it('creates a weekly email subscription with a start date about a week out', async () => {
+ await expectLogic(logic, () => logic.actions.createReportSubscription()).toFinishAllListeners()
+
+ expect(mockedCreate).toHaveBeenCalledTimes(1)
+ const [, payload] = mockedCreate.mock.calls[0]
+ expect(payload).toMatchObject({
+ target_type: 'email',
+ frequency: 'weekly',
+ interval: 1,
+ send_test_now: false,
+ })
+ expect(payload.prompt).toBeTruthy()
+ expect(payload.title).toBeTruthy()
+ const daysOut = dayjs(payload.start_date).diff(dayjs(), 'day', true)
+ expect(daysOut).toBeGreaterThan(6)
+ expect(daysOut).toBeLessThan(8)
+ expect(logic.values.createdSubscriptionId).toBe(123)
+ })
+
+ it('does not create a second subscription while one exists', async () => {
+ await expectLogic(logic, () => logic.actions.createReportSubscription()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.createReportSubscription()).toFinishAllListeners()
+
+ expect(mockedCreate).toHaveBeenCalledTimes(1)
+ })
+
+ // The error leg of the double-submit guard: a failed create must leave the button usable
+ // (loading reset, no phantom created state) and tell the user where to recover.
+ it('resets state and shows a toast when creation fails', async () => {
+ mockedCreate.mockRejectedValue(new Error('quota'))
+
+ await expectLogic(logic, () => logic.actions.createReportSubscription()).toFinishAllListeners()
+
+ expect(logic.values.createdSubscriptionId).toBeNull()
+ expect(logic.values.createdSubscriptionIdLoading).toBe(false)
+ expect(lemonToast.error).toHaveBeenCalled()
+ })
+
+ it('undo soft-deletes the created subscription and clears the created state', async () => {
+ await expectLogic(logic, () => logic.actions.createReportSubscription()).toFinishAllListeners()
+
+ await expectLogic(logic, () => logic.actions.removeReportSubscription()).toFinishAllListeners()
+
+ expect(mockedPartialUpdate).toHaveBeenCalledTimes(1)
+ const [, id, payload] = mockedPartialUpdate.mock.calls[0]
+ expect(id).toBe(123)
+ expect(payload).toEqual({ deleted: true })
+ expect(logic.values.createdSubscriptionId).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/onboarding/legacy/notifications/onboardingAIReportsLogic.ts b/frontend/src/scenes/onboarding/legacy/notifications/onboardingAIReportsLogic.ts
new file mode 100644
index 000000000000..4963d9883f07
--- /dev/null
+++ b/frontend/src/scenes/onboarding/legacy/notifications/onboardingAIReportsLogic.ts
@@ -0,0 +1,168 @@
+import { MakeLogicType, connect, kea, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { projectLogic } from 'scenes/projectLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { UserType } from '~/types'
+
+import { subscriptionsCreate, subscriptionsPartialUpdate } from 'products/subscriptions/frontend/generated/api'
+
+import { AIReportDefinition, reportForRole, resolveAIReportsArm } from './aiReportDefinitions'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface onboardingAIReportsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentProjectId: number | null // projectLogic
+ user: UserType | null // userLogic
+ createdSubscriptionId: number | null
+ createdSubscriptionIdLoading: boolean
+ report: AIReportDefinition
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface onboardingAIReportsLogicActions {
+ reportOnboardingAIReportRemoved: (
+ role: string | null,
+ reportKey: string,
+ experimentArm: string | null
+ ) => {
+ experimentArm: string | null
+ reportKey: string
+ role: string | null
+ } // eventUsageLogic
+ reportOnboardingAIReportSubscribed: (
+ role: string | null,
+ reportKey: string,
+ experimentArm: string | null
+ ) => {
+ experimentArm: string | null
+ reportKey: string
+ role: string | null
+ } // eventUsageLogic
+ createReportSubscription: () => any
+ createReportSubscriptionFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ createReportSubscriptionSuccess: (
+ createdSubscriptionId: number | null,
+ payload?: any
+ ) => {
+ createdSubscriptionId: number | null
+ payload?: any
+ }
+ removeReportSubscription: () => any
+ removeReportSubscriptionFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ removeReportSubscriptionSuccess: (
+ createdSubscriptionId: number | null,
+ payload?: any
+ ) => {
+ createdSubscriptionId: number | null
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface onboardingAIReportsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ report: (user: UserType | null) => AIReportDefinition
+ }
+}
+
+export type onboardingAIReportsLogicType = MakeLogicType<
+ onboardingAIReportsLogicValues,
+ onboardingAIReportsLogicActions,
+ Record<string, any>,
+ onboardingAIReportsLogicMeta
+>
+
+export const onboardingAIReportsLogic = kea<onboardingAIReportsLogicType>([
+ path(['scenes', 'onboarding', 'legacy', 'notifications', 'onboardingAIReportsLogic']),
+ connect(() => ({
+ values: [userLogic, ['user'], projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],
+ actions: [eventUsageLogic, ['reportOnboardingAIReportSubscribed', 'reportOnboardingAIReportRemoved']],
+ })),
+ selectors({
+ report: [
+ (s) => [s.user],
+ (user: UserType | null): AIReportDefinition => reportForRole(user?.role_at_organization),
+ ],
+ }),
+ loaders(({ actions, values }) => ({
+ createdSubscriptionId: [
+ null as number | null,
+ {
+ createReportSubscription: async (): Promise<number | null> => {
+ if (values.createdSubscriptionId !== null || !values.currentProjectId) {
+ return values.createdSubscriptionId
+ }
+ const report = values.report
+ try {
+ const created = await subscriptionsCreate(String(values.currentProjectId), {
+ // resource_type derives to 'ai_prompt' server-side from the prompt
+ prompt: report.prompt,
+ title: report.title,
+ target_type: 'email',
+ target_value: values.user?.email ?? '',
+ frequency: 'weekly',
+ interval: 1,
+ // A week out: the user declares interest now, the first report fires
+ // once there's been time to instrument and collect data.
+ start_date: dayjs().add(7, 'day').hour(9).minute(0).second(0).toISOString(),
+ // Defaults to true on create, which would deliver an AI report over a
+ // project that likely has no events yet.
+ send_test_now: false,
+ })
+ actions.reportOnboardingAIReportSubscribed(
+ values.user?.role_at_organization ?? null,
+ report.key,
+ resolveAIReportsArm(values.featureFlags)
+ )
+ return created.id
+ } catch {
+ lemonToast.error(
+ 'Could not set up the report. You can add it later from Notifications & alerts.'
+ )
+ return values.createdSubscriptionId
+ }
+ },
+ removeReportSubscription: async (): Promise<number | null> => {
+ const subscriptionId = values.createdSubscriptionId
+ if (subscriptionId === null || !values.currentProjectId) {
+ return values.createdSubscriptionId
+ }
+ try {
+ // Subscriptions have no hard delete; setting `deleted` soft-deletes.
+ await subscriptionsPartialUpdate(String(values.currentProjectId), subscriptionId, {
+ deleted: true,
+ })
+ actions.reportOnboardingAIReportRemoved(
+ values.user?.role_at_organization ?? null,
+ values.report.key,
+ resolveAIReportsArm(values.featureFlags)
+ )
+ return null
+ } catch {
+ lemonToast.error('Could not undo. You can remove the report from Notifications & alerts.')
+ return values.createdSubscriptionId
+ }
+ },
+ },
+ ],
+ })),
+])
diff --git a/frontend/src/scenes/onboarding/legacy/onboardingFlowUtils.ts b/frontend/src/scenes/onboarding/legacy/onboardingFlowUtils.ts
index 848cc64d3807..cdcb2b14d05c 100644
--- a/frontend/src/scenes/onboarding/legacy/onboardingFlowUtils.ts
+++ b/frontend/src/scenes/onboarding/legacy/onboardingFlowUtils.ts
@@ -5,6 +5,8 @@ import { OnboardingStepKey } from '~/types'
const STEP_KEY_TITLE_OVERRIDES: Partial<Record<OnboardingStepKey, string>> = {
[OnboardingStepKey.LINK_DATA]: 'Import data',
+ // The default derivation would read "Ai reports" — wrong casing, and the step is weekly.
+ [OnboardingStepKey.AI_REPORTS]: 'Weekly reports',
}
export const stepKeyToTitle = (stepKey?: OnboardingStepKey): undefined | string => {
diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts
index a439cc219ad0..6c307103d2c5 100644
--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts
+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.test.ts
@@ -1,9 +1,12 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { SetupTaskId } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -716,4 +719,55 @@ describe('onboardingLogic — flow composition', () => {
expect(flowStepKeys()).not.toContain(OnboardingStepKey.LINK_DATA)
})
})
+
+ // Gate regressions here invalidate the experiment: leaking the step to control users breaks the
+ // readout, hiding it from test users ships a dead experiment.
+ describe('AI reports step gating', () => {
+ const setFlags = (variants: Record<string, string | boolean>): void => {
+ featureFlagLogic.findMounted()?.actions.setFeatureFlags(Object.keys(variants), variants)
+ }
+
+ it('includes the step last when AI subscriptions are available and the arm is test', () => {
+ setFlags({
+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true,
+ [FEATURE_FLAGS.ONBOARDING_AI_REPORTS]: 'test',
+ })
+ // The org load is async in the test env; the gate needs is_ai_data_processing_approved.
+ organizationLogic.findMounted()?.actions.loadCurrentOrganizationSuccess(MOCK_DEFAULT_ORGANIZATION)
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+
+ expect(flowIds()[flowIds().length - 1]).toBe('ai_reports:product_analytics')
+ })
+
+ it.each([
+ ['the arm is control', { [FEATURE_FLAGS.ONBOARDING_AI_REPORTS]: 'control' }],
+ ['the experiment flag is unset', {}],
+ [
+ 'AI subscriptions are unavailable',
+ {
+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: false,
+ [FEATURE_FLAGS.ONBOARDING_AI_REPORTS]: 'test',
+ },
+ ],
+ ])('excludes the step when %s', (_label, extraVariants) => {
+ setFlags({ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true, ...extraVariants })
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+
+ expect(flowStepKeys()).not.toContain(OnboardingStepKey.AI_REPORTS)
+ })
+
+ it('excludes the step when the organization has not approved AI data processing', async () => {
+ setFlags({
+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true,
+ [FEATURE_FLAGS.ONBOARDING_AI_REPORTS]: 'test',
+ })
+ organizationLogic.findMounted()?.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: false,
+ })
+ logic.actions.setProductKey(ProductKey.PRODUCT_ANALYTICS)
+
+ expect(flowStepKeys()).not.toContain(OnboardingStepKey.AI_REPORTS)
+ })
+ })
})
diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
index c40dbecf54ab..c8c8173f3fb0 100644
--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
@@ -5,7 +5,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import { type SetupTaskId } from 'lib/components/ProductSetup'
import { globalSetupLogic } from 'lib/components/ProductSetup/globalSetupLogic'
-import { OrganizationMembershipLevel } from 'lib/constants'
+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { isKeyOf } from 'lib/utils/guards'
@@ -80,6 +80,7 @@ export interface onboardingLogicValues {
productKey: ProductKey | null
secondaryProductKeys: ProductKey[]
shouldShowBillingStep: boolean
+ showAIReportsStep: boolean
stepId: string
subscribedDuringOnboarding: boolean
totalOnboardingSteps: number
@@ -178,6 +179,7 @@ export interface onboardingLogicMeta {
__keaTypeGenInternalSelectorTypes: {
onboardingFlowVariant: (featureFlags: FeatureFlagsSet) => string
canInviteTeammates: (currentOrganization: OrganizationType | null, user: UserType | null) => boolean
+ showAIReportsStep: (featureFlags: FeatureFlagsSet, currentOrganization: OrganizationType | null) => boolean
billingProduct: (billing: BillingType | null, productKey: ProductKey | null) => BillingProductV2Type | null
shouldShowBillingStep: (
subscribedDuringOnboarding: boolean,
@@ -196,7 +198,8 @@ export interface onboardingLogicMeta {
isCloudOrDev: boolean | undefined,
subscribedDuringOnboarding: boolean,
canInviteTeammates: boolean,
- featureFlags: FeatureFlagsSet
+ featureFlags: FeatureFlagsSet,
+ showAIReportsStep: boolean
) => OnboardingStepDescriptor[]
onboardingStepKeys: (flow: OnboardingStepDescriptor[]) => OnboardingStepKey[]
currentFlowStep: (flow: OnboardingStepDescriptor[], stepId: string) => OnboardingStepDescriptor | null
@@ -380,6 +383,26 @@ export const onboardingLogic = kea<onboardingLogicType>([
return typeof level === 'number' && level >= OrganizationMembershipLevel.Admin
},
],
+ showAIReportsStep: [
+ (s) => [s.featureFlags, s.currentOrganization],
+ (
+ featureFlags: FeatureFlagsSet,
+ currentOrganization: null | import('~/types').OrganizationType
+ ): boolean => {
+ // Eligibility first: reading the experiment flag records exposure, so users who
+ // could never see the step (AI subscriptions unavailable) must not reach that read.
+ // Both gates hold for new users by default — the ai-subscriptions flag is GA at 100%
+ // and new orgs default is_ai_data_processing_approved=true — so this only excludes
+ // orgs that explicitly opted out of AI data processing.
+ if (
+ !featureFlags[FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT] ||
+ !currentOrganization?.is_ai_data_processing_approved
+ ) {
+ return false
+ }
+ return featureFlags[FEATURE_FLAGS.ONBOARDING_AI_REPORTS] === 'test'
+ },
+ ],
billingProduct: [
(s) => [s.billing, s.productKey],
(billing: null | import('~/types').BillingType, productKey: ProductKey | null) =>
@@ -422,6 +445,7 @@ export const onboardingLogic = kea<onboardingLogicType>([
s.subscribedDuringOnboarding,
s.canInviteTeammates,
s.featureFlags,
+ s.showAIReportsStep,
],
(
primary: ProductKey | null,
@@ -433,7 +457,8 @@ export const onboardingLogic = kea<onboardingLogicType>([
isCloudOrDev: boolean | undefined,
subscribedDuringOnboarding: boolean,
canInviteTeammates: boolean,
- featureFlags: FeatureFlagsSet
+ featureFlags: FeatureFlagsSet,
+ showAIReportsStep: boolean
): OnboardingStepDescriptor[] => {
if (!primary) {
return []
@@ -448,6 +473,7 @@ export const onboardingLogic = kea<onboardingLogicType>([
subscribedDuringOnboarding,
canInviteTeammates,
featureFlags,
+ showAIReportsStep,
}
const productSteps = orderedProducts.flatMap((p, i) => {
const provider = onboardingProviderRegistry[p]
diff --git a/frontend/src/scenes/onboarding/legacy/sharedSteps.tsx b/frontend/src/scenes/onboarding/legacy/sharedSteps.tsx
index a7b2b9dd4448..00c249c96972 100644
--- a/frontend/src/scenes/onboarding/legacy/sharedSteps.tsx
+++ b/frontend/src/scenes/onboarding/legacy/sharedSteps.tsx
@@ -4,6 +4,7 @@ import { OnboardingStepKey } from '~/types'
import { OnboardingUpgradeStep } from './billing/OnboardingUpgradeStep'
import { OnboardingDataWarehouseSourcesStep } from './data-warehouse/OnboardingDataWarehouseSourcesStep'
+import { OnboardingAIReports } from './notifications/OnboardingAIReports'
import { OnboardingInviteTeammates } from './OnboardingInviteTeammates'
import { OnboardingFlowContext, OnboardingStepDescriptor } from './types'
@@ -46,5 +47,17 @@ export function appendSharedTrailingSteps(
})
}
+ // Last on purpose: the lowest-stakes step, so any drop-off it causes shows up in the
+ // completion metric without blocking higher-value steps.
+ if (ctx.showAIReportsStep) {
+ result.push({
+ id: `${OnboardingStepKey.AI_REPORTS}:${ctx.primary}`,
+ productKey: ctx.primary,
+ stepKey: OnboardingStepKey.AI_REPORTS,
+ role: 'primary',
+ render: () => <OnboardingAIReports />,
+ })
+ }
+
return result
}
diff --git a/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts b/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts
index 0ce73b74910c..db01612348fb 100644
--- a/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts
+++ b/frontend/src/scenes/onboarding/legacy/stepProviderRegistry.test.ts
@@ -16,6 +16,7 @@ function context(primary: ProductKey): OnboardingFlowContext {
subscribedDuringOnboarding: false,
canInviteTeammates: true,
featureFlags: {},
+ showAIReportsStep: false,
}
}
diff --git a/frontend/src/scenes/onboarding/legacy/types.ts b/frontend/src/scenes/onboarding/legacy/types.ts
index 94b430eae595..15c9776431de 100644
--- a/frontend/src/scenes/onboarding/legacy/types.ts
+++ b/frontend/src/scenes/onboarding/legacy/types.ts
@@ -70,6 +70,8 @@ export interface OnboardingFlowContext {
* via `featureFlagLogic.findMounted()` (an imperative read never re-fires the flow).
*/
featureFlags: FeatureFlagsSet
+ /** Experiment arm + AI-subscription availability — drives the trailing weekly-report step. */
+ showAIReportsStep: boolean
}
export type StepProvider = (ctx: OnboardingFlowContext) => OnboardingStepDescriptor[]
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 7ea44a5e1614..021e72c08f06 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -7845,6 +7845,7 @@ export enum OnboardingStepKey {
SOURCE_MAPS = 'source_maps',
ALERTS = 'alerts',
PATH_CLEANING = 'path_cleaning',
+ AI_REPORTS = 'ai_reports',
}
// Managed viewset
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
index 962e361d1b29..c9c149f6e446 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
@@ -245,7 +245,9 @@ def send_email_ai_subscription_report(
template_context={
"title": title,
"rendered_html": html,
- "subscription_url": f"{subscription_url}?{utm_tags}",
+ # `delivery` lets the frontend capture `ai_report_clicked` on landing — the
+ # click-through signal for whether delivered reports actually get read.
+ "subscription_url": f"{subscription_url}?{utm_tags}&delivery={delivery_id}",
"unsubscribe_url": unsubscribe_url,
"feedback_positive_url": _build_feedback_url(subscription_url, delivery_id, "positive", "email"),
"feedback_negative_url": _build_feedback_url(subscription_url, delivery_id, "negative", "email"),
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
index 58089e53e0cb..6706ef3dd251 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
@@ -270,8 +270,8 @@ class TestFeedbackFooter:
assert "Was this report useful?" in text
assert f"<{_feedback_url(feedback, 'slack')}|{label}>" in text
- @pytest.mark.parametrize("feedback", ["positive", "negative"])
- def test_email_context_carries_feedback_urls(self, feedback: str) -> None:
+ @staticmethod
+ def _send_email_and_get_context() -> dict:
with (
patch(
"products.exports.backend.temporal.subscriptions.ai_subscription.delivery.EmailMessage"
@@ -293,9 +293,19 @@ class TestFeedbackFooter:
delivery_run_id="run-1",
delivery_id=_DELIVERY_ID,
)
- context = email_message.call_args.kwargs["template_context"]
+ return email_message.call_args.kwargs["template_context"]
+
+ @pytest.mark.parametrize("feedback", ["positive", "negative"])
+ def test_email_context_carries_feedback_urls(self, feedback: str) -> None:
+ context = self._send_email_and_get_context()
assert context[f"feedback_{feedback}_url"] == _feedback_url(feedback, "email")
+ def test_email_cta_carries_delivery_id(self) -> None:
+ # Dropping this param silently kills click attribution: the frontend captures
+ # `ai_report_clicked` from it, the report-engagement signal.
+ context = self._send_email_and_get_context()
+ assert f"&delivery={_DELIVERY_ID}" in context["subscription_url"]
+
class TestPersistAiQueryPlanRaceGuard(APIBaseTest):
@parameterized.expand(
diff --git a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts
index ff1bad2e0979..fe01c32334dc 100644
--- a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts
+++ b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts
@@ -221,6 +221,13 @@ describe('subscriptionSceneLogic', () => {
source,
previous_feedback: null,
})
+ // A feedback landing is also a click-through on the delivered report.
+ expect(captureSpy).toHaveBeenCalledWith('ai_report_clicked', {
+ subscription_id: 2,
+ delivery_id: 'd-123',
+ link: 'feedback',
+ source,
+ })
// The replace must remove the params so a refresh doesn't double-capture.
expect(router.values.searchParams).toEqual({})
expect(captureSpy.mock.calls.filter(([event]) => event === 'ai_report_feedback')).toHaveLength(1)
@@ -229,6 +236,35 @@ describe('subscriptionSceneLogic', () => {
captureSpy.mockRestore()
})
+ it('captures ai_report_clicked from the report CTA delivery param and strips it', async () => {
+ useMocks({
+ get: {
+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/2/`]: () => [200, MOCK_AI_SUBSCRIPTION],
+ },
+ })
+ initKeaTests()
+ const captureSpy = jest.spyOn(posthog, 'capture')
+
+ const logic = subscriptionSceneLogic({ id: '2' })
+ logic.mount()
+ await expectLogic(logic, () => {
+ router.actions.push('/subscriptions/2', { delivery: 'd-123', utm_medium: 'email' })
+ }).toFinishAllListeners()
+
+ expect(captureSpy).toHaveBeenCalledWith('ai_report_clicked', {
+ subscription_id: 2,
+ delivery_id: 'd-123',
+ link: 'manage',
+ source: 'email',
+ })
+ expect(captureSpy.mock.calls.filter(([event]) => event === 'ai_report_feedback')).toHaveLength(0)
+ // Only the delivery param is consumed — utm params stay for posthog-js.
+ expect(router.values.searchParams).toEqual({ utm_medium: 'email' })
+
+ logic.unmount()
+ captureSpy.mockRestore()
+ })
+
it('does not re-capture from a feedback link for an already-recorded delivery', async () => {
useMocks({
get: {
diff --git a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx
index ccd488bc0cf7..78b72258ced8 100644
--- a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx
+++ b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.tsx
@@ -350,22 +350,33 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([
},
})),
urlToAction(({ actions, props, values }) => ({
- // Feedback links in delivered emails/Slack messages land here with these params;
- // capture once, then strip them so a refresh doesn't double-capture.
+ // Links in delivered reports land here with these params; capture once,
+ // then strip them so a refresh doesn't double-capture.
[urls.subscription(':id')]: ({ id }, searchParams) => {
if (id !== props.id) {
return
}
- const { feedback_delivery, feedback, feedback_source, ...restSearchParams } = searchParams
- if (!feedback_delivery || (feedback !== 'positive' && feedback !== 'negative')) {
+ const { feedback_delivery, feedback, feedback_source, delivery, ...restSearchParams } = searchParams
+ const clickedDelivery = feedback_delivery ?? delivery
+ if (!clickedDelivery) {
return
}
- const deliveryId = String(feedback_delivery)
- if (values.deliveryFeedback[deliveryId]) {
- // Persisted state remembers this delivery — don't re-capture from a re-clicked link.
- lemonToast.info('Your feedback for this report was already recorded')
- } else {
- actions.submitDeliveryFeedback(deliveryId, feedback, feedback_source === 'slack' ? 'slack' : 'email')
+ const source = feedback_source === 'slack' ? 'slack' : 'email'
+ // Delivery engagement is a proxy for the report being read — subscribing alone is a weak signal.
+ posthog.capture('ai_report_clicked', {
+ subscription_id: parseInt(props.id, 10),
+ delivery_id: String(clickedDelivery),
+ link: feedback_delivery ? 'feedback' : 'manage',
+ source,
+ })
+ if (feedback_delivery && (feedback === 'positive' || feedback === 'negative')) {
+ const deliveryId = String(feedback_delivery)
+ if (values.deliveryFeedback[deliveryId]) {
+ // Persisted state remembers this delivery — don't re-capture from a re-clicked link.
+ lemonToast.info('Your feedback for this report was already recorded')
+ } else {
+ actions.submitDeliveryFeedback(deliveryId, feedback, source)
+ }
}
router.actions.replace(router.values.location.pathname, restSearchParams, router.values.hashParams)
},