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.

7.7 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import type { PostHog } from 'posthog-js'

import { FlagInfo, toFlagInfo } from '~/toolbar/shared/flags/flagInfo'
import { flagsToolbarLogic, flagsToolbarLogicValues } from '~/toolbar/shared/flags/flagsToolbarLogic'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'

import type { FeatureFlagType } from '../../../../types'
import type { PageFlagMutationStatus } from '../../messaging/pagePosthogBridge'
import type { PageToolbarFlagsState } from '../../messaging/pageToolbarBridge'

export type PageFlagsCommand =
    | { type: 'set-flag-override'; flagKey: string; value: string | boolean }
    | { type: 'remove-flag-override'; flagKey: string }
    | { type: 'save-flag-payload'; flagKey: string; draftPayload: string }
    | { type: 'clear-flag-overrides' }
    | { type: 'reload-flags' }
    | { type: 'impersonate-flags'; distinctId: string }
    | { type: 'clear-flag-impersonation' }

type FilteredFlag = flagsToolbarLogicValues['filteredFlags'][number]

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageFlagsLogicValues {
    countFlagsOverridden: number // flagsToolbarLogic
    filteredFlags: {
        currentValue: boolean | string
        feature_flag: FeatureFlagType
        hasOverride: boolean
        hasVariants: boolean
        payloadOverride: any
        value: boolean | string
    }[] // flagsToolbarLogic
    impersonatedDistinctId: string | null // flagsToolbarLogic
    payloadErrors: Record<string, string | null> // flagsToolbarLogic
    userFlagsLoading: boolean // flagsToolbarLogic
    posthog: PostHog | null // toolbarConfigLogic
    flagMutationStatus: PageFlagMutationStatus
    flags: FlagInfo[]
    pageState: PageToolbarFlagsState
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageFlagsLogicActions {
    handleCommand: (command: PageFlagsCommand) => {
        command: PageFlagsCommand
    }
    openFlags: () => {
        value: true
    }
    setFlagMutationStatus: (status: PageFlagMutationStatus) => {
        status: PageFlagMutationStatus
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionPageFlagsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        flags: (
            filteredFlags: {
                currentValue: boolean | string
                feature_flag: FeatureFlagType
                hasOverride: boolean
                hasVariants: boolean
                payloadOverride: any
                value: boolean | string
            }[]
        ) => FlagInfo[]
        pageState: (
            posthog: PostHog | null,
            userFlagsLoading: boolean,
            flags: FlagInfo[],
            countFlagsOverridden: number,
            impersonatedDistinctId: string | null,
            payloadErrors: Record<string, string | null>,
            flagMutationStatus: PageFlagMutationStatus
        ) => PageToolbarFlagsState
    }
}

export type extensionPageFlagsLogicType = MakeLogicType<
    extensionPageFlagsLogicValues,
    extensionPageFlagsLogicActions,
    Record<string, any>,
    extensionPageFlagsLogicMeta
>

export const extensionPageFlagsLogic = kea<extensionPageFlagsLogicType>([
    path(['toolbar', 'extension', 'extensionPageFlagsLogic']),
    connect(() => ({
        values: [
            flagsToolbarLogic,
            ['filteredFlags', 'userFlagsLoading', 'countFlagsOverridden', 'impersonatedDistinctId', 'payloadErrors'],
            toolbarConfigLogic,
            ['posthog'],
        ],
    })),
    actions({
        openFlags: true,
        handleCommand: (command: PageFlagsCommand) => ({ command }),
        setFlagMutationStatus: (status: PageFlagMutationStatus) => ({ status }),
    }),
    reducers({
        flagMutationStatus: [
            { pending: false, error: null, revision: 0 } as PageFlagMutationStatus,
            { setFlagMutationStatus: (_, { status }) => status },
        ],
    }),
    selectors({
        flags: [(s) => [s.filteredFlags], (filteredFlags: FilteredFlag[]): FlagInfo[] => filteredFlags.map(toFlagInfo)],
        pageState: [
            (s) => [
                s.posthog,
                s.userFlagsLoading,
                s.flags,
                s.countFlagsOverridden,
                s.impersonatedDistinctId,
                s.payloadErrors,
                s.flagMutationStatus,
            ],
            (
                posthog: PostHog | null,
                userFlagsLoading: boolean,
                flags: FlagInfo[],
                countFlagsOverridden: number,
                impersonatedDistinctId: string | null,
                payloadErrors: Record<string, string | null>,
                flagMutationStatus: PageFlagMutationStatus
            ): PageToolbarFlagsState => ({
                available: !!posthog,
                loading: userFlagsLoading,
                flags,
                countFlagsOverridden,
                impersonatedDistinctId,
                payloadErrors,
                mutationPending: flagMutationStatus.pending,
                mutationError: flagMutationStatus.error,
                mutationRevision: flagMutationStatus.revision,
            }),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        openFlags: () => {
            const posthog: PostHog | null = values.posthog
            const flags = flagsToolbarLogic.actions
            if (posthog && !cache.subscribed) {
                cache.subscribed = true
                posthog.onFeatureFlags(flags.setFeatureFlagValueFromPostHogClient)
                const variants = posthog.featureFlags.getFlagVariants()
                flags.setFeatureFlagValueFromPostHogClient(Object.keys(variants), variants)
            }
            flags.getUserFlags()
            flags.checkLocalOverrides()
        },
        setFlagMutationStatus: () => {
            // The page agent reports the overrides the page applied, which can differ from the ones the logic sent.
            flagsToolbarLogic.actions.checkLocalOverrides()
        },
        handleCommand: ({ command }) => {
            const flags = flagsToolbarLogic.actions
            switch (command.type) {
                case 'set-flag-override':
                    flags.setOverriddenUserFlag(command.flagKey, command.value)
                    return
                case 'remove-flag-override':
                    flags.deleteOverriddenUserFlag(command.flagKey)
                    return
                case 'save-flag-payload':
                    flags.setDraftPayload(command.flagKey, command.draftPayload)
                    flags.savePayloadOverride(command.flagKey)
                    if (values.payloadErrors[command.flagKey]) {
                        // Invalid JSON never reaches the page's posthog-js, so the change ends here with its error.
                        actions.setFlagMutationStatus({
                            ...values.flagMutationStatus,
                            revision: values.flagMutationStatus.revision + 1,
                        })
                    }
                    return
                case 'clear-flag-overrides':
                    flags.clearAllOverrides()
                    return
                case 'reload-flags':
                    flags.getUserFlags()
                    flags.checkLocalOverrides()
                    return
                case 'impersonate-flags':
                    flags.loadFlagsForDistinctId(command.distinctId)
                    return
                case 'clear-flag-impersonation':
                    flags.clearImpersonation()
                    return
            }
        },
    })),
])