Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

15.7 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { EarlyAccessFeature, posthog } from 'posthog-js'

import { supportLogic } from 'lib/components/Support/supportLogic'
import type { SupportFormFields } from 'lib/components/Support/supportLogic'
import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { createFeaturePreviewSearch } from 'lib/utils/fuseSearch'
import type { ProductCrossSellProperties } from 'lib/utils/product-intents'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import type { UserType } from '~/types'

export interface EnrichedEarlyAccessFeature extends Omit<EarlyAccessFeature, 'flagKey'> {
    flagKey: string
    enabled: boolean
    payload: Record<string, any> | undefined
}

const search = createFeaturePreviewSearch<EnrichedEarlyAccessFeature>()

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featurePreviewsLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    user: UserType | null // userLogic
    activeFeedbackFlagKey: string | null
    activeFeedbackFlagKeyLoading: boolean
    conceptEnrollments: Record<string, boolean>
    conceptSurveySubmissions: Record<string, boolean>
    earlyAccessFeatures: EnrichedEarlyAccessFeature[]
    filteredEarlyAccessFeatures: EnrichedEarlyAccessFeature[]
    rawEarlyAccessFeatures: EarlyAccessFeature[]
    rawEarlyAccessFeaturesLoading: boolean
    searchTerm: string
    waitlistSurveysEnabled: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featurePreviewsLogicActions {
    submitSupportTicket: (form: SupportFormFields) => SupportFormFields // supportLogic
    addProductIntentForCrossSell: (properties: ProductCrossSellProperties) => ProductCrossSellProperties // teamLogic
    beginEarlyAccessFeatureFeedback: (flagKey: string) => {
        flagKey: string
    }
    cancelEarlyAccessFeatureFeedback: () => {
        value: true
    }
    conceptSurveySubmitted: (flagKey: string) => {
        flagKey: string
    }
    copyExternalFeaturePreviewLink: (flagKey: string) => {
        flagKey: string
    }
    loadEarlyAccessFeatures: () => any
    loadEarlyAccessFeaturesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEarlyAccessFeaturesSuccess: (
        rawEarlyAccessFeatures: EarlyAccessFeature[],
        payload?: any
    ) => {
        rawEarlyAccessFeatures: EarlyAccessFeature[]
        payload?: any
    }
    setSearchTerm: (searchTerm: string) => {
        searchTerm: string
    }
    submitConceptSurvey: (
        flagKey: string,
        email: string
    ) => {
        email: string
        flagKey: string
    }
    submitEarlyAccessFeatureFeedback: (message: string) => {
        message: string
    }
    submitEarlyAccessFeatureFeedbackFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    submitEarlyAccessFeatureFeedbackSuccess: (
        activeFeedbackFlagKey: string | null,
        payload?: {
            message: string
        }
    ) => {
        activeFeedbackFlagKey: string | null
        payload?: {
            message: string
        }
    }
    updateEarlyAccessFeatureEnrollment: (
        flagKey: string,
        enabled: boolean,
        stage?: string
    ) => {
        enabled: boolean
        flagKey: string
        stage: string | undefined
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featurePreviewsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        earlyAccessFeatures: (
            rawEarlyAccessFeatures: EarlyAccessFeature[],
            featureFlags: FeatureFlagsSet,
            conceptEnrollments: Record<string, boolean>
        ) => EnrichedEarlyAccessFeature[]
        filteredEarlyAccessFeatures: (
            earlyAccessFeatures: EnrichedEarlyAccessFeature[],
            searchTerm: string
        ) => EnrichedEarlyAccessFeature[]
        waitlistSurveysEnabled: (featureFlags: FeatureFlagsSet) => boolean
    }
}

export type featurePreviewsLogicType = MakeLogicType<
    featurePreviewsLogicValues,
    featurePreviewsLogicActions,
    Record<string, any>,
    featurePreviewsLogicMeta
>

export const featurePreviewsLogic = kea<featurePreviewsLogicType>([
    path(['lib', 'components', 'FeaturePreviews', 'featurePreviewsLogic']),
    connect(() => ({
        values: [featureFlagLogic, ['featureFlags'], userLogic, ['user']],
        actions: [supportLogic, ['submitSupportTicket'], teamLogic, ['addProductIntentForCrossSell']],
    })),
    actions({
        setSearchTerm: (searchTerm: string) => ({ searchTerm }),
        updateEarlyAccessFeatureEnrollment: (flagKey: string, enabled: boolean, stage?: string) => ({
            flagKey,
            enabled,
            stage,
        }),
        beginEarlyAccessFeatureFeedback: (flagKey: string) => ({ flagKey }),
        cancelEarlyAccessFeatureFeedback: true,
        submitEarlyAccessFeatureFeedback: (message: string) => ({ message }),
        copyExternalFeaturePreviewLink: (flagKey: string) => ({ flagKey }),
        // Coming Soon (concept) waitlist: submit an email to the feature's linked survey
        // instead of the one-click enrollment.
        submitConceptSurvey: (flagKey: string, email: string) => ({ flagKey, email }),
        // Fired by the submitConceptSurvey listener once the response has actually been
        // captured, so the "thanks" state can't show when submission failed.
        conceptSurveySubmitted: (flagKey: string) => ({ flagKey }),
    }),
    loaders(({ values }) => ({
        rawEarlyAccessFeatures: [
            [] as EarlyAccessFeature[],
            {
                loadEarlyAccessFeatures: async () => {
                    return await new Promise((resolve) =>
                        posthog.getEarlyAccessFeatures((features) => resolve(features), true, [
                            'concept',
                            'alpha',
                            'beta',
                        ])
                    )
                },
            },
        ],
        activeFeedbackFlagKey: [
            null as string | null,
            {
                submitEarlyAccessFeatureFeedback: async ({ message }) => {
                    if (!values.user) {
                        throw new Error('Cannot submit early access feature feedback without a user')
                    }
                    if (!values.activeFeedbackFlagKey) {
                        throw new Error('Cannot submit early access feature feedback without an active flag key')
                    }
                    const feature = values.rawEarlyAccessFeatures.find(
                        (f) => f.flagKey === values.activeFeedbackFlagKey
                    )
                    // submitSupportTicket sets lastSubmittedTicketId only on success (it swallows
                    // failures with an error toast), so compare it before/after to tell them apart
                    const ticketIdBefore = supportLogic.values.lastSubmittedTicketId
                    await supportLogic.asyncActions.submitSupportTicket({
                        name: values.user.first_name,
                        email: values.user.email,
                        kind: 'feedback',
                        // The feature identity has to live in the message itself — a conversations
                        // ticket carries only the message, so without this the feedback arrives
                        // context-free
                        message: `Feedback on feature preview "${feature?.name ?? values.activeFeedbackFlagKey}":\n\n${message}`,
                    })
                    const ticketId = supportLogic.values.lastSubmittedTicketId
                    const succeeded = ticketId != null && ticketId !== ticketIdBefore
                    // On success clear the active key (closes the panel); on failure keep it open so
                    // the user's text survives for a retry (supportLogic already showed the error)
                    return succeeded ? null : values.activeFeedbackFlagKey
                },
            },
        ],
    })),
    reducers({
        searchTerm: [
            '',
            {
                setSearchTerm: (_, { searchTerm }) => searchTerm,
            },
        ],
        activeFeedbackFlagKey: {
            beginEarlyAccessFeatureFeedback: (_, { flagKey }) => flagKey,
            cancelEarlyAccessFeatureFeedback: () => null,
        },
        // Concept stage features don't enable their feature flag, so we track
        // enrollment locally to keep the "Registered" button state stable.
        conceptEnrollments: [
            {} as Record<string, boolean>,
            {
                updateEarlyAccessFeatureEnrollment: (state, { flagKey, enabled, stage }) => {
                    if (stage === 'concept') {
                        return { ...state, [flagKey]: enabled }
                    }
                    return state
                },
            },
        ],
        // Tracks which concept features the user has submitted the waitlist email for,
        // so the card can show a "thanks" state.
        conceptSurveySubmissions: [
            {} as Record<string, boolean>,
            {
                conceptSurveySubmitted: (state, { flagKey }) => ({ ...state, [flagKey]: true }),
            },
        ],
    }),
    listeners(({ values, actions }) => ({
        updateEarlyAccessFeatureEnrollment: ({ flagKey, enabled, stage }) => {
            if (window.IMPERSONATED_SESSION) {
                lemonToast.error('Cannot update early access feature enrollment while impersonating a user')
            } else {
                posthog.updateEarlyAccessFeatureEnrollment(flagKey, enabled, stage)

                // Track product intent if user is opting in and payload contains product_intent
                // The format on the payload should be: { product_intent: ProductKey }
                if (enabled) {
                    const feature = values.rawEarlyAccessFeatures.find((f) => f.flagKey === flagKey)

                    // TODO: We can stop using this crazy type cast once the companion `posthog-js` PR is merged
                    // https://github.com/PostHog/posthog-js/pull/2642
                    const payload = (feature as any)?.payload as Record<string, any> | undefined
                    if (payload?.product_intent) {
                        const productIntent = payload.product_intent

                        if (
                            productIntent &&
                            typeof productIntent === 'string' &&
                            Object.values(ProductKey).includes(productIntent as ProductKey)
                        ) {
                            void actions.addProductIntentForCrossSell({
                                from: ProductKey.EARLY_ACCESS_FEATURES,
                                to: productIntent as ProductKey,
                                intent_context: ProductIntentContext.FEATURE_PREVIEW_ENABLED,
                            })
                        }
                    }
                }
            }
        },
        copyExternalFeaturePreviewLink: ({ flagKey }) => {
            void copyToClipboard(urls.absolute(`/settings/user-feature-previews#${flagKey}`))
        },
        submitConceptSurvey: ({ flagKey, email }) => {
            // Keep the survey response and the enrollment person property in sync — the
            // enrollment listener below refuses impersonated sessions, so bail before
            // capturing anything.
            if (window.IMPERSONATED_SESSION) {
                lemonToast.error('Cannot sign up for a waitlist while impersonating a user')
                return
            }
            const feature = values.rawEarlyAccessFeatures.find((f) => f.flagKey === flagKey)
            const payload = (feature as any)?.payload as Record<string, any> | undefined
            const surveyId = payload?.survey_id
            if (!surveyId) {
                lemonToast.error("This feature isn't accepting sign-ups yet. Please try again later.")
                return
            }
            const surveyQuestionId = payload?.survey_question_id
            const properties: Record<string, any> = { $survey_id: surveyId, $survey_response: email }
            if (surveyQuestionId) {
                properties[`$survey_response_${surveyQuestionId}`] = email
            }
            posthog.capture('survey sent', properties)
            actions.conceptSurveySubmitted(flagKey)
            // Also record the enrollment so the "registered" state persists across
            // reloads (person property), matching the pre-survey behavior.
            actions.updateEarlyAccessFeatureEnrollment(flagKey, true, 'concept')
        },
    })),
    selectors({
        earlyAccessFeatures: [
            (s) => [s.rawEarlyAccessFeatures, s.featureFlags, s.conceptEnrollments],
            (
                rawEarlyAccessFeatures: EarlyAccessFeature[],
                featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,
                conceptEnrollments: Record<string, boolean>
            ): EnrichedEarlyAccessFeature[] => {
                // posthog-js persists enrollment as person properties in localStorage,
                // which survives page reloads even though concept-stage flags evaluate
                // to false on the server.
                const storedPersonProps =
                    (posthog.get_property('$stored_person_properties') as Record<string, string> | undefined) ?? {}

                const result = rawEarlyAccessFeatures
                    .filter((feature) => !!feature.flagKey) // Filter out features without a flag linked
                    .map((feature) => {
                        const flagKey = feature.flagKey! as FeatureFlagKey
                        const flag = featureFlags[flagKey]
                        const isConceptEnrolled =
                            feature.stage === 'concept' &&
                            (flagKey in conceptEnrollments
                                ? !!conceptEnrollments[flagKey]
                                : !!storedPersonProps[`$feature_enrollment/${flagKey}`])

                        return {
                            ...feature,
                            flagKey,
                            // Use payload from early access feature, fallback to empty object
                            payload: ((feature as any).payload as Record<string, any> | undefined) || {},
                            enabled: !!flag || isConceptEnrolled,
                        }
                    })

                return result
            },
        ],

        filteredEarlyAccessFeatures: [
            (s) => [s.earlyAccessFeatures, s.searchTerm],
            (earlyAccessFeatures: EnrichedEarlyAccessFeature[], searchTerm: string): EnrichedEarlyAccessFeature[] => {
                return search(earlyAccessFeatures, searchTerm)
            },
        ],

        // When enabled, concept-stage ("Coming Soon") items collect an email via their
        // linked survey instead of the one-click enrollment.
        waitlistSurveysEnabled: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.COMING_SOON_WAITLIST_SURVEYS],
        ],
    }),
])