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): default report destination to the last one used (#117435)

Lucas Faria287f67eb941e
diff --git a/docs/published/docs/mcp-analytics/notifications.mdx b/docs/published/docs/mcp-analytics/notifications.mdx
index 7f495bc8bae2..6ed00ae55a69 100644
--- a/docs/published/docs/mcp-analytics/notifications.mdx
+++ b/docs/published/docs/mcp-analytics/notifications.mdx
@@ -28,6 +28,8 @@ To set one up:
3. Choose where it should go and how often, then create it.
The report's question is already written for you, and you can edit it before saving.
+The destination starts as the one you chose for your last report.
+For your first report, it starts as Slack if your project has Slack connected, and as email to your own address otherwise.
Recurring reports are built on PostHog's AI subscriptions, which are in early access.
If the report shows **Turn on early access** instead of **Set up**, select it to turn on **AI subscriptions** in your [feature previews](https://app.posthog.com/settings/user-feature-previews) first.
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
index b26282551f7b..4a29e97c3f97 100644
--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts
@@ -1,8 +1,11 @@
import { expectLogic } from 'kea-test-utils'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
+import { userLogic } from 'scenes/userLogic'
import { initKeaTests } from '~/test/init'
+import { IntegrationType, UserType } from '~/types'
import { toggleSubscriptionEnabled } from 'products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled'
import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'
@@ -87,6 +90,40 @@ describe('mcpRecurringReportsLogic', () => {
expect(logic.values.otherReports.map((r) => r.id)).toEqual([2, 3])
})
+ const ME = 'user-me'
+ const createdBy = (id: number, target_type: string, uuid: string | null): SubscriptionApi =>
+ makeReport(id, { target_type, created_by: uuid ? { uuid } : null } as Partial<SubscriptionApi>)
+
+ async function loadDefaultInputs(slackConnected: boolean): Promise<void> {
+ userLogic.actions.loadUserSuccess({ uuid: ME } as UserType)
+ await expectLogic(integrationsLogic).toFinishAllListeners()
+ integrationsLogic.actions.loadIntegrationsSuccess(
+ slackConnected ? [{ id: 1, kind: 'slack' } as IntegrationType] : []
+ )
+ }
+
+ // Reports arrive newest first, as the API orders them.
+ it.each([
+ ['my most recent report wins', [createdBy(2, 'teams', ME), createdBy(1, 'email', ME)], true, 'teams'],
+ ['a teammate report is not my choice', [createdBy(1, 'teams', 'someone-else')], false, 'email'],
+ ['a report with a deleted creator is not my choice', [createdBy(1, 'teams', null)], false, 'email'],
+ ['no report of mine, Slack connected', [createdBy(1, 'email', 'someone-else')], true, 'slack'],
+ ['no report and no Slack', [], false, 'email'],
+ ])('defaults the destination when %s', async (_name, reports, slackConnected, expected) => {
+ await loadDefaultInputs(slackConnected)
+ listReturns(reports)
+
+ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()
+
+ expect(logic.values.defaultTargetType).toBe(expected)
+ })
+
+ it('has no default destination until the reports load', async () => {
+ await loadDefaultInputs(true)
+
+ expect(logic.values.defaultTargetType).toBeNull()
+ })
+
it('lists only the MCP reports among the project AI reports', async () => {
const mcpReport = makeReport(1)
listReturns([mcpReport, makeReport(2, { prompt: 'Weekly $pageview summary.' })])
diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
index 58bf0c9bc8f1..1120a3c6d363 100644
--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts
@@ -1,13 +1,21 @@
-import { actions, kea, listeners, MakeLogicType, path, reducers, selectors } from 'kea'
+import { actions, connect, kea, listeners, MakeLogicType, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { userLogic } from 'scenes/userLogic'
+
+import { IntegrationType, UserType } from '~/types'
import { toggleSubscriptionEnabled } from 'products/subscriptions/frontend/components/Subscriptions/toggleSubscriptionEnabled'
import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'
-import { SubscriptionApi, SubscriptionsListResourceType } from 'products/subscriptions/frontend/generated/api.schemas'
+import {
+ SubscriptionApi,
+ SubscriptionsListResourceType,
+ SubscriptionTargetEnumApi,
+} from 'products/subscriptions/frontend/generated/api.schemas'
import { MCP_RECURRING_REPORTS } from './recurringReportDefinitions'
@@ -35,6 +43,9 @@ export function isMCPRecurringReport(subscription: Pick<SubscriptionApi, 'prompt
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface mcpRecurringReportsLogicValues {
+ slackIntegrations: IntegrationType[] | undefined // integrationsLogic
+ user: UserType | null // userLogic
+ defaultTargetType: SubscriptionTargetEnumApi | null
otherReports: SubscriptionApi[]
pendingToggleIds: Record<number, true>
reports: SubscriptionApi[]
@@ -91,6 +102,12 @@ export interface mcpRecurringReportsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
reportsByTemplateTitle: (reports: SubscriptionApi[]) => Record<string, SubscriptionApi[]>
otherReports: (reports: SubscriptionApi[]) => SubscriptionApi[]
+ defaultTargetType: (
+ reports: SubscriptionApi[],
+ reportsLoaded: boolean,
+ user: UserType | null,
+ slackIntegrations: IntegrationType[] | undefined
+ ) => SubscriptionTargetEnumApi | null
}
}
@@ -105,6 +122,9 @@ const TEMPLATE_TITLES = new Set(MCP_RECURRING_REPORTS.map((report) => report.tit
export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([
path(['products', 'mcp_analytics', 'frontend', 'notifications', 'mcpRecurringReportsLogic']),
+ connect(() => ({
+ values: [integrationsLogic, ['slackIntegrations'], userLogic, ['user']],
+ })),
actions({
toggleReportEnabled: (reportId: number, enabled: boolean) => ({ reportId, enabled }),
toggleReportEnabledStarted: (reportId: number) => ({ reportId }),
@@ -193,6 +213,28 @@ export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([
(reports: SubscriptionApi[]): SubscriptionApi[] =>
reports.filter((saved) => !saved.title || !TEMPLATE_TITLES.has(saved.title)),
],
+ // The destination someone picked for their last report is the best guess for the next one.
+ // Before that, a connected Slack workspace is the likeliest channel, and email needs no setup.
+ // Null until all three inputs load, so an early click gets the form's own default, not a guess.
+ defaultTargetType: [
+ (s) => [s.reports, s.reportsLoaded, s.user, s.slackIntegrations],
+ (
+ reports: SubscriptionApi[],
+ reportsLoaded: boolean,
+ user: UserType | null,
+ slackIntegrations: IntegrationType[] | undefined
+ ): SubscriptionTargetEnumApi | null => {
+ if (!reportsLoaded || !user || slackIntegrations === undefined) {
+ return null
+ }
+ // The API lists newest first, so the first match is the most recent.
+ const lastOwnReport = reports.find((report) => report.created_by?.uuid === user.uuid)
+ if (lastOwnReport) {
+ return lastOwnReport.target_type
+ }
+ return slackIntegrations.length ? SubscriptionTargetEnumApi.Slack : SubscriptionTargetEnumApi.Email
+ },
+ ],
}),
listeners(({ actions, values }) => ({
toggleReportEnabled: async ({ reportId, enabled }) => {
diff --git a/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts b/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts
index 687616b7c43e..c6876dcec282 100644
--- a/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts
+++ b/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts
@@ -2,6 +2,8 @@ import { combineUrl } from 'kea-router'
import { urls } from 'scenes/urls'
+import { SubscriptionTargetEnumApi } from 'products/subscriptions/frontend/generated/api.schemas'
+
export interface MCPRecurringReport {
key: string
headline: string
@@ -75,12 +77,15 @@ export const MCP_RECURRING_REPORTS: MCPRecurringReport[] = [
* Opens the AI-subscription form with the report already written, so setting one up is choosing a
* destination and a cadence rather than composing a prompt.
*/
-export function urlForRecurringReport(report: MCPRecurringReport): string {
+export function urlForRecurringReport(
+ report: MCPRecurringReport,
+ targetType: SubscriptionTargetEnumApi | null
+): string {
return combineUrl(urls.subscriptionNew(), {
resource_type: 'ai_prompt',
prompt: report.prompt,
title: report.title,
frequency: report.frequency,
- target_type: 'slack',
+ target_type: targetType ?? undefined,
}).url
}
diff --git a/products/mcp_analytics/frontend/notifications/recurringReportRows.tsx b/products/mcp_analytics/frontend/notifications/recurringReportRows.tsx
index 4d573197bc1d..2e54e0833f2e 100644
--- a/products/mcp_analytics/frontend/notifications/recurringReportRows.tsx
+++ b/products/mcp_analytics/frontend/notifications/recurringReportRows.tsx
@@ -10,7 +10,7 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
-import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'
+import type { SubscriptionApi, SubscriptionTargetEnumApi } from 'products/subscriptions/frontend/generated/api.schemas'
import { mcpRecurringReportsLogic } from './mcpRecurringReportsLogic'
import { countSaved, NotificationTypeRow } from './NotificationTypesTable'
@@ -51,7 +51,12 @@ function SavedReportRow({ report }: { report: SubscriptionApi }): JSX.Element {
// `mayExist` covers a cut list too: a match may sit past the page limit, so the row must not push
// a primary "Set up" that creates a duplicate.
-function reportAction(report: MCPRecurringReport, mayExist: boolean, aiSubscriptionsEnabled: boolean): JSX.Element {
+function reportAction(
+ report: MCPRecurringReport,
+ mayExist: boolean,
+ aiSubscriptionsEnabled: boolean,
+ targetType: SubscriptionTargetEnumApi | null
+): JSX.Element {
if (!aiSubscriptionsEnabled) {
return (
<LemonButton
@@ -70,7 +75,7 @@ function reportAction(report: MCPRecurringReport, mayExist: boolean, aiSubscript
type={mayExist ? 'secondary' : 'primary'}
size="small"
icon={mayExist ? <IconPlus /> : undefined}
- to={urlForRecurringReport(report)}
+ to={urlForRecurringReport(report, targetType)}
data-attr={`mcp-analytics-recurring-report-${report.key}`}
>
{mayExist ? 'Add' : 'Set up'}
@@ -94,7 +99,7 @@ export interface RecurringReportRows {
export function useRecurringReportRows(): RecurringReportRows {
const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')
const { receivedFeatureFlags } = useValues(featureFlagLogic)
- const { reportsByTemplateTitle, otherReports, reportsLoaded, reportsFailed, reportsTruncated } =
+ const { reportsByTemplateTitle, otherReports, reportsLoaded, reportsFailed, reportsTruncated, defaultTargetType } =
useValues(mcpRecurringReportsLogic)
const { loadReports } = useActions(mcpRecurringReportsLogic)
// An unresolved flag reads as off, so the row would offer "Turn on early access" to someone who
@@ -121,7 +126,12 @@ export function useRecurringReportRows(): RecurringReportRows {
),
cadence: report.frequency,
saved: ready ? countSaved(saved, reportsTruncated) : undefined,
- action: reportAction(report, saved.length > 0 || reportsTruncated, aiSubscriptionsEnabled),
+ action: reportAction(
+ report,
+ saved.length > 0 || reportsTruncated,
+ aiSubscriptionsEnabled,
+ defaultTargetType
+ ),
preview: <RecurringReportDetails covers={report.covers} prompt={report.prompt} />,
savedRows: saved.map((report) => <SavedReportRow key={report.id} report={report} />),
}