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(mcp-analytics): offer a one-click weekly report on the activity tab (#128666)

Lucas Fariab50f769fa6e4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 846cf6e6a348..e6aaffb8431b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -14210,6 +14210,22 @@ snapshots:
hash: v1.k794b7964.d2a3ac80bc595c41015ae9618ba546c8d809578894bc04d89b172e33e53b3b9f.qbyifaSmWrRx2hMDaS-IaEgheGNnbCHyJB7_EUrs0m0
scenes-app-mcp-analytics--activity--light:
hash: v1.k794b7964.c04cc27b140152a363fb6e789aabcb4b4453d4798ca8fe81c460be84b1284ab5.HzUuZj5kOugUnIrnPIlW9GVDNLORwJWXcs9Le_FM9Ow
+ scenes-app-mcp-analytics--activity-weekly-report-offer--dark:
+ hash: v1.k794b7964.015d41d53e1e8a466f1298fbf4650bf693c8cf4a032881ef88e5ac26f27a4acf.Ap1TLeW53SN53WtDCXBqV7RKiqk8sSYJTWOa_JPqWTE
+ scenes-app-mcp-analytics--activity-weekly-report-offer--light:
+ hash: v1.k794b7964.c2a31ef509fca27a5b553a75be3b0513563a2120bceac7fe0fe5183628d536d0.3bg1-20HvCvb3wYelRjuOtNmaNBbvD8L3vyEC7c2MvM
+ scenes-app-mcp-analytics--activity-weekly-report-offer-failed--dark:
+ hash: v1.k794b7964.9e931d7beb03f0369c1cfcff95292acd3afaeb1a6b7461644188041bf8a53405.q7_gUO4HHpIOGMhJQfNMTIQPKu9QBeOnjKrUMoN5EiM
+ scenes-app-mcp-analytics--activity-weekly-report-offer-failed--light:
+ hash: v1.k794b7964.f87c7f7ed986ceeb889147d6995fbf0b09d7723c7623e2303d367d6ab292a5cc.oQ58OGokdXnymMViiDfdzR8S-K0NJhxesoPLcnmnBkQ
+ scenes-app-mcp-analytics--activity-weekly-report-offer-narrow--dark:
+ hash: v1.k794b7964.58f914c4e06a5dc7a4ff15d2d5d7275422eda120054ad8acd2022ac5c9e52740.MepuCgXQOk1feYUH4PNgdD5tvqoGu1lqAIDEyPA6PLY
+ scenes-app-mcp-analytics--activity-weekly-report-offer-narrow--light:
+ hash: v1.k794b7964.658fa4dc8524b276a16f818adb63791012f6d8868a7bec2e8f8214202b775a9b.axbru-R97XHtl3u-i8RhkXLPQx33wWyk0rADnPhcxu8
+ scenes-app-mcp-analytics--activity-weekly-report-offer-needs-consent--dark:
+ hash: v1.k794b7964.83e185e1e11ee68625fd8d44f54097ff5567e32fb9a2d76f87b92f9aa5e6b4e9.pTLGthRIF3-gSVAuijDIo7ItzG_jTIwGQcikpAWhg08
+ scenes-app-mcp-analytics--activity-weekly-report-offer-needs-consent--light:
+ hash: v1.k794b7964.2daa5ec0a27c8907f8184097aaf3c126c314dde8c3fa8da8f8c37d26ade16848.L5-MBfozdbWrV8D23tlz_FW618NAzE5xiGvHtgFRTe8
scenes-app-mcp-analytics--dashboard--medium--dark:
hash: v1.k794b7964.dd7d59b4a53412ddfa4d33b8752189a73ac5567ba08076d4421081564f7f182b.HVcCDSxVMKWB4PP8x3x9ffFtOwVpQlMSHQky7E23wjY
scenes-app-mcp-analytics--dashboard--medium--light:
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
index bb51f633d3a2..67c83498cda1 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
@@ -1,7 +1,7 @@
-import { MOCK_DEFAULT_USER } from '~/lib/api.mock'
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from '~/lib/api.mock'
import { Meta, StoryObj } from '@storybook/react'
-import { within } from '@testing-library/dom'
+import { waitFor, within } from '@testing-library/dom'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
@@ -9,11 +9,14 @@ import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
+import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'
-import { expect } from 'storybook/test'
+import { expect, userEvent } from 'storybook/test'
import { modelLab } from './aiLabs'
import { labMark } from './brandMarks'
+import { ActivityNextSteps } from './earlyData/ActivityNextSteps'
import { MCPAnalyticsDashboardOverview } from './MCPAnalyticsDashboardOverview'
const KPI_RESULTS = [
@@ -1018,6 +1021,100 @@ export const Activity: Story = {
},
}
+const WEEKLY_REPORT_BUTTON = '[data-attr=mcp-analytics-activity-next-step-weekly-report]'
+
+const WEEKLY_REPORT_OFFER_GET_MOCKS = {
+ '/_preflight': { ...preflightJson, cloud: true, realm: 'cloud' },
+ '/api/projects/:team_id/hog_functions': EMPTY_PAGINATED_RESPONSE,
+ '/api/projects/:team_id/subscriptions': EMPTY_PAGINATED_RESPONSE,
+}
+
+const CREATED_WEEKLY_REPORT = {
+ id: 1,
+ title: 'MCP tool health',
+ enabled: true,
+ target_type: 'email',
+ target_value: MOCK_DEFAULT_USER.email,
+ next_delivery_date: '2026-06-08T09:00:00Z',
+}
+
+const WEEKLY_REPORT_OFFER_PARAMETERS = {
+ featureFlags: [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT],
+ msw: {
+ mocks: {
+ get: WEEKLY_REPORT_OFFER_GET_MOCKS,
+ post: { '/api/projects/:team_id/subscriptions': CREATED_WEEKLY_REPORT },
+ },
+ },
+ testOptions: { waitForSelector: WEEKLY_REPORT_BUTTON },
+}
+
+async function clickWeeklyReportButton(): Promise<void> {
+ // A bare querySelector misses while the card is still loading, and the click would silently do nothing.
+ const button = await waitFor(() => {
+ const element = document.querySelector<HTMLElement>(WEEKLY_REPORT_BUTTON)
+ if (!element) {
+ throw new Error('The weekly report button is not rendered')
+ }
+ return element
+ })
+ await userEvent.click(button)
+}
+
+export const ActivityWeeklyReportOffer: Story = {
+ parameters: { ...WEEKLY_REPORT_OFFER_PARAMETERS, pageUrl: urls.mcpAnalyticsActivity() },
+}
+
+export const ActivityWeeklyReportOfferNarrow: Story = {
+ parameters: { ...WEEKLY_REPORT_OFFER_PARAMETERS, layout: 'padded' },
+ render: () => (
+ <div className="w-[520px]">
+ <ActivityNextSteps />
+ </div>
+ ),
+}
+
+export const ActivityWeeklyReportOfferFailed: Story = {
+ parameters: {
+ ...WEEKLY_REPORT_OFFER_PARAMETERS,
+ pageUrl: urls.mcpAnalyticsActivity(),
+ msw: {
+ mocks: {
+ get: WEEKLY_REPORT_OFFER_GET_MOCKS,
+ post: {
+ '/api/projects/:team_id/subscriptions': (): [number, { detail: string }] => [
+ 400,
+ { detail: 'Your plan is limited to 5 subscriptions.' },
+ ],
+ },
+ },
+ },
+ testOptions: { waitForSelector: '[data-attr=mcp-analytics-activity-next-steps] [role=alert]' },
+ },
+ play: clickWeeklyReportButton,
+}
+
+export const ActivityWeeklyReportOfferNeedsConsent: Story = {
+ parameters: {
+ ...WEEKLY_REPORT_OFFER_PARAMETERS,
+ pageUrl: urls.mcpAnalyticsActivity(),
+ msw: {
+ mocks: {
+ get: {
+ ...WEEKLY_REPORT_OFFER_GET_MOCKS,
+ '/api/organizations/@current/': {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: false,
+ },
+ },
+ post: { '/api/projects/:team_id/subscriptions': CREATED_WEEKLY_REPORT },
+ },
+ },
+ testOptions: { waitForSelector: '[data-attr=ai-consent-approve]' },
+ },
+ play: clickWeeklyReportButton,
+}
+
export const Sessions: Story = {
parameters: {
pageUrl: urls.mcpAnalyticsSessions(),
diff --git a/products/mcp_analytics/frontend/earlyData/ActivityNextSteps.tsx b/products/mcp_analytics/frontend/earlyData/ActivityNextSteps.tsx
index f8012f4efc46..2c7cc3a88f87 100644
--- a/products/mcp_analytics/frontend/earlyData/ActivityNextSteps.tsx
+++ b/products/mcp_analytics/frontend/earlyData/ActivityNextSteps.tsx
@@ -9,6 +9,7 @@ import { CodeSnippet } from 'lib/components/CodeSnippet/CodeSnippet'
import { Card } from '../dashboard/Card'
import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'
import type { NextStep } from './nextSteps'
+import { WeeklyReportActions } from './WeeklyReportActions'
// Mirrors the empty state's "Install with your agent" modal so the two setup surfaces read the same.
function AgentPromptAction({
@@ -61,6 +62,9 @@ function AgentPromptAction({
function NextStepActions({ step }: { step: NextStep }): JSX.Element {
const { nextStepClicked } = useActions(mcpEarlyDataLogic)
+ if (step.action.kind === 'weekly-report') {
+ return <WeeklyReportActions offer={step.action.offer} />
+ }
if (step.action.kind === 'link') {
return (
<LemonButton
@@ -96,8 +100,13 @@ export function ActivityNextSteps(): JSX.Element | null {
<div className="min-w-0">
<div className="font-medium">{step.title}</div>
<div className="text-muted text-sm">{step.detail}</div>
+ {step.error ? (
+ <div className="text-danger text-sm" role="alert">
+ {step.error}
+ </div>
+ ) : null}
</div>
- <div className="flex shrink-0 items-center gap-1">
+ <div className="flex shrink-0 flex-wrap items-center gap-1">
<NextStepActions step={step} />
</div>
</div>
diff --git a/products/mcp_analytics/frontend/earlyData/WeeklyReportActions.tsx b/products/mcp_analytics/frontend/earlyData/WeeklyReportActions.tsx
new file mode 100644
index 000000000000..e2c967ba199b
--- /dev/null
+++ b/products/mcp_analytics/frontend/earlyData/WeeklyReportActions.tsx
@@ -0,0 +1,94 @@
+import { useActions } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { IconLetter } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+import { urls } from 'scenes/urls'
+
+import { mcpRecurringReportsLogic } from '../notifications/mcpRecurringReportsLogic'
+import type { ActionableWeeklyReportOffer } from '../notifications/weeklyReportOffer'
+import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'
+
+// pinned: autocapture dashboards and Playwright selectors depend on it
+const DATA_ATTR = 'mcp-analytics-activity-next-step-weekly-report'
+
+export function WeeklyReportActions({ offer }: { offer: ActionableWeeklyReportOffer }): JSX.Element {
+ const { nextStepClicked } = useActions(mcpEarlyDataLogic)
+ const { createWeeklyReport, rememberWeeklyReportIntent, resumeWeeklyReportIntent } =
+ useActions(mcpRecurringReportsLogic)
+ const [consentOpen, setConsentOpen] = useState(false)
+
+ useEffect(() => {
+ if (offer.state === 'ready') {
+ resumeWeeklyReportIntent()
+ }
+ }, [offer.state, resumeWeeklyReportIntent])
+
+ if (offer.state === 'created') {
+ return (
+ <LemonButton
+ type="secondary"
+ size="small"
+ to={urls.subscription(offer.report.id)}
+ onClick={() => nextStepClicked('weekly-report', 'manage-report')}
+ data-attr={`${DATA_ATTR}-manage`}
+ >
+ Manage
+ </LemonButton>
+ )
+ }
+
+ const createButton = (
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconLetter />}
+ loading={offer.state === 'creating'}
+ onClick={() => {
+ if (offer.state === 'needs-ai-consent') {
+ nextStepClicked('weekly-report', 'open-consent')
+ setConsentOpen(true)
+ } else {
+ nextStepClicked('weekly-report', 'create-report')
+ createWeeklyReport()
+ }
+ }}
+ data-attr={DATA_ATTR}
+ >
+ {offer.state === 'failed' ? 'Try again' : 'Email me weekly'}
+ </LemonButton>
+ )
+
+ return (
+ <>
+ {offer.state === 'needs-ai-consent' ? (
+ <AIConsentPopoverWrapper
+ hidden={!consentOpen}
+ ignoreDismissal
+ pendingRedirectUrl={urls.mcpAnalyticsActivity()}
+ onDismiss={() => setConsentOpen(false)}
+ onBeforeApprove={rememberWeeklyReportIntent}
+ onApprove={() => {
+ setConsentOpen(false)
+ createWeeklyReport()
+ }}
+ >
+ {createButton}
+ </AIConsentPopoverWrapper>
+ ) : (
+ createButton
+ )}
+ <LemonButton
+ type="tertiary"
+ size="small"
+ to={urls.mcpAnalyticsNotifications()}
+ onClick={() => nextStepClicked('weekly-report', 'more-options')}
+ data-attr={`${DATA_ATTR}-options`}
+ >
+ Other destinations
+ </LemonButton>
+ </>
+ )
+}
diff --git a/products/mcp_analytics/frontend/earlyData/earlyData.test.ts b/products/mcp_analytics/frontend/earlyData/earlyData.test.ts
index 710c5dcae16d..f8465916ed93 100644
--- a/products/mcp_analytics/frontend/earlyData/earlyData.test.ts
+++ b/products/mcp_analytics/frontend/earlyData/earlyData.test.ts
@@ -1,5 +1,8 @@
import { DESTINATION_OPTIONS } from 'scenes/hog-functions/list/newNotificationDialogLogic'
+import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'
+
+import type { ResolvedWeeklyReportOffer } from '../notifications/weeklyReportOffer'
import { buildActivitySummary } from './activitySummary'
import { EarlyStats, buildNextSteps } from './nextSteps'
@@ -14,6 +17,17 @@ const stats = (overrides: Partial<EarlyStats>): EarlyStats => ({
...overrides,
})
+const HIDDEN: ResolvedWeeklyReportOffer = { state: 'hidden', reason: 'has-report' }
+const READY: ResolvedWeeklyReportOffer = { state: 'ready', email: '[email protected]' }
+const CREATED: ResolvedWeeklyReportOffer = {
+ state: 'created',
+ report: {
+ id: 3,
+ target_value: '[email protected]',
+ next_delivery_date: '2026-10-13T09:00:00Z',
+ } as SubscriptionApi,
+}
+
describe('early data derivations', () => {
it.each([
// First calls get the celebratory copy, not a stats sentence.
@@ -95,14 +109,87 @@ describe('early data derivations', () => {
[stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8, errorCalls: 3 }), null, []],
[stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8, errorCalls: 3 }), false, ['notification']],
])('picks next steps for %j with notification=%s', (input, hasFailureNotification, expectedKeys) => {
- expect(buildNextSteps(input, hasFailureNotification).map((step) => step.key)).toEqual(expectedKeys)
+ expect(
+ buildNextSteps({ stats: input, hasFailureNotification, weeklyReport: HIDDEN }).map((step) => step.key)
+ ).toEqual(expectedKeys)
+ })
+
+ it.each([
+ ['leads from the first call', stats({ totalCalls: 1 }), false, READY, ['weekly-report']],
+ [
+ 'leads ahead of instrumentation and pushes the last step out',
+ stats({ totalCalls: 40, callsWithIntent: 2, distinctSessions: 40, errorCalls: 3 }),
+ false,
+ READY,
+ ['weekly-report', 'intent', 'notification'],
+ ],
+ [
+ 'stays for a consent prompt',
+ stats({ totalCalls: 1 }),
+ false,
+ { state: 'needs-ai-consent', email: '[email protected]' },
+ ['weekly-report'],
+ ],
+ ['stays once created', stats({ totalCalls: 1 }), false, CREATED, ['weekly-report']],
+ ] as const)('the weekly report %s', (_name, input, alert, offer, keys) => {
+ expect(
+ buildNextSteps({ stats: input, hasFailureNotification: alert, weeklyReport: offer }).map((step) => step.key)
+ ).toEqual(keys)
+ })
+
+ it.each([
+ [
+ READY,
+ 'Get a weekly report in your inbox',
+ 'Volume, error rate and latency per tool, with the failures worth acting on. First one tomorrow morning to [email protected], then every week.',
+ undefined,
+ ],
+ [
+ { state: 'failed', email: '[email protected]', message: 'Your plan is limited to 5 subscriptions.' },
+ 'Get a weekly report in your inbox',
+ 'Volume, error rate and latency per tool, with the failures worth acting on. First one tomorrow morning to [email protected], then every week.',
+ 'Your plan is limited to 5 subscriptions.',
+ ],
+ [
+ { state: 'needs-ai-consent', email: '[email protected]' },
+ 'Get a weekly report in your inbox',
+ 'Volume, error rate and latency per tool, with the failures worth acting on. First one tomorrow morning to [email protected], then every week.',
+ undefined,
+ ],
+ [
+ CREATED,
+ 'Your weekly report is set up',
+ 'The first one goes to [email protected] on Tuesday at 9:00 AM.',
+ undefined,
+ ],
+ [
+ { state: 'created', report: { id: 3, target_value: '[email protected]', next_delivery_date: null } },
+ 'Your weekly report is set up',
+ 'It goes to [email protected] every week.',
+ undefined,
+ ],
+ ] as const)('writes the weekly report step for %j', (offer, title, detail, error) => {
+ const [step] = buildNextSteps({
+ stats: stats({ totalCalls: 1 }),
+ hasFailureNotification: false,
+ weeklyReport: offer as ResolvedWeeklyReportOffer,
+ })
+
+ expect(step).toMatchObject({
+ key: 'weekly-report',
+ title,
+ detail,
+ error,
+ action: { kind: 'weekly-report', offer },
+ })
})
it('hands instrumentation steps to an agent and product steps to a link', () => {
- const steps = buildNextSteps(
- stats({ totalCalls: 40, callsWithIntent: 0, distinctSessions: 8, errorCalls: 1 }),
- false
- )
+ const steps = buildNextSteps({
+ stats: stats({ totalCalls: 40, callsWithIntent: 0, distinctSessions: 8, errorCalls: 1 }),
+ hasFailureNotification: false,
+ weeklyReport: HIDDEN,
+ })
expect(steps.map((step) => [step.key, step.action.kind])).toEqual([
['intent', 'agent-prompt'],
@@ -116,10 +203,11 @@ describe('early data derivations', () => {
})
describe('alert step copy', () => {
- const alertStep = buildNextSteps(
- stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8, errorCalls: 3 }),
- false
- )[0]
+ const alertStep = buildNextSteps({
+ stats: stats({ totalCalls: 40, callsWithIntent: 35, distinctSessions: 8, errorCalls: 3 }),
+ hasFailureNotification: false,
+ weeklyReport: HIDDEN,
+ })[0]
// Hog function alerts can only go to the destinations the new-alert dialog lists.
it.each(DESTINATION_OPTIONS.map(({ label }) => label))('offers %s', (label) => {
diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts
index 8972a6059669..3332ac6b6b81 100644
--- a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts
+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.test.ts
@@ -1,22 +1,35 @@
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { preflightLogic } from 'lib/logic/preflightLogic'
import posthog from 'lib/posthog-typed'
import { initKeaTests } from '~/test/init'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+import { subscriptionsCreate, subscriptionsList } from 'products/subscriptions/frontend/generated/api'
+import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'
+
import { mcpAnalyticsSessionsActivityOverview } from '../generated/api'
import type { MCPActivityOverviewApi } from '../generated/api.schemas'
import { mcpAnalyticsFiltersLogic } from '../mcpAnalyticsFiltersLogic'
+import { mcpRecurringReportsLogic } from '../notifications/mcpRecurringReportsLogic'
import { mcpEarlyDataLogic } from './mcpEarlyDataLogic'
jest.mock('lib/api')
jest.mock('lib/posthog-typed', () => ({ __esModule: true, default: { capture: jest.fn(), captureRaw: jest.fn() } }))
jest.mock('../generated/api', () => ({ mcpAnalyticsSessionsActivityOverview: jest.fn() }))
+jest.mock('products/subscriptions/frontend/generated/api', () => ({
+ subscriptionsList: jest.fn(),
+ subscriptionsCreate: jest.fn(),
+}))
const overviewMock = mcpAnalyticsSessionsActivityOverview as jest.Mock
const captureRawMock = posthog.captureRaw as jest.Mock
+const createReportMock = subscriptionsCreate as jest.Mock
function overviewWith(stats: Partial<MCPActivityOverviewApi['stats']>): MCPActivityOverviewApi {
return {
@@ -36,6 +49,13 @@ function overviewWith(stats: Partial<MCPActivityOverviewApi['stats']>): MCPActiv
}
}
+const LANDED_REPORT = {
+ id: 5,
+ enabled: true,
+ prompt: 'Report on $mcp_tool_name',
+ target_type: 'email',
+} as SubscriptionApi
+
const INTENT_AND_ALERT_STEPS = overviewWith({ calls_with_intent: 2, error_calls: 3 })
const ALERT_STEP_ONLY = overviewWith({ error_calls: 3 })
const NO_STEPS = overviewWith({})
@@ -43,6 +63,7 @@ const NO_STEPS = overviewWith({})
function eventsNamed(name: string): unknown[][] {
return captureRawMock.mock.calls.filter(([event]) => event === name).map(([, properties]) => properties)
}
+
const TOOL_FILTER: AnyPropertyFilter = {
key: '$mcp_tool_name',
value: ['create_insight'],
@@ -63,10 +84,21 @@ describe('mcpEarlyDataLogic', () => {
results: [],
})
overviewMock.mockResolvedValue(null)
+ ;(subscriptionsList as jest.Mock).mockResolvedValue({ next: null, previous: null, results: [] })
logic = mcpEarlyDataLogic()
logic.mount()
})
+ // Self-hosted instances never see the weekly report, so the other steps show alone.
+ async function resolveOffer(cloud: boolean): Promise<void> {
+ // Let the mounted preflight request land first, so it cannot overwrite the answer set here.
+ await expectLogic(preflightLogic).toFinishAllListeners()
+ preflightLogic.actions.loadPreflightSuccess({ cloud, is_debug: false } as any)
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT], {
+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true,
+ })
+ }
+
afterEach(() => {
logic.unmount()
jest.clearAllMocks()
@@ -124,6 +156,7 @@ describe('mcpEarlyDataLogic', () => {
],
],
])('reports the steps shown for %s', async (_label, overviews, expectedShown) => {
+ await resolveOffer(false)
await expectLogic(logic).toFinishAllListeners()
captureRawMock.mockClear()
@@ -141,6 +174,7 @@ describe('mcpEarlyDataLogic', () => {
['loads', false, ['intent', 'notification']],
['fails to load', true, ['intent']],
])('holds the card until the alert list %s, then reports it once', async (_label, listFails, expectedSteps) => {
+ await resolveOffer(false)
logic.unmount()
let settleList!: () => void
const list = new Promise<Awaited<ReturnType<typeof api.hogFunctions.list>>>((resolve, reject) => {
@@ -152,7 +186,6 @@ describe('mcpEarlyDataLogic', () => {
captureRawMock.mockClear()
logic = mcpEarlyDataLogic()
logic.mount()
-
await expectLogic(logic).toDispatchActions(['loadOverviewSuccess'])
expect(logic.values.nextSteps).toBeNull()
@@ -166,7 +199,8 @@ describe('mcpEarlyDataLogic', () => {
])
})
- it('reports how much data stood behind the steps shown', async () => {
+ it('reports how much data stood behind the steps shown and why the report is missing', async () => {
+ await resolveOffer(false)
await expectLogic(logic).toFinishAllListeners()
captureRawMock.mockClear()
overviewMock.mockResolvedValue(INTENT_AND_ALERT_STEPS)
@@ -174,22 +208,135 @@ describe('mcpEarlyDataLogic', () => {
await expectLogic(logic, () => logic.actions.loadOverview()).toFinishAllListeners()
expect(eventsNamed('mcp analytics next steps shown')).toEqual([
- { step_keys: ['intent', 'notification'], total_calls: 40, error_calls: 3 },
+ {
+ step_keys: ['intent', 'notification'],
+ weekly_report: 'hidden:self-hosted',
+ total_calls: 40,
+ error_calls: 3,
+ },
+ ])
+ })
+
+ it.each([
+ ['loads', false, ['weekly-report', 'intent', 'notification']],
+ ['fails to load', true, ['intent', 'notification']],
+ ])('holds the card until the report list %s, then reports it once', async (_label, listFails, expectedKeys) => {
+ await resolveOffer(true)
+ logic.unmount()
+ let settleList!: () => void
+ const list = new Promise<{ next: null; previous: null; results: [] }>((resolve, reject) => {
+ settleList = () =>
+ listFails ? reject(new Error('down')) : resolve({ next: null, previous: null, results: [] })
+ })
+ ;(subscriptionsList as jest.Mock).mockReturnValue(list)
+ overviewMock.mockResolvedValue(INTENT_AND_ALERT_STEPS)
+ captureRawMock.mockClear()
+ logic = mcpEarlyDataLogic()
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadOverviewSuccess', 'loadNotificationsSuccess'])
+
+ expect(logic.values.nextSteps).toBeNull()
+ expect(eventsNamed('mcp analytics next steps shown')).toEqual([])
+
+ settleList()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(eventsNamed('mcp analytics next steps shown').map((properties: any) => properties.step_keys)).toEqual([
+ expectedKeys,
])
})
+ it('holds the card back until the weekly report offer is known', async () => {
+ overviewMock.mockResolvedValue(INTENT_AND_ALERT_STEPS)
+ await expectLogic(logic, () => logic.actions.loadOverview()).toFinishAllListeners()
+ expect(logic.values.nextSteps).toBeNull()
+
+ await resolveOffer(true)
+
+ expect(logic.values.nextSteps?.map((step) => step.key)).toEqual(['weekly-report', 'intent', 'notification'])
+ })
+
it.each([
['intent', 'open', 0],
['intent', 'docs', 0],
['notification', 'open', 1],
] as const)('reports a %s click with interaction %s at position %s', async (stepKey, interaction, position) => {
+ await resolveOffer(false)
overviewMock.mockResolvedValue(INTENT_AND_ALERT_STEPS)
await expectLogic(logic, () => logic.actions.loadOverview()).toFinishAllListeners()
captureRawMock.mockClear()
logic.actions.nextStepClicked(stepKey, interaction)
- expect(eventsNamed('mcp analytics next step clicked')).toEqual([{ step_key: stepKey, interaction, position }])
+ expect(eventsNamed('mcp analytics next step clicked')).toEqual([
+ { step_key: stepKey, interaction, position, weekly_report: 'hidden:self-hosted' },
+ ])
+ })
+
+ describe('with the weekly report on offer', () => {
+ beforeEach(async () => {
+ await resolveOffer(true)
+ overviewMock.mockResolvedValue(INTENT_AND_ALERT_STEPS)
+ createReportMock.mockResolvedValue({ id: 5, target_type: 'email' } as SubscriptionApi)
+ await expectLogic(logic, () => logic.actions.loadOverview()).toFinishAllListeners()
+ })
+
+ it('reports the steps shown with the report leading and its state', () => {
+ expect(eventsNamed('mcp analytics next steps shown')).toEqual([
+ {
+ step_keys: ['weekly-report', 'intent', 'notification'],
+ weekly_report: 'ready',
+ total_calls: 40,
+ error_calls: 3,
+ },
+ ])
+ })
+
+ it.each([
+ ['succeeds', () => Promise.resolve(LANDED_REPORT), []],
+ ['is refused', () => Promise.reject(new ApiError('Bad Request', 400)), []],
+ [
+ 'fails in transit after the report landed',
+ () => {
+ ;(subscriptionsList as jest.Mock).mockResolvedValue({
+ next: null,
+ previous: null,
+ results: [LANDED_REPORT],
+ })
+ return Promise.reject(new Error('network'))
+ },
+ [['intent', 'notification']],
+ ],
+ ])(
+ 'reports the steps again only if creating the report %s changes them',
+ async (_label, create, expectedShown) => {
+ createReportMock.mockImplementation(create)
+ captureRawMock.mockClear()
+
+ mcpRecurringReportsLogic.actions.createWeeklyReport()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(
+ eventsNamed('mcp analytics next steps shown').map((properties: any) => properties.step_keys)
+ ).toEqual(expectedShown)
+ }
+ )
+
+ it.each(['create-report', 'open-consent', 'manage-report', 'more-options'] as const)(
+ 'a %s click only reports the click, with the offer state',
+ async (interaction) => {
+ captureRawMock.mockClear()
+
+ logic.actions.nextStepClicked('weekly-report', interaction)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createReportMock).not.toHaveBeenCalled()
+ expect(eventsNamed('mcp analytics next step clicked')).toEqual([
+ { step_key: 'weekly-report', interaction, position: 0, weekly_report: 'ready' },
+ ])
+ }
+ )
})
const MINUTE = 60_000
diff --git a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts
index 2adff7e6da84..31b3ca3c0914 100644
--- a/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts
+++ b/products/mcp_analytics/frontend/earlyData/mcpEarlyDataLogic.ts
@@ -40,6 +40,8 @@ import { mcpAnalyticsOnboardingLogic } from '../mcpAnalyticsOnboardingLogic'
import type { MCPOnboardingSignals } from '../mcpAnalyticsOnboardingLogic'
import type { HarnessRow, ModelRow } from '../mcpDashboardOverviewLogic'
import { mcpAnalyticsNotificationsLogic } from '../notifications/mcpAnalyticsNotificationsLogic'
+import { mcpRecurringReportsLogic } from '../notifications/mcpRecurringReportsLogic'
+import { type WeeklyReportOffer, weeklyReportOfferLabel } from '../notifications/weeklyReportOffer'
import { ActivitySummary, buildActivitySummary } from './activitySummary'
import { EarlyStats, NextStep, NextStepInteraction, NextStepKey, buildNextSteps } from './nextSteps'
@@ -81,6 +83,7 @@ export interface mcpEarlyDataLogicValues {
sharedQueryFilters: MCPSharedQueryFilters // mcpAnalyticsFiltersLogic
notifications: HogFunctionType[] // mcpAnalyticsNotificationsLogic
signals: MCPOnboardingSignals | null // mcpAnalyticsOnboardingLogic
+ weeklyReportOffer: WeeklyReportOffer // mcpRecurringReportsLogic
currentProjectId: number | string // teamLogic
activityQuery: DataTableNode
harnessRows: HarnessRow[]
@@ -133,6 +136,24 @@ export interface mcpEarlyDataLogicActions {
payload?: any
} // mcpAnalyticsNotificationsLogic
loadSignals: (_?: void | undefined) => void // mcpAnalyticsOnboardingLogic
+ createWeeklyReportReconciled: () => {
+ value: true
+ } // mcpRecurringReportsLogic
+ loadReports: () => any // mcpRecurringReportsLogic
+ loadReportsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // mcpRecurringReportsLogic
+ loadReportsSuccess: (
+ reports: import('products/subscriptions/frontend/generated/api.schemas').SubscriptionApi[],
+ payload?: any
+ ) => {
+ payload?: any
+ reports: import('products/subscriptions/frontend/generated/api.schemas').SubscriptionApi[]
+ } // mcpRecurringReportsLogic
loadHarnessRows: (_: void) => void
loadHarnessRowsFailure: (
error: string,
@@ -236,7 +257,8 @@ export interface mcpEarlyDataLogicMeta {
overview: MCPActivityOverviewApi | null,
stats: EarlyStats,
notificationsLoad: NotificationsLoad,
- hasFailureNotification: boolean | null
+ hasFailureNotification: boolean | null,
+ weeklyReportOffer: WeeklyReportOffer
) => NextStep[] | null
hasModelData: (modelRows: ModelRow[]) => boolean
refreshDelayMs: (refreshesWithoutInput: number) => number
@@ -262,6 +284,8 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([
['queryFilters as sharedQueryFilters'],
mcpAnalyticsNotificationsLogic,
['notifications'],
+ mcpRecurringReportsLogic,
+ ['weeklyReportOffer'],
],
actions: [
// Refresh the lifetime signal with the overview so first-call copy can
@@ -272,6 +296,8 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([
['hydrateFilters', 'setFilterTestAccounts', 'setPropertyFilters'],
mcpAnalyticsNotificationsLogic,
['loadNotifications', 'loadNotificationsSuccess', 'loadNotificationsFailure'],
+ mcpRecurringReportsLogic,
+ ['loadReports', 'loadReportsSuccess', 'loadReportsFailure', 'createWeeklyReportReconciled'],
dataNodeCollectionLogic({ key: MCP_ACTIVITY_DATA_COLLECTION_ID }),
['reloadAll as reloadActivityQuery'],
],
@@ -393,16 +419,19 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([
(notificationsLoad: NotificationsLoad, notifications: HogFunctionType[]): boolean | null =>
notificationsLoad === 'loaded' ? notifications.some((notification) => notification.enabled) : null,
],
- // Null until the overview and the notification list both resolve, so steps never reorder under the reader.
+ // Null until the overview, the notification list and the report offer all resolve, so steps never reorder under the reader.
nextSteps: [
- (s) => [s.overview, s.stats, s.notificationsLoad, s.hasFailureNotification],
+ (s) => [s.overview, s.stats, s.notificationsLoad, s.hasFailureNotification, s.weeklyReportOffer],
(
overview: MCPActivityOverviewApi | null,
stats: EarlyStats,
notificationsLoad: NotificationsLoad,
- hasFailureNotification: boolean | null
+ hasFailureNotification: boolean | null,
+ weeklyReportOffer: WeeklyReportOffer
): NextStep[] | null =>
- overview && notificationsLoad !== 'pending' ? buildNextSteps(stats, hasFailureNotification) : null,
+ overview && notificationsLoad !== 'pending' && weeklyReportOffer.state !== 'loading'
+ ? buildNextSteps({ stats, hasFailureNotification, weeklyReport: weeklyReportOffer })
+ : null,
],
hasModelData: [
(s) => [s.modelRows],
@@ -428,6 +457,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([
if (stepKeys.length > 0) {
posthog.captureRaw('mcp analytics next steps shown', {
step_keys: stepKeys,
+ weekly_report: weeklyReportOfferLabel(values.weeklyReportOffer),
total_calls: values.stats.totalCalls,
error_calls: values.stats.errorCalls,
})
@@ -438,11 +468,15 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([
loadOverviewSuccess: sharedListeners.captureNextStepsShown,
loadNotificationsSuccess: sharedListeners.captureNextStepsShown,
loadNotificationsFailure: sharedListeners.captureNextStepsShown,
+ loadReportsSuccess: sharedListeners.captureNextStepsShown,
+ loadReportsFailure: sharedListeners.captureNextStepsShown,
+ createWeeklyReportReconciled: sharedListeners.captureNextStepsShown,
nextStepClicked: ({ stepKey, interaction }) => {
posthog.captureRaw('mcp analytics next step clicked', {
step_key: stepKey,
interaction,
position: values.nextSteps?.findIndex((step) => step.key === stepKey) ?? -1,
+ weekly_report: weeklyReportOfferLabel(values.weeklyReportOffer),
})
},
scheduleRefresh: () => {
@@ -489,6 +523,7 @@ export const mcpEarlyDataLogic = kea<mcpEarlyDataLogicType>([
)
actions.loadOverview()
actions.loadNotifications()
+ actions.loadReports()
actions.loadHarnessRows()
actions.loadModelRows()
actions.scheduleRefresh()
diff --git a/products/mcp_analytics/frontend/earlyData/nextSteps.ts b/products/mcp_analytics/frontend/earlyData/nextSteps.ts
index c3ce7eb389e5..e7441cacdd83 100644
--- a/products/mcp_analytics/frontend/earlyData/nextSteps.ts
+++ b/products/mcp_analytics/frontend/earlyData/nextSteps.ts
@@ -1,5 +1,11 @@
+import { dayjs } from 'lib/dayjs'
import { urls } from 'scenes/urls'
+import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'
+
+import { TOOL_HEALTH_REPORT } from '../notifications/recurringReportDefinitions'
+import type { ActionableWeeklyReportOffer, ResolvedWeeklyReportOffer } from '../notifications/weeklyReportOffer'
+
export interface EarlyStats {
totalCalls: number
distinctTools: number
@@ -14,15 +20,17 @@ export type NextStepAction =
| { kind: 'link'; label: string; to: string }
/** A self-contained instruction the user pastes into their coding agent, with the docs as the fallback. */
| { kind: 'agent-prompt'; prompt: string; docsUrl: string }
+ | { kind: 'weekly-report'; offer: ActionableWeeklyReportOffer }
-export type NextStepKey = 'intent' | 'notification' | 'sessions'
+export type NextStepKey = 'weekly-report' | 'intent' | 'notification' | 'sessions'
-export type NextStepInteraction = 'open' | 'docs'
+export type NextStepInteraction = 'open' | 'docs' | 'create-report' | 'open-consent' | 'manage-report' | 'more-options'
export interface NextStep {
key: NextStepKey
title: string
detail: string
+ error?: string
action: NextStepAction
}
@@ -41,8 +49,44 @@ const MIN_CALLS_FOR_SIGNAL = 10
/** More than this and the card competes with the feed for attention. */
const MAX_STEPS = 3
-/** Only the applicable steps, in priority order: a step that is already done is dead space. */
-export function buildNextSteps(stats: EarlyStats, hasFailureNotification: boolean | null): NextStep[] {
+export interface NextStepInputs {
+ stats: EarlyStats
+ hasFailureNotification: boolean | null
+ weeklyReport: ResolvedWeeklyReportOffer
+}
+
+function weeklyReportDetail(offer: ActionableWeeklyReportOffer): string {
+ if (offer.state === 'created') {
+ return createdReportDetail(offer.report)
+ }
+ return `${TOOL_HEALTH_REPORT.lead} First one tomorrow morning to ${offer.email}, then every week.`
+}
+
+function createdReportDetail(report: SubscriptionApi): string {
+ if (!report.next_delivery_date) {
+ return `It goes to ${report.target_value} every week.`
+ }
+ return `The first one goes to ${report.target_value} on ${dayjs(report.next_delivery_date).format('dddd [at] h:mm A')}.`
+}
+
+// The tool health report has something to say on day one. The intent roundup needs intent capture first.
+function weeklyReportStep(offer: ActionableWeeklyReportOffer): NextStep {
+ return {
+ key: 'weekly-report',
+ title: offer.state === 'created' ? 'Your weekly report is set up' : 'Get a weekly report in your inbox',
+ detail: weeklyReportDetail(offer),
+ error: offer.state === 'failed' ? offer.message : undefined,
+ action: { kind: 'weekly-report', offer },
+ }
+}
+
+/**
+ * The applicable steps in priority order. A step that is already done is dead space, except the
+ * weekly report once created: it stays for the session so the card confirms what the click did.
+ * The weekly report leads from the first call, because the moment data arrives is the moment to give a
+ * reason to come back.
+ */
+export function buildNextSteps({ stats, hasFailureNotification, weeklyReport }: NextStepInputs): NextStep[] {
const enoughSignal = stats.totalCalls >= MIN_CALLS_FOR_SIGNAL
const intentShare = stats.totalCalls > 0 ? stats.callsWithIntent / stats.totalCalls : 0
// One session per call means no session state survives between calls
@@ -53,6 +97,9 @@ export function buildNextSteps(stats: EarlyStats, hasFailureNotification: boolea
(stats.distinctSessions === 0 || stats.distinctSessions >= Math.max(2, Math.ceil(stats.totalCalls * 0.9)))
const steps: NextStep[] = []
+ if (weeklyReport.state !== 'hidden') {
+ steps.push(weeklyReportStep(weeklyReport))
+ }
if (enoughSignal && intentShare < 0.5) {
steps.push({
key: 'intent',
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
index 813f93bcadd1..ec06bc49c7ad 100644
--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
@@ -424,6 +424,22 @@ describe('mcpRecurringReportsLogic', () => {
expect(logic.values.weeklyReportOffer).toEqual({ state: 'hidden', reason: 'has-report' })
})
+ it.each([
+ ['creates the report when the page comes back soon', 60 * 1000, 1],
+ ['ignores a click from long ago', 11 * 60 * 1000, 0],
+ ])('after a reauthentication redirect, %s', async (_name, elapsedMs, expectedCreates) => {
+ await becomeReadyToCreate()
+ mockedCreate.mockResolvedValue(SAVED)
+ logic.actions.rememberWeeklyReportIntent()
+ const clock = jest.spyOn(Date, 'now').mockReturnValue(Date.now() + elapsedMs)
+
+ await expectLogic(logic, () => logic.actions.resumeWeeklyReportIntent()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.resumeWeeklyReportIntent()).toFinishAllListeners()
+ clock.mockRestore()
+
+ expect(mockedCreate).toHaveBeenCalledTimes(expectedCreates)
+ })
+
it('creates the report once the organization approves AI processing', async () => {
useMocks({
patch: {
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
index ed63f2be668d..b4b3d45ff99b 100644
--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
@@ -47,6 +47,26 @@ export const AI_REPORT_LIST_LIMIT = 200
*/
const MCP_PROPERTY_PREFIX = '$mcp_'
+// Approving AI consent can trigger a full-page SSO reauthentication, which unloads the page before
+// `onApprove` runs. The click is stored first, so the offer can finish it when the page comes back.
+const WEEKLY_REPORT_INTENT_KEY = 'mcp-analytics-weekly-report-intent'
+const WEEKLY_REPORT_INTENT_TTL_MS = 10 * 60 * 1000
+
+interface WeeklyReportIntent {
+ teamId: number
+ setAt: number
+}
+
+function takeWeeklyReportIntent(): WeeklyReportIntent | null {
+ try {
+ const stored = sessionStorage.getItem(WEEKLY_REPORT_INTENT_KEY)
+ sessionStorage.removeItem(WEEKLY_REPORT_INTENT_KEY)
+ return stored ? (JSON.parse(stored) as WeeklyReportIntent) : null
+ } catch {
+ return null
+ }
+}
+
export function isMCPRecurringReport(subscription: Pick<SubscriptionApi, 'prompt'>): boolean {
return (subscription.prompt ?? '').includes(MCP_PROPERTY_PREFIX)
}
@@ -112,6 +132,12 @@ export interface mcpRecurringReportsLogicActions {
reports: SubscriptionApi[]
payload?: any
}
+ rememberWeeklyReportIntent: () => {
+ value: true
+ }
+ resumeWeeklyReportIntent: () => {
+ value: true
+ }
setReports: (reports: SubscriptionApi[]) => {
reports: SubscriptionApi[]
}
@@ -197,6 +223,8 @@ export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([
setReportsTruncated: (reportsTruncated: boolean) => ({ reportsTruncated }),
deleteReport: (report: SubscriptionApi) => ({ report }),
createWeeklyReport: true,
+ rememberWeeklyReportIntent: true,
+ resumeWeeklyReportIntent: true,
createWeeklyReportStarted: true,
createWeeklyReportSucceeded: (report: SubscriptionApi) => ({ report }),
createWeeklyReportFailed: (message: string, reconciling: boolean) => ({ message, reconciling }),
@@ -368,7 +396,22 @@ export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([
setReports: () => {
cache.localReportWrites = (cache.localReportWrites ?? 0) + 1
},
+ rememberWeeklyReportIntent: () => {
+ const intent: WeeklyReportIntent = { teamId: getCurrentTeamId(), setAt: Date.now() }
+ try {
+ sessionStorage.setItem(WEEKLY_REPORT_INTENT_KEY, JSON.stringify(intent))
+ } catch {
+ // Without storage the report waits for another click, as it did before.
+ }
+ },
+ resumeWeeklyReportIntent: () => {
+ const intent = takeWeeklyReportIntent()
+ if (intent?.teamId === getCurrentTeamId() && Date.now() - intent.setAt < WEEKLY_REPORT_INTENT_TTL_MS) {
+ actions.createWeeklyReport()
+ }
+ },
createWeeklyReport: async () => {
+ takeWeeklyReportIntent()
const offer = values.weeklyReportOffer
// The same union drives the UI, so a double click and every closed gate end here.
if (offer.state !== 'ready' && offer.state !== 'failed') {