:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(feature-flags): warn about a taken flag key while typing (#109066)
posthog[bot]aa96af75e25a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d74899f8299f..c63684e61290 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10746,6 +10746,10 @@ snapshots:hash: v1.k794b7964.70df3db2b33bd03ae45c4aac90d5db824f0640857b9029abca867a170a5f82c5.6nQgIAyy17NzNkvmvJdJ50-JxIZRrUiXcYkx7O1ukyQscenes-app-feature-flags--new-feature-flag--light:hash: v1.k794b7964.2d50bd19b5cdb52666bd2fc43bca72664f8bdfa989925b0454ffea8ebfa6df1b.yR5fkxwq8lbgPyAAnn8POP0NNKmqxwz-GEIMvpReiyw+ scenes-app-feature-flags--new-feature-flag-key-taken--dark:+ hash: v1.k794b7964.142f62a7acbb00825bc594ba3ff919b9450295bdb0571ba2df92ab3cee0ed354.fec3OkPTHOhJcvRwXCUbpHeB5Pl5uW_pX-xyjrvSVHw+ scenes-app-feature-flags--new-feature-flag-key-taken--light:+ hash: v1.k794b7964.19e230a5fbf359402bfce84eee5334eef4128a6833c709d76a0af87dac14cd50.IacafwN4AL2T4ZMy4mUSR-yCkLZX7DjXP74M9omFqN0scenes-app-feature-flags--new-multivariate-flag-variant-key-error--dark:hash: v1.k794b7964.8dd56396d8b7ec00c72b2baa5133a5b8b29afd2645178a7bd24f8e3437c65fc1.5bXnpXPEs-oavqJakfJZkeGFXMi-Rs2VGQ81lEvV8Loscenes-app-feature-flags--new-multivariate-flag-variant-key-error--light:diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsxindex 18b53f38d1e5..8cd13dd7f059 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx@@ -180,6 +180,7 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {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@@ -210,6 +211,10 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {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 tagsconst isNewFeatureFlag = id === 'new' || id === undefinedconst requiresApprovalToEnable = isNewFeatureFlag && isApprovalRequired(ApprovalActionKey.FEATURE_FLAG_ENABLE)+ const renamedFromKey =+ !isNewFeatureFlag && originalFeatureFlag && featureFlag.key !== originalFeatureFlag.key+ ? originalFeatureFlag.key+ : nullconst implementationRef = useRef<HTMLDivElement>(null)useEffect(() => {@@ -471,17 +476,42 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {label="Flag key"info="Unique identifier used in your code."help={- !isNewFeatureFlag &&- originalFeatureFlag &&- featureFlag.key !== originalFeatureFlag.key ? (- <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('{originalFeatureFlag.key}')- </code>- ). Make sure to update all SDK calls and integrations.- </span>+ 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}>diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsxindex ca0552912ac0..8bec53968b2d 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx@@ -1,5 +1,6 @@import { Meta, StoryObj } from '@storybook/react'import { waitFor } from '@testing-library/dom'+import userEvent from '@testing-library/user-event'import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'@@ -339,6 +340,35 @@ export const NewMultivariateFlagVariantKeyError: Story = {},}+export const NewFeatureFlagKeyTaken: Story = {+ parameters: {+ pageUrl: urls.featureFlag('new'),+ testOptions: { waitForLoadersToDisappear: false },+ },+ play: async ({ canvasElement }) => {+ await waitForMountedFeatureFlagLogic()+ const keyInput = await waitFor(+ () => {+ const input = canvasElement.querySelector<HTMLInputElement>('input[data-attr="feature-flag-key"]')+ if (!input) {+ throw new Error('flag key input not yet rendered')+ }+ return input+ },+ { timeout: 5000 }+ )+ await userEvent.type(keyInput, 'session-recording-console')+ await waitFor(+ () => {+ if (!canvasElement.querySelector('[data-attr="feature-flag-key-conflict-link"]')) {+ throw new Error('key conflict message not yet visible')+ }+ },+ { timeout: 5000 }+ )+ },+}+export const NewRemoteConfigFlagPayloadError: Story = {parameters: {pageUrl: urls.featureFlag('new'),diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex d46fdad5c9b9..b8bcfd1acd10 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -880,6 +880,71 @@ describe('featureFlagLogic', () => {})})+ describe('live key conflict check', () => {+ const flagListUrl = `/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/`+ const flagList = (flags: { id: number; key: string }[]): [number, Record<string, any>] => [+ 200,+ { results: flags.map((flag) => ({ ...MOCK_FEATURE_FLAG, ...flag })), count: flags.length },+ ]++ it.each([+ [+ 'another flag uses the exact key',+ 'taken-key',+ flagList([{ id: 42, key: 'taken-key' }]),+ { existingFlagId: 42, existingFlagKey: 'taken-key', exact: true },+ ],+ [+ 'another flag uses the key with different case',+ 'taken-key',+ flagList([{ id: 42, key: 'Taken-Key' }]),+ { existingFlagId: 42, existingFlagKey: 'Taken-Key', exact: false },+ ],+ [+ 'a case-only match comes back before the exact match',+ 'taken-key',+ flagList([+ { id: 43, key: 'Taken-Key' },+ { id: 42, key: 'taken-key' },+ ]),+ { existingFlagId: 42, existingFlagKey: 'taken-key', exact: true },+ ],+ [+ 'only the flag being edited matches',+ 'taken-key',+ flagList([{ id: MOCK_FEATURE_FLAG.id, key: 'taken-key' }]),+ null,+ ],+ ['no flag matches', 'free-key', flagList([]), null],+ ['the lookup fails', 'taken-key', [500, {}] as [number, Record<string, any>], null],+ ])('when %s', async (_desc, key, response, expectedConflict) => {+ useMocks({ get: { [flagListUrl]: () => response } })++ await expectLogic(logic, () => {+ logic.actions.setFeatureFlagValue(['key'], key)+ })+ .toDispatchActions(['checkKeyConflictSuccess'])+ .toFinishAllListeners()++ expect(logic.values.currentKeyConflict).toEqual(expectedConflict && { key, ...expectedConflict })+ })++ it('hides a conflict once the key changes again', async () => {+ useMocks({ get: { [flagListUrl]: () => flagList([{ id: 42, key: 'taken-key' }]) } })+ await expectLogic(logic, () => {+ logic.actions.setFeatureFlagValue(['key'], 'taken-key')+ })+ .toDispatchActions(['checkKeyConflictSuccess'])+ .toFinishAllListeners()+ expect(logic.values.currentKeyConflict?.exact).toBe(true)++ logic.actions.setFeatureFlagValue(['key'], 'taken-key-2')+ expect(logic.values.currentKeyConflict).toBeNull()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.currentKeyConflict).toBeNull()+ })+ })+describe('saveFeatureFlag error handling', () => {it('shows the friendly permission toast on a save-time 403', async () => {useMocks({diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 91a01b7b4c3a..26480c6e05ac 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -400,6 +400,15 @@ export type VariantError = {key: string | undefined}+/** Another flag in the project that uses the key typed in the form. */+export interface FeatureFlagKeyConflict {+ key: string+ existingFlagId: number+ existingFlagKey: string+ /** False when the keys differ only by letter case. The backend rejects only exact matches. */+ exact: boolean+}+export interface DependentFlag {id: numberkey: string@@ -965,6 +974,7 @@ export interface featureFlagLogicValues {copySchedule: booleancronExpression: string | nullcronPreview: string | null+ currentKeyConflict: FeatureFlagKeyConflict | nullcustomPairDisableCron: stringcustomPairDisableCronPreview: string | nullcustomPairEnableCron: string@@ -1103,6 +1113,8 @@ export interface featureFlagLogicValues {isFeatureFlagValid: booleanisFormDirty: booleanisRecurring: boolean+ keyConflict: FeatureFlagKeyConflict | null+ keyConflictLoading: booleanmultivariateEnabled: booleannewCohort: CohortType | nullnewCohortLoading: boolean@@ -1198,6 +1210,31 @@ export interface featureFlagLogicActions {applyUrlTemplate: (templateId: string) => {templateId: string}+ checkKeyConflict: (key: string) => string+ checkKeyConflictFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ checkKeyConflictSuccess: (+ keyConflict: {+ exact: boolean+ existingFlagId: number+ existingFlagKey: string+ key: string+ } | null,+ payload?: string+ ) => {+ keyConflict: {+ exact: boolean+ existingFlagId: number+ existingFlagKey: string+ key: string+ } | null+ payload?: string+ }copyFlag: () => anycopyFlagFailure: (error: string,@@ -2198,6 +2235,10 @@ export interface featureFlagLogicMeta {projectTreeRef: (arg: number | 'link' | 'new') => ProjectTreeRefsidePanelContext: (featureFlag: FeatureFlagType) => SidePanelSceneContext | nullrecordingFilterForFlag: (featureFlag: FeatureFlagType) => Partial<RecordingUniversalFilters>+ currentKeyConflict: (+ keyConflict: FeatureFlagKeyConflict | null,+ featureFlag: FeatureFlagType+ ) => FeatureFlagKeyConflict | nullhasEarlyAccessFeatures: (featureFlag: FeatureFlagType) => booleantagsRequired: (currentTeam: TeamPublicType | TeamType | null) => booleanadvancedPanelOpen: (@@ -3751,6 +3792,33 @@ export const featureFlagLogic = kea<featureFlagLogicType>([return null},},+ keyConflict: [+ null as FeatureFlagKeyConflict | null,+ {+ checkKeyConflict: async (key: string, breakpoint) => {+ await breakpoint(300)+ const { currentProjectId, featureFlag, originalFeatureFlag } = values+ if (+ !currentProjectId ||+ validateFeatureFlagKey(key) ||+ (featureFlag.id && key === originalFeatureFlag?.key)+ ) {+ return null+ }+ // A failed lookup must not block the form. The save-time check stays as the fallback.+ const response = await featureFlagsList(String(currentProjectId), { key }).catch(() => null)+ breakpoint()+ // The list filter is case-insensitive, so it also returns keys that differ only by case.+ const others = (response?.results ?? []).filter((flag) => flag.id !== featureFlag.id)+ const match =+ others.find((flag) => flag.key === key) ??+ others.find((flag) => flag.key.toLowerCase() === key.toLowerCase())+ return match+ ? { key, existingFlagId: match.id, existingFlagKey: match.key, exact: match.key === key }+ : null+ },+ },+ ],dependentFlags: [[] as DependentFlag[],{@@ -3784,6 +3852,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},}),listeners(({ actions, values, props, sharedListeners, cache }) => ({+ setFeatureFlagValue: ({ name, value }) => {+ // The form `Field` dispatches the name as a path array (`['key']`), while direct calls pass a string.+ const field = Array.isArray(name) ? name.join('.') : name+ if (field === 'key') {+ actions.checkKeyConflict(value)+ }+ },loadCopyDependencyRequirements: async (_, breakpoint): Promise<void> => {const { copyDestinationProject, currentOrganizationId, currentProjectId, featureFlag } = values@@ -5080,6 +5155,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([return getRecordingFilterForFlagVariant(flagKey, null, featureFlag.has_enriched_analytics)},],+ currentKeyConflict: [+ (s) => [s.keyConflict, s.featureFlag],+ (keyConflict: FeatureFlagKeyConflict | null, featureFlag: FeatureFlagType): FeatureFlagKeyConflict | null =>+ keyConflict && keyConflict.key === featureFlag.key ? keyConflict : null,+ ],hasEarlyAccessFeatures: [(s) => [s.featureFlag],(featureFlag: FeatureFlagType) => {