: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(product-analytics): add notifications tab to saved insights (#76674)
Joe Martin32352cb2add4
diff --git a/products/mcp_analytics/frontend/notifications/MCPNotificationPreview.tsx b/frontend/src/scenes/hog-functions/sub-templates/NotificationSlackPreview.tsxsimilarity index 89%rename from products/mcp_analytics/frontend/notifications/MCPNotificationPreview.tsxrename to frontend/src/scenes/hog-functions/sub-templates/NotificationSlackPreview.tsxindex bdd691063b51..4e95cdb9907d 100644--- a/products/mcp_analytics/frontend/notifications/MCPNotificationPreview.tsx+++ b/frontend/src/scenes/hog-functions/sub-templates/NotificationSlackPreview.tsx@@ -22,8 +22,8 @@ function renderSlackMarkup(message: string): JSX.Element[] {})}-export interface MCPNotificationPreviewProps {- /** Slack mrkdwn, as produced by `mcpNotificationPreviewMessage` */+export interface NotificationSlackPreviewProps {+ /** Slack mrkdwn, as produced by a sub-template's preview-message helper */message: stringbuttonLabel: string/** Where the interpolated values came from — the project's own events, or sample copy. */@@ -35,7 +35,11 @@ export interface MCPNotificationPreviewProps {* channel before connecting one. Deliberately static: the copy comes from the real template, but* the values are samples.*/-export function MCPNotificationPreview({ message, buttonLabel, caption }: MCPNotificationPreviewProps): JSX.Element {+export function NotificationSlackPreview({+ message,+ buttonLabel,+ caption,+}: NotificationSlackPreviewProps): JSX.Element {return (<div className="flex gap-2 rounded border bg-surface-primary p-2"><div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-surface-secondary">diff --git a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.tsindex 60ee90e20692..50c90afe416c 100644--- a/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts+++ b/frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts@@ -61,6 +61,19 @@ function mcpFailedToolCallEvent(errorType?: string): CyclotronJobFilterEvents {return { id: '$mcp_tool_call', type: 'events', properties }}+// The page a rageclick happened on: $pathname when posthog-js set it, else the full URL.+const PA_RAGECLICK_PAGE_EXPR = 'event.properties.$pathname ? event.properties.$pathname : event.properties.$current_url'++// How long rageclick alerts stay deduped — same trade-off as the MCP TTL above.+const PA_ALERT_MASKING_TTL_SECONDS = 30 * 60++// A constant key, deliberately not per-page. $pathname/$current_url are attacker-controlled+// (anyone holding the public project token can send $rageclick events), so a per-page bucket+// would let a sender mint a fresh bucket per event and flood the destination. The constant+// bounds delivery to one message per function per TTL; the message still names the page that+// triggered it, and the replay list has the rest.+const PA_RAGECLICK_MASKING_HASH = 'rageclick'+export const HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES: Record<HogFunctionSubTemplateIdType,Pick<HogFunctionSubTemplateType, 'sub_template_id' | 'type' | 'context_id'> &@@ -100,6 +113,16 @@ export const HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES: Record<// per tool per interval still surfaces each distinct breakage.masking: { hash: MCP_ALERT_MASKING_HASH, ttl: MCP_ALERT_MASKING_TTL_SECONDS, threshold: null },},+ 'pa-rageclick': {+ sub_template_id: 'pa-rageclick',+ type: 'destination',+ context_id: 'standard',+ filters: { events: [{ id: '$rageclick', type: 'events' }] },+ // A broken element gets rage clicked by every visitor who hits it, so an undeduped alert+ // would post a message per event. Deduped globally (see PA_RAGECLICK_MASKING_HASH for why+ // not per-page): at most one message per interval.+ masking: { hash: PA_RAGECLICK_MASKING_HASH, ttl: PA_ALERT_MASKING_TTL_SECONDS, threshold: null },+ },'activity-log': {sub_template_id: 'activity-log',type: 'internal_destination',@@ -429,6 +452,64 @@ export function mcpNotificationPreviewMessage(values: Record<MCPMessageField, stconst MCP_TOOL_ERROR_SLACK_MESSAGE = mcpToolFailureMessage(hogFieldRenderer(slackEscapeExpr), '*')const MCP_TOOL_ERROR_MARKDOWN_MESSAGE = mcpToolFailureMessage(hogFieldRenderer(markdownEscapeExpr), '**')+// $pathname, $current_url and $browser are producer-controlled just like the $mcp_* properties, so+// the rageclick message reuses the same escaping and length bounds.+const PA_FIELD_MAX_LENGTH = 200++/** The producer-controlled values a rageclick notification message interpolates. */+export type PAMessageField = 'page' | 'browser'+type PAFieldRenderer = (field: PAMessageField) => string++function paHogFieldRenderer(escape: ChatEscaper): PAFieldRenderer {+ return (field) => {+ switch (field) {+ case 'page':+ return `{${escape(PA_RAGECLICK_PAGE_EXPR, PA_FIELD_MAX_LENGTH)}}`+ case 'browser':+ return `{${escape('event.properties.$browser', PA_FIELD_MAX_LENGTH)}}`+ }+ }+}++// Same single-source pattern as mcpToolFailureMessage: the Hog templates and the in-app preview+// render the one copy string, so the preview can't drift from what gets delivered.+function paRageclickMessage(field: PAFieldRenderer, bold: string): string {+ return (+ `Users are rage clicking on ${bold}${field('page')}${bold} ` ++ `(browser: ${field('browser')}). The element they're clicking isn't responding.`+ )+}++export type PANotificationSubTemplateId = 'pa-rageclick'++export const PA_NOTIFICATION_BUTTON_LABELS: Record<PANotificationSubTemplateId, string> = {+ 'pa-rageclick': 'Watch session replay',+}++/** See MCP_MESSAGE_FIELD_LIMITS — the caps a preview built from real event values must apply. */+export const PA_MESSAGE_FIELD_LIMITS: Record<PAMessageField, number> = {+ page: PA_FIELD_MAX_LENGTH,+ browser: PA_FIELD_MAX_LENGTH,+}++/** See mcpNotificationPreviewMessage — the Slack message rendered with sample values. */+export function paNotificationPreviewMessage(values: Record<PAMessageField, string>): string {+ const field: PAFieldRenderer = (name) => values[name]+ return paRageclickMessage(field, '*')+}++const PA_RAGECLICK_SLACK_MESSAGE = paRageclickMessage(paHogFieldRenderer(slackEscapeExpr), '*')+const PA_RAGECLICK_MARKDOWN_MESSAGE = paRageclickMessage(paHogFieldRenderer(markdownEscapeExpr), '**')++// Session IDs are producer-controlled too: cap the encoded form like the MCP tool link does (a+// truncated ID would resolve to nothing, and a lone surrogate would make encodeURLComponent throw),+// falling back to the replay home page when the ID is missing or oversized.+const PA_ENCODED_SESSION_EXPR = 'encodeURLComponent(concat(event.properties.$session_id))'+const PA_RAGECLICK_LINK =+ `{project.url}/replay` ++ `{length(${PA_ENCODED_SESSION_EXPR}) > 0 and length(${PA_ENCODED_SESSION_EXPR}) <= ${MCP_URL_ENCODED_TOOL_BUDGET}` ++ ` ? concat('/', ${PA_ENCODED_SESSION_EXPR}) : '/home'}`+const MCP_ENCODED_EFFECTIVE_TOOL_EXPR = `encodeURLComponent(concat(${MCP_EFFECTIVE_TOOL_EXPR}))`// Deep-links to the failing tool, falling back to the tool list when the encoded name would// blow the Discord budget (see MCP_URL_ENCODED_TOOL_BUDGET). project.url stays a plain@@ -438,7 +519,7 @@ const MCP_TOOL_ERROR_LINK =`{length(${MCP_ENCODED_EFFECTIVE_TOOL_EXPR}) <= ${MCP_URL_ENCODED_TOOL_BUDGET}` +` ? concat('/', ${MCP_ENCODED_EFFECTIVE_TOOL_EXPR}) : ''}`-interface MCPNotificationVariantsOptions {+interface NotificationVariantsOptions {subTemplateId: HogFunctionSubTemplateIdTypenameSuffix: stringdescription: string@@ -449,7 +530,7 @@ interface MCPNotificationVariantsOptions {slackButton: { url: string; label: string }}-function mcpNotificationVariants({+function notificationVariants({subTemplateId,nameSuffix,description,@@ -458,7 +539,7 @@ function mcpNotificationVariants({slackFallbackText,markdownMessage,slackButton,-}: MCPNotificationVariantsOptions): HogFunctionSubTemplateType[] {+}: NotificationVariantsOptions): HogFunctionSubTemplateType[] {const commonProperties = HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES[subTemplateId]return [@@ -514,7 +595,7 @@ function mcpNotificationVariants({}export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, HogFunctionSubTemplateType[]> = {- 'mcp-tool-error': mcpNotificationVariants({+ 'mcp-tool-error': notificationVariants({subTemplateId: 'mcp-tool-error',nameSuffix: 'when an MCP tool call fails',description: 'Know the moment agents hit an error on one of your tools',@@ -524,6 +605,16 @@ export const HOG_FUNCTION_SUB_TEMPLATES: Record<HogFunctionSubTemplateIdType, HomarkdownMessage: `${MCP_TOOL_ERROR_MARKDOWN_MESSAGE}\n\n${MCP_TOOL_ERROR_LINK}`,slackButton: { url: MCP_TOOL_ERROR_LINK, label: MCP_NOTIFICATION_BUTTON_LABELS['mcp-tool-error'] },}),+ 'pa-rageclick': notificationVariants({+ subTemplateId: 'pa-rageclick',+ nameSuffix: 'when users rage click',+ description: "Know when users repeatedly click something that isn't working",+ webhookDescription: 'Send rage click events to your own endpoint',+ slackMessage: PA_RAGECLICK_SLACK_MESSAGE,+ slackFallbackText: 'Users are rage clicking',+ markdownMessage: `${PA_RAGECLICK_MARKDOWN_MESSAGE}\n\n${PA_RAGECLICK_LINK}`,+ slackButton: { url: PA_RAGECLICK_LINK, label: PA_NOTIFICATION_BUTTON_LABELS['pa-rageclick'] },+ }),'survey-response': [{...HOG_FUNCTION_SUB_TEMPLATE_COMMON_PROPERTIES['survey-response'],diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsxindex 46c651ac5f3b..e5079726cb45 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx@@ -49,6 +49,9 @@ import {export * from './insightTypesMetadata'+import { ProductAnalyticsNotifications } from 'products/product_analytics/frontend/notifications/ProductAnalyticsNotifications'+import { productAnalyticsNotificationsLogic } from 'products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic'+import { isDraftInsightRow } from './draftInsight'import { DraftInsightMoreMenu, DraftInsightNameCell } from './DraftInsightRow'import { QUERY_TYPES_METADATA } from './insightTypesMetadata'@@ -101,6 +104,7 @@ export function SavedInsights(): JSX.Element {} = useValues(savedInsightsLogic)const { currentProjectId } = useValues(projectLogic)+ const { notificationCount } = useValues(productAnalyticsNotificationsLogic)const summarizeInsight = useSummarizeInsight()const { tab } = filters@@ -339,12 +343,27 @@ export function SavedInsights(): JSX.Element {{ key: SavedInsightsTabs.All, label: 'All insights' },{ key: SavedInsightsTabs.Yours, label: 'My insights' },{ key: SavedInsightsTabs.Alerts, label: 'Alerts' },+ {+ key: SavedInsightsTabs.Notifications,+ label: (+ <span className="flex items-center gap-1.5">+ Notifications+ {notificationCount > 0 && (+ <LemonTag type="completion" size="small">+ {notificationCount}+ </LemonTag>+ )}+ </span>+ ),+ },{ key: SavedInsightsTabs.History, label: 'History' },]}sceneInset/>- {tab === SavedInsightsTabs.History ? (+ {tab === SavedInsightsTabs.Notifications ? (+ <ProductAnalyticsNotifications />+ ) : tab === SavedInsightsTabs.History ? (<ActivityLog scope={ActivityScope.INSIGHT} />) : (<>diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 751173337d0f..60fe086bba5c 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1088,6 +1088,7 @@ export enum SavedInsightsTabs {Yours = 'yours',History = 'history',Alerts = 'alerts',+ Notifications = 'notifications',}export enum ReplayTabs {@@ -7267,6 +7268,7 @@ export type HogFunctionSubTemplateIdType =| 'early-access-feature-enrollment'| 'survey-response'| 'mcp-tool-error'+ | 'pa-rageclick'| 'activity-log'| 'feature-flag-change'| 'error-tracking-issue-created'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 67493fac882b..66c791009c28 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3847,6 +3847,9 @@ importers:'@testing-library/react':specifier: '*'+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))products/product_tours: {}diff --git a/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsxindex fd2dc42ea662..d6266e8dc26b 100644--- a/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx+++ b/products/mcp_analytics/frontend/notifications/MCPAnalyticsNotifications.tsx@@ -13,6 +13,7 @@ import { urlForHogFunction } from 'scenes/hog-functions/list/HogFunctionsList'import { NewNotificationDialog } from 'scenes/hog-functions/list/NewNotificationDialog'import { newNotificationDialogLogic } from 'scenes/hog-functions/list/newNotificationDialogLogic'import { getNotificationDescription } from 'scenes/hog-functions/list/notificationDescription'+import { NotificationSlackPreview } from 'scenes/hog-functions/sub-templates/NotificationSlackPreview'import {MCP_NOTIFICATION_BUTTON_LABELS,MCPMessageField,@@ -29,7 +30,6 @@ import {MCPNotificationUseCase,} from './mcpAnalyticsNotificationsLogic'import { MCPNotificationExample, mcpNotificationExamplesLogic } from './mcpNotificationExamplesLogic'-import { MCPNotificationPreview } from './MCPNotificationPreview'import { MCPRecurringReports } from './MCPRecurringReports'interface MCPUseCaseConfig {@@ -141,7 +141,7 @@ function UseCaseCard({ config, notifications, onAdd, addDisabledReason, example</LemonButton></div>- <MCPNotificationPreview+ <NotificationSlackPreviewmessage={mcpNotificationPreviewMessage(example ?? config.sample)}buttonLabel={MCP_NOTIFICATION_BUTTON_LABELS[config.subTemplateId]}caption={example ? config.realCaption : 'Example'}diff --git a/products/product_analytics/frontend/notifications/ProductAnalyticsNotifications.tsx b/products/product_analytics/frontend/notifications/ProductAnalyticsNotifications.tsxnew file mode 100644index 000000000000..a8b5291e3310--- /dev/null+++ b/products/product_analytics/frontend/notifications/ProductAnalyticsNotifications.tsx@@ -0,0 +1,287 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconCursor, IconPlus, IconWarning } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonCard, LemonSkeleton, LemonSwitch, Link } from '@posthog/lemon-ui'++import { ConfirmDeleteButton } from 'lib/components/ConfirmDeleteButton'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { OrganizationMembershipLevel } from 'lib/constants'+import { HogFunctionIcon } from 'scenes/hog-functions/configuration/HogFunctionIcon'+import { urlForHogFunction } from 'scenes/hog-functions/list/HogFunctionsList'+import { NewNotificationDialog } from 'scenes/hog-functions/list/NewNotificationDialog'+import { newNotificationDialogLogic } from 'scenes/hog-functions/list/newNotificationDialogLogic'+import { getNotificationDescription } from 'scenes/hog-functions/list/notificationDescription'+import { NotificationSlackPreview } from 'scenes/hog-functions/sub-templates/NotificationSlackPreview'+import {+ PA_NOTIFICATION_BUTTON_LABELS,+ PAMessageField,+ PANotificationSubTemplateId,+ paNotificationPreviewMessage,+} from 'scenes/hog-functions/sub-templates/sub-templates'+import { urls } from 'scenes/urls'++import { HogFunctionType, SavedInsightsTabs } from '~/types'++import {+ PANotificationExample,+ productAnalyticsNotificationExamplesLogic,+} from './productAnalyticsNotificationExamplesLogic'+import {+ getPANotificationUseCase,+ PANotificationUseCase,+ productAnalyticsNotificationsLogic,+} from './productAnalyticsNotificationsLogic'+import { ProductAnalyticsRecurringReports } from './ProductAnalyticsRecurringReports'++interface PAUseCaseConfig {+ useCase: PANotificationUseCase+ subTemplateId: PANotificationSubTemplateId+ icon: JSX.Element+ headline: string+ lead: string+ dialogTitle: string+ /** Shown until the project's own latest event loads; the copy always comes from the template. */+ sample: Record<PAMessageField, string>+ /** Caption for a preview built from the project's own event. */+ realCaption: string+}++const USE_CASES: PAUseCaseConfig[] = [+ {+ useCase: 'rageclick',+ subTemplateId: 'pa-rageclick',+ icon: <IconCursor />,+ headline: 'Users are rage clicking',+ lead: 'Which page, which browser, and a link to the session replay.',+ dialogTitle: 'Notify me about rage clicks',+ sample: {+ page: '/pricing',+ browser: 'Chrome',+ },+ realCaption: 'Your most recent',+ },+]++function NotificationRow({ notification }: { notification: HogFunctionType }): JSX.Element {+ const { notificationsLoading, pendingToggleIds } = useValues(productAnalyticsNotificationsLogic)+ const { toggleNotificationEnabled, deleteNotification } = useActions(productAnalyticsNotificationsLogic)++ const description = getNotificationDescription(notification)++ return (+ <div className="flex items-center gap-2 rounded border p-2">+ <HogFunctionIcon src={notification.icon_url} size="small" />+ <div className="min-w-0 flex-1">+ <Link+ to={urlForHogFunction(notification, urls.savedInsights(SavedInsightsTabs.Notifications))}+ className="font-medium truncate"+ >+ {notification.name}+ </Link>+ {description ? <div className="text-xs text-muted truncate">{description}</div> : null}+ </div>+ <LemonSwitch+ checked={notification.enabled}+ onChange={() => toggleNotificationEnabled(notification.id, !notification.enabled)}+ loading={!!pendingToggleIds[notification.id]}+ // Refresh in flight: a mutation started now could be clobbered by the stale response+ disabled={notificationsLoading}+ aria-label={`Enable ${notification.name}`}+ />+ <ConfirmDeleteButton+ onDelete={() => deleteNotification(notification)}+ disabledReason={+ notificationsLoading+ ? 'Refreshing notifications…'+ : pendingToggleIds[notification.id]+ ? 'Waiting for the enable/disable update to finish…'+ : undefined+ }+ data-attr="product-analytics-notification-delete"+ />+ </div>+ )+}++interface UseCaseCardProps {+ config: PAUseCaseConfig+ notifications: HogFunctionType[]+ onAdd: () => void+ addDisabledReason?: string+ /** The project's own latest event for this use case, once it has loaded. */+ example?: PANotificationExample+}++function UseCaseCard({ config, notifications, onAdd, addDisabledReason, example }: UseCaseCardProps): 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="flex min-w-0 items-start gap-1.5">+ <span className="mt-0.5 shrink-0 text-muted">{config.icon}</span>+ <div className="min-w-0">+ <h3 className="m-0 text-sm font-semibold">{config.headline}</h3>+ <p className="m-0 text-xs text-muted">{config.lead}</p>+ </div>+ </div>+ <LemonButton+ type={notifications.length > 0 ? 'secondary' : 'primary'}+ size="xsmall"+ icon={<IconPlus />}+ onClick={onAdd}+ disabledReason={addDisabledReason}+ data-attr={`product-analytics-add-notification-${config.useCase}`}+ >+ {notifications.length > 0 ? 'Add' : 'Notify me'}+ </LemonButton>+ </div>++ <NotificationSlackPreview+ message={paNotificationPreviewMessage(example ?? config.sample)}+ buttonLabel={PA_NOTIFICATION_BUTTON_LABELS[config.subTemplateId]}+ caption={example ? config.realCaption : 'Example'}+ />++ {notifications.length > 0 && (+ <div className="flex flex-col gap-1">+ {notifications.map((notification) => (+ <NotificationRow key={notification.id} notification={notification} />+ ))}+ </div>+ )}+ </LemonCard>+ )+}++/** Threshold alerts are their own product (per-insight), so this card links out instead of duplicating them. */+function InsightAlertsCard(): 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="flex min-w-0 items-start gap-1.5">+ <span className="mt-0.5 shrink-0 text-muted">+ <IconWarning />+ </span>+ <div className="min-w-0">+ <h3 className="m-0 text-sm font-semibold">An insight crosses a threshold</h3>+ <p className="m-0 text-xs text-muted">+ Set a threshold on any insight and get a message when it's breached.+ </p>+ </div>+ </div>+ <LemonButton+ type="secondary"+ size="xsmall"+ to={urls.alerts()}+ data-attr="product-analytics-notifications-insight-alerts"+ >+ Manage alerts+ </LemonButton>+ </div>+ </LemonCard>+ )+}++export function ProductAnalyticsNotifications(): JSX.Element {+ const { notifications, notificationsLoaded, notificationsFailed } = useValues(productAnalyticsNotificationsLogic)+ const { loadNotifications } = useActions(productAnalyticsNotificationsLogic)+ const { examples } = useValues(productAnalyticsNotificationExamplesLogic)+ const { loadExamples } = useActions(productAnalyticsNotificationExamplesLogic)+ const addDisabledReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: OrganizationMembershipLevel.Admin,+ })++ useEffect(() => {+ loadNotifications()+ // The previews render sample copy straight away and upgrade to the project's own events when+ // this lands, so there's deliberately no loading state to wait on.+ loadExamples()+ }, [loadNotifications, loadExamples])++ const onCreated = (): void => {+ loadNotifications()+ }++ // One dialog logic per use case, called in a fixed order so the hook calls stay stable.+ const { openDialog: openRageclickDialog } = useActions(+ newNotificationDialogLogic({ subTemplateId: 'pa-rageclick', onCreated })+ )+ const openDialogFor: Record<PANotificationSubTemplateId, () => void> = {+ 'pa-rageclick': openRageclickDialog,+ }++ // Anything the filters matched but we can't classify still needs a home, so it can't be+ // silently dropped from the list.+ const unclassified = notifications.filter((notification) => !getPANotificationUseCase(notification))++ const instantAlerts = notificationsFailed ? (+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: () => loadNotifications() }}+ data-attr="product-analytics-notifications-load-error"+ >+ We couldn't load your alerts. Please try again in a moment.+ </LemonBanner>+ ) : !notificationsLoaded ? (+ <div className="grid gap-2 md:grid-cols-2">+ {USE_CASES.map((config) => (+ <LemonCard key={config.useCase} hoverEffect={false} className="flex flex-col gap-2 p-3">+ <LemonSkeleton className="h-4 w-48 max-w-full" />+ <LemonSkeleton className="h-16 w-full" />+ </LemonCard>+ ))}+ </div>+ ) : (+ <>+ <div className="grid gap-2 md:grid-cols-2">+ {USE_CASES.map((config) => (+ <UseCaseCard+ key={config.useCase}+ config={config}+ notifications={notifications.filter(+ (notification) => getPANotificationUseCase(notification) === config.useCase+ )}+ onAdd={openDialogFor[config.subTemplateId]}+ addDisabledReason={addDisabledReason ?? undefined}+ example={examples[config.useCase]}+ />+ ))}+ <InsightAlertsCard />+ </div>++ {unclassified.length > 0 && (+ <LemonCard hoverEffect={false} className="flex flex-col gap-1 p-3">+ <h3 className="m-0 text-sm font-semibold">Other product analytics alerts</h3>+ {unclassified.map((notification) => (+ <NotificationRow key={notification.id} notification={notification} />+ ))}+ </LemonCard>+ )}+ </>+ )++ return (+ <div className="flex flex-col gap-6" data-attr="product-analytics-notifications">+ <ProductAnalyticsRecurringReports />++ <section className="flex flex-col gap-2">+ <h2 className="m-0 text-base font-semibold">Instant alerts</h2>+ <p className="m-0 text-sm text-muted">+ One message per event, for the things you'd want to hear about the moment they happen. A busy site+ can send a lot of these.+ </p>+ {instantAlerts}+ </section>++ {USE_CASES.map((config) => (+ <NewNotificationDialog+ key={config.subTemplateId}+ subTemplateId={config.subTemplateId}+ onCreated={onCreated}+ title={config.dialogTitle}+ />+ ))}+ </div>+ )+}diff --git a/products/product_analytics/frontend/notifications/ProductAnalyticsRecurringReports.tsx b/products/product_analytics/frontend/notifications/ProductAnalyticsRecurringReports.tsxnew file mode 100644index 000000000000..77d824af4bcf--- /dev/null+++ b/products/product_analytics/frontend/notifications/ProductAnalyticsRecurringReports.tsx@@ -0,0 +1,82 @@+import { IconCalendar, IconOpenSidebar } from '@posthog/icons'+import { LemonButton, LemonCard, LemonTag, Link } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { urls } from 'scenes/urls'++import { PA_RECURRING_REPORTS, PARecurringReport, urlForRecurringReport } from './recurringReportDefinitions'++function ReportCard({ report, enabled }: { report: PARecurringReport; enabled: boolean }): 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="primary"+ size="xsmall"+ icon={<IconCalendar />}+ to={urlForRecurringReport(report)}+ data-attr={`product-analytics-recurring-report-${report.key}`}+ >+ 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>+ </LemonCard>+ )+}++/**+ * Recurring AI reports for the questions that suit a digest better than a per-event ping: how the+ * product was used, what's moving, and whether new users stick. All are summaries over a window,+ * so they stay useful on a quiet project and can't flood a channel the way a per-event alert can.+ */+export function ProductAnalyticsRecurringReports(): JSX.Element {+ const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')++ 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>+ )}++ <div className="grid gap-2 md:grid-cols-2">+ {PA_RECURRING_REPORTS.map((report) => (+ <ReportCard key={report.key} report={report} enabled={aiSubscriptionsEnabled} />+ ))}+ </div>+ </section>+ )+}diff --git a/products/product_analytics/frontend/notifications/productAnalyticsNotificationExamplesLogic.test.ts b/products/product_analytics/frontend/notifications/productAnalyticsNotificationExamplesLogic.test.tsnew file mode 100644index 000000000000..9dfa2d3069d9--- /dev/null+++ b/products/product_analytics/frontend/notifications/productAnalyticsNotificationExamplesLogic.test.ts@@ -0,0 +1,35 @@+import { PA_MESSAGE_FIELD_LIMITS } from 'scenes/hog-functions/sub-templates/sub-templates'++import { parseExampleRows } from './productAnalyticsNotificationExamplesLogic'++// Rows arrive positionally: [use_case, page, browser].+const RAGECLICK_ROW = ['rageclick', '/pricing', 'Chrome']++describe('parseExampleRows', () => {+ it('maps a rageclick example from its positional columns', () => {+ expect(parseExampleRows([RAGECLICK_ROW])).toEqual({+ rageclick: {+ page: '/pricing',+ browser: 'Chrome',+ },+ })+ })++ // A half-real example (project's page, our invented browser) reads as genuine but isn't,+ // so an incomplete row is dropped in favour of the honest sample copy.+ it.each([+ ['missing page', ['rageclick', '', 'Chrome']],+ ['missing browser', ['rageclick', '/pricing', null]],+ ['an unrecognized use case', ['something-else', '/pricing', 'Chrome']],+ ])('drops a row with %s', (_label, row) => {+ expect(parseExampleRows([row])).toEqual({})+ })++ it('cuts a field at the limit the delivered message uses', () => {+ const page = '/'.concat('x'.repeat(PA_MESSAGE_FIELD_LIMITS.page + 50))++ const parsed = parseExampleRows([['rageclick', page, 'Chrome']])++ expect(parsed['rageclick']?.page).toHaveLength(PA_MESSAGE_FIELD_LIMITS.page)+ })+})diff --git a/products/product_analytics/frontend/notifications/productAnalyticsNotificationExamplesLogic.ts b/products/product_analytics/frontend/notifications/productAnalyticsNotificationExamplesLogic.tsnew file mode 100644index 000000000000..eec4d1bdb16e--- /dev/null+++ b/products/product_analytics/frontend/notifications/productAnalyticsNotificationExamplesLogic.ts@@ -0,0 +1,120 @@+import { MakeLogicType, kea, path } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { PA_MESSAGE_FIELD_LIMITS, PAMessageField } from 'scenes/hog-functions/sub-templates/sub-templates'++import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'++import { PANotificationUseCase } from './productAnalyticsNotificationsLogic'++export type PANotificationExample = Record<PAMessageField, string>+export type PANotificationExamples = Partial<Record<PANotificationUseCase, PANotificationExample>>++// The most recent real event per use case, so a preview can show the project's own traffic instead+// of invented values. Time-bounded to keep it cheap (30 days is plenty: any project with+// autocapture on sees rageclicks far more often than that); the preview falls back to sample copy+// when a project has nothing (yet), so an empty result is normal, not an error.+const EXAMPLES_QUERY = `+SELECT+ 'rageclick' AS use_case,+ argMax(coalesce(nullIf(toString(properties.$pathname), ''), toString(properties.$current_url)), timestamp) AS page,+ argMax(toString(properties.$browser), timestamp) AS browser+FROM events+WHERE timestamp >= now() - INTERVAL 30 DAY+ AND event = '$rageclick'+`++const KNOWN_USE_CASES: PANotificationUseCase[] = ['rageclick']++// Every field the message renders must be present, otherwise the "real" example would be a mix of+// the project's data and our invented copy — more misleading than an honest sample.+const REQUIRED_FIELDS: Record<PANotificationUseCase, PAMessageField[]> = {+ rageclick: ['page', 'browser'],+}++/** String columns arrive null when the property is missing — normalize those to an empty string. */+const asString = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')++// Array.from so a cut can't land inside a surrogate pair and render as a replacement character.+function truncateField(field: PAMessageField, value: string): string {+ const characters = Array.from(value)+ return characters.length > PA_MESSAGE_FIELD_LIMITS[field]+ ? characters.slice(0, PA_MESSAGE_FIELD_LIMITS[field]).join('')+ : value+}++export function parseExampleRows(rows: unknown[]): PANotificationExamples {+ const examples: PANotificationExamples = {}++ for (const row of rows) {+ const [rawUseCase, page, browser] = row as unknown[]+ const useCase = KNOWN_USE_CASES.find((candidate) => candidate === asString(rawUseCase))+ if (!useCase) {+ continue+ }++ const candidate: PANotificationExample = {+ page: asString(page),+ browser: asString(browser),+ }+ if (!REQUIRED_FIELDS[useCase].every((field) => candidate[field])) {+ continue+ }++ examples[useCase] = {+ page: truncateField('page', candidate.page),+ browser: truncateField('browser', candidate.browser),+ }+ }++ return examples+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productAnalyticsNotificationExamplesLogicValues {+ examples: PANotificationExamples+ examplesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productAnalyticsNotificationExamplesLogicActions {+ loadExamples: () => any+ loadExamplesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadExamplesSuccess: (+ examples: Partial<Record<'rageclick', PANotificationExample>>,+ payload?: any+ ) => {+ examples: Partial<Record<'rageclick', PANotificationExample>>+ payload?: any+ }+}++export type productAnalyticsNotificationExamplesLogicType = MakeLogicType<+ productAnalyticsNotificationExamplesLogicValues,+ productAnalyticsNotificationExamplesLogicActions+>++export const productAnalyticsNotificationExamplesLogic = kea<productAnalyticsNotificationExamplesLogicType>([+ path(['products', 'product_analytics', 'frontend', 'notifications', 'productAnalyticsNotificationExamplesLogic']),+ loaders({+ examples: [+ {} as PANotificationExamples,+ {+ loadExamples: async (): Promise<PANotificationExamples> => {+ const response = (await api.query({+ kind: NodeKind.HogQLQuery,+ query: EXAMPLES_QUERY,+ })) as HogQLQueryResponse+ return parseExampleRows(response?.results ?? [])+ },+ },+ ],+ }),+])diff --git a/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.test.ts b/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.test.tsnew file mode 100644index 000000000000..550248b286bc--- /dev/null+++ b/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.test.ts@@ -0,0 +1,137 @@+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { deleteWithUndo } from 'lib/utils/deleteWithUndo'++import { initKeaTests } from '~/test/init'+import { HogFunctionType } from '~/types'++import { getPANotificationUseCase, productAnalyticsNotificationsLogic } from './productAnalyticsNotificationsLogic'++jest.mock('lib/utils/deleteWithUndo', () => ({+ deleteWithUndo: jest.fn(),+}))++const mockedDeleteWithUndo = jest.mocked(deleteWithUndo)++function makeNotification(id: string, overrides: Partial<HogFunctionType> = {}): HogFunctionType {+ return {+ id,+ name: `Notification ${id}`,+ enabled: false,+ deleted: false,+ filters: { events: [{ id: '$rageclick', type: 'events' }] },+ inputs: {},+ icon_url: null,+ ...overrides,+ } as HogFunctionType+}++function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((promiseResolve) => {+ resolve = promiseResolve+ })+ return { promise, resolve }+}++describe('productAnalyticsNotificationsLogic', () => {+ let logic: ReturnType<typeof productAnalyticsNotificationsLogic.build>+ let listSpy: jest.SpyInstance++ beforeEach(async () => {+ initKeaTests()+ listSpy = jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({+ count: 2,+ next: null,+ previous: null,+ results: [],+ })+ jest.spyOn(api.hogFunctions, 'update').mockResolvedValue(makeNotification('updated'))+ jest.spyOn(lemonToast, 'warning').mockImplementation(() => 'toast-id')+ mockedDeleteWithUndo.mockReset().mockResolvedValue()++ logic = productAnalyticsNotificationsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ test.each([+ ['$rageclick', 'rageclick'],+ ['$pageview', null],+ ['$mcp_tool_call', null],+ ])('classifies the %s event as %s', (eventId, expected) => {+ expect(+ getPANotificationUseCase({+ filters: { events: [{ id: eventId, type: 'events' }] },+ })+ ).toBe(expected)+ })++ it('loads only a lightweight count when mounted', () => {+ expect(logic.values.notificationCount).toBe(2)+ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(listSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ limit: 1,+ types: ['destination'],+ })+ )+ expect(listSpy.mock.calls[0][0]).not.toHaveProperty('full')+ })++ it('keeps the fetched rows and warns when the list is truncated', async () => {+ const notifications = [makeNotification('a'), makeNotification('b')]+ listSpy.mockReset().mockResolvedValue({+ count: 501,+ next: 'http://localhost/api/projects/1/hog_functions/?limit=500&offset=500',+ previous: null,+ results: notifications,+ })++ logic.actions.loadNotificationCountSuccess(501)++ await expectLogic(logic, () => logic.actions.loadNotifications())+ .toFinishAllListeners()+ .toMatchValues({+ notificationCount: 501,+ notifications,+ notificationsFailed: false,+ notificationsTruncated: true,+ })++ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ full: true, limit: 500 }))+ expect(lemonToast.warning).toHaveBeenCalledWith(expect.stringContaining('first 500'))+ })++ it('blocks a second toggle and reconciles the first with the server response', async () => {+ const notification = makeNotification('toggle')+ const serverNotification = makeNotification('toggle', { enabled: false, name: 'Server name' })+ const updateDeferred = createDeferred<HogFunctionType>()+ const updateSpy = jest.spyOn(api.hogFunctions, 'update').mockReturnValue(updateDeferred.promise)+ logic.actions.loadNotificationsSuccess([notification])++ logic.actions.toggleNotificationEnabled(notification.id, true)++ expect(logic.values.pendingToggleIds).toEqual({ [notification.id]: true })+ expect(logic.values.notifications[0].enabled).toBe(true)++ logic.actions.toggleNotificationEnabled(notification.id, false)+ expect(updateSpy).toHaveBeenCalledTimes(1)++ updateDeferred.resolve(serverNotification)+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ notifications: [serverNotification],+ pendingToggleIds: {},+ })+ })+})diff --git a/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.ts b/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.tsnew file mode 100644index 000000000000..2f5f73ff0f20--- /dev/null+++ b/products/product_analytics/frontend/notifications/productAnalyticsNotificationsLogic.ts@@ -0,0 +1,328 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import posthog from 'lib/posthog-typed'+import { deleteWithUndo } from 'lib/utils/deleteWithUndo'+import { getFiltersFromSubTemplateId } from 'scenes/hog-functions/list/LinkedHogFunctions'+import { projectLogic } from 'scenes/projectLogic'++import { CyclotronJobFiltersType, HogFunctionSubTemplateIdType, HogFunctionType } from '~/types'++const PA_NOTIFICATION_LIST_LIMIT = 500+const PA_NOTIFICATION_SUB_TEMPLATE_IDS: HogFunctionSubTemplateIdType[] = ['pa-rageclick']++function getPANotificationFilterGroups(): CyclotronJobFiltersType[] {+ return PA_NOTIFICATION_SUB_TEMPLATE_IDS.map(getFiltersFromSubTemplateId).filter(+ (filters): filters is CyclotronJobFiltersType => !!filters+ )+}++export type PANotificationUseCase = 'rageclick'++export function getPANotificationUseCase(fn: Pick<HogFunctionType, 'filters'>): PANotificationUseCase | null {+ const events = fn.filters?.events ?? []+ return events.some((event) => event.id === '$rageclick') ? 'rageclick' : null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productAnalyticsNotificationsLogicValues {+ currentProjectId: number | null // projectLogic+ notificationCount: number+ notificationCountLoading: boolean+ notifications: HogFunctionType[]+ notificationsFailed: boolean+ notificationsLoaded: boolean+ notificationsLoading: boolean+ notificationsTruncated: boolean+ pendingDeleteIds: Record<string, true>+ pendingToggleIds: Record<string, true>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface productAnalyticsNotificationsLogicActions {+ deleteNotification: (notification: HogFunctionType) => {+ notification: HogFunctionType+ }+ deleteNotificationSettled: (notificationId: string) => {+ notificationId: string+ }+ deleteNotificationStarted: (notificationId: string) => {+ notificationId: string+ }+ loadNotificationCount: () => any+ loadNotificationCountFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadNotificationCountSuccess: (+ notificationCount: number,+ payload?: any+ ) => {+ notificationCount: number+ payload?: any+ }+ loadNotifications: () => any+ loadNotificationsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadNotificationsSuccess: (+ notifications: HogFunctionType[],+ payload?: any+ ) => {+ notifications: HogFunctionType[]+ payload?: any+ }+ setNotifications: (notifications: HogFunctionType[]) => {+ notifications: HogFunctionType[]+ }+ setNotificationsTruncated: (notificationsTruncated: boolean) => {+ notificationsTruncated: boolean+ }+ toggleNotificationEnabled: (+ notificationId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ notificationId: string+ }+ toggleNotificationEnabledSettled: (notificationId: string) => {+ notificationId: string+ }+ toggleNotificationEnabledStarted: (notificationId: string) => {+ notificationId: string+ }+}++export type productAnalyticsNotificationsLogicType = MakeLogicType<+ productAnalyticsNotificationsLogicValues,+ productAnalyticsNotificationsLogicActions+>++export const productAnalyticsNotificationsLogic = kea<productAnalyticsNotificationsLogicType>([+ path(['products', 'product_analytics', 'frontend', 'notifications', 'productAnalyticsNotificationsLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ toggleNotificationEnabled: (notificationId: string, enabled: boolean) => ({ notificationId, enabled }),+ toggleNotificationEnabledStarted: (notificationId: string) => ({ notificationId }),+ toggleNotificationEnabledSettled: (notificationId: string) => ({ notificationId }),+ deleteNotification: (notification: HogFunctionType) => ({ notification }),+ deleteNotificationStarted: (notificationId: string) => ({ notificationId }),+ deleteNotificationSettled: (notificationId: string) => ({ notificationId }),+ setNotificationsTruncated: (notificationsTruncated: boolean) => ({ notificationsTruncated }),+ // Local (optimistic) writes go through this rather than the loader's success action, which+ // would also clear `notificationsLoading` and hide a reload that is still in flight.+ setNotifications: (notifications: HogFunctionType[]) => ({ notifications }),+ }),+ loaders(({ actions, values }) => ({+ notificationCount: [+ 0,+ {+ loadNotificationCount: async (): Promise<number> => {+ const response = await api.hogFunctions.list({+ filter_groups: getPANotificationFilterGroups(),+ types: ['destination'],+ limit: 1,+ })++ return response.count+ },+ },+ ],+ notifications: [+ [] as HogFunctionType[],+ {+ loadNotifications: async (): Promise<HogFunctionType[]> => {+ const response = await api.hogFunctions.list({+ filter_groups: getPANotificationFilterGroups(),+ types: ['destination'],+ full: true,+ limit: PA_NOTIFICATION_LIST_LIMIT,+ })+ const notificationsTruncated = !!response.next+ actions.setNotificationsTruncated(notificationsTruncated)+ if (notificationsTruncated) {+ lemonToast.warning(+ `Showing the first ${PA_NOTIFICATION_LIST_LIMIT} notifications. Manage the rest from the data pipelines page.`+ )+ }++ // A reload can race in-flight mutations: a GET that read the DB before a+ // toggle/delete landed would otherwise revert the toggle or resurrect the+ // deleted row. Keep the local value for rows with a pending mutation.+ return response.results+ .filter((notification) => !notification.deleted && !values.pendingDeleteIds[notification.id])+ .map((notification) => {+ if (!values.pendingToggleIds[notification.id]) {+ return notification+ }+ const local = values.notifications.find((item) => item.id === notification.id)+ return local ? { ...notification, enabled: local.enabled } : notification+ })+ },+ },+ ],+ })),+ reducers({+ notifications: {+ setNotifications: (_: HogFunctionType[], { notifications }: { notifications: HogFunctionType[] }) =>+ notifications,+ },+ notificationsTruncated: [+ false,+ {+ setNotificationsTruncated: (_, { notificationsTruncated }) => notificationsTruncated,+ },+ ],+ pendingToggleIds: [+ {} as Record<string, true>,+ {+ toggleNotificationEnabledStarted: (state, { notificationId }) => ({+ ...state,+ [notificationId]: true,+ }),+ toggleNotificationEnabledSettled: (state, { notificationId }) => {+ const nextState = { ...state }+ delete nextState[notificationId]+ return nextState+ },+ },+ ],+ pendingDeleteIds: [+ {} as Record<string, true>,+ {+ deleteNotificationStarted: (state, { notificationId }) => ({+ ...state,+ [notificationId]: true,+ }),+ deleteNotificationSettled: (state, { notificationId }) => {+ const nextState = { ...state }+ delete nextState[notificationId]+ return nextState+ },+ },+ ],+ notificationsFailed: [+ false,+ {+ loadNotifications: () => false,+ loadNotificationsSuccess: () => false,+ loadNotificationsFailure: () => true,+ },+ ],+ // The list loads lazily when the tab mounts; without this flag the tab's first+ // render (before the load kicks off) would flash the empty state.+ notificationsLoaded: [+ false,+ {+ loadNotificationsSuccess: () => true,+ loadNotificationsFailure: () => true,+ },+ ],+ }),+ listeners(({ actions, values }) => {+ // Preserve the server total while the list is capped. Optimistic deletes can leave it+ // slightly stale until the next count reload, which is more accurate than replacing it with 500.+ const syncCountFromList = (notifications: HogFunctionType[]): void => {+ if (values.notificationsTruncated) {+ return+ }+ actions.loadNotificationCountSuccess(notifications.length)+ }++ return {+ // If a reload was already in flight when a mutation settled, that GET read pre-mutation+ // state and its pending-id tombstone is now cleared — reload once more so the stale+ // response can't revert a confirmed toggle or resurrect a confirmed delete.+ toggleNotificationEnabledSettled: () => {+ if (values.notificationsLoading) {+ actions.loadNotifications()+ }+ },+ deleteNotificationSettled: () => {+ if (values.notificationsLoading) {+ actions.loadNotifications()+ }+ },+ loadNotificationsSuccess: ({ notifications }) => syncCountFromList(notifications),+ setNotifications: ({ notifications }) => syncCountFromList(notifications),+ toggleNotificationEnabled: async ({ notificationId, enabled }) => {+ if (values.pendingToggleIds[notificationId]) {+ return+ }++ const target = values.notifications.find((notification) => notification.id === notificationId)+ if (!target) {+ return+ }+ actions.toggleNotificationEnabledStarted(notificationId)+ const previousEnabled = target.enabled++ const applyEnabled = (next: boolean): void => {+ actions.setNotifications(+ values.notifications.map((notification) =>+ notification.id === notificationId ? { ...notification, enabled: next } : notification+ )+ )+ }++ applyEnabled(enabled)++ try {+ const updatedNotification = await api.hogFunctions.update(notificationId, { enabled })+ actions.setNotifications(+ values.notifications.map((notification) =>+ notification.id === notificationId ? updatedNotification : notification+ )+ )+ } catch (error) {+ applyEnabled(previousEnabled)+ lemonToast.error('Failed to update notification')+ posthog.captureException(error, {+ action: 'toggle-product-analytics-notification',+ notification: notificationId,+ })+ } finally {+ actions.toggleNotificationEnabledSettled(notificationId)+ }+ },+ deleteNotification: async ({ notification }) => {+ actions.deleteNotificationStarted(notification.id)+ actions.setNotifications(values.notifications.filter((item) => item.id !== notification.id))++ let callbackFired = false+ await deleteWithUndo({+ endpoint: `projects/${values.currentProjectId}/hog_functions`,+ object: { id: notification.id, name: notification.name },+ callback: (undo) => {+ callbackFired = true+ // Settle before reloading so the undone row isn't filtered back out+ actions.deleteNotificationSettled(notification.id)+ if (undo) {+ actions.loadNotifications()+ }+ },+ })++ if (!callbackFired) {+ actions.deleteNotificationSettled(notification.id)+ actions.loadNotifications()+ }+ },+ }+ }),+ afterMount(({ actions }) => {+ actions.loadNotificationCount()+ }),+])diff --git a/products/product_analytics/frontend/notifications/recurringReportDefinitions.ts b/products/product_analytics/frontend/notifications/recurringReportDefinitions.tsnew file mode 100644index 000000000000..2632b245e9ec--- /dev/null+++ b/products/product_analytics/frontend/notifications/recurringReportDefinitions.ts@@ -0,0 +1,82 @@+import { combineUrl } from 'kea-router'++import { urls } from 'scenes/urls'++export interface PARecurringReport {+ key: string+ headline: string+ lead: string+ frequency: 'daily' | 'weekly'+ title: string+ /**+ * Handed to the AI-subscription planner, which writes and runs its own HogQL. Names the+ * event properties explicitly so it queries the right ones rather than guessing.+ */+ prompt: string+}++// All weekly: daily windows make week-over-week comparisons and retention math meaningless for+// most projects, and a weekly digest is the cadence these questions are worth thinking about.+export const PA_RECURRING_REPORTS: PARecurringReport[] = [+ {+ key: 'usage-digest',+ headline: 'How your product was used',+ lead: 'Active users, top pages and top events for the week, with what moved.',+ frequency: 'weekly',+ 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.',+ ].join(' '),+ },+ {+ key: 'growing-declining',+ headline: 'What is growing and what is declining',+ lead: 'The fastest-rising and fastest-falling events week over week.',+ frequency: 'weekly',+ title: 'Growing and declining events',+ prompt: [+ 'Compare event volume for the last 7 days against the previous 7 days for every event',+ 'name in this project, excluding internal events that start with $ (but keep $pageview).',+ 'Rank the five fastest-growing and five fastest-declining events by relative change,',+ 'ignoring events with fewer than 100 occurrences in both windows.',+ 'For each, give the counts and whether unique users moved the same way as event volume,',+ 'since volume rising on flat users means heavier use rather than more reach.',+ 'Close with one hypothesis worth checking for the biggest decline.',+ ].join(' '),+ },+ {+ key: 'activation-retention',+ headline: 'Are new users coming back',+ lead: 'This week’s new users, how many returned, and where they landed first.',+ frequency: 'weekly',+ title: 'New-user activation and retention',+ prompt: [+ 'Report on new-user activation using $pageview events.',+ 'Count persons whose first event ever was in the last 7 days, the share of them that',+ 'returned on a later day within the same week, and compare with the previous week’s cohort.',+ 'List the top three first-touch pages for new users using $entry_current_url when set,',+ 'otherwise the $pathname of their first $pageview, and note whether the landing page',+ 'correlates with returning. End with the one thing most likely to improve week-one retention.',+ ].join(' '),+ },+]++/**+ * 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: PARecurringReport): string {+ return combineUrl(urls.subscriptionNew(), {+ resource_type: 'ai_prompt',+ prompt: report.prompt,+ title: report.title,+ frequency: report.frequency,+ target_type: 'slack',+ }).url+}diff --git a/products/product_analytics/package.json b/products/product_analytics/package.jsonindex 75cf88a667ac..d0010dd4ab26 100644--- a/products/product_analytics/package.json+++ b/products/product_analytics/package.json@@ -12,7 +12,8 @@},"devDependencies": {"@storybook/react": "catalog:",- "@testing-library/react": "*"+ "@testing-library/react": "*",+ "kea-test-utils": "catalog:"},"peerDependencies": {"@posthog/icons": "catalog:",