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.

53.1 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { useEffect, useRef, useState } from 'react'

import { IconArchive, IconLock, IconPlusSmall, IconTrash } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonTag, Link, lemonToast } from '@posthog/lemon-ui'

import api from 'lib/api'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { BulkUpdateTagsButton } from 'lib/components/BulkActions/BulkUpdateTagsButton'
import { FeedbackSurveyButton } from 'lib/components/FeedbackSurveyButton/FeedbackSurveyButton'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
import { FEATURE_FLAGS } from 'lib/constants'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { createdAtColumn, createdByColumn, updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { cn } from 'lib/utils/css-classes'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
import stringWithWBR from 'lib/utils/stringWithWBR'
import { toParams } from 'lib/utils/url'
import { PendingApprovalsBanner } from 'scenes/approvals/PendingApprovalsBanner'
import { NotificationsPane } from 'scenes/hog-functions/list/NotificationsPane'
import { organizationLogic } from 'scenes/organizationLogic'
import { projectLogic } from 'scenes/projectLogic'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { QuickSurveyType } from 'scenes/surveys/quick-create/types'
import { QuickSurveyModal } from 'scenes/surveys/QuickSurveyModal'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { Noun, groupsModel } from '~/models/groupsModel'
import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import {
    AccessControlLevel,
    AccessControlResourceType,
    ActivityScope,
    AnyPropertyFilter,
    BaseMathType,
    FeatureFlagConfig,
    FeatureFlagEvaluationRuntime,
    FeatureFlagType,
} from '~/types'

import {
    cohortCanBeRestored,
    deletedCohortDisabledReason,
    deletedCohortFilters,
    restoreChecksCohorts,
} from 'products/feature_flags/frontend/deletedCohortFilters'
import { featureFlagsEmptyState } from 'products/feature_flags/frontend/emptyState/featureFlagsEmptyState'
import {
    ARCHIVE_UNAVAILABLE_DISABLED_REASON,
    RESTORE_UNAVAILABLE_DISABLED_REASON,
    UNSUPPORTED_CONFIG_DISABLED_REASON,
    canArchiveFeatureFlag,
    canRestoreFeatureFlag,
    featureFlagConfigFormat,
    featureFlagConfigFormatLabel,
    featureFlagDeleteOptions,
    isRulesV2FeatureFlagConfig,
    isV1FeatureFlagConfig,
    rulesV2CreateDisabledReason,
} from 'products/feature_flags/frontend/featureFlagConfigFormat'
import { FeatureFlagRequestUsage } from 'products/feature_flags/frontend/requestUsage/FeatureFlagRequestUsage'

import { ApprovalsPromoBanner } from './ApprovalsPromoBanner'
import { BulkCopyFlagsModal, BulkCopyToProjectsButton } from './BulkCopyFlagsModal'
import { BulkDeleteResultsModal } from './BulkDeleteResultsModal'
import { openBulkArchiveFlagsDialog, openFeatureFlagArchiveDialog } from './featureFlagArchiveDialog'
import { openFeatureFlagDeleteDialog } from './featureFlagDeleteDialog'
import { FeatureFlagFiltersSection } from './FeatureFlagFilters'
import {
    FLAGS_PER_PAGE,
    FeatureFlagsTab,
    featureFlagUrlFromList,
    featureFlagsLogic,
    flagMatchesType,
} from './featureFlagsLogic'
import { BULK_ARCHIVE_MAX_FLAGS, flagSelectionLogic } from './flagSelectionLogic'
import { OverlayForNewFeatureFlagMenu } from './NewFeatureFlagMenu'
import ProjectsGrid from './projects-grid/ProjectsGrid'
import { QuillFeatureFlagsActions } from './QuillFeatureFlagsActions'

// "Feature Flags open feedback" in project 2: https://us.posthog.com/project/2/surveys/01a08364-0b1f-0000-5d00-170b29838bc5
// Button-only: its URL condition never matches, so this button is the survey's sole entry point.
const FEATURE_FLAGS_FEEDBACK_SURVEY_ID = '01a08364-0b1f-0000-5d00-170b29838bc5'

function FlagDescription({ name }: { name: string }): JSX.Element {
    const ref = useRef<HTMLDivElement | null>(null)
    const [isTruncated, setIsTruncated] = useState(false)

    useEffect(() => {
        if (ref.current) {
            setIsTruncated(ref.current.scrollHeight > ref.current.clientHeight)
        }
    }, [name])

    return (
        <Tooltip title={isTruncated ? name : undefined} delayMs={500}>
            <div ref={ref} className="line-clamp-2 max-w-[30rem]">
                {name}
            </div>
        </Tooltip>
    )
}

// Component for rendering status cell with loading state
function FeatureFlagStatusCell({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Element {
    const flagLogic = featureFlagsLogic({})
    const { featureFlagsUpdating } = useValues(flagLogic)

    const isUpdating = featureFlag.id ? featureFlagsUpdating[featureFlag.id] : false
    const deletedCohorts = deletedCohortFilters(featureFlag.filters)
    const cohortMissing = !deletedCohorts.every(cohortCanBeRestored)

    return (
        <div className="flex flex-wrap justify-start gap-1">
            {isUpdating ? (
                <LemonTag type="muted" className="uppercase">
                    <span className="inline-flex items-center gap-1">
                        <span className="animate-spin h-3 w-3 border-2 border-current border-t-transparent rounded-full" />
                        Updating
                    </span>
                </LemonTag>
            ) : featureFlag.deleted ? (
                <Tooltip title="This flag is deleted, so it can't be evaluated. Restore it from the row menu to use it again.">
                    <span>
                        <LemonTag type="danger" className="uppercase cursor-default">
                            Deleted
                        </LemonTag>
                    </span>
                </Tooltip>
            ) : featureFlag.archived ? (
                <Tooltip title="This flag is done for good. It's hidden from the flag list by default, but linked experiments and surveys keep their data.">
                    <span>
                        <LemonTag type="muted" className="uppercase cursor-default">
                            Archived
                        </LemonTag>
                    </span>
                </Tooltip>
            ) : featureFlag.active ? (
                <LemonTag type="success" className="uppercase">
                    Enabled
                </LemonTag>
            ) : (
                <LemonTag type="default" className="uppercase">
                    Disabled
                </LemonTag>
            )}
            {deletedCohorts.length > 0 && (
                <WarningStatusTag
                    label={cohortMissing ? 'Missing cohort' : 'Deleted cohort'}
                    heading={
                        cohortMissing
                            ? 'A release condition targets a cohort that does not exist in this project'
                            : 'A release condition targets a deleted cohort'
                    }
                    detail="The flag can't evaluate that condition. Open the flag to update its release conditions."
                />
            )}
            {featureFlag.status === 'STALE' && (
                <WarningStatusTag
                    label="Stale"
                    heading="This flag is likely safe to remove"
                    detail="Not called in 30+ days or fully rolled out. Make sure to remove any references in your code before deleting it."
                />
            )}
        </div>
    )
}

function WarningStatusTag({ label, heading, detail }: { label: string; heading: string; detail: string }): JSX.Element {
    return (
        <Tooltip
            title={
                <>
                    <div className="text-sm">{heading}</div>
                    <div className="text-xs">{detail}</div>
                </>
            }
            placement="left"
        >
            <span>
                <LemonTag type="warning" className="uppercase cursor-default">
                    {label}
                </LemonTag>
            </span>
        </Tooltip>
    )
}

// Deleting a flag that an experiment uses renames its key to `<key>:deleted:<id>`. Code still calls the flag by
// its old key, so that's the key to copy.
function keyBeforeDelete(featureFlag: FeatureFlagType): string {
    const suffix = `:deleted:${featureFlag.id}`
    return featureFlag.key.endsWith(suffix) ? featureFlag.key.slice(0, -suffix.length) : featureFlag.key
}

// Component for feature flag row actions that needs to use hooks
function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Element {
    const { currentProjectId } = useValues(projectLogic)
    const flagLogic = featureFlagsLogic({})
    const { featureFlagsUpdating, filters } = useValues(flagLogic)
    const { toggleFeatureFlagActive, updateFeatureFlagArchived, loadFeatureFlags, restoreFeatureFlag } =
        useActions(flagLogic)

    const isUpdating = featureFlag.id ? featureFlagsUpdating[featureFlag.id] : false
    const [isQuickSurveyModalOpen, setIsQuickSurveyModalOpen] = useState(false)
    const configFormat = featureFlagConfigFormat(featureFlag.filters)
    const isV1Config = configFormat === 'v1'
    const deletedCohortReason = deletedCohortDisabledReason(deletedCohortFilters(featureFlag.filters))

    const tryInInsightsUrl = (featureFlag: FeatureFlagType): string => {
        const query: InsightVizNode = {
            kind: NodeKind.InsightVizNode,
            source: {
                kind: NodeKind.TrendsQuery,
                series: [
                    {
                        event: '$pageview',
                        name: '$pageview',
                        kind: NodeKind.EventsNode,
                        math: BaseMathType.UniqueUsers,
                    },
                ],
                breakdownFilter: {
                    breakdown_type: 'event',
                    breakdown: `$feature/${featureFlag.key}`,
                },
            },
        }
        return urls.insightNew({ query })
    }

    // Both menus open with these, so a deleted row's View keeps the list's filters like a live row's does.
    const viewAndCopyKeyItems = (
        <>
            {featureFlag.id && (
                <LemonButton
                    to={featureFlagUrlFromList(featureFlag.id, filters)}
                    data-attr="feature-flag-view"
                    fullWidth
                >
                    View
                </LemonButton>
            )}
            <LemonButton
                onClick={() => {
                    void copyToClipboard(keyBeforeDelete(featureFlag), 'feature flag key')
                }}
                fullWidth
            >
                Copy key
            </LemonButton>
        </>
    )

    // A deleted flag serves nobody, so the only change it takes is a restore.
    if (featureFlag.deleted) {
        return (
            <More
                overlay={
                    <>
                        {viewAndCopyKeyItems}
                        {featureFlag.id && (
                            <>
                                <LemonDivider />
                                <AccessControlAction
                                    resourceType={AccessControlResourceType.FeatureFlag}
                                    minAccessLevel={AccessControlLevel.Editor}
                                    userAccessLevel={featureFlag.user_access_level}
                                >
                                    <LemonButton
                                        data-attr={`feature-flag-${featureFlag.key}-restore`}
                                        onClick={() => featureFlag.id && restoreFeatureFlag({ id: featureFlag.id })}
                                        fullWidth
                                        loading={isUpdating}
                                        disabledReason={
                                            isUpdating
                                                ? 'Updating…'
                                                : !canRestoreFeatureFlag(featureFlag.filters)
                                                  ? RESTORE_UNAVAILABLE_DISABLED_REASON
                                                  : restoreChecksCohorts(featureFlag)
                                                    ? deletedCohortReason
                                                    : undefined
                                        }
                                    >
                                        Restore
                                    </LemonButton>
                                </AccessControlAction>
                            </>
                        )}
                    </>
                }
            />
        )
    }

    return (
        <>
            <More
                overlay={
                    <>
                        {viewAndCopyKeyItems}

                        {featureFlag.id && isV1Config && (
                            <AccessControlAction
                                resourceType={AccessControlResourceType.FeatureFlag}
                                minAccessLevel={AccessControlLevel.Editor}
                                userAccessLevel={featureFlag.user_access_level}
                            >
                                <LemonButton
                                    fullWidth
                                    disabledReason={
                                        !featureFlag.can_edit
                                            ? "You don't have permission to edit this feature flag."
                                            : null
                                    }
                                    to={featureFlagUrlFromList(featureFlag.id, filters, { edit: true })}
                                >
                                    Edit
                                </LemonButton>
                            </AccessControlAction>
                        )}

                        {isV1Config && (
                            <LemonButton
                                to={urls.featureFlagNew({ sourceId: featureFlag.id })}
                                data-attr="feature-flag-duplicate"
                                fullWidth
                            >
                                Duplicate
                            </LemonButton>
                        )}

                        <LemonButton to={tryInInsightsUrl(featureFlag)} data-attr="usage" fullWidth targetBlank>
                            Try out in Insights
                        </LemonButton>

                        <LemonButton
                            onClick={() => setIsQuickSurveyModalOpen(true)}
                            data-attr="create-survey"
                            fullWidth
                        >
                            Create survey
                        </LemonButton>

                        <LemonDivider />

                        <AccessControlAction
                            resourceType={AccessControlResourceType.FeatureFlag}
                            minAccessLevel={AccessControlLevel.Editor}
                            userAccessLevel={featureFlag.user_access_level}
                        >
                            <LemonButton
                                data-attr={`feature-flag-${featureFlag.key}-switch`}
                                onClick={() =>
                                    featureFlag.id && toggleFeatureFlagActive(featureFlag.id, !featureFlag.active)
                                }
                                id={`feature-flag-${featureFlag.id}-switch`}
                                fullWidth
                                loading={isUpdating}
                                disabledReason={
                                    isUpdating
                                        ? 'Updating…'
                                        : featureFlag.archived
                                          ? 'Unarchive this flag before enabling it.'
                                          : configFormat === 'unsupported'
                                            ? UNSUPPORTED_CONFIG_DISABLED_REASON
                                            : !featureFlag.active
                                              ? deletedCohortReason
                                              : undefined
                                }
                            >
                                {featureFlag.active ? 'Disable' : 'Enable'}
                            </LemonButton>
                        </AccessControlAction>

                        {featureFlag.id && (
                            <AccessControlAction
                                resourceType={AccessControlResourceType.FeatureFlag}
                                minAccessLevel={AccessControlLevel.Editor}
                                userAccessLevel={featureFlag.user_access_level}
                            >
                                <LemonButton
                                    data-attr={`feature-flag-${featureFlag.key}-${featureFlag.archived ? 'unarchive' : 'archive'}`}
                                    onClick={() => {
                                        if (featureFlag.archived) {
                                            featureFlag.id &&
                                                updateFeatureFlagArchived({ id: featureFlag.id, archived: false })
                                            return
                                        }
                                        openFeatureFlagArchiveDialog(featureFlag, () => {
                                            featureFlag.id &&
                                                updateFeatureFlagArchived({
                                                    id: featureFlag.id,
                                                    archived: true,
                                                    via: 'archive-dialog',
                                                })
                                        })
                                    }}
                                    fullWidth
                                    loading={isUpdating}
                                    disabledReason={
                                        isUpdating
                                            ? 'Updating…'
                                            : !canArchiveFeatureFlag(featureFlag.filters)
                                              ? ARCHIVE_UNAVAILABLE_DISABLED_REASON
                                              : featureFlag.archived
                                                ? deletedCohortReason
                                                : undefined
                                    }
                                >
                                    {featureFlag.archived ? 'Unarchive' : 'Archive'}
                                </LemonButton>
                            </AccessControlAction>
                        )}

                        {featureFlag.id && configFormat !== 'unsupported' && (
                            <AccessControlAction
                                resourceType={AccessControlResourceType.FeatureFlag}
                                minAccessLevel={AccessControlLevel.Editor}
                                userAccessLevel={featureFlag.user_access_level}
                            >
                                <LemonButton
                                    status="danger"
                                    onClick={() => {
                                        openFeatureFlagDeleteDialog(featureFlag, () => {
                                            void deleteWithUndo({
                                                endpoint: `projects/${currentProjectId}/feature_flags`,
                                                object: { id: featureFlag.id },
                                                label: featureFlag.key,
                                                ...featureFlagDeleteOptions(featureFlag, loadFeatureFlags),
                                                callback: () => loadFeatureFlags(),
                                            }).catch((e) => {
                                                lemonToast.error(`Failed to delete feature flag: ${e.detail}`)
                                            })
                                        })
                                    }}
                                    disabledReason={
                                        !featureFlag.can_edit
                                            ? "You have only 'View' access for this feature flag. To make changes, please contact the flag's creator."
                                            : null
                                    }
                                    fullWidth
                                >
                                    Delete
                                </LemonButton>
                            </AccessControlAction>
                        )}
                    </>
                }
            />
            <QuickSurveyModal
                context={{ type: QuickSurveyType.FEATURE_FLAG, flag: featureFlag }}
                info="This survey will display to all users in this feature flag, filtered by any conditions you specify below."
                isOpen={isQuickSurveyModalOpen}
                onCancel={() => setIsQuickSurveyModalOpen(false)}
            />
        </>
    )
}

export const scene: SceneExport = {
    component: FeatureFlags,
    logic: featureFlagsLogic,
    productKey: ProductKey.FEATURE_FLAGS,
    emptyState: featureFlagsEmptyState,
}

const RUNTIME_LABELS: Record<FeatureFlagEvaluationRuntime, string> = {
    [FeatureFlagEvaluationRuntime.ALL]: 'All',
    [FeatureFlagEvaluationRuntime.CLIENT]: 'Client',
    [FeatureFlagEvaluationRuntime.SERVER]: 'Server',
}

export function OverviewTab({
    flagPrefix = '',
    searchPlaceholder = 'Search for feature flags (or experiment keys)',
    nouns = ['feature flag', 'feature flags'],
}: {
    flagPrefix?: string
    searchPlaceholder?: string
    nouns?: [string, string]
}): JSX.Element {
    const { aggregationLabel } = useValues(groupsModel)

    const flagLogic = featureFlagsLogic({ flagPrefix })
    const {
        featureFlagsLoading,
        displayedFlags,
        pagination,
        filters,
        shouldShowEmptyState,
        filtersChanged,
        hasActiveFilters,
        switchingDeletedView,
    } = useValues(flagLogic)
    const { setFeatureFlagsFilters, resetFilters } = useActions(flagLogic)

    const { currentProjectId } = useValues(projectLogic)
    const { currentOrganization } = useValues(organizationLogic)
    const { paramsFromFilters } = useValues(featureFlagsLogic({}))
    const { bulkDeleteResponseLoading, bulkArchiveRunning, bulkArchiveProgress } = useValues(flagSelectionLogic)
    const { bulkDeleteFlags, bulkArchiveFlags, openBulkCopyModal } = useActions(flagSelectionLogic)

    const [matchingFlagIds, setMatchingFlagIds] = useState<readonly number[] | null>(null)
    const [matchingFlagIdsLoading, setMatchingFlagIdsLoading] = useState(false)

    const page = filters.page || 1
    const startCount = (page - 1) * FLAGS_PER_PAGE + 1
    const effectiveCount = pagination.entryCount ?? 0
    const endCount = page * FLAGS_PER_PAGE < effectiveCount ? page * FLAGS_PER_PAGE : effectiveCount
    const flagCountText = `${startCount}${endCount - startCount > 1 ? '-' + endCount : ''} of ${pluralize(effectiveCount, 'flag')}`

    const columns: LemonTableColumns<FeatureFlagType> = [
        {
            title: 'Key',
            dataIndex: 'key',
            className: 'ph-no-capture',
            sticky: true,
            width: '40%',
            sorter: (a: FeatureFlagType, b: FeatureFlagType) => (a.key || '').localeCompare(b.key || ''),
            render: function Render(_, featureFlag: FeatureFlagType) {
                return (
                    <LemonTableLink
                        to={
                            featureFlag.id
                                ? // Carry the list's filters on the flag URL, so the detail page's
                                  // breadcrumb and back arrow return to this view of the list
                                  featureFlagUrlFromList(featureFlag.id, filters)
                                : undefined
                        }
                        title={
                            <>
                                <span>{stringWithWBR(featureFlag.key, 17)}</span>
                                {!featureFlag.can_edit && (
                                    <Tooltip title="You don't have edit permissions for this feature flag.">
                                        <IconLock
                                            style={{
                                                marginLeft: 6,
                                                verticalAlign: '-0.125em',
                                                display: 'inline',
                                            }}
                                        />
                                    </Tooltip>
                                )}
                            </>
                        }
                        description={featureFlag.name ? <FlagDescription name={featureFlag.name} /> : undefined}
                    />
                )
            },
        },
        {
            title: 'Type',
            width: 120,
            render: function RenderType(_, featureFlag: FeatureFlagType) {
                if (!isV1FeatureFlagConfig(featureFlag.filters)) {
                    return (
                        <LemonTag type="highlight" className="whitespace-nowrap" data-attr="feature-flag-config-format">
                            {featureFlagConfigFormatLabel(featureFlag.filters)}
                        </LemonTag>
                    )
                }
                const labels: string[] = []
                if (flagMatchesType(featureFlag, 'remote_config')) {
                    labels.push('Remote config')
                }
                if (flagMatchesType(featureFlag, 'experiment')) {
                    labels.push('Experiment')
                }
                if (flagMatchesType(featureFlag, 'multivariant')) {
                    labels.push('Multiple variants')
                }
                if (labels.length === 0) {
                    labels.push('Boolean')
                }
                return (
                    <div className="flex flex-wrap gap-1">
                        {labels.map((label) => (
                            <LemonTag key={label} type="default" className="whitespace-nowrap">
                                {label}
                            </LemonTag>
                        ))}
                    </div>
                )
            },
        },
        {
            title: 'Tags',
            dataIndex: 'tags' as keyof FeatureFlagType,
            render: function Render(_, featureFlag: FeatureFlagType) {
                const tags = featureFlag.tags
                if (!tags || tags.length === 0) {
                    return null
                }
                return <ObjectTags tags={tags} staticOnly />
            },
        } as LemonTableColumn<FeatureFlagType, keyof FeatureFlagType | undefined>,
        createdByColumn<FeatureFlagType>() as LemonTableColumn<FeatureFlagType, keyof FeatureFlagType | undefined>,
        createdAtColumn<FeatureFlagType>() as LemonTableColumn<FeatureFlagType, keyof FeatureFlagType | undefined>,
        updatedAtColumn<FeatureFlagType>() as LemonTableColumn<FeatureFlagType, keyof FeatureFlagType | undefined>,
        {
            title: 'Release conditions',
            width: 280,
            render: function Render(_, featureFlag: FeatureFlagType) {
                const releaseText = groupFilters(featureFlag.filters, undefined, aggregationLabel)
                const variants = featureFlag.filters?.multivariate?.variants
                const isMultivariate = variants && variants.length > 0

                return (
                    <div className="max-w-[280px] space-y-1 overflow-x-auto">
                        <div className="whitespace-nowrap">
                            {typeof releaseText === 'string' && releaseText.startsWith('100% of') ? (
                                <LemonTag type="highlight">{releaseText}</LemonTag>
                            ) : (
                                releaseText
                            )}
                        </div>
                        {isMultivariate && (
                            <div className="flex gap-1">
                                {variants.map((variant) => (
                                    <span key={variant.key}>
                                        <LemonTag type="muted" size="small">
                                            {variant.key}:{' '}
                                            <span className="tabular-nums">{variant.rollout_percentage}%</span>
                                        </LemonTag>
                                    </span>
                                ))}
                            </div>
                        )}
                    </div>
                )
            },
        },
        {
            title: 'Status',
            dataIndex: 'active',
            sorter: (a: FeatureFlagType, b: FeatureFlagType) => Number(a.active) - Number(b.active),
            width: 100,
            render: function RenderActive(_, featureFlag: FeatureFlagType) {
                return <FeatureFlagStatusCell featureFlag={featureFlag} />
            },
        },
        {
            title: 'Runtime',
            dataIndex: 'evaluation_runtime' as keyof FeatureFlagType,
            width: 120,
            render: function RenderFlagRuntime(_: any, featureFlag: FeatureFlagType) {
                const runtime = featureFlag.evaluation_runtime || FeatureFlagEvaluationRuntime.ALL
                return (
                    <LemonTag type="default" className="uppercase">
                        {RUNTIME_LABELS[runtime] ?? RUNTIME_LABELS[FeatureFlagEvaluationRuntime.ALL]}
                    </LemonTag>
                )
            },
        },
        {
            width: 0,
            render: function Render(_, featureFlag: FeatureFlagType) {
                return <FeatureFlagRowActions featureFlag={featureFlag} />
            },
        },
    ]

    const countTextNode = (
        <span
            className={cn(
                'text-secondary text-sm transition-opacity whitespace-nowrap',
                filtersChanged && 'opacity-50'
            )}
            aria-busy={filtersChanged}
            aria-live="polite"
        >
            {filtersChanged ? (
                <WrappingLoadingSkeleton>{flagCountText}</WrappingLoadingSkeleton>
            ) : effectiveCount > 0 ? (
                flagCountText
            ) : null}
        </span>
    )

    const filtersSection = (
        <FeatureFlagFiltersSection
            filters={filters}
            setFeatureFlagsFilters={setFeatureFlagsFilters}
            searchPlaceholder={searchPlaceholder || ''}
            filtersConfig={{
                search: true,
                type: true,
                status: true,
                createdBy: true,
                tags: true,
                runtime: true,
            }}
            countText={countTextNode}
        />
    )

    return (
        <SceneContent>
            {!shouldShowEmptyState && <ApprovalsPromoBanner />}
            <PendingApprovalsBanner />
            <div>{filtersSection}</div>
            <BulkDeleteResultsModal />
            <BulkCopyFlagsModal />

            {/*
             * Outside the selection toolbar, which unmounts as soon as the selection is cleared.
             * The region stays mounted and only its text changes, so screen readers announce each
             * update as a mutation — a region that appears already populated is not announced.
             */}
            <div className="text-muted text-sm" role="status" aria-live="polite">
                {bulkArchiveRunning && bulkArchiveProgress
                    ? `Archiving flags… ${bulkArchiveProgress.done} of ${bulkArchiveProgress.total}`
                    : null}
            </div>

            <LemonTable
                dataSource={displayedFlags}
                columns={columns}
                rowKey="key"
                rowClassName={(record) => (!record.active ? 'opacity-60' : null)}
                defaultSorting={{
                    columnKey: 'created_at',
                    order: -1,
                }}
                noSortingCancellation
                loading={featureFlagsLoading}
                disableTableWhileLoading={false}
                pagination={pagination}
                nouns={nouns}
                data-attr="feature-flag-table"
                emptyState={
                    hasActiveFilters || filtersChanged ? (
                        <>
                            No feature flags match your filters.{' '}
                            <Link onClick={() => resetFilters()}>Clear filters</Link>
                        </>
                    ) : (
                        'No feature flags yet. Create one to get started.'
                    )
                }
                onSort={(newSorting) =>
                    setFeatureFlagsFilters({
                        order: newSorting ? `${newSorting.order === -1 ? '-' : ''}${newSorting.columnKey}` : undefined,
                        page: 1,
                    })
                }
                bulkSelection={{
                    // Deleted rows can't be selected, so a selection carried in from another view would act on hidden live flags.
                    clearSelectionKey: filters.deleted,
                    getKey: (flag: FeatureFlagType): number => flag.id ?? -1,
                    isRowSelectable: (flag: FeatureFlagType) =>
                        flag.id === null
                            ? false
                            : switchingDeletedView
                              ? { disabledReason: 'Wait for the list to finish loading.' }
                              : flag.deleted
                                ? { disabledReason: 'Restore deleted flags one at a time from the row menu.' }
                                : !isV1FeatureFlagConfig(flag.filters)
                                  ? { disabledReason: 'Bulk actions are not available for this flag yet.' }
                                  : flag.can_edit
                                    ? true
                                    : { disabledReason: "You don't have permission to edit this feature flag." },
                    rowAriaLabel: (flag: FeatureFlagType) => `Select feature flag ${flag.key}`,
                    headerAriaLabel: 'Select all feature flags on this page',
                    noun: ['flag', 'flags'],
                    renderActions: (ctx) => {
                        const totalMatchingCount = effectiveCount
                        const selectedKeysSet = new Set(ctx.selectedKeys)
                        const isAllMatchingSelected =
                            matchingFlagIds !== null &&
                            ctx.selectedCount === matchingFlagIds.length &&
                            matchingFlagIds.every((id) => selectedKeysSet.has(id))
                        const showSelectAllMatchingBanner =
                            !isAllMatchingSelected &&
                            ctx.selectedCount >= FLAGS_PER_PAGE &&
                            totalMatchingCount > ctx.selectedCount
                        return (
                            <>
                                {isAllMatchingSelected && (
                                    <span className="text-muted text-sm">
                                        All {ctx.selectedCount} matching flags selected
                                    </span>
                                )}
                                {showSelectAllMatchingBanner && (
                                    <LemonButton
                                        type="secondary"
                                        size="small"
                                        loading={matchingFlagIdsLoading}
                                        onClick={async () => {
                                            setMatchingFlagIdsLoading(true)
                                            try {
                                                const { limit, offset, ...filters } = paramsFromFilters
                                                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. featureFlagsMatchingIdsRetrieve() from 'products/feature_flags/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
                                                const response = (await api.get(
                                                    `api/projects/${currentProjectId}/feature_flags/matching_ids/?${toParams(filters)}`
                                                )) as { ids: number[]; total: number }
                                                setMatchingFlagIds(response.ids)
                                                ctx.setSelectedKeys(response.ids)
                                            } finally {
                                                setMatchingFlagIdsLoading(false)
                                            }
                                        }}
                                    >
                                        Select all {totalMatchingCount} matching flags
                                    </LemonButton>
                                )}
                                <BulkCopyToProjectsButton
                                    dataAttr="bulk-copy-flags-button"
                                    selectedCount={ctx.selectedCount}
                                    extraDisabledReason={
                                        (currentOrganization?.teams?.length ?? 0) <= 1
                                            ? 'Your organization has only one project'
                                            : undefined
                                    }
                                    onOpen={() => {
                                        if (currentProjectId) {
                                            openBulkCopyModal({
                                                sourceProjectId: currentProjectId,
                                                flagIds: [...ctx.selectedKeys],
                                            })
                                        }
                                    }}
                                />
                                <BulkUpdateTagsButton
                                    resource="feature_flags"
                                    selectedIds={ctx.selectedKeys}
                                    onSuccess={() => {
                                        ctx.clearSelection()
                                        setMatchingFlagIds(null)
                                    }}
                                />
                                {/* Nothing to archive when the list is already filtered to archived flags */}
                                {filters.archived !== 'true' && (
                                    <LemonButton
                                        type="secondary"
                                        size="small"
                                        icon={<IconArchive />}
                                        data-attr="bulk-archive-flags-button"
                                        loading={bulkArchiveRunning}
                                        disabledReason={
                                            ctx.selectedCount > BULK_ARCHIVE_MAX_FLAGS
                                                ? `Archiving supports up to ${BULK_ARCHIVE_MAX_FLAGS} flags at once`
                                                : undefined
                                        }
                                        onClick={() => {
                                            openBulkArchiveFlagsDialog(ctx.selectedCount, () => {
                                                bulkArchiveFlags([...ctx.selectedKeys])
                                                ctx.clearSelection()
                                                setMatchingFlagIds(null)
                                            })
                                        }}
                                    >
                                        Archive selected
                                    </LemonButton>
                                )}
                                <LemonButton
                                    type="primary"
                                    status="danger"
                                    size="small"
                                    icon={<IconTrash />}
                                    loading={bulkDeleteResponseLoading}
                                    onClick={() => {
                                        const description = `Are you sure you want to delete ${ctx.selectedCount} feature flag${ctx.selectedCount !== 1 ? 's' : ''}? You can restore most flags from the results that open next. Flags on the newer configuration format can't be restored yet.`
                                        LemonDialog.open({
                                            title: `Delete ${ctx.selectedCount} feature flag${ctx.selectedCount !== 1 ? 's' : ''}?`,
                                            description,
                                            primaryButton: {
                                                children: 'Delete',
                                                status: 'danger',
                                                onClick: () => {
                                                    bulkDeleteFlags({
                                                        ids: [...ctx.selectedKeys],
                                                        allMatching: isAllMatchingSelected,
                                                    })
                                                    ctx.clearSelection()
                                                    setMatchingFlagIds(null)
                                                },
                                                size: 'small',
                                            },
                                            secondaryButton: {
                                                children: 'Cancel',
                                                type: 'tertiary',
                                                size: 'small',
                                            },
                                        })
                                    }}
                                >
                                    {bulkDeleteResponseLoading ? 'Deleting…' : 'Delete selected'}
                                </LemonButton>
                            </>
                        )
                    },
                }}
            />
        </SceneContent>
    )
}

function FeatureFlagNotificationsTab(): JSX.Element {
    return (
        <NotificationsPane
            subTemplateId="feature-flag-change"
            description="Get notified when feature flags are created, updated, or deleted."
            dialogTitle="New feature flag notification"
            returnTo={urls.featureFlags(FeatureFlagsTab.NOTIFICATIONS)}
        />
    )
}

export function FeatureFlags(): JSX.Element {
    const { activeTab } = useValues(featureFlagsLogic)
    const { setActiveTab } = useActions(featureFlagsLogic)
    const { featureFlags: enabledFeatureFlags } = useValues(enabledFeaturesLogic)
    const newFeatureFlagUrl = urls.featureFlagTemplates()
    const showNotificationsTab = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_NOTIFICATIONS]
    const showRequestUsageTab = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE]
    const showRulesV2Editor = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR]
    const { currentTeam } = useValues(teamLogic)
    const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')

    return (
        <SceneContent className="feature_flags">
            <SceneTitleSection
                name={sceneConfigurations[Scene.FeatureFlags].name}
                description={sceneConfigurations[Scene.FeatureFlags].description}
                resourceType={{
                    type: 'feature_flag',
                }}
                actions={
                    todayRailNav ? (
                        <QuillFeatureFlagsActions
                            feedbackSurveyId={FEATURE_FLAGS_FEEDBACK_SURVEY_ID}
                            showRulesV2Editor={showRulesV2Editor}
                            rulesV2DisabledReason={rulesV2CreateDisabledReason(currentTeam, enabledFeatureFlags)}
                            newFeatureFlagUrl={newFeatureFlagUrl}
                        />
                    ) : (
                        <>
                            <FeedbackSurveyButton
                                surveyId={FEATURE_FLAGS_FEEDBACK_SURVEY_ID}
                                data-attr="feature-flags-feedback-button"
                            />
                            {showRulesV2Editor && (
                                <AccessControlAction
                                    resourceType={AccessControlResourceType.FeatureFlag}
                                    minAccessLevel={AccessControlLevel.Editor}
                                >
                                    <LemonButton
                                        type="secondary"
                                        size="small"
                                        to={urls.featureFlagNew({ format: 'rules_v2' })}
                                        disabledReason={rulesV2CreateDisabledReason(currentTeam, enabledFeatureFlags)}
                                        data-attr="new-rules-v2-feature-flag"
                                    >
                                        New rules v2 flag
                                    </LemonButton>
                                </AccessControlAction>
                            )}
                            <AccessControlAction
                                resourceType={AccessControlResourceType.FeatureFlag}
                                minAccessLevel={AccessControlLevel.Editor}
                            >
                                <Shortcut
                                    name="NewFeatureFlag"
                                    keybind={[keyBinds.new]}
                                    intent="New feature flag"
                                    interaction="click"
                                    scope={Scene.FeatureFlags}
                                >
                                    <LemonButton
                                        type="primary"
                                        to={newFeatureFlagUrl}
                                        data-attr="new-feature-flag"
                                        size="small"
                                        icon={<IconPlusSmall />}
                                        sideAction={{
                                            dropdown: {
                                                placement: 'bottom-end',
                                                className: 'new-feature-flag-overlay',
                                                actionable: true,
                                                closeOnClickInside: false,
                                                overlay: <OverlayForNewFeatureFlagMenu />,
                                            },
                                            'data-attr': 'new-feature-flag-dropdown',
                                        }}
                                        tooltip="New feature flag"
                                    >
                                        New
                                    </LemonButton>
                                </Shortcut>
                            </AccessControlAction>
                        </>
                    )
                }
            />
            <LemonTabs
                activeKey={
                    activeTab === FeatureFlagsTab.USAGE && !showRequestUsageTab ? FeatureFlagsTab.OVERVIEW : activeTab
                }
                onChange={(newKey) => setActiveTab(newKey)}
                sceneInset
                tabs={[
                    {
                        key: FeatureFlagsTab.OVERVIEW,
                        label: 'Overview',
                        content: <OverviewTab />,
                    },
                    ...(showRequestUsageTab
                        ? [
                              {
                                  key: FeatureFlagsTab.USAGE,
                                  label: 'Request usage',
                                  content: <FeatureFlagRequestUsage />,
                              },
                          ]
                        : []),
                    {
                        key: FeatureFlagsTab.PROJECTS,
                        label: 'Projects',
                        content: <ProjectsGrid />,
                    },
                    {
                        key: FeatureFlagsTab.HISTORY,
                        label: 'History',
                        content: <ActivityLog scope={ActivityScope.FEATURE_FLAG} />,
                    },
                    ...(showNotificationsTab
                        ? [
                              {
                                  key: FeatureFlagsTab.NOTIFICATIONS,
                                  label: 'Notifications',
                                  content: <FeatureFlagNotificationsTab />,
                              },
                          ]
                        : []),
                ]}
                data-attr="feature-flags-tab-navigation"
            />
        </SceneContent>
    )
}

export function groupFilters(
    filters: FeatureFlagConfig,
    stringOnly?: true,
    aggregationLabel?: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
): string
export function groupFilters(
    filters: FeatureFlagConfig,
    stringOnly?: false,
    aggregationLabel?: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
): JSX.Element | string
export function groupFilters(
    filters: FeatureFlagConfig,
    stringOnly?: boolean,
    aggregationLabel?: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
): JSX.Element | string {
    if (!isV1FeatureFlagConfig(filters)) {
        return isRulesV2FeatureFlagConfig(filters)
            ? `${capitalizeFirstLetter(filters.return_type)} · ${pluralize(filters.rules.length, 'rule')}`
            : 'Unsupported configuration'
    }
    const aggregationTargetName =
        aggregationLabel && filters.aggregation_group_type_index != null
            ? aggregationLabel(filters.aggregation_group_type_index).plural
            : 'users'
    const groups = filters.groups || []

    if (groups.length === 0 || !groups.some((group) => group.rollout_percentage !== 0)) {
        // There are no rollout groups or all are at 0%
        return `No ${aggregationTargetName}`
    }
    if (
        groups.some((group) => !group.properties?.length && [null, undefined, 100].includes(group.rollout_percentage))
    ) {
        // There's some group without filters that has 100% rollout
        return `100% of all ${aggregationTargetName}`
    }

    if (groups.length === 1) {
        const { properties, rollout_percentage = null } = groups[0]
        if ((properties?.length || 0) > 0) {
            return stringOnly ? (
                `${rollout_percentage ?? 100}% of one group`
            ) : (
                <div className="flex items-center">
                    <span className="shrink-0 mr-2 tabular-nums">{rollout_percentage ?? 100}% of</span>
                    <PropertyFiltersDisplay filters={properties as AnyPropertyFilter[]} compact />
                </div>
            )
        } else if (rollout_percentage !== null) {
            return `${rollout_percentage}% of all ${aggregationTargetName}`
        }
        console.error('A group with full rollout was not detected early')
        return `100% of all ${aggregationTargetName}`
    }
    return 'Multiple groups'
}