: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp-analytics): list recurring reports in a notification table (#102592)
Lucas Faria1dbfef284ff7
diff --git a/docs/published/docs/mcp-analytics/notifications.mdx b/docs/published/docs/mcp-analytics/notifications.mdxindex cf0ff252bf02..90c586d05e17 100644--- a/docs/published/docs/mcp-analytics/notifications.mdx+++ b/docs/published/docs/mcp-analytics/notifications.mdx@@ -21,13 +21,13 @@ Two are ready to set up from the **Notifications** tab:To set one up:1. Open **MCP analytics** and select the **Notifications** tab.-2. Under **Recurring reports**, select **Set up** on the report you want.+2. Select **Set up** on the row of the report you want.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.Recurring reports are built on PostHog's AI subscriptions, which are in early access.-If you don't see a **Set up** button, turn on **AI subscriptions** in your [feature previews](https://app.posthog.com/settings/user-feature-previews) first.+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.Your organization also needs to approve AI data processing in its settings.Because a report summarizes a window of time, it stays useful on a low-volume server and can't flood a channel.diff --git a/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsxindex d6266e8dc26b..15d9ad877ecf 100644--- a/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx+++ b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx@@ -3,7 +3,7 @@ import { combineUrl, router } from 'kea-router'import { useEffect } from 'react'import { IconPlus, IconWarning } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonSwitch, Link } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonSwitch, LemonTag, Link } from '@posthog/lemon-ui'import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'@@ -30,7 +30,9 @@ import {MCPNotificationUseCase,} from './mcpAnalyticsNotificationsLogic'import { MCPNotificationExample, mcpNotificationExamplesLogic } from './mcpNotificationExamplesLogic'-import { MCPRecurringReports } from './MCPRecurringReports'+import { AI_REPORT_LIST_LIMIT } from './mcpRecurringReportsLogic'+import { NotificationTypesTable } from './NotificationTypesTable'+import { useRecurringReportRows } from './recurringReportRows'interface MCPUseCaseConfig {useCase: MCPNotificationUseCase@@ -162,6 +164,7 @@ export function MCPAnalyticsNotifications(): JSX.Element {const { notifications, notificationsLoaded, notificationsFailed } = useValues(mcpAnalyticsNotificationsLogic)const { loadNotifications } = useActions(mcpAnalyticsNotificationsLogic)const { examples } = useValues(mcpNotificationExamplesLogic)+ const reports = useRecurringReportRows()const { loadExamples } = useActions(mcpNotificationExamplesLogic)const addDisabledReason = useRestrictedArea({scope: RestrictionScope.Project,@@ -237,8 +240,32 @@ export function MCPAnalyticsNotifications(): JSX.Element {)return (- <div className="flex flex-col gap-6" data-attr="mcp-analytics-notifications">- <MCPRecurringReports />+ <div className="@container flex flex-col gap-6" data-attr="mcp-analytics-notifications">+ <section className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-1.5">+ <h2 className="m-0 text-base font-semibold">Recurring reports</h2>+ <LemonTag type="completion">Beta</LemonTag>+ </div>+ {reports.failed ? (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: reports.reload }}+ data-attr="mcp-analytics-recurring-reports-load-error"+ >+ We couldn't load your MCP reports. Please try again in a moment.+ </LemonBanner>+ ) : (+ <NotificationTypesTable rows={reports.rows} />+ )}+ {/* Say so rather than quietly dropping the tail — an invisible report is the bug this+ whole section exists to fix. */}+ {reports.truncated && (+ <p className="m-0 text-xs text-muted">+ Showing the first {AI_REPORT_LIST_LIMIT} reports.{' '}+ <Link to={urls.subscriptions()}>See all subscriptions</Link> for the rest.+ </p>+ )}+ </section><section className="flex flex-col gap-2"><h2 className="m-0 text-base font-semibold">Instant alerts</h2>diff --git a/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx b/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsxdeleted file mode 100644index 1f75e3483115..000000000000--- a/products/mcp_analytics/frontend/notifications/MCPRecurringReports.tsx+++ /dev/null@@ -1,194 +0,0 @@-import { useActions, useValues } from 'kea'-import { useEffect } from 'react'--import { IconCalendar, IconOpenSidebar, IconPlus } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonSwitch, LemonTag, Link } from '@posthog/lemon-ui'--import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'-import { TZLabel } from 'lib/components/TZLabel'-import { FEATURE_FLAGS } from 'lib/constants'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { urls } from 'scenes/urls'--import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'--import { AI_REPORT_LIST_LIMIT, mcpRecurringReportsLogic } from './mcpRecurringReportsLogic'-import { MCP_RECURRING_REPORTS, MCPRecurringReport, urlForRecurringReport } from './recurringReportDefinitions'--function SavedReportRow({ report }: { report: SubscriptionApi }): JSX.Element {- const { pendingToggleIds } = useValues(mcpRecurringReportsLogic)- const { toggleReportEnabled, deleteReport } = useActions(mcpRecurringReportsLogic)-- return (- <div className="flex items-center gap-2 rounded border p-2">- <div className="min-w-0 flex-1">- <Link to={urls.subscription(report.id)} className="truncate font-medium">- {report.title || 'Untitled report'}- </Link>- <div className="text-xs text-muted">- {report.summary}- {report.next_delivery_date && report.enabled ? (- <>- {' · next '}- <TZLabel time={report.next_delivery_date} />- </>- ) : null}- </div>- </div>- <LemonSwitch- checked={!!report.enabled}- onChange={() => toggleReportEnabled(report.id, !report.enabled)}- loading={!!pendingToggleIds[report.id]}- aria-label={`Enable ${report.title || 'report'}`}- />- <ConfirmDeleteButton- onDelete={() => deleteReport(report)}- disabledReason={- pendingToggleIds[report.id] ? 'Waiting for the enable/disable update to finish…' : undefined- }- data-attr="mcp-analytics-recurring-report-delete"- />- </div>- )-}--function ReportCard({- report,- enabled,- savedReports,-}: {- report: MCPRecurringReport- enabled: boolean- savedReports: SubscriptionApi[]-}): JSX.Element {- return (- <LemonCard hoverEffect={false} className="flex flex-col gap-2 p-3">- <div className="flex items-start justify-between gap-2">- <div className="min-w-0">- <div className="flex items-center gap-1.5">- <h3 className="m-0 text-sm font-semibold">{report.headline}</h3>- <LemonTag type="muted" size="small">- {report.frequency === 'daily' ? 'Daily' : 'Weekly'}- </LemonTag>- </div>- <p className="m-0 text-xs text-muted">{report.lead}</p>- </div>- {enabled && (- <LemonButton- type={savedReports.length > 0 ? 'secondary' : 'primary'}- size="xsmall"- icon={savedReports.length > 0 ? <IconPlus /> : <IconCalendar />}- to={urlForRecurringReport(report)}- data-attr={`mcp-analytics-recurring-report-${report.key}`}- >- {savedReports.length > 0 ? 'Add' : 'Set up'}- </LemonButton>- )}- </div>-- {/* The report itself is written by an LLM each run, so there's nothing faithful to preview.- Showing the question it asks is the honest version — and it's editable before saving. */}- <div className="rounded border bg-surface-primary p-2">- <div className="text-xs font-medium text-muted">What it asks</div>- <p className="m-0 mt-0.5 text-xs">{report.prompt}</p>- </div>-- {savedReports.length > 0 && (- <div className="flex flex-col gap-1">- {savedReports.map((saved) => (- <SavedReportRow key={saved.id} report={saved} />- ))}- </div>- )}- </LemonCard>- )-}--/**- * Recurring AI reports for the two questions that suit a digest better than a per-event ping: what- * agents keep asking for, and how the tools are holding up. Both are summaries over a window, so- * they stay useful on a quiet server and can't flood a channel the way a per-event alert can.- */-export function MCPRecurringReports(): JSX.Element {- const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')- const { reports, reportsLoaded, reportsFailed, reportsTruncated } = useValues(mcpRecurringReportsLogic)- const { loadReports } = useActions(mcpRecurringReportsLogic)-- // Loaded even without the feature flag: a project can hold reports created before the flag was- // turned off, and hiding them would repeat the problem this list exists to fix.- useEffect(() => {- loadReports()- }, [loadReports])-- // A saved report is tied back to the card that offers it by title, which is what the card's- // deep-link sets. Renaming one moves it to "Other MCP reports" rather than losing it.- const savedByTitle = (title: string): SubscriptionApi[] => reports.filter((saved) => saved.title === title)- const templateTitles = new Set(MCP_RECURRING_REPORTS.map((report) => report.title))- const otherReports = reports.filter((saved) => !saved.title || !templateTitles.has(saved.title))-- return (- <section className="flex flex-col gap-2">- <div className="flex flex-wrap items-center gap-1.5">- <h2 className="m-0 text-base font-semibold">Recurring reports</h2>- <LemonTag type="completion">Beta</LemonTag>- </div>- <p className="m-0 text-sm text-muted">- A written summary on a schedule, delivered to Slack or email. Best for the questions you want to think- about regularly rather than react to.- </p>-- {!aiSubscriptionsEnabled && (- <p className="m-0 text-xs text-muted">- AI reports are in early access.{' '}- <Link to={urls.featurePreview(FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT)}>- Turn them on for your account <IconOpenSidebar />- </Link>{' '}- to set one up.- </p>- )}-- {reportsFailed && (- <LemonBanner- type="error"- action={{ children: 'Try again', onClick: () => loadReports() }}- data-attr="mcp-analytics-recurring-reports-load-error"- >- We couldn't load your MCP reports. Please try again in a moment.- </LemonBanner>- )}-- {/* Say so rather than quietly dropping the tail — an invisible report is the bug this- whole section exists to fix. */}- {reportsTruncated && (- <p className="m-0 text-xs text-muted">- Showing the first {AI_REPORT_LIST_LIMIT} reports.{' '}- <Link to={urls.subscriptions()}>See all subscriptions</Link> for the rest.- </p>- )}-- <div className="grid gap-2 md:grid-cols-2">- {MCP_RECURRING_REPORTS.map((report) => (- <ReportCard- key={report.key}- report={report}- enabled={aiSubscriptionsEnabled}- savedReports={reportsLoaded ? savedByTitle(report.title) : []}- />- ))}- </div>-- {!reportsLoaded && !reportsFailed && <LemonSkeleton className="h-8 w-full" />}-- {/* Anything MCP-related the cards don't account for still needs a home, so it can't be- silently dropped from the list. */}- {otherReports.length > 0 && (- <LemonCard hoverEffect={false} className="flex flex-col gap-1 p-3">- <h3 className="m-0 text-sm font-semibold">Other MCP reports</h3>- {otherReports.map((saved) => (- <SavedReportRow key={saved.id} report={saved} />- ))}- </LemonCard>- )}- </section>- )-}diff --git a/products/mcp_analytics/frontend/notifications/NotificationTypesTable.test.ts b/products/mcp_analytics/frontend/notifications/NotificationTypesTable.test.tsnew file mode 100644index 000000000000..4555a7ab1608--- /dev/null+++ b/products/mcp_analytics/frontend/notifications/NotificationTypesTable.test.ts@@ -0,0 +1,17 @@+import { statusLabel } from './NotificationTypesTable'++describe('statusLabel', () => {+ it.each([+ [{ total: 0, enabled: 0, truncated: false }, 'Not set up'],+ [{ total: 1, enabled: 1, truncated: false }, 'On'],+ [{ total: 2, enabled: 2, truncated: false }, '2 on'],+ [{ total: 1, enabled: 0, truncated: false }, 'Paused'],+ [{ total: 3, enabled: 0, truncated: false }, '3 paused'],+ [{ total: 2, enabled: 1, truncated: false }, '1 of 2 on'],+ [{ total: 2, enabled: 1, truncated: true }, '1+ on'],+ [{ total: 2, enabled: 0, truncated: true }, '2+ paused'],+ [{ total: 0, enabled: 0, truncated: true }, 'Unknown'],+ ])('describes %j as %s', (counts, expected) => {+ expect(statusLabel(counts)).toBe(expected)+ })+})diff --git a/products/mcp_analytics/frontend/notifications/NotificationTypesTable.tsx b/products/mcp_analytics/frontend/notifications/NotificationTypesTable.tsxnew file mode 100644index 000000000000..79b51d26a0d7--- /dev/null+++ b/products/mcp_analytics/frontend/notifications/NotificationTypesTable.tsx@@ -0,0 +1,151 @@+import { useState } from 'react'++import { LemonSkeleton, LemonTable, LemonTag } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'++export type NotificationCadence = 'instant' | 'daily' | 'weekly'++const CADENCE_LABELS: Record<NotificationCadence, string> = {+ instant: 'Instant',+ daily: 'Daily',+ weekly: 'Weekly',+}++export interface SavedNotificationCounts {+ total: number+ enabled: number+ /** The list behind the counts was cut at its page limit, so both numbers are lower bounds. */+ truncated: boolean+}++export function countSaved(items: { enabled?: boolean | null }[], truncated: boolean): SavedNotificationCounts {+ return { total: items.length, enabled: items.filter((item) => item.enabled).length, truncated }+}++export interface NotificationTypeRow {+ key: string+ icon: JSX.Element+ headline: string+ lead: string+ tag?: JSX.Element+ cadence?: NotificationCadence+ /** Undefined until the list of configured notifications has loaded. */+ saved?: SavedNotificationCounts+ action?: JSX.Element+ preview?: JSX.Element+ savedRows: JSX.Element[]+}++export function statusLabel({ total, enabled, truncated }: SavedNotificationCounts): string {+ // A cut list cannot say a template has nothing: the match may sit past the page limit.+ if (truncated) {+ if (total === 0) {+ return 'Unknown'+ }+ return enabled > 0 ? `${enabled}+ on` : `${total}+ paused`+ }+ if (total === 0) {+ return 'Not set up'+ }+ if (enabled === total) {+ return total === 1 ? 'On' : `${total} on`+ }+ if (enabled === 0) {+ return total === 1 ? 'Paused' : `${total} paused`+ }+ return `${enabled} of ${total} on`+}++/**+ * Rows that already have something set up start expanded, so the active destinations are visible+ * without a click. When nothing is set up yet every row starts expanded instead, because the+ * details are the only way to judge what a notification would send. The user's own toggles then+ * take over.+ *+ * Below the `@2xl` container width the status column folds into the notification cell, so a scene+ * beside an open side panel keeps the action on screen instead of scrolling sideways.+ */+export function NotificationTypesTable({ rows }: { rows: NotificationTypeRow[] }): JSX.Element {+ const [expandedOverrides, setExpandedOverrides] = useState<Record<string, boolean>>({})+ const nothingSetUp = rows.every((row) => row.saved && row.saved.total === 0)++ return (+ <LemonTable+ dataSource={rows}+ rowKey="key"+ showHeader={false}+ data-attr="mcp-analytics-notification-types"+ columns={[+ {+ title: 'Notification',+ key: 'notification',+ className: 'min-w-64',+ render: (_, row) => (+ <div className="flex items-center gap-3 py-1">+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded bg-surface-secondary text-lg text-muted">+ {row.icon}+ </span>+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-semibold">{row.headline}</span>+ {row.tag}+ {row.cadence && (+ <LemonTag type="muted" size="small">+ {CADENCE_LABELS[row.cadence]}+ </LemonTag>+ )}+ </div>+ <div className="text-xs text-muted">{row.lead}</div>+ {row.saved && (+ <div className="mt-0.5 text-xs text-muted @2xl:hidden">+ {statusLabel(row.saved)}+ </div>+ )}+ </div>+ </div>+ ),+ },+ {+ title: 'Status',+ key: 'status',+ width: 0,+ className: '@max-2xl:hidden',+ render: (_, row) =>+ row.saved ? (+ <span className={cn('whitespace-nowrap', row.saved.total === 0 && 'text-muted')}>+ {statusLabel(row.saved)}+ </span>+ ) : (+ <LemonSkeleton className="h-4 w-16" />+ ),+ },+ {+ key: 'action',+ width: 0,+ align: 'right',+ render: (_, row) =>+ !row.saved ? (+ <LemonSkeleton className="h-8 w-24" />+ ) : row.action ? (+ <div className="flex justify-end whitespace-nowrap">{row.action}</div>+ ) : null,+ },+ ]}+ expandable={{+ rowExpandable: (row) => !!row.preview || row.savedRows.length > 0,+ isRowExpanded: (row) => expandedOverrides[row.key] ?? (nothingSetUp || (row.saved?.total ?? 0) > 0),+ onRowExpand: (row) => setExpandedOverrides((current) => ({ ...current, [row.key]: true })),+ onRowCollapse: (row) => setExpandedOverrides((current) => ({ ...current, [row.key]: false })),+ // pl-13 lines the details up with the headline text: the 8px cell padding, the 32px icon+ // tile and the 12px gap before the text.+ expandedRowRender: (row) => (+ <div className="flex max-w-2xl flex-col gap-3 py-3 pr-4 pl-13">+ {row.preview}+ {row.savedRows.length > 0 && <div className="divide-y rounded border">{row.savedRows}</div>}+ </div>+ ),+ }}+ />+ )+}diff --git a/products/mcp_analytics/frontend/notifications/RecurringReportDetails.tsx b/products/mcp_analytics/frontend/notifications/RecurringReportDetails.tsxnew file mode 100644index 000000000000..dcaeec8e5dea--- /dev/null+++ b/products/mcp_analytics/frontend/notifications/RecurringReportDetails.tsx@@ -0,0 +1,31 @@+import { useState } from 'react'++import { Link } from '@posthog/lemon-ui'++/**+ * The report itself is written by an LLM each run, so there is nothing faithful to preview. The+ * coverage list says what a delivery answers; the question handed to the model stays behind a+ * disclosure because it is written for the model, not the reader, and is editable before saving.+ */+export function RecurringReportDetails({ covers, prompt }: { covers: string[]; prompt: string }): JSX.Element {+ const [promptShown, setPromptShown] = useState(false)++ return (+ <div className="flex flex-col gap-1">+ <div className="text-xs font-medium text-muted">What it covers</div>+ <ul className="m-0 list-disc pl-4 text-sm">+ {covers.map((line) => (+ <li key={line}>{line}</li>+ ))}+ </ul>+ <Link+ className="text-xs"+ onClick={() => setPromptShown(!promptShown)}+ data-attr="mcp-analytics-recurring-report-toggle-prompt"+ >+ {promptShown ? 'Hide the question it asks' : 'Show the question it asks'}+ </Link>+ {promptShown && <p className="m-0 text-sm text-muted">{prompt}</p>}+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/notifications/SavedNotificationRow.tsx b/products/mcp_analytics/frontend/notifications/SavedNotificationRow.tsxnew file mode 100644index 000000000000..06a95941176e--- /dev/null+++ b/products/mcp_analytics/frontend/notifications/SavedNotificationRow.tsx@@ -0,0 +1,53 @@+import { ReactNode } from 'react'++import { LemonSwitch, Link } from '@posthog/lemon-ui'++import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'++interface SavedNotificationRowProps {+ icon?: JSX.Element+ name: string+ to: string+ summary?: ReactNode+ enabled: boolean+ onToggle: (enabled: boolean) => void+ toggleLoading: boolean+ toggleDisabled?: boolean+ onDelete: () => void+ deleteDisabledReason?: string+ deleteDataAttr: string+}++export function SavedNotificationRow({+ icon,+ name,+ to,+ summary,+ enabled,+ onToggle,+ toggleLoading,+ toggleDisabled,+ onDelete,+ deleteDisabledReason,+ deleteDataAttr,+}: SavedNotificationRowProps): JSX.Element {+ return (+ <div className="flex items-center gap-3 px-4 py-2">+ {icon}+ <div className="min-w-0 flex-1">+ <Link to={to} className="block truncate text-sm font-medium">+ {name}+ </Link>+ {summary ? <div className="truncate text-xs text-muted">{summary}</div> : null}+ </div>+ <LemonSwitch+ checked={enabled}+ onChange={() => onToggle(!enabled)}+ loading={toggleLoading}+ disabled={toggleDisabled}+ aria-label={`Enable ${name}`}+ />+ <ConfirmDeleteButton onDelete={onDelete} disabledReason={deleteDisabledReason} data-attr={deleteDataAttr} />+ </div>+ )+}diff --git a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.tsindex ba8b1c04846c..b26282551f7b 100644--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.test.ts@@ -9,6 +9,7 @@ import { subscriptionsList } from 'products/subscriptions/frontend/generated/apiimport type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'import { isMCPRecurringReport, mcpRecurringReportsLogic } from './mcpRecurringReportsLogic'+import { MCP_RECURRING_REPORTS } from './recurringReportDefinitions'jest.mock('lib/utils/deleteWithUndo', () => ({ deleteWithUndo: jest.fn() }))jest.mock('products/subscriptions/frontend/generated/api', () => ({@@ -72,6 +73,20 @@ describe('mcpRecurringReportsLogic', () => {expect(isMCPRecurringReport({ prompt })).toBe(expected)})+ it('groups saved reports by template title and keeps renamed or untitled ones under other', async () => {+ listReturns([+ makeReport(1, { title: MCP_RECURRING_REPORTS[0].title }),+ makeReport(2, { title: 'Renamed report' }),+ makeReport(3, { title: '' }),+ ])++ await expectLogic(logic, () => logic.actions.loadReports()).toFinishAllListeners()++ expect(logic.values.reportsByTemplateTitle[MCP_RECURRING_REPORTS[0].title].map((r) => r.id)).toEqual([1])+ expect(logic.values.reportsByTemplateTitle[MCP_RECURRING_REPORTS[1].title]).toEqual([])+ expect(logic.values.otherReports.map((r) => r.id)).toEqual([2, 3])+ })+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.tsindex 9d88513e8fc7..58bf0c9bc8f1 100644--- a/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts+++ b/products/mcp_analytics/frontend/notifications/mcpRecurringReportsLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'+import { actions, kea, listeners, MakeLogicType, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'@@ -9,6 +9,8 @@ import { toggleSubscriptionEnabled } from 'products/subscriptions/frontend/compoimport { subscriptionsList } from 'products/subscriptions/frontend/generated/api'import { SubscriptionApi, SubscriptionsListResourceType } from 'products/subscriptions/frontend/generated/api.schemas'+import { MCP_RECURRING_REPORTS } from './recurringReportDefinitions'+// A ceiling on what one tab render will pull. The server-side `search` below already narrows to MCP// reports, so reaching this means a project with hundreds of them — at which point the list is the// wrong tool anyway and `reportsTruncated` says so rather than quietly dropping the tail.@@ -33,8 +35,10 @@ 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 {+ otherReports: SubscriptionApi[]pendingToggleIds: Record<number, true>reports: SubscriptionApi[]+ reportsByTemplateTitle: Record<string, SubscriptionApi[]>reportsFailed: booleanreportsLoaded: booleanreportsLoading: boolean@@ -82,11 +86,23 @@ export interface mcpRecurringReportsLogicActions {}}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface mcpRecurringReportsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ reportsByTemplateTitle: (reports: SubscriptionApi[]) => Record<string, SubscriptionApi[]>+ otherReports: (reports: SubscriptionApi[]) => SubscriptionApi[]+ }+}+export type mcpRecurringReportsLogicType = MakeLogicType<mcpRecurringReportsLogicValues,- mcpRecurringReportsLogicActions+ mcpRecurringReportsLogicActions,+ Record<string, any>,+ mcpRecurringReportsLogicMeta>+const TEMPLATE_TITLES = new Set(MCP_RECURRING_REPORTS.map((report) => report.title))+export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([path(['products', 'mcp_analytics', 'frontend', 'notifications', 'mcpRecurringReportsLogic']),actions({@@ -159,6 +175,25 @@ export const mcpRecurringReportsLogic = kea<mcpRecurringReportsLogicType>([},],}),+ selectors({+ // A saved report is tied back to the template that offers it by title, which is what the+ // template's deep link sets. Renaming one moves it to "other" rather than losing it.+ reportsByTemplateTitle: [+ (s) => [s.reports],+ (reports: SubscriptionApi[]): Record<string, SubscriptionApi[]> =>+ Object.fromEntries(+ MCP_RECURRING_REPORTS.map((report) => [+ report.title,+ reports.filter((saved) => saved.title === report.title),+ ])+ ),+ ],+ otherReports: [+ (s) => [s.reports],+ (reports: SubscriptionApi[]): SubscriptionApi[] =>+ reports.filter((saved) => !saved.title || !TEMPLATE_TITLES.has(saved.title)),+ ],+ }),listeners(({ actions, values }) => ({toggleReportEnabled: async ({ reportId, enabled }) => {if (values.pendingToggleIds[reportId]) {diff --git a/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts b/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.tsindex 0172ae35944c..a1ce60482d15 100644--- a/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts+++ b/products/mcp_analytics/frontend/notifications/recurringReportDefinitions.ts@@ -13,6 +13,8 @@ export interface MCPRecurringReport {* $mcp_* properties explicitly so it queries the right ones rather than guessing.*/prompt: string+ /** What a delivery covers, in the reader's terms, one short line each. */+ covers: string[]}export const MCP_RECURRING_REPORTS: MCPRecurringReport[] = [@@ -34,6 +36,12 @@ export const MCP_RECURRING_REPORTS: MCPRecurringReport[] = ['Call out intents that are new compared with previous weeks, and finish with the single','change to our tools that would help the most agents.',].join(' '),+ covers: [+ "Agent goals grouped and ranked by how often they came up, quoted in the agents' own words",+ 'The share of each goal that ended in a failed tool call',+ 'Goals that are new compared with previous weeks',+ 'One change to your tools that would help the most agents',+ ],},{key: 'tool-health',@@ -51,6 +59,12 @@ export const MCP_RECURRING_REPORTS: MCPRecurringReport[] = ['Highlight tools whose error rate or latency is clearly worse than the weeks before,','and skip sections where nothing notable happened.',].join(' '),+ covers: [+ 'Total calls and calls per tool',+ 'Error rate, the most common error types and example messages',+ 'p95 latency per tool',+ 'Tools whose errors or latency got clearly worse than the weeks before',+ ],},]diff --git a/products/mcp_analytics/frontend/notifications/recurringReportRows.tsx b/products/mcp_analytics/frontend/notifications/recurringReportRows.tsxnew file mode 100644index 000000000000..4d573197bc1d--- /dev/null+++ b/products/mcp_analytics/frontend/notifications/recurringReportRows.tsx@@ -0,0 +1,142 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconCalendar, IconOpenSidebar, IconPlus } from '@posthog/icons'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'+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 { mcpRecurringReportsLogic } from './mcpRecurringReportsLogic'+import { countSaved, NotificationTypeRow } from './NotificationTypesTable'+import { MCP_RECURRING_REPORTS, MCPRecurringReport, urlForRecurringReport } from './recurringReportDefinitions'+import { RecurringReportDetails } from './RecurringReportDetails'+import { SavedNotificationRow } from './SavedNotificationRow'++function SavedReportRow({ report }: { report: SubscriptionApi }): JSX.Element {+ const { pendingToggleIds } = useValues(mcpRecurringReportsLogic)+ const { toggleReportEnabled, deleteReport } = useActions(mcpRecurringReportsLogic)++ return (+ <SavedNotificationRow+ name={report.title || 'Untitled report'}+ to={urls.subscription(report.id)}+ summary={+ <>+ {report.summary}+ {report.next_delivery_date && report.enabled ? (+ <>+ {' · next '}+ <TZLabel time={report.next_delivery_date} />+ </>+ ) : null}+ </>+ }+ enabled={!!report.enabled}+ onToggle={(enabled) => toggleReportEnabled(report.id, enabled)}+ toggleLoading={!!pendingToggleIds[report.id]}+ onDelete={() => deleteReport(report)}+ deleteDisabledReason={+ pendingToggleIds[report.id] ? 'Waiting for the enable/disable update to finish…' : undefined+ }+ deleteDataAttr="mcp-analytics-recurring-report-delete"+ />+ )+}++// `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 {+ if (!aiSubscriptionsEnabled) {+ return (+ <LemonButton+ type="secondary"+ size="small"+ sideIcon={<IconOpenSidebar />}+ to={urls.featurePreview(FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT)}+ data-attr="mcp-analytics-recurring-report-early-access"+ >+ Turn on early access+ </LemonButton>+ )+ }+ return (+ <LemonButton+ type={mayExist ? 'secondary' : 'primary'}+ size="small"+ icon={mayExist ? <IconPlus /> : undefined}+ to={urlForRecurringReport(report)}+ data-attr={`mcp-analytics-recurring-report-${report.key}`}+ >+ {mayExist ? 'Add' : 'Set up'}+ </LemonButton>+ )+}++export interface RecurringReportRows {+ rows: NotificationTypeRow[]+ loaded: boolean+ failed: boolean+ truncated: boolean+ reload: () => void+}++/**+ * Recurring AI reports for the two questions that suit a digest better than a per-event ping: what+ * agents keep asking for, and how the tools are holding up. Both are summaries over a window, so+ * they stay useful on a quiet server and can't flood a channel the way a per-event alert can.+ */+export function useRecurringReportRows(): RecurringReportRows {+ const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')+ const { receivedFeatureFlags } = useValues(featureFlagLogic)+ const { reportsByTemplateTitle, otherReports, reportsLoaded, reportsFailed, reportsTruncated } =+ useValues(mcpRecurringReportsLogic)+ const { loadReports } = useActions(mcpRecurringReportsLogic)+ // An unresolved flag reads as off, so the row would offer "Turn on early access" to someone who+ // already has it until the flags land.+ const ready = reportsLoaded && receivedFeatureFlags++ // Loaded even without the feature flag: a project can hold reports created before the flag was+ // turned off, and hiding them would repeat the problem this list exists to fix.+ useEffect(() => {+ loadReports()+ }, [loadReports])++ const rows: NotificationTypeRow[] = MCP_RECURRING_REPORTS.map((report) => {+ const saved = ready ? (reportsByTemplateTitle[report.title] ?? []) : []+ return {+ key: `report-${report.key}`,+ icon: <IconCalendar />,+ headline: report.headline,+ lead: report.lead,+ tag: (+ <LemonTag type="completion" size="small">+ Beta+ </LemonTag>+ ),+ cadence: report.frequency,+ saved: ready ? countSaved(saved, reportsTruncated) : undefined,+ action: reportAction(report, saved.length > 0 || reportsTruncated, aiSubscriptionsEnabled),+ preview: <RecurringReportDetails covers={report.covers} prompt={report.prompt} />,+ savedRows: saved.map((report) => <SavedReportRow key={report.id} report={report} />),+ }+ })++ if (otherReports.length > 0) {+ rows.push({+ key: 'report-other',+ icon: <IconCalendar />,+ headline: 'Other MCP reports',+ lead: 'Reports that mention MCP but do not match a template above.',+ saved: countSaved(otherReports, reportsTruncated),+ savedRows: otherReports.map((report) => <SavedReportRow key={report.id} report={report} />),+ })+ }++ return { rows, loaded: reportsLoaded, failed: reportsFailed, truncated: reportsTruncated, reload: loadReports }+}