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.

72.9 KB
Raw Blame
import './FeatureFlag.scss'

import {
    DndContext,
    DragEndEvent,
    DragOverlay,
    DragStartEvent,
    PointerSensor,
    UniqueIdentifier,
    useSensor,
    useSensors,
} from '@dnd-kit/core'
import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { useActions, useValues } from 'kea'
import { Form, Group } from 'kea-forms'
import { router } from 'kea-router'
import { useEffect, useRef, useState } from 'react'

import {
    IconBalance,
    IconCheckCircle,
    IconCode,
    IconFlag,
    IconCollapse,
    IconExpand,
    IconGlobe,
    IconInfo,
    IconList,
    IconPlus,
    IconServer,
    IconTrash,
} from '@posthog/icons'
import {
    LemonBanner,
    LemonButton,
    LemonCheckbox,
    LemonCollapse,
    LemonDivider,
    LemonInput,
    LemonInputSelect,
    LemonLabel,
    LemonSelect,
    LemonSwitch,
    LemonTextArea,
    Lettermark,
    LettermarkColor,
    Link,
    Spinner,
    Tooltip,
} from '@posthog/lemon-ui'
import { Button } from '@posthog/quill'

import { approvalsGateLogic } from 'lib/approvals/approvalsGateLogic'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { IconArrowDown, IconArrowUp, SortableDragIcon } from 'lib/lemon-ui/icons'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonField } from 'lib/lemon-ui/LemonField'
import 'lib/lemon-ui/Lettermark'
import { alphabet } from 'lib/utils/strings'
import { ApprovalActionKey } from 'scenes/approvals/utils'
import { JSONEditorInput } from 'scenes/feature-flags/JSONEditorInput'
import { urls } from 'scenes/urls'

import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { cohortsModel } from '~/models/cohortsModel'
import { tagsModel } from '~/models/tagsModel'
import {
    FeatureFlagBucketingIdentifier,
    FeatureFlagEvaluationRuntime,
    FeatureFlagWithV1Config,
    MultivariateFlagVariant,
} from '~/types'

import { runningExperimentId } from 'products/feature_flags/frontend/runningExperimentId'

import { FeatureFlagCodeExample } from './FeatureFlagCodeExample'
import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'
import {
    FeatureFlagLogicProps,
    featureFlagLogic,
    hasStaticCohortDependency,
    slugifyFeatureFlagKey,
    validateVariantRolloutSum,
} from './featureFlagLogic'
import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'
import { BULK_COPY_MAX_TARGET_PROJECTS } from './flagSelectionLogic'
import { PercentageInput } from './PercentageInput'

interface SortableVariantHeaderProps {
    variant: MultivariateFlagVariant
    index: number
    variants: MultivariateFlagVariant[]
    alphabet: string[]
    moveVariantUp: (index: number) => void
    moveVariantDown: (index: number) => void
}

function SortableVariantHeader({
    variant,
    index,
    variants,
    alphabet,
    moveVariantUp,
    moveVariantDown,
}: SortableVariantHeaderProps): JSX.Element {
    const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
        id: `variant-${index}`,
    })

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
    }

    return (
        <div ref={setNodeRef} style={style} className="flex gap-2 items-center justify-between w-full">
            <div className="flex gap-2 items-center">
                <Lettermark name={alphabet[index] ?? String(index + 1)} color={LettermarkColor.Gray} size="small" />
                <span className="text-sm font-medium">{variant.key || `Variant ${index + 1}`}</span>
                <span className="text-xs text-muted tabular-nums">({variant.rollout_percentage || 0}%)</span>
            </div>
            <div className="flex gap-1 items-center ml-auto">
                <LemonButton
                    size="xsmall"
                    onClick={(e) => {
                        e.stopPropagation()
                        moveVariantUp(index)
                    }}
                    disabled={index === 0}
                    tooltip="Move up"
                    icon={<IconArrowUp />}
                />
                <LemonButton
                    size="xsmall"
                    onClick={(e) => {
                        e.stopPropagation()
                        moveVariantDown(index)
                    }}
                    disabled={index === variants.length - 1}
                    tooltip="Move down"
                    icon={<IconArrowDown />}
                />
                <LemonButton
                    size="xsmall"
                    tooltip="Drag to reorder"
                    icon={<SortableDragIcon className="text-muted hover:text-default shrink-0" />}
                    onClick={(e) => e.stopPropagation()}
                    {...listeners}
                    {...attributes}
                    style={{ cursor: 'grab' }}
                    onMouseDown={(e) => {
                        e.currentTarget.style.cursor = 'grabbing'
                    }}
                    onMouseUp={(e) => {
                        e.currentTarget.style.cursor = 'grab'
                    }}
                />
            </div>
        </div>
    )
}

export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {
    const {
        props,
        featureFlag: loadedFeatureFlag,
        originalFeatureFlag,
        multivariateEnabled,
        variants,
        nonEmptyVariants,
        variantErrors,
        isEditingFlag,
        showImplementation,
        openVariants,
        payloadExpanded,
        advancedPanelOpen,
        hasEncryptedPayloadBeenSaved,
        hasEarlyAccessFeatures,
        alsoCreateInProjects,
        alsoCreateInProjectOptions,
        currentKeyConflict,
    } = useValues(featureFlagLogic)
    // The form never mounts for another config version (FeatureFlag.tsx), so the document is v1.
    const featureFlag = loadedFeatureFlag as FeatureFlagWithV1Config
    const lockedByExperimentId = runningExperimentId(featureFlag)
    const {
        setMultivariateEnabled,
        setFeatureFlag,
        addVariant,
        removeVariant,
        moveVariantUp,
        moveVariantDown,
        reorderVariants,
        distributeVariantsEqually,
        setFeatureFlagFilters,
        editFeatureFlag,
        loadFeatureFlag,
        setShowImplementation,
        setOpenVariants,
        setPayloadExpanded,
        setAdvancedExpanded,
        resetEncryptedPayload,
        setAlsoCreateInProjects,
        startNewFlagDisabled,
    } = useActions(featureFlagLogic)
    const { tags: availableTags } = useValues(tagsModel)
    const { isApprovalRequired } = useValues(approvalsGateLogic)
    const { allCohorts } = useValues(cohortsModel)
    const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
    const hasEvaluationContexts = useFeatureFlag('FLAG_EVALUATION_TAGS') // NB: the tag was named "flag-evaluation-tags" before we renamed the concept – i.e. this powers evaluation contexts even though the name implies tags
    const isNewFeatureFlag = id === 'new' || id === undefined
    const requiresApprovalToEnable = isNewFeatureFlag && isApprovalRequired(ApprovalActionKey.FEATURE_FLAG_ENABLE)
    const renamedFromKey =
        !isNewFeatureFlag && originalFeatureFlag && featureFlag.key !== originalFeatureFlag.key
            ? originalFeatureFlag.key
            : null
    const implementationRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
        if (requiresApprovalToEnable && featureFlag.active) {
            startNewFlagDisabled()
        }
    }, [requiresApprovalToEnable, featureFlag.active, startNewFlagDisabled])

    const cancelEditing = (): void => {
        if (isEditingFlag) {
            editFeatureFlag(false)
            loadFeatureFlag()
        } else {
            router.actions.push(urls.featureFlags())
        }
    }

    const handleShowImplementation = (): void => {
        setShowImplementation(true)
        setTimeout(() => {
            implementationRef.current?.scrollIntoView({
                behavior: 'smooth',
                block: 'start',
            })
        }, 150)
    }

    const confirmEncryptedPayloadReset = (): void => {
        LemonDialog.open({
            title: 'Reset payload?',
            description: 'The existing payload will not be reset until the feature flag is saved.',
            primaryButton: {
                children: 'Reset',
                onClick: resetEncryptedPayload,
                size: 'small',
                status: 'danger',
            },
            secondaryButton: {
                children: 'Cancel',
                type: 'tertiary',
                size: 'small',
            },
        })
    }

    const updateVariant = (
        index: number,
        field: 'key' | 'name' | 'rollout_percentage',
        value: string | number
    ): void => {
        const coercedValue = field === 'rollout_percentage' ? Number(value) || 0 : String(value)
        const currentVariants = [...variants]
        currentVariants[index] = {
            ...currentVariants[index],
            [field]: coercedValue,
        }

        setFeatureFlag({
            ...featureFlag,
            filters: {
                ...featureFlag?.filters,
                multivariate: {
                    ...featureFlag?.filters?.multivariate,
                    variants: currentVariants,
                },
            },
        })
    }

    const updateVariantPayload = (index: number, value: string | undefined): void => {
        const currentPayloads = { ...featureFlag?.filters?.payloads }
        if (value === '' || value === undefined) {
            delete currentPayloads[index]
        } else {
            currentPayloads[index] = value
        }
        setFeatureFlag({
            ...featureFlag,
            filters: {
                ...featureFlag?.filters,
                payloads: currentPayloads,
            },
        })
    }

    const currentFlagType = featureFlag?.is_remote_configuration
        ? 'remote_config'
        : multivariateEnabled
          ? 'multivariate'
          : 'boolean'

    const onSelectFlagType = (value: string): void => {
        // Leaving remote config: the backend invariant requires
        // has_encrypted_payloads=true only on remote config flags,
        // and the prior ciphertext is no longer valid.
        const wasLeavingRemoteConfig =
            featureFlag?.is_remote_configuration === true &&
            value !== 'remote_config' &&
            featureFlag?.has_encrypted_payloads

        if (value === 'remote_config') {
            setFeatureFlag({
                ...featureFlag,
                is_remote_configuration: true,
            })
            setMultivariateEnabled(false)
        } else if (value === 'multivariate') {
            setFeatureFlag({
                ...featureFlag,
                is_remote_configuration: false,
                filters: {
                    ...featureFlag?.filters,
                    payloads: {},
                },
            })
            setMultivariateEnabled(true)
        } else {
            setFeatureFlag({
                ...featureFlag,
                is_remote_configuration: false,
            })
            setMultivariateEnabled(false)
        }

        if (wasLeavingRemoteConfig) {
            resetEncryptedPayload()
        }
    }

    const rolloutSumError = validateVariantRolloutSum(variants)

    const FLAG_TYPE_OPTIONS = [
        {
            value: 'boolean',
            icon: <IconFlag className="text-lg" />,
            label: 'Boolean',
            description: 'Release toggle with optional static payload',
        },
        {
            value: 'multivariate',
            icon: <IconList className="text-lg" />,
            label: 'Multivariate',
            description: 'Multiple variants with rollout percentages (A/B/n test)',
        },
        {
            value: 'remote_config',
            icon: <IconCode className="text-lg" />,
            label: 'Remote config',
            description: 'Single payload without feature flag logic',
        },
    ] as const

    // Drag and drop functionality
    const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null)
    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 8,
            },
        })
    )

    const handleDragStart = (event: DragStartEvent): void => {
        setActiveId(event.active.id)
    }

    const handleDragEnd = (event: DragEndEvent): void => {
        const { active, over } = event

        if (over && active.id !== over.id) {
            const fromIndex = variants.findIndex((_, index) => `variant-${index}` === active.id)
            const toIndex = variants.findIndex((_, index) => `variant-${index}` === over.id)

            if (fromIndex !== -1 && toIndex !== -1) {
                reorderVariants(fromIndex, toIndex)
            }
        }

        setActiveId(null)
    }

    const getActiveVariant = (): MultivariateFlagVariant | null => {
        if (!activeId) {
            return null
        }
        const index = variants.findIndex((_, index) => `variant-${index}` === String(activeId))
        return index !== -1 ? variants[index] : null
    }

    // Calculate active variant index for drag overlay
    const activeVariantIndex = activeId ? variants.findIndex((_, index) => `variant-${index}` === String(activeId)) : -1

    // Calculate expand/collapse button state
    const allVariantKeys = variants.map((_, index) => `variant-${index}`)
    const allExpanded = allVariantKeys.every((key) => openVariants.includes(key))
    const anyExpanded = openVariants.length > 0

    if (!featureFlag) {
        return (
            <div className="flex items-center justify-center p-8">
                <Spinner className="text-2xl" />
            </div>
        )
    }
    return (
        <>
            <Form
                id="feature-flag"
                logic={featureFlagLogic}
                props={props}
                formKey="featureFlag"
                enableFormOnSubmit
                className="flex flex-col gap-4"
            >
                <SceneTitleSection
                    name={featureFlag.key || 'New feature flag'}
                    resourceType={{
                        type: featureFlag.active ? 'feature_flag' : 'feature_flag_off',
                    }}
                    forceBackTo={
                        isNewFeatureFlag
                            ? {
                                  key: 'FeatureFlagTemplates',
                                  name: 'Templates',
                                  path: urls.featureFlagTemplates(),
                              }
                            : undefined
                    }
                    actions={
                        todayRailNav ? (
                            <>
                                <Button data-attr="cancel-feature-flag" variant="outline" onClick={cancelEditing}>
                                    Cancel
                                </Button>
                                <Button
                                    variant="primary"
                                    data-attr="save-feature-flag"
                                    type="submit"
                                    form="feature-flag"
                                >
                                    Save
                                </Button>
                            </>
                        ) : (
                            <>
                                <LemonButton
                                    data-attr="cancel-feature-flag"
                                    type="secondary"
                                    size="small"
                                    onClick={cancelEditing}
                                >
                                    Cancel
                                </LemonButton>
                                <LemonButton
                                    type="primary"
                                    data-attr="save-feature-flag"
                                    htmlType="submit"
                                    form="feature-flag"
                                    size="small"
                                >
                                    Save
                                </LemonButton>
                            </>
                        )
                    }
                />

                <SceneContent>
                    {/* Two-column layout */}
                    <div className="flex gap-4 flex-wrap items-start">
                        {/* Left column */}
                        <div className="flex-1 min-w-[20rem] flex flex-col gap-4">
                            {/* Main settings card */}
                            <div className="rounded border p-3 bg-bg-light gap-2 flex flex-col">
                                <LemonField
                                    name="key"
                                    label="Flag key"
                                    info="Unique identifier used in your code."
                                    help={
                                        currentKeyConflict || renamedFromKey ? (
                                            <div className="flex flex-col gap-1">
                                                {currentKeyConflict ? (
                                                    <span
                                                        className={
                                                            currentKeyConflict.exact ? 'text-danger' : 'text-warning'
                                                        }
                                                        role="status"
                                                        aria-live="polite"
                                                    >
                                                        {currentKeyConflict.exact
                                                            ? 'A feature flag with this key already exists. Choose another key or '
                                                            : `A feature flag with the key "${currentKeyConflict.existingFlagKey}" already exists. Keys that differ only by case are easy to confuse. `}
                                                        <Link
                                                            to={urls.featureFlag(currentKeyConflict.existingFlagId)}
                                                            target="_blank"
                                                            data-attr="feature-flag-key-conflict-link"
                                                        >
                                                            {currentKeyConflict.exact
                                                                ? 'open the existing flag'
                                                                : 'Open it'}
                                                        </Link>
                                                        .
                                                    </span>
                                                ) : null}
                                                {renamedFromKey ? (
                                                    <span className="text-warning">
                                                        <b>Warning! </b>Changing this key will break any existing code
                                                        that references it (e.g.{' '}
                                                        <code className="text-xs bg-fill-secondary rounded px-1 py-0.5">
                                                            getFeatureFlag('{renamedFromKey}')
                                                        </code>
                                                        ). Make sure to update all SDK calls and integrations.
                                                    </span>
                                                ) : null}
                                            </div>
                                        ) : undefined
                                    }
                                >
                                    {({ value, onChange }) => (
                                        <LemonInput
                                            value={value}
                                            onChange={(v) => onChange(slugifyFeatureFlagKey(v))}
                                            data-attr="feature-flag-key"
                                            className="ph-ignore-input"
                                            autoComplete="off"
                                            autoCapitalize="off"
                                            autoCorrect="off"
                                            spellCheck={false}
                                            placeholder="Enter a unique key - e.g. new-landing-page, betaFeature, ab_test_1"
                                        />
                                    )}
                                </LemonField>

                                <LemonField name="name" label="Description">
                                    <LemonTextArea
                                        className="ph-ignore-input"
                                        data-attr="feature-flag-description"
                                        placeholder="(Optional) A description of the feature flag for your reference."
                                    />
                                </LemonField>

                                <LemonDivider />

                                <LemonField name="active">
                                    {({ value, onChange }) => {
                                        return (
                                            <LemonSwitch
                                                checked={value}
                                                onChange={onChange}
                                                disabledReason={
                                                    requiresApprovalToEnable
                                                        ? 'Enabling feature flags requires approval. Create the flag first, then enable it.'
                                                        : undefined
                                                }
                                                label={
                                                    <span className="flex items-center gap-1">
                                                        <span>Enabled</span>
                                                        <Tooltip title="When disabled, all SDKs return false without checking release conditions.">
                                                            <IconInfo className="text-secondary text-base" />
                                                        </Tooltip>
                                                    </span>
                                                }
                                                bordered
                                                fullWidth
                                                data-attr="feature-flag-enabled"
                                            />
                                        )
                                    }}
                                </LemonField>

                                {isNewFeatureFlag && alsoCreateInProjectOptions.length > 0 && (
                                    <>
                                        <LemonDivider />
                                        <LemonField.Pure
                                            label="Also create in these projects"
                                            info="The flag is created in the current project, then copied to each selected project. If a project already has a flag with this key, that flag is overwritten. If a project requires approval for flag changes, a change request is created there instead."
                                            showOptional
                                        >
                                            <LemonInputSelect<number>
                                                mode="multiple"
                                                value={alsoCreateInProjects}
                                                onChange={setAlsoCreateInProjects}
                                                options={alsoCreateInProjectOptions}
                                                limit={BULK_COPY_MAX_TARGET_PROJECTS}
                                                placeholder="Select projects"
                                                data-attr="feature-flag-also-create-in-projects"
                                            />
                                        </LemonField.Pure>
                                        {alsoCreateInProjects.length > 0 &&
                                            hasStaticCohortDependency(featureFlag, allCohorts.results) && (
                                                <LemonBanner
                                                    type="warning"
                                                    data-attr="feature-flag-also-create-in-projects-static-cohort-warning"
                                                >
                                                    This flag targets a static cohort. Projects that don't have a cohort
                                                    with the same name get an empty copy of it, so that condition
                                                    matches nobody there until you add people to it.
                                                </LemonBanner>
                                            )}
                                    </>
                                )}
                            </div>

                            {/* Advanced options - collapsed by default. Controlled rather than seeded,
                                because a failed save has to open the panel to show a tag error inside it. */}
                            <LemonCollapse
                                className="bg-bg-light"
                                activeKey={advancedPanelOpen ? 'advanced' : null}
                                onChange={(key) => setAdvancedExpanded(key === 'advanced')}
                                panels={[
                                    {
                                        key: 'advanced',
                                        header: {
                                            children: (
                                                <div className="py-1">
                                                    <div className="font-semibold">Advanced options</div>
                                                    <div className="text-secondary text-sm font-normal">
                                                        Tags,{hasEvaluationContexts ? ' evaluation contexts,' : ''}{' '}
                                                        runtime settings, and persistence.
                                                    </div>
                                                </div>
                                            ),
                                        },
                                        content: (
                                            <div className="flex flex-col gap-4">
                                                {/* Tags and evaluation contexts */}
                                                <div className="flex flex-col gap-2">
                                                    {!hasEvaluationContexts && (
                                                        <label className="text-sm font-medium flex items-center gap-1">
                                                            Tags
                                                            <Tooltip title="Organize and filter your flags.">
                                                                <IconInfo className="text-secondary text-base" />
                                                            </Tooltip>
                                                        </label>
                                                    )}
                                                    {hasEvaluationContexts ? (
                                                        <LemonField name="tags">
                                                            {({ value: formTags, onChange: onChangeTags }) => (
                                                                <LemonField name="evaluation_contexts">
                                                                    {({
                                                                        value: formEvalContexts,
                                                                        onChange: onChangeEvalContexts,
                                                                    }) => (
                                                                        <FeatureFlagEvaluationContexts
                                                                            tags={formTags}
                                                                            evaluationContexts={formEvalContexts || []}
                                                                            context="form"
                                                                            onChange={(
                                                                                updatedTags,
                                                                                updatedEvaluationContexts
                                                                            ) => {
                                                                                onChangeTags(updatedTags)
                                                                                onChangeEvalContexts(
                                                                                    updatedEvaluationContexts
                                                                                )
                                                                            }}
                                                                            tagsAvailable={availableTags.filter(
                                                                                (tag: string) =>
                                                                                    !formTags?.includes(tag)
                                                                            )}
                                                                        />
                                                                    )}
                                                                </LemonField>
                                                            )}
                                                        </LemonField>
                                                    ) : (
                                                        <LemonField name="tags">
                                                            {({ value: formTags, onChange: onChangeTags }) => (
                                                                <ObjectTags
                                                                    tags={formTags}
                                                                    onChange={onChangeTags}
                                                                    saving={false}
                                                                    tagsAvailable={availableTags.filter(
                                                                        (tag: string) => !formTags?.includes(tag)
                                                                    )}
                                                                />
                                                            )}
                                                        </LemonField>
                                                    )}
                                                </div>

                                                <LemonDivider className="my-1" />

                                                {/* Evaluation runtime */}
                                                <LemonField
                                                    name="evaluation_runtime"
                                                    label="Evaluation runtime"
                                                    labelClassName="text-sm font-medium"
                                                    info={
                                                        <>
                                                            Control whether this flag evaluates on client, server, or
                                                            both.{' '}
                                                            <Link
                                                                to="https://posthog.com/docs/feature-flags/creating-feature-flags#step-5-configure-evaluation-runtime-and-environments-optional"
                                                                target="_blank"
                                                            >
                                                                Learn more
                                                            </Link>
                                                        </>
                                                    }
                                                >
                                                    <LemonSelect
                                                        fullWidth
                                                        options={[
                                                            {
                                                                label: (
                                                                    <div className="flex flex-col">
                                                                        <span className="font-medium">
                                                                            Both client and server
                                                                        </span>
                                                                        <span className="text-xs text-muted">
                                                                            Single-user apps + multi-user systems
                                                                        </span>
                                                                    </div>
                                                                ),
                                                                value: FeatureFlagEvaluationRuntime.ALL,
                                                                icon: <IconGlobe />,
                                                            },
                                                            {
                                                                label: (
                                                                    <div className="flex flex-col">
                                                                        <span className="font-medium">
                                                                            Client-side only
                                                                        </span>
                                                                        <span className="text-xs text-muted">
                                                                            Single-user apps (mobile, desktop, embedded)
                                                                        </span>
                                                                    </div>
                                                                ),
                                                                value: FeatureFlagEvaluationRuntime.CLIENT,
                                                                icon: <IconList />,
                                                            },
                                                            {
                                                                label: (
                                                                    <div className="flex flex-col">
                                                                        <span className="font-medium">
                                                                            Server-side only
                                                                        </span>
                                                                        <span className="text-xs text-muted">
                                                                            Multi-user systems in trusted environments
                                                                        </span>
                                                                    </div>
                                                                ),
                                                                value: FeatureFlagEvaluationRuntime.SERVER,
                                                                icon: <IconServer />,
                                                            },
                                                        ]}
                                                        data-attr="feature-flag-evaluation-runtime"
                                                    />
                                                </LemonField>

                                                {/* Persistence - hide when device ID bucketing is selected */}
                                                {featureFlag.bucketing_identifier !==
                                                    FeatureFlagBucketingIdentifier.DEVICE_ID && (
                                                    <>
                                                        <LemonDivider className="my-1" />

                                                        <LemonField
                                                            name="ensure_experience_continuity"
                                                            label="Persistence"
                                                            labelClassName="text-sm font-medium"
                                                            info={
                                                                <>
                                                                    Keep flag values consistent before and after login.
                                                                    Requires anonymous user profiles.{' '}
                                                                    <Link
                                                                        to="https://posthog.com/docs/feature-flags/creating-feature-flags#persisting-feature-flags-across-authentication-steps"
                                                                        target="_blank"
                                                                    >
                                                                        Learn more
                                                                    </Link>
                                                                </>
                                                            }
                                                        >
                                                            {({ value, onChange }) => (
                                                                <LemonSwitch
                                                                    checked={value}
                                                                    onChange={onChange}
                                                                    bordered
                                                                    fullWidth
                                                                    label="Persist flag across authentication steps"
                                                                    data-attr="feature-flag-persist-across-auth"
                                                                />
                                                            )}
                                                        </LemonField>
                                                    </>
                                                )}
                                            </div>
                                        ),
                                    },
                                ]}
                            />
                        </div>

                        {/* Right column */}
                        <div className="flex-2 flex flex-col gap-4" style={{ minWidth: '30rem' }}>
                            {/* Flag type cards */}
                            <div className="rounded border p-3 bg-bg-light gap-4 flex flex-col">
                                <div className="flex flex-col gap-2">
                                    <LemonLabel info="Changing type may remove existing variants or payloads.">
                                        Flag type
                                    </LemonLabel>
                                    <div
                                        className="grid grid-cols-1 md:grid-cols-3 gap-3"
                                        role="radiogroup"
                                        aria-label="Flag type"
                                        data-attr="feature-flag-type"
                                    >
                                        {FLAG_TYPE_OPTIONS.map((option) => {
                                            const isSelected = currentFlagType === option.value
                                            return (
                                                <div
                                                    key={option.value}
                                                    role="radio"
                                                    aria-checked={isSelected}
                                                    tabIndex={0}
                                                    className={`rounded p-3 cursor-pointer transition-colors ${
                                                        isSelected
                                                            ? 'bg-accent-highlight-light border-2 border-accent'
                                                            : 'border bg-surface-primary border-primary hover:bg-fill-button-tertiary-hover'
                                                    }`}
                                                    onClick={() => onSelectFlagType(option.value)}
                                                    onKeyDown={(e) => {
                                                        if (e.key === 'Enter' || e.key === ' ') {
                                                            e.preventDefault()
                                                            onSelectFlagType(option.value)
                                                        }
                                                    }}
                                                    data-attr={`feature-flag-type-${option.value}`}
                                                >
                                                    <div className="flex flex-col gap-1">
                                                        <div className="flex items-center gap-2">
                                                            {option.icon}
                                                            <span className="font-medium flex-1">{option.label}</span>
                                                            {isSelected && (
                                                                <IconCheckCircle className="text-accent text-base" />
                                                            )}
                                                        </div>
                                                        <span className="text-xs text-muted">{option.description}</span>
                                                    </div>
                                                </div>
                                            )
                                        })}
                                    </div>
                                    <div className="text-secondary text-xs mt-1">
                                        {featureFlag.is_remote_configuration ? (
                                            <>
                                                Returns a JSON payload directly, without feature flag evaluation logic.
                                                Access it via <code className="text-xs">getFeatureFlagPayload</code>.
                                            </>
                                        ) : multivariateEnabled ? (
                                            <>
                                                When release conditions match, returns one of the variant keys (string)
                                                based on rollout percentages. Each variant can optionally include a JSON
                                                payload. Access the variant via{' '}
                                                <code className="text-xs">getFeatureFlag</code> and its payload via{' '}
                                                <code className="text-xs">getFeatureFlagPayload</code>.
                                            </>
                                        ) : (
                                            <>
                                                Returns <code className="text-xs">true</code> or{' '}
                                                <code className="text-xs">false</code> based on targeting rules. You can
                                                optionally attach a JSON payload that will be available on the flag when
                                                it evaluates to <code className="text-xs">true</code>.
                                            </>
                                        )}
                                    </div>
                                </div>

                                {/* Variants section - only for multivariate */}
                                {multivariateEnabled && (
                                    <div className="flex flex-col gap-2">
                                        <div className="flex items-center justify-between">
                                            <LemonLabel>Variants</LemonLabel>
                                            <div className="flex gap-1">
                                                {!allExpanded && variants.length > 1 && (
                                                    <LemonButton
                                                        size="small"
                                                        icon={<IconExpand />}
                                                        onClick={() => setOpenVariants(allVariantKeys)}
                                                        tooltip="Expand all variants"
                                                    >
                                                        Expand all
                                                    </LemonButton>
                                                )}
                                                {anyExpanded && (
                                                    <LemonButton
                                                        size="small"
                                                        icon={<IconCollapse />}
                                                        onClick={() => setOpenVariants([])}
                                                        tooltip="Collapse all variants"
                                                    >
                                                        Collapse all
                                                    </LemonButton>
                                                )}
                                                <LemonButton
                                                    size="small"
                                                    icon={<IconBalance />}
                                                    onClick={distributeVariantsEqually}
                                                    tooltip="Distribute rollout percentages equally"
                                                />
                                            </div>
                                        </div>

                                        {rolloutSumError && (
                                            <span className="Field--error text-danger text-xs">{rolloutSumError}</span>
                                        )}

                                        <DndContext
                                            sensors={sensors}
                                            onDragStart={handleDragStart}
                                            onDragEnd={handleDragEnd}
                                        >
                                            <SortableContext
                                                items={variants.map((_, index) => `variant-${index}`)}
                                                strategy={verticalListSortingStrategy}
                                            >
                                                <LemonCollapse
                                                    multiple
                                                    activeKeys={openVariants}
                                                    onChange={setOpenVariants}
                                                    className="mb-3 [&_.LemonCollapsePanel:not(:last-child)]:border-b [&_.LemonCollapsePanel:not(:last-child)]:border-border-secondary"
                                                    panels={variants.map((variant, index) => ({
                                                        key: `variant-${index}`,
                                                        className: '!pl-[2.5rem] dark:bg-surface-secondary',
                                                        header: (
                                                            <SortableVariantHeader
                                                                variant={variant}
                                                                index={index}
                                                                variants={variants}
                                                                alphabet={alphabet}
                                                                moveVariantUp={moveVariantUp}
                                                                moveVariantDown={moveVariantDown}
                                                            />
                                                        ),
                                                        content: (
                                                            <div className="flex flex-col gap-2">
                                                                <LemonLabel>Variant key</LemonLabel>
                                                                <LemonInput
                                                                    placeholder="Enter a variant key - e.g. control, test, variant_1"
                                                                    value={variant.key}
                                                                    onChange={(value) =>
                                                                        updateVariant(index, 'key', value)
                                                                    }
                                                                    status={
                                                                        variantErrors[index]?.key ? 'danger' : undefined
                                                                    }
                                                                    data-attr={`feature-flag-variant-key-${index}`}
                                                                />
                                                                {variantErrors[index]?.key && (
                                                                    <span className="Field--error text-danger text-xs">
                                                                        {variantErrors[index].key}
                                                                    </span>
                                                                )}

                                                                <LemonLabel>Rollout percentage</LemonLabel>
                                                                <LemonField.Pure error={!!rolloutSumError}>
                                                                    <PercentageInput
                                                                        value={variant.rollout_percentage}
                                                                        onChange={(value) =>
                                                                            updateVariant(
                                                                                index,
                                                                                'rollout_percentage',
                                                                                value
                                                                            )
                                                                        }
                                                                        data-attr={`feature-flag-variant-rollout-${index}`}
                                                                    />
                                                                </LemonField.Pure>

                                                                <LemonLabel>Description</LemonLabel>
                                                                <LemonTextArea
                                                                    placeholder="Enter an optional description for the variant"
                                                                    value={variant.name || ''}
                                                                    onChange={(value) =>
                                                                        updateVariant(index, 'name', value)
                                                                    }
                                                                    data-attr={`feature-flag-variant-description-${index}`}
                                                                />

                                                                <LemonLabel info="Optionally return JSON data when this variant matches.">
                                                                    Payload
                                                                </LemonLabel>
                                                                <JSONEditorInput
                                                                    onChange={(value) =>
                                                                        updateVariantPayload(index, value)
                                                                    }
                                                                    value={featureFlag.filters?.payloads?.[index]}
                                                                    placeholder='{"key": "value"}'
                                                                />

                                                                {variants.length > 1 && <LemonDivider />}
                                                                {variants.length > 1 && (
                                                                    <LemonButton
                                                                        type="secondary"
                                                                        status="danger"
                                                                        size="small"
                                                                        icon={<IconTrash />}
                                                                        onClick={() => {
                                                                            const variantKey =
                                                                                variant.key || `Variant ${index + 1}`
                                                                            const hasPayload =
                                                                                !!featureFlag.filters?.payloads?.[index]
                                                                            LemonDialog.open({
                                                                                title: `Remove variant "${variantKey}"?`,
                                                                                description: hasPayload
                                                                                    ? 'This variant has a payload configured. Both the variant and its payload will be deleted.'
                                                                                    : 'This action cannot be undone.',
                                                                                primaryButton: {
                                                                                    children: 'Remove variant',
                                                                                    status: 'danger',
                                                                                    onClick: () => removeVariant(index),
                                                                                },
                                                                                secondaryButton: {
                                                                                    children: 'Cancel',
                                                                                },
                                                                            })
                                                                        }}
                                                                    >
                                                                        Remove variant
                                                                    </LemonButton>
                                                                )}
                                                            </div>
                                                        ),
                                                    }))}
                                                />
                                            </SortableContext>
                                            <DragOverlay>
                                                {activeId ? (
                                                    <div className="bg-bg-light border rounded p-3 shadow-lg opacity-95">
                                                        <div className="flex gap-2 items-center">
                                                            <Lettermark
                                                                name={alphabet[activeVariantIndex] ?? '?'}
                                                                color={LettermarkColor.Gray}
                                                                size="small"
                                                            />
                                                            <span className="text-sm font-medium">
                                                                {getActiveVariant()?.key || 'Variant'}
                                                            </span>
                                                            <span className="text-xs text-muted tabular-nums">
                                                                ({getActiveVariant()?.rollout_percentage || 0}%)
                                                            </span>
                                                        </div>
                                                    </div>
                                                ) : null}
                                            </DragOverlay>
                                        </DndContext>

                                        <div>
                                            <LemonButton
                                                type="secondary"
                                                icon={<IconPlus />}
                                                onClick={addVariant}
                                                data-attr="feature-flag-add-variant"
                                            >
                                                Add variant
                                            </LemonButton>
                                        </div>
                                    </div>
                                )}

                                {/* Payload section - for boolean and remote config flags */}
                                {!multivariateEnabled && featureFlag.is_remote_configuration && (
                                    <div className="flex flex-col gap-2">
                                        <LemonLabel info="JSON data returned by this remote config.">
                                            Payload
                                        </LemonLabel>
                                        <div className="text-secondary text-xs mb-1">
                                            Remote config flags always return the payload. Access it via{' '}
                                            <code className="text-xs">
                                                {featureFlag.has_encrypted_payloads
                                                    ? 'getRemoteConfigPayload'
                                                    : 'getFeatureFlagPayload'}
                                            </code>
                                            . Using standard SDK methods such as{' '}
                                            <code className="text-xs">getFeatureFlag</code> or{' '}
                                            <code className="text-xs">isFeatureEnabled</code> will always return{' '}
                                            <code className="text-xs">true</code>.
                                        </div>
                                        <LemonField name="has_encrypted_payloads">
                                            {({ value, onChange }) => (
                                                <LemonCheckbox
                                                    id="flag-payload-encrypted-checkbox"
                                                    label="Encrypt remote configuration payload"
                                                    onChange={() => onChange(!value)}
                                                    checked={value}
                                                    data-attr="feature-flag-payload-encrypted-checkbox"
                                                    disabledReason={
                                                        hasEncryptedPayloadBeenSaved &&
                                                        'An encrypted payload has already been saved for this flag. Reset the payload or create a new flag to create an unencrypted configuration payload.'
                                                    }
                                                />
                                            )}
                                        </LemonField>
                                        <div className="flex gap-2 min-w-0">
                                            <Group name={['filters', 'payloads']}>
                                                <LemonField name="true" className="grow min-w-0">
                                                    <JSONEditorInput
                                                        readOnly={
                                                            featureFlag.has_encrypted_payloads &&
                                                            Boolean(featureFlag.filters?.payloads?.['true'])
                                                        }
                                                        placeholder='Examples: "A string", 2500, {"key": "value"}'
                                                    />
                                                </LemonField>
                                            </Group>
                                            {featureFlag.has_encrypted_payloads && (
                                                <LemonButton
                                                    className="shrink-0"
                                                    icon={<IconTrash />}
                                                    type="secondary"
                                                    size="small"
                                                    status="danger"
                                                    onClick={confirmEncryptedPayloadReset}
                                                >
                                                    Reset
                                                </LemonButton>
                                            )}
                                        </div>
                                    </div>
                                )}
                                {!multivariateEnabled && !featureFlag.is_remote_configuration && (
                                    <LemonCollapse
                                        activeKeys={payloadExpanded ? ['payload'] : []}
                                        onChange={(keys) => setPayloadExpanded(keys?.includes('payload') ?? false)}
                                        panels={[
                                            {
                                                key: 'payload',
                                                header: 'Payload',
                                                content: (
                                                    <div className="flex flex-col gap-2">
                                                        <div className="text-secondary text-xs">
                                                            When the flag evaluates to{' '}
                                                            <code className="text-xs">true</code>, this payload will be
                                                            available via{' '}
                                                            <code className="text-xs">getFeatureFlagPayload</code>.{' '}
                                                            <Link
                                                                to="https://posthog.com/docs/feature-flags/creating-feature-flags#payloads"
                                                                target="_blank"
                                                            >
                                                                Learn more
                                                            </Link>
                                                        </div>
                                                        <Group name={['filters', 'payloads']}>
                                                            <LemonField name="true">
                                                                <JSONEditorInput placeholder='Examples: "A string", 2500, {"key": "value"}' />
                                                            </LemonField>
                                                        </Group>
                                                    </div>
                                                ),
                                            },
                                        ]}
                                    />
                                )}
                            </div>

                            {/* Release conditions card - skip for remote config */}
                            {!featureFlag.is_remote_configuration && (
                                <div className="rounded border p-3 bg-bg-light flex flex-col gap-2">
                                    {lockedByExperimentId !== null && (
                                        <LemonBanner type="info">
                                            Release conditions are managed by the running experiment.{' '}
                                            <Link
                                                to={urls.experiment(lockedByExperimentId, null, { tab: 'variants' })}
                                                data-attr="feature-flag-form-experiment-release-conditions-link"
                                            >
                                                Edit them in the experiment
                                            </Link>
                                        </LemonBanner>
                                    )}
                                    <FeatureFlagReleaseConditionsCollapsible
                                        id={String(props.id)}
                                        flagId={props.id}
                                        filters={featureFlag.filters}
                                        onChange={setFeatureFlagFilters}
                                        readOnly={lockedByExperimentId !== null}
                                        variants={nonEmptyVariants}
                                        isDisabled={!featureFlag.active}
                                        bucketingIdentifier={featureFlag.bucketing_identifier}
                                        hasEarlyAccessFeatures={hasEarlyAccessFeatures}
                                        onBucketingIdentifierChange={(value: FeatureFlagBucketingIdentifier | null) => {
                                            // Always go through setFeatureFlag so this caller and
                                            // FeatureFlagReleaseConditions use the same shape — listeners on
                                            // setBucketingIdentifier (variant reset, telemetry, autosave) won't
                                            // silently fire on one path and not the other. Switching to device
                                            // bucketing also disables persist across auth, since the two are
                                            // incompatible.
                                            const ensureContinuity =
                                                value === FeatureFlagBucketingIdentifier.DEVICE_ID
                                                    ? false
                                                    : featureFlag.ensure_experience_continuity
                                            setFeatureFlag({
                                                ...featureFlag,
                                                bucketing_identifier: value,
                                                ensure_experience_continuity: ensureContinuity,
                                            })
                                        }}
                                        evaluationRuntime={featureFlag.evaluation_runtime}
                                    />
                                </div>
                            )}

                            {/* Implementation section */}
                            {showImplementation ? (
                                <div
                                    ref={implementationRef}
                                    className="rounded border p-3 bg-bg-light gap-2 flex flex-col mb-4"
                                >
                                    <LemonButton
                                        className="-m-2"
                                        icon={<IconCode />}
                                        onClick={() => setShowImplementation(false)}
                                    >
                                        Implementation
                                    </LemonButton>
                                    <LemonDivider />
                                    <FeatureFlagCodeExample featureFlag={featureFlag} />
                                </div>
                            ) : (
                                <div className="rounded border bg-bg-light gap-2 flex flex-col p-3 mb-4">
                                    <LemonButton
                                        className="-m-2"
                                        icon={<IconCode />}
                                        onClick={handleShowImplementation}
                                    >
                                        Show implementation
                                    </LemonButton>
                                </div>
                            )}
                        </div>
                    </div>
                </SceneContent>
            </Form>
        </>
    )
}