: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(flags): show config version 2 flags read-only in the flag pages (#106774)
Anders0038fdd45447
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex fecea918bea9..7947292c6fe3 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10111,9 +10111,13 @@ snapshots:scenes-app-feature-flags--feature-flag-not-found--light:hash: v1.k794b7964.9760899dc54ed1457b2f2790151da4dced7ce03ba2db211fc8987584331225f7.NwLOFpddIBI2MKFCF_nA7ICbR7JCJISgydgqg4pdPWgscenes-app-feature-flags--feature-flags-list--dark:- hash: v1.k794b7964.4c1b48b0e9deb796e0872380e2c6a09169b43a80fe9cb73cf05d14d09bd45421.1gC96ce4ji6NuvBFXPNB79ctn-cV3KGjcBnnVMEd3Jc+ hash: v1.k794b7964.d89fe28a6ed950990ef3945db822482775f9b5dedc18e5b30785c26ca2c62523.Xx4-lykuSTuRLWUZkBzgAe8ZJfIRWP9QsbmVBxQjPswscenes-app-feature-flags--feature-flags-list--light:- hash: v1.k794b7964.8f58297a9f87ef35cc3957980bc76ff840b2c1b1935f3e7da7362a47dcc7271d.eFEqxrtccazmTD7Uq1cd0eXkfGFbE2hiODT0I7allug+ hash: v1.k794b7964.ad33870f5b7f4889085a6f2b6a893790607e6dbf2c250254e121e8d9b257363a.hioAjfQjRn52D7MigxTZBa0NyIewpgAv09-8nCifsNM+ scenes-app-feature-flags--feature-flags-list-with-rules-v-2-flag--dark:+ hash: v1.k794b7964.fac30975fe1422a694cff775d4a2876db4f7d50b810b6badf98dadf9afbd67c0.swyXN6EB5-pGe2FC95FLRh1JqveAl8r4DF97h56Cvtw+ scenes-app-feature-flags--feature-flags-list-with-rules-v-2-flag--light:+ hash: v1.k794b7964.c4ef2d9634c7a7a45cff940ba307c2569ee5c027dbd25695b053bcf49d86155f.gixP5nQSZti4jcI7XMlS8AI3wvGruY-qYzGg0uS5jlsscenes-app-feature-flags--new-feature-flag--dark:hash: v1.k794b7964.70df3db2b33bd03ae45c4aac90d5db824f0640857b9029abca867a170a5f82c5.6nQgIAyy17NzNkvmvJdJ50-JxIZRrUiXcYkx7O1ukyQscenes-app-feature-flags--new-feature-flag--light:@@ -10126,6 +10130,14 @@ snapshots:hash: v1.k794b7964.6851706b75cd4605afeb2e7c610e52dc7958dee609a8a2c45c9fa3bb267646b5.-85HVvXHiMTHAh0XQAaQg6f5vqXqcNfxOFWcsOvwI9wscenes-app-feature-flags--new-remote-config-flag-payload-error--light:hash: v1.k794b7964.bbbbecef36aa418ff943f76d2006e75aec34f4ed6b26c4303ad005cbc95771ce.t6SkxtqE_6K7m6nlXwksQYnWs2s91AkmcYNUBy5ao-8+ scenes-app-feature-flags--rules-v-2-feature-flag--dark:+ hash: v1.k794b7964.2e595e65c1e4494c71c07b2772015cbcaf64fb4120d32192163e26ae95ca5231.aGTUL2hQW0He1Ia68rgMjgp-KslX-HAyApsF3Uwj5YI+ scenes-app-feature-flags--rules-v-2-feature-flag--light:+ hash: v1.k794b7964.9be1f7a27ef9df90e456212676e6f3bd01f590ac47c07b6e0db76e34eccc0075.FtbgBPtQq1lleQ32jk0zd6EUz8Vdex3ciHhheCbh0i0+ scenes-app-feature-flags--rules-v-2-feature-flag-edit-deep-link--dark:+ hash: v1.k794b7964.2e595e65c1e4494c71c07b2772015cbcaf64fb4120d32192163e26ae95ca5231.fNaTKRMtH9HwMByvOc77CzVjKpmDG-1hStBUXueEMLk+ scenes-app-feature-flags--rules-v-2-feature-flag-edit-deep-link--light:+ hash: v1.k794b7964.8cbffc977bea22684cf73144ab837a5acabffac33eac687ba2c29e6858ebb3a6.OCNkBGO_Dioqet3YCVFl028n_2oOoNgl2foc1d7VzSkscenes-app-feature-flags--stale-feature-flag--dark:hash: v1.k794b7964.a5c6ecebf63f113c10df1a1b54b48141b7763f4d1f19f9223f6e445477b7d7f8.I7PbADnaKTfiWr8aPI3zmO0xG_mPSWRVi29ovh4okrsscenes-app-feature-flags--stale-feature-flag--light:diff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsxindex 706008991bf8..330e17d28c44 100644--- a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsx+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelLinkFeatureFlag.test.tsx@@ -11,6 +11,7 @@ import {FeatureFlagBucketingIdentifier,FeatureFlagEvaluationRuntime,FeatureFlagType,+ FeatureFlagWithV1Config,} from '~/types'import { VariantsPanelLinkFeatureFlag } from './VariantsPanelLinkFeatureFlag'@@ -18,7 +19,7 @@ import { VariantsPanelLinkFeatureFlag } from './VariantsPanelLinkFeatureFlag'describe('VariantsPanelLinkFeatureFlag', () => {const mockSetShowFeatureFlagSelector = jest.fn()- const baseFeatureFlag: FeatureFlagType = {+ const baseFeatureFlag: FeatureFlagWithV1Config = {id: 1,key: 'test-experiment-flag',name: 'Test Experiment Feature Flag',diff --git a/frontend/src/scenes/experiments/ExperimentView/ReleaseConditionsTable.tsx b/frontend/src/scenes/experiments/ExperimentView/ReleaseConditionsTable.tsxindex 64582a237de4..4161deacf209 100644--- a/frontend/src/scenes/experiments/ExperimentView/ReleaseConditionsTable.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ReleaseConditionsTable.tsx@@ -7,7 +7,7 @@ import { FeatureFlagLogicProps, featureFlagLogic } from 'scenes/feature-flags/feimport { FeatureFlagReleaseConditions } from 'scenes/feature-flags/FeatureFlagReleaseConditions'import { groupsModel } from '~/models/groupsModel'-import { FeatureFlagGroupType } from '~/types'+import { FeatureFlagFilters, FeatureFlagGroupType } from '~/types'import { experimentLogic } from '../experimentLogic'import { modalsLogic } from '../modalsLogic'@@ -67,7 +67,8 @@ export function ReleaseConditionsModal(): JSX.Element {<BindLogic logic={featureFlagLogic} props={{ id: experiment.feature_flag?.id ?? null }}><FeatureFlagReleaseConditionsid={`${experiment.feature_flag?.id}`}- filters={featureFlag?.filters ?? []}+ // An experiment's flag is always v1: experiments create their own flags and cannot adopt another config version.+ filters={(featureFlag?.filters as FeatureFlagFilters | undefined) ?? { groups: [] }}onChange={setFeatureFlagFilters}nonEmptyFeatureFlagVariants={nonEmptyVariants}/>diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex 63769e8316fd..2ea8ae108fc9 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -16,6 +16,7 @@ import {FeatureFlagBucketingIdentifier,FeatureFlagEvaluationRuntime,FeatureFlagType,+ FeatureFlagWithV1Config,PropertyFilterType,PropertyOperator,} from '~/types'@@ -270,7 +271,7 @@ describe('getFunnelDropoffReason', () => {})describe('checkFeatureFlagEligibility', () => {- const baseFeatureFlag: FeatureFlagType = {+ const baseFeatureFlag: FeatureFlagWithV1Config = {id: 1,key: 'test',name: 'Test',diff --git a/frontend/src/scenes/feature-flags/EditableOverviewSection.tsx b/frontend/src/scenes/feature-flags/EditableOverviewSection.tsxindex 8caacc9e330f..b02441ec3390 100644--- a/frontend/src/scenes/feature-flags/EditableOverviewSection.tsx+++ b/frontend/src/scenes/feature-flags/EditableOverviewSection.tsx@@ -7,6 +7,8 @@ import { AccessControlAction } from 'lib/components/AccessControlAction'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { isV1FeatureFlagConfig } from 'products/feature_flags/frontend/featureFlagConfigFormat'+import { featureFlagLogic } from './featureFlagLogic'interface EditableOverviewSectionProps {@@ -27,7 +29,7 @@ export function EditableOverviewSection({const { featureFlag } = useValues(featureFlagLogic)const { editFeatureFlag } = useActions(featureFlagLogic)- const canShowEditButton = !featureFlag.deleted+ const canShowEditButton = !featureFlag.deleted && isV1FeatureFlagConfig(featureFlag.filters)return (<div className={`relative rounded border p-4 bg-bg-light ${className ?? ''}`}>diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 4d8caf409618..752864afcafe 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -78,6 +78,11 @@ import {PropertyOperator,} from '~/types'+import {+ ARCHIVE_UNAVAILABLE_DISABLED_REASON,+ canArchiveFeatureFlag,+ featureFlagConfigFormatLabel,+} from 'products/feature_flags/frontend/featureFlagConfigFormat'import { FeatureFlagStaleBanner } from 'products/feature_flags/frontend/FeatureFlagStaleBanner'import { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM, useAttachedContext } from 'products/posthog_ai/frontend/api/logics'@@ -138,7 +143,9 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {featureFlagActiveUpdateLoading,featureFlagRestoreLoading,dependentFlags,+ configFormat,} = useValues(featureFlagLogic)+ const isV1Config = configFormat === 'v1'const { featureFlags } = useValues(enabledFeaturesLogic)const {deleteFeatureFlag,@@ -146,10 +153,9 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {editFeatureFlag,createStaticCohort,setSelectedTab,- updateFlag,- saveFeatureFlag,saveDescriptionInline,saveTagsInline,+ saveSidebarTags,updateFeatureFlagArchived,refreshFeatureFlagAfterAgentChange,} = useActions(featureFlagLogic)@@ -208,7 +214,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {// immediately when the scene first renders already in form mode (deep-link/new flag), but when the// user clicks Edit on the readonly view, defer one frame so the click flips state and the loading// skeleton paints before that render — otherwise the click blocks the thread and reads as dead.- const shouldShowForm = isNewFeatureFlag || isEditingFlag+ const shouldShowForm = isNewFeatureFlag || (isEditingFlag && isV1Config)const [isFormMounted, setIsFormMounted] = useState(shouldShowForm)useEffect(() => {if (!shouldShowForm) {@@ -338,26 +344,17 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {<FeatureFlagEvaluationContextstags={featureFlag.tags}evaluationContexts={featureFlag.evaluation_contexts || []}- onSave={(updatedTags, updatedEvaluationContexts) => {- const updatedFlag = {- ...featureFlag,- tags: updatedTags,- evaluation_contexts: updatedEvaluationContexts,- }- updateFlag(updatedFlag)- saveFeatureFlag(updatedFlag)- }}+ onSave={saveSidebarTags}+ evaluationContextsDisabledReason={+ isV1Config ? null : "Evaluation contexts can't be changed on this flag yet."+ }tagsAvailable={tags.filter((tag: string) => !featureFlag.tags?.includes(tag))}flagId={featureFlag.id}context="sidebar"/>) : (<SceneTags- onSave={(tags) => {- const updatedFlag = { ...featureFlag, tags }- updateFlag(updatedFlag)- saveFeatureFlag(updatedFlag)- }}+ onSave={(tags) => saveSidebarTags(tags)}canEdittags={featureFlag.tags}tagsAvailable={tags.filter((tag: string) => !featureFlag.tags?.includes(tag))}@@ -369,18 +366,20 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {</ScenePanelInfoSection><ScenePanelDivider /><ScenePanelActionsSection>- <ButtonPrimitive- onClick={() => {- router.actions.push(urls.featureFlagNew({ sourceId: featureFlag.id }))- }}- menuItem- data-attr={`${RESOURCE_TYPE}-duplicate`}- >- <IconCopy />- Duplicate- </ButtonPrimitive>+ {isV1Config && (+ <ButtonPrimitive+ onClick={() => {+ router.actions.push(urls.featureFlagNew({ sourceId: featureFlag.id }))+ }}+ menuItem+ data-attr={`${RESOURCE_TYPE}-duplicate`}+ >+ <IconCopy />+ Duplicate+ </ButtonPrimitive>+ )}<SceneAddToNotebookDropdownMenu dataAttrKey={RESOURCE_TYPE} />- {featureFlags[FEATURE_FLAGS.FEATURE_FLAG_COHORT_CREATION] && (+ {isV1Config && featureFlags[FEATURE_FLAGS.FEATURE_FLAG_COHORT_CREATION] && (<ButtonPrimitivemenuItemdata-attr={`${RESOURCE_TYPE}-create-cohort`}@@ -426,6 +425,9 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {...(disabledReason ? { [disabledReason]: true } : {}),"You have only 'View' access for this feature flag. To make changes, please contact the flag's creator.":!featureFlag.can_edit,+ [ARCHIVE_UNAVAILABLE_DISABLED_REASON]: !canArchiveFeatureFlag(+ featureFlag.filters+ ),'Updating…': featureFlagActiveUpdateLoading,}}>@@ -435,38 +437,40 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {)}</AccessControlAction>)}- <AccessControlAction- resourceType={AccessControlResourceType.FeatureFlag}- minAccessLevel={AccessControlLevel.Editor}- >- {({ disabledReason }) => (- <ButtonPrimitive- menuItem- variant="danger"- data-attr={featureFlag.deleted ? 'restore-feature-flag' : 'delete-feature-flag'}- onClick={() => {- if (featureFlag.deleted) {- restoreFeatureFlag(featureFlag)- } else {- openFeatureFlagDeleteDialog(- featureFlag,- () => deleteFeatureFlag(featureFlag),- dependentFlags- )- }- }}- disabledReasons={{- ...(disabledReason ? { [disabledReason]: true } : {}),- "You have only 'View' access for this feature flag. To make changes, please contact the flag's creator.":- !featureFlag.can_edit,- 'Restoring…': featureFlagRestoreLoading,- }}- >- {featureFlag.deleted ? <IconRewind /> : <IconTrash />}- {featureFlag.deleted ? 'Restore' : 'Delete'} feature flag- </ButtonPrimitive>- )}- </AccessControlAction>+ {isV1Config && (+ <AccessControlAction+ resourceType={AccessControlResourceType.FeatureFlag}+ minAccessLevel={AccessControlLevel.Editor}+ >+ {({ disabledReason }) => (+ <ButtonPrimitive+ menuItem+ variant="danger"+ data-attr={featureFlag.deleted ? 'restore-feature-flag' : 'delete-feature-flag'}+ onClick={() => {+ if (featureFlag.deleted) {+ restoreFeatureFlag(featureFlag)+ } else {+ openFeatureFlagDeleteDialog(+ featureFlag,+ () => deleteFeatureFlag(featureFlag),+ dependentFlags+ )+ }+ }}+ disabledReasons={{+ ...(disabledReason ? { [disabledReason]: true } : {}),+ "You have only 'View' access for this feature flag. To make changes, please contact the flag's creator.":+ !featureFlag.can_edit,+ 'Restoring…': featureFlagRestoreLoading,+ }}+ >+ {featureFlag.deleted ? <IconRewind /> : <IconTrash />}+ {featureFlag.deleted ? 'Restore' : 'Delete'} feature flag+ </ButtonPrimitive>+ )}+ </AccessControlAction>+ )}</ScenePanelActionsSection></ScenePanel><SceneContent>@@ -478,7 +482,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {<LemonBannertype="error"action={- featureFlag.can_edit+ featureFlag.can_edit && isV1Config? {children: 'Restore',onClick: () => restoreFeatureFlag(featureFlag),@@ -489,9 +493,11 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {}>This feature flag is deleted. It's hidden from the flag list and can't be evaluated.{' '}- {featureFlag.can_edit- ? 'Restore it to use it again.'- : 'Ask someone with edit access to restore it.'}+ {!isV1Config+ ? 'Restoring is not available for this flag yet.'+ : featureFlag.can_edit+ ? 'Restore it to use it again.'+ : 'Ask someone with edit access to restore it.'}</LemonBanner>)}{featureFlag.archived && (@@ -511,7 +517,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {experiments and surveys keep their data.</LemonBanner>)}- <FeatureFlagStaleBanner />+ {isV1Config && <FeatureFlagStaleBanner />}{earlyAccessFeature && earlyAccessFeature.stage === EarlyAccessFeatureStage.Concept && (<LemonBanner type="info">This feature flag is assigned to an early access feature in the{' '}@@ -538,7 +544,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {}}/>)}- {featureFlags[FEATURE_FLAGS.FEATURE_FLAG_COHORT_CREATION] && (+ {isV1Config && featureFlags[FEATURE_FLAGS.FEATURE_FLAG_COHORT_CREATION] && (<SceneMenuBarItemonClick={() => createStaticCohort()}data-attr={`${RESOURCE_TYPE}-menubar-create-cohort`}@@ -558,49 +564,55 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {</SceneMenuBarSubMenu><SceneMenuBarSeparator /><SceneMenuBarFileItems dataAttrKey={RESOURCE_TYPE} />- <SceneMenuBarSeparator />- <AccessControlAction- resourceType={AccessControlResourceType.FeatureFlag}- minAccessLevel={AccessControlLevel.Editor}- >- {({ disabledReason }) => (- <SceneMenuBarItem- variant="destructive"- disabled={!!disabledReason || featureFlagRestoreLoading}- data-attr={- featureFlag.deleted- ? `${RESOURCE_TYPE}-menubar-restore`- : `${RESOURCE_TYPE}-menubar-delete`- }- onClick={() => {- if (featureFlag.deleted) {- restoreFeatureFlag(featureFlag)- } else {- openFeatureFlagDeleteDialog(- featureFlag,- () => deleteFeatureFlag(featureFlag),- dependentFlags- )- }- }}+ {isV1Config && (+ <>+ <SceneMenuBarSeparator />+ <AccessControlAction+ resourceType={AccessControlResourceType.FeatureFlag}+ minAccessLevel={AccessControlLevel.Editor}>- {featureFlag.deleted ? <IconRewind /> : <IconTrash />}- {featureFlag.deleted ? 'Restore' : 'Delete'} feature flag- </SceneMenuBarItem>- )}- </AccessControlAction>- </SceneMenuBarMenu>- <SceneMenuBarMenu label="Edit" dataAttr={`${RESOURCE_TYPE}-menubar-edit`}>- <SceneMenuBarItem- onClick={() => {- router.actions.push(urls.featureFlagNew({ sourceId: featureFlag.id }))- }}- data-attr={`${RESOURCE_TYPE}-menubar-duplicate`}- >- <IconCopy />- Duplicate- </SceneMenuBarItem>+ {({ disabledReason }) => (+ <SceneMenuBarItem+ variant="destructive"+ disabled={!!disabledReason || featureFlagRestoreLoading}+ data-attr={+ featureFlag.deleted+ ? `${RESOURCE_TYPE}-menubar-restore`+ : `${RESOURCE_TYPE}-menubar-delete`+ }+ onClick={() => {+ if (featureFlag.deleted) {+ restoreFeatureFlag(featureFlag)+ } else {+ openFeatureFlagDeleteDialog(+ featureFlag,+ () => deleteFeatureFlag(featureFlag),+ dependentFlags+ )+ }+ }}+ >+ {featureFlag.deleted ? <IconRewind /> : <IconTrash />}+ {featureFlag.deleted ? 'Restore' : 'Delete'} feature flag+ </SceneMenuBarItem>+ )}+ </AccessControlAction>+ </>+ )}</SceneMenuBarMenu>+ {isV1Config && (+ <SceneMenuBarMenu label="Edit" dataAttr={`${RESOURCE_TYPE}-menubar-edit`}>+ <SceneMenuBarItem+ onClick={() => {+ router.actions.push(urls.featureFlagNew({ sourceId: featureFlag.id }))+ }}+ data-attr={`${RESOURCE_TYPE}-menubar-duplicate`}+ >+ <IconCopy />+ Duplicate+ </SceneMenuBarItem>+ </SceneMenuBarMenu>+ )}<SceneMenuBarPopover label="Metadata" dataAttr={`${RESOURCE_TYPE}-menubar-metadata`}><SceneTagsComboboxonSave={(updatedTags) => saveTagsInline(updatedTags)}@@ -631,22 +643,28 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {saveDescriptionInline(newName)}}actions={- <AccessControlAction- resourceType={AccessControlResourceType.FeatureFlag}- minAccessLevel={AccessControlLevel.Editor}- userAccessLevel={featureFlag.user_access_level}- >- {({ disabledReason }) => (- <LemonButton- type="secondary"- size="small"- disabledReason={disabledReason}- onClick={() => editFeatureFlag(true)}- >- Edit- </LemonButton>- )}- </AccessControlAction>+ isV1Config ? (+ <AccessControlAction+ resourceType={AccessControlResourceType.FeatureFlag}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={featureFlag.user_access_level}+ >+ {({ disabledReason }) => (+ <LemonButton+ type="secondary"+ size="small"+ disabledReason={disabledReason}+ onClick={() => editFeatureFlag(true)}+ >+ Edit+ </LemonButton>+ )}+ </AccessControlAction>+ ) : (+ <LemonTag type="highlight" data-attr="feature-flag-config-format">+ {featureFlagConfigFormatLabel(featureFlag.filters)}+ </LemonTag>+ )}/><LemonTabsdiff --git a/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.test.tsxnew file mode 100644index 000000000000..19cff61c0fa5--- /dev/null+++ b/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.test.tsx@@ -0,0 +1,58 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render } from '@testing-library/react'+import { BindLogic, Provider } from 'kea'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'+import { featureFlagLogic } from './featureFlagLogic'++describe('FeatureFlagEvaluationContexts', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team/default_evaluation_contexts/': {+ default_evaluation_contexts: [],+ available_contexts: [],+ hidden_contexts: [],+ enabled: false,+ },+ '/api/environments/:team/default_release_conditions/': { default_groups: [], enabled: false },+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ it.each([+ { disabledReason: null, opensEditor: true },+ { disabledReason: "Evaluation contexts can't be changed on this flag yet.", opensEditor: false },+ ])(+ 'opens the contexts editor only without a disabled reason: $disabledReason',+ ({ disabledReason, opensEditor }) => {+ const { container } = render(+ <Provider>+ <BindLogic logic={featureFlagLogic} props={{ id: 'new' }}>+ <FeatureFlagEvaluationContexts+ tags={[]}+ evaluationContexts={[]}+ flagId={1}+ context="sidebar"+ onSave={jest.fn()}+ evaluationContextsDisabledReason={disabledReason}+ />+ </BindLogic>+ </Provider>+ )++ fireEvent.click(container.querySelector('[data-attr="button-edit-evaluation-contexts"]') as Element)++ expect(!!container.querySelector('[data-attr="feature-flag-evaluation-contexts-input"]')).toBe(opensEditor)+ }+ )+})diff --git a/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsx b/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsxindex 9ee43c064e78..c90e0bdacac2 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagEvaluationContexts.tsx@@ -25,6 +25,7 @@ interface FeatureFlagEvaluationContextsProps {onChange?: (tags: string[], evaluationContexts: string[]) => void/** Sidebar mode: component handles persistence. Mutually exclusive with onChange. */onSave?: (tags: string[], evaluationContexts: string[]) => void+ evaluationContextsDisabledReason?: string | null}export function FeatureFlagEvaluationContexts({@@ -36,6 +37,7 @@ export function FeatureFlagEvaluationContexts({context,onChange,onSave,+ evaluationContextsDisabledReason,}: FeatureFlagEvaluationContextsProps): JSX.Element {const staticOnly = context === 'static'const logic = featureFlagEvaluationContextsLogic({ flagId, context, tags, evaluationContexts })@@ -240,7 +242,10 @@ export function FeatureFlagEvaluationContexts({{!staticOnly && (<LemonTagtype="none"- onClick={() => setIsEditingContexts(true)}+ onClick={+ evaluationContextsDisabledReason ? undefined : () => setIsEditingContexts(true)+ }+ disabledReason={evaluationContextsDisabledReason}data-attr="button-edit-evaluation-contexts"icon={evaluationContexts.length > 0 ? <IconPencil /> : <IconPlus />}className="border border-dashed cursor-pointer"diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsxindex e232cffac4c1..8c162b3f9e9c 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx@@ -66,7 +66,12 @@ 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, MultivariateFlagVariant } from '~/types'+import {+ FeatureFlagBucketingIdentifier,+ FeatureFlagEvaluationRuntime,+ FeatureFlagWithV1Config,+ MultivariateFlagVariant,+} from '~/types'import { FeatureFlagCodeExample } from './FeatureFlagCodeExample'import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'@@ -158,7 +163,7 @@ function SortableVariantHeader({export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {const {props,- featureFlag,+ featureFlag: loadedFeatureFlag,originalFeatureFlag,multivariateEnabled,variants,@@ -174,6 +179,8 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {alsoCreateInProjects,alsoCreateInProjectOptions,} = useValues(featureFlagLogic)+ // The form never mounts for another config version (FeatureFlag.tsx), so the document is v1.+ const featureFlag = loadedFeatureFlag as FeatureFlagWithV1Configconst {setMultivariateEnabled,setFeatureFlag,diff --git a/frontend/src/scenes/feature-flags/FeatureFlagInstructions.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagInstructions.test.tsxnew file mode 100644index 000000000000..b5bc40ad2763--- /dev/null+++ b/frontend/src/scenes/feature-flags/FeatureFlagInstructions.test.tsx@@ -0,0 +1,49 @@+import '@testing-library/jest-dom'++import { cleanup, render } from '@testing-library/react'+import { Provider } from 'kea'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { FeatureFlagConfig, SDKKey } from '~/types'++import { OPTIONS } from './FeatureFlagCodeOptions'+import { CodeInstructions } from './FeatureFlagInstructions'+import { NEW_FLAG } from './featureFlagLogic'++describe('CodeInstructions', () => {+ beforeEach(() => {+ useMocks({ get: { '/api/projects/:team/groups_types/': [] } })+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ it.each<{ format: string; filters: FeatureFlagConfig; disabled: boolean }>([+ {+ format: 'v1',+ filters: { groups: [{ properties: [], rollout_percentage: 100, variant: null }] },+ disabled: false,+ },+ {+ format: 'rules v2',+ filters: { version: 2, return_type: 'boolean', default_value: false, rules: [] },+ disabled: true,+ },+ ])('a $format flag has the local evaluation option disabled: $disabled', ({ filters, disabled }) => {+ const { container } = render(+ <Provider>+ <CodeInstructions+ options={OPTIONS}+ featureFlag={{ ...NEW_FLAG, id: 1, key: 'checkout', filters }}+ selectedLanguage={SDKKey.NODE_JS}+ />+ </Provider>+ )++ const checkbox = container.querySelector('[data-attr="flags-code-example-local-eval-option"] input')+ expect((checkbox as HTMLInputElement).disabled).toBe(disabled)+ })+})diff --git a/frontend/src/scenes/feature-flags/FeatureFlagInstructions.tsx b/frontend/src/scenes/feature-flags/FeatureFlagInstructions.tsxindex 58b074d4289f..107b32664b8c 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagInstructions.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagInstructions.tsx@@ -13,6 +13,8 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { groupsModel } from '~/models/groupsModel'import { FeatureFlagEvaluationRuntime, FeatureFlagType, GroupTypeIndex, SDKKey } from '~/types'+import { isV1FeatureFlagConfig } from 'products/feature_flags/frontend/featureFlagConfigFormat'+import {BOOTSTRAPPING_OPTIONS,FF_ANCHOR,@@ -97,6 +99,19 @@ export function CodeInstructions({}))const hasUnsupportedFeatures = !!localEvalWarning+ // Local evaluation definitions leave out flags in any other config version, so SDKs evaluate them remotely.+ const unsupportedConfigForLocalEval = !!featureFlag && !isV1FeatureFlagConfig(featureFlag.filters)+ const localEvalDisabledReason = remoteConfiguration+ ? "Local evaluation isn't available for remote config flags"+ : !LOCAL_EVALUATION_LIBRARIES.includes(selectedOption.key)+ ? 'Local evaluation is only available in server-side libraries'+ : featureFlag?.ensure_experience_continuity+ ? "Local evaluation doesn't work for flags that persist across authentication steps"+ : unsupportedConfigForLocalEval+ ? "Local evaluation doesn't support this flag's config format yet, so SDKs evaluate it remotely"+ : hasUnsupportedFeatures+ ? `Local evaluation is unavailable for this flag due to unsupported features: ${localEvalWarning}`+ : nullconst { reportFlagsCodeExampleInteraction, reportFlagsCodeExampleLanguage } = useActions(eventUsageLogic)const getDocumentationLink = (): string => {@@ -164,7 +179,7 @@ export function CodeInstructions({setShowPayloadCode(false)}- if (featureFlag?.ensure_experience_continuity) {+ if (featureFlag?.ensure_experience_continuity || unsupportedConfigForLocalEval) {setShowLocalEvalCode(false)}}, [selectedLanguage, featureFlag]) // oxlint-disable-line react-hooks/exhaustive-deps@@ -305,17 +320,7 @@ export function CodeInstructions({<IconInfo className="text-xl text-secondary shrink-0" /></div></Tooltip>- <Tooltip- title={- !LOCAL_EVALUATION_LIBRARIES.includes(selectedOption.key)- ? 'Local evaluation is only available in server-side libraries'- : featureFlag?.ensure_experience_continuity- ? "Local evaluation doesn't work for flags that persist across authentication steps"- : hasUnsupportedFeatures- ? `Local evaluation is unavailable for this flag due to unsupported features: ${localEvalWarning}`- : 'Show code for local evaluation'- }- >+ <Tooltip title={localEvalDisabledReason ?? 'Show code for local evaluation'}><div className="flex items-center gap-1"><LemonCheckboxlabel="Show local evaluation option"@@ -325,12 +330,7 @@ export function CodeInstructions({setShowLocalEvalCode(!showLocalEvalCode)reportFlagsCodeExampleInteraction('local evaluation')}}- disabled={- remoteConfiguration ||- !LOCAL_EVALUATION_LIBRARIES.includes(selectedOption.key) ||- !!featureFlag?.ensure_experience_continuity ||- hasUnsupportedFeatures- }+ disabled={!!localEvalDisabledReason}/><IconInfo className="text-xl text-secondary shrink-0" /></div>diff --git a/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx b/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsxindex d376336428d1..f1e4cba31f47 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagOverview.tsx@@ -13,6 +13,15 @@ import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLimport { AccessControlLevel, AccessControlResourceType, FeatureFlagEvaluationRuntime, FeatureFlagType } from '~/types'+import {+ UNSUPPORTED_CONFIG_DISABLED_REASON,+ featureFlagConfigFormat,+ isRulesV2FeatureFlagConfig,+ isV1FeatureFlagConfig,+} from 'products/feature_flags/frontend/featureFlagConfigFormat'+import { FeatureFlagConfigReadonlyNotice } from 'products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice'+import { FeatureFlagRulesV2Readonly } from 'products/feature_flags/frontend/FeatureFlagRulesV2Readonly'+import { EditableOverviewSection } from './EditableOverviewSection'import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'import { FeatureFlagInstructions } from './FeatureFlagInstructions'@@ -62,9 +71,13 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):const hasEvaluationContexts = !!featureFlags[FEATURE_FLAGS.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 multivariateEnabled = !!featureFlag.filters?.multivariate- const variants = featureFlag.filters?.multivariate?.variants || []- const hasPayload = !!featureFlag.filters?.payloads?.['true']+ const v1Filters = isV1FeatureFlagConfig(featureFlag.filters) ? featureFlag.filters : null+ const multivariateEnabled = !!v1Filters?.multivariate+ const variants = v1Filters?.multivariate?.variants || []+ const hasPayload = !!v1Filters?.payloads?.['true']+ const showImplementation =+ !!v1Filters ||+ (isRulesV2FeatureFlagConfig(featureFlag.filters) && featureFlag.filters.return_type === 'boolean')const getFlagTypeDisplay = (): { icon: JSX.Element; label: string; description: string } => {if (featureFlag.is_remote_configuration) {@@ -153,7 +166,9 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):disabledReason={!featureFlag.can_edit? "You only have view access to this feature flag. To make changes, contact the flag's creator."- : null+ : featureFlagConfigFormat(featureFlag.filters) === 'unsupported'+ ? UNSUPPORTED_CONFIG_DISABLED_REASON+ : null}label="Enable feature flag"bordered@@ -218,7 +233,15 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):</div><div className="flex-[2] min-w-80 flex flex-col gap-4">- {multivariateEnabled && variants.length > 0 ? (+ {!v1Filters ? (+ <div className="rounded border p-4 bg-bg-light">+ {isRulesV2FeatureFlagConfig(featureFlag.filters) ? (+ <FeatureFlagRulesV2Readonly config={featureFlag.filters} />+ ) : (+ <FeatureFlagConfigReadonlyNotice filters={featureFlag.filters} />+ )}+ </div>+ ) : multivariateEnabled && variants.length > 0 ? (<EditableOverviewSectiondisabledReason={featureFlag.experiment_set && featureFlag.experiment_set.length > 0@@ -237,8 +260,8 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):{flagTypeCard}<div className="flex flex-col gap-2"><label className="text-sm font-semibold">Payload</label>- {hasPayload && featureFlag.filters?.payloads?.['true'] ? (- <JSONEditorInput readOnly value={featureFlag.filters.payloads['true']} />+ {hasPayload && v1Filters.payloads?.['true'] ? (+ <JSONEditorInput readOnly value={v1Filters.payloads['true']} />) : (<div className="text-sm text-muted p-3 rounded border border-dashed bg-surface-secondary">No payload configured@@ -249,7 +272,7 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):</EditableOverviewSection>)}- {!featureFlag.is_remote_configuration && (+ {v1Filters && !featureFlag.is_remote_configuration && (<><EditableOverviewSectiondisabledReason={@@ -260,7 +283,7 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):><FeatureFlagReleaseConditionsReadonlyid={String(featureFlag.id)}- filters={featureFlag.filters}+ filters={v1Filters}isDisabled={!featureFlag.active}evaluationRuntime={featureFlag.evaluation_runtime}/>@@ -270,23 +293,25 @@ export function FeatureFlagOverview({ featureFlag }: FeatureFlagOverviewProps):</div></div>- <LemonCollapse- className="bg-bg-light"- panels={[- {- key: 'implementation',- header: 'How to implement',- content: (- <div className="flex flex-col gap-4">- <p className="text-sm text-muted m-0">- Use the following code to implement this feature flag.- </p>- <FeatureFlagInstructions featureFlag={featureFlag} />- </div>- ),- },- ]}- />+ {showImplementation && (+ <LemonCollapse+ className="bg-bg-light"+ panels={[+ {+ key: 'implementation',+ header: 'How to implement',+ content: (+ <div className="flex flex-col gap-4">+ <p className="text-sm text-muted m-0">+ Use the following code to implement this feature flag.+ </p>+ <FeatureFlagInstructions featureFlag={featureFlag} />+ </div>+ ),+ },+ ]}+ />+ )}</div>)}diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.blastRadiusError.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.blastRadiusError.test.tsxindex 6a8df034016e..636242f5b970 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.blastRadiusError.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.blastRadiusError.test.tsx@@ -5,7 +5,7 @@ import { Provider } from 'kea'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { FeatureFlagGroupType, FeatureFlagType, PropertyFilterType, PropertyOperator } from '~/types'+import { FeatureFlagFilters, FeatureFlagGroupType, PropertyFilterType, PropertyOperator } from '~/types'import { FeatureFlagReleaseConditions } from './FeatureFlagReleaseConditions'import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'@@ -15,7 +15,7 @@ jest.mock('lib/components/AutoSizer', () => ({renderProp({ height: 400, width: 400 }),}))-function buildFilters(): FeatureFlagType['filters'] {+function buildFilters(): FeatureFlagFilters {const group: FeatureFlagGroupType = {properties: [{diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.cohortOperator.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.cohortOperator.test.tsxindex ec665e0de29e..657e009f609a 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.cohortOperator.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.cohortOperator.test.tsx@@ -11,7 +11,7 @@ import {CohortType,FeatureFlagGroupType,FilterLogicalOperator,- FeatureFlagType,+ FeatureFlagFilters,PropertyFilterType,PropertyOperator,} from '~/types'@@ -38,7 +38,7 @@ const cohortFilter: CohortPropertyFilter = {cohort_name: 'Power Users',}-function buildFilters(): FeatureFlagType['filters'] {+function buildFilters(): FeatureFlagFilters {const group: FeatureFlagGroupType = {properties: [cohortFilter],rollout_percentage: 100,diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.earlyAccessGroupTargeting.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.earlyAccessGroupTargeting.test.tsxindex 35bef566752d..13e791730165 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.earlyAccessGroupTargeting.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.earlyAccessGroupTargeting.test.tsx@@ -7,7 +7,7 @@ import { Provider } from 'kea'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'-import { FeatureFlagGroupType, FeatureFlagType } from '~/types'+import { FeatureFlagFilters, FeatureFlagGroupType } from '~/types'import { EARLY_ACCESS_GROUP_TARGETING_DISABLED_REASON } from './constants'import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'@@ -17,7 +17,7 @@ jest.mock('lib/components/AutoSizer', () => ({renderProp({ height: 400, width: 400 }),}))-function buildFilters(): FeatureFlagType['filters'] {+function buildFilters(): FeatureFlagFilters {const group: FeatureFlagGroupType = {properties: [],rollout_percentage: 100,diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.flagDependencyLabel.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.flagDependencyLabel.test.tsxindex a17bbc8fafca..71f25c5ad01d 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.flagDependencyLabel.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.flagDependencyLabel.test.tsx@@ -7,7 +7,7 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import {FeatureFlagGroupType,- FeatureFlagType,+ FeatureFlagFilters,FlagPropertyFilter,PropertyFilterType,PropertyOperator,@@ -23,7 +23,7 @@ const flagDependencyFilter: FlagPropertyFilter = {value: true,}-function buildFilters(): FeatureFlagType['filters'] {+function buildFilters(): FeatureFlagFilters {const group: FeatureFlagGroupType = {properties: [flagDependencyFilter],rollout_percentage: 100,diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.incompleteFilterOnSave.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.incompleteFilterOnSave.test.tsxindex 88f837e1a217..64c40063df05 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.incompleteFilterOnSave.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.incompleteFilterOnSave.test.tsx@@ -7,7 +7,13 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'-import { FeatureFlagGroupType, FeatureFlagType, PropertyFilterType, PropertyOperator } from '~/types'+import {+ FeatureFlagFilters,+ FeatureFlagGroupType,+ FeatureFlagType,+ PropertyFilterType,+ PropertyOperator,+} from '~/types'import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'@@ -22,7 +28,7 @@ const INCOMPLETE_FILTER_MESSAGE = 'Add a value or remove this filter'// A property picked from the taxonomic list starts with a null value, and the form blocks the save// while that half-built row is on the flag.-function buildFilters(planValue: string | null = null): FeatureFlagType['filters'] {+function buildFilters(planValue: string | null = null): FeatureFlagFilters {const groups: FeatureFlagGroupType[] = [{properties: [diff --git a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.matchingUsersLink.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.matchingUsersLink.test.tsxindex 506a9c8c6e8f..04577a08ebcd 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.matchingUsersLink.test.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagReleaseConditions.matchingUsersLink.test.tsx@@ -8,7 +8,7 @@ import { Provider } from 'kea'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'-import { FeatureFlagGroupType, FeatureFlagType, PropertyFilterType, PropertyOperator } from '~/types'+import { FeatureFlagFilters, FeatureFlagGroupType, PropertyFilterType, PropertyOperator } from '~/types'import { FeatureFlagReleaseConditions } from './FeatureFlagReleaseConditions'import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'@@ -20,7 +20,7 @@ jest.mock('lib/components/AutoSizer', () => ({// `aggregation_group_type_index` is set at flag level only, so the condition has to inherit it. That// resolution happens at the call site and is invisible to `matchingActorsUrl`'s own tests.-function buildFilters(aggregationGroupTypeIndex?: number): FeatureFlagType['filters'] {+function buildFilters(aggregationGroupTypeIndex?: number): FeatureFlagFilters {const group: FeatureFlagGroupType = {properties: [{diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsxindex 26d885d8fac5..8c5be4a549d3 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx@@ -40,7 +40,7 @@ import { urls } from 'scenes/urls'import { groupsModel, Noun } from '~/models/groupsModel'import {- FeatureFlagType,+ FeatureFlagWithV1Config,MultivariateFlagVariant,RecurrenceInterval,ScheduledChangeOperationType,@@ -69,7 +69,7 @@ export const DAYJS_FORMAT = 'MMMM DD, YYYY h:mm A'type AggregationLabel = (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Nounfunction getScheduledVariantsPayloads(- featureFlag: FeatureFlagType,+ featureFlag: FeatureFlagWithV1Config,schedulePayload: { variants?: MultivariateFlagVariant[]; payloads?: Record<string, any>; filters?: any }): { variants: MultivariateFlagVariant[]; payloads: Record<string, any> } {const currentVariants = featureFlag.filters.multivariate?.variants || []@@ -413,7 +413,7 @@ function ScheduleCard({export default function FeatureFlagSchedule(): JSX.Element {const {- featureFlag,+ featureFlag: loadedFeatureFlag,scheduledChangesLoading,scheduledChangeOperation,scheduleDateMarker,@@ -437,6 +437,8 @@ export default function FeatureFlagSchedule(): JSX.Element {scheduleFormState,scheduleFormCollapsible,} = useValues(featureFlagLogic)+ // The Schedule tab is not offered for another config version (availableTabs), so the document is v1.+ const featureFlag = loadedFeatureFlag as FeatureFlagWithV1Configconst {deleteScheduledChange,setScheduleDateMarker,diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsxindex 96d62edf04f8..c17b9753f92c 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx@@ -12,6 +12,7 @@ import featureFlags from './__mocks__/feature_flags.json'import { featureFlagLogic } from './featureFlagLogic'const STALE_FLAG_ID = 1498+const RULES_V2_FLAG_ID = 1802const DELETED_FLAG_ID = 1526const meta: Meta = {@@ -184,6 +185,25 @@ export const StaleFeatureFlag: Story = {},}+export const FeatureFlagsListWithRulesV2Flag: Story = {+ parameters: {+ pageUrl: `${urls.featureFlags()}?search=rules-v2`,+ },+}++export const RulesV2FeatureFlag: Story = {+ parameters: {+ pageUrl: urls.featureFlag(RULES_V2_FLAG_ID),+ },+}++// `?edit=true` must still show the read-only view, because the v1 form's full save would rewrite the document.+export const RulesV2FeatureFlagEditDeepLink: Story = {+ parameters: {+ pageUrl: `${urls.featureFlag(RULES_V2_FLAG_ID)}?edit=true`,+ },+}+export const StaleFeatureFlagWithAiAssessment: Story = {parameters: {pageUrl: urls.featureFlag(STALE_FLAG_ID),diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsxindex f5e9e42bba12..a108214416ba 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx@@ -27,7 +27,7 @@ import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/Wrappingimport { copyToClipboard } from 'lib/utils/copyToClipboard'import { cn } from 'lib/utils/css-classes'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'-import { pluralize } from 'lib/utils/strings'+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'@@ -50,12 +50,21 @@ import {ActivityScope,AnyPropertyFilter,BaseMathType,+ FeatureFlagConfig,FeatureFlagEvaluationRuntime,- FeatureFlagFilters,FeatureFlagType,} from '~/types'import { featureFlagsEmptyState } from 'products/feature_flags/frontend/emptyState/featureFlagsEmptyState'+import {+ ARCHIVE_UNAVAILABLE_DISABLED_REASON,+ UNSUPPORTED_CONFIG_DISABLED_REASON,+ canArchiveFeatureFlag,+ featureFlagConfigFormat,+ featureFlagConfigFormatLabel,+ isRulesV2FeatureFlagConfig,+ isV1FeatureFlagConfig,+} from 'products/feature_flags/frontend/featureFlagConfigFormat'import { FeatureFlagRequestUsage } from 'products/feature_flags/frontend/requestUsage/FeatureFlagRequestUsage'import { ApprovalsPromoBanner } from './ApprovalsPromoBanner'@@ -158,6 +167,8 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }const isUpdating = featureFlag.id ? featureFlagsUpdating[featureFlag.id] : falseconst [isQuickSurveyModalOpen, setIsQuickSurveyModalOpen] = useState(false)+ const configFormat = featureFlagConfigFormat(featureFlag.filters)+ const isV1Config = configFormat === 'v1'const tryInInsightsUrl = (featureFlag: FeatureFlagType): string => {const query: InsightVizNode = {@@ -201,7 +212,7 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }Copy key</LemonButton>- {featureFlag.id && (+ {featureFlag.id && isV1Config && (<AccessControlActionresourceType={AccessControlResourceType.FeatureFlag}minAccessLevel={AccessControlLevel.Editor}@@ -221,13 +232,15 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }</AccessControlAction>)}- <LemonButton- to={urls.featureFlagNew({ sourceId: featureFlag.id })}- data-attr="feature-flag-duplicate"- fullWidth- >- Duplicate- </LemonButton>+ {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@@ -261,7 +274,9 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }? 'Updating…': featureFlag.archived? 'Unarchive this flag before enabling it.'- : undefined+ : configFormat === 'unsupported'+ ? UNSUPPORTED_CONFIG_DISABLED_REASON+ : undefined}>{featureFlag.active ? 'Disable' : 'Enable'}@@ -293,14 +308,20 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }}}fullWidthloading={isUpdating}- disabledReason={isUpdating ? 'Updating…' : undefined}+ disabledReason={+ isUpdating+ ? 'Updating…'+ : !canArchiveFeatureFlag(featureFlag.filters)+ ? ARCHIVE_UNAVAILABLE_DISABLED_REASON+ : undefined+ }>{featureFlag.archived ? 'Unarchive' : 'Archive'}</LemonButton></AccessControlAction>)}- {featureFlag.id && (+ {featureFlag.id && isV1Config && (<AccessControlActionresourceType={AccessControlResourceType.FeatureFlag}minAccessLevel={AccessControlLevel.Editor}@@ -432,6 +453,13 @@ export function OverviewTab({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')@@ -622,9 +650,11 @@ export function OverviewTab({isRowSelectable: (flag: FeatureFlagType) =>flag.id === null? false- : flag.can_edit- ? true- : { disabledReason: "You don't have permission to edit this feature flag." },+ : !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'],@@ -878,20 +908,25 @@ export function FeatureFlags(): JSX.Element {}export function groupFilters(- filters: FeatureFlagFilters,+ filters: FeatureFlagConfig,stringOnly?: true,aggregationLabel?: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun): stringexport function groupFilters(- filters: FeatureFlagFilters,+ filters: FeatureFlagConfig,stringOnly?: false,aggregationLabel?: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun): JSX.Element | stringexport function groupFilters(- filters: FeatureFlagFilters,+ 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).pluraldiff --git a/frontend/src/scenes/feature-flags/__mocks__/feature_flags.json b/frontend/src/scenes/feature-flags/__mocks__/feature_flags.jsonindex 3327c0dbe786..6a7a22dec656 100644--- a/frontend/src/scenes/feature-flags/__mocks__/feature_flags.json+++ b/frontend/src/scenes/feature-flags/__mocks__/feature_flags.json@@ -1,5 +1,5 @@{- "count": 4,+ "count": 8,"next": null,"previous": null,"results": [@@ -255,6 +255,60 @@},"created_at": "2022-02-08T20:54:04.344072Z","updated_at": "2022-02-08T20:54:04.344072Z"+ },+ {+ "id": 1802,+ "name": "Checkout redesign, first rules v2 flag",+ "key": "checkout-redesign-rules-v2",+ "filters": {+ "version": 2,+ "return_type": "boolean",+ "default_value": false,+ "rules": [+ {+ "id": "6f1d3c2a-9b8e-4c7d-a1f0-2e3b4c5d6e7f",+ "rule_type": "targeted_release",+ "description": "Internal testers",+ "targeting": {+ "properties": [+ {+ "key": "email",+ "type": "person",+ "value": "@hedgehog.example",+ "operator": "icontains"+ }+ ]+ },+ "value": true+ },+ {+ "id": "0a9b8c7d-6e5f-4a3b-9c2d-1e0f9a8b7c6d",+ "rule_type": "percentage_rollout",+ "description": "Gradual rollout",+ "targeting": {+ "properties": []+ },+ "rollout_percentage": 25,+ "on_rollout_miss": "return_default",+ "assignment_algorithm": "sha1_60_v1",+ "seed": "checkout-redesign-rules-v2",+ "assign_by": "person",+ "value": true+ }+ ]+ },+ "deleted": false,+ "active": false,+ "version": 3,+ "created_by": {+ "id": 4765,+ "uuid": "4609ea95-6a1c-4577-bc5d-00ded02ffca9",+ "distinct_id": "98ca6644-43b2-4d78-a35b-0cb1cc520e35",+ "first_name": "Rick",+ "email": "[email protected]"+ },+ "created_at": "2023-01-20T10:00:00.000000Z",+ "updated_at": "2023-01-21T10:00:00.000000Z"}]}diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.tsindex c7759671d0eb..43b27250910f 100644--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts@@ -2,8 +2,10 @@ import {AccessControlLevel,FeatureFlagBucketingIdentifier,FeatureFlagEvaluationRuntime,+ FeatureFlagFilters,FeatureFlagGroupType,FeatureFlagType,+ FeatureFlagWithV1Config,PropertyFilterType,PropertyOperator,} from '~/types'@@ -23,7 +25,7 @@ import {const MAX_BACKEND_TEXT_LENGTH = 4096describe('featureFlagAiContext', () => {- const baseFeatureFlag: FeatureFlagType = {+ const baseFeatureFlag: FeatureFlagWithV1Config = {id: 1,key: 'test-flag',name: '',@@ -60,7 +62,7 @@ describe('featureFlagAiContext', () => {variant: null,}- function withFilters(filters: Partial<FeatureFlagType['filters']>): FeatureFlagType {+ function withFilters(filters: Partial<FeatureFlagFilters>): FeatureFlagType {return { ...baseFeatureFlag, filters: { ...baseFeatureFlag.filters, ...filters } }}@@ -117,9 +119,27 @@ describe('featureFlagAiContext', () => {],})+ function rulesV2Flag(ruleCount: number): FeatureFlagType {+ return {+ ...baseFeatureFlag,+ filters: {+ version: 2,+ return_type: 'boolean',+ default_value: false,+ rules: Array.from({ length: ruleCount }, (_, index) => ({+ id: `rule-${index}`,+ rule_type: 'targeted_release' as const,+ targeting: { properties: personCondition.properties ?? [] },+ value: true,+ })),+ },+ }+ }+const oversized: [string, FeatureFlagType][] = [['a condition holding hundreds of pasted values', flagWithPastedValues],['a very long description', { ...withFilters({ groups: [personCondition] }), name: 'x'.repeat(20000) }],+ ['a rules v2 document with hundreds of rules', rulesV2Flag(300)],]test.each(oversized)('keeps the attachment under the backend limit with %s', (_name, featureFlag) => {@@ -138,6 +158,17 @@ describe('featureFlagAiContext', () => {expect(JSON.parse(value).release_condition_count).toBe(1)})+ it('attaches a rules v2 document whole, and only its config version once it is too large', () => {+ const small = rulesV2Flag(1)++ expect(JSON.parse(targetingValue(small)).config).toEqual(small.filters)+ expect(JSON.parse(targetingValue(rulesV2Flag(300)))).toEqual({+ key: 'test-flag',+ active: true,+ config_version: 2,+ })+ })+describe('featureFlagCleanupAssessmentContextItems', () => {it('includes the cleanup skill for the agent', () => {const items = featureFlagCleanupAssessmentContextItems(baseFeatureFlag, 123)diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.tsindex 43405ee21b68..fe32c782d838 100644--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.ts@@ -1,5 +1,6 @@import { FeatureFlagType } from '~/types'+import { isV1FeatureFlagConfig } from 'products/feature_flags/frontend/featureFlagConfigFormat'import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'// The backend rejects a text attachment longer than this and fails the whole send with a 400@@ -29,6 +30,12 @@ export function featureFlagContextItems(featureFlag: FeatureFlagType): AttachedCfunction targetingValue(featureFlag: FeatureFlagType): string {const filters = featureFlag.filters+ if (!isV1FeatureFlagConfig(filters)) {+ const full = JSON.stringify({ key: featureFlag.key, active: featureFlag.active, config: filters })+ return full.length <= MAX_TARGETING_VALUE_LENGTH+ ? full+ : JSON.stringify({ key: featureFlag.key, active: featureFlag.active, config_version: filters.version })+ }const identity = {key: featureFlag.key,description: featureFlag.name.slice(0, MAX_DESCRIPTION_LENGTH),diff --git a/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.ts b/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.tsindex a111f01db115..0f7905d6d4b3 100644--- a/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagConfirmationLogic.ts@@ -154,6 +154,7 @@ export function checkFeatureFlagConfirmation(if (!updatedFlag.active && onDisableAndArchive) {openFeatureFlagDisableDialog({source: 'feature-flag-detail',+ filters: updatedFlag.filters,onDisable: onConfirm,onDisableAndArchive,})diff --git a/frontend/src/scenes/feature-flags/featureFlagDisableDialog.test.ts b/frontend/src/scenes/feature-flags/featureFlagDisableDialog.test.tsindex 796c08ba43b2..a84bba4d52cf 100644--- a/frontend/src/scenes/feature-flags/featureFlagDisableDialog.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagDisableDialog.test.ts@@ -14,6 +14,7 @@ describe('openFeatureFlagDisableDialog', () => {const open = (): void =>openFeatureFlagDisableDialog({source: 'feature-flags-list',+ filters: { groups: [] },onDisable,onDisableAndArchive,})diff --git a/frontend/src/scenes/feature-flags/featureFlagDisableDialog.tsx b/frontend/src/scenes/feature-flags/featureFlagDisableDialog.tsxindex 22566da7de69..df233f57a484 100644--- a/frontend/src/scenes/feature-flags/featureFlagDisableDialog.tsx+++ b/frontend/src/scenes/feature-flags/featureFlagDisableDialog.tsx@@ -2,6 +2,10 @@ import posthog from 'posthog-js'import { LemonDialog } from '@posthog/lemon-ui'+import { FeatureFlagConfig } from '~/types'++import { canArchiveFeatureFlag } from 'products/feature_flags/frontend/featureFlagConfigFormat'+export type FeatureFlagDisableDialogSource = 'feature-flags-list' | 'feature-flag-detail'export type FeatureFlagDisableDialogOption = 'disable' | 'disable_and_archive' | 'cancel'@@ -13,6 +17,8 @@ export function reportFeatureFlagDisableDialogOptionSelected(posthog.capture('feature flag disable confirmation option selected', { source, option })}+const ROLLBACK_DESCRIPTION = 'This flag will be immediately rolled back from the users matching the release conditions.'+/*** Opens the disable confirmation dialog for a feature flag. "Disable only" is the primary action;* "Disable and archive" sits alongside it as a destructive secondary, so the more destructive@@ -20,14 +26,17 @@ export function reportFeatureFlagDisableDialogOptionSelected(*/export function openFeatureFlagDisableDialog({source,+ filters,onDisable,onDisableAndArchive,}: {source: FeatureFlagDisableDialogSource+ filters: FeatureFlagConfig | undefinedonDisable: () => voidonDisableAndArchive: () => void}): void {posthog.capture('feature flag disable confirmation shown', { source })+ const offerArchive = canArchiveFeatureFlag(filters)const selectDisable = (): void => {reportFeatureFlagDisableDialogOptionSelected(source, 'disable')@@ -41,21 +50,24 @@ export function openFeatureFlagDisableDialog({LemonDialog.open({title: 'Disable this flag?',- description:- 'This flag will be immediately rolled back from the users matching the release conditions. Done with it for good? Archive it too: archived flags are hidden from the flag list, but linked experiments and surveys keep their data.',+ description: offerArchive+ ? `${ROLLBACK_DESCRIPTION} Done with it for good? Archive it too: archived flags are hidden from the flag list, but linked experiments and surveys keep their data.`+ : ROLLBACK_DESCRIPTION,primaryButton: {children: 'Disable only',type: 'primary',size: 'small',onClick: selectDisable,},- secondaryButton: {- children: 'Disable and archive',- type: 'secondary',- status: 'danger',- size: 'small',- onClick: selectDisableAndArchive,- },+ secondaryButton: offerArchive+ ? {+ children: 'Disable and archive',+ type: 'secondary',+ status: 'danger',+ size: 'small',+ onClick: selectDisableAndArchive,+ }+ : null,tertiaryButton: {children: 'Cancel',type: 'tertiary',diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 2fad6ac72bb4..10448832c7e3 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -16,6 +16,7 @@ import { toast } from 'react-toastify'import { lemonToast as sharedLemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { dayjs } from 'lib/dayjs'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -32,6 +33,7 @@ import {CohortType,FeatureFlagGroupType,FeatureFlagType,+ FeatureFlagWithV1Config,OrganizationFeatureFlag,PropertyFilterType,PropertyOperator,@@ -83,6 +85,10 @@ function capturesOf(event: string): any[][] {return (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === event)}+function v1Filters(flag: FeatureFlagType): FeatureFlagFilters {+ return flag.filters as FeatureFlagFilters+}+// A promise the test resolves by hand, so it can hold a request open while something else lands.function deferred(): { promise: Promise<void>; resolve: () => void } {let resolve: () => void = () => {}@@ -909,7 +915,7 @@ describe('featureFlagLogic', () => {})it('resets the variants and group variant keys when disabling multivariate', async () => {- const MOCK_MULTIVARIATE_FEATURE_FLAG: FeatureFlagType = {+ const MOCK_MULTIVARIATE_FEATURE_FLAG: FeatureFlagWithV1Config = {...logic.values.featureFlag,filters: {groups: [@@ -998,7 +1004,7 @@ describe('featureFlagLogic', () => {is_remote_configuration: true,has_encrypted_payloads: true,filters: {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),payloads: { true: 'encrypted-ciphertext' },},}@@ -1042,7 +1048,7 @@ describe('featureFlagLogic', () => {logic.actions.applyTemplate('targeted')}).toDispatchActions(['applyTemplate', 'setFeatureFlag'])- const groups = logic.values.featureFlag.filters.groups+ const groups = v1Filters(logic.values.featureFlag).groupsexpect(groups[0]).toMatchObject(DEFAULT_GROUP)expect(groups.length).toBeGreaterThan(1)})@@ -1053,7 +1059,7 @@ describe('featureFlagLogic', () => {is_remote_configuration: false,has_encrypted_payloads: false,filters: {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),payloads: { control: '{"x":1}', test: '{"y":2}' },},}@@ -1121,7 +1127,7 @@ describe('featureFlagLogic', () => {is_remote_configuration: true,has_encrypted_payloads: true,filters: {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),payloads: { true: 'encrypted-ciphertext' },},}@@ -1154,7 +1160,7 @@ describe('featureFlagLogic', () => {is_remote_configuration: true,has_encrypted_payloads: false,filters: {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),payloads: { true: 'plain-payload' },},}@@ -1189,7 +1195,7 @@ describe('featureFlagLogic', () => {await expectLogic(logic, () => {logic.actions.setFeatureFlagValue('filters', {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),payloads: { true: payload },})}).toMatchValues({@@ -1201,7 +1207,7 @@ describe('featureFlagLogic', () => {})const updatedConditionFilters: FeatureFlagFilters = {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),groups: [{properties: [@@ -1321,7 +1327,7 @@ describe('featureFlagLogic', () => {it('becomes true after filters change via the form', async () => {await expectLogic(logic, () => {logic.actions.setFeatureFlagValue('filters', {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),groups: [{ properties: [], rollout_percentage: 42, variant: null }],})}).toMatchValues({ hasUnsavedChanges: true })@@ -1344,9 +1350,9 @@ describe('featureFlagLogic', () => {// working copy, flipping the guard to clean so navigation silently discarded the edit.await expectLogic(logic, () => {logic.actions.setFeatureFlagValue('filters', {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),groups: [- ...logic.values.featureFlag.filters.groups,+ ...v1Filters(logic.values.featureFlag).groups,{ properties: [], rollout_percentage: 100, variant: null },],})@@ -1374,19 +1380,19 @@ describe('featureFlagLogic', () => {],])('keeps an in-progress release-condition edit after %s reconciles', async (_label, reconcile) => {const editedGroups = [- ...logic.values.featureFlag.filters.groups,+ ...v1Filters(logic.values.featureFlag).groups,{ properties: [], rollout_percentage: 100, variant: null },]await expectLogic(logic, () => {logic.actions.setFeatureFlagValue('filters', {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),groups: editedGroups,})}).toMatchValues({ hasUnsavedChanges: true })await expectLogic(logic, reconcile).toFinishAllListeners()- expect(logic.values.featureFlag.filters.groups).toHaveLength(editedGroups.length)+ expect(v1Filters(logic.values.featureFlag).groups).toHaveLength(editedGroups.length)expect(logic.values.hasUnsavedChanges).toBe(true)})@@ -1687,7 +1693,7 @@ describe('featureFlagLogic', () => {it('applies an enabled group-targeted default and mirrors the aggregation onto the new flag', async () => {const newLogic = await mountNewFlag({ enabled: true, default_groups: [groupDefault] })- expect(newLogic.values.featureFlag.filters.groups).toEqual([groupDefault])+ expect(v1Filters(newLogic.values.featureFlag).groups).toEqual([groupDefault])expect(newLogic.values.featureFlag.filters.aggregation_group_type_index).toBe(1)newLogic.unmount()})@@ -1695,7 +1701,7 @@ describe('featureFlagLogic', () => {it('leaves a new flag on user targeting when the default config is disabled', async () => {const newLogic = await mountNewFlag({ enabled: false, default_groups: [groupDefault] })- expect(newLogic.values.featureFlag.filters.groups).toEqual([+ expect(v1Filters(newLogic.values.featureFlag).groups).toEqual([{ properties: [], rollout_percentage: 0, variant: null },])expect(newLogic.values.featureFlag.filters.aggregation_group_type_index).toBeUndefined()@@ -2784,7 +2790,7 @@ describe('featureFlagLogic', () => {newLogic.mount()await expectLogic(newLogic).toDispatchActions(['loadFeatureFlagSuccess'])- const groups = newLogic.values.featureFlag.filters.groups+ const groups = v1Filters(newLogic.values.featureFlag).groupsexpect(groups[0]).toMatchObject(DEFAULT_GROUP)expect(groups.length).toBe(1)@@ -2937,6 +2943,22 @@ describe('featureFlagLogic', () => {})})+ describe('saveSidebarTags', () => {+ it('saves a v1 flag through the full save, evaluation contexts included', async () => {+ const update = jest+ .spyOn(api, 'update')+ .mockImplementation(async (_url, payload) => ({ ...MOCK_FEATURE_FLAG, ...(payload as object) }))++ logic.actions.saveSidebarTags(['beta'], ['web'])+ await expectLogic(logic).toDispatchActions(['updateFlag', 'saveFeatureFlag']).toFinishAllListeners()++ expect(update).toHaveBeenCalledWith(+ expect.stringContaining(`/feature_flags/${MOCK_FEATURE_FLAG.id}`),+ expect.objectContaining({ tags: ['beta'], evaluation_contexts: ['web'], filters: expect.anything() })+ )+ })+ })+describe('stale status after a mutation', () => {const STATUS_URL = `/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/status`@@ -4131,7 +4153,7 @@ describe('variant reordering', () => {logic.actions.setFeatureFlag({...logic.values.featureFlag,filters: {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),payloads: undefined,},})@@ -4144,7 +4166,7 @@ describe('variant reordering', () => {logic.actions.setFeatureFlag({...logic.values.featureFlag,filters: {- ...logic.values.featureFlag.filters,+ ...v1Filters(logic.values.featureFlag),payloads: { 0: { option: 'default' }, 2: { option: 'variant-b' } }, // Missing index 1},})@@ -4158,3 +4180,334 @@ describe('variant reordering', () => {})})})++describe('a flag in config version 2', () => {+ let logic: ReturnType<typeof featureFlagLogic.build>++ beforeEach(silenceKeaLoadersErrors)+ afterEach(resumeKeaLoadersErrors)++ const V2_FLAG = {+ ...NEW_FLAG,+ id: 7,+ key: 'checkout-rules-v2',+ active: false,+ version: 3,+ filters: {+ version: 2,+ return_type: 'boolean',+ default_value: false,+ rules: [+ {+ id: 'rule-1',+ rule_type: 'targeted_release',+ targeting: { properties: [] },+ value: true,+ },+ ],+ },+ }++ beforeEach(async () => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [200, V2_FLAG],+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/status`]: () => [+ 200,+ MOCK_FEATURE_FLAG_STATUS,+ ],+ },+ })+ initKeaTests()+ logic = featureFlagLogic({ id: 7 })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ it('loads without error, keeps the document untouched and exposes the format', () => {+ expect(logic.values.featureFlag.filters).toEqual(V2_FLAG.filters)+ expect(logic.values.configFormat).toBe('v2')+ expect(logic.values.hasUnsavedChanges).toBe(false)+ })++ it('offers no tab that rewrites or copies the document', () => {+ for (const tab of [FeatureFlagsTab.PROJECTS, FeatureFlagsTab.SCHEDULE, FeatureFlagsTab.TESTING]) {+ expect(logic.values.availableTabs).not.toContain(tab)+ }+ expect(logic.values.availableTabs).toEqual(+ expect.arrayContaining([FeatureFlagsTab.OVERVIEW, FeatureFlagsTab.USAGE, FeatureFlagsTab.HISTORY])+ )+ })++ it('refreshes the flag when its row version was stale instead of retrying', async () => {+ // The conflicting write replaced the document, so the refresh must show it, not only its version.+ const changedElsewhere = {+ ...V2_FLAG,+ name: 'Renamed elsewhere',+ version: 4,+ filters: { ...V2_FLAG.filters, default_value: true, rules: [] },+ }+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [200, changedElsewhere],+ },+ })+ const detail = 'This feature flag has changed since version 3'+ const update = jest+ .spyOn(api, 'update')+ .mockRejectedValueOnce(new ApiError(undefined, 409, undefined, { detail }))+ const approvalWarning = jest.spyOn(sharedLemonToast, 'warning').mockReturnValue('toast-id')++ logic.actions.updateFeatureFlagActive(true)+ await expectLogic(logic)+ .toDispatchActions(['updateFeatureFlagActiveFailure', 'refreshFeatureFlag', 'refreshFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(update).toHaveBeenCalledTimes(1)+ expect(lemonToast.error).toHaveBeenCalledWith(detail)+ // The approval handler treats every 409 as a change request, so the stale branch must return before it.+ expect(approvalWarning).not.toHaveBeenCalled()+ expect(logic.values.featureFlag).toMatchObject({+ name: 'Renamed elsewhere',+ version: 4,+ filters: changedElsewhere.filters,+ })+ expect(logic.values.hasUnsavedChanges).toBe(false)+ })++ it('carries the row version when toggling active and when archiving', async () => {+ const update = jest.spyOn(api, 'update').mockImplementation(async (_url, payload: any) => ({+ ...V2_FLAG,+ ...payload,+ version: payload.version + 1,+ }))++ logic.actions.updateFeatureFlagActive(true)+ await expectLogic(logic).toDispatchActions(['updateFeatureFlagActiveSuccess'])+ expect(update).toHaveBeenLastCalledWith(expect.stringContaining('/feature_flags/7'), {+ active: true,+ version: 3,+ })++ logic.actions.updateFeatureFlagArchived({ archived: true })+ await expectLogic(logic).toDispatchActions(['updateFeatureFlagArchivedSuccess'])+ expect(update).toHaveBeenLastCalledWith(expect.stringContaining('/feature_flags/7'), {+ archived: true,+ active: false,+ version: 4,+ })+ })++ it('offers early access creation only for a v1 document', () => {+ expect(logic.values.canCreateEarlyAccessFeature).toBe(false)++ logic.actions.setFeatureFlag({ ...V2_FLAG, filters: { groups: [] } })+ expect(logic.values.canCreateEarlyAccessFeature).toBe(true)+ })++ it('offers only disable in the disable confirmation, sending the row version', async () => {+ const dialogOpenSpy = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const update = jest+ .spyOn(api, 'update')+ .mockImplementation(async (_url, payload) => ({ ...V2_FLAG, ...(payload as object) }))+ logic.actions.setFeatureFlag({ ...V2_FLAG, active: true })+ logic.actions.setOriginalFeatureFlag({ ...V2_FLAG, active: true })++ await expectLogic(logic, () => logic.actions.toggleFeatureFlagActive(false)).toFinishAllListeners()++ const dialogProps = dialogOpenSpy.mock.calls[0][0]+ expect(dialogProps.secondaryButton).toBeNull()+ dialogProps.primaryButton?.onClick?.(undefined as any)+ await expectLogic(logic).toFinishAllListeners()+ expect(update).toHaveBeenCalledWith(expect.stringContaining('/feature_flags/7'), { active: false, version: 3 })+ })++ it('saves sidebar tags as a narrow versioned write, not the full save', async () => {+ const update = jest+ .spyOn(api, 'update')+ .mockImplementation(async (_url, payload) => ({ ...V2_FLAG, ...(payload as object), version: 4 }))++ logic.actions.saveSidebarTags(['checkout'], [])+ await expectLogic(logic)+ .toDispatchActions(['saveTagsInline'])+ .toNotHaveDispatchedActions(['saveFeatureFlag'])+ .toFinishAllListeners()++ expect(update).toHaveBeenCalledTimes(1)+ expect(update).toHaveBeenCalledWith(expect.stringContaining('/feature_flags/7'), {+ tags: ['checkout'],+ version: 3,+ })+ })++ it.each([+ ['tags', () => logic.actions.saveTagsInline(['checkout'])],+ ['description', () => logic.actions.saveDescriptionInline('Checkout redesign')],+ ])('takes the row version its inline %s save produced, so the next write is not stale', async (_, save) => {+ const update = jest+ .spyOn(api, 'update')+ .mockImplementation(async (_url, payload) => ({ ...V2_FLAG, ...(payload as object), version: 4 }))++ save()+ await expectLogic(logic).toFinishAllListeners()++ expect(update).toHaveBeenCalledWith(+ expect.stringContaining('/feature_flags/7'),+ expect.objectContaining({ version: 3 })+ )+ expect(logic.values.rowVersionToken).toEqual({ version: 4 })+ expect(logic.values.originalFeatureFlag?.version).toBe(4)+ })++ it.each([+ ['tags', () => logic.actions.saveTagsInline(['checkout'])],+ ['description', () => logic.actions.saveDescriptionInline('Checkout redesign')],+ ])('reloads the flag when its inline %s save hits a stale row version', async (_, save) => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [200, { ...V2_FLAG, version: 5 }],+ },+ })+ jest.spyOn(api, 'update').mockRejectedValue({ status: 409, detail: 'This feature flag has changed.' })++ save()+ await expectLogic(logic)+ .toDispatchActions(['refreshFeatureFlag', 'refreshFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(logic.values.rowVersionToken).toEqual({ version: 5 })+ })++ it.each([+ ['tags', () => logic.actions.saveTagsInline(['checkout'])],+ ['description', () => logic.actions.saveDescriptionInline('Checkout redesign')],+ ])('keeps a v1 flag on its loaded row version after an inline %s save', async (_, save) => {+ // A v1 full save sends the loaded version, and a stale one makes the server drop the fields this page did not change.+ const V1_FLAG = { ...V2_FLAG, filters: { groups: [] } }+ logic.actions.setFeatureFlag(V1_FLAG)+ logic.actions.setOriginalFeatureFlag(V1_FLAG)+ jest.spyOn(api, 'update').mockImplementation(async (_url, payload) => ({+ ...V1_FLAG,+ ...(payload as object),+ version: 4,+ }))++ save()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.featureFlag.version).toBe(3)+ expect(logic.values.originalFeatureFlag?.version).toBe(3)+ })++ const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))++ it('sends a tag save made while another is in flight with the version that save returned', async () => {+ const firstResponse = deferred()+ const update = jest.spyOn(api, 'update').mockImplementation(async (_url, payload: any) => {+ if (update.mock.calls.length === 1) {+ await firstResponse.promise+ }+ return { ...V2_FLAG, ...payload, version: payload.version + 1 }+ })++ logic.actions.saveTagsInline(['checkout'])+ await wait(300)+ expect(update).toHaveBeenCalledTimes(1)+ // The second save passes its debounce while the first request is still open.+ logic.actions.saveTagsInline(['checkout', 'pricing'])+ await wait(300)+ firstResponse.resolve()+ await expectLogic(logic).toFinishAllListeners()++ expect(update.mock.calls.map(([, payload]) => payload)).toEqual([+ { tags: ['checkout'], version: 3 },+ { tags: ['checkout', 'pricing'], version: 4 },+ ])+ expect(logic.values.featureFlag).toMatchObject({ tags: ['checkout', 'pricing'], version: 5 })+ expect(lemonToast.error).not.toHaveBeenCalled()+ })++ it.each([+ [+ 'a description save',+ 'a tag save',+ () => logic.actions.saveTagsInline(['checkout']),+ () => logic.actions.saveDescriptionInline('Checkout redesign'),+ ],+ [+ 'a tag save',+ 'a description save',+ () => logic.actions.saveDescriptionInline('Checkout redesign'),+ () => logic.actions.saveTagsInline(['checkout']),+ ],+ ])('sends %s made while %s is in flight with the version that save returned', async (_, __, first, second) => {+ const firstResponse = deferred()+ const update = jest.spyOn(api, 'update').mockImplementation(async (_url, payload: any) => {+ if (update.mock.calls.length === 1) {+ await firstResponse.promise+ }+ return { ...V2_FLAG, ...payload, version: payload.version + 1 }+ })++ first()+ await wait(300)+ second()+ await wait(300)+ firstResponse.resolve()+ await expectLogic(logic).toFinishAllListeners()++ expect(update.mock.calls.map(([, payload]) => (payload as any).version)).toEqual([3, 4])+ // Each save's response leaves the other save's field alone.+ expect(logic.values.featureFlag).toMatchObject({ name: 'Checkout redesign', tags: ['checkout'], version: 5 })+ expect(lemonToast.error).not.toHaveBeenCalled()+ })++ it('keeps the first tag save when the save queued behind it is refused', async () => {+ const detail = 'Keep at least one tag. This project requires feature flags to stay tagged.'+ const firstResponse = deferred()+ const update = jest.spyOn(api, 'update').mockImplementation(async (_url, payload: any) => {+ if (update.mock.calls.length > 1) {+ throw new ApiError(undefined, 400, undefined, { detail })+ }+ await firstResponse.promise+ return { ...V2_FLAG, ...payload, version: payload.version + 1 }+ })++ logic.actions.saveTagsInline(['checkout'])+ await wait(300)+ logic.actions.saveTagsInline([])+ await wait(300)+ firstResponse.resolve()+ await expectLogic(logic).toFinishAllListeners()++ expect(update.mock.calls.map(([, payload]) => payload)).toEqual([+ { tags: ['checkout'], version: 3 },+ { tags: [], version: 4 },+ ])+ expect(logic.values.featureFlag).toMatchObject({ tags: ['checkout'], version: 4 })+ expect(logic.values.originalFeatureFlag).toMatchObject({ tags: ['checkout'], version: 4 })+ expect(lemonToast.error).toHaveBeenCalledWith(detail)+ })++ it('starts a blank flag when a duplicate link names this flag', async () => {+ defaultReleaseConditionsLogic.actions.loadDefaultReleaseConditionsSuccess({+ enabled: false,+ default_groups: [],+ })+ router.actions.push(`${urls.featureFlag('new')}?sourceId=7`)+ const newLogic = featureFlagLogic({ id: 'new' })+ newLogic.mount()+ await expectLogic(newLogic).toFinishAllListeners()++ expect(lemonToast.error).toHaveBeenCalledWith("This flag's configuration format can't be duplicated yet.")+ expect(newLogic.values.configFormat).toBe('v1')+ expect(newLogic.values.featureFlag.key).toBe('')+ expect(router.values.searchParams.sourceId).toBeUndefined()+ newLogic.unmount()+ })+})diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 9dfa41d5cacf..ae15f6af0955 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -5,6 +5,7 @@ import {afterMount,beforeUnmount,connect,+ isBreakpoint,kea,key,listeners,@@ -67,6 +68,7 @@ import {FeatureFlagGroupType,FeatureFlagStatus,FeatureFlagType,+ FeatureFlagWithV1Config,FilterLogicalOperator,InsightModel,JsonType,@@ -87,11 +89,20 @@ import {} from '~/types'import { NEW_EARLY_ACCESS_FEATURE } from 'products/early_access_features/frontend/earlyAccessFeatureLogic'+import {+ FeatureFlagConfigFormat,+ STALE_ROW_VERSION_RELOADED_MESSAGE,+ featureFlagConfigFormat,+ isStaleRowVersionError,+ isV1FeatureFlagConfig,+ rowVersionToken,+} from 'products/feature_flags/frontend/featureFlagConfigFormat'import { TEMPLATE_NAMES } from 'products/feature_flags/frontend/featureFlagTemplateConstants'import {featureFlagsCopyFlagsCreate,featureFlagsCopyFlagsDependencyRequirementsCreate,featureFlagsList,+ featureFlagsRetrieve,featureFlagsStatusRetrieve,} from 'products/feature_flags/frontend/generated/api'import type {@@ -376,7 +387,7 @@ export const PAIRED_PRESETS: Record<Exclude<PairedPresetKey, 'custom_pair'>, Pai* then collapsed behind a button when the flag already has a plan to read. */export type ScheduleFormState = 'loading' | 'collapsed' | 'expanded'-export type ScheduleFlagPayload = Pick<FeatureFlagType, 'filters' | 'active'> & {+export type ScheduleFlagPayload = Pick<FeatureFlagWithV1Config, 'filters' | 'active'> & {variants?: MultivariateFlagVariant[]payloads?: Record<string, any>}@@ -391,7 +402,7 @@ export interface DependentFlag {name: string}-export const NEW_FLAG: FeatureFlagType = {+export const NEW_FLAG: FeatureFlagWithV1Config = {id: null,created_at: null,updated_at: null,@@ -645,7 +656,7 @@ async function copyNewFlagToAdditionalProjects(// This doesn't work for forms because variant-keys can be updated too which would invalidate the dictionary entry.// If a multivariant flag is returned, the payload dictionary will be transformed to be <variant-key-index>: <payload>export const variantKeyToIndexFeatureFlagPayloads = (flag: FeatureFlagType): FeatureFlagType => {- if (!flag.filters.multivariate) {+ if (!isV1FeatureFlagConfig(flag.filters) || !flag.filters.multivariate) {return flag}@@ -686,6 +697,9 @@ export const convertIndexBasedPayloadsToVariantKeys = (}export const indexToVariantKeyFeatureFlagPayloads = (flag: Partial<FeatureFlagType>): Partial<FeatureFlagType> => {+ if (flag.filters && !isV1FeatureFlagConfig(flag.filters)) {+ return flag+ }if (flag.filters?.multivariate) {const newPayloads = convertIndexBasedPayloadsToVariantKeys(flag.filters.multivariate.variants,@@ -722,6 +736,9 @@ const reorderVariantState = (fromIndex: number,toIndex: number): FeatureFlagType => {+ if (!isV1FeatureFlagConfig(state.filters)) {+ return state+ }// Create new variants array with reordered elementsconst newVariants = [...variants]const [movedVariant] = newVariants.splice(fromIndex, 1)@@ -836,8 +853,28 @@ export const getRecordingFilterForFlagVariant = (}}+// The conflicting write may have replaced the whole document, so a stale row version reloads the flag.+function reloadIfStaleRowVersion(token: { version?: number }, error: any, reload: () => void): boolean {+ if (!isStaleRowVersionError(token, error)) {+ return false+ }+ lemonToast.error(error?.detail || STALE_ROW_VERSION_RELOADED_MESSAGE)+ reload()+ return true+}++// A v2 write must carry the row version the previous write returned, so inline saves go out one at a time.+function queueInlineSave<T>(cache: Record<string, any>, send: () => Promise<T>): Promise<T> {+ const request = (cache.inlineSaveQueue ?? Promise.resolve()).catch(() => null).then(send)+ cache.inlineSaveQueue = request+ return request+}+function cleanFlag(flag: Partial<FeatureFlagType>): Partial<FeatureFlagType> {const { created_at, id, created_by, last_modified_by, ...cleanedFlag } = flag+ if (cleanedFlag.filters && !isV1FeatureFlagConfig(cleanedFlag.filters)) {+ return cleanedFlag+ }return {...cleanedFlag,filters: {@@ -912,6 +949,7 @@ export interface featureFlagLogicValues {canCreateEarlyAccessFeature: booleancanCreatePairedSchedule: booleancompletedSchedules: ScheduledChangeType[]+ configFormat: FeatureFlagConfigFormatcopyDependencies: booleancopyDependencyRequirements: CopyFlagsDependencyRequirementsResponseApi | nullcopyDependencyRequirementsLoading: boolean@@ -1080,6 +1118,9 @@ export interface featureFlagLogicValues {relatedInsightsLoading: booleanrepeatsValue: RecurrenceInterval | 'cron' | 'none'roleBasedAccessEnabled: boolean+ rowVersionToken: {+ version?: number+ }scheduleDateMarker: anyscheduleDefaultsAppliedFromFlag: booleanscheduleFormCollapsible: boolean@@ -1104,7 +1145,7 @@ export interface featureFlagLogicValues {templateExpanded: booleantemplates: Array<{description: string- getValues: (flag: FeatureFlagType) => Partial<FeatureFlagType>+ getValues: (filters: FeatureFlagFilters) => Partial<FeatureFlagType>id: stringname: string}>@@ -1578,6 +1619,13 @@ export interface featureFlagLogicActions {featureFlag: FeatureFlagTypepayload?: Partial<FeatureFlagType>}+ saveSidebarTags: (+ tags: string[],+ evaluationContexts?: string[]+ ) => {+ evaluationContexts: string[] | undefined+ tags: string[]+ }saveTagsInline: (tags: string[]) => {tags: string[]}@@ -1622,7 +1670,7 @@ export interface featureFlagLogicActions {featureFlag: FeatureFlagType}setFeatureFlagFilters: (- filters: FeatureFlagType['filters'],+ filters: FeatureFlagFilters,errors: any) => {errors: any@@ -1759,7 +1807,7 @@ export interface featureFlagLogicActions {expanded: boolean}setSchedulePayload: (- filters: FeatureFlagType['filters'] | null,+ filters: FeatureFlagFilters | null,active: FeatureFlagType['active'] | null,errors?: any,variants?: MultivariateFlagVariant[] | null,@@ -2094,6 +2142,10 @@ export interface featureFlagLogicMeta {__keaTypeGenInternalSelectorTypes: {props: (arg: any) => anyavailableTabs: (featureFlag: FeatureFlagType, props: any) => FeatureFlagsTab[]+ configFormat: (featureFlag: FeatureFlagType) => FeatureFlagConfigFormat+ rowVersionToken: (featureFlag: FeatureFlagType) => {+ version?: number+ }activeTab: (selectedTab: FeatureFlagsTab, availableTabs: FeatureFlagsTab[]) => FeatureFlagsTabhasUnsavedChanges: (featureFlag: FeatureFlagType, originalFeatureFlag: FeatureFlagType | null) => booleanisFormDirty: (@@ -2182,7 +2234,7 @@ export interface featureFlagLogicMeta {emailDomain: (user: UserType | null) => stringtemplates: (emailDomain: string) => Array<{description: string- getValues: (flag: FeatureFlagType) => Partial<FeatureFlagType>+ getValues: (filters: FeatureFlagFilters) => Partial<FeatureFlagType>id: stringname: string}>@@ -2236,7 +2288,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// Only dispatch with server-authoritative state, so in-progress edits stay dirty.setOriginalFeatureFlag: (featureFlag: FeatureFlagType | null) => ({ featureFlag }),refreshFeatureFlagAfterAgentChange: true,- setFeatureFlagFilters: (filters: FeatureFlagType['filters'], errors: any) => ({ filters, errors }),+ setFeatureFlagFilters: (filters: FeatureFlagFilters, errors: any) => ({ filters, errors }),setSelectedTab: (tab: FeatureFlagsTab) => ({ tab }),setFeatureFlagMissing: true,deleteFeatureFlag: (featureFlag: Partial<FeatureFlagType>) => ({ featureFlag }),@@ -2270,7 +2322,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([setScheduleFormExpanded: (expanded: boolean) => ({ expanded }),resetScheduleFormExpanded: true,setSchedulePayload: (- filters: FeatureFlagType['filters'] | null,+ filters: FeatureFlagFilters | null,active: FeatureFlagType['active'] | null,errors?: any,variants?: MultivariateFlagVariant[] | null,@@ -2307,6 +2359,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}) => payload,saveDescriptionInline: (name: string) => ({ name }),saveTagsInline: (tags: string[]) => ({ tags }),+ saveSidebarTags: (tags: string[], evaluationContexts?: string[]) => ({ tags, evaluationContexts }),// V2 form UI actionssetShowImplementation: (show: boolean) => ({ show }),setOpenVariants: (openVariants: string[]) => ({ openVariants }),@@ -2417,7 +2470,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},setMultivariateOptions: (state, { multivariateOptions }) => {- if (!state) {+ if (!state || !isV1FeatureFlagConfig(state.filters)) {return state}const variantsSet = new Set(multivariateOptions?.variants.map((variant) => variant.key))@@ -2457,7 +2510,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},resetEncryptedPayload: (state) => {- if (!state) {+ if (!state || !isV1FeatureFlagConfig(state.filters)) {return state}@@ -2471,7 +2524,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},addVariant: (state) => {- if (!state) {+ if (!state || !isV1FeatureFlagConfig(state.filters)) {return state}const variants = [...(state.filters.multivariate?.variants || [])]@@ -2487,7 +2540,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},removeVariant: (state, { index }) => {- if (!state) {+ if (!state || !isV1FeatureFlagConfig(state.filters)) {return state}const variants = [...(state.filters.multivariate?.variants || [])]@@ -2559,7 +2612,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([distributeVariantsEqually: (state) => {// Adjust the variants to be as evenly distributed as possible,// taking integer rounding into account- if (!state) {+ if (!state || !isV1FeatureFlagConfig(state.filters)) {return state}const variants = [...(state.filters.multivariate?.variants || [])]@@ -3020,9 +3073,19 @@ export const featureFlagLogic = kea<featureFlagLogicType>([loadFeatureFlag: async () => {const sourceId = router.values.searchParams.sourceId- if (props.id === 'new' && sourceId) {- // Used when "duplicating a feature flag". This populates the form with the source flag's data.- const sourceFlag = await api.featureFlags.get(sourceId)+ // Used when "duplicating a feature flag". This populates the form with the source flag's data.+ const sourceFlag =+ props.id === 'new' && sourceId+ ? ((await featureFlagsRetrieve(+ String(values.currentProjectId),+ Number(sourceId)+ )) as unknown as FeatureFlagType)+ : null+ if (sourceFlag && !isV1FeatureFlagConfig(sourceFlag.filters)) {+ // The form edits only v1 documents, so a duplicate link to another version starts a blank flag.+ lemonToast.error("This flag's configuration format can't be duplicated yet.")+ router.actions.replace(router.values.location.pathname)+ } else if (sourceFlag) {// But first, remove fields that we don't want to duplicateconst {id,@@ -3280,7 +3343,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.const savedFlag = await api.update(`api/projects/${values.currentProjectId}/feature_flags/${values.featureFlag.id}`,- { active }+ { active, ...values.rowVersionToken })savedFlag.id && refreshTreeItem('feature_flag', String(savedFlag.id))return variantKeyToIndexFeatureFlagPayloads(savedFlag)@@ -3301,7 +3364,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.const savedFlag = await api.update(`api/projects/${values.currentProjectId}/feature_flags/${values.featureFlag.id}`,- archived ? { archived: true, active: false } : { archived: false }+ archived+ ? { archived: true, active: false, ...values.rowVersionToken }+ : { archived: false, ...values.rowVersionToken })savedFlag.id && refreshTreeItem('feature_flag', String(savedFlag.id))if (archived && via) {@@ -3911,6 +3976,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([})},updateFeatureFlagActiveFailure: ({ errorObject }) => {+ if (reloadIfStaleRowVersion(values.rowVersionToken, errorObject, actions.refreshFeatureFlag)) {+ return+ }if (values.featureFlag.id && handleApprovalRequired(errorObject, 'feature_flag', values.featureFlag.id)) {return}@@ -4014,7 +4082,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},toggleProjectFlagActive: async ({ teamId, flagId, active }) => {- const updatedFlag = await updateFlagActiveInProject({ teamId, flagId, active })+ const row = values.projectsWithCurrentFlag.find((p) => p.team_id === teamId && p.flag_id === flagId)+ const updatedFlag = await updateFlagActiveInProject({+ teamId,+ flagId,+ active,+ filters: row?.filters,+ })if (!updatedFlag) {actions.projectFlagActiveUpdateFailed(teamId, flagId)return@@ -4065,7 +4139,12 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// Replacing the whole flag would discard an edit made during the request and re-baseline// over it, leaving the guard clean. An agent change on a clean form is the one refresh// safe to take whole, and it has to be: it can have rewritten any field.- if (!baseline || (afterAgentChange && !values.isFormDirty)) {+ // A row in another config version never has form edits to keep, so it always takes the whole refresh.+ if (+ !baseline ||+ !isV1FeatureFlagConfig(values.featureFlag.filters) ||+ (afterAgentChange && !values.isFormDirty)+ ) {actions.setFeatureFlag(featureFlagRefresh)actions.setOriginalFeatureFlag(toFeatureFlagBaseline(featureFlagRefresh))} else {@@ -4149,6 +4228,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},updateFeatureFlagArchivedFailure: ({ errorObject }) => {+ if (reloadIfStaleRowVersion(values.rowVersionToken, errorObject, actions.refreshFeatureFlag)) {+ return+ }// Archiving an enabled flag also disables it, which can trip the approval gate (409).// Surface the change-request flow instead of silently doing nothing.if (values.featureFlag.id && handleApprovalRequired(errorObject, 'feature_flag', values.featureFlag.id)) {@@ -4237,10 +4319,10 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},applyTemplate: async ({ templateId }, breakpoint) => {const template = values.templates.find((t) => t.id === templateId)- if (!template || !values.featureFlag) {+ if (!template || !values.featureFlag || !isV1FeatureFlagConfig(values.featureFlag.filters)) {return}- const templateValues = template.getValues(values.featureFlag)+ const templateValues = template.getValues(values.featureFlag.filters)const defaultConfig = await resolveDefaultReleaseConditions(values.defaultReleaseConditions,@@ -4461,7 +4543,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},setRemoteConfigEnabled: ({ enabled }) => {- if (enabled) {+ if (enabled && isV1FeatureFlagConfig(values.featureFlag.filters)) {actions.setFeatureFlagFilters({...values.featureFlag.filters,@@ -4483,23 +4565,31 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},saveDescriptionInline: async ({ name }) => {- const flag = values.featureFlag- if (!flag.id || name === flag.name) {+ const flagId = values.featureFlag.id+ if (!flagId || name === values.featureFlag.name) {return}try {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.- const savedFlag = await api.update(`api/projects/${values.currentProjectId}/feature_flags/${flag.id}`, {- name,- })- actions.setFeatureFlag({ ...flag, name: savedFlag.name })+ const savedFlag = await queueInlineSave(cache, () =>+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.+ api.update(`api/projects/${values.currentProjectId}/feature_flags/${flagId}`, {+ name,+ ...values.rowVersionToken,+ })+ )+ // A v1 page keeps the version it loaded. A later full save then sends a version behind the+ // stored row, so the server's stale-write check drops the fields this page did not change.+ const persisted = { name: savedFlag.name, ...rowVersionToken(savedFlag) }+ actions.setFeatureFlag({ ...values.featureFlag, ...persisted })if (values.originalFeatureFlag) {- actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, name: savedFlag.name })+ actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, ...persisted })}- actions.updateFlag({ ...flag, name: savedFlag.name })+ actions.updateFlag({ ...values.featureFlag, ...persisted })lemonToast.success('Description saved')- } catch {- lemonToast.error('Failed to save description')+ } catch (error: any) {+ if (!reloadIfStaleRowVersion(values.rowVersionToken, error, actions.refreshFeatureFlag)) {+ lemonToast.error(error?.detail || 'Failed to save description')+ }}},saveTagsInline: async ({ tags }, breakpoint) => {@@ -4526,43 +4616,71 @@ export const featureFlagLogic = kea<featureFlagLogicType>([await breakpoint(250)try {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.- const savedFlag = await api.update(`api/projects/${values.currentProjectId}/feature_flags/${flag.id}`, {- tags,+ const savedFlag = await queueInlineSave(cache, () => {+ breakpoint()+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.+ return api.update(`api/projects/${values.currentProjectId}/feature_flags/${flag.id}`, {+ tags,+ ...values.rowVersionToken,+ })})+ // Store the bumped row version before the breakpoint, because a newer call's write needs it.+ const savedVersion = rowVersionToken(savedFlag)+ if (savedVersion.version !== undefined) {+ actions.setFeatureFlag({ ...values.featureFlag, ...savedVersion })+ if (values.originalFeatureFlag) {+ actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, ...savedVersion })+ }+ }// If the listener has been invoked again since this await started, bail out// — the newer call owns reconciliation.breakpoint()- // Reconcile with server only if the *set* of tags differs (e.g. server-side- // normalization added/removed a tag). Avoid blindly overwriting — the- // server may return tags in a different order which would re-shuffle chips.+ // Keep the local tags when the server returns the same set, because the server may reorder them+ // and that would reshuffle the chips. Take the server's tags when the set differs, e.g. after+ // server-side normalization.const localSet = new Set(tags)const serverTags = savedFlag.tags ?? []const serverSet = new Set(serverTags)const setsEqual = localSet.size === serverSet.size && tags.every((t) => serverSet.has(t))- if (!setsEqual) {- actions.setFeatureFlag({ ...flag, tags: serverTags })- if (values.originalFeatureFlag) {- actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, tags: serverTags })- }- actions.updateFlag({ ...flag, tags: serverTags })+ const persisted = { tags: setsEqual ? tags : serverTags }+ actions.setFeatureFlag({ ...values.featureFlag, ...persisted })+ if (values.originalFeatureFlag) {+ actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, ...persisted })}+ actions.updateFlag({ ...values.featureFlag, ...persisted })} catch (error: any) {// Re-throw breakpoint cancellation so kea swallows it silently.- if (error?.isBreakpoint) {+ if (isBreakpoint(error)) {throw error}- actions.setFeatureFlag({ ...flag, tags: previousTags })+ // Roll back the tags only: the page may hold a newer row version than when this call started.+ actions.setFeatureFlag({ ...values.featureFlag, tags: previousTags })if (values.originalFeatureFlag) {actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, tags: previousTags })}- actions.updateFlag({ ...flag, tags: previousTags })+ actions.updateFlag({ ...values.featureFlag, tags: previousTags })// The server explains rule failures such as a project that requires tags, so show// its message rather than a generic one the user cannot act on.- lemonToast.error(error?.detail || 'Failed to save tags')+ if (!reloadIfStaleRowVersion(values.rowVersionToken, error, actions.refreshFeatureFlag)) {+ lemonToast.error(error?.detail || 'Failed to save tags')+ }}},+ saveSidebarTags: ({ tags, evaluationContexts }) => {+ // The full save sends every loaded field, and a row in another config version refuses most of them.+ if (values.configFormat !== 'v1') {+ actions.saveTagsInline(tags)+ return+ }+ const updatedFlag = {+ ...values.featureFlag,+ tags,+ ...(evaluationContexts ? { evaluation_contexts: evaluationContexts } : {}),+ }+ actions.updateFlag(updatedFlag)+ actions.saveFeatureFlag(updatedFlag)+ },editFeatureFlag: async ({ editing }) => {if (editing) {actions.loadFeatureFlag()@@ -4648,8 +4766,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([(s) => [s.featureFlag, s.props],(featureFlag: FeatureFlagType, props: FeatureFlagLogicProps): FeatureFlagsTab[] => {const tabs = [FeatureFlagsTab.OVERVIEW]+ // Projects (copy), Schedule and Testing read or rewrite the v1 document.+ const v1 = isV1FeatureFlagConfig(featureFlag.filters)if (props.id) {- tabs.push(FeatureFlagsTab.USAGE, FeatureFlagsTab.PROJECTS, FeatureFlagsTab.SCHEDULE)+ tabs.push(FeatureFlagsTab.USAGE)+ if (v1) {+ tabs.push(FeatureFlagsTab.PROJECTS, FeatureFlagsTab.SCHEDULE)+ }}if (featureFlag.id) {tabs.push(FeatureFlagsTab.HISTORY)@@ -4658,12 +4781,20 @@ export const featureFlagLogic = kea<featureFlagLogicType>([tabs.push(FeatureFlagsTab.PERMISSIONS)}tabs.push(FeatureFlagsTab.FEEDBACK, FeatureFlagsTab.EXPERIMENTS)- if (props.id) {+ if (props.id && v1) {tabs.push(FeatureFlagsTab.TESTING)}return tabs},],+ configFormat: [+ (s) => [s.featureFlag],+ (featureFlag: FeatureFlagType): FeatureFlagConfigFormat => featureFlagConfigFormat(featureFlag.filters),+ ],+ rowVersionToken: [+ (s) => [s.featureFlag],+ (featureFlag: FeatureFlagType): { version?: number } => rowVersionToken(featureFlag),+ ],// Clamped in a selector rather than in urlToAction so it re-derives when the flag// loads (a deep-linked tab can arrive before `can_edit` is known)activeTab: [@@ -4830,7 +4961,12 @@ export const featureFlagLogic = kea<featureFlagLogicType>([canCreateEarlyAccessFeature: [(s) => [s.featureFlag, s.variants],(featureFlag: FeatureFlagType, variants: MultivariateFlagVariant[]) => {- return featureFlag && featureFlag.filters.aggregation_group_type_index == null && variants.length === 0+ return (+ featureFlag &&+ isV1FeatureFlagConfig(featureFlag.filters) &&+ featureFlag.filters.aggregation_group_type_index == null &&+ variants.length === 0+ )},],hasSurveys: [@@ -5043,17 +5179,17 @@ export const featureFlagLogic = kea<featureFlagLogicType>([id: stringname: stringdescription: string- getValues: (flag: FeatureFlagType) => Partial<FeatureFlagType>+ getValues: (filters: FeatureFlagFilters) => Partial<FeatureFlagType>}> => [{id: 'simple',name: TEMPLATE_NAMES.simple,description: 'On/off for all users',- getValues: (flag) => ({+ getValues: (filters) => ({key: 'my-feature',is_remote_configuration: false,filters: {- ...flag.filters,+ ...filters,multivariate: null,groups: [{ properties: [], rollout_percentage: 0, variant: null }],},@@ -5063,11 +5199,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([id: 'targeted',name: TEMPLATE_NAMES.targeted,description: 'Release to specific users',- getValues: (flag) => ({+ getValues: (filters) => ({key: 'targeted-release',is_remote_configuration: false,filters: {- ...flag.filters,+ ...filters,multivariate: null,groups: [{@@ -5090,11 +5226,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([id: 'multivariate',name: TEMPLATE_NAMES.multivariate,description: 'Multiple variants',- getValues: (flag) => ({+ getValues: (filters) => ({key: 'multivariate-flag',is_remote_configuration: false,filters: {- ...flag.filters,+ ...filters,multivariate: {variants: [{ key: 'control', rollout_percentage: 50 },@@ -5109,11 +5245,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([id: 'targeted-multivariate',name: TEMPLATE_NAMES['targeted-multivariate'],description: 'Variants for specific users',- getValues: (flag) => ({+ getValues: (filters) => ({key: 'targeted-multivariate',is_remote_configuration: false,filters: {- ...flag.filters,+ ...filters,multivariate: {variants: [{ key: 'control', rollout_percentage: 50 },diff --git a/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsx b/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsxindex fb45e3725c59..283f738bf598 100644--- a/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsx+++ b/frontend/src/scenes/feature-flags/featureFlagNotebookWidgetViews.tsx@@ -11,6 +11,12 @@ import { NotebookNodeProps } from 'scenes/notebooks/types'import { FeatureFlagType } from '~/types'+import {+ featureFlagConfigFormatLabel,+ isV1FeatureFlagConfig,+} from 'products/feature_flags/frontend/featureFlagConfigFormat'+import { FeatureFlagConfigReadonlyNotice } from 'products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice'+import { FeatureFlagCodeExample } from './FeatureFlagCodeExample'import { FeatureFlagLogicProps, featureFlagLogic } from './featureFlagLogic'import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'@@ -120,19 +126,22 @@ function FeatureFlagCompactSummary({}function FeatureFlagCompactSummaryContent({ featureFlag }: LoadedFeatureFlagWidgetProps): JSX.Element {+ const isV1Config = isV1FeatureFlagConfig(featureFlag.filters)const conditionCount = featureFlag.filters.groups?.length ?? 0const variantCount = featureFlag.filters.multivariate?.variants?.length ?? 0- const flagType = featureFlag.is_remote_configuration- ? 'Remote config'- : variantCount > 0- ? 'Multivariate'- : 'Boolean'+ const flagType = !isV1Config+ ? featureFlagConfigFormatLabel(featureFlag.filters)+ : featureFlag.is_remote_configuration+ ? 'Remote config'+ : variantCount > 0+ ? 'Multivariate'+ : 'Boolean'return (<div className="flex flex-wrap items-center gap-2 p-3">{featureFlag.name ? <span className="min-w-48 flex-1 truncate">{featureFlag.name}</span> : null}<LemonTag type="muted">{flagType}</LemonTag>- {!featureFlag.is_remote_configuration ? (+ {isV1Config && !featureFlag.is_remote_configuration ? (<span className="text-xs text-secondary">{conditionCount} release {conditionCount === 1 ? 'condition' : 'conditions'}</span>@@ -157,7 +166,9 @@ function FeatureFlagReleaseConditionsWidget({return (<BindLogic logic={featureFlagLogic} props={{ id }}><div className="p-3">- {featureFlag.is_remote_configuration ? (+ {!isV1FeatureFlagConfig(featureFlag.filters) ? (+ <FeatureFlagConfigReadonlyNotice filters={featureFlag.filters} />+ ) : featureFlag.is_remote_configuration ? (<div className="text-sm text-secondary">Remote config flags do not use release conditions.</div>) : (<FeatureFlagReleaseConditionsCollapsible id={String(id)} filters={featureFlag.filters} readOnly />@@ -219,7 +230,9 @@ function FeatureFlagCompactEditor({ attributes }: NotebookNodeProps<FeatureFlagNreturn (<BindLogic logic={featureFlagLogic} props={{ id }}><div className="flex flex-col gap-3 p-3">- {featureFlag.is_remote_configuration ? (+ {!isV1FeatureFlagConfig(featureFlag.filters) ? (+ <FeatureFlagConfigReadonlyNotice filters={featureFlag.filters} />+ ) : featureFlag.is_remote_configuration ? (<div className="rounded border border-dashed p-3 text-sm text-secondary">Open the feature flag to edit its remote config payload.</div>@@ -238,7 +251,7 @@ function FeatureFlagCompactEditor({ attributes }: NotebookNodeProps<FeatureFlagN/>)}- {!featureFlag.is_remote_configuration ? (+ {isV1FeatureFlagConfig(featureFlag.filters) && !featureFlag.is_remote_configuration ? (<div className="flex justify-end gap-2 border-t pt-3"><LemonButtontype="secondary"diff --git a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.tsindex 31d461a8b8d1..1c44156d9fa3 100644--- a/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagReleaseConditionsLogic.test.ts@@ -8,8 +8,8 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import {AnyPropertyFilter,+ FeatureFlagFilters,FeatureFlagGroupType,- FeatureFlagType,FlagPropertyFilter,MultivariateFlagOptions,PropertyFilterType,@@ -31,7 +31,7 @@ jest.mock('uuid', () => ({function generateFeatureFlagFilters(groups: FeatureFlagGroupType[],multivariate?: MultivariateFlagOptions-): FeatureFlagType['filters'] {+): FeatureFlagFilters {return { groups, multivariate: multivariate ?? null, payloads: {} }}@@ -1506,7 +1506,7 @@ describe('the feature flag release conditions logic', () => {})describe('distinct_id display names', () => {- function distinctIdFilters(value: string | string[]): FeatureFlagType['filters'] {+ function distinctIdFilters(value: string | string[]): FeatureFlagFilters {return generateFeatureFlagFilters([{properties: [@@ -1968,3 +1968,24 @@ describe('the feature flag release conditions logic', () => {})})})++describe('a document in another config version', () => {+ it('does not throw and shows no condition sets', () => {+ const logic = featureFlagReleaseConditionsLogic({+ id: 'rules-v2',+ readOnly: true,+ filters: {+ version: 2,+ return_type: 'boolean',+ default_value: false,+ rules: [],+ } as unknown as FeatureFlagFilters,+ })+ logic.mount()++ expect(logic.values.filterGroups).toEqual([])+ expect(logic.values.properties).toEqual([])++ logic.unmount()+ })+})diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.tsindex 9a6347232b74..63007b6bc032 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts@@ -3,8 +3,10 @@ import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { FEATURE_FLAGS } from 'lib/constants'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'import { NEW_FLAG } from 'scenes/feature-flags/featureFlagLogic'@@ -662,3 +664,115 @@ describe('displayedFlags stability while a load is in flight', () => {expect(logic.values.displayedFlags.map((f) => f.key)).toEqual(['fresh'])})})++describe('rows in config version 2', () => {+ let logic: ReturnType<typeof featureFlagsLogic.build>++ const V1_ROW: FeatureFlagType = { ...NEW_FLAG, id: 1, key: 'release-v1', active: true, version: 4 }+ const V2_ROW: FeatureFlagType = {+ ...NEW_FLAG,+ id: 2,+ key: 'checkout-rules-v2',+ active: false,+ version: 7,+ filters: { version: 2, return_type: 'boolean', default_value: false, rules: [] },+ }++ beforeEach(silenceKeaLoadersErrors)+ afterEach(resumeKeaLoadersErrors)++ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:projectId/feature_flags/': () => [200, { results: [V1_ROW, V2_ROW], count: 2 }],+ '/api/projects/:projectId/feature_flags/2/': () => [200, { ...V2_ROW, version: 8 }],+ },+ })+ initKeaTests()+ logic = featureFlagsLogic()+ logic.mount()+ logic.actions.loadFeatureFlags()+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it('loads a list mixing v1 and v2 rows', () => {+ expect(logic.values.displayedFlags.map((flag) => flag.key)).toEqual(['release-v1', 'checkout-rules-v2'])+ })++ it('sends the row version only when toggling a v2 row', async () => {+ const update = jest+ .spyOn(api, 'update')+ .mockImplementation(async (_url, payload) => ({ ...V2_ROW, ...(payload as object) }))++ logic.actions.updateFeatureFlag({ id: 2, payload: { active: true } })+ logic.actions.updateFeatureFlag({ id: 1, payload: { active: false } })+ await expectLogic(logic).toFinishAllListeners()++ expect(update).toHaveBeenCalledWith(expect.stringContaining('/feature_flags/2'), { active: true, version: 7 })+ expect(update).toHaveBeenCalledWith(expect.stringContaining('/feature_flags/1'), { active: false })+ })++ it('offers archive only for a v1 row when disabling, and disables a v2 row with its version', async () => {+ const openDialog = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const update = jest+ .spyOn(api, 'update')+ .mockImplementation(async (_url, payload) => ({ ...V2_ROW, ...(payload as object) }))++ logic.actions.toggleFeatureFlagActive(1, false)+ logic.actions.toggleFeatureFlagActive(2, false)+ expect(openDialog.mock.calls[0][0].secondaryButton?.children).toBe('Disable and archive')+ expect(openDialog.mock.calls[1][0].secondaryButton).toBeNull()++ openDialog.mock.calls[1][0].primaryButton?.onClick?.(undefined as any)+ await expectLogic(logic).toFinishAllListeners()+ expect(update).toHaveBeenCalledWith(expect.stringContaining('/feature_flags/2'), { active: false, version: 7 })+ })++ it('refetches a v2 row whose version was stale instead of retrying', async () => {+ // The conflicting write replaced the document, so the row must show it, not only its version.+ const changedElsewhere = {+ ...V2_ROW,+ name: 'Renamed elsewhere',+ version: 8,+ filters: { ...V2_ROW.filters, default_value: true },+ }+ useMocks({ get: { '/api/projects/:projectId/feature_flags/2/': () => [200, changedElsewhere] } })+ const detail = 'This feature flag has changed since version 7'+ const update = jest+ .spyOn(api, 'update')+ .mockRejectedValueOnce(new ApiError(undefined, 409, undefined, { detail }))+ const toastError = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')++ logic.actions.updateFeatureFlag({ id: 2, payload: { active: true } })+ await expectLogic(logic).toDispatchActions(['updateFlag', 'updateFeatureFlagFailure']).toFinishAllListeners()++ expect(update).toHaveBeenCalledTimes(1)+ expect(logic.values.featureFlags.results.find((flag) => flag.id === 2)).toEqual(changedElsewhere)+ expect(showApprovalRequiredToast).not.toHaveBeenCalled()+ expect(toastError).toHaveBeenCalledWith(detail)+ })++ it('keeps the stale refusal as the failure when the refetch also fails', async () => {+ useMocks({ get: { '/api/projects/:projectId/feature_flags/2/': () => [500, {}] } })+ const stale = new ApiError(undefined, 409, undefined, {+ detail: 'This feature flag has changed since version 7',+ })+ jest.spyOn(api, 'update').mockRejectedValueOnce(stale)+ jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')++ logic.actions.updateFeatureFlag({ id: 2, payload: { active: true } })+ await expectLogic(logic)+ .toDispatchActions([+ (action) =>+ action.type === logic.actionTypes.updateFeatureFlagFailure && action.payload.errorObject === stale,+ ])+ .toFinishAllListeners()++ expect(logic.values.featureFlags.results.find((flag) => flag.id === 2)).toEqual(V2_ROW)+ })+})diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.tsindex 6aec38f655ff..71af25184aa7 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts@@ -2,7 +2,7 @@ import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers,import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'-import { LemonDialog, PaginationManual } from '@posthog/lemon-ui'+import { LemonDialog, PaginationManual, lemonToast } from '@posthog/lemon-ui'import api, { CountedPaginatedResponse } from 'lib/api'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'@@ -18,6 +18,13 @@ import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { ActivityScope, Breadcrumb, FeatureFlagType } from '~/types'+import {+ STALE_ROW_VERSION_RELOADED_MESSAGE,+ isStaleRowVersionError,+ rowVersionToken,+} from 'products/feature_flags/frontend/featureFlagConfigFormat'+import { featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'+import { FeatureFlagArchivedSource, reportFeatureFlagArchived } from './featureFlagArchiveDialog'import { openFeatureFlagDisableDialog } from './featureFlagDisableDialog'@@ -476,11 +483,12 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([}},updateFeatureFlag: async ({ id, payload }: { id: number; payload: Partial<FeatureFlagType> }) => {+ const versioned = rowVersionToken(values.featureFlags.results.find((flag) => flag.id === id))try {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.const response = await api.update(`api/projects/${values.currentProjectId}/feature_flags/${id}`,- payload+ { ...payload, ...versioned })const updatedFlags = values.featureFlags.results.map((flag) =>flag.id === response.id ? response : flag@@ -497,6 +505,18 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([? 'disable this feature flag': 'update this feature flag'handleFlagApprovalRequired(e, id, actionDescription)+ if (isStaleRowVersionError(versioned, e)) {+ // The global error toast skips every 409, so say why the click seemed to do nothing.+ lemonToast.error(e?.detail || STALE_ROW_VERSION_RELOADED_MESSAGE)+ // The row version we sent is stale: the conflicting write may have replaced the whole+ // document, so take the fresh row whole, not only its version.+ try {+ const fresh = await featureFlagsRetrieve(String(values.currentProjectId), id)+ actions.updateFlag(fresh as unknown as FeatureFlagType)+ } catch {+ // The 409 stays the failure this loader reports.+ }+ }throw e}},@@ -516,7 +536,10 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.const response = await api.update(`api/projects/${values.currentProjectId}/feature_flags/${id}`,- archived ? { archived: true, active: false } : { archived: false }+ {+ ...(archived ? { archived: true, active: false } : { archived: false }),+ ...rowVersionToken(values.featureFlags.results.find((flag) => flag.id === id)),+ })const updatedFlags = values.featureFlags.results.map((flag) =>flag.id === response.id ? response : flag@@ -723,6 +746,7 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([openFeatureFlagDisableDialog({source: 'feature-flags-list',+ filters: values.featureFlags.results.find((flag) => flag.id === id)?.filters,onDisable: () => applyUpdate({ active: false }),onDisableAndArchive: () =>actions.updateFeatureFlagArchived({ id, archived: true, via: 'disable-confirmation' }),diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.tsindex 9a94ff49cd7c..e0670be5067c 100644--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts@@ -301,6 +301,49 @@ describe('projectsGridLogic', () => {expect(logic.values.flags[0].active).toBe(false)})+ it.each([+ { filters: { groups: [] }, calls: ['patch'], body: { active: false } },+ {+ filters: { version: 2, return_type: 'boolean', default_value: false, rules: [] },+ calls: ['get', 'patch'],+ body: { active: false, version: 3 },+ },+ ])(+ 'toggles the representative row before its siblings load, sending $body',+ async ({ filters, calls, body }) => {+ const seen: string[] = []+ let sent: unknown+ useMocks({+ get: {+ '/api/organizations/:org/feature_flags/keys/': {+ count: 1,+ next: null,+ previous: null,+ results: [{ ...buildFlag(5), filters }],+ },+ '/api/projects/:team_id/feature_flags/:id/': () => {+ seen.push('get')+ return [200, { id: 5, filters, version: 3 }]+ },+ },+ patch: {+ '/api/projects/:team_id/feature_flags/:id/': async ({ request }) => {+ seen.push('patch')+ sent = await request.json()+ return [200, { id: 5, active: false }]+ },+ },+ })+ logic.actions.loadFlagsPage({ offset: 0, search: '' })+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.toggleFlagActive('flag_5', 1, 5, false)+ await expectLogic(logic).toDispatchActions(['flagActiveUpdated']).toFinishAllListeners()+ expect(seen).toEqual(calls)+ expect(sent).toEqual(body)+ }+ )+it('clears the in-flight marker and keeps state when the update fails', async () => {await expectLogic(logic).toFinishAllListeners()logic.actions.siblingsLoaded('flag_1', [diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.tsindex cab2889dfff9..2ba256b35f03 100644--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts@@ -358,7 +358,10 @@ export const projectsGridLogic = kea<projectsGridLogicType>([}},toggleFlagActive: async ({ flagKey, teamId, flagId, active }) => {- const updatedFlag = await updateFlagActiveInProject({ teamId, flagId, active })+ const sibling = values.siblingsByFlagKey[flagKey]?.find((s) => s.team_id === teamId && s.flag_id === flagId)+ // Before siblings load, the current team's cell renders from the representative row.+ const row = sibling ?? values.flags.find((f) => f.team_id === teamId && f.id === flagId)+ const updatedFlag = await updateFlagActiveInProject({ teamId, flagId, active, filters: row?.filters })if (updatedFlag) {actions.flagActiveUpdated(flagKey, teamId, flagId, updatedFlag.active ?? active)} else {diff --git a/frontend/src/scenes/feature-flags/updateFlagActiveInProject.test.ts b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.test.tsindex ffda78223a59..d6da47427150 100644--- a/frontend/src/scenes/feature-flags/updateFlagActiveInProject.test.ts+++ b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.test.ts@@ -2,6 +2,7 @@ import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBannimport { dispatchChangeRequestCreated } from 'scenes/approvals/utils'import { useMocks } from '~/mocks/jest'+import { FeatureFlagConfig } from '~/types'import { updateFlagActiveInProject } from './updateFlagActiveInProject'@@ -13,7 +14,58 @@ jest.mock('scenes/approvals/utils', () => ({dispatchChangeRequestCreated: jest.fn(),}))+const V2_FILTERS: FeatureFlagConfig = { version: 2, return_type: 'boolean', default_value: false, rules: [] }+describe('updateFlagActiveInProject', () => {+ it.each([+ { case: 'a v1 row', filters: { groups: [] }, stored: undefined, calls: ['patch'], body: { active: true } },+ {+ case: 'a row in another config version',+ filters: V2_FILTERS,+ stored: V2_FILTERS,+ calls: ['get', 'patch'],+ body: { active: true, version: 9 },+ },+ {+ case: 'a v1 row of unknown format',+ filters: undefined,+ stored: { groups: [] },+ calls: ['get', 'patch'],+ body: { active: true },+ },+ {+ case: 'a v2 row of unknown format',+ filters: undefined,+ stored: V2_FILTERS,+ calls: ['get', 'patch'],+ body: { active: true, version: 9 },+ },+ ])('sends $body for $case', async ({ filters, stored, calls: expectedCalls, body: expectedBody }) => {+ const calls: string[] = []+ let body: unknown+ useMocks({+ get: {+ '/api/projects/:team_id/feature_flags/:id/': () => {+ calls.push('get')+ return [200, { id: 42, active: false, version: 9, filters: stored }]+ },+ },+ patch: {+ '/api/projects/:team_id/feature_flags/:id/': async ({ request }) => {+ calls.push('patch')+ body = await request.json()+ return [200, { id: 42, active: true, version: 10 }]+ },+ },+ })++ const result = await updateFlagActiveInProject({ teamId: 2, flagId: 42, active: true, filters })++ expect(calls).toEqual(expectedCalls)+ expect(body).toEqual(expectedBody)+ expect(result?.version).toBe(10)+ })+it('shows the approval toast with the response code and announces the change request on a 409', async () => {useMocks({patch: {@@ -24,7 +76,7 @@ describe('updateFlagActiveInProject', () => {},})- const result = await updateFlagActiveInProject({ teamId: 2, flagId: 42, active: true })+ const result = await updateFlagActiveInProject({ teamId: 2, flagId: 42, active: true, filters: { groups: [] } })expect(result).toBeNull()expect(showApprovalRequiredToast).toHaveBeenCalledWith(diff --git a/frontend/src/scenes/feature-flags/updateFlagActiveInProject.ts b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.tsindex ba110d929ea9..54c0dbf92560 100644--- a/frontend/src/scenes/feature-flags/updateFlagActiveInProject.ts+++ b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.ts@@ -4,7 +4,10 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'-import { featureFlagsPartialUpdate } from 'products/feature_flags/frontend/generated/api'+import { FeatureFlagConfig } from '~/types'++import { isV1FeatureFlagConfig, rowVersionToken } from 'products/feature_flags/frontend/featureFlagConfigFormat'+import { featureFlagsPartialUpdate, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'import type { FeatureFlagApi } from 'products/feature_flags/frontend/generated/api.schemas'/** Key for the per-row in-flight maps shared by the Projects tab toggles. */@@ -64,14 +67,24 @@ export async function updateFlagActiveInProject({teamId,flagId,active,+ filters,}: {teamId: numberflagId: numberactive: boolean+ filters?: FeatureFlagConfig}): Promise<FeatureFlagApi | null> {const actionDescription = `${active ? 'enable' : 'disable'} this feature flag`try {- const updatedFlag = await featureFlagsPartialUpdate(String(teamId), flagId, { active })+ let versioned: { version?: number } = {}+ if (!(filters && isV1FeatureFlagConfig(filters))) {+ const stored = await featureFlagsRetrieve(String(teamId), flagId)+ versioned = rowVersionToken({+ filters: stored.filters as FeatureFlagConfig | undefined,+ version: stored.version,+ })+ }+ const updatedFlag = await featureFlagsPartialUpdate(String(teamId), flagId, { active, ...versioned })lemonToast.success(`Feature flag ${active ? 'enabled' : 'disabled'}`)return updatedFlag} catch (e: any) {diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsxindex 781a6f884573..b18a914558ff 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeFlag.tsx@@ -17,6 +17,9 @@ import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'import { getNotebookWidgetDefaultView } from 'scenes/notebooks/notebookWidgetCatalog'import { urls } from 'scenes/urls'+import { isV1FeatureFlagConfig } from 'products/feature_flags/frontend/featureFlagConfigFormat'+import { FeatureFlagConfigReadonlyNotice } from 'products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice'+import { NotebookNodeProps, NotebookNodeType } from '../types'import { buildEarlyAccessFeatureContent } from './NotebookNodeEarlyAccessFeature'import { buildCodeExampleContent } from './NotebookNodeFlagCodeExample'@@ -80,7 +83,9 @@ function FeatureFlagNotebookActions({ attributes }: NotebookNodeProps<FeatureFla}},},- canCreateEarlyAccessFeature+ // canCreateEarlyAccessFeature is false for a non-v1 flag, so the notebook never offers Create.+ // A non-v1 flag that already has an early access feature still gets the View action.+ canCreateEarlyAccessFeature || (hasEarlyAccessFeatures && !isV1FeatureFlagConfig(featureFlag.filters))? {text: `${hasEarlyAccessFeatures ? 'View' : 'Create'} early access feature`,icon: <IconRocket />,@@ -123,7 +128,11 @@ const Component = ({ attributes }: NotebookNodeProps<FeatureFlagNotebookWidgetAt<BindLogic logic={featureFlagLogic} props={{ id }}>{expanded ? (<div className="p-2">- <FeatureFlagReleaseConditions readOnly filters={featureFlag.filters} />+ {isV1FeatureFlagConfig(featureFlag.filters) ? (+ <FeatureFlagReleaseConditions readOnly filters={featureFlag.filters} />+ ) : (+ <FeatureFlagConfigReadonlyNotice filters={featureFlag.filters} />+ )}</div>) : null}</BindLogic>diff --git a/frontend/src/scenes/product-tours/productTourLogic.ts b/frontend/src/scenes/product-tours/productTourLogic.tsindex c8f50dc88065..0e600c77dad1 100644--- a/frontend/src/scenes/product-tours/productTourLogic.ts+++ b/frontend/src/scenes/product-tours/productTourLogic.ts@@ -22,7 +22,6 @@ import {Breadcrumb,FeatureFlagBasicType,FeatureFlagFilters,- FeatureFlagType,ProductTour,ProductTourBannerConfig,ProductTourContent,@@ -35,7 +34,7 @@ import { prepareStepsForRender } from './editor/generateStepHtml'import { isAnnouncement, productToursLogic } from './productToursLogic'import { getUpdatedStepOrderHistory, hasIncompleteTargeting, resolveStepTranslation } from './stepUtils'-export const DEFAULT_TARGETING_FILTERS: FeatureFlagType['filters'] = {+export const DEFAULT_TARGETING_FILTERS: FeatureFlagFilters = {...NEW_FLAG.filters,groups: [{ ...NEW_FLAG.filters.groups[0], rollout_percentage: 100 }],}diff --git a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx b/frontend/src/scenes/surveys/surveyActivityDescriber.tsxindex 5b6fa8c5b5e3..3c45405bfaae 100644--- a/frontend/src/scenes/surveys/surveyActivityDescriber.tsx+++ b/frontend/src/scenes/surveys/surveyActivityDescriber.tsx@@ -286,7 +286,7 @@ const surveyActionsMapping: Record<added a targeting flag with key <strong>{afterFlag.key}</strong></>)- if (afterFlag.filters?.groups?.length > 0) {+ if ((afterFlag.filters?.groups?.length ?? 0) > 0) {changes.push(<>set new targeting conditions</>)}} else if (beforeFlag && !afterFlag) {diff --git a/frontend/src/scenes/surveys/surveyLogic.tsx b/frontend/src/scenes/surveys/surveyLogic.tsxindex cb20ee51fc41..0b9017f37f05 100644--- a/frontend/src/scenes/surveys/surveyLogic.tsx+++ b/frontend/src/scenes/surveys/surveyLogic.tsx@@ -154,6 +154,7 @@ import {sanitizeSurveyAppearance,surveyResponseColumnId,validateSurveyAppearance,+ v1TargetingFlagFilters,} from './utils'export type SurveyBaseStatTuple = [@@ -3188,7 +3189,7 @@ export const surveyLogic = kea<surveyLogicType>([feature_enrollment: undefined,}}- return survey.targeting_flag?.filters || undefined+ return v1TargetingFlagFilters(survey)},],urlMatchTypeValidationError: [diff --git a/frontend/src/scenes/surveys/utils.ts b/frontend/src/scenes/surveys/utils.tsindex cdb1c7c81f55..7f51dfe5dec9 100644--- a/frontend/src/scenes/surveys/utils.ts+++ b/frontend/src/scenes/surveys/utils.ts@@ -46,6 +46,8 @@ import {SurveyType,} from '~/types'+import { isV1FeatureFlagConfig } from 'products/feature_flags/frontend/featureFlagConfigFormat'+const sanitizeConfig = { ADD_ATTR: ['target'] }export function sanitizeHTML(html: string): string {@@ -1431,7 +1433,7 @@ export function duplicateExistingSurvey(survey: Survey | NewSurvey): Partial<Surarchived: false,start_date: null,end_date: null,- targeting_flag_filters: survey.targeting_flag?.filters ?? NEW_SURVEY.targeting_flag_filters,+ targeting_flag_filters: v1TargetingFlagFilters(survey) ?? NEW_SURVEY.targeting_flag_filters,linked_flag_id: survey.linked_flag?.id ?? NEW_SURVEY.linked_flag_id,}}@@ -1511,7 +1513,13 @@ export function getSurveyTargetingFilters(survey: Survey | NewSurvey): FeatureFlreturn survey.targeting_flag_filters}- return survey.targeting_flag?.filters || undefined+ return v1TargetingFlagFilters(survey)+}++/** A survey's targeting flag is v1 by construction; any other config version has no release conditions to show. */+export function v1TargetingFlagFilters(survey: Survey | NewSurvey): FeatureFlagFilters | undefined {+ const filters = survey.targeting_flag?.filters+ return filters && isV1FeatureFlagConfig(filters) ? filters : undefined}export function getSurveyAudienceRuleCount(filters?: FeatureFlagFilters | null): number {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex cd7448f040fc..8ed284a08982 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4455,7 +4455,9 @@ export enum FeatureFlagBucketingIdentifier {DEVICE_ID = 'device_id',}+/** Config version 1: release conditions, variants and payloads. Stored without a `version` key. */export interface FeatureFlagFilters {+ version?: 1groups: FeatureFlagGroupType[]multivariate?: MultivariateFlagOptions | nullaggregation_group_type_index?: integer | null@@ -4470,13 +4472,85 @@ export interface FeatureFlagFilters {super_groups?: FeatureFlagGroupType[] | null}+/**+ * Declares the v1 keys absent on other versions, so optional reads compile on the union and return undefined for them.+ * Narrow with `isV1FeatureFlagConfig` to use the v1 shape.+ */+interface WithoutFeatureFlagFiltersKeys {+ groups?: never+ multivariate?: never+ payloads?: never+ early_exit?: never+ feature_enrollment?: never+ holdout?: never+ holdout_groups?: never+ super_groups?: never+}++export type FeatureFlagRulesV2ReturnType = 'boolean' | 'string' | 'number' | 'object'++interface FeatureFlagRulesV2RuleBase {+ id: string+ targeting: { properties: AnyPropertyFilter[] }+ description?: string+ metadata?: Record<string, unknown>+ value: JsonType+}++interface FeatureFlagRulesV2RolloutFields {+ rollout_percentage: number+ on_rollout_miss: 'continue' | 'return_default'+ assignment_algorithm: string+ seed: string+ assign_by?: 'person'+}++export interface FeatureFlagRulesV2TargetedReleaseRule extends FeatureFlagRulesV2RuleBase {+ rule_type: 'targeted_release'+}++export interface FeatureFlagRulesV2PercentageRolloutRule+ extends FeatureFlagRulesV2RuleBase, FeatureFlagRulesV2RolloutFields {+ rule_type: 'percentage_rollout'+}++export interface FeatureFlagRulesV2ExperimentRule extends FeatureFlagRulesV2RuleBase, FeatureFlagRulesV2RolloutFields {+ rule_type: 'experiment'+ experiment_id: number+ paused: boolean+ variants: { key: string; weight: number; value: JsonType }[]+ holdout?: { id: number; seed: string; exclusion_percentage: number }+}++export type FeatureFlagRulesV2Rule =+ | FeatureFlagRulesV2TargetedReleaseRule+ | FeatureFlagRulesV2PercentageRolloutRule+ | FeatureFlagRulesV2ExperimentRule++/** Config version 2: an ordered rule list. Read-only in this frontend; the API returns it under `filters` unchanged. */+export interface FeatureFlagRulesV2Config extends WithoutFeatureFlagFiltersKeys {+ version: 2+ return_type: FeatureFlagRulesV2ReturnType+ default_value: JsonType | null+ rules: FeatureFlagRulesV2Rule[]+ aggregation_group_type_index?: integer | null+}++export interface FeatureFlagUnsupportedConfig extends WithoutFeatureFlagFiltersKeys {+ version: number+ aggregation_group_type_index?: never+}++/** What the API stores under a flag's `filters`, discriminated by `version` (absent means 1). */+export type FeatureFlagConfig = FeatureFlagFilters | FeatureFlagRulesV2Config | FeatureFlagUnsupportedConfig+export interface FeatureFlagBasicType {id: numberteam_id: TeamType['id']key: string/* The description field (the name is a misnomer because of its legacy). */name: string- filters: FeatureFlagFilters+ filters: FeatureFlagConfigdeleted: booleanactive: booleanensure_experience_continuity: boolean | null@@ -4511,12 +4585,14 @@ export interface FeatureFlagType extends Omit<FeatureFlagBasicType, 'id' | 'teamis_used_in_replay_settings?: boolean}+export type FeatureFlagWithV1Config = FeatureFlagType & { filters: FeatureFlagFilters }+export interface OrganizationFeatureFlag {flag_id: number | nullteam_id: number | nullcreated_by: UserBasicType | nullcreated_at: string | null- filters: FeatureFlagFilters+ filters: FeatureFlagConfigactive: booleanevaluations_7d?: number | null}@@ -4530,7 +4606,7 @@ export interface OrganizationFeatureFlagRow {// (already on the row). created_by/created_at are omitted: the grid never renders them, and// serializing created_by would force a per-row join.active: boolean- filters: FeatureFlagFilters+ filters: FeatureFlagConfig}export interface OrganizationFeatureFlagKeysResponse {diff --git a/products/experiments/frontend/modals/SelectExistingFeatureFlagModal/SelectExistingFeatureFlagModal.test.tsx b/products/experiments/frontend/modals/SelectExistingFeatureFlagModal/SelectExistingFeatureFlagModal.test.tsxindex 2377f971a6e5..89261b901f2c 100644--- a/products/experiments/frontend/modals/SelectExistingFeatureFlagModal/SelectExistingFeatureFlagModal.test.tsx+++ b/products/experiments/frontend/modals/SelectExistingFeatureFlagModal/SelectExistingFeatureFlagModal.test.tsx@@ -14,6 +14,7 @@ import {FeatureFlagBucketingIdentifier,FeatureFlagEvaluationRuntime,FeatureFlagType,+ FeatureFlagWithV1Config,} from '~/types'import { SelectExistingFeatureFlagModal } from './SelectExistingFeatureFlagModal'@@ -24,7 +25,7 @@ describe('SelectExistingFeatureFlagModal', () => {const mockOnSelect = jest.fn()let logic: ReturnType<typeof selectExistingFeatureFlagModalLogic.build>- const baseFeatureFlag: FeatureFlagType = {+ const baseFeatureFlag: FeatureFlagWithV1Config = {id: 1,key: 'test-flag',name: 'Test Flag',diff --git a/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx b/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsxnew file mode 100644index 000000000000..e3b8acd46dd7--- /dev/null+++ b/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx@@ -0,0 +1,23 @@+import { LemonBanner } from '@posthog/lemon-ui'++import { FeatureFlagConfig } from '~/types'++import { featureFlagConfigFormat, featureFlagConfigFormatLabel } from './featureFlagConfigFormat'++export function FeatureFlagConfigReadonlyNotice({ filters }: { filters: FeatureFlagConfig }): JSX.Element {+ const label = featureFlagConfigFormatLabel(filters)+ return (+ <LemonBanner type="info">+ {featureFlagConfigFormat(filters) === 'v2' ? (+ <>+ This flag is stored as <strong>{label}</strong> and is shown read-only here. You can enable and+ disable it; archiving and editing its rules are not available yet.+ </>+ ) : (+ <>+ This flag is stored as <strong>{label}</strong>, which this page cannot display or change.+ </>+ )}+ </LemonBanner>+ )+}diff --git a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsxnew file mode 100644index 000000000000..73c5c360b0fd--- /dev/null+++ b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx@@ -0,0 +1,50 @@+import '@testing-library/jest-dom'++import { cleanup, render } from '@testing-library/react'+import { Provider } from 'kea'++import { initKeaTests } from '~/test/init'+import { FeatureFlagRulesV2Config } from '~/types'++import { FeatureFlagRulesV2Readonly } from './FeatureFlagRulesV2Readonly'++const CONFIG: FeatureFlagRulesV2Config = {+ version: 2,+ return_type: 'boolean',+ default_value: false,+ rules: [+ {+ id: 'rule-1',+ rule_type: 'percentage_rollout',+ description: 'Half of everyone',+ targeting: { properties: [] },+ value: true,+ rollout_percentage: 50,+ on_rollout_miss: 'return_default',+ assignment_algorithm: 'sha1_v1',+ seed: 'seed-must-not-render',+ },+ ],+}++describe('FeatureFlagRulesV2Readonly', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ it('shows the rule but never its seed', () => {+ const { container } = render(+ <Provider>+ <FeatureFlagRulesV2Readonly config={CONFIG} />+ </Provider>+ )++ expect(container).toHaveTextContent('Half of everyone')+ expect(container).toHaveTextContent('50%')+ expect(container).not.toHaveTextContent('seed-must-not-render')+ })+})diff --git a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsxnew file mode 100644index 000000000000..2f608c898778--- /dev/null+++ b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx@@ -0,0 +1,142 @@+import { useValues } from 'kea'++import { LemonTable, LemonTag } from '@posthog/lemon-ui'++import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { capitalizeFirstLetter } from 'lib/utils/strings'++import { groupsModel } from '~/models/groupsModel'+import { FeatureFlagRulesV2Config, FeatureFlagRulesV2Rule } from '~/types'++import { FeatureFlagConfigReadonlyNotice } from './FeatureFlagConfigReadonlyNotice'+import { formatPercentage } from './FractionalRolloutWarning'++const RULE_TYPE_LABELS: Record<FeatureFlagRulesV2Rule['rule_type'], string> = {+ targeted_release: 'Targeted release',+ percentage_rollout: 'Percentage rollout',+ experiment: 'Experiment',+}++function JsonValue({ value }: { value: unknown }): JSX.Element {+ return <code className="text-xs break-all">{JSON.stringify(value)}</code>+}++function RolloutCell({ rule }: { rule: FeatureFlagRulesV2Rule }): JSX.Element {+ if (rule.rule_type === 'targeted_release') {+ return <span>Everyone matching</span>+ }+ return (+ <div className="flex flex-col gap-1">+ <span className="tabular-nums">{formatPercentage(rule.rollout_percentage)}</span>+ <span className="text-xs text-muted">+ {rule.on_rollout_miss === 'continue' ? 'Miss: next rule' : 'Miss: default value'}+ </span>+ </div>+ )+}++function ValueCell({ rule }: { rule: FeatureFlagRulesV2Rule }): JSX.Element {+ if (rule.rule_type !== 'experiment') {+ return <JsonValue value={rule.value} />+ }+ return (+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-1">+ <span>Experiment #{rule.experiment_id}</span>+ {rule.paused && (+ <LemonTag type="warning" size="small">+ Paused+ </LemonTag>+ )}+ </div>+ {rule.variants.map((variant) => (+ <div key={variant.key} className="flex items-center gap-2 text-xs">+ <span className="font-mono">{variant.key}</span>+ <span className="tabular-nums text-muted">{formatPercentage(variant.weight)}</span>+ <JsonValue value={variant.value} />+ </div>+ ))}+ {rule.holdout && (+ <span className="text-xs text-muted">+ Holdout #{rule.holdout.id} excludes {formatPercentage(rule.holdout.exclusion_percentage)}+ </span>+ )}+ </div>+ )+}++export function FeatureFlagRulesV2Readonly({ config }: { config: FeatureFlagRulesV2Config }): JSX.Element {+ const { aggregationLabel } = useValues(groupsModel)+ const subjects = aggregationLabel(config.aggregation_group_type_index, true).plural++ const columns: LemonTableColumns<FeatureFlagRulesV2Rule> = [+ {+ title: '#',+ width: 0,+ render: (_, __, index) => <span className="tabular-nums">{index + 1}</span>,+ },+ {+ title: 'Type',+ width: 0,+ render: (_, rule) => (+ <LemonTag type="default" className="whitespace-nowrap">+ {RULE_TYPE_LABELS[rule.rule_type]}+ </LemonTag>+ ),+ },+ {+ title: 'Description',+ render: (_, rule) => rule.description || <span className="text-muted">—</span>,+ },+ {+ title: 'Targeting',+ render: (_, rule) =>+ rule.targeting.properties.length > 0 ? (+ <PropertyFiltersDisplay filters={rule.targeting.properties} compact />+ ) : (+ <span className="text-muted">All {subjects}</span>+ ),+ },+ {+ title: 'Rollout',+ width: 0,+ render: (_, rule) => <RolloutCell rule={rule} />,+ },+ {+ title: 'Value',+ render: (_, rule) => <ValueCell rule={rule} />,+ },+ ]++ return (+ <div className="flex flex-col gap-4" data-attr="feature-flag-rules-v2-readonly">+ <FeatureFlagConfigReadonlyNotice filters={config} />+ <div className="flex flex-wrap gap-6 text-sm">+ <div className="flex flex-col gap-1">+ <span className="font-semibold">Return type</span>+ <LemonTag type="default">{capitalizeFirstLetter(config.return_type)}</LemonTag>+ </div>+ <div className="flex flex-col gap-1">+ <span className="font-semibold">Default value</span>+ <JsonValue value={config.default_value} />+ </div>+ <div className="flex flex-col gap-1">+ <span className="font-semibold">Evaluated per</span>+ <span>{capitalizeFirstLetter(subjects)}</span>+ </div>+ </div>+ <div className="flex flex-col gap-2">+ <span className="font-semibold">Rules</span>+ <p className="text-xs text-muted m-0">Rules are evaluated top to bottom; the first match decides.</p>+ <LemonTable+ dataSource={config.rules}+ columns={columns}+ rowKey="id"+ size="small"+ emptyState="No rules: every evaluation returns the default value."+ />+ </div>+ </div>+ )+}diff --git a/products/feature_flags/frontend/featureFlagConfigFormat.test.ts b/products/feature_flags/frontend/featureFlagConfigFormat.test.tsnew file mode 100644index 000000000000..5e518318f531--- /dev/null+++ b/products/feature_flags/frontend/featureFlagConfigFormat.test.ts@@ -0,0 +1,27 @@+import { FeatureFlagConfig } from '~/types'++import { featureFlagConfigFormat, featureFlagConfigFormatLabel, rowVersionToken } from './featureFlagConfigFormat'++describe('featureFlagConfigFormat', () => {+ it.each([+ [undefined, 'v1', 'Config v1'],+ [{ groups: [] }, 'v1', 'Config v1'],+ [{ version: 1, groups: [] }, 'v1', 'Config v1'],+ [{ version: 2, return_type: 'boolean', default_value: false, rules: [] }, 'v2', 'Rules v2'],+ [{ version: 3 }, 'unsupported', 'Config v3 (unsupported)'],+ [{ version: null }, 'unsupported', 'Unsupported config'],+ [{ version: '2' }, 'unsupported', 'Unsupported config'],+ ])('reads %j as %s', (filters, format, label) => {+ expect(featureFlagConfigFormat(filters as FeatureFlagConfig | undefined)).toBe(format)+ expect(featureFlagConfigFormatLabel(filters as FeatureFlagConfig | undefined)).toBe(label)+ })++ it.each([+ ['a v1 row', { filters: { groups: [] }, version: 4 }, {}],+ ['a v2 row', { filters: { version: 2 } as FeatureFlagConfig, version: 4 }, { version: 4 }],+ ['an unsupported row', { filters: { version: 3 }, version: 4 }, { version: 4 }],+ ['a v2 row written before versioning', { filters: { version: 2 } as FeatureFlagConfig, version: null }, {}],+ ])('sends the row version only for a row outside v1: %s', (_, flag, expected) => {+ expect(rowVersionToken(flag)).toEqual(expected)+ })+})diff --git a/products/feature_flags/frontend/featureFlagConfigFormat.ts b/products/feature_flags/frontend/featureFlagConfigFormat.tsnew file mode 100644index 000000000000..61ed2a253446--- /dev/null+++ b/products/feature_flags/frontend/featureFlagConfigFormat.ts@@ -0,0 +1,63 @@+import { isApprovalRequiredError } from 'lib/api-error'++import { FeatureFlagConfig, FeatureFlagFilters, FeatureFlagRulesV2Config } from '~/types'++export type FeatureFlagConfigFormat = 'v1' | 'v2' | 'unsupported'++export const UNSUPPORTED_CONFIG_DISABLED_REASON =+ 'This flag is stored in a configuration version this page cannot change.'+export const ARCHIVE_UNAVAILABLE_DISABLED_REASON = 'Archiving is not available for this flag yet.'+export const STALE_ROW_VERSION_RELOADED_MESSAGE = 'This flag changed elsewhere and has been reloaded.'++/** Mirrors the server's detector: no `version` or `1` is v1, `2` is v2, anything else is unsupported here. */+export function featureFlagConfigFormat(filters: FeatureFlagConfig | null | undefined): FeatureFlagConfigFormat {+ const version = filters?.version+ if (version === undefined || version === 1) {+ return 'v1'+ }+ if (version === 2) {+ return 'v2'+ }+ return 'unsupported'+}++export function isV1FeatureFlagConfig(filters: FeatureFlagConfig): filters is FeatureFlagFilters {+ return featureFlagConfigFormat(filters) === 'v1'+}++export function isRulesV2FeatureFlagConfig(filters: FeatureFlagConfig): filters is FeatureFlagRulesV2Config {+ return featureFlagConfigFormat(filters) === 'v2'+}++/** The server refuses `archived` on every config version but v1. */+export function canArchiveFeatureFlag(filters: FeatureFlagConfig | null | undefined): boolean {+ return featureFlagConfigFormat(filters) === 'v1'+}++/**+ * A write to a row in another config version must carry the row version. For a v1 row this returns+ * `{}`, so the write sends no version and the server applies it without a version check.+ */+export function rowVersionToken(+ flag: { filters?: FeatureFlagConfig | null; version?: number | null } | null | undefined+): { version?: number } {+ return !flag || featureFlagConfigFormat(flag.filters) === 'v1' || flag.version == null+ ? {}+ : { version: flag.version }+}++export function isStaleRowVersionError(token: { version?: number }, error: any): boolean {+ return token.version !== undefined && error?.status === 409 && !isApprovalRequiredError(error)+}++export function featureFlagConfigFormatLabel(filters: FeatureFlagConfig | null | undefined): string {+ const version = filters?.version+ switch (featureFlagConfigFormat(filters)) {+ case 'v1':+ return 'Config v1'+ case 'v2':+ return 'Rules v2'+ default:+ return typeof version === 'number' ? `Config v${version} (unsupported)` : 'Unsupported config'+ }+}