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.

feat(flags): prefill key and variants on the new flag page from the url (#129474)

Patricio1223811ff2a1
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index a380ce562f4c..e2f0fba8f14b 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1753,6 +1753,8 @@ export const productUrls = {
intent,
format,
properties,
+ key,
+ variants,
}: {
type?: 'boolean' | 'multivariate' | 'remote_config'
sourceId?: number | string | null
@@ -1760,6 +1762,8 @@ export const productUrls = {
intent?: 'local-eval' | 'first-page-load'
format?: 'rules_v2'
properties?: AnyPropertyFilter[]
+ key?: string
+ variants?: string[]
}): string => {
const params = new URLSearchParams()
if (type) {
@@ -1780,6 +1784,12 @@ export const productUrls = {
if (properties?.length) {
params.set('properties', JSON.stringify(properties))
}
+ if (key) {
+ params.set('key', key)
+ }
+ if (variants?.length) {
+ params.set('variants', variants.join(','))
+ }
return `/feature-flags/new?${params.toString()}`
},
game368hedgehogs: (): string => `/games/368hedgehogs`,
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
index 2d3f2a230407..d516d56e4f03 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
@@ -5824,6 +5824,113 @@ describe('a flag in config version 2', () => {
])
newLogic.unmount()
})
+
+ it.each([
+ [
+ 'splits prefilled variants evenly',
+ urls.featureFlagNew({
+ key: 'checkout-layout',
+ type: 'multivariate',
+ variants: ['control', 'compact', 'wide'],
+ }),
+ 'checkout-layout',
+ [
+ { key: 'control', name: '', rollout_percentage: 34 },
+ { key: 'compact', name: '', rollout_percentage: 33 },
+ { key: 'wide', name: '', rollout_percentage: 33 },
+ ],
+ ],
+ [
+ 'trims and dedupes hand-written variants',
+ '/feature-flags/new?type=multivariate&variants=control,%20wide,control',
+ '',
+ [
+ { key: 'control', name: '', rollout_percentage: 50 },
+ { key: 'wide', name: '', rollout_percentage: 50 },
+ ],
+ ],
+ [
+ 'keeps only as many variants as a flag allows',
+ urls.featureFlagNew({
+ key: 'checkout-layout',
+ type: 'multivariate',
+ variants: Array.from({ length: 25 }, (_, i) => `v${i}`),
+ }),
+ 'checkout-layout',
+ Array.from({ length: 20 }, (_, i) => ({ key: `v${i}`, name: '', rollout_percentage: 5 })),
+ ],
+ [
+ 'ignores a key and variants the router decodes into objects',
+ '/feature-flags/new?type=multivariate&key={"toString":null}&variants=[{"toString":null},"wide"]',
+ '',
+ [{ key: 'wide', name: '', rollout_percentage: 100 }],
+ ],
+ [
+ 'keeps the default variants without a variants param',
+ urls.featureFlagNew({ key: 'checkout-layout', type: 'multivariate' }),
+ 'checkout-layout',
+ [
+ { key: 'control', name: '', rollout_percentage: 50 },
+ { key: 'test', name: '', rollout_percentage: 50 },
+ ],
+ ],
+ [
+ 'ignores variants on a boolean flag',
+ urls.featureFlagNew({ key: 'checkout-layout', variants: ['control', 'compact'] }),
+ 'checkout-layout',
+ null,
+ ],
+ [
+ 'drops a key and variants that fail validation',
+ urls.featureFlagNew({
+ key: "x' + (globalThis.injected = true) + '",
+ type: 'multivariate',
+ variants: ['control', "a'b"],
+ }),
+ '',
+ [{ key: 'control', name: '', rollout_percentage: 100 }],
+ ],
+ ])('prefills from the link and %s', async (_label, link, expectedKey, expectedVariants) => {
+ defaultReleaseConditionsLogic.actions.loadDefaultReleaseConditionsSuccess({
+ enabled: false,
+ default_groups: [],
+ })
+ router.actions.push(link)
+ const newLogic = featureFlagLogic({ id: 'new' })
+ newLogic.mount()
+ await expectLogic(newLogic).toFinishAllListeners()
+
+ expect(newLogic.values.featureFlag.key).toBe(expectedKey)
+ expect(newLogic.values.featureFlag.filters.multivariate?.variants ?? null).toEqual(expectedVariants)
+ newLogic.unmount()
+ })
+
+ it('warns on load when the prefilled key is already taken', async () => {
+ defaultReleaseConditionsLogic.actions.loadDefaultReleaseConditionsSuccess({
+ enabled: false,
+ default_groups: [],
+ })
+ useMocks({
+ get: {
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/`]: () => [
+ 200,
+ { results: [{ ...NEW_FLAG, id: 42, key: 'taken-key' }], count: 1 },
+ ],
+ },
+ })
+ router.actions.push(urls.featureFlagNew({ key: 'taken-key' }))
+ const newLogic = featureFlagLogic({ id: 'new' })
+ newLogic.mount()
+ await expectLogic(newLogic).toDispatchActions(['checkKeyConflictSuccess']).toFinishAllListeners()
+
+ expect(newLogic.values.currentKeyConflict).toEqual({
+ key: 'taken-key',
+ existingFlagId: 42,
+ existingFlagKey: 'taken-key',
+ exact: true,
+ })
+ newLogic.unmount()
+ })
})
describe('the editor a flag opens in', () => {
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index a4e45f2759ac..cf822ccb9758 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -45,6 +45,7 @@ import { capitalizeFirstLetter, humanList, slugify } from 'lib/utils/strings'
import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'
import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'
import { experimentLogic } from 'scenes/experiments/experimentLogic'
+import { percentageDistribution } from 'scenes/experiments/utils'
import {
FeatureFlagsTab,
carriedListFilterParams,
@@ -167,6 +168,7 @@ import { checkFeatureFlagConfirmation } from './featureFlagConfirmationLogic'
import type { FlagIntent } from './featureFlagIntentWarningLogic'
import { confirmFeatureFlagKeyChange } from './featureFlagKeyChangeDialog'
import { featureFlagReleaseConditionsLogic } from './featureFlagReleaseConditionsLogic'
+import { MAX_VARIANTS } from './featureFlagRulesV2Draft'
import {
ProjectSelectOption,
aggregateCopyResponse,
@@ -666,6 +668,26 @@ const EMPTY_MULTIVARIATE_OPTIONS: MultivariateFlagOptions = {
],
}
+/** The `?key=` from a new-flag link, or null when it isn't a valid key. Code examples render it before save-time validation. */
+export function prefilledFlagKey(value: unknown): string | null {
+ const key = scalarParam(value) ?? ''
+ return validateFeatureFlagKey(key) ? null : key
+}
+
+// The router JSON-decodes `[...]` and `{...}` params, and `String()` can throw on an object.
+function scalarParam(value: unknown): string | null {
+ return ['string', 'number', 'boolean'].includes(typeof value) ? String(value) : null
+}
+
+function variantsFromSearchParam(value: unknown): MultivariateFlagVariant[] {
+ const raw = Array.isArray(value) ? value.map(scalarParam) : (scalarParam(value)?.split(',') ?? [])
+ const keys = [...new Set(raw.map((key) => (key ?? '').trim()))]
+ .filter((key) => !validateFeatureFlagVariantKey(key))
+ .slice(0, MAX_VARIANTS)
+ const percentages = percentageDistribution(keys.length)
+ return keys.map((key, index) => ({ key, name: '', rollout_percentage: percentages[index] }))
+}
+
const FLAG_DEPENDENCY_TIMEOUT_MS = 2000
// Only returns true when groups are present and ALL explicitly set to 0.
@@ -3610,17 +3632,23 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
}
}
+ const prefilledKey = prefilledFlagKey(router.values.searchParams.key)
+ if (prefilledKey) {
+ baseFlagConfig = { ...baseFlagConfig, key: prefilledKey }
+ }
+
// Apply type-specific configuration
if (flagType === 'multivariate') {
+ const prefilledVariants = variantsFromSearchParam(router.values.searchParams.variants)
baseFlagConfig = {
...baseFlagConfig,
filters: {
...baseFlagConfig.filters,
multivariate: {
- variants: [
- { key: 'control', name: '', rollout_percentage: 50 },
- { key: 'test', name: '', rollout_percentage: 50 },
- ],
+ variants:
+ prefilledVariants.length > 0
+ ? prefilledVariants
+ : EMPTY_MULTIVARIATE_OPTIONS.variants,
},
},
}
@@ -4966,6 +4994,10 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
}
actions.loadRelatedInsights()
actions.loadDependentFlags()
+ // A key prefilled from the URL never goes through the key field, so check it once here.
+ if (props.id === 'new' && featureFlag?.key) {
+ actions.checkKeyConflict(featureFlag.key)
+ }
reportFlagWithDeletedCohortLoaded(featureFlag, cache)
// Experiment is now loaded inline during loadFeatureFlag, not here
diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
index eab55b57cbc3..db4d5b077816 100644
--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
@@ -507,6 +507,19 @@ describe('featureFlagRulesV2EditorLogic', () => {
expect(JSON.stringify(body)).not.toContain('seed')
})
+ it.each([
+ ['a valid key', urls.featureFlagNew({ format: 'rules_v2', key: 'checkout-layout' }), 'checkout-layout'],
+ ['an invalid key', urls.featureFlagNew({ format: 'rules_v2', key: "x' + 1 + '" }), ''],
+ ['a key the router decodes into an object', '/feature-flags/new?format=rules_v2&key={"toString":null}', ''],
+ ])('starts a new flag with %s from the link', (_label, link, expectedKey) => {
+ router.actions.push(link)
+ const logic = featureFlagRulesV2EditorLogic({ id: 'new' })
+ logic.mount()
+
+ expect(logic.values.draft.key).toBe(expectedKey)
+ expect(logic.values.hasUnsavedChanges).toBe(false)
+ })
+
it('blocks a create in a project that requires evaluation contexts, which a rules v2 create cannot set', () => {
enabledFeaturesLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.FLAG_EVALUATION_TAGS]: true })
teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, require_evaluation_contexts: true })
diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
index 8f8b07a50a4c..80dbc1de3c79 100644
--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
@@ -53,6 +53,7 @@ import { confirmFeatureFlagKeyChange } from './featureFlagKeyChangeDialog'
import {
FeatureFlagLogicProps,
featureFlagLogic,
+ prefilledFlagKey,
validateFeatureFlagKey,
variantKeyToIndexFeatureFlagPayloads,
} from './featureFlagLogic'
@@ -566,6 +567,11 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
afterMount(({ actions, values, props }) => {
if (typeof props.id === 'number') {
actions.loadDraft(rulesV2DraftFromFlag(values.featureFlag))
+ } else if (props.id === 'new') {
+ const key = prefilledFlagKey(router.values.searchParams.key)
+ if (key) {
+ actions.loadDraft({ ...NEW_RULES_V2_DRAFT, key })
+ }
}
}),
])
diff --git a/products/feature_flags/manifest.tsx b/products/feature_flags/manifest.tsx
index c3b2cd0d2d09..a3804561e493 100644
--- a/products/feature_flags/manifest.tsx
+++ b/products/feature_flags/manifest.tsx
@@ -50,6 +50,8 @@ export const manifest: ProductManifest = {
intent,
format,
properties,
+ key,
+ variants,
}: {
type?: 'boolean' | 'multivariate' | 'remote_config'
sourceId?: number | string | null
@@ -58,6 +60,9 @@ export const manifest: ProductManifest = {
format?: 'rules_v2'
/** Release condition properties for a single condition set rolled out to 100%. */
properties?: AnyPropertyFilter[]
+ key?: string
+ /** Variant keys for a multivariate flag, split evenly. Only used with `type: 'multivariate'`. */
+ variants?: string[]
}): string => {
const params = new URLSearchParams()
if (type) {
@@ -78,6 +83,12 @@ export const manifest: ProductManifest = {
if (properties?.length) {
params.set('properties', JSON.stringify(properties))
}
+ if (key) {
+ params.set('key', key)
+ }
+ if (variants?.length) {
+ params.set('variants', variants.join(','))
+ }
return `/feature-flags/new?${params.toString()}`
},
},