: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(subscriptions): add experiment-gated subscription wizard (#88825)
Matt Pua7183623f93a5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 53cd7040f2c1..9e61cfdf36ea 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5328,10 +5328,14 @@ snapshots:hash: v1.k794b7964.fdd194fa7f91e1eaa642256ba2dd7e0951bc382b7df24e39c504ba428cfabe0a.KLwxXJI2yw_P7hQMu-vHOJKoXi4mSHf3IVabPbV2vdMproducts-subscriptions-subscriptions-modal--insight-with-subscriptions--light:hash: v1.k794b7964.0850b21723e94659d48e7930f44b3806423409fa4e324370cea825f7ee834371.uKJgYFJ-_LNL0M6CQHDlG1kNfpEccF8eSmPDv3hO-1c+ products-subscriptions-subscriptions-modal--subscription-wizard-new--dark:+ hash: v1.k794b7964.e5aa7358fd68838279ee1a054c4da58e139de7f8cdf7cc31fc55858cf62db633.2cy5yElBtv75-dE9TsJ5XINpT4QnHYAf_g405VzPZ2I+ products-subscriptions-subscriptions-modal--subscription-wizard-new--light:+ hash: v1.k794b7964.a25e52c871d0eda0d3aa152eae70692b6e7afdce17781140e344d9118222c5a0.p4Ekexj90QTVLPreWagC3oRfB1Eo5TzfTRrLBba2ASUproducts-subscriptions-subscriptions-modal--subscriptions-new--dark:- hash: v1.k794b7964.f311eeee76a344bb3e5d6f821bfc39eaed7084676ed8303b75f72bc7a1b07850.kivXKHF2HMr1zM8HTo7oNgN81xKNFTmqPgYVxW1za90+ hash: v1.k794b7964.689c2da7432f8fa3420601743c883ae66267aa7f506a84d1480984ec4e858eea.UKt2PmN2WWy_glphF6O-ypRyF5yqWfKv0n1xusY4cZYproducts-subscriptions-subscriptions-modal--subscriptions-new--light:- hash: v1.k794b7964.5811e86e8e76821927d62745628b48be1c326808cdcb74a9df4391cbbd699267.JFnGN37k4aWrIGrYAWOlc54BaWHhy0cHDBbEHRxQFqE+ hash: v1.k794b7964.fc5e1a3a8bfaa345888181c9e9374d64c3c734333f7a67910635fc4cd3ff3379.Tf36g4kzJf_s9TcM1AEk4gnGPkNQh_ntQcr-ZR1TsQsproducts-subscriptions-subscriptions-modal--subscriptions-tabbed--dark:hash: v1.k794b7964.1f9aa8adee753b12e1b50c143ed4e2eed36a5ceaea7f934a43cb16b16ff9974a.KtXqx6ZGFgLFGRPjRxGd10KmRLwCgZPyMSowVK2PPKgproducts-subscriptions-subscriptions-modal--subscriptions-tabbed--light:diff --git a/frontend/src/lib/components/ScheduledRunStatus.tsx b/frontend/src/lib/components/ScheduledRunStatus.tsxnew file mode 100644index 000000000000..e79c3a0c2ebe--- /dev/null+++ b/frontend/src/lib/components/ScheduledRunStatus.tsx@@ -0,0 +1,42 @@+import type { ReactNode } from 'react'++import { IconCalendar, IconClock } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++interface NextScheduledRunProps {+ children: ReactNode+ label: string+ loading?: boolean+}++export function NextScheduledRun({ children, label, loading = false }: NextScheduledRunProps): JSX.Element {+ return (+ <div className="text-sm text-muted flex flex-wrap items-center gap-x-2 gap-y-0">+ <IconClock+ className={`size-4 shrink-0 text-muted motion-reduce:animate-none${loading ? ' animate-spin' : ''}`}+ aria-hidden+ />+ <span className="shrink-0">{label}</span>+ {children}+ </div>+ )+}++interface ProjectTimezoneNoticeProps {+ timezone: string+ settingsUrl: string+}++export function ProjectTimezoneNotice({ timezone, settingsUrl }: ProjectTimezoneNoticeProps): JSX.Element {+ return (+ <div className="text-muted text-sm flex flex-wrap items-start gap-2">+ <IconCalendar className="size-4 shrink-0 text-muted mt-0.5" aria-hidden />+ <span className="min-w-0">+ Times use your project timezone ({timezone}).{' '}+ <Link to={settingsUrl} target="_blank" targetBlankIcon={false}>+ Change in settings+ </Link>+ </span>+ </div>+ )+}diff --git a/products/alerts/frontend/components/AlertWizardReview.tsx b/frontend/src/lib/components/WizardReview.tsxsimilarity index 66%rename from products/alerts/frontend/components/AlertWizardReview.tsxrename to frontend/src/lib/components/WizardReview.tsxindex e9d12341c454..7e12041be39a 100644--- a/products/alerts/frontend/components/AlertWizardReview.tsx+++ b/frontend/src/lib/components/WizardReview.tsx@@ -1,23 +1,23 @@import type { ReactNode } from 'react'-export interface AlertWizardReviewItem {+export interface WizardReviewItem {label: stringvalue: ReactNode}-interface AlertWizardReviewProps {- items: AlertWizardReviewItem[]+interface WizardReviewProps {+ items: WizardReviewItem[]notice?: ReactNodefooter?: ReactNode}-export function AlertWizardReview({ items, notice, footer }: AlertWizardReviewProps): JSX.Element {+export function WizardReview({ items, notice, footer }: WizardReviewProps): JSX.Element {return (<div className="space-y-3">{notice}<div className="space-y-1.5 rounded border border-border bg-bg-light p-3 text-sm">{items.map(({ label, value }) => (- <div key={label} className="grid grid-cols-[13rem_minmax(0,1fr)] gap-2">+ <div key={label} className="grid grid-cols-1 gap-1 sm:grid-cols-[13rem_minmax(0,1fr)] sm:gap-2"><span className="text-muted">{label}</span><span className="font-medium">{value}</span></div>diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 1b48a005c2a3..c04632c8f54d 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -498,6 +498,7 @@ export const FEATURE_FLAGS = {STREAMLIT_APPS: 'streamlit-apps', // owner: @sakceSUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptionsSUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE: 'subscription-ai-summary-prompt-guide', // owner: #team-analytics-platform, gates the per-subscription prompt guide textarea+ SUBSCRIPTION_CREATION_WIZARD: 'subscription-creation-wizard', // owner: #team-analytics-platform, experiment=control,testSURVEY_HEADLINE_SUMMARY: 'survey-headline-summary', // owner: @adboio #team-surveysSURVEYS_ERROR_TRACKING_CROSS_SELL: 'surveys-in-error-tracking', // owner: @adboio #team-surveysSURVEYS_FORM_BUILDER: 'surveys-form-builder', // owner: @adboio #team-surveysdiff --git a/frontend/src/lib/posthog-typed.ts b/frontend/src/lib/posthog-typed.tsindex 18ff52bbcd95..ea01628a1ffa 100644--- a/frontend/src/lib/posthog-typed.ts+++ b/frontend/src/lib/posthog-typed.ts@@ -3563,6 +3563,7 @@ interface EventSchemas {subscribe_to_product_updates: Record<string, any>'subscription cancelled': Record<string, any>'subscription created': {+ creation_source?: 'editor' | 'wizard'resource_type?: stringdashboard_id?: numberinsight_short_id?: stringdiff --git a/frontend/src/scenes/dashboard/DashboardModals.tsx b/frontend/src/scenes/dashboard/DashboardModals.tsxindex 38cd999b4211..0004807a8503 100644--- a/frontend/src/scenes/dashboard/DashboardModals.tsx+++ b/frontend/src/scenes/dashboard/DashboardModals.tsx@@ -47,7 +47,8 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType<QueryBisOpen={showSubscriptions}closeModal={() => push(urls.dashboard(dashboard.id))}dashboard={dashboard}- subscriptionId={subscriptionId}+ isCreating={subscriptionId === 'new'}+ subscriptionId={subscriptionId === 'new' ? null : subscriptionId}/><SharingModaltitle="Dashboard permissions & sharing"diff --git a/frontend/src/scenes/insights/InsightModals.tsx b/frontend/src/scenes/insights/InsightModals.tsxindex ef9b4cba28b0..37d780292d2e 100644--- a/frontend/src/scenes/insights/InsightModals.tsx+++ b/frontend/src/scenes/insights/InsightModals.tsx@@ -50,7 +50,7 @@ function InsightSubscriptionsModalWrapper({}: {insightLogicProps: InsightLogicProps}): JSX.Element {- const { insightMode, itemId } = useValues(insightSceneLogic)+ const { insightMode, itemId, isNewSubscription } = useValues(insightSceneLogic)const { insight } = useValues(insightLogic(insightLogicProps))const { push } = useActions(router)@@ -60,7 +60,9 @@ function InsightSubscriptionsModalWrapper({isOpen={insightMode === ItemMode.Subscriptions}closeModal={() => push(urls.insightView(insight.short_id as InsightShortId))}insightShortId={insight.short_id}- subscriptionId={typeof itemId === 'number' || itemId === 'new' ? itemId : null}+ insightName={insight.name || insight.derived_name || 'Untitled insight'}+ isCreating={isNewSubscription}+ subscriptionId={itemId}/>)}diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.tsindex 782d9f2ae18e..395321bacc3b 100644--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts@@ -475,7 +475,7 @@ describe('insightSceneLogic', () => {})it.each([- ['new subscription', 'new', 'new'],+ ['new subscription', 'new', null],['a specific subscription', '5', 5],])('updates itemId when navigating from subscriptions list to %s',diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsxindex 35625182bd72..4a4141e3d155 100644--- a/frontend/src/scenes/insights/insightSceneLogic.tsx+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx@@ -77,18 +77,11 @@ import { getInsightIconTypeFromQuery, parseDraftQueryFromURL } from './utils'const NEW_INSIGHT = 'new' as constexport type InsightId = InsightShortId | typeof NEW_INSIGHT | null--function normalizeItemId(itemId: string | undefined): string | number | null {- if (itemId === undefined) {+function normalizeItemId(itemId: string | undefined): number | null {+ if (!itemId) {return null}- if (itemId === 'new' || itemId.startsWith('new-')) {- return 'new'- }- if (Number.isInteger(+itemId)) {- return parseInt(itemId, 10)- }- return itemId+ return Number(itemId) || null}// Tag a new insight's query with the product_analytics productKey (on the executed source query) so@@ -155,7 +148,8 @@ export interface insightSceneLogicValues {props?: InsightLogicProps<QuerySchema> | undefined) => Partial<QueryBasedInsightModel<Node<Record<string, any>>>>)| undefined- itemId: number | string | null+ isNewSubscription: boolean+ itemId: number | nullmaxContext: MaxContextInput[]projectTreeRef: ProjectTreeRefsceneSource: InsightSceneSource | null@@ -382,11 +376,18 @@ export const insightSceneLogic = kea<insightSceneLogicType>([},],itemId: [- null as null | string | number,+ null as number | null,{setSceneState: (_, { itemId }) => normalizeItemId(itemId),},],+ isNewSubscription: [+ false,+ {+ setSceneState: (_, { insightMode, itemId }) =>+ insightMode === ItemMode.Subscriptions && itemId === 'new',+ },+ ],alertId: [null as null | AlertType['id'],{@@ -835,7 +836,7 @@ export const insightSceneLogic = kea<insightSceneLogicType>([method === 'PUSH' ||insightId !== values.insightId ||insightMode !== values.insightMode ||- (itemId ?? null) !== values.itemId ||+ normalizeItemId(itemId) !== values.itemId ||(sceneSource ?? null) !== values.sceneSource ||alertChanged ||!objectsEqual(variablesOverride ?? null, values.variablesOverride) ||diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsxindex 1c2385a7e3b5..332ec890ea6c 100644--- a/products/alerts/frontend/components/AlertComponents.stories.tsx+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx@@ -6,6 +6,7 @@ import { useEffect, useState } from 'react'import type { LemonSegmentedButtonOption, LemonSelectOptions } from '@posthog/lemon-ui'import { LemonCheckbox, LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'+import { NextScheduledRun, ProjectTimezoneNotice } from 'lib/components/ScheduledRunStatus'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { useStorybookMocks } from '~/mocks/browser'@@ -19,7 +20,7 @@ import type { ScheduleRestriction } from 'products/alerts/frontend/types'import { InlineAlertNotifications } from 'products/alerts/frontend/views/InlineAlertNotifications'import { AlertAdvancedOptions } from './AlertAdvancedOptions'-import { AlertDefinitionRow, AlertNextEvaluationStatus, AlertTimezoneNotice } from './AlertDefinition'+import { AlertDefinitionRow } from './AlertDefinition'import { AlertEditor, AlertEditorFormDetails, AlertEditorLoading, AlertEditorSection } from './AlertEditor'import {AlertEvaluationHistoryChart,@@ -119,8 +120,8 @@ function DefinitionStory(): JSX.Element {<AlertDefinitionRow label="Evaluate every"><span className="font-semibold">15 minutes</span></AlertDefinitionRow>- <AlertNextEvaluationStatus>July 17, 2026 at 12:15 PM</AlertNextEvaluationStatus>- <AlertTimezoneNotice timezone="America/Toronto" settingsUrl="#project-settings" />+ <NextScheduledRun label="Next planned evaluation:">July 17, 2026 at 12:15 PM</NextScheduledRun>+ <ProjectTimezoneNotice timezone="America/Toronto" settingsUrl="#project-settings" /></div></div>)diff --git a/products/alerts/frontend/components/AlertIntervalRow.tsx b/products/alerts/frontend/components/AlertIntervalRow.tsxindex 9216a0d28238..eb00aa0779b3 100644--- a/products/alerts/frontend/components/AlertIntervalRow.tsx+++ b/products/alerts/frontend/components/AlertIntervalRow.tsx@@ -2,6 +2,7 @@ import { useValues } from 'kea'import { LemonSelect, Tooltip } from '@posthog/lemon-ui'+import { NextScheduledRun } from 'lib/components/ScheduledRunStatus'import { TZLabel } from 'lib/components/TZLabel'import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'import { LemonField } from 'lib/lemon-ui/LemonField'@@ -11,7 +12,7 @@ import { userLogic } from 'scenes/userLogic'import { AlertCalculationInterval } from '~/queries/schema/schema-general'import { AvailableFeature } from '~/types'-import { AlertDefinitionRow, AlertNextEvaluationStatus } from 'products/alerts/frontend/components/AlertDefinition'+import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'import { AlertFormType } from 'products/alerts/frontend/logic/alertFormLogic'import {cadenceFinerThanInsightInterval,@@ -96,11 +97,11 @@ export function AlertIntervalRow({} else if (creatingNewAlert || nextPlannedEvaluationStale) {const approximateTime = approximateNextAlertRun(alertForm.calculation_interval, currentTeam?.timezone ?? 'UTC')nextEvaluation = (- <AlertNextEvaluationStatus>+ <NextScheduledRun label="Next planned evaluation:"><span>Approximately <TZLabel time={approximateTime} /></span>- </AlertNextEvaluationStatus>+ </NextScheduledRun>)} else if (alert) {let status: JSX.Element@@ -110,9 +111,12 @@ export function AlertIntervalRow({status = <span>We're calculating this. This can take a few minutes.</span>}nextEvaluation = (- <AlertNextEvaluationStatus loading={!nextPlannedEvaluationStale && !alert.next_check_at}>+ <NextScheduledRun+ label="Next planned evaluation:"+ loading={!nextPlannedEvaluationStale && !alert.next_check_at}+ >{status}- </AlertNextEvaluationStatus>+ </NextScheduledRun>)} else {nextEvaluation = nulldiff --git a/products/alerts/frontend/views/EditAlertModal.tsx b/products/alerts/frontend/views/EditAlertModal.tsxindex 89a622cae63e..9dae789da526 100644--- a/products/alerts/frontend/views/EditAlertModal.tsx+++ b/products/alerts/frontend/views/EditAlertModal.tsx@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { useCallback, useMemo } from 'react'+import { ProjectTimezoneNotice } from 'lib/components/ScheduledRunStatus'import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/UserActivityIndicator'import { dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'@@ -19,11 +20,7 @@ import { isFunnelsQuery, isInsightVizNode } from '~/queries/utils'import { FunnelVizType, InsightLogicProps, InsightShortId, QueryBasedInsightModel } from '~/types'import { AlertAdvancedOptionsSection } from 'products/alerts/frontend/components/AlertAdvancedOptionsSection'-import {- AlertErrorBanner,- AlertStateIndicator,- AlertTimezoneNotice,-} from 'products/alerts/frontend/components/AlertDefinition'+import { AlertErrorBanner, AlertStateIndicator } from 'products/alerts/frontend/components/AlertDefinition'import { AlertDefinitionSection } from 'products/alerts/frontend/components/AlertDefinitionSection'import {AlertEditor,@@ -369,7 +366,7 @@ export function EditAlertModal(props: AlertModalProps): JSX.Element {canCheckOngoingInterval={can_check_ongoing_interval}onSetAlertFormValue={setAlertFormValue}/>- <AlertTimezoneNotice+ <ProjectTimezoneNoticetimezone={projectTimezone}settingsUrl={urls.settings('environment-customization', 'date-and-time')}/>diff --git a/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsx b/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsxindex 1f38a672d6a9..570eb2efe6e6 100644--- a/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsx+++ b/products/alerts/frontend/views/EditAlertModal/buildWizardSteps.tsx@@ -1,7 +1,8 @@import type { ReactNode } from 'react'+import { WizardReview } from 'lib/components/WizardReview'+import { AlertWizardStep } from 'products/alerts/frontend/components/AlertWizard'-import { AlertWizardReview } from 'products/alerts/frontend/components/AlertWizardReview'interface WizardStepInput {nameNode: ReactNode@@ -67,7 +68,7 @@ export function buildWizardSteps(input: WizardStepInput): AlertWizardStep[] {canAdvance: !alertFormHasErrors,cannotAdvanceReason: alertFormHasErrors ? 'Fix the errors in previous steps before creating.' : undefined,content: (- <AlertWizardReview+ <WizardReviewitems={[{ label: 'Fires when', value: reviewFires },{ label: 'Runs', value: reviewCadence },diff --git a/products/billing_alerts/frontend/BillingAlertEditor.tsx b/products/billing_alerts/frontend/BillingAlertEditor.tsxindex 457d71f0f242..5d8a73b01758 100644--- a/products/billing_alerts/frontend/BillingAlertEditor.tsx+++ b/products/billing_alerts/frontend/BillingAlertEditor.tsx@@ -4,11 +4,12 @@ import { Form } from 'kea-forms'import { IconPlay } from '@posthog/icons'import { LemonButton, LemonInput, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'+import { NextScheduledRun } from 'lib/components/ScheduledRunStatus'import { dayjs } from 'lib/dayjs'import { LemonField } from 'lib/lemon-ui/LemonField'import { AlertAdvancedOptions } from 'products/alerts/frontend/components/AlertAdvancedOptions'-import { AlertDefinitionRow, AlertNextEvaluationStatus } from 'products/alerts/frontend/components/AlertDefinition'+import { AlertDefinitionRow } from 'products/alerts/frontend/components/AlertDefinition'import {AlertEditor,AlertEditorFormDetails,@@ -132,11 +133,11 @@ function BillingAlertEditorContent(props: BillingAlertFormLogicProps): JSX.Eleme? 'Projected period spend estimates what this billing period will cost by its end, after discounts.': 'Current period spend is what this billing period has cost so far, after discounts.'}</div>- <AlertNextEvaluationStatus loading={false}>+ <NextScheduledRun label="Next planned evaluation:" loading={false}>{props.alert?.next_check_at? dayjs.utc(props.alert.next_check_at).format('MMM D, HH:mm [UTC]'): 'after the alert is created'}- </AlertNextEvaluationStatus>+ </NextScheduledRun></div></AlertEditorSection>diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsxindex f7f32e59b91f..11402eee506b 100644--- a/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertCreateModal.tsx@@ -3,9 +3,10 @@ import { Form } from 'kea-forms'import { LemonBanner, LemonModal } from '@posthog/lemon-ui'+import { WizardReview } from 'lib/components/WizardReview'+import { AlertEditorFormDetails } from 'products/alerts/frontend/components/AlertEditor'import { AlertWizard, AlertWizardStep } from 'products/alerts/frontend/components/AlertWizard'-import { AlertWizardReview } from 'products/alerts/frontend/components/AlertWizardReview'import { LogsAlertFilters, LogsAlertTrigger } from './LogsAlertForm'import { logsAlertFormLogic, LogsAlertFormType } from './logsAlertFormLogic'@@ -142,7 +143,7 @@ function LogsAlertReview({: 'No notification destinations'return (- <AlertWizardReview+ <WizardReviewnotice={pendingNotifications.length === 0 ? (<LemonBanner type="warning">diff --git a/products/subscriptions/frontend/components/Subscriptions/AiPromptFields.tsx b/products/subscriptions/frontend/components/Subscriptions/AiPromptFields.tsxnew file mode 100644index 000000000000..d0e6e7b9aa7d--- /dev/null+++ b/products/subscriptions/frontend/components/Subscriptions/AiPromptFields.tsx@@ -0,0 +1,203 @@+import type { ReactElement, ReactNode } from 'react'++import { IconLineGraph, IconPulse, IconTrending, IconWarning } from '@posthog/icons'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'++import { SubscriptionAIPromptMaxLength } from '~/queries/schema/schema-general'++import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'++export function AiPromptSubscriptionIntroduction(): JSX.Element {+ return (+ <LemonBanner type="info" className="text-sm">+ Tell us what you want to know. We'll surface the relevant information from your project data in each report.+ </LemonBanner>+ )+}++const AI_PROMPT_EXAMPLES: { icon: ReactElement; label: string; prompt: string }[] = [+ {+ icon: <IconLineGraph />,+ label: 'Top events',+ prompt: 'Top 5 events by volume, with counts and unique users for each.',+ },+ {+ icon: <IconTrending />,+ label: 'Period-over-period growth',+ prompt: 'For the top 10 events by volume, compare the current period vs the previous one and rank by growth rate. Flag any event that more than doubled or halved.',+ },+ {+ icon: <IconPulse />,+ label: 'Health check',+ prompt: 'Health check: total event volume and unique active users, and how each compares to the previous period.',+ },+ {+ icon: <IconWarning />,+ label: 'Tracking gaps',+ prompt: 'Which events we normally track received no data? List them so I can catch broken instrumentation.',+ },+]++const AI_WINDOW_MODE_OPTIONS = [+ {+ value: 'since_last_sent' as const,+ label: 'Since last report',+ labelInMenu: (+ <div className="flex flex-col">+ <span>Since last report</span>+ <span className="text-xs text-secondary">+ Everything new since the previous scheduled report (no gaps)+ </span>+ </div>+ ),+ },+ {+ value: 'last_n_days' as const,+ label: 'Last N days',+ labelInMenu: (+ <div className="flex flex-col">+ <span>Last N days</span>+ <span className="text-xs text-secondary">A fixed trailing window, e.g. always the last 7 days</span>+ </div>+ ),+ },+ {+ value: 'days_ago_range' as const,+ label: 'Between X and Y days ago',+ labelInMenu: (+ <div className="flex flex-col">+ <span>Between X and Y days ago</span>+ <span className="text-xs text-secondary">An explicit historical range, e.g. 14 to 7 days ago</span>+ </div>+ ),+ },+]++interface AiPromptFieldsProps {+ compactAnalysisWindow?: boolean+ prompt?: string | null+ windowMode?: AIWindowConfigApi['mode']+ consentBanner?: ReactNode+ onSelectAnalysisWindow: (mode: AIWindowConfigApi['mode']) => void+ onSelectExample: (prompt: string, label: string) => void+}++function shouldShowAiPromptExamples(prompt?: string | null): boolean {+ return !prompt?.trim() || AI_PROMPT_EXAMPLES.some((example) => example.prompt === prompt)+}++export function AiPromptFields({+ compactAnalysisWindow = false,+ prompt,+ windowMode,+ consentBanner,+ onSelectAnalysisWindow,+ onSelectExample,+}: AiPromptFieldsProps): JSX.Element {+ const showExamples = shouldShowAiPromptExamples(prompt)+ const analysisWindowClassName = compactAnalysisWindow ? 'w-80 max-w-full' : undefined++ return (+ <>+ {consentBanner ? (+ <LemonBanner type="warning" className="text-sm">+ {consentBanner}+ </LemonBanner>+ ) : null}+ <LemonField+ name="prompt"+ label="What do you want to know?"+ help="We'll use this question to surface the right information in each report."+ >+ <LemonTextArea+ placeholder="e.g. Which events grew the most week-over-week? Highlight any unusual spikes."+ minRows={4}+ maxLength={SubscriptionAIPromptMaxLength.CHARACTERS}+ />+ </LemonField>+ {showExamples ? (+ <div className="flex flex-col gap-1">+ <span className="text-xs text-secondary">Try one of these questions:</span>+ <div className="flex flex-wrap gap-1">+ {AI_PROMPT_EXAMPLES.map((example) => (+ <LemonButton+ key={example.label}+ size="xsmall"+ type="secondary"+ icon={example.icon}+ onClick={() => onSelectExample(example.prompt, example.label)}+ >+ {example.label}+ </LemonButton>+ ))}+ </div>+ </div>+ ) : null}+ <LemonField+ name={['ai_prompt_config', 'window', 'mode']}+ label="What time period should we look at?"+ help="This controls the project data included in each report."+ >+ {({ value }) => (+ <LemonSelect+ options={AI_WINDOW_MODE_OPTIONS}+ value={value}+ onChange={(mode) => mode && onSelectAnalysisWindow(mode)}+ className={analysisWindowClassName}+ />+ )}+ </LemonField>+ {windowMode === 'last_n_days' ? (+ <LemonField name={['ai_prompt_config', 'window', 'start_days_ago']} label="Number of days to analyze">+ {({ value, onChange }) => (+ <div className="flex items-center gap-2">+ <LemonInput+ type="number"+ min={1}+ max={365}+ value={value ?? undefined}+ onChange={(newValue) => onChange(newValue ?? null)}+ className="w-24"+ />+ <span>days back from each run</span>+ </div>+ )}+ </LemonField>+ ) : null}+ {windowMode === 'days_ago_range' ? (+ <div className="flex items-start gap-2">+ <LemonField name={['ai_prompt_config', 'window', 'start_days_ago']} label="From (days ago)">+ {({ value, onChange }) => (+ <LemonInput+ type="number"+ min={1}+ max={365}+ value={value ?? undefined}+ onChange={(newValue) => onChange(newValue ?? null)}+ className="w-24"+ />+ )}+ </LemonField>+ <LemonField name={['ai_prompt_config', 'window', 'end_days_ago']} label="To (days ago)">+ {({ value, onChange }) => (+ <LemonInput+ type="number"+ min={0}+ max={365}+ value={value ?? undefined}+ onChange={(newValue) => onChange(newValue ?? null)}+ className="w-24"+ />+ )}+ </LemonField>+ </div>+ ) : null}+ </>+ )+}diff --git a/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsx b/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsxindex a81f242f91dc..727a9ef389f1 100644--- a/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/InsightSelector.tsx@@ -72,7 +72,7 @@ export function InsightSelector({<span className="font-medium">{selectedCount} of {MAX_INSIGHTS} insights selected</span>- {selectedCount === 0 && <span className="text-warning">Select at least one insight</span>}+ {selectedCount === 0 && <span className="text-danger">Select at least one insight</span>}</div>{showSearch && (<LemonInputdiff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionDayPicker.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionDayPicker.tsxnew file mode 100644index 000000000000..df7954cbdb67--- /dev/null+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionDayPicker.tsx@@ -0,0 +1,62 @@+import { LemonCheckbox, LemonDropdown } from '@posthog/lemon-ui'++import { LemonButton } from 'lib/lemon-ui/LemonButton'++import { WeekdayType } from '~/types'++import { ALL_DAYS, selectedDaysToDayPickerLabel, toggleSelectedDay, weekdayOptions } from './utils'++interface SubscriptionDayPickerProps {+ value: WeekdayType[]+ onChange: (value: WeekdayType[]) => void+}++export function SubscriptionDayPicker({ value, onChange }: SubscriptionDayPickerProps): JSX.Element {+ let selectAllChecked: boolean | 'indeterminate' = false+ if (value.length === ALL_DAYS.length) {+ selectAllChecked = true+ } else if (value.length > 0) {+ selectAllChecked = 'indeterminate'+ }++ return (+ <LemonDropdown+ closeOnClickInside={false}+ placement="bottom-start"+ overlay={+ <div className="w-48 flex flex-col gap-0.5">+ <div className="flex items-center mb-0.5">+ <LemonButton+ size="small"+ className="flex-1"+ icon={<LemonCheckbox checked={selectAllChecked} className="pointer-events-none" />}+ disabledReason={value.length === ALL_DAYS.length ? 'All days are selected' : undefined}+ onClick={() => onChange([...ALL_DAYS])}+ >+ Select all+ </LemonButton>+ <LemonButton+ size="small"+ disabledReason={value.length === 0 ? 'No days are selected' : undefined}+ onClick={() => onChange([])}+ >+ Clear all+ </LemonButton>+ </div>+ {weekdayOptions.map((day) => (+ <LemonCheckbox+ key={day.value}+ checked={value.includes(day.value)}+ label={day.label}+ fullWidth+ className="px-2 py-1 rounded hover:bg-bg-3000"+ onChange={() => onChange(toggleSelectedDay(value, day.value))}+ />+ ))}+ </div>+ }+ >+ <LemonButton type="secondary">{selectedDaysToDayPickerLabel(value)}</LemonButton>+ </LemonDropdown>+ )+}diff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionWizard.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionWizard.tsxnew file mode 100644index 000000000000..3b3364a67c5f--- /dev/null+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionWizard.tsx@@ -0,0 +1,778 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'+import { useState } from 'react'++import { IconChevronLeft, IconGraph } from '@posthog/icons'+import { LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'++import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'+import { UsageLimitPaywall } from 'lib/components/PayGateMini/UsageLimitPaywall'+import { NextScheduledRun, ProjectTimezoneNotice } from 'lib/components/ScheduledRunStatus'+import { TZLabel } from 'lib/components/TZLabel'+import { usersLemonSelectOptions } from 'lib/components/UserSelectItem'+import { WizardReview } from 'lib/components/WizardReview'+import { dayjs } from 'lib/dayjs'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'+import { preflightLogic } from 'lib/logic/preflightLogic'+import { cn } from 'lib/utils/css-classes'+import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'+import { membersLogic } from 'scenes/organization/membersLogic'+import { organizationLogic } from 'scenes/organizationLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { DashboardType, InsightShortId, SubscriptionResourceTypes, SubscriptionType } from '~/types'++import { AiPromptFields, AiPromptSubscriptionIntroduction } from './AiPromptFields'+import { InsightSelector } from './InsightSelector'+import { SubscriptionDayPicker } from './SubscriptionDayPicker'+import { subscriptionLogic } from './subscriptionLogic'+import type { SubscriptionLogicProps } from './subscriptionLogic'+import {+ frequencyOptionsPlural,+ frequencyOptionsSingular,+ getAiSubscriptionGate,+ intervalOptions,+ bysetposOptions,+ monthlyWeekdayOptions,+ getSubscriptionAdvancedSettings,+ getNextDeliveryDate,+ formatSubscriptionSchedule,+ shouldShowDayPicker,+ requestSubscriptionWizardCancellation,+ targetTypeOptions,+ timeOptions,+ WEEKDAYS,+ weekdayOptions,+} from './utils'+import { SubscriptionCreationGate, SubscriptionFormSkeleton } from './views/EditSubscription'++interface SubscriptionWizardProps {+ insightShortId?: InsightShortId+ insightName?: string+ dashboard?: DashboardType<any> | null+ onCancel: () => void+}++enum SubscriptionWizardStep {+ Content = 'content',+ Delivery = 'delivery',+ Schedule = 'schedule',+ Review = 'review',+}++const steps = [+ { key: SubscriptionWizardStep.Content, label: 'What to send' },+ { key: SubscriptionWizardStep.Delivery, label: 'Notify' },+ { key: SubscriptionWizardStep.Schedule, label: 'Schedule' },+ { key: SubscriptionWizardStep.Review, label: 'Review' },+]++function wizardStepDescription(step: SubscriptionWizardStep): string {+ if (step === SubscriptionWizardStep.Content) {+ return 'Choose the report content to include.'+ }+ if (step === SubscriptionWizardStep.Delivery) {+ return 'Choose who to notify about this subscription.'+ }+ if (step === SubscriptionWizardStep.Schedule) {+ return 'Choose when to send this subscription.'+ }+ return 'Check the delivery details before creating the subscription.'+}++export function SubscriptionWizard({+ insightShortId,+ insightName,+ dashboard,+ onCancel,+}: SubscriptionWizardProps): JSX.Element {+ const logicProps = {+ id: 'new' as const,+ insightShortId,+ dashboardId: dashboard?.id,+ dashboardName: dashboard?.name,+ insightName,+ creationSource: 'wizard' as const,+ }+ const subscriptionFormLogic = subscriptionLogic(logicProps)+ const [currentStep, setStep] = useState<SubscriptionWizardStep>(SubscriptionWizardStep.Content)+ const {+ subscription,+ subscriptionLoading,+ subscriptionInitialized,+ isSubscriptionSubmitting,+ subscriptionChanged,+ } = useValues(subscriptionFormLogic)+ const { generatePreview, resetSubscription } = useActions(subscriptionFormLogic)+ const { preflight } = useValues(preflightLogic)+ const { currentOrganization } = useValues(organizationLogic)+ const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')++ if (subscriptionLoading || !subscriptionInitialized) {+ return <SubscriptionFormSkeleton />+ }+ if (!subscription) {+ return <div>Could not load the subscription form.</div>+ }++ const isAiPrompt = subscription.resource_type === SubscriptionResourceTypes.AiPrompt+ const aiGate = getAiSubscriptionGate({+ isAiPrompt,+ isParentless: !insightShortId && !dashboard,+ isEditing: false,+ aiConsentApproved: Boolean(currentOrganization?.is_ai_data_processing_approved),+ isCloud: Boolean(preflight?.cloud),+ isDebug: Boolean(preflight?.is_debug),+ aiFlagEnabled: Boolean(aiSubscriptionsEnabled),+ })+ const selectedInsightsReady = !dashboard || Boolean(subscription.dashboard_export_insights?.length)+ const contentDetailReady = isAiPrompt ? Boolean(subscription.prompt?.trim()) : selectedInsightsReady+ const contentReady = Boolean(subscription.title?.trim()) && contentDetailReady+ let contentDisabledReason: string | undefined++ if (!subscription.title?.trim()) {+ contentDisabledReason = 'Enter a subscription name'+ } else if (isAiPrompt && !subscription.prompt?.trim()) {+ contentDisabledReason = 'Enter a prompt'+ } else if (aiGate.submitBlocked) {+ contentDisabledReason = 'Enable AI data processing to create an AI prompt subscription'+ } else if (!selectedInsightsReady) {+ contentDisabledReason = 'Select at least one insight'+ }+ const emailAvailable = subscription.target_type !== 'email' || Boolean(preflight?.email_service_available)+ const destinationReady = Boolean(+ emailAvailable &&+ subscription.target_value &&+ (subscription.target_type !== 'slack' || subscription.integration_id)+ )+ const requiresDeliveryDays = shouldShowDayPicker(subscription.frequency, subscription.interval)+ const scheduleReady = Boolean(+ subscription.frequency &&+ subscription.interval &&+ subscription.start_date &&+ (!requiresDeliveryDays || subscription.byweekday?.length)+ )+ let destinationDisabledReason: string | undefined+ if (!destinationReady) {+ destinationDisabledReason = emailAvailable+ ? 'Choose a destination and recipient'+ : 'Email delivery is not configured for this PostHog instance'+ }+ const currentStepIndex = steps.findIndex((step) => step.key === currentStep)+ const goToStep = (step: SubscriptionWizardStep): void => {+ if (step === SubscriptionWizardStep.Review && insightShortId && !isAiPrompt) {+ generatePreview()+ }+ setStep(step)+ }+ const requestCancel = (): void =>+ requestSubscriptionWizardCancellation({ onCancel, resetSubscription, subscriptionChanged })+ let stepContent: JSX.Element+ switch (currentStep) {+ case SubscriptionWizardStep.Content:+ stepContent = (+ <SubscriptionContentStep+ logicProps={logicProps}+ dashboard={dashboard}+ insightName={insightName}+ subscription={subscription}+ aiSubscriptionBlocked={aiGate.submitBlocked}+ />+ )+ break+ case SubscriptionWizardStep.Delivery:+ stepContent = <SubscriptionDeliveryStep subscription={subscription} logicProps={logicProps} />+ break+ case SubscriptionWizardStep.Schedule:+ stepContent = <SubscriptionScheduleStep logicProps={logicProps} />+ break+ case SubscriptionWizardStep.Review:+ stepContent = (+ <SubscriptionReviewStep+ logicProps={logicProps}+ subscription={subscription}+ dashboard={dashboard}+ insightShortId={insightShortId}+ />+ )+ break+ default:+ stepContent = <></>+ }+ const nextStep = steps[currentStepIndex + 1]?.key+ let continueDisabledReason: string | undefined+ if (currentStep === SubscriptionWizardStep.Content) {+ continueDisabledReason = contentReady ? undefined : contentDisabledReason+ } else if (currentStep === SubscriptionWizardStep.Delivery) {+ continueDisabledReason = destinationDisabledReason+ } else if (currentStep === SubscriptionWizardStep.Schedule) {+ continueDisabledReason = scheduleReady ? undefined : 'Choose a delivery time and at least one delivery day'+ }+ let primaryAction: JSX.Element | null = null+ if (currentStep === SubscriptionWizardStep.Review) {+ primaryAction = (+ <LemonButton type="primary" htmlType="submit" loading={isSubscriptionSubmitting}>+ Create subscription+ </LemonButton>+ )+ } else if (nextStep) {+ primaryAction = (+ <LemonButton+ type="primary"+ htmlType="button"+ onClick={(event) => {+ event.preventDefault()+ goToStep(nextStep)+ }}+ disabledReason={continueDisabledReason}+ >+ Continue+ </LemonButton>+ )+ }++ return (+ <SubscriptionCreationGate onCancel={requestCancel}>+ <Form+ logic={subscriptionLogic}+ props={logicProps}+ formKey="subscription"+ enableFormOnSubmit+ className="flex flex-1 flex-col"+ >+ <div className="flex min-h-[36rem] flex-1 flex-col overflow-hidden">+ <header className="border-b p-4">+ <div className="flex items-center gap-2">+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconChevronLeft />}+ onClick={requestCancel}+ />+ <h2 className="text-lg font-semibold m-0">New subscription</h2>+ </div>+ <nav aria-label="Subscription setup progress" className="mt-3">+ <ol className="flex flex-wrap items-center gap-x-1 gap-y-2">+ {steps.map((step, index) => {+ const isCurrent = index === currentStepIndex+ const isComplete = index < currentStepIndex+ const canAccess = index <= currentStepIndex+ return (+ <li key={step.key} className="flex shrink-0 items-center gap-1">+ <button+ type="button"+ disabled={!canAccess}+ onClick={() => canAccess && goToStep(step.key)}+ className={cn(+ 'flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-accent',+ canAccess && 'cursor-pointer',+ !canAccess && 'opacity-40 cursor-not-allowed',+ isCurrent+ ? 'bg-accent text-white font-semibold'+ : isComplete+ ? 'bg-success-highlight text-success'+ : 'text-muted hover:bg-border'+ )}+ aria-current={isCurrent ? 'step' : undefined}+ >+ <span+ className={cn(+ 'inline-flex size-5 shrink-0 items-center justify-center rounded-full text-[11px] font-bold',+ isCurrent+ ? 'bg-white text-accent'+ : isComplete+ ? 'bg-success text-white'+ : 'border border-border'+ )}+ >+ {index + 1}+ </span>+ <span>{step.label}</span>+ </button>+ {index < steps.length - 1 ? <span className="text-border">→</span> : null}+ </li>+ )+ })}+ </ol>+ </nav>+ </header>+ <section className="p-4 min-h-0 flex-1 overflow-y-auto">+ <div className="space-y-1 mb-3">+ <h3 className="text-base font-semibold m-0">{steps[currentStepIndex].label}</h3>+ <p className="text-xs text-secondary m-0">{wizardStepDescription(currentStep)}</p>+ </div>+ {stepContent}+ </section>+ <footer className="flex flex-wrap items-center justify-between gap-2 border-t p-4">+ <div />+ <div className="flex items-center gap-2">+ {currentStep === SubscriptionWizardStep.Content ? (+ <LemonButton type="secondary" htmlType="button" onClick={requestCancel}>+ Close+ </LemonButton>+ ) : (+ <LemonButton+ type="secondary"+ htmlType="button"+ icon={<IconChevronLeft className="size-4" />}+ onClick={() => setStep(steps[currentStepIndex - 1].key)}+ disabled={isSubscriptionSubmitting}+ >+ Back+ </LemonButton>+ )}+ {primaryAction}+ </div>+ </footer>+ </div>+ </Form>+ </SubscriptionCreationGate>+ )+}++function SubscriptionDeliveryStep({+ subscription,+ logicProps,+}: {+ subscription: SubscriptionType+ logicProps: SubscriptionLogicProps+}): JSX.Element {+ const { meFirstMembers, membersLoading } = useValues(membersLogic)+ const { integrations, slackIntegrations } = useValues(integrationsLogic)+ const { preflight } = useValues(preflightLogic)+ const { setSubscriptionValue } = useActions(subscriptionLogic(logicProps))++ return (+ <div className="flex flex-col gap-4">+ <LemonField name="target_type" label="Send to">+ <LemonSelect options={targetTypeOptions} />+ </LemonField>+ {subscription.target_type === 'email' && !preflight?.email_service_available ? (+ <LemonBanner type="error">+ Email subscriptions are not available because this PostHog instance is not configured to send email.{' '}+ <Link to="https://posthog.com/docs/self-host/configure/email" target="_blank" targetBlankIcon>+ Configure email delivery+ </Link>+ </LemonBanner>+ ) : null}+ {subscription.target_type === 'email' ? (+ <>+ <LemonField name="target_value" label="Recipients">+ {({ value, onChange }) => (+ <LemonInputSelect+ value={value?.split(',').filter(Boolean)}+ onChange={(recipients) => onChange(recipients.join(','))}+ mode="multiple"+ allowCustomValues+ options={usersLemonSelectOptions(meFirstMembers.map((member) => member.user))}+ loading={membersLoading}+ placeholder="Enter an email address"+ />+ )}+ </LemonField>+ <LemonField name="invite_message" label="Message" showOptional>+ <LemonTextArea placeholder="Message for recipients" />+ </LemonField>+ </>+ ) : null}+ {subscription.target_type === 'slack' ? (+ !slackIntegrations?.length ? (+ <SlackNotConfiguredBanner />+ ) : (+ <>+ <LemonField name="integration_id" label="Slack connection">+ {({ value, onChange }) => (+ <IntegrationChoice+ integration="slack"+ value={value}+ onChange={(integrationId) => {+ onChange(integrationId)+ if (value !== null && integrationId !== value) {+ setSubscriptionValue('target_value', '')+ }+ }}+ />+ )}+ </LemonField>+ {subscription.integration_id ? (+ <LemonField name="target_value" label="Slack channel">+ {({ value, onChange }) => {+ const integration = integrations?.find(+ (item) => item.id === subscription.integration_id+ )+ return integration ? (+ <SlackChannelPicker+ value={value}+ onChange={onChange}+ integration={integration}+ />+ ) : (+ <></>+ )+ }}+ </LemonField>+ ) : null}+ </>+ )+ ) : null}+ </div>+ )+}++function SubscriptionContentStep({+ logicProps,+ dashboard,+ insightName,+ subscription,+ aiSubscriptionBlocked,+}: {+ logicProps: SubscriptionLogicProps+ dashboard?: DashboardType<any> | null+ insightName?: string+ subscription: SubscriptionType+ aiSubscriptionBlocked: boolean+}): JSX.Element {+ const { applyDefaultSelectedInsights, selectAiAnalysisWindow, selectAiExamplePrompt } = useActions(+ subscriptionLogic(logicProps)+ )+ const isAiPrompt = subscription.resource_type === SubscriptionResourceTypes.AiPrompt++ return (+ <div className="flex flex-col gap-4">+ {isAiPrompt ? <AiPromptSubscriptionIntroduction /> : null}+ {isAiPrompt && aiSubscriptionBlocked ? (+ <LemonBanner type="info">+ Enable AI data processing in your Organization settings to create an AI prompt subscription.{' '}+ <Link to={urls.settings('organization-details', 'organization-ai-consent')}>+ Manage AI data processing+ </Link>+ </LemonBanner>+ ) : null}+ {insightName && !isAiPrompt ? (+ <div className="flex items-center gap-2 font-semibold">+ <IconGraph className="size-5 shrink-0 text-accent" />+ {insightName}+ </div>+ ) : null}+ <LemonField name="title" label="Name">+ <LemonInput />+ </LemonField>+ {isAiPrompt ? (+ <AiPromptFields+ compactAnalysisWindow+ prompt={subscription.prompt}+ windowMode={subscription.ai_prompt_config?.window?.mode}+ onSelectAnalysisWindow={selectAiAnalysisWindow}+ onSelectExample={selectAiExamplePrompt}+ />+ ) : null}+ {dashboard?.tiles && !isAiPrompt ? (+ <LemonField name="dashboard_export_insights" label="Insights to include">+ {({ value, onChange }) => (+ <InsightSelector+ tiles={dashboard.tiles}+ selectedInsightIds={value ?? []}+ onChange={onChange}+ onDefaultsApplied={applyDefaultSelectedInsights}+ />+ )}+ </LemonField>+ ) : null}+ <SubscriptionSettingsStep subscription={subscription} logicProps={logicProps} />+ </div>+ )+}++function SubscriptionScheduleStep({ logicProps }: { logicProps: SubscriptionLogicProps }): JSX.Element {+ const { subscription } = useValues(subscriptionLogic(logicProps))+ const { currentTeam } = useValues(teamLogic)+ const availableFrequencyOptions = subscription?.interval === 1 ? frequencyOptionsSingular : frequencyOptionsPlural+ const nextDeliveryDate = subscription ? getNextDeliveryDate(subscription) : null++ return (+ <div className="flex flex-col gap-4">+ <LemonLabel>When should we send it?</LemonLabel>+ <div className="flex flex-wrap items-center gap-2">+ <span>Every</span>+ <LemonField name="interval">+ <LemonSelect options={intervalOptions} />+ </LemonField>+ <LemonField name="frequency">+ <LemonSelect options={availableFrequencyOptions} />+ </LemonField>+ {subscription && shouldShowDayPicker(subscription.frequency, subscription.interval) ? (+ <>+ <span>on</span>+ <LemonField name="byweekday">+ {({ value, onChange }) => <SubscriptionDayPicker value={value ?? []} onChange={onChange} />}+ </LemonField>+ </>+ ) : null}+ {subscription?.frequency === 'monthly' ? (+ <>+ <span>on the</span>+ <LemonField name="bysetpos">+ {({ value, onChange }) => (+ <LemonSelect+ options={bysetposOptions}+ value={value ? String(value) : null}+ onChange={(value) => onChange(value === null ? null : Number(value))}+ />+ )}+ </LemonField>+ <LemonField name="byweekday">+ {({ value, onChange }) => {+ const isWeekday = value?.length === 5 && value.every((day: string) => WEEKDAYS.has(day))+ let displayValue = 'day'+ if (isWeekday) {+ displayValue = 'weekday'+ } else if (value?.length === 1) {+ displayValue = value[0]+ }++ return (+ <LemonSelect+ dropdownMatchSelectWidth={false}+ options={monthlyWeekdayOptions}+ value={displayValue}+ onChange={(value) => {+ if (value === 'day') {+ onChange(weekdayOptions.map(({ value }) => value))+ return+ }+ if (value === 'weekday') {+ onChange([...WEEKDAYS])+ return+ }+ onChange([value])+ }}+ />+ )+ }}+ </LemonField>+ </>+ ) : null}+ <span>at</span>+ <LemonField name="start_date">+ {({ value, onChange }) => (+ <LemonSelect+ options={timeOptions}+ value={dayjs(value).hour().toString()}+ onChange={(hour) =>+ onChange(+ dayjs()+ .hour(Number(hour ?? 0))+ .minute(0)+ .second(0)+ .toISOString()+ )+ }+ />+ )}+ </LemonField>+ </div>+ {nextDeliveryDate ? (+ <div className="flex flex-col gap-3">+ <NextScheduledRun label="Next planned delivery:">+ <span>+ Approximately <TZLabel time={dayjs(nextDeliveryDate)} />+ </span>+ </NextScheduledRun>+ <ProjectTimezoneNotice+ timezone={currentTeam?.timezone ?? 'UTC'}+ settingsUrl={urls.settings('environment-customization', 'date-and-time')}+ />+ </div>+ ) : null}+ </div>+ )+}++function SubscriptionSettingsStep({+ subscription,+ logicProps,+}: {+ subscription: SubscriptionType+ logicProps: SubscriptionLogicProps+}): JSX.Element {+ const { dataProcessingAccepted } = useValues(maxGlobalLogic)+ const { summaryQuota } = useValues(subscriptionLogic(logicProps))++ return (+ <div className="mt-6 flex flex-col gap-2">+ <LemonLabel>Advanced settings</LemonLabel>+ {dataProcessingAccepted && subscription.resource_type !== SubscriptionResourceTypes.AiPrompt ? (+ <LemonField name="summary_enabled">+ {({ value, onChange }) => (+ <LemonSwitch+ checked={value}+ onChange={onChange}+ disabledReason={+ summaryQuota?.at_limit && !value+ ? `Plan limit reached (${summaryQuota.limit} active AI summaries)`+ : undefined+ }+ bordered+ fullWidth+ label={+ <div className="flex flex-col gap-1 py-1">+ <div className="leading-tight">Include an automatic AI summary</div>+ <div className="text-xs text-secondary font-normal leading-tight">+ Add an AI-written overview of the report to each delivery.+ </div>+ </div>+ }+ />+ )}+ </LemonField>+ ) : null}+ {summaryQuota?.at_limit && !subscription.summary_enabled && summaryQuota.limit !== null ? (+ <UsageLimitPaywall+ title="AI summary limit reached"+ description="Disable an existing AI summary or upgrade your plan to add more."+ limit={summaryQuota.limit}+ currentUsage={summaryQuota.active_count}+ unit="active AI summaries on your plan"+ />+ ) : null}+ <LemonField name="send_test_now">+ {({ value, onChange }) => (+ <LemonSwitch+ checked={value}+ onChange={onChange}+ bordered+ fullWidth+ label={+ <div className="flex flex-col gap-1 py-1">+ <div className="leading-tight">Send a test run now</div>+ <div className="text-xs text-secondary font-normal leading-tight">+ Send this report once now so you can confirm the delivery.+ </div>+ </div>+ }+ />+ )}+ </LemonField>+ </div>+ )+}++function formatAiAnalysisWindow(subscription: SubscriptionType): string {+ const window = subscription.ai_prompt_config?.window++ if (window?.mode === 'last_n_days') {+ return `Last ${window.start_days_ago} days`+ }+ if (window?.mode === 'days_ago_range') {+ return `${window.start_days_ago} to ${window.end_days_ago} days ago`+ }+ return 'Since last report'+}++function SubscriptionReviewStep({+ logicProps,+ subscription,+ dashboard,+ insightShortId,+}: {+ logicProps: SubscriptionLogicProps+ subscription: SubscriptionType+ dashboard?: DashboardType<any> | null+ insightShortId?: InsightShortId+}): JSX.Element {+ const { previewLoading, previewError, previewImageUrl } = useValues(subscriptionLogic(logicProps))+ const { generatePreview } = useActions(subscriptionLogic(logicProps))+ const selectedInsightsCount = subscription.dashboard_export_insights?.length ?? 0+ const advancedSettings = getSubscriptionAdvancedSettings(subscription)+ const nextDeliveryDate = getNextDeliveryDate(subscription)+ const isAiPrompt = subscription.resource_type === SubscriptionResourceTypes.AiPrompt+ let reviewNotice: JSX.Element++ if (subscription.send_test_now) {+ reviewNotice = <>We will send a test report now so you can confirm the delivery.</>+ } else if (nextDeliveryDate) {+ reviewNotice = (+ <>+ No test report will be sent. The first scheduled report will arrive{' '}+ <TZLabel+ time={dayjs(nextDeliveryDate)}+ formatDate="ddd, MMM D"+ formatTime="h:mm A"+ timestampStyle="absolute"+ />+ .+ </>+ )+ } else {+ reviewNotice = <>No test report will be sent. The subscription will start on its normal schedule.</>+ }+ const reviewItems = [+ { label: 'Name', value: subscription.title },+ ...(isAiPrompt+ ? [+ { label: 'Prompt', value: subscription.prompt ?? '' },+ { label: 'Analysis window', value: formatAiAnalysisWindow(subscription) },+ ]+ : []),+ { label: 'Sends to', value: subscription.target_value },+ { label: 'Runs', value: formatSubscriptionSchedule(subscription) },+ ...(dashboard+ ? [+ {+ label: 'Insights',+ value: `${selectedInsightsCount} ${selectedInsightsCount === 1 ? 'insight' : 'insights'} included`,+ },+ ]+ : []),+ ...(advancedSettings.length ? [{ label: 'Advanced settings', value: advancedSettings.join(' · ') }] : []),+ ]++ return (+ <div className="flex flex-col gap-4">+ <WizardReview items={reviewItems} footer={<div className="text-secondary text-sm">{reviewNotice}</div>} />+ {insightShortId && !isAiPrompt ? (+ <div>+ <LemonLabel className="mb-2">Preview</LemonLabel>+ <div className="border rounded p-2">+ {previewLoading ? (+ <div className="overflow-hidden rounded border">+ <LemonSkeleton className="aspect-video w-full" />+ </div>+ ) : null}+ {previewError ? (+ <div className="flex flex-col items-start gap-2">+ <LemonBanner type="error">{previewError}</LemonBanner>+ <LemonButton+ type="secondary"+ htmlType="button"+ onClick={generatePreview}+ disabled={previewLoading}+ size="small"+ data-attr="subscription-wizard-generate-preview"+ >+ Try again+ </LemonButton>+ </div>+ ) : null}+ {previewImageUrl ? (+ <div className="mt-2 border rounded">+ <img src={previewImageUrl} alt="Subscription export preview" className="w-full" />+ </div>+ ) : null}+ </div>+ </div>+ ) : null}+ </div>+ )+}diff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsxindex 42af3fa5153b..22b31ada62de 100644--- a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx@@ -270,7 +270,16 @@ export default metatype Story = StoryObj<StoryArgs>export const SubscriptionsNew: Story = {- args: { subscriptionId: 'new', formScenario: 'default' },+ args: { isCreating: true, formScenario: 'default' },+}++export const SubscriptionWizardNew: Story = {+ parameters: {+ featureFlags: {+ [FEATURE_FLAGS.SUBSCRIPTION_CREATION_WIZARD]: 'test',+ },+ },+ args: { isCreating: true, formScenario: 'default' },}// Tabbed overview, dashboard context: This dashboard / Insights / AI prompt reports tabs.@@ -281,16 +290,17 @@ export const SubscriptionsTabbed: Story = {},},args: {+ subscriptionId: null,dashboard: DASHBOARD,},}export const DashboardWithSubscriptions: Story = {parameters: AI_PROMPT_PARAMETERS,- args: { dashboard: DASHBOARD },+ args: { subscriptionId: null, dashboard: DASHBOARD },}export const InsightWithSubscriptions: Story = {parameters: AI_PROMPT_PARAMETERS,- args: { insightShortId: 'ins11' as InsightShortId },+ args: { subscriptionId: null, insightShortId: 'ins11' as InsightShortId },}diff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsxindex 50286f592195..88e8330036dd 100644--- a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsx@@ -1,34 +1,92 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { useState } from 'react'+import posthog from 'posthog-js'+import { useEffect, useRef, useState } from 'react'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonModal } from 'lib/lemon-ui/LemonModal'import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { userLogic } from 'scenes/userLogic'-import { DashboardType, InsightShortId } from '~/types'+import { DashboardType, InsightShortId, SubscriptionResourceTypes } from '~/types'-import { SubscriptionBaseProps, urlForSubscription, urlForSubscriptions } from './utils'+import { subscriptionLogic } from './subscriptionLogic'+import { SubscriptionWizard } from './SubscriptionWizard'+import {+ requestSubscriptionWizardCancellation,+ SubscriptionBaseProps,+ urlForSubscription,+ urlForSubscriptions,+} from './utils'import { EditSubscription } from './views/EditSubscription'import { SubscriptionTabKey, TabbedManageSubscriptions } from './views/TabbedManageSubscriptions'export interface SubscriptionsModalProps {isOpen: booleancloseModal: () => void- subscriptionId: number | 'new' | null+ subscriptionId?: number | null+ isCreating?: booleaninline?: booleaninsightShortId?: InsightShortId+ insightName?: stringdashboard?: DashboardType<any> | null'data-attr'?: string}export function SubscriptionsModal(props: SubscriptionsModalProps): JSX.Element {- const { closeModal, dashboard, insightShortId, subscriptionId, isOpen, inline, 'data-attr': dataAttr } = props+ const {+ closeModal,+ dashboard,+ insightShortId,+ insightName,+ isCreating = false,+ subscriptionId,+ isOpen,+ inline,+ 'data-attr': dataAttr,+ } = propsconst { push } = useActions(router)const { userLoading } = useValues(userLogic)+ const { searchParams } = useValues(router)+ const subscriptionWizardExperimentEnabled = useFeatureFlag('SUBSCRIPTION_CREATION_WIZARD', 'test')const dashboardId = dashboard?.id+ const isAiPrompt = searchParams.resource_type === SubscriptionResourceTypes.AiPromptconst baseProps: SubscriptionBaseProps = { insightShortId, dashboardId }+ const isWizard = isCreating && (insightShortId || dashboard || isAiPrompt) && subscriptionWizardExperimentEnabled+ const modalWasOpen = useRef(false)+ useEffect(() => {+ if (!isOpen) {+ modalWasOpen.current = false+ return+ }+ if (!isCreating || modalWasOpen.current) {+ return+ }+ modalWasOpen.current = true+ posthog.capture('subscription creation modal opened', {+ creation_source: isWizard ? 'wizard' : 'editor',+ resource_type: isAiPrompt ? 'ai' : dashboard ? 'dashboard' : 'insight',+ })+ }, [dashboard, isAiPrompt, isCreating, isOpen, isWizard])+ const cancelWizard = (): void => push(urlForSubscriptions(baseProps))+ const requestWizardCancel = (): void => {+ const wizardForm = subscriptionLogic.findMounted({+ id: 'new',+ insightShortId,+ dashboardId,+ creationSource: 'wizard',+ })+ if (!wizardForm) {+ cancelWizard()+ return+ }+ requestSubscriptionWizardCancellation({+ onCancel: cancelWizard,+ resetSubscription: () => wizardForm.actions.resetSubscription(),+ subscriptionChanged: wizardForm.values.subscriptionChanged,+ })+ }// Owned here (not in the tabbed view) so the selected tab survives the edit round-trip,// during which the tabbed view unmounts.const [activeTab, setActiveTab] = useState<SubscriptionTabKey>('resource')@@ -38,15 +96,15 @@ export function SubscriptionsModal(props: SubscriptionsModalProps): JSX.Element}return (<LemonModal- onClose={closeModal}+ onClose={isWizard ? requestWizardCancel : closeModal}isOpen={isOpen}width={720}simple- title=""+ title={isWizard ? 'New subscription' : ''}inline={inline}data-attr={dataAttr}>- {!subscriptionId ? (+ {!isCreating && subscriptionId === null ? (<TabbedManageSubscriptions{...baseProps}activeTab={activeTab}@@ -59,9 +117,16 @@ export function SubscriptionsModal(props: SubscriptionsModalProps): JSX.Element)}/>+ ) : isWizard ? (+ <SubscriptionWizard+ insightShortId={insightShortId}+ insightName={insightName}+ dashboard={dashboard}+ onCancel={cancelWizard}+ />) : (<EditSubscription- id={subscriptionId}+ id={subscriptionId ?? 'new'}insightShortId={insightShortId}dashboard={dashboard}onCancel={() => push(urlForSubscriptions(baseProps))}diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.tsindex b8974d35537b..3f4f55ee3e88 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts@@ -238,6 +238,34 @@ describe('subscriptionLogic', () => {})})+ it('records successful wizard-created subscriptions separately from the editor', async () => {+ const wizardLogic = subscriptionLogic({+ insightShortId: Insight1,+ insightName: 'Feature flag evaluations',+ id: 'new',+ creationSource: 'wizard',+ })+ wizardLogic.mount()++ router.actions.push('/insights/123/subscriptions/new')+ await expectLogic(wizardLogic).toFinishListeners()+ expect(wizardLogic.values.subscription.title).toBe('Weekly report: Feature flag evaluations')++ wizardLogic.actions.setSubscriptionValues({+ title: 'Weekly report: Feature flag evaluations',+ target_type: 'email',+ target_value: '[email protected]',+ })+ wizardLogic.actions.submitSubscription()+ await expectLogic(wizardLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])++ expect(posthog.capture).toHaveBeenCalledWith(+ 'subscription created',+ expect.objectContaining({ creation_source: 'wizard' })+ )+ wizardLogic.unmount()+ })+it('preselects an AI prompt report from the new-subscription URL', async () => {router.actions.push('/insights/123/subscriptions/new?resource_type=ai_prompt')@@ -246,6 +274,53 @@ describe('subscriptionLogic', () => {expect(newLogic.values.subscription.resource_type).toBe('ai_prompt')})+ it('keeps the analysis window when selecting an example question', async () => {+ router.actions.push('/insights/123/subscriptions/new?resource_type=ai_prompt')+ await expectLogic(newLogic).toFinishListeners()+ newLogic.actions.setSubscriptionValues({+ ai_prompt_config: { window: { mode: 'days_ago_range', start_days_ago: 14, end_days_ago: 7 } },+ })++ newLogic.actions.selectAiExamplePrompt(+ 'Top 5 events by volume, with counts and unique users for each.',+ 'Top events'+ )+ await expectLogic(newLogic).toFinishListeners()++ expect(newLogic.values.subscription.ai_prompt_config?.window).toEqual({+ mode: 'days_ago_range',+ start_days_ago: 14,+ end_days_ago: 7,+ })+ })++ it('prefills seven days when selecting the last-N-days analysis window', async () => {+ router.actions.push('/insights/123/subscriptions/new?resource_type=ai_prompt')+ await expectLogic(newLogic).toFinishListeners()++ newLogic.actions.selectAiAnalysisWindow('last_n_days')+ await expectLogic(newLogic).toFinishListeners()++ expect(newLogic.values.subscription.ai_prompt_config?.window).toEqual({+ mode: 'last_n_days',+ start_days_ago: 7,+ })+ })++ it('prefills a two-week range ending today when selecting the range analysis window', async () => {+ router.actions.push('/insights/123/subscriptions/new?resource_type=ai_prompt')+ await expectLogic(newLogic).toFinishListeners()++ newLogic.actions.selectAiAnalysisWindow('days_ago_range')+ await expectLogic(newLogic).toFinishListeners()++ expect(newLogic.values.subscription.ai_prompt_config?.window).toEqual({+ mode: 'days_ago_range',+ start_days_ago: 14,+ end_days_ago: 0,+ })+ })+it('sets the type from query params', async () => {router.actions.push('/insights/123/subscriptions/new?target_type=slack')await expectLogic(newLogic).toFinishListeners()@@ -254,6 +329,23 @@ describe('subscriptionLogic', () => {})})+ it('prefills the current user email for a new email subscription', async () => {+ router.actions.push('/insights/123/subscriptions/new')+ await expectLogic(newLogic).toFinishListeners()++ expect(newLogic.values.subscription).toMatchObject({+ target_type: 'email',+ target_value: MOCK_DEFAULT_USER.email,+ })+ expect(newLogic.values.subscriptionChanged).toBe(false)++ newLogic.actions.setSubscriptionValue('target_type', 'slack')+ newLogic.actions.setSubscriptionValue('target_type', 'email')+ await expectLogic(newLogic).toFinishListeners()++ expect(newLogic.values.subscription.target_value).toBe(MOCK_DEFAULT_USER.email)+ })+// Products deep-link here with a ready-made report (the MCP analytics recurring-report cards),// so dropping this prefill would silently open an empty form and lose the whole one-click flow.it('prefills a ready-made AI report from the parent-less new-subscription URL', async () => {diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.tsindex d95a3615e516..8c2a7191a97b 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts@@ -28,6 +28,7 @@ import type { AIWindowConfigApi, SubscriptionDeliveryApi } from 'products/subscrimport type { SubscriptionResourceType, UserBasicType, WeekdayType } from '../../../../../frontend/src/types'import type { OrganizationType, UserType } from '../../../../../frontend/src/types'import type { AIPromptConfigApi } from '../../generated/api.schemas'+import type { AIWindowConfigModeEnumApi } from '../../generated/api.schemas'import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'import { SUBSCRIPTION_PREFILL_PARAMS } from './subscriptionNudge'import { subscriptionsLogic } from './subscriptionsLogic'@@ -180,6 +181,8 @@ 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+ insightName?: string+ creationSource?: 'editor' | 'wizard'}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface subscriptionLogicValues {@@ -200,6 +203,7 @@ export interface subscriptionLogicValues {subscriptionChanged: booleansubscriptionErrors: DeepPartialMap<SubscriptionType, ValidationErrorType>subscriptionHasErrors: boolean+ subscriptionInitialized: booleansubscriptionLoading: booleansubscriptionManualErrors: Record<string, any>subscriptionTouched: boolean@@ -336,14 +340,15 @@ export interface subscriptionLogicActions {resetSubscription: (values?: SubscriptionType) => {values?: SubscriptionType}+ selectAiAnalysisWindow: (mode: AIWindowConfigApi['mode']) => {+ mode: AIWindowConfigModeEnumApi | undefined+ }selectAiExamplePrompt: (prompt: string,- label: string,- window?: AIWindowConfigApi+ label: string) => {label: stringprompt: string- window: AIWindowConfigApi | undefined}sendTestDelivery: () => {value: true@@ -415,7 +420,10 @@ export type subscriptionLogicType = MakeLogicType<export const subscriptionLogic = kea<subscriptionLogicType>([path(['lib', 'components', 'Subscriptions', 'subscriptionLogic']),props({} as SubscriptionLogicProps),- key(({ id, insightShortId, dashboardId }) => `${insightShortId || dashboardId}-${id ?? 'new'}`),+ key(+ ({ id, insightShortId, dashboardId, creationSource }) =>+ `${insightShortId || dashboardId}-${id ?? 'new'}-${creationSource ?? 'editor'}`+ ),connect(() => ({ values: [userLogic, ['user'], organizationLogic, ['currentOrganization']] })),actions({@@ -428,11 +436,11 @@ export const subscriptionLogic = kea<subscriptionLogicType>([setPreviewError: (error: string | null) => ({ error }),setPreviewImageUrl: (url: string | null) => ({ url }),applyDefaultSelectedInsights: (selectedIds: number[]) => ({ selectedIds }),- selectAiExamplePrompt: (prompt: string, label: string, window?: AIWindowConfigApi) => ({+ selectAiExamplePrompt: (prompt: string, label: string) => ({prompt,label,- window,}),+ selectAiAnalysisWindow: (mode: AIWindowConfigApi['mode']) => ({ mode }),}),reducers({@@ -476,6 +484,12 @@ export const subscriptionLogic = kea<subscriptionLogicType>([setPreviewImageUrl: (_, { url }) => url,},],+ subscriptionInitialized: [+ false,+ {+ loadSubscriptionSuccess: () => true,+ },+ ],}),loaders(({ props }) => ({@@ -577,6 +591,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([if (updatedSub.id !== props.id) {router.actions.replace(urlForSubscription(updatedSub.id, props))posthog.capture('subscription created', {+ creation_source: props.creationSource ?? 'editor',resource_type: isAi ? 'ai' : props.dashboardId ? 'dashboard' : 'insight',dashboard_id: props.dashboardId,insight_short_id: props.insightShortId,@@ -601,6 +616,34 @@ export const subscriptionLogic = kea<subscriptionLogicType>([listeners(({ actions, values, props, selectors, cache }) => ({loadSubscriptionSuccess: () => {+ const initialSubscription = values.subscription+ if (!initialSubscription) {+ return+ }+ const defaults = { ...initialSubscription }+ let defaultsApplied = false+ if (+ props.id === 'new' &&+ defaults.target_type === 'email' &&+ !defaults.target_value &&+ values.user?.email+ ) {+ defaults.target_value = values.user.email+ defaultsApplied = true+ }+ if (props.id === 'new' && props.creationSource === 'wizard' && !defaults.title) {+ let title = 'Weekly report'+ if (props.dashboardName) {+ title = `${props.dashboardName} weekly digest`+ } else if (props.insightName) {+ title = `Weekly report: ${props.insightName}`+ }+ defaults.title = title+ defaultsApplied = true+ }+ if (defaultsApplied) {+ actions.resetSubscription(defaults)+ }if (props.id !== 'new') {actions.loadLastDelivery()}@@ -664,18 +707,25 @@ export const subscriptionLogic = kea<subscriptionLogicType>([// suppression matching and serves as the applied-once guard on later quota reloads.cache.prefillBaseline = { ...cache.prefillBaseline, summary_enabled: true }},- selectAiExamplePrompt: ({ prompt, label, window }) => {+ selectAiExamplePrompt: ({ prompt, label }) => {posthog.capture('subscription_ai_example_prompt_selected', { label })actions.setSubscriptionValue('prompt', prompt)- const currentMode = values.subscription?.ai_prompt_config?.window?.mode ?? 'since_last_sent'- if (window && currentMode === 'since_last_sent') {- // Presets that imply a timeframe prefill the analysis window — but only while the- // window is still the default, so a deliberately-chosen one survives the click.- // Spread keeps future sibling config keys intact.- actions.setSubscriptionValues({- ai_prompt_config: { ...values.subscription?.ai_prompt_config, window },- })+ },+ selectAiAnalysisWindow: ({ mode }) => {+ const config = values.subscription?.ai_prompt_config ?? {}+ const window = { ...config.window, mode }+ if (mode === 'last_n_days' && !window.start_days_ago) {+ window.start_days_ago = 7}+ if (mode === 'days_ago_range') {+ if (window.start_days_ago === null || window.start_days_ago === undefined) {+ window.start_days_ago = 14+ }+ if (window.end_days_ago === null || window.end_days_ago === undefined) {+ window.end_days_ago = 0+ }+ }+ actions.setSubscriptionValues({ ai_prompt_config: { ...config, window } })},submitSubscriptionFailure: ({ error }) => {// Kea-forms emits this when client validation fails; fields already show errors.@@ -721,7 +771,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([if (key === 'target_type') {actions.setSubscriptionValues({- target_value: '',+ target_value: value === 'email' ? (values.user?.email ?? '') : '',integration_id: null,})}@@ -803,8 +853,11 @@ export const subscriptionLogic = kea<subscriptionLogicType>([},})),- events(({ actions, values }) => ({+ events(({ actions, values, props }) => ({afterMount: () => {+ if (props.id === 'new' && !values.subscriptionInitialized) {+ actions.loadSubscriptionSuccess({ ...NEW_SUBSCRIPTION })+ }// Load the org-wide AI summary quota once per logic mount so// the paywall conditional in EditSubscription has data to react// to without depending on URL navigation. urlToAction kept itsdiff --git a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts b/products/subscriptions/frontend/components/Subscriptions/utils.test.tsindex 480790441be4..c591b482dfbc 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts@@ -2,8 +2,10 @@ import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'import {canNudgeToSubscribe,+ formatSubscriptionSchedule,getAiSubscriptionGate,getNextDeliveryDate,+ getSubscriptionAdvancedSettings,selectedDaysToDayPickerLabel,shouldShowDayPicker,toggleSelectedDay,@@ -40,6 +42,31 @@ describe('day picker values', () => {})})+describe('formatSubscriptionSchedule', () => {+ it('includes every selected delivery day in a weekly schedule summary', () => {+ expect(+ formatSubscriptionSchedule({+ frequency: 'weekly',+ interval: 1,+ start_date: '2024-01-01T09:00:00Z',+ byweekday: ['monday', 'wednesday'],+ })+ ).toBe('Every 1 week on Monday and Wednesday at 9:00 AM')+ })+})++describe('getSubscriptionAdvancedSettings', () => {+ it('lists only delivery settings that differ from the default flow', () => {+ expect(+ getSubscriptionAdvancedSettings({+ summary_enabled: true,+ summary_prompt_guide: 'Prioritize activation changes',+ send_test_now: false,+ })+ ).toEqual(['Automatic AI summary', 'Custom AI summary context', 'No test delivery'])+ })+})+describe('getNextDeliveryDate', () => {beforeEach(() => {jest.useFakeTimers()diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsxindex bebacd74db1f..fbf54eb66a11 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx@@ -3,7 +3,9 @@ import { RRule } from 'rrule'import { IconLetter } from '@posthog/icons'import { LemonSelectOption, LemonSelectOptionLeaf, LemonSelectOptions } from '@posthog/lemon-ui'+import { dayjs } from 'lib/dayjs'import { IconSlack } from 'lib/lemon-ui/icons'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { range } from 'lib/utils/arrays'import { urls } from 'scenes/urls'@@ -12,6 +14,37 @@ import { InsightShortId, SubscriptionType, WeekdayType } from '~/types'export const AI_PROMPT_MAX_LENGTH = SubscriptionAIPromptMaxLength.CHARACTERS+export function requestSubscriptionWizardCancellation({+ onCancel,+ resetSubscription,+ subscriptionChanged,+}: {+ onCancel: () => void+ resetSubscription: () => void+ subscriptionChanged: boolean+}): void {+ if (!subscriptionChanged) {+ onCancel()+ return+ }++ LemonDialog.open({+ title: 'Discard subscription changes?',+ description: 'Your subscription configuration will be lost.',+ primaryButton: {+ children: 'Discard changes',+ status: 'danger',+ onClick: () => {+ resetSubscription()+ onCancel()+ },+ },+ secondaryButton: {+ children: 'Keep editing',+ },+ })+}+export function isFreeTierCreateAtLimit(subscriptionCount: number | null): boolean {return subscriptionCount !== null && subscriptionCount >= SubscriptionFreeTierLimit.COUNT}@@ -121,6 +154,60 @@ export function selectedDaysToDayPickerLabel(selectedDays: WeekdayType[]): strinreturn `on ${selectedDays.length} days`}+export function formatSubscriptionSchedule(+ subscription: Pick<SubscriptionType, 'frequency' | 'interval' | 'start_date' | 'byweekday'>+): string {+ const frequency =+ subscription.interval === 1+ ? { daily: 'day', weekly: 'week', monthly: 'month', yearly: 'year' }[subscription.frequency]+ : subscription.frequency+ const selectedDays = shouldShowDayPicker(subscription.frequency, subscription.interval)+ ? ` ${formatSelectedDeliveryDays(subscription.byweekday ?? [])}`+ : ''++ return `Every ${subscription.interval} ${frequency}${selectedDays} at ${dayjs(subscription.start_date).format('h:mm A')}`+}++export function getSubscriptionAdvancedSettings(+ subscription: Pick<SubscriptionType, 'summary_enabled' | 'summary_prompt_guide' | 'send_test_now'>+): string[] {+ const settings: string[] = []++ if (subscription.summary_enabled) {+ settings.push('Automatic AI summary')+ }+ if (subscription.summary_prompt_guide?.trim()) {+ settings.push('Custom AI summary context')+ }+ if (subscription.send_test_now === false) {+ settings.push('No test delivery')+ }++ return settings+}++function formatSelectedDeliveryDays(selectedDays: WeekdayType[]): string {+ if (hasSameDays(selectedDays, ALL_DAYS)) {+ return 'on Monday to Sunday'+ }+ if (hasSameDays(selectedDays, WEEKDAY_DAYS)) {+ return 'on weekdays'+ }+ if (hasSameDays(selectedDays, WEEKEND_DAYS)) {+ return 'on weekends'+ }++ const labels = weekdayOptions.filter((day) => selectedDays.includes(day.value)).map((day) => day.label)+ if (labels.length < 2) {+ return labels.length ? `on ${labels[0]}` : 'on no days'+ }+ if (labels.length === 2) {+ return `on ${labels[0]} and ${labels[1]}`+ }++ return `on ${labels.slice(0, -1).join(', ')}, and ${labels[labels.length - 1]}`+}+export function toggleSelectedDay(selectedDays: WeekdayType[], day: WeekdayType): WeekdayType[] {const nextDays = new Set(selectedDays)if (nextDays.has(day)) {diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex 18c990003bfc..7a341f00f747 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -1,8 +1,9 @@import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'+import { ReactNode } from 'react'import { IconChevronLeft, IconSend } from '@posthog/icons'-import { LemonCheckbox, LemonDropdown, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'+import { LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'import { FlaggedFeature } from 'lib/components/FlaggedFeature'@@ -35,31 +36,29 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'-import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes, WeekdayType } from '~/types'+import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes } from '~/types'-import type { AIWindowConfigApi, SubscriptionDeliveryApi } from 'products/subscriptions/frontend/generated/api.schemas'+import type { SubscriptionDeliveryApi } from 'products/subscriptions/frontend/generated/api.schemas'+import { AiPromptFields, AiPromptSubscriptionIntroduction } from '../AiPromptFields'import { InsightSelector } from '../InsightSelector'import { subscriptionCountLogic } from '../subscriptionCountLogic'+import { SubscriptionDayPicker } from '../SubscriptionDayPicker'import { subscriptionLogic } from '../subscriptionLogic'import { subscriptionsLogic } from '../subscriptionsLogic'import {bysetposOptions,- ALL_DAYS,frequencyOptionsPlural,frequencyOptionsSingular,getAiSubscriptionGate,getNextDeliveryDate,intervalOptions,monthlyWeekdayOptions,- selectedDaysToDayPickerLabel,shouldShowDayPicker,targetTypeOptions,timeOptions,- toggleSelectedDay,- weekdayOptions,WEEKDAYS,- AI_PROMPT_MAX_LENGTH,+ weekdayOptions,isFreeTierCreateAtLimit,} from '../utils'@@ -77,62 +76,6 @@ function AiConsentGateMessage(): JSX.Element {)}-function SubscriptionDayPicker({- value,- onChange,-}: {- value: WeekdayType[]- onChange: (value: WeekdayType[]) => void-}): JSX.Element {- let selectAllChecked: boolean | 'indeterminate' = false- if (value.length === ALL_DAYS.length) {- selectAllChecked = true- } else if (value.length > 0) {- selectAllChecked = 'indeterminate'- }-- return (- <LemonDropdown- closeOnClickInside={false}- placement="bottom-start"- overlay={- <div className="w-48 flex flex-col gap-0.5">- <div className="flex items-center mb-0.5">- <LemonButton- size="small"- className="flex-1"- icon={<LemonCheckbox checked={selectAllChecked} className="pointer-events-none" />}- disabledReason={value.length === ALL_DAYS.length ? 'All days are selected' : undefined}- onClick={() => onChange([...ALL_DAYS])}- >- Select all- </LemonButton>- <LemonButton- size="small"- disabledReason={value.length === 0 ? 'No days are selected' : undefined}- onClick={() => onChange([])}- >- Clear all- </LemonButton>- </div>- {weekdayOptions.map((day) => (- <LemonCheckbox- key={day.value}- checked={value.includes(day.value)}- label={day.label}- fullWidth- className="px-2 py-1 rounded hover:bg-bg-3000"- onChange={() => onChange(toggleSelectedDay(value, day.value))}- />- ))}- </div>- }- >- <LemonButton type="secondary">{selectedDaysToDayPickerLabel(value)}</LemonButton>- </LemonDropdown>- )-}-function LastDeliveryStatus({lastDelivery,loading,@@ -167,29 +110,6 @@ function LastDeliveryStatus({)}-const AI_PROMPT_EXAMPLES: { label: string; prompt: string; window?: AIWindowConfigApi }[] = [- {- label: 'Top events',- prompt: 'Top 5 events by volume, with counts and unique users for each.',- window: { mode: 'last_n_days', start_days_ago: 7 },- },- {- label: 'Period-over-period growth',- prompt: 'For the top 10 events by volume, compare the current period vs the previous one and rank by growth rate. Flag any event that more than doubled or halved.',- window: { mode: 'last_n_days', start_days_ago: 7 },- },- {- label: 'Health check',- prompt: 'Health check: total event volume and unique active users, and how each compares to the previous period.',- window: { mode: 'last_n_days', start_days_ago: 7 },- },- {- label: 'Tracking gaps',- prompt: 'Which events we normally track received no data? List them so I can catch broken instrumentation.',- window: { mode: 'last_n_days', start_days_ago: 7 },- },-]-interface EditSubscriptionProps {id: number | 'new'insightShortId?: InsightShortId@@ -199,20 +119,32 @@ interface EditSubscriptionProps {}export function EditSubscription(props: EditSubscriptionProps): JSX.Element {- const { hasAvailableFeature } = useValues(userLogic)const isCreating = props.id === 'new'- const hasSubscriptionsFeature = hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS)- // Editing existing subscriptions, and any paid org, are never gated and never fetch the count.- if (!isCreating || hasSubscriptionsFeature) {+ if (!isCreating) {return <EditSubscriptionForm {...props} />}- return <FreeTierCreateGate {...props} />+ return (+ <SubscriptionCreationGate onCancel={props.onCancel}>+ <EditSubscriptionForm {...props} />+ </SubscriptionCreationGate>+ )}-function FreeTierCreateGate(props: EditSubscriptionProps): JSX.Element {+export function SubscriptionCreationGate({+ onCancel,+ children,+}: {+ onCancel: () => void+ children: ReactNode+}): JSX.Element {+ const { hasAvailableFeature } = useValues(userLogic)const { subscriptionCount, subscriptionCountLoading } = useValues(subscriptionCountLogic)+ if (hasAvailableFeature(AvailableFeature.SUBSCRIPTIONS)) {+ return <>{children}</>+ }+// Wait for the count before deciding form-vs-paywall, otherwise the form flashes during the// in-flight fetch and is yanked away once the count arrives. On fetch failure the loader settles// with a null count and loading=false, so we fall through and fail open to the form.@@ -229,7 +161,7 @@ function FreeTierCreateGate(props: EditSubscriptionProps): JSX.Element {<div className="flex flex-1 flex-col min-h-0"><LemonModal.Header><div className="flex items-center gap-2">- <LemonButton icon={<IconChevronLeft />} onClick={props.onCancel} size="xsmall" />+ <LemonButton icon={<IconChevronLeft />} onClick={onCancel} size="xsmall" /><h3>New Subscription</h3></div></LemonModal.Header>@@ -250,149 +182,36 @@ function FreeTierCreateGate(props: EditSubscriptionProps): JSX.Element {</div>)}- return <EditSubscriptionForm {...props} />+ return <>{children}</>}-const AI_WINDOW_MODE_OPTIONS = [- {- value: 'since_last_sent' as const,- label: 'Since last report',- labelInMenu: (- <div className="flex flex-col">- <span>Since last report</span>- <span className="text-xs text-secondary">- Everything new since the previous scheduled report (no gaps)- </span>- </div>- ),- },- {- value: 'last_n_days' as const,- label: 'Last N days',- labelInMenu: (- <div className="flex flex-col">- <span>Last N days</span>- <span className="text-xs text-secondary">A fixed trailing window, e.g. always the last 7 days</span>- </div>- ),- },- {- value: 'days_ago_range' as const,- label: 'Between X and Y days ago',- labelInMenu: (- <div className="flex flex-col">- <span>Between X and Y days ago</span>- <span className="text-xs text-secondary">An explicit historical range, e.g. 14 to 7 days ago</span>- </div>- ),- },-]--function AiPromptFields({- prompt,- windowMode,- showConsentBanner,- onSelectExample,-}: {- prompt?: string | null- windowMode?: AIWindowConfigApi['mode']- showConsentBanner: boolean- onSelectExample: (prompt: string, label: string, window?: AIWindowConfigApi) => void-}): JSX.Element {+export function SubscriptionFormSkeleton(): JSX.Element {return (- <>- {showConsentBanner && (- <LemonBanner type="warning" className="text-sm">- <AiConsentGateMessage />- </LemonBanner>- )}- <LemonBanner type="info" className="text-sm">- The AI analyzes your project's recent events and writes a markdown report. Each delivery is generated- independently.- </LemonBanner>- <LemonField- name="prompt"- label="Prompt"- help="Describe what the AI should look for. The same prompt runs every time the subscription fires."- >- <LemonTextArea- placeholder="e.g. Which events grew the most week-over-week? Highlight any unusual spikes."- minRows={4}- maxLength={AI_PROMPT_MAX_LENGTH}- />- </LemonField>- {/* Starter chips replace the whole prompt, so only offer them while the field is empty — once the- user has typed anything, a stray click would wipe their prompt with no undo. */}- {!prompt?.trim() && (- <div className="flex flex-col gap-1">- <span className="text-xs text-secondary">Try one of these prompts:</span>- <div className="flex flex-wrap gap-1">- {AI_PROMPT_EXAMPLES.map((example) => (- <LemonButton- key={example.label}- size="xsmall"- type="secondary"- onClick={() => onSelectExample(example.prompt, example.label, example.window)}- >- {example.label}- </LemonButton>- ))}- </div>+ <div className="flex min-h-[36rem] flex-col gap-4 p-4">+ {[+ ['w-1/3', 'w-full'],+ ['w-1/4', 'w-full'],+ ].map(([label, field], index) => (+ <div key={index} className="flex flex-col gap-2">+ <LemonSkeleton className={`h-4 ${label}`} />+ <LemonSkeleton className={`h-9 ${field}`} /></div>- )}- <LemonField- name={['ai_prompt_config', 'window', 'mode']}- label="Analysis window"- help="The exact time range is computed in your project's timezone each time the report runs."- >- <LemonSelect options={AI_WINDOW_MODE_OPTIONS} />- </LemonField>- {windowMode === 'last_n_days' && (- <LemonField name={['ai_prompt_config', 'window', 'start_days_ago']} label="Number of days to analyze">- {({ value, onChange }) => (- <div className="flex items-center gap-2">- <LemonInput- type="number"- min={1}- max={365}- value={value ?? undefined}- onChange={(newValue) => onChange(newValue ?? null)}- className="w-24"- />- <span>days back from each run</span>- </div>- )}- </LemonField>- )}- {windowMode === 'days_ago_range' && (- <div className="flex items-start gap-2">- <LemonField name={['ai_prompt_config', 'window', 'start_days_ago']} label="From (days ago)">- {({ value, onChange }) => (- <LemonInput- type="number"- min={1}- max={365}- value={value ?? undefined}- onChange={(newValue) => onChange(newValue ?? null)}- className="w-24"- />- )}- </LemonField>- <LemonField name={['ai_prompt_config', 'window', 'end_days_ago']} label="To (days ago)">- {({ value, onChange }) => (- <LemonInput- type="number"- min={0}- max={365}- value={value ?? undefined}- onChange={(newValue) => onChange(newValue ?? null)}- className="w-24"- />- )}- </LemonField>+ ))}+ <div className="flex flex-col gap-2">+ <LemonSkeleton className="h-4 w-1/3" />+ <div className="rounded border p-3 flex flex-wrap gap-2">+ <LemonSkeleton className="h-9 w-16" />+ <LemonSkeleton className="h-9 w-20" />+ <LemonSkeleton className="h-9 w-28" />+ <LemonSkeleton className="h-9 w-24" /></div>- )}- </>+ </div>+ <div className="flex flex-col gap-2">+ <LemonSkeleton className="h-4 w-1/4" />+ <LemonSkeleton className="h-12 w-full" />+ <LemonSkeleton className="h-12 w-full" />+ </div>+ </div>)}@@ -485,6 +304,10 @@ function EditSubscriptionForm({const subscriptionLoaded = !!subscription?.target_typeconst selectionReady = !isEditing || subscriptionLoaded+ if (subscriptionLoading || (isEditing && !subscriptionLoaded)) {+ return <SubscriptionFormSkeleton />+ }+const _onDelete = (): void => {if (isEditing) {deleteSubscription(id)@@ -622,12 +445,18 @@ function EditSubscriptionForm({)}{isAiPrompt ? (- <AiPromptFields- prompt={subscription.prompt}- windowMode={subscription.ai_prompt_config?.window?.mode}- showConsentBanner={aiGate.showAiFormConsentBanner}- onSelectExample={logic.actions.selectAiExamplePrompt}- />+ <>+ <AiPromptSubscriptionIntroduction />+ <AiPromptFields+ prompt={subscription.prompt}+ windowMode={subscription.ai_prompt_config?.window?.mode}+ consentBanner={+ aiGate.showAiFormConsentBanner ? <AiConsentGateMessage /> : undefined+ }+ onSelectAnalysisWindow={logic.actions.selectAiAnalysisWindow}+ onSelectExample={logic.actions.selectAiExamplePrompt}+ />+ </>) : null}<LemonField name="target_type" label="Destination">diff --git a/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx b/products/subscriptions/frontend/scenes/SubscriptionsScene.tsxindex d97157d4b36b..e531c9ed5694 100644--- a/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx+++ b/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx@@ -7,6 +7,7 @@ import { LemonButton, LemonMenu, LemonModal, Link } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'import { Spinner } from 'lib/lemon-ui/Spinner'@@ -22,6 +23,9 @@ import { ProductKey } from '~/queries/schema/schema-general'import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'+import { subscriptionLogic } from '../components/Subscriptions/subscriptionLogic'+import { SubscriptionWizard } from '../components/Subscriptions/SubscriptionWizard'+import { requestSubscriptionWizardCancellation } from '../components/Subscriptions/utils'import { EditSubscription } from '../components/Subscriptions/views/EditSubscription'import { SubscriptionsFiltersBar } from './components/SubscriptionsFiltersBar'import {@@ -118,6 +122,21 @@ export function SubscriptionsScene(): JSX.Element {subscriptionModalId,aiSubscriptionsAvailable,} = useValues(subscriptionsSceneLogic)+ const subscriptionWizardExperimentEnabled = useFeatureFlag('SUBSCRIPTION_CREATION_WIZARD', 'test')+ const isWizard = subscriptionModalId === 'new' && subscriptionWizardExperimentEnabled+ const cancelWizard = (): void => router.actions.push(urls.subscriptions())+ const requestWizardCancel = (): void => {+ const wizardForm = subscriptionLogic.findMounted({ id: 'new', creationSource: 'wizard' })+ if (!wizardForm) {+ cancelWizard()+ return+ }+ requestSubscriptionWizardCancellation({+ onCancel: cancelWizard,+ resetSubscription: () => wizardForm.actions.resetSubscription(),+ subscriptionChanged: wizardForm.values.subscriptionChanged,+ })+ }const { setCurrentTab, setSubscriptionsSorting } = useActions(subscriptionsSceneLogic)const isFiltered =@@ -206,12 +225,17 @@ export function SubscriptionsScene(): JSX.Element {)}</div>{subscriptionModalId !== null && (- <LemonModal isOpen onClose={() => router.actions.push(urls.subscriptions())} simple={false} width={650}>- <EditSubscription- id={subscriptionModalId}- onCancel={() => router.actions.push(urls.subscriptions())}- onDelete={() => router.actions.push(urls.subscriptions())}- />+ <LemonModal+ isOpen+ onClose={isWizard ? requestWizardCancel : cancelWizard}+ simple={isWizard}+ width={isWizard ? 720 : 650}+ >+ {isWizard ? (+ <SubscriptionWizard onCancel={cancelWizard} />+ ) : (+ <EditSubscription id={subscriptionModalId} onCancel={cancelWizard} onDelete={cancelWizard} />+ )}</LemonModal>)}</SceneContent>