: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(dashboards): nudge repeat dashboard viewers to subscribe (#70700)
Vasco de Krijgerbb0a9504ce06
diff --git a/.agents/skills/sending-notifications/SKILL.md b/.agents/skills/sending-notifications/SKILL.mdindex 8fc56ce11a6d..3033698075d5 100644--- a/.agents/skills/sending-notifications/SKILL.md+++ b/.agents/skills/sending-notifications/SKILL.md@@ -115,10 +115,9 @@ Kafka publish happens on `transaction.on_commit` — won't fire if the transacti## Adding a new notification type1. Add enum value in `products/notifications/backend/facade/enums.py`-2. Add icon mapping in `frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx` (`NOTIFICATION_TYPE_ICONS`)-3. Add the same icon in the toast handler in `frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx` (`iconMap`)-4. Add sample data in `SAMPLE_NOTIFICATIONS` in `products/notifications/backend/presentation/views.py`-5. Run `python manage.py makemigrations notifications`+2. Add icon mapping in `frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx` (`NOTIFICATION_TYPE_ICONS`) — the single icon source, read by `getNotificationIcon`, which only `NotificationRow` calls; the side panel gets the icon by rendering that row+3. Add a label + description entry in `frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx` (`REALTIME_NOTIFICATION_TYPE_META`) — drives the per-type notification preferences UI+4. Run `python manage.py makemigrations notifications`## Testingdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ef3d100940f5..a15c8ad5d4a4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -757,9 +757,9 @@ snapshots:components-hogcharts-linechart--combined-overlays--light:hash: v1.k794b7964.14dfe01a2843fc6520c4a47cb75d360744d221db45aefb219d12b8c0a2e85091.jNXH_Smv6Cjeso_gAxYkVi0sJxku4ecUvCs3PLSKU7ocomponents-hogcharts-linechart--confidence-band-below-zero--dark:- hash: v1.k794b7964.0c7aaceb394edfc991d2543566ac409107f32531d0e4d52456e53b5f69703d75.tTkxlTKSJ7po5VXuEM6fbyA8rZhfDmnatcxIvGdAMJg+ hash: v1.k794b7964.75fb342836a0ce7ec1370dccebd600cf0f7da32dba451a5c684e2d38b62c3d4c.2an212AjIAEBdvH5VwyZwe1d39XoConRd2Py02pxQ48components-hogcharts-linechart--confidence-band-below-zero--light:- hash: v1.k794b7964.b2d5510efc17ecc1cd6f34b25adf964fed3c56f6752f3e95cf0b23b59813b2da.M4hPw2IWfpnb8qYRYlZ4PD-eLfoknPJK4BVH86n_dc4+ hash: v1.k794b7964.1a07aa1663f9089547024e0101e6c03b6f5896e07ad20b989225af21c6f88fbd.sJDvTfHfxb7jB6P4KsdxTrd-5BKVseoJ5YSOhI89pEIcomponents-hogcharts-linechart--dual-y-axis--dark:hash: v1.k794b7964.7d3a5acab999dfc4fc7d9eeb6601d2ed47637bf13975e46b1a72c025bb58cf12.MlvaVVa6kp_drn35wHCDDaKydGxJmaJaYPQ6lZPn0TQcomponents-hogcharts-linechart--dual-y-axis--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex eeedbe16c997..38e7c70a95d6 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -36,6 +36,9 @@ const ERROR_FILTER_ALLOW_LIST = ['loadRecordingMeta', // Gracefully handled in the recording player'loadSimilarIssues', // Gracefully handled in the similar issues list'saveEarlyAccessFeature', // Field-level errors handled in earlyAccessFeatureLogic+ 'loadExistingSubscription', // Background eligibility check for the dashboard subscribe nudge+ 'loadTeamSubscriptionCount', // Background free-tier limit check for the dashboard subscribe nudge+ 'sendNudgeNotification', // Background delivery request for the dashboard subscribe nudge]/*diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex 451ccc0b57d7..70442360d5ef 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -65,6 +65,10 @@ export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; delabel: 'Achievement unlocked',description: 'When you unlock a new achievement',},+ subscription_nudge: {+ label: 'Subscription suggestions',+ description: 'When PostHog suggests subscribing to a dashboard you keep coming back to',+ },}export function NotificationTitle({diff --git a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsxindex 1448b398f7f0..af7d45f90091 100644--- a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx+++ b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx@@ -1,6 +1,7 @@import { ComponentType } from 'react'import {+ IconBell,IconBug,IconCheckCircle,IconClock,@@ -33,6 +34,7 @@ const NOTIFICATION_TYPE_ICONS: Record<string, { Icon: ComponentType<{ className?reminder: { Icon: IconClock, color: 'text-primary' },web_analytics_digest: { Icon: IconPieChart, color: 'text-primary' },achievement_unlocked: { Icon: IconStar, color: 'text-warning' },+ subscription_nudge: { Icon: IconBell, color: 'text-primary' },}export function getNotificationIcon(notificationType: string, className: string = 'size-5'): JSX.Element {diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex f6cc019f5005..7ce46e5b5cd9 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -277,6 +277,9 @@ export const FEATURE_FLAGS = {DASHBOARD_INLINE_TILE_INSERTION: 'dashboard-inline-tile-insertion', // owner: @MattPua #team-analytics-platformDASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platformDASHBOARD_POSTHOG_AI_BUTTON_LABEL: 'dashboard-posthog-ai-button-label', // owner: @pauldambra #team-product-analytics multivariate=control,control_b,test+ DASHBOARD_QUICK_FILTERS_EXPERIMENT: 'dashboard-quick-filters-experiment', // owner: @vdekrijger #team-product-analytics multivariate=control,test+ DASHBOARD_SUBSCRIBE_NUDGE: 'dashboard-subscribe-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges repeat dashboard viewers with no subscription toward setting one up+ DASHBOARD_SUBSCRIBE_PLACEMENT: 'dashboard-subscribe-placement', // owner: @MattPua #team-analytics-platform multivariate=control,button,menuDASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,newDASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platformDASHBOARDS_LIST_VIEW: 'dashboards-list-view', // owner: @vdekrijger #team-product-analytics multivariate=control,treediff --git a/frontend/src/lib/posthog-typed.ts b/frontend/src/lib/posthog-typed.tsindex 7ca10592cc5f..a0764d472910 100644--- a/frontend/src/lib/posthog-typed.ts+++ b/frontend/src/lib/posthog-typed.ts@@ -661,6 +661,22 @@ interface EventSchemas {'dashboard refreshed': Record<string, any>'dashboard renamed': Record<string, any>'dashboard share toggled': Record<string, any>+ 'dashboard subscribe nudge check failed': {+ dashboard_id?: number+ step?: string+ error_name?: string+ error_status?: number+ error_message?: string+ }+ 'dashboard subscribe nudge clicked': {+ dashboard_id?: number+ prefilled?: boolean+ via?: string+ }+ 'dashboard subscribe nudge shown': {+ dashboard_id?: number+ view_count_7d?: number+ }'dashboard subscription created': Record<string, any>'dashboard subscription updated': Record<string, any>'dashboard updated': Record<string, any>@@ -3536,7 +3552,14 @@ interface EventSchemas {'subscribed during onboarding': Record<string, any>subscribe_to_product_updates: Record<string, any>'subscription cancelled': Record<string, any>- 'subscription created': Record<string, any>+ 'subscription created': {+ resource_type?: string+ dashboard_id?: number+ insight_short_id?: string+ subscription_id?: number+ target_type?: string+ ai_summary_prefilled?: boolean+ }subscription_intent: Record<string, any>'subscription updated': Record<string, any>'Substack subscribe error': Record<string, any>diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsxindex 4777542ad393..4fc058dd25ff 100644--- a/frontend/src/scenes/dashboard/Dashboard.tsx+++ b/frontend/src/scenes/dashboard/Dashboard.tsx@@ -27,9 +27,16 @@ import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'import { DashboardHeader } from './DashboardHeader'import { DashboardOverridesBanner } from './DashboardOverridesBanner'import { DashboardPublicAccessBanner } from './DashboardPublicAccessBanner'+import { dashboardSubscribeNudgeLogic } from './dashboardSubscribeNudgeLogic'import { DashboardZoomControl } from './DashboardZoomControl'import { EmptyDashboardComponent } from './EmptyDashboardComponent'+// Mount-only: runs the subscribe-nudge eligibility machinery for this dashboard; renders nothing.+function DashboardSubscribeNudgeTrigger({ dashboardId }: { dashboardId: number }): null {+ useMountedLogic(dashboardSubscribeNudgeLogic({ dashboardId }))+ return null+}+interface DashboardProps {id?: stringdashboard?: DashboardType<QueryBasedInsightModel>@@ -122,6 +129,9 @@ function DashboardScene({return (<SceneContent className={cn('dashboard')}>{placement == DashboardPlacement.Dashboard && <DashboardHeader />}+ {placement == DashboardPlacement.Dashboard && !!dashboard?.id && (+ <DashboardSubscribeNudgeTrigger dashboardId={dashboard.id} />+ )}{canEditDashboard && addInsightToDashboardModalVisible && <AddInsightToDashboardModal />}<DashboardPublicAccessBanner dashboard={dashboard} placement={placement} />diff --git a/frontend/src/scenes/dashboard/DashboardSubscribeNudgeToast.tsx b/frontend/src/scenes/dashboard/DashboardSubscribeNudgeToast.tsxnew file mode 100644index 000000000000..f20710996ee6--- /dev/null+++ b/frontend/src/scenes/dashboard/DashboardSubscribeNudgeToast.tsx@@ -0,0 +1,76 @@+import { router } from 'kea-router'++import { IconBell } from '@posthog/icons'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import {+ SUBSCRIPTION_PREFILL_PARAMS,+ urlForSubscription,+} from 'products/subscriptions/frontend/components/Subscriptions/utils'++export function dashboardSubscribeNudgeToastId(dashboardId: number): string {+ return `dashboard-subscribe-nudge-${dashboardId}`+}++// Deliberately free of any kea logic dependency: the sticky toast can outlive the dashboard+// scene (and its keyed logic), so the CTA only touches globals — the router and the toast itself.+export function onDashboardSubscribeNudgeToastCta(dashboardId: number): void {+ lemonToast.dismiss(dashboardSubscribeNudgeToastId(dashboardId))+ router.actions.push(urlForSubscription('new', { dashboardId }), {+ [SUBSCRIPTION_PREFILL_PARAMS.param]: SUBSCRIPTION_PREFILL_PARAMS.nudge,+ [SUBSCRIPTION_PREFILL_PARAMS.viaParam]: SUBSCRIPTION_PREFILL_PARAMS.viaToast,+ })+}++export function DashboardSubscribeNudgeToast({+ dashboardId,+ dashboardName,+ viewCount7d,+}: {+ dashboardId: number+ dashboardName?: string | null+ viewCount7d: number+}): JSX.Element {+ return (+ <div className="flex flex-col gap-1.5 py-1 pr-1 min-w-0 items-start">+ <div className="flex items-center gap-1.5 text-sm font-semibold">+ <IconBell className="size-4 shrink-0 text-primary" />+ <span>You keep coming back to {dashboardName || 'this dashboard'}</span>+ </div>+ <div className="text-xs text-secondary leading-snug">+ You've viewed it {viewCount7d} times in the last week. Get it delivered to your inbox every Monday+ instead.+ </div>+ <LemonButton+ type="primary"+ size="small"+ data-attr="dashboard-subscribe-nudge-toast-cta"+ onClick={() => onDashboardSubscribeNudgeToastCta(dashboardId)}+ >+ Set up subscription+ </LemonButton>+ </div>+ )+}++/** Sticky nudge toast: persists until the user clicks the CTA (which dismisses it) or the X. */+export function showDashboardSubscribeNudgeToast(+ dashboardId: number,+ dashboardName: string | null | undefined,+ viewCount7d: number+): void {+ lemonToast.info(+ <DashboardSubscribeNudgeToast+ dashboardId={dashboardId}+ dashboardName={dashboardName}+ viewCount7d={viewCount7d}+ />,+ {+ toastId: dashboardSubscribeNudgeToastId(dashboardId),+ autoClose: false,+ icon: false, // the body carries its own bell icon+ }+ )+}diff --git a/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.test.ts b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.test.tsnew file mode 100644index 000000000000..4a9c2b9f7eac--- /dev/null+++ b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.test.ts@@ -0,0 +1,512 @@+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'++import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import posthog from 'lib/posthog-typed'+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import {+ dashboardNudgeScopeKey,+ dashboardSubscribeNudgeStoreLogic,+} from 'scenes/dashboard/dashboardSubscribeNudgeStoreLogic'+import { userLogic } from 'scenes/userLogic'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { useMocks } from '~/mocks/jest'+import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import {+ AccessControlLevel,+ AvailableFeature,+ DashboardPlacement,+ DashboardType,+ QueryBasedInsightModel,+ UserType,+} from '~/types'++import { subscriptionsLogic } from 'products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic'+import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'++import { DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD, dashboardSubscribeNudgeLogic } from './dashboardSubscribeNudgeLogic'+import {+ DASHBOARD_VIEW_DEDUPE_WINDOW_MS,+ DASHBOARD_VIEW_LOG_WINDOW_MS,+ MAX_TRACKED_DASHBOARDS,+} from './dashboardSubscribeNudgeStoreLogic'+import { DashboardSubscribeNudgeToast, onDashboardSubscribeNudgeToastCta } from './DashboardSubscribeNudgeToast'++jest.mock('lib/posthog-typed', () => ({+ __esModule: true,+ default: { capture: jest.fn() },+}))++jest.mock('products/subscriptions/frontend/generated/api', () => ({+ subscriptionsList: jest.fn(),+}))++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { info: jest.fn(), error: jest.fn(), success: jest.fn(), dismiss: jest.fn() },+}))++const mockSubscriptionsList = subscriptionsList as jest.Mock++const DASHBOARD_ID = 1+const START_TIME = 1_700_000_000_000+/** kea-localstorage derives each persisted entry's key from the logic's path (which carries the scope). */+const STORE_PATH = 'scenes.dashboard.dashboardSubscribeNudgeStoreLogic'++const USER_WITH_SUBSCRIPTIONS_FEATURE: UserType = {+ ...MOCK_DEFAULT_USER,+ organization: {+ ...MOCK_DEFAULT_ORGANIZATION,+ available_product_features: [{ key: AvailableFeature.SUBSCRIPTIONS, name: 'Subscriptions' }],+ },+}++function mockDashboard(): DashboardType<QueryBasedInsightModel> {+ return {+ id: DASHBOARD_ID,+ name: 'Test dashboard',+ user_access_level: AccessControlLevel.Editor,+ tiles: [],+ } as unknown as DashboardType<QueryBasedInsightModel>+}++function capturesOf(event: string): any[][] {+ return (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === event)+}++describe('dashboardSubscribeNudgeLogic', () => {+ let logic: ReturnType<typeof dashboardSubscribeNudgeLogic.build>+ let storeLogic: ReturnType<typeof dashboardSubscribeNudgeStoreLogic.build>+ let now: number+ let dateSpy: jest.SpyInstance+ let nudgePostCount: number+ let nudgePostResponse: [number, Record<string, unknown>]++ /** Records views spaced beyond the dedupe window, so each counts as a distinct visit. */+ function recordViews(count: number, dashboardId: number = DASHBOARD_ID): void {+ for (let i = 0; i < count; i++) {+ now += DASHBOARD_VIEW_DEDUPE_WINDOW_MS + 1000+ logic.actions.recordDashboardView(dashboardId)+ }+ }++ beforeEach(() => {+ window.localStorage.clear()+ mockSubscriptionsList.mockReset()+ mockSubscriptionsList.mockResolvedValue({ count: 0, results: [] })+ ;(lemonToast.info as jest.Mock).mockClear()+ nudgePostCount = 0+ nudgePostResponse = [201, { created: true }]+ now = START_TIME+ dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => now)+ useMocks({+ post: {+ '/api/projects/:team_id/dashboards/:dashboard_id/subscribe_nudge/': () => {+ nudgePostCount += 1+ return nudgePostResponse+ },+ },+ })+ initKeaTests()+ userLogic.mount()+ userLogic.actions.loadUserSuccess(USER_WITH_SUBSCRIPTIONS_FEATURE)+ featureFlagLogic.mount()+ dashboardLogic({+ id: DASHBOARD_ID,+ dashboard: mockDashboard(),+ placement: DashboardPlacement.Dashboard,+ }).mount()+ logic = dashboardSubscribeNudgeLogic({ dashboardId: DASHBOARD_ID })+ logic.mount()+ // Same keyed instance the logic connects to — already mounted via that connect.+ storeLogic = dashboardSubscribeNudgeStoreLogic({ scope: dashboardNudgeScopeKey() })+ ;(posthog.capture as jest.Mock).mockClear()+ })++ afterEach(() => {+ logic.unmount()+ dateSpy.mockRestore()+ window.localStorage.clear()+ })++ it.each([+ [1, false],+ [2, false],+ [DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD, true],+ [DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD + 1, true],+ ])('treats %i view(s) in the last 7 days as past-threshold=%s', (viewCount, expected) => {+ recordViews(viewCount)+ expect(logic.values.viewCount7d).toBe(viewCount)+ expect(logic.values.isPastViewThreshold).toBe(expected)+ })++ it('counts re-dispatches within the dedupe window as a single visit', () => {+ // dashboardLogic can dispatch reportDashboardViewed twice per real page view+ // (mount + after-API-load), so back-to-back records must count once.+ logic.actions.recordDashboardView(DASHBOARD_ID)+ now += 1000+ logic.actions.recordDashboardView(DASHBOARD_ID)+ expect(logic.values.viewCount7d).toBe(1)++ // A genuinely separate visit (past the window) counts again.+ now += DASHBOARD_VIEW_DEDUPE_WINDOW_MS + 1000+ logic.actions.recordDashboardView(DASHBOARD_ID)+ expect(logic.values.viewCount7d).toBe(2)+ })++ it('keeps the same viewLog reference on a no-op deduped record', () => {+ // A re-dispatch inside the dedupe window with nothing stale to prune must not mint a new+ // map object, so kea-localstorage skips a redundant full-map persist write.+ logic.actions.recordDashboardView(DASHBOARD_ID)+ const before = storeLogic.values.viewLog+ now += 1000+ logic.actions.recordDashboardView(DASHBOARD_ID)+ expect(storeLogic.values.viewLog).toBe(before)+ })++ it('prunes stale views across the whole map and drops emptied dashboards', () => {+ recordViews(3)+ recordViews(1, 999) // another dashboard, whose views all go stale++ now += DASHBOARD_VIEW_LOG_WINDOW_MS + 1000+ logic.actions.recordDashboardView(DASHBOARD_ID)++ expect(logic.values.viewCount7d).toBe(1)+ expect(logic.values.isPastViewThreshold).toBe(false)+ // The persisted map is bounded: fully-stale dashboards disappear entirely.+ expect(Object.keys(storeLogic.values.viewLog)).toEqual([String(DASHBOARD_ID)])+ })++ describe('free-tier subscription limit', () => {+ beforeEach(() => {+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER) // no available features -> free tier+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SUBSCRIBE_NUDGE]: 'test' })+ })++ it.each([+ [0, true],+ [SubscriptionFreeTierLimit.COUNT - 1, true],+ [SubscriptionFreeTierLimit.COUNT, false],+ ])('with %i existing team subscriptions, nudges=%s', async (teamCount, nudges) => {+ mockSubscriptionsList.mockImplementation((_teamId: string, params?: Record<string, unknown>) =>+ Promise.resolve(params?.dashboard ? { count: 0, results: [] } : { count: teamCount, results: [] })+ )++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ // On success the flow marks the dashboard notified (isCandidate flips false again),+ // so assert the observable outcomes rather than intermediate selector state.+ expect(logic.values.isWithinSubscriptionLimit).toBe(nudges)+ expect(nudgePostCount).toBe(nudges ? 1 : 0)+ expect(capturesOf('dashboard subscribe nudge shown')).toHaveLength(nudges ? 1 : 0)+ })++ it('fails closed and reports the failure when the count fetch errors', async () => {+ silenceKeaLoadersErrors()+ mockSubscriptionsList.mockImplementation((_teamId: string, params?: Record<string, unknown>) =>+ params?.dashboard+ ? Promise.resolve({ count: 0, results: [] })+ : Promise.reject(new Error('network down'))+ )++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()+ resumeKeaLoadersErrors()++ expect(logic.values.isWithinSubscriptionLimit).toBe(false)+ expect(logic.values.showNudge).toBe(false)+ expect(nudgePostCount).toBe(0)+ const failures = capturesOf('dashboard subscribe nudge check failed')+ expect(failures).toHaveLength(1)+ expect(failures[0][1]).toMatchObject({+ dashboard_id: DASHBOARD_ID,+ step: 'limit',+ error_message: 'network down',+ })+ })+ })++ it('never fetches the team-wide count for orgs with the subscriptions feature', async () => {+ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ const teamWideCalls = mockSubscriptionsList.mock.calls.filter(+ ([, params]: [string, Record<string, unknown> | undefined]) => !params?.dashboard+ )+ expect(teamWideCalls).toHaveLength(0)+ })++ describe('feature flag exposure gating and notification delivery', () => {+ beforeEach(() => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SUBSCRIBE_NUDGE]: 'test' })+ })++ it('does not read the flag while the existing-subscription check is in flight', () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)++ // Synchronously after the threshold view: the check hasn't resolved yet.+ expect(logic.values.hasExistingSubscription).toBeNull()+ expect(logic.values.isEligible).toBe(false)+ expect(logic.values.flagVariant).toBeUndefined()+ })++ it('suppresses the dashboard permanently when it already has a subscription, without reading the flag or notifying', async () => {+ mockSubscriptionsList.mockResolvedValue({ count: 1, results: [{ id: 7 }] })++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ expect(logic.values.isSuppressed).toBe(true)+ expect(logic.values.isCandidate).toBe(false)+ expect(logic.values.flagVariant).toBeUndefined()+ expect(mockSubscriptionsList).toHaveBeenCalledTimes(1)+ expect(nudgePostCount).toBe(0)++ // Further views on a suppressed dashboard never re-trigger the check.+ await expectLogic(logic, () => {+ recordViews(1)+ }).toFinishAllListeners()+ expect(mockSubscriptionsList).toHaveBeenCalledTimes(1)+ })++ it('requests the notification once when eligible, reporting shown and toasting on creation', async () => {+ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ // After a successful delivery the notified marker deliberately ends candidacy,+ // so the observable outcomes are the POST, the marker, the event, and the toast.+ expect(nudgePostCount).toBe(1)+ expect(logic.values.isNotified).toBe(true)+ expect(capturesOf('dashboard subscribe nudge shown')).toEqual([+ [+ 'dashboard subscribe nudge shown',+ { dashboard_id: DASHBOARD_ID, view_count_7d: DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD },+ ],+ ])+ expect(lemonToast.info).toHaveBeenCalledTimes(1)++ // A further view neither refetches, re-posts, nor re-reports.+ await expectLogic(logic, () => {+ recordViews(1)+ }).toFinishAllListeners()+ expect(mockSubscriptionsList).toHaveBeenCalledTimes(1)+ expect(nudgePostCount).toBe(1)+ expect(capturesOf('dashboard subscribe nudge shown')).toHaveLength(1)+ })++ it('shows a sticky stacked toast carrying the send-time view count', async () => {+ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ const [body, options] = (lemonToast.info as jest.Mock).mock.calls[0]+ // Sticky: persists until the CTA (which dismisses via the toastId) or the X.+ expect(options).toMatchObject({+ autoClose: false,+ toastId: `dashboard-subscribe-nudge-${DASHBOARD_ID}`,+ })+ expect(body.type).toBe(DashboardSubscribeNudgeToast)+ expect(body.props).toEqual({+ dashboardId: DASHBOARD_ID,+ dashboardName: 'Test dashboard',+ viewCount7d: DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD,+ })+ })++ it('the toast CTA dismisses the toast and routes to the prefilled new-subscription form', () => {+ onDashboardSubscribeNudgeToastCta(DASHBOARD_ID)++ expect(lemonToast.dismiss).toHaveBeenCalledWith(`dashboard-subscribe-nudge-${DASHBOARD_ID}`)+ expect(router.values.location.pathname).toMatch(new RegExp(`/dashboard/${DASHBOARD_ID}/subscriptions/new$`))+ expect(router.values.searchParams).toMatchObject({ prefill: 'nudge', via: 'toast' })+ })++ it('does not burn the client marker when the server reports nothing was created', async () => {+ // created:false covers a server dedupe-skip AND a released sentinel (notifications+ // unavailable / opt-out) — the marker must not stick, so the nudge can retry later.+ nudgePostResponse = [200, { created: false }]++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ expect(nudgePostCount).toBe(1)+ expect(logic.values.isNotified).toBe(false)+ expect(capturesOf('dashboard subscribe nudge shown')).toHaveLength(0)+ expect(lemonToast.info).not.toHaveBeenCalled()++ // The next qualifying visit (fresh mount) retries; the server sentinel still+ // collapses genuine duplicates.+ logic.unmount()+ logic = dashboardSubscribeNudgeLogic({ dashboardId: DASHBOARD_ID })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(nudgePostCount).toBe(2)+ })++ it('reports the notify failure and does not mark notified when the delivery request errors', async () => {+ silenceKeaLoadersErrors()+ nudgePostResponse = [500, {}]++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()+ resumeKeaLoadersErrors()++ expect(logic.values.isNotified).toBe(false)+ expect(capturesOf('dashboard subscribe nudge shown')).toHaveLength(0)+ const failures = capturesOf('dashboard subscribe nudge check failed')+ expect(failures).toHaveLength(1)+ expect(failures[0][1]).toMatchObject({ dashboard_id: DASHBOARD_ID, step: 'notify' })+ })++ it('reports the check failure and stays hidden when the eligibility check errors', async () => {+ silenceKeaLoadersErrors()+ mockSubscriptionsList.mockRejectedValue(new Error('network down'))++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()+ resumeKeaLoadersErrors()++ expect(logic.values.showNudge).toBe(false)+ expect(nudgePostCount).toBe(0)+ const failures = capturesOf('dashboard subscribe nudge check failed')+ expect(failures).toHaveLength(1)+ expect(failures[0][1]).toMatchObject({+ dashboard_id: DASHBOARD_ID,+ step: 'check',+ error_message: 'network down',+ })+ })++ it('does not notify already-notified dashboards, and skips their eligibility fetch entirely', async () => {+ storeLogic.actions.markDashboardNotified(DASHBOARD_ID)++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ expect(logic.values.isCandidate).toBe(false)+ expect(mockSubscriptionsList).not.toHaveBeenCalled()+ expect(nudgePostCount).toBe(0)+ })+ })++ it('does not notify for the control variant', async () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SUBSCRIBE_NUDGE]: 'control' })++ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ expect(logic.values.isEligible).toBe(true)+ expect(logic.values.showNudge).toBe(false)+ expect(nudgePostCount).toBe(0)+ })++ it('requests the notification when feature flags resolve only after the check completed', async () => {+ // No flag variant yet: the check resolves eligible but the nudge can't fire.+ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()+ expect(nudgePostCount).toBe(0)++ // Flags arrive late — the nudge must still be delivered.+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SUBSCRIBE_NUDGE]: 'test' })+ await expectLogic(logic).toFinishAllListeners()++ expect(nudgePostCount).toBe(1)+ expect(capturesOf('dashboard subscribe nudge shown')).toHaveLength(1)+ })++ it.each([+ [true, 1],+ [false, 0],+ ])(+ 'reuses an already-mounted subscriptionsLogic without calling the API (has subscription: %s)',+ async (hasSubscription, expectedCount) => {+ useMocks({+ get: {+ '/api/environments/:team_id/subscriptions': {+ count: expectedCount,+ results: hasSubscription ? [{ id: 7 }] : [],+ },+ },+ })+ const subsLogic = subscriptionsLogic({ dashboardId: DASHBOARD_ID })+ subsLogic.mount()+ await expectLogic(subsLogic).toFinishAllListeners()++ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SUBSCRIBE_NUDGE]: 'test' })+ await expectLogic(logic, () => {+ recordViews(DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD)+ }).toFinishAllListeners()++ expect(mockSubscriptionsList).not.toHaveBeenCalled()+ expect(logic.values.hasExistingSubscription).toBe(hasSubscription)+ expect(nudgePostCount).toBe(hasSubscription ? 0 : 1)++ subsLogic.unmount()+ }+ )++ it('caps the suppression list at the most recent entries', () => {+ for (let i = 1; i <= MAX_TRACKED_DASHBOARDS + 1; i++) {+ logic.actions.suppressDashboardNudge(i)+ }+ const suppressed = storeLogic.values.suppressedDashboardIds+ expect(suppressed).toHaveLength(MAX_TRACKED_DASHBOARDS)+ expect(suppressed).not.toContain(1) // oldest evicted+ expect(suppressed).toContain(MAX_TRACKED_DASHBOARDS + 1) // newest kept+ })++ it('caps the view log at the most recently viewed dashboards', () => {+ for (let i = 1; i <= MAX_TRACKED_DASHBOARDS + 1; i++) {+ now += 1000+ logic.actions.recordDashboardView(i)+ }+ const trackedIds = Object.keys(storeLogic.values.viewLog)+ expect(trackedIds).toHaveLength(MAX_TRACKED_DASHBOARDS)+ expect(trackedIds).not.toContain('1') // least recently viewed evicted+ expect(trackedIds).toContain(String(MAX_TRACKED_DASHBOARDS + 1)) // newest kept+ })++ it('isolates persisted state between scopes so a second account never inherits the first', () => {+ // Two accounts on the same browser: distinct scope keys must not share view counts.+ const scopeA = dashboardSubscribeNudgeStoreLogic({ scope: '1:user-a' })+ const scopeB = dashboardSubscribeNudgeStoreLogic({ scope: '2:user-b' })+ scopeA.mount()+ scopeB.mount()++ scopeA.actions.recordDashboardView(DASHBOARD_ID)++ expect(scopeA.values.viewLog[DASHBOARD_ID]).toHaveLength(1)+ expect(scopeB.values.viewLog[DASHBOARD_ID]).toBeUndefined()++ // The scope reaches the persistence layer: each account gets its own namespaced entry,+ // and there is no shared unscoped entry both would read back on a later visit.+ const persistedViewLogKeys = Object.keys(window.localStorage).filter(+ (storageKey) => storageKey.startsWith(`${STORE_PATH}.`) && storageKey.endsWith('.viewLog')+ )+ expect(persistedViewLogKeys).toEqual(+ expect.arrayContaining([`${STORE_PATH}.1:user-a.viewLog`, `${STORE_PATH}.2:user-b.viewLog`])+ )+ expect(window.localStorage.getItem(`${STORE_PATH}.viewLog`)).toBeNull()++ scopeA.unmount()+ scopeB.unmount()+ })+})diff --git a/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.ts b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.tsnew file mode 100644index 000000000000..d2c478009819--- /dev/null+++ b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeLogic.ts@@ -0,0 +1,268 @@+import { BreakPointFunction, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { dashboardsSubscribeNudgeCreate } from '@posthog/products-dashboards/frontend/generated/api'+import type { DashboardSubscribeNudgeResponseApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import posthog from 'lib/posthog-typed'+import { getCurrentTeamId } from 'lib/utils/getAppContext'+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import {+ dashboardNudgeScopeKey,+ dashboardSubscribeNudgeStoreLogic,+ freshTimestamps,+} from 'scenes/dashboard/dashboardSubscribeNudgeStoreLogic'+import { showDashboardSubscribeNudgeToast } from 'scenes/dashboard/DashboardSubscribeNudgeToast'+import { userLogic } from 'scenes/userLogic'++import { AvailableFeature, DashboardPlacement } from '~/types'++import { subscriptionsLogic } from 'products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic'+import { isFreeTierCreateAtLimit } from 'products/subscriptions/frontend/components/Subscriptions/views/EditSubscription'+import { subscriptionsList } from 'products/subscriptions/frontend/generated/api'++import type { dashboardSubscribeNudgeLogicType } from './dashboardSubscribeNudgeLogicType'++export const DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD = 3++export interface DashboardSubscribeNudgeLogicProps {+ dashboardId: number+}++export const dashboardSubscribeNudgeLogic = kea<dashboardSubscribeNudgeLogicType>([+ path((key) => ['scenes', 'dashboard', 'dashboardSubscribeNudgeLogic', key]),+ props({} as DashboardSubscribeNudgeLogicProps),+ key((props) => props.dashboardId),+ connect((props: DashboardSubscribeNudgeLogicProps) => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ dashboardLogic({ id: props.dashboardId }),+ ['dashboard', 'canEditDashboard', 'placement'],+ userLogic,+ ['hasAvailableFeature'],+ dashboardSubscribeNudgeStoreLogic({ scope: dashboardNudgeScopeKey() }),+ ['viewLog', 'suppressedDashboardIds', 'notifiedDashboardIds'],+ ],+ actions: [+ dashboardLogic({ id: props.dashboardId }),+ ['reportDashboardViewed'],+ dashboardSubscribeNudgeStoreLogic({ scope: dashboardNudgeScopeKey() }),+ ['recordDashboardView', 'suppressDashboardNudge', 'markDashboardNotified'],+ ],+ })),+ loaders(({ props }) => ({+ // Whether this dashboard already has a subscription. null = not checked yet. Only fetched+ // once every free, local check has passed (`isCandidate`: repeat views, not already+ // nudged/dismissed, subscribable dashboard) — most dashboard views make no request at all.+ // `load` prefix + initKea's ERROR_FILTER_ALLOW_LIST keep a failed background check from+ // toasting at a user who never asked for anything.+ hasExistingSubscription: [+ null as boolean | null,+ {+ loadExistingSubscription: async (_?: unknown, breakpoint?: BreakPointFunction) => {+ // If a subscriptionsLogic for this dashboard is already mounted (e.g. the+ // subscriptions modal was opened), reuse its data instead of refetching.+ const mounted = subscriptionsLogic.findMounted({ dashboardId: props.dashboardId })+ if (mounted && !mounted.values.subscriptionsLoading) {+ return mounted.values.subscriptions.length > 0+ }+ // limit=1 keeps the payload tiny; `count` reflects the dashboard's full total.+ const response = await subscriptionsList(String(getCurrentTeamId()), {+ dashboard: props.dashboardId,+ limit: 1,+ })+ breakpoint?.()+ return (response.count ?? 0) > 0+ },+ },+ ],+ // Team-wide subscription count, fetched only for free-tier candidates: those orgs can+ // create subscriptions until SubscriptionFreeTierLimit.COUNT, and nudging someone already+ // at the limit would push them straight into the create-form paywall.+ teamSubscriptionCount: [+ null as number | null,+ {+ loadTeamSubscriptionCount: async (_?: unknown, breakpoint?: BreakPointFunction) => {+ // limit=1 keeps the payload tiny; `count` reflects the team's full total.+ const response = await subscriptionsList(String(getCurrentTeamId()), { limit: 1 })+ breakpoint?.()+ return response.count ?? 0+ },+ },+ ],+ // Asks the backend to deliver the in-app nudge notification. The server dedupes per+ // (user, dashboard) and reports whether a notification was actually created.+ nudgeNotification: [+ null as DashboardSubscribeNudgeResponseApi | null,+ {+ sendNudgeNotification: async (_?: unknown, breakpoint?: BreakPointFunction) => {+ const response = await dashboardsSubscribeNudgeCreate(String(getCurrentTeamId()), props.dashboardId)+ breakpoint?.()+ return response+ },+ },+ ],+ })),+ selectors({+ viewCount7d: [+ (s) => [s.viewLog, (_, props) => props.dashboardId],+ (viewLog, dashboardId): number => freshTimestamps(viewLog[dashboardId] ?? [], Date.now()).length,+ ],+ isPastViewThreshold: [+ (s) => [s.viewCount7d],+ (viewCount7d): boolean => viewCount7d >= DASHBOARD_SUBSCRIBE_NUDGE_VIEW_THRESHOLD,+ ],+ isSuppressed: [+ (s) => [s.suppressedDashboardIds, (_, props) => props.dashboardId],+ (suppressedDashboardIds, dashboardId): boolean => suppressedDashboardIds.includes(dashboardId),+ ],+ isNotified: [+ (s) => [s.notifiedDashboardIds, (_, props) => props.dashboardId],+ (notifiedDashboardIds, dashboardId): boolean => notifiedDashboardIds.includes(dashboardId),+ ],+ // Excludes shared/public/embedded placements — the nudge only makes sense where "set up a+ // subscription" is an action the viewer can actually take. Free-tier orgs are NOT excluded+ // here: they can create subscriptions up to SubscriptionFreeTierLimit.COUNT, so their gate+ // is the count check in `isWithinSubscriptionLimit` instead.+ isDashboardEligible: [+ (s) => [s.dashboard, s.canEditDashboard, s.placement],+ (dashboard, canEditDashboard, placement): boolean =>+ !!dashboard && canEditDashboard && placement === DashboardPlacement.Dashboard,+ ],+ hasSubscriptionsFeature: [+ (s) => [s.hasAvailableFeature],+ (hasAvailableFeature): boolean => hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS),+ ],+ // Cheap half of eligibility: needs no API data, so the existing-subscription fetch only+ // happens for dashboards that pass this first.+ isCandidate: [+ (s) => [s.isPastViewThreshold, s.isSuppressed, s.isNotified, s.isDashboardEligible],+ (isPastViewThreshold, isSuppressed, isNotified, isDashboardEligible): boolean =>+ isPastViewThreshold && !isSuppressed && !isNotified && isDashboardEligible,+ ],+ // Paid orgs are never limited. Free-tier orgs must have room under the free-tier cap —+ // and unlike EditSubscription (where a null count fails open because the user explicitly+ // asked and the backend is the hard gate), a proactive nudge fails closed on an unknown+ // count: don't advertise an action we can't confirm they can complete.+ isWithinSubscriptionLimit: [+ (s) => [s.hasSubscriptionsFeature, s.teamSubscriptionCount],+ (hasSubscriptionsFeature, teamSubscriptionCount): boolean =>+ hasSubscriptionsFeature ||+ (teamSubscriptionCount !== null && !isFreeTierCreateAtLimit(teamSubscriptionCount)),+ ],+ isEligible: [+ (s) => [s.isCandidate, s.hasExistingSubscription, s.isWithinSubscriptionLimit],+ (isCandidate, hasExistingSubscription, isWithinSubscriptionLimit): boolean =>+ isCandidate && hasExistingSubscription === false && isWithinSubscriptionLimit,+ ],+ // CRITICAL: `featureFlags[...]` is a proxy access that reports the flag's exposure event the+ // first time it's read. Only touch it once `isEligible` is true, so the experiment's exposure+ // ($feature_flag_called) fires only for the population that could actually receive the nudge.+ flagVariant: [+ (s) => [s.isEligible, s.featureFlags],+ (isEligible, featureFlags): string | boolean | undefined =>+ isEligible ? featureFlags[FEATURE_FLAGS.DASHBOARD_SUBSCRIBE_NUDGE] : undefined,+ ],+ showNudge: [(s) => [s.flagVariant], (flagVariant): boolean => flagVariant === 'test'],+ }),+ listeners(({ actions, values, props }) => ({+ reportDashboardViewed: () => {+ actions.recordDashboardView(props.dashboardId)+ },+ recordDashboardView: ({ dashboardId }) => {+ if (dashboardId !== props.dashboardId || !values.isCandidate) {+ return+ }+ if (values.hasExistingSubscription === null && !values.hasExistingSubscriptionLoading) {+ actions.loadExistingSubscription()+ }+ if (+ !values.hasSubscriptionsFeature &&+ values.teamSubscriptionCount === null &&+ !values.teamSubscriptionCountLoading+ ) {+ actions.loadTeamSubscriptionCount()+ }+ },+ loadExistingSubscriptionSuccess: ({ hasExistingSubscription }) => {+ if (hasExistingSubscription) {+ // The viewer clearly knows the feature — permanently stop nudging (and rechecking)+ // this dashboard, even if the subscription is later deleted.+ actions.suppressDashboardNudge(props.dashboardId)+ }+ },+ loadExistingSubscriptionFailure: ({ error, errorObject }) => {+ // Distinguishes a broken eligibility check from genuine ineligibility in the experiment readout.+ posthog.capture('dashboard subscribe nudge check failed', {+ dashboard_id: props.dashboardId,+ step: 'check',+ error_name: errorObject?.name,+ error_status: errorObject?.status,+ error_message: error,+ })+ },+ loadTeamSubscriptionCountFailure: ({ error, errorObject }) => {+ // A failed count check silently excludes a free-tier user (fail closed) — capture it so+ // the readout can tell that apart from genuinely being at the limit.+ posthog.capture('dashboard subscribe nudge check failed', {+ dashboard_id: props.dashboardId,+ step: 'limit',+ error_name: errorObject?.name,+ error_status: errorObject?.status,+ error_message: error,+ })+ },+ sendNudgeNotificationSuccess: ({ nudgeNotification }) => {+ if (!nudgeNotification?.created) {+ // Nothing was delivered (server dedupe-skip, notifications unavailable, or user+ // opt-out) — don't burn the client marker; a later qualifying visit retries and the+ // server sentinel still collapses races.+ return+ }+ // Delivered — never request again from this browser.+ actions.markDashboardNotified(props.dashboardId)+ posthog.capture('dashboard subscribe nudge shown', {+ dashboard_id: props.dashboardId,+ view_count_7d: values.viewCount7d,+ })+ showDashboardSubscribeNudgeToast(props.dashboardId, values.dashboard?.name, values.viewCount7d)+ },+ sendNudgeNotificationFailure: ({ error, errorObject }) => {+ // Not marked notified: the next qualifying visit retries.+ posthog.capture('dashboard subscribe nudge check failed', {+ dashboard_id: props.dashboardId,+ step: 'notify',+ error_name: errorObject?.name,+ error_status: errorObject?.status,+ error_message: error,+ })+ },+ })),+ subscriptions(({ actions, values, cache }) => ({+ // The nudge is requested off the fully-gated state itself (eligibility + test variant),+ // so it also fires when feature flags resolve after the subscription check completed.+ showNudge: (showNudge: boolean) => {+ if (showNudge && !cache.nudgeRequested && !values.nudgeNotificationLoading) {+ cache.nudgeRequested = true+ actions.sendNudgeNotification()+ }+ },+ })),+ afterMount(({ actions, values }) => {+ // Covers dashboards already past the threshold from earlier sessions; new views route+ // through the recordDashboardView listener instead.+ if (!values.isCandidate) {+ return+ }+ if (values.hasExistingSubscription === null) {+ actions.loadExistingSubscription()+ }+ if (!values.hasSubscriptionsFeature && values.teamSubscriptionCount === null) {+ actions.loadTeamSubscriptionCount()+ }+ }),+])diff --git a/frontend/src/scenes/dashboard/dashboardSubscribeNudgeStoreLogic.ts b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeStoreLogic.tsnew file mode 100644index 000000000000..800c586e4b4c--- /dev/null+++ b/frontend/src/scenes/dashboard/dashboardSubscribeNudgeStoreLogic.ts@@ -0,0 +1,122 @@+import { actions, kea, key, path, props, reducers } from 'kea'++import { getCurrentTeamIdOrNone, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'++import type { dashboardSubscribeNudgeStoreLogicType } from './dashboardSubscribeNudgeStoreLogicType'++export const DASHBOARD_VIEW_LOG_WINDOW_MS = 7 * 24 * 60 * 60 * 1000+// dashboardLogic dispatches reportDashboardViewed more than once per real page view (on mount and+// again after the API load); dispatches this close together are the same visit and count once.+export const DASHBOARD_VIEW_DEDUPE_WINDOW_MS = 60 * 1000+export const MAX_TRACKED_DASHBOARDS = 100++/** Per-dashboard view timestamps within the trailing window, keyed by dashboard id. */+export type DashboardViewLog = Record<string, number[]>++/** Timestamps still inside the trailing 7-day window. */+export function freshTimestamps(timestamps: number[], now: number): number[] {+ const cutoff = now - DASHBOARD_VIEW_LOG_WINDOW_MS+ return timestamps.filter((timestamp) => timestamp > cutoff)+}++// Shared shape for the persisted per-dashboard marker lists: append-once, bounded to the+// most recent entries.+function appendCapped(state: number[], { dashboardId }: { dashboardId: number }): number[] {+ return state.includes(dashboardId) ? state : [...state, dashboardId].slice(-MAX_TRACKED_DASHBOARDS)+}++// Prunes stale timestamps across the whole map and drops dashboards left with none, so the+// persisted entry stays bounded no matter how many dashboards were ever viewed. Returns the+// original reference untouched when nothing was stale, so a no-op dedupe skips a redundant+// persist of the whole map.+function pruneViewLog(log: DashboardViewLog, now: number): DashboardViewLog {+ const pruned: DashboardViewLog = {}+ let changed = false+ for (const [dashboardId, timestamps] of Object.entries(log)) {+ const fresh = freshTimestamps(timestamps, now)+ if (fresh.length > 0) {+ pruned[dashboardId] = fresh+ }+ if (fresh.length !== timestamps.length) {+ changed = true+ }+ }+ return changed ? pruned : log+}++export interface DashboardSubscribeNudgeStoreLogicProps {+ /** Isolates persisted state per team+user so a second account on the same browser never+ * inherits the first account's view counts, suppressions, or notified markers. */+ scope: string+}++// Derived at mount time from app context, which is set before any logic mounts. Anonymous viewers+// (public/shared dashboards) fall back to 'anon' rather than throwing.+export function dashboardNudgeScopeKey(): string {+ return `${getCurrentTeamIdOrNone() ?? 'anon'}:${getCurrentUserIdOrNone() ?? 'anon'}`+}++// Per-scope store behind the dashboard subscribe nudge: one persisted map of recent views for+// all dashboards (instead of a localStorage entry per dashboard ever viewed), plus the set of+// dashboards permanently excluded from the nudge. Keyed by scope so kea derives a distinct+// localStorage key per team+user.+export const dashboardSubscribeNudgeStoreLogic = kea<dashboardSubscribeNudgeStoreLogicType>([+ path((key) => ['scenes', 'dashboard', 'dashboardSubscribeNudgeStoreLogic', key]),+ props({} as DashboardSubscribeNudgeStoreLogicProps),+ key((props) => props.scope),+ actions({+ recordDashboardView: (dashboardId: number) => ({ dashboardId }),+ suppressDashboardNudge: (dashboardId: number) => ({ dashboardId }),+ markDashboardNotified: (dashboardId: number) => ({ dashboardId }),+ }),+ reducers({+ viewLog: [+ {} as DashboardViewLog,+ { persist: true },+ {+ recordDashboardView: (state, { dashboardId }) => {+ const now = Date.now()+ const pruned = pruneViewLog(state, now)+ const existing = pruned[dashboardId] ?? []+ const lastView = existing[existing.length - 1]+ if (lastView !== undefined && now - lastView < DASHBOARD_VIEW_DEDUPE_WINDOW_MS) {+ // Same real visit re-reported (remount, post-load re-dispatch) — count it once.+ // pruneViewLog hands back the original reference when nothing was stale, so this+ // no-op path leaves state identity intact and skips a redundant full-map write.+ return pruned+ }+ const next: DashboardViewLog = { ...pruned, [dashboardId]: [...existing, now] }+ // Bound the map in both dimensions: pruning caps the time axis, this caps the+ // number of distinct dashboards by evicting the least recently viewed ones.+ const keys = Object.keys(next)+ if (keys.length > MAX_TRACKED_DASHBOARDS) {+ const lastViewOf = (key: string): number => next[key][next[key].length - 1]+ keys.sort((a, b) => lastViewOf(a) - lastViewOf(b))+ for (const key of keys.slice(0, keys.length - MAX_TRACKED_DASHBOARDS)) {+ delete next[key]+ }+ }+ return next+ },+ },+ ],+ // Dashboards observed to already have a subscription: the viewer clearly knows the feature,+ // so they are never nudged for that dashboard again — even if the subscription is later deleted.+ suppressedDashboardIds: [+ [] as number[],+ { persist: true },+ {+ suppressDashboardNudge: appendCapped,+ },+ ],+ // Dashboards the nudge notification was already requested for — never request again from+ // this browser (the server also dedupes, this just avoids pointless calls).+ notifiedDashboardIds: [+ [] as number[],+ { persist: true },+ {+ markDashboardNotified: appendCapped,+ },+ ],+ }),+])diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 99f63f64d9af..a9196c5f6f19 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -84,7 +84,13 @@ from posthog.slo.context import SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperationfrom posthog.sync import database_sync_to_asyncfrom posthog.user_permissions import UserPermissionsSerializerMixin-from posthog.utils import filters_override_requested_by_client, str_to_bool, variables_override_requested_by_client+from posthog.utils import (+ filters_override_requested_by_client,+ safe_cache_add,+ safe_cache_delete,+ str_to_bool,+ variables_override_requested_by_client,+)from products.ai_observability.backend.dashboard_templates import get_ai_observability_default_templatefrom products.alerts.backend.models.alert import AlertConfiguration@@ -126,6 +132,14 @@ from products.dashboards.backend.widget_registry import (validate_widget_config,)from products.mcp_analytics.backend.dashboard_templates import get_mcp_analytics_default_template+from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ TargetType,+ create_notification,+ has_been_dispatched,+)from products.product_analytics.backend.api.insight import (DashboardTileBasicSerializer,InsightSerializer,@@ -178,6 +192,9 @@ tracer = trace.get_tracer(__name__)RUN_WIDGETS_QUERY_CONCURRENCY = 4+# One subscribe-nudge notification per (user, dashboard) within this window.+SUBSCRIBE_NUDGE_DEDUPE_TTL_SECONDS = 30 * 24 * 60 * 60+WIDGET_TYPE_API_HELP = ("Widget type identifier. Supported values: "+ ", ".join(sorted(EXPECTED_WIDGET_TYPES))@@ -2062,6 +2079,13 @@ class DashboardSerializer(DashboardMetadataSerializer):return {**validated_data, "creation_mode": "default"}+class DashboardSubscribeNudgeResponseSerializer(serializers.Serializer):+ created = serializers.BooleanField(+ help_text="Whether a nudge notification was created. False when one was already sent recently "+ "for this user and dashboard, or when in-app notifications are unavailable."+ )++@extend_schema_view(list=extend_schema(parameters=[@@ -2191,6 +2215,13 @@ class DashboardsViewSet(assert self.team.project_id is not Nonequeryset = self.queryset.filter(team__project_id=self.team.project_id)+ # subscribe_nudge only reads the dashboard's pk and name, so skip the detail prefetch+ # cascade (tiles → insights → their dashboards) and the folder/last-viewed annotations.+ # Team scoping is preserved by the filter above; the CanEditDashboard object permission+ # still gates the write.+ if self.action == "subscribe_nudge":+ return queryset.exclude(deleted=True)+if self.request.user.is_authenticated:queryset = queryset.alias(recent_dashboard_views=FilteredRelation(@@ -3277,6 +3308,68 @@ class DashboardsViewSet(status=status.HTTP_201_CREATED,)+ @extend_schema(+ request=None,+ responses={+ 201: DashboardSubscribeNudgeResponseSerializer,+ 200: DashboardSubscribeNudgeResponseSerializer,+ },+ description="Send the requesting user an in-app notification suggesting they subscribe to this "+ "dashboard. Deduplicated server-side: at most one notification per user and dashboard, ever, "+ "so repeat calls return 200 with created=false.",+ )+ @action(methods=["POST"], detail=True, url_path="subscribe_nudge", required_scopes=["dashboard:write"])+ def subscribe_nudge(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ dashboard = self.get_object()+ user = cast(User, request.user)++ dedupe_key = f"dashboard_subscribe_nudge:{user.pk}:{dashboard.pk}"+ if not safe_cache_add(dedupe_key, "1", timeout=SUBSCRIBE_NUDGE_DEDUPE_TTL_SECONDS):+ return Response({"created": False}, status=status.HTTP_200_OK)++ # Durable backstop behind the cache sentinel: a nudge is once-ever per (user, dashboard),+ # so losing the sentinel (cache flush, eviction, Redis outage) must not let a second one+ # through. Mirrors the client's permanent notified marker.+ if has_been_dispatched(+ notification_type=NotificationType.SUBSCRIPTION_NUDGE,+ target_type=TargetType.USER,+ target_id=str(user.pk),+ resource_id=str(dashboard.pk),+ ):+ return Response({"created": False}, status=status.HTTP_200_OK)++ try:+ event = create_notification(+ NotificationData(+ team_id=self.team_id,+ notification_type=NotificationType.SUBSCRIPTION_NUDGE,+ priority=Priority.NORMAL,+ title=f"You keep coming back to {dashboard.name or 'this dashboard'}",+ body="Get it delivered to your inbox every Monday instead of checking back.",+ target_type=TargetType.USER,+ target_id=str(user.pk),+ resource_type="dashboard",+ resource_id=str(dashboard.pk),+ # Query params mirror SUBSCRIPTION_PREFILL_PARAMS in+ # products/subscriptions/frontend/components/Subscriptions/utils.tsx, which+ # consumes them to prefill the new-subscription form.+ source_url=f"/dashboard/{dashboard.pk}/subscriptions/new?prefill=nudge&via=notification",+ )+ )+ except Exception:+ # Release the sentinel so a transient create_notification failure doesn't burn the+ # nudge for the full dedupe window; then let the error propagate.+ safe_cache_delete(dedupe_key)+ raise+ if event is None:+ # Notifications disabled or no recipients resolved — report honestly so the caller+ # doesn't treat this as a delivered nudge, and release the sentinel so the nudge isn't+ # silently burned for 30 days once the condition clears.+ safe_cache_delete(dedupe_key)+ return Response({"created": False}, status=status.HTTP_200_OK)++ return Response({"created": True}, status=status.HTTP_201_CREATED)+class LegacyDashboardsViewSet(DashboardsViewSet):param_derived_from_user_current_team = "project_id"diff --git a/products/dashboards/backend/api/test/test_dashboard_subscribe_nudge.py b/products/dashboards/backend/api/test/test_dashboard_subscribe_nudge.pynew file mode 100644index 000000000000..338250b0b730--- /dev/null+++ b/products/dashboards/backend/api/test/test_dashboard_subscribe_nudge.py@@ -0,0 +1,168 @@+from typing import TYPE_CHECKING++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.core.cache import cache++from rest_framework import status++if TYPE_CHECKING:+ from rest_framework.response import _MonkeyPatchedResponse++from posthog.constants import AvailableFeature+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.team import Team+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.dashboards.backend.models.dashboard import Dashboard+from products.notifications.backend.facade.api import NotificationType, Priority, TargetType++from ee.models.rbac.access_control import AccessControl+++@patch("products.dashboards.backend.api.dashboard.create_notification")+class TestDashboardSubscribeNudge(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ cache.clear()+ self.dashboard = Dashboard.objects.create(team=self.team, name="Key metrics", created_by=self.user)++ def _post_nudge(self, dashboard_id: int) -> "_MonkeyPatchedResponse":+ return self.client.post(f"/api/environments/{self.team.id}/dashboards/{dashboard_id}/subscribe_nudge/")++ def test_creates_notification_for_requesting_user(self, mock_create_notification: MagicMock) -> None:+ mock_create_notification.return_value = MagicMock()++ response = self._post_nudge(self.dashboard.id)++ assert response.status_code == status.HTTP_201_CREATED+ assert response.json() == {"created": True}++ data = mock_create_notification.call_args.args[0]+ assert data.notification_type == NotificationType.SUBSCRIPTION_NUDGE+ assert data.priority == Priority.NORMAL+ assert data.target_type == TargetType.USER+ assert data.target_id == str(self.user.id)+ assert data.resource_type == "dashboard"+ assert data.resource_id == str(self.dashboard.id)+ assert data.title == "You keep coming back to Key metrics"+ assert data.source_url == f"/dashboard/{self.dashboard.id}/subscriptions/new?prefill=nudge&via=notification"++ def test_dedupes_repeat_calls_per_user_and_dashboard(self, mock_create_notification: MagicMock) -> None:+ mock_create_notification.return_value = MagicMock()++ first = self._post_nudge(self.dashboard.id)+ second = self._post_nudge(self.dashboard.id)++ assert first.status_code == status.HTTP_201_CREATED+ assert second.status_code == status.HTTP_200_OK+ assert second.json() == {"created": False}+ assert mock_create_notification.call_count == 1++ @patch("products.dashboards.backend.api.dashboard.has_been_dispatched")+ def test_dedupes_from_the_notification_record_when_the_cache_is_lost(+ self, mock_has_been_dispatched: MagicMock, mock_create_notification: MagicMock+ ) -> None:+ mock_create_notification.return_value = MagicMock()+ mock_has_been_dispatched.return_value = False++ first = self._post_nudge(self.dashboard.id)+ assert first.status_code == status.HTTP_201_CREATED++ # The cache sentinel is gone (flush/eviction/Redis outage), but the notification record+ # is durable — the nudge stays once-ever rather than being re-delivered.+ cache.clear()+ mock_has_been_dispatched.return_value = True++ second = self._post_nudge(self.dashboard.id)++ assert second.status_code == status.HTTP_200_OK+ assert second.json() == {"created": False}+ assert mock_create_notification.call_count == 1+ mock_has_been_dispatched.assert_called_with(+ notification_type=NotificationType.SUBSCRIPTION_NUDGE,+ target_type=TargetType.USER,+ target_id=str(self.user.id),+ resource_id=str(self.dashboard.id),+ )++ def test_returns_404_for_other_team_dashboard(self, mock_create_notification: MagicMock) -> None:+ other_org = Organization.objects.create(name="Other org")+ other_team = Team.objects.create(organization=other_org, name="Other team")+ other_dashboard = Dashboard.objects.create(team=other_team, name="Not yours")++ response = self._post_nudge(other_dashboard.id)++ assert response.status_code == status.HTTP_404_NOT_FOUND+ mock_create_notification.assert_not_called()++ def test_releases_the_dedupe_sentinel_when_notifications_unavailable(+ self, mock_create_notification: MagicMock+ ) -> None:+ mock_create_notification.return_value = None++ response = self._post_nudge(self.dashboard.id)++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"created": False}++ # The sentinel must not burn the nudge for 30 days: once notifications become+ # available again, the next call creates.+ mock_create_notification.return_value = MagicMock()+ retry = self._post_nudge(self.dashboard.id)+ assert retry.status_code == status.HTTP_201_CREATED+ assert retry.json() == {"created": True}++ def test_releases_the_dedupe_sentinel_when_create_notification_raises(+ self, mock_create_notification: MagicMock+ ) -> None:+ mock_create_notification.side_effect = RuntimeError("notifications backend down")++ response = self._post_nudge(self.dashboard.id)++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR++ # The sentinel must be released on failure, not left to burn the nudge for 30 days:+ # once the backend recovers, the next call creates.+ mock_create_notification.side_effect = None+ mock_create_notification.return_value = MagicMock()+ retry = self._post_nudge(self.dashboard.id)+ assert retry.status_code == status.HTTP_201_CREATED+ assert retry.json() == {"created": True}++ def test_rejects_viewer_only_access_control(self, mock_create_notification: MagicMock) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ viewer = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)+ AccessControl.objects.create(+ resource="dashboard", resource_id=str(self.dashboard.id), team=self.team, access_level="viewer"+ )++ self.client.force_login(viewer)+ response = self._post_nudge(self.dashboard.id)++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mock_create_notification.assert_not_called()++ def test_rejects_read_scoped_api_key(self, mock_create_notification: MagicMock) -> None:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="dashboard read only",+ user=self.user,+ secure_value=hash_key_value(token),+ scopes=["dashboard:read"],+ scoped_teams=[],+ scoped_organizations=[],+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/dashboards/{self.dashboard.id}/subscribe_nudge/",+ HTTP_AUTHORIZATION=f"Bearer {token}",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mock_create_notification.assert_not_called()diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex aef9951785a2..327b7c114231 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -8480,6 +8480,11 @@ export interface RunWidgetsResponseApi {results: DashboardWidgetRunResultApi[]}+export interface DashboardSubscribeNudgeResponseApi {+ /** Whether a nudge notification was created. False when one was already sent recently for this user and dashboard, or when in-app notifications are unavailable. */+ created: boolean+}+export interface UpdateTextTileRequestApi {/** ID of the dashboard tile to update. Use dashboard-get to look up tile IDs. */tile_id: number@@ -9483,6 +9488,18 @@ export const DashboardsStreamTilesRetrieveLayoutSize = {Xs: 'xs',} as const+export type DashboardsSubscribeNudgeCreateParams = {+ format?: DashboardsSubscribeNudgeCreateFormat+}++export type DashboardsSubscribeNudgeCreateFormat =+ (typeof DashboardsSubscribeNudgeCreateFormat)[keyof typeof DashboardsSubscribeNudgeCreateFormat]++export const DashboardsSubscribeNudgeCreateFormat = {+ Json: 'json',+ Txt: 'txt',+} as const+export type DashboardsUpdateTextTileCreateParams = {format?: DashboardsUpdateTextTileCreateFormat}diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.tsindex b3ab3a73e757..228e0445a7ad 100644--- a/products/dashboards/frontend/generated/api.ts+++ b/products/dashboards/frontend/generated/api.ts@@ -18,6 +18,7 @@ import type {CreateTextTileRequestApi,DashboardApi,DashboardCollaboratorApi,+ DashboardSubscribeNudgeResponseApi,DashboardTemplateApi,DashboardTemplatesListParams,DashboardTileApi,@@ -38,6 +39,7 @@ import type {DashboardsRunInsightsRetrieveParams,DashboardsRunWidgetsRetrieveParams,DashboardsStreamTilesRetrieveParams,+ DashboardsSubscribeNudgeCreateParams,DashboardsUpdateParams,DashboardsUpdateTextTileCreateParams,DashboardsUpdateWidgetsBatchParams,@@ -780,6 +782,41 @@ export const dashboardsStreamTilesRetrieve = async (})}+export const getDashboardsSubscribeNudgeCreateUrl = (+ projectId: string,+ id: number,+ params?: DashboardsSubscribeNudgeCreateParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/dashboards/${id}/subscribe_nudge/?${stringifiedParams}`+ : `/api/projects/${projectId}/dashboards/${id}/subscribe_nudge/`+}++/**+ * Send the requesting user an in-app notification suggesting they subscribe to this dashboard. Deduplicated server-side: at most one notification per user and dashboard, ever, so repeat calls return 200 with created=false.+ */+export const dashboardsSubscribeNudgeCreate = async (+ projectId: string,+ id: number,+ params?: DashboardsSubscribeNudgeCreateParams,+ options?: RequestInit+): Promise<DashboardSubscribeNudgeResponseApi> => {+ return apiMutator<DashboardSubscribeNudgeResponseApi>(getDashboardsSubscribeNudgeCreateUrl(projectId, id, params), {+ ...options,+ method: 'POST',+ })+}+export const getDashboardsUpdateTextTileCreateUrl = (projectId: string,id: number,diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yamlindex 2bba8d9326ac..cca8b9ef2ba9 100644--- a/products/dashboards/mcp/tools.yaml+++ b/products/dashboards/mcp/tools.yaml@@ -512,6 +512,9 @@ tools:dashboards-stream-tiles-retrieve:operation: dashboards_stream_tiles_retrieveenabled: false+ dashboards-subscribe-nudge-create:+ operation: dashboards_subscribe_nudge_create+ enabled: falsedashboards-update:operation: dashboards_updateenabled: falsediff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 60ded344bb65..0d11e3707e30 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -18,6 +18,7 @@ class NotificationType(str, Enum):REMINDER = "reminder"WEB_ANALYTICS_DIGEST = "web_analytics_digest"ACHIEVEMENT_UNLOCKED = "achievement_unlocked"+ SUBSCRIPTION_NUDGE = "subscription_nudge"class Priority(str, Enum):diff --git a/products/notifications/backend/migrations/0018_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0018_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..dce271844706--- /dev/null+++ b/products/notifications/backend/migrations/0018_alter_notificationevent_notification_type.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.14 on 2026-07-15 07:35++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0017_notificationevent_archivable_notificationarchivestate"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notificationevent",+ name="notification_type",+ field=models.CharField(+ choices=[+ ("comment_mention", "COMMENT_MENTION"),+ ("alert_firing", "ALERT_FIRING"),+ ("issue_assigned", "ISSUE_ASSIGNED"),+ ("approval_requested", "APPROVAL_REQUESTED"),+ ("approval_resolved", "APPROVAL_RESOLVED"),+ ("experiment_concluded", "EXPERIMENT_CONCLUDED"),+ ("pipeline_failure", "PIPELINE_FAILURE"),+ ("project_created", "PROJECT_CREATED"),+ ("usage_spike", "USAGE_SPIKE"),+ ("reminder", "REMINDER"),+ ("web_analytics_digest", "WEB_ANALYTICS_DIGEST"),+ ("achievement_unlocked", "ACHIEVEMENT_UNLOCKED"),+ ("subscription_nudge", "SUBSCRIPTION_NUDGE"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex 7d36f23444ee..b3d74acdbf7f 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0017_notificationevent_archivable_notificationarchivestate+0018_alter_notificationevent_notification_typediff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.tsindex a503bd011a8a..7b8a854adf35 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts@@ -1,9 +1,14 @@+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { ApiError } from 'lib/api'import { getRecentSlackChannelIds } from 'lib/integrations/slackChannel'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { organizationLogic } from 'scenes/organizationLogic'+import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -11,6 +16,8 @@ import { InsightShortId, SubscriptionType } from '~/types'import { subscriptionLogic } from './subscriptionLogic'+jest.mock('posthog-js')+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({lemonToast: {success: jest.fn(),@@ -59,6 +66,8 @@ describe('subscriptionLogic', () => {},})initKeaTests()+ userLogic.mount()+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)newLogic = subscriptionLogic({insightShortId: Insight1,id: 'new',@@ -101,6 +110,9 @@ describe('subscriptionLogic', () => {bysetpos: 1,byweekday: ['monday'],})+ // A plain "new subscription" open (no prefill) must not pre-mark the form as changed,+ // otherwise "Create subscription" would be enabled before the user has done anything.+ expect(newLogic.values.subscriptionChanged).toBe(false)newLogic.actions.setSubscriptionValue('frequency', 'daily')await expectLogic(newLogic).toFinishListeners()@@ -127,6 +139,216 @@ describe('subscriptionLogic', () => {})})+ it.each<[string, string, string]>([+ // The notification's source_url carries via=notification; the transient toast via=toast.+ // Absent via defaults to notification for safety.+ ['?prefill=nudge&via=notification', 'notification', 'notification link'],+ ['?prefill=nudge&via=toast', 'toast', 'toast button'],+ ['?prefill=nudge', 'notification', 'legacy link without via'],+ ])('prefills the form from %s and reports the click (via=%s, %s)', async (search, expectedVia) => {+ // The nudge notification can be clicked days later in a fresh session, so the prefill is+ // built from the URL param + logic context, not from any preexisting kea state.+ const prefilledLogic = subscriptionLogic({+ dashboardId: 9,+ dashboardName: 'Key metrics',+ id: 'new',+ })+ prefilledLogic.mount()++ router.actions.push(`/dashboard/9/subscriptions/new${search}`)+ await expectLogic(prefilledLogic).toFinishListeners()++ expect(prefilledLogic.values.subscription).toMatchObject({+ title: 'Key metrics weekly digest',+ target_value: MOCK_DEFAULT_USER.email,+ frequency: 'weekly',+ target_type: 'email',+ })+ expect(prefilledLogic.values.subscriptionChanged).toBe(true)+ const clickedCaptures = (): any[][] =>+ (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === 'dashboard subscribe nudge clicked')+ expect(clickedCaptures()).toEqual([+ ['dashboard subscribe nudge clicked', { dashboard_id: 9, prefilled: true, via: expectedVia }],+ ])++ // The params are consumed on apply, so refreshing the resulting URL neither re-captures+ // the click nor re-applies a stale prefill.+ expect(prefilledLogic.values.subscription.title).toBe('Key metrics weekly digest')+ expect(router.values.searchParams.prefill).toBeUndefined()+ expect(router.values.searchParams.via).toBeUndefined()+ router.actions.push(router.values.location.pathname)+ await expectLogic(prefilledLogic).toFinishListeners()+ expect(clickedCaptures()).toHaveLength(1)++ prefilledLogic.unmount()+ })++ it.each<[string, boolean, boolean]>([+ // The prefill marks the form "changed" so Create is enabled, but the user never touched it —+ // navigating away must not pop the discard-changes prompt.+ ['an untouched prefilled form', false, false],+ // Any real edit on top of the prefill re-arms the prompt.+ ['a prefilled form the user then edited', true, true],+ ])('navigating away from %s prompts=%s', async (_label, editAfterPrefill, expectPrompt) => {+ const confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true)+ const prefilledLogic = subscriptionLogic({+ dashboardId: 9,+ dashboardName: 'Key metrics',+ id: 'new',+ })+ prefilledLogic.mount()++ router.actions.push('/dashboard/9/subscriptions/new?prefill=nudge')+ await expectLogic(prefilledLogic).toFinishListeners()+ if (editAfterPrefill) {+ prefilledLogic.actions.setSubscriptionValue('title', 'My own title')+ }++ router.actions.push('/insights/123')++ expect(confirmSpy).toHaveBeenCalledTimes(expectPrompt ? 1 : 0)+ expect(router.values.location.pathname).toMatch(/\/insights\/123$/)++ prefilledLogic.unmount()+ confirmSpy.mockRestore()+ })++ it.each<[string, string, boolean]>([+ // The dashboard-with-tiles nudge flow: InsightSelector auto-selects right after the prefill.+ // A reset here would wipe the prefill's "changed" flag and disable Create.+ ['a prefilled form', '?prefill=nudge', true],+ // Plain new subscription keeps existing behavior: auto-select resets to a clean form.+ ['a plain new form', '', false],+ ])('insight auto-select on %s leaves the form changed=%s', async (_label, search, expectChanged) => {+ const confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true)+ const testLogic = subscriptionLogic({+ dashboardId: 9,+ dashboardName: 'Key metrics',+ id: 'new',+ })+ testLogic.mount()++ router.actions.push(`/dashboard/9/subscriptions/new${search}`)+ await expectLogic(testLogic).toFinishListeners()++ testLogic.actions.applyInsightSelectionDefaults([101, 102])+ await expectLogic(testLogic).toFinishListeners()++ expect(testLogic.values.subscription.dashboard_export_insights).toEqual([101, 102])+ expect(testLogic.values.subscriptionChanged).toBe(expectChanged)++ // Either way the user never touched the form — navigating away must not prompt to discard.+ router.actions.push('/dashboard/9')+ expect(confirmSpy).not.toHaveBeenCalled()++ testLogic.unmount()+ confirmSpy.mockRestore()+ })++ it.each<[string, boolean, boolean, boolean]>([+ // The upsell mirrors the server-side create validation: consent + quota headroom required.+ ['consent accepted and quota ok', true, false, true],+ ['org AI consent missing', false, false, false],+ ['summary quota at limit', true, true, false],+ ])(+ 'nudge prefill with %s defaults summary_enabled=%s without arming the discard prompt',+ async (_label, consentAccepted, atLimit, expectEnabled) => {+ const confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true)+ // Settle the initial org load first, so the case's consent value can't be overwritten.+ await expectLogic(organizationLogic).toFinishAllListeners()+ organizationLogic.actions.loadCurrentOrganizationSuccess({+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: consentAccepted,+ })+ useMocks({+ get: {+ '/api/environments/:team/subscriptions/summary_quota': {+ active_count: 0,+ limit: 5,+ at_limit: atLimit,+ },+ },+ })+ const prefilledLogic = subscriptionLogic({+ dashboardId: 9,+ dashboardName: 'Key metrics',+ id: 'new',+ })+ prefilledLogic.mount()++ router.actions.push('/dashboard/9/subscriptions/new?prefill=nudge')+ // The quota answer arrives after the prefill applied — the default is deferred to it.+ await expectLogic(prefilledLogic).toFinishAllListeners()++ expect(!!prefilledLogic.values.subscription.summary_enabled).toBe(expectEnabled)++ // Untouched form: the deferred default is folded into the prefill baseline, so+ // navigating away never prompts to discard.+ router.actions.push('/insights/123')+ expect(confirmSpy).not.toHaveBeenCalled()++ prefilledLogic.unmount()+ confirmSpy.mockRestore()+ }+ )++ it('respects a manual summary toggle-off after the default applied, and the edited form prompts on leave', async () => {+ const confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true)+ await expectLogic(organizationLogic).toFinishAllListeners()+ organizationLogic.actions.loadCurrentOrganizationSuccess({+ ...MOCK_DEFAULT_ORGANIZATION,+ is_ai_data_processing_approved: true,+ })+ const prefilledLogic = subscriptionLogic({+ dashboardId: 9,+ dashboardName: 'Key metrics',+ id: 'new',+ })+ prefilledLogic.mount()++ router.actions.push('/dashboard/9/subscriptions/new?prefill=nudge')+ await expectLogic(prefilledLogic).toFinishAllListeners()+ expect(prefilledLogic.values.subscription.summary_enabled).toBe(true)++ // The user turns it back off; a later quota reload must not re-apply the default.+ prefilledLogic.actions.setSubscriptionValue('summary_enabled', false)+ await expectLogic(prefilledLogic, () => {+ prefilledLogic.actions.loadSummaryQuotaSuccess({ active_count: 0, limit: 5, at_limit: false })+ }).toFinishListeners()+ expect(prefilledLogic.values.subscription.summary_enabled).toBe(false)++ // The form now genuinely differs from the prefill baseline — leaving prompts.+ router.actions.push('/insights/123')+ expect(confirmSpy).toHaveBeenCalledTimes(1)++ prefilledLogic.unmount()+ confirmSpy.mockRestore()+ })++ it('leaves summary_enabled off for a plain non-nudge new subscription', async () => {+ router.actions.push('/insights/123/subscriptions/new')+ await expectLogic(newLogic).toFinishListeners()++ await expectLogic(newLogic, () => {+ newLogic.actions.loadSummaryQuotaSuccess({ active_count: 0, limit: 5, at_limit: false })+ }).toFinishListeners()++ expect(newLogic.values.subscription.summary_enabled).toBe(false)+ })++ it('still prompts when leaving a genuinely edited non-prefilled form', async () => {+ const confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(true)++ router.actions.push('/insights/123/subscriptions/new')+ await expectLogic(newLogic).toFinishListeners()+ newLogic.actions.setSubscriptionValue('title', 'My own title')++ router.actions.push('/insights/123')++ expect(confirmSpy).toHaveBeenCalledWith('Changes you made will be discarded.')+ confirmSpy.mockRestore()+ })+it('does not toast when kea-forms reports client validation failure', async () => {await expectLogic(newLogic, () => {newLogic.actions.submitSubscriptionFailure(new Error('Validation Failed'), {})diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.tsindex e8187d1f059c..ac6f7527775a 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts@@ -1,4 +1,4 @@-import { actions, events, kea, key, listeners, path, props, reducers } from 'kea'+import { actions, connect, events, kea, key, listeners, path, props, reducers } from 'kea'import { forms } from 'kea-forms'import { loaders } from 'kea-loaders'import { beforeUnload, router, urlToAction } from 'kea-router'@@ -8,8 +8,11 @@ import api, { ApiError } from 'lib/api'import { dayjs } from 'lib/dayjs'import { recordRecentSlackChannel, slackChannelId } from 'lib/integrations/slackChannel'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { objectsEqual } from 'lib/utils/objects'import { isEmail } from 'lib/utils/url'import { getInsightId } from 'scenes/insights/utils'+import { organizationLogic } from 'scenes/organizationLogic'+import { userLogic } from 'scenes/userLogic'import { ExportedAssetType, ExporterFormat, SubscriptionResourceTypes, SubscriptionType } from '~/types'@@ -17,7 +20,7 @@ import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generateimport type { subscriptionLogicType } from './subscriptionLogicType'import { subscriptionsLogic } from './subscriptionsLogic'-import { AI_PROMPT_MAX_LENGTH, SubscriptionBaseProps, urlForSubscription } from './utils'+import { AI_PROMPT_MAX_LENGTH, SUBSCRIPTION_PREFILL_PARAMS, SubscriptionBaseProps, urlForSubscription } from './utils'function validatePrompt(resource_type: SubscriptionType['resource_type'],@@ -126,11 +129,14 @@ const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {export interface SubscriptionLogicProps extends SubscriptionBaseProps {id: number | 'new'+ /** Used to build the prefilled title when the form is opened via the subscribe-nudge notification. */+ dashboardName?: string | null}export const subscriptionLogic = kea<subscriptionLogicType>([path(['lib', 'components', 'Subscriptions', 'subscriptionLogic']),props({} as SubscriptionLogicProps),key(({ id, insightShortId, dashboardId }) => `${insightShortId || dashboardId}-${id ?? 'new'}`),+ connect(() => ({ values: [userLogic, ['user'], organizationLogic, ['currentOrganization']] })),actions({generatePreview: true,@@ -138,6 +144,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([setPreviewLoading: (loading: boolean) => ({ loading }),setPreviewError: (error: string | null) => ({ error }),setPreviewImageUrl: (url: string | null) => ({ url }),+ applyInsightSelectionDefaults: (selectedIds: number[]) => ({ selectedIds }),selectAiExamplePrompt: (prompt: string, label: string, window?: AIWindowConfigApi) => ({prompt,label,@@ -205,7 +212,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([},})),- forms(({ props, actions }) => ({+ forms(({ props, actions, cache }) => ({subscription: {defaults: { enabled: NEW_SUBSCRIPTION.enabled } as unknown as SubscriptionType,errors: (subscription) => ({@@ -255,6 +262,8 @@ export const subscriptionLogic = kea<subscriptionLogicType>([insight_short_id: props.insightShortId,subscription_id: updatedSub.id,target_type: updatedSub.target_type,+ // True when the nudge flow's deferred AI-summary default was applied to this form.+ ai_summary_prefilled: cache.prefillBaseline?.summary_enabled === true,})}@@ -271,12 +280,47 @@ export const subscriptionLogic = kea<subscriptionLogicType>([},})),- listeners(({ actions, values, props, selectors }) => ({+ listeners(({ actions, values, props, selectors, cache }) => ({submitSubscriptionSuccess: ({ subscription }) => {if (subscription?.target_type === 'slack' && subscription.target_value && subscription.integration_id) {recordRecentSlackChannel(subscription.integration_id, slackChannelId(subscription.target_value))}},+ applyInsightSelectionDefaults: ({ selectedIds }) => {+ if (cache.prefillBaseline) {+ // Prefilled form: the auto-selection joins the programmatic baseline. A reset here+ // would wipe the "changed" flag the prefill deliberately set (disabling Create), so+ // set the value instead and fold the ids into the baseline, keeping the untouched-form+ // navigation suppression matching.+ actions.setSubscriptionValue('dashboard_export_insights', selectedIds)+ cache.prefillBaseline = { ...cache.prefillBaseline, dashboard_export_insights: selectedIds }+ return+ }+ // Reset the form's "changed" state after auto-selecting defaults so it doesn't trip the+ // unsaved-changes warning; merge the IDs into the subscription to preserve them.+ actions.resetSubscription({ ...values.subscription, dashboard_export_insights: selectedIds })+ },+ loadSummaryQuotaSuccess: ({ summaryQuota }) => {+ // Nudge upsell, deferred until the quota answer exists: default the AI summary on for a+ // nudge-prefilled create. Never for a non-consented org (the server rejects the create+ // and the consent popover must not appear uninvited) and never at the quota limit —+ // both gates mirror the server-side create validation. Applied at most once, so a+ // user toggling it back off is respected on later quota reloads.+ if (+ props.id !== 'new' ||+ !cache.prefillBaseline ||+ cache.prefillBaseline.summary_enabled === true ||+ summaryQuota?.at_limit ||+ !values.currentOrganization?.is_ai_data_processing_approved ||+ values.subscription?.summary_enabled+ ) {+ return+ }+ actions.setSubscriptionValue('summary_enabled', true)+ // Folding the default into the baseline both keeps the untouched-form navigation+ // suppression matching and serves as the applied-once guard on later quota reloads.+ cache.prefillBaseline = { ...cache.prefillBaseline, summary_enabled: true }+ },selectAiExamplePrompt: ({ prompt, label, window }) => {posthog.capture('subscription_ai_example_prompt_selected', { label })actions.setSubscriptionValue('prompt', prompt)@@ -419,17 +463,55 @@ export const subscriptionLogic = kea<subscriptionLogicType>([},})),- beforeUnload(({ actions, values }) => ({- enabled: () => values.subscriptionChanged,+ beforeUnload(({ actions, values, cache }) => ({+ // A form whose only "changes" are the programmatic prefill was never touched by the user —+ // navigating away from it must not prompt to discard. Any real edit diverges from the+ // captured baseline and re-arms the prompt.+ enabled: () =>+ values.subscriptionChanged &&+ !(cache.prefillBaseline && objectsEqual(values.subscription, cache.prefillBaseline)),message: 'Changes you made will be discarded.',onConfirm: () => {actions.resetSubscription()},})),- urlToAction(({ actions }) => ({+ urlToAction(({ actions, props, cache, values }) => ({'/*/*/subscriptions/new': (_, searchParams) => {actions.loadSubscriptionSuccess({ ...NEW_SUBSCRIPTION })+ // ?prefill=nudge is set by the subscribe-nudge notification / toast, possibly opened in a+ // fresh session days later — the prefill is built here from URL + context, not kea state.+ if (+ searchParams[SUBSCRIPTION_PREFILL_PARAMS.param] === SUBSCRIPTION_PREFILL_PARAMS.nudge &&+ props.dashboardId+ ) {+ // Consume the params before applying: the replace synchronously re-enters this+ // handler (resetting the form to plain defaults), and it also makes a later refresh+ // of the URL neither re-capture the click nor re-apply a stale prefill.+ const {+ [SUBSCRIPTION_PREFILL_PARAMS.param]: _prefill,+ [SUBSCRIPTION_PREFILL_PARAMS.viaParam]: _via,+ ...restSearchParams+ } = router.values.searchParams+ router.actions.replace(router.values.location.pathname, restSearchParams, router.values.hashParams)+ const prefill: Partial<SubscriptionType> = {+ title: `${props.dashboardName || 'Dashboard'} weekly digest`,+ ...(values.user?.email ? { target_value: values.user.email } : {}),+ }+ // Goes through setSubscriptionValues (not the loaded baseline) so the form is marked+ // dirty immediately — the prefilled fields are a deliberate change, not the pristine+ // default, so "Create subscription" doesn't require an extra no-op edit to enable.+ actions.setSubscriptionValues(prefill)+ cache.prefillBaseline = { ...NEW_SUBSCRIPTION, ...prefill }+ posthog.capture('dashboard subscribe nudge clicked', {+ dashboard_id: props.dashboardId,+ prefilled: !!values.user?.email,+ via:+ searchParams[SUBSCRIPTION_PREFILL_PARAMS.viaParam] === SUBSCRIPTION_PREFILL_PARAMS.viaToast+ ? SUBSCRIPTION_PREFILL_PARAMS.viaToast+ : SUBSCRIPTION_PREFILL_PARAMS.viaNotification,+ })+ }if (searchParams.target_type) {actions.setSubscriptionValue('target_type', searchParams.target_type)}diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsxindex 1a63cd47c506..d2fd9c14020f 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx@@ -34,6 +34,20 @@ export const urlForSubscriptions = ({ dashboardId, insightShortId }: Subscriptioreturn urls.subscriptions()}+/**+ * Deep-link params the subscribe-nudge uses to open the new-subscription form prefilled.+ * Single source of truth shared by the producer (dashboard toast) and the consumer (this+ * logic's urlToAction). The backend notification's source_url must mirror these — see the+ * comment on source_url in products/dashboards/backend/api/dashboard.py.+ */+export const SUBSCRIPTION_PREFILL_PARAMS = {+ param: 'prefill',+ nudge: 'nudge',+ viaParam: 'via',+ viaToast: 'toast',+ viaNotification: 'notification',+} as const+export const urlForSubscription = (id: number | 'new',{ dashboardId, insightShortId }: SubscriptionBasePropsdiff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex 5913d24c91f2..01cdda104b87 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -34,7 +34,7 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'-import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes, SubscriptionType } from '~/types'+import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes } from '~/types'import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'@@ -308,12 +308,10 @@ function AiPromptFields({function DashboardInsightsField({dashboard,- subscription,- onResetSubscription,+ onDefaultsApplied,}: {dashboard: DashboardType<any>- subscription: SubscriptionType- onResetSubscription: (subscription: SubscriptionType) => void+ onDefaultsApplied: (selectedIds: number[]) => void}): JSX.Element {return (<LemonField name="dashboard_export_insights" label="Insights to include">@@ -322,11 +320,9 @@ function DashboardInsightsField({tiles={dashboard.tiles}selectedInsightIds={value ?? []}onChange={onChange}- // Reset the form's "changed" state after auto-selecting defaults so it doesn't trip the- // unsaved-changes warning; merge the IDs into the subscription to preserve them.- onDefaultsApplied={(selectedIds) =>- onResetSubscription({ ...subscription, dashboard_export_insights: selectedIds })- }+ // The logic decides whether the auto-selection resets the form to a clean state+ // or joins a prefill's baseline — see applyInsightSelectionDefaults.+ onDefaultsApplied={onDefaultsApplied}/>)}</LemonField>@@ -345,6 +341,7 @@ function EditSubscriptionForm({id,insightShortId,dashboardId,+ dashboardName: dashboard?.name,}const logic = subscriptionLogic(logicProps)const subscriptionslogic = subscriptionsLogic({@@ -356,7 +353,7 @@ function EditSubscriptionForm({const { subscription, subscriptionLoading, isSubscriptionSubmitting, subscriptionChanged, summaryQuota } =useValues(logic)const { previewLoading, previewError, previewImageUrl } = useValues(logic)- const { resetSubscription, generatePreview } = useActions(logic)+ const { applyInsightSelectionDefaults, generatePreview } = useActions(logic)const { preflight, siteUrlMisconfigured } = useValues(preflightLogic)const { currentOrganization } = useValues(organizationLogic)const { deleteSubscription } = useActions(subscriptionslogic)@@ -515,8 +512,7 @@ function EditSubscriptionForm({{dashboard?.tiles && selectionReady && !isAiPrompt && (<DashboardInsightsFielddashboard={dashboard}- subscription={subscription}- onResetSubscription={resetSubscription}+ onDefaultsApplied={applyInsightSelectionDefaults}/>)}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 964b3650afab..680768225f9c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16079,6 +16079,11 @@ export namespace Schemas {widget?: DashboardPatchWidgetOpenApi;}+ export interface DashboardSubscribeNudgeResponse {+ /** Whether a nudge notification was created. False when one was already sent recently for this user and dashboard, or when in-app notifications are unavailable. */+ created: boolean;+ }+/*** * `team` - Only team* * `organization` - Organization@@ -65222,6 +65227,18 @@ export namespace Schemas {Xs: 'xs',} as const;+ export type EnvironmentsDashboardsSubscribeNudgeCreateParams = {+ format?: EnvironmentsDashboardsSubscribeNudgeCreateFormat;+ };++ export type EnvironmentsDashboardsSubscribeNudgeCreateFormat = typeof EnvironmentsDashboardsSubscribeNudgeCreateFormat[keyof typeof EnvironmentsDashboardsSubscribeNudgeCreateFormat];+++ export const EnvironmentsDashboardsSubscribeNudgeCreateFormat = {+ Json: 'json',+ Txt: 'txt',+ } as const;+export type EnvironmentsDashboardsUpdateTextTileCreateParams = {format?: EnvironmentsDashboardsUpdateTextTileCreateFormat;};@@ -71667,6 +71684,18 @@ export namespace Schemas {Xs: 'xs',} as const;+ export type DashboardsSubscribeNudgeCreateParams = {+ format?: DashboardsSubscribeNudgeCreateFormat;+ };++ export type DashboardsSubscribeNudgeCreateFormat = typeof DashboardsSubscribeNudgeCreateFormat[keyof typeof DashboardsSubscribeNudgeCreateFormat];+++ export const DashboardsSubscribeNudgeCreateFormat = {+ Json: 'json',+ Txt: 'txt',+ } as const;+export type DashboardsUpdateTextTileCreateParams = {format?: DashboardsUpdateTextTileCreateFormat;};diff --git a/tach.toml b/tach.tomlindex 43411dbab761..502c7ae673ea 100644--- a/tach.toml+++ b/tach.toml@@ -238,6 +238,7 @@ depends_on = ["products.feature_flags","products.logs","products.mcp_analytics",+ "products.notifications","products.product_analytics","products.surveys",]