: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): edit config version 2 flags in the flag pages (#107734)
Anders1e78e48b55d8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7617da3d5ccf..83b052996d64 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10130,6 +10130,10 @@ snapshots:hash: v1.k794b7964.e15a46c19ffe0a06b72ca3709fec32c2777b9f9646c13aa8363d11289ed1072a.Y3hGG3lZz-EZL8KZVK8XlAhNUbhNo2mB2bzVrI6j92wscenes-app-feature-flags--edit-remote-config-feature-flag--light:hash: v1.k794b7964.b4ce39ca84852217949cff9ef8bc695b8ad34e7cf5ff7cc831bd679830ff50b7.2E1I6gZE60WLh4uX2JOO4iigiSSmZRNFF8r2ofBuRWw+ scenes-app-feature-flags--edit-rules-v-2-feature-flag--dark:+ hash: v1.k794b7964.7c1812f3bae81f2ec5f88bdd8981269c9ab1db8de052f62261b6a526078e1db1.lLPRMvHcm3J30ZNs_Uv27aiYvPrYiEkQ9v9jzeGl4Rw+ scenes-app-feature-flags--edit-rules-v-2-feature-flag--light:+ hash: v1.k794b7964.6d2f9704f59bf6e3d61b811d92c7ecfc3d4a5263096d0e57181c2bce6dc4dc97.RTb3YQ69UQA3cySea7dGUkkZhOnIDrzoqgk7t0HpMXIscenes-app-feature-flags--feature-flag-not-found--dark:hash: v1.k794b7964.4f1e063fd0ea193507fc461100835138a210c677172cf02c4e6a1d3ca85053af.QLMBnXZd8GFY-ERfzWmRUW-eFybjMBVuSeT9PLkOnzIscenes-app-feature-flags--feature-flag-not-found--light:@@ -10154,6 +10158,10 @@ 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--new-rules-v-2-feature-flag--dark:+ hash: v1.k794b7964.1a8f4e9d348c8be23625ab231962fc9c2ce44233e6d699b52ad397f1c9acbc5d.TsUGKIvznQ4mzFHDJGhHd6kdTG6MN0vawhALQYuQHug+ scenes-app-feature-flags--new-rules-v-2-feature-flag--light:+ hash: v1.k794b7964.75a2d3403cf21fc78b4da29dd83c5f47d30ef487b5c34a97bbbb8164265ed506.Fb5E6agVEfrf6Zf-9T-eyjBYxFcG3UFmjnfqVQzh-Roscenes-app-feature-flags--rules-v-2-feature-flag--dark:hash: v1.k794b7964.2e595e65c1e4494c71c07b2772015cbcaf64fb4120d32192163e26ae95ca5231.aGTUL2hQW0He1Ia68rgMjgp-KslX-HAyApsF3Uwj5YIscenes-app-feature-flags--rules-v-2-feature-flag--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex a9e45ec9ec9a..c15028303421 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -350,6 +350,7 @@ export const FEATURE_FLAGS = {FEATURE_FLAG_EARLY_EXIT: 'feature-flag-early-exit', // owner: @gustavo #team-feature-flagsFEATURE_FLAG_NOTIFICATIONS: 'feature-flag-notifications', // owner: @reecejones #team-platform-featuresFEATURE_FLAG_REQUEST_USAGE: 'feature-flag-request-usage', // owner: #team-feature-flags+ FEATURE_FLAG_RULES_V2_EDITOR: 'feature-flag-rules-v2-editor', // owner: @andehen #team-feature-flags, entry points of the rules v2 flag editorFIELD_NOTES: 'field-notes', // owner: @adamleithpFLAG_EVALUATION_TAGS: 'flag-evaluation-tags', // owner: @dmarticus #team-feature-flagsFLAGGED_FEATURE_INDICATOR: 'flagged-feature-indicator', // owner: @benjackwhitediff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 55c9547017c3..5580afd5b739 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -1566,11 +1566,13 @@ export const productUrls = {sourceId,template,intent,+ format,}: {type?: 'boolean' | 'multivariate' | 'remote_config'sourceId?: number | string | nulltemplate?: 'simple' | 'targeted' | 'multivariate' | 'targeted-multivariate'intent?: 'local-eval' | 'first-page-load'+ format?: 'rules_v2'}): string => {const params = new URLSearchParams()if (type) {@@ -1585,6 +1587,9 @@ export const productUrls = {if (intent) {params.set('intent', intent)}+ if (format) {+ params.set('format', format)+ }return `/feature_flags/new?${params.toString()}`},game368hedgehogs: (): string => `/games/368hedgehogs`,diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 752864afcafe..5e45de328ca4 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -82,6 +82,7 @@ import {ARCHIVE_UNAVAILABLE_DISABLED_REASON,canArchiveFeatureFlag,featureFlagConfigFormatLabel,+ isRulesV2EditableConfig,} 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'@@ -95,6 +96,7 @@ import { FeedbackTab } from './FeatureFlagFeedbackTab'import { FeatureFlagLogicProps, featureFlagLogic } from './featureFlagLogic'import { FeatureFlagOverview } from './FeatureFlagOverview'import FeatureFlagProjects from './FeatureFlagProjects'+import { FeatureFlagRulesV2Editor } from './FeatureFlagRulesV2Editor'import FeatureFlagSchedule from './FeatureFlagSchedule'import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'import { FeatureFlagTestingTab } from './FeatureFlagTestingTab'@@ -135,7 +137,6 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {featureFlag,featureFlagLoading,featureFlagMissing,- isEditingFlag,activeTab,availableTabs,accessDeniedToFeatureFlag,@@ -144,6 +145,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {featureFlagRestoreLoading,dependentFlags,configFormat,+ editorKind,} = useValues(featureFlagLogic)const isV1Config = configFormat === 'v1'const { featureFlags } = useValues(enabledFeaturesLogic)@@ -214,7 +216,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 && isV1Config)+ const shouldShowForm = editorKind === 'v1'const [isFormMounted, setIsFormMounted] = useState(shouldShowForm)useEffect(() => {if (!shouldShowForm) {@@ -241,6 +243,26 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {),})+ const editButton = (+ <AccessControlAction+ resourceType={AccessControlResourceType.FeatureFlag}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={featureFlag.user_access_level}+ >+ {({ disabledReason }) => (+ <LemonButton+ type="secondary"+ size="small"+ disabledReason={disabledReason}+ onClick={() => editFeatureFlag(true)}+ data-attr={isV1Config ? undefined : 'edit-rules-v2-flag'}+ >+ Edit+ </LemonButton>+ )}+ </AccessControlAction>+ )+if (featureFlagMissing) {return <NotFound object="feature flag" />}@@ -249,6 +271,10 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {return <FeatureFlagFormSkeleton />}+ if (editorKind === 'rules_v2') {+ return <FeatureFlagRulesV2Editor id={props.id} />+ }+// Use the form UI for creating new flags or editing existing flags.// For viewing existing flags (readonly), use the tabbed UI below.if (shouldShowForm) {@@ -644,26 +670,14 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {}}actions={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>+ editButton) : (- <LemonTag type="highlight" data-attr="feature-flag-config-format">- {featureFlagConfigFormatLabel(featureFlag.filters)}- </LemonTag>+ <div className="flex items-center gap-2">+ <LemonTag type="highlight" data-attr="feature-flag-config-format">+ {featureFlagConfigFormatLabel(featureFlag.filters)}+ </LemonTag>+ {isRulesV2EditableConfig(featureFlag.filters, featureFlags) && editButton}+ </div>)}/>diff --git a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsxnew file mode 100644index 000000000000..996ec8d73d01--- /dev/null+++ b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx@@ -0,0 +1,100 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'++import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'+import { FeatureFlagRulesV2Editor } from './FeatureFlagRulesV2Editor'++jest.mock('lib/components/AutoSizer', () => ({+ AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>+ renderProp({ height: 400, width: 400 }),+}))++const V2_FLAG = {+ ...NEW_FLAG,+ id: 7,+ key: 'new-checkout',+ name: 'Checkout redesign',+ version: 3,+ filters: {+ version: 2,+ return_type: 'boolean',+ default_value: false,+ rules: [+ {+ id: 'rule-beta',+ rule_type: 'targeted_release',+ description: 'Beta users',+ targeting: { properties: [] },+ value: true,+ },+ {+ id: 'rule-rollout',+ rule_type: 'percentage_rollout',+ description: 'Everyone else',+ targeting: { properties: [] },+ value: true,+ rollout_percentage: 20,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ assign_by: 'person',+ seed: 'stored-seed',+ },+ ],+ },+}++describe('FeatureFlagRulesV2Editor', () => {+ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:team/event_definitions': mockGetEventDefinitions,+ '/api/projects/:team/property_definitions': mockGetPropertyDefinitions,+ '/api/projects/:team/feature_flags/7/': V2_FLAG,+ '/api/projects/:team/feature_flags/7/status': { status: 'active', reason: 'mock reason' },+ },+ })+ initKeaTests()+ const pageLogic = featureFlagLogic({ id: 7 })+ pageLogic.mount()+ await expectLogic(pageLogic).toDispatchActions(['loadFeatureFlagSuccess']).toFinishAllListeners()+ render(+ <Provider>+ <FeatureFlagRulesV2Editor id={7} />+ </Provider>+ )+ })++ afterEach(cleanup)++ it('names each text input by its label', () => {+ expect(screen.getByLabelText('Flag key')).toHaveValue('new-checkout')+ expect(screen.getAllByLabelText(/^Description/).map((input) => input.tagName)).toEqual([+ 'TEXTAREA',+ 'INPUT',+ 'INPUT',+ ])+ expect(screen.getByLabelText('Rollout percentage')).toHaveValue('20')+ })++ // Moving the card re-inserts it, which drops focus. React's commit then refocuses the button,+ // because it is still mounted.+ it('keeps focus on the rule a keyboard user moved down', async () => {+ const [moveDown] = document.querySelectorAll<HTMLElement>('[data-attr="rules-v2-move-rule-down"]')+ moveDown.focus()+ fireEvent.click(moveDown)++ await waitFor(() =>+ expect(document.querySelector('[data-attr="rules-v2-rule"] input')).toHaveValue('Everyone else')+ )+ const focusedRule = document.activeElement?.closest('[data-attr="rules-v2-rule"]')+ expect(focusedRule).toHaveTextContent('Rule 2')+ expect(focusedRule?.querySelector('input')).toHaveValue('Beta users')+ })+})diff --git a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsxnew file mode 100644index 000000000000..6b307c2f82e4--- /dev/null+++ b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx@@ -0,0 +1,176 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'+import { useId } from 'react'++import { IconPlusSmall } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonInput,+ LemonSegmentedButton,+ LemonSelect,+ LemonTextArea,+} from '@posthog/lemon-ui'++import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { tagsModel } from '~/models/tagsModel'++import { FeatureFlagLogicProps, slugifyFeatureFlagKey } from './featureFlagLogic'+import { BOOLEAN_OPTIONS, featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'+import { RulesV2RuleEditor } from './RulesV2RuleEditor'++export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.Element {+ const logic = featureFlagRulesV2EditorLogic({ id })+ const { draft, ruleKeys, featureFlag, saving, saveError, saveDisabledReason, fieldError } = useValues(logic)+ const { setDraft, setConfig, addRule, saveRulesV2Flag, editFeatureFlag } = useActions(logic)+ const { tags } = useValues(tagsModel)+ const { loadTagsIfNeeded } = useActions(tagsModel)+ const isNew = id === 'new'+ const keyInputId = useId()+ const descriptionInputId = useId()++ return (+ <div className="flex flex-col gap-4" data-attr="feature-flag-rules-v2-editor">+ <SceneTitleSection+ name={draft.key || 'New rules v2 flag'}+ resourceType={{ type: !isNew && featureFlag.active ? 'feature_flag' : 'feature_flag_off' }}+ actions={+ <>+ <LemonButton+ type="secondary"+ size="small"+ data-attr="cancel-rules-v2-flag"+ onClick={() => (isNew ? router.actions.push(urls.featureFlags()) : editFeatureFlag(false))}+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ data-attr="save-rules-v2-flag"+ loading={saving}+ disabledReason={saveDisabledReason}+ onClick={saveRulesV2Flag}+ >+ Save+ </LemonButton>+ </>+ }+ />+ <SceneContent>+ {saveError && saveError.field === null && (+ <LemonBanner type="error" data-attr="rules-v2-save-error">+ {saveError.message}+ </LemonBanner>+ )}+ <div className="rounded border p-3 bg-surface-primary flex flex-col gap-3 max-w-200">+ <LemonField.Pure+ label="Flag key"+ htmlFor={keyInputId}+ error={fieldError('key')}+ help={+ !isNew && draft.key !== featureFlag.key+ ? 'Changing the key breaks every SDK call that uses the old one.'+ : undefined+ }+ >+ <LemonInput+ id={keyInputId}+ value={draft.key}+ onChange={(key) => setDraft({ key: slugifyFeatureFlagKey(key) })}+ data-attr="rules-v2-flag-key"+ className="ph-ignore-input"+ autoComplete="off"+ spellCheck={false}+ placeholder="e.g. new-checkout"+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Description"+ htmlFor={descriptionInputId}+ showOptional+ error={fieldError('name')}+ >+ <LemonTextArea+ id={descriptionInputId}+ value={draft.name}+ onChange={(name) => setDraft({ name })}+ className="ph-ignore-input"+ />+ </LemonField.Pure>+ <LemonField.Pure label="Tags" showOptional error={fieldError('tags')}>+ <ObjectTags+ tags={draft.tags}+ onChange={(tags) => setDraft({ tags })}+ onEdit={loadTagsIfNeeded}+ saving={saving}+ tagsAvailable={tags.filter((tag: string) => !draft.tags.includes(tag))}+ data-attr="rules-v2-flag-tags"+ />+ </LemonField.Pure>+ <div className="flex flex-wrap gap-4">+ <LemonField.Pure label="Return type">+ <LemonSelect+ value={draft.config.return_type}+ options={[{ value: 'boolean', label: 'Boolean' }]}+ disabledReason="Other return types are not available yet."+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Default value"+ help="Returned when no rule matches. Null returns no value, so the SDK uses the caller's default."+ error={fieldError('filters.default_value')}+ >+ <LemonSegmentedButton+ size="small"+ value={String(draft.config.default_value)}+ onChange={(value) =>+ setConfig({ default_value: value === 'null' ? null : value === 'true' })+ }+ options={[...BOOLEAN_OPTIONS, { value: 'null', label: 'null' }]}+ data-attr="rules-v2-default-value"+ />+ </LemonField.Pure>+ </div>+ {isNew && (+ <p className="text-xs text-muted m-0">+ New flags are created disabled. Enable the flag from its page after saving.+ </p>+ )}+ </div>+ <div className="flex flex-col gap-2 max-w-200">+ <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>+ {draft.config.rules.map((rule, index) => (+ <RulesV2RuleEditor+ key={ruleKeys[index]}+ ruleKey={ruleKeys[index]}+ id={id}+ index={index}+ rule={rule}+ ruleCount={draft.config.rules.length}+ />+ ))}+ <div>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconPlusSmall />}+ onClick={addRule}+ data-attr="rules-v2-add-rule"+ >+ Add rule+ </LemonButton>+ </div>+ </div>+ </SceneContent>+ </div>+ )+}diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsxindex c17b9753f92c..5b1f4e24184e 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx@@ -197,13 +197,28 @@ export const RulesV2FeatureFlag: Story = {},}-// `?edit=true` must still show the read-only view, because the v1 form's full save would rewrite the document.+// Without the editor flag, `?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 NewRulesV2FeatureFlag: Story = {+ parameters: {+ pageUrl: urls.featureFlagNew({ format: 'rules_v2' }),+ featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING, FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR],+ },+}++export const EditRulesV2FeatureFlag: Story = {+ parameters: {+ pageUrl: `${urls.featureFlag(RULES_V2_FLAG_ID)}?edit=true`,+ featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING, FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR],+ },+}+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 a108214416ba..7d4094a02c19 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx@@ -38,6 +38,7 @@ import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'import { QuickSurveyType } from 'scenes/surveys/quick-create/types'import { QuickSurveyModal } from 'scenes/surveys/QuickSurveyModal'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'@@ -64,6 +65,7 @@ import {featureFlagConfigFormatLabel,isRulesV2FeatureFlagConfig,isV1FeatureFlagConfig,+ rulesV2CreateDisabledReason,} from 'products/feature_flags/frontend/featureFlagConfigFormat'import { FeatureFlagRequestUsage } from 'products/feature_flags/frontend/requestUsage/FeatureFlagRequestUsage'@@ -809,6 +811,8 @@ export function FeatureFlags(): JSX.Element {const newFeatureFlagUrl = urls.featureFlagTemplates()const showNotificationsTab = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_NOTIFICATIONS]const showRequestUsageTab = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE]+ const showRulesV2Editor = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR]+ const { currentTeam } = useValues(teamLogic)return (<SceneContent className="feature_flags">@@ -824,6 +828,22 @@ export function FeatureFlags(): JSX.Element {surveyId={FEATURE_FLAGS_FEEDBACK_SURVEY_ID}data-attr="feature-flags-feedback-button"/>+ {showRulesV2Editor && (+ <AccessControlAction+ resourceType={AccessControlResourceType.FeatureFlag}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="secondary"+ size="small"+ to={urls.featureFlagNew({ format: 'rules_v2' })}+ disabledReason={rulesV2CreateDisabledReason(currentTeam, enabledFeatureFlags)}+ data-attr="new-rules-v2-feature-flag"+ >+ New rules v2 flag+ </LemonButton>+ </AccessControlAction>+ )}<AccessControlActionresourceType={AccessControlResourceType.FeatureFlag}minAccessLevel={AccessControlLevel.Editor}diff --git a/frontend/src/scenes/feature-flags/PercentageInput.tsx b/frontend/src/scenes/feature-flags/PercentageInput.tsxindex a0882a501a60..9e0c95d6a1fc 100644--- a/frontend/src/scenes/feature-flags/PercentageInput.tsx+++ b/frontend/src/scenes/feature-flags/PercentageInput.tsx@@ -6,11 +6,13 @@ import { useEffect, useRef, useState } from 'react'export function PercentageInput({value,onChange,+ id,className,...rest}: {value: numberonChange: (value: number) => void+ id?: stringstep?: numberclassName?: string'data-attr'?: string@@ -28,6 +30,7 @@ export function PercentageInput({return (<span className="LemonInput input-like LemonInput--type-number LemonInput--medium LemonInput--full-width"><input+ id={id}className={`LemonInput__input ${className ?? ''}`}type="text"inputMode="decimal"diff --git a/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx b/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsxnew file mode 100644index 000000000000..cfe325fccf9d--- /dev/null+++ b/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx@@ -0,0 +1,144 @@+import { useActions, useValues } from 'kea'+import { useId } from 'react'++import { IconTrash } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'++import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'+import { LemonField } from 'lib/lemon-ui/LemonField'++import { FeatureFlagRulesV2DraftRule } from '~/types'++import { FeatureFlagLogicProps } from './featureFlagLogic'+import { BOOLEAN_OPTIONS, featureFlagRulesV2EditorLogic, withRuleType } from './featureFlagRulesV2EditorLogic'+import { PercentageInput } from './PercentageInput'++export function RulesV2RuleEditor({+ id,+ index,+ rule,+ ruleCount,+ ruleKey,+}: FeatureFlagLogicProps & {+ index: number+ rule: FeatureFlagRulesV2DraftRule+ ruleCount: number+ ruleKey: number+}): JSX.Element {+ const { fieldError } = useValues(featureFlagRulesV2EditorLogic({ id }))+ const { updateRule, removeRule, moveRule } = useActions(featureFlagRulesV2EditorLogic({ id }))+ const path = `filters.rules[${index}]`+ const descriptionInputId = useId()+ const rolloutInputId = useId()++ return (+ <div className="rounded border p-3 bg-surface-primary flex flex-col gap-3" data-attr="rules-v2-rule">+ <div className="flex items-center gap-2">+ <span className="font-semibold">Rule {index + 1}</span>+ <LemonSelect+ size="small"+ value={rule.rule_type}+ onChange={(ruleType) => updateRule(index, withRuleType(rule, ruleType))}+ options={[+ { value: 'targeted_release', label: 'Targeted release' },+ { value: 'percentage_rollout', label: 'Percentage rollout' },+ ]}+ data-attr="rules-v2-rule-type"+ />+ <div className="flex-1" />+ <LemonButton+ icon={<IconArrowUp />}+ size="small"+ tooltip="Move up"+ data-attr="rules-v2-move-rule-up"+ disabledReason={index === 0 ? 'This rule is evaluated first.' : undefined}+ onClick={() => moveRule(index, index - 1)}+ />+ <LemonButton+ icon={<IconArrowDown />}+ size="small"+ tooltip="Move down"+ data-attr="rules-v2-move-rule-down"+ disabledReason={index === ruleCount - 1 ? 'This rule is evaluated last.' : undefined}+ onClick={() => moveRule(index, index + 1)}+ />+ <LemonButton+ icon={<IconTrash />}+ size="small"+ status="danger"+ tooltip="Remove rule"+ data-attr="rules-v2-remove-rule"+ onClick={() => removeRule(index)}+ />+ </div>+ {fieldError(path) && <LemonBanner type="error">{fieldError(path)}</LemonBanner>}+ <LemonField.Pure+ label="Description"+ htmlFor={descriptionInputId}+ showOptional+ error={fieldError(`${path}.description`)}+ >+ <LemonInput+ id={descriptionInputId}+ value={rule.description ?? ''}+ onChange={(description) => updateRule(index, { ...rule, description: description || undefined })}+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Match persons where"+ help={rule.targeting.properties.length === 0 ? 'No conditions: every person matches.' : undefined}+ error={fieldError(`${path}.targeting`)}+ >+ <PropertyFilters+ pageKey={`rules-v2-${id}-${ruleKey}`}+ propertyFilters={rule.targeting.properties}+ onChange={(properties) => updateRule(index, { ...rule, targeting: { properties } })}+ taxonomicGroupTypes={[TaxonomicFilterGroupType.PersonProperties]}+ hasRowOperator={false}+ logicalRowDivider+ sendAllKeyUpdates+ addText="Add condition"+ />+ </LemonField.Pure>+ {rule.rule_type === 'percentage_rollout' && (+ <div className="flex flex-wrap gap-4">+ <LemonField.Pure+ label="Rollout percentage"+ htmlFor={rolloutInputId}+ className="w-40"+ error={fieldError(`${path}.rollout_percentage`)}+ >+ <PercentageInput+ id={rolloutInputId}+ value={rule.rollout_percentage}+ onChange={(rollout_percentage) => updateRule(index, { ...rule, rollout_percentage })}+ data-attr="rules-v2-rollout-percentage"+ />+ </LemonField.Pure>+ <LemonField.Pure label="Persons outside the rollout" error={fieldError(`${path}.on_rollout_miss`)}>+ <LemonSelect+ value={rule.on_rollout_miss}+ onChange={(on_rollout_miss) => updateRule(index, { ...rule, on_rollout_miss })}+ options={[+ { value: 'continue', label: 'Continue to the next rule' },+ { value: 'return_default', label: 'Get the default value' },+ ]}+ data-attr="rules-v2-rollout-miss"+ />+ </LemonField.Pure>+ </div>+ )}+ <LemonField.Pure label="Value" error={fieldError(`${path}.value`)}>+ <LemonSegmentedButton+ size="small"+ value={String(rule.value)}+ onChange={(value) => updateRule(index, { ...rule, value: value === 'true' })}+ options={BOOLEAN_OPTIONS}+ data-attr="rules-v2-rule-value"+ />+ </LemonField.Pure>+ </div>+ )+}diff --git a/frontend/src/scenes/feature-flags/featureFlagKeyChangeDialog.tsx b/frontend/src/scenes/feature-flags/featureFlagKeyChangeDialog.tsxnew file mode 100644index 000000000000..16970faeb0e5--- /dev/null+++ b/frontend/src/scenes/feature-flags/featureFlagKeyChangeDialog.tsx@@ -0,0 +1,26 @@+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'++/** Resolves true when the user confirms a key rename, which breaks SDK calls that still use the old key. */+export function confirmFeatureFlagKeyChange(oldKey: string): Promise<boolean> {+ return new Promise<boolean>((resolve) => {+ LemonDialog.open({+ title: 'Change flag key?',+ description: (+ <span>+ Renaming this key will break any existing code that references it (e.g.{' '}+ <code className="text-xs bg-fill-secondary rounded px-1 py-0.5">{`getFeatureFlag('${oldKey}')`}</code>+ ). Make sure to update all SDK calls and integrations.+ </span>+ ),+ primaryButton: {+ children: 'Change key',+ status: 'danger',+ onClick: () => resolve(true),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ onAfterClose: () => resolve(false),+ })+ })+}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 10448832c7e3..41d2a4b14350 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -17,9 +17,11 @@ import { lemonToast as sharedLemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { ApiError } from 'lib/api-error'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { organizationLogic } from 'scenes/organizationLogic'import { teamLogic } from 'scenes/teamLogic'@@ -4511,3 +4513,95 @@ describe('a flag in config version 2', () => {newLogic.unmount()})})++describe('the editor a flag opens in', () => {+ const V1_FLAG = { ...NEW_FLAG, id: 8, key: 'v1-flag', version: 1 }+ const V2_FLAG = {+ ...NEW_FLAG,+ id: 7,+ key: 'rules-v2-flag',+ version: 3,+ filters: { version: 2, return_type: 'boolean', default_value: false, rules: [] },+ }++ beforeEach(() => {+ silenceKeaLoadersErrors()+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [200, V2_FLAG],+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/8/`]: () => [200, V1_FLAG],+ },+ })+ initKeaTests()+ })++ afterEach(resumeKeaLoadersErrors)++ async function editorKind(id: 7 | 8 | 'new', editorEnabled: boolean, search = ''): Promise<string | null> {+ enabledFeaturesLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR]: editorEnabled,+ })+ router.actions.push(`${urls.featureFlag(id)}${search}`)+ const logic = featureFlagLogic({ id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ if (id !== 'new') {+ logic.actions.editFeatureFlag(true)+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagSuccess']).toFinishAllListeners()+ }+ const kind = logic.values.editorKind+ logic.unmount()+ return kind+ }++ it.each([+ ['a v1 flag', 'v1', 8, true, ''],+ ['a v1 flag with the editor off', 'v1', 8, false, ''],+ ['a v2 flag', 'rules_v2', 7, true, ''],+ ['a v2 flag with the editor off', null, 7, false, ''],+ ['a new flag', 'v1', 'new', true, ''],+ ['a new rules v2 flag', 'rules_v2', 'new', true, '?format=rules_v2'],+ ['a new rules v2 flag with the editor off', 'v1', 'new', false, '?format=rules_v2'],+ ] as const)('%s opens the %s editor', async (_label, expected, id, editorEnabled, search) => {+ expect(await editorKind(id, editorEnabled, search)).toBe(expected)+ })++ // The editor builds its draft from the stored rules and would throw on, or drop, what it cannot represent.+ it.each([+ ['a string return type', { return_type: 'string', default_value: 'control' }],+ ['group assignment', { aggregation_group_type_index: 0 }],+ [+ 'an experiment rule',+ {+ rules: [+ {+ id: 'rule-experiment',+ rule_type: 'experiment',+ targeting: { properties: [] },+ experiment_id: 12,+ paused: false,+ variants: [+ { key: 'control', weight: 50, value: false },+ { key: 'test', weight: 50, value: true },+ ],+ rollout_percentage: 100,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ assign_by: 'person',+ seed: 'stored-seed',+ },+ ],+ },+ ],+ ])('a v2 flag with %s opens no editor, even with the editor on', async (_label, filters) => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [+ 200,+ { ...V2_FLAG, filters: { ...V2_FLAG.filters, ...filters } },+ ],+ },+ })+ expect(await editorKind(7, true)).toBeNull()+ })+})diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex ae15f6af0955..2c283fe05199 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -22,7 +22,6 @@ import { loaders } from 'kea-loaders'import { beforeUnload, router, urlToAction } from 'kea-router'import { CombinedLocation } from 'kea-router/lib/utils'import posthog from 'posthog-js'-import { createElement } from 'react'import { toast } from 'react-toastify'import api, { PaginatedResponse } from 'lib/api'@@ -31,11 +30,12 @@ import { handleApprovalRequired } from 'lib/approvals/utils'import { ACTIVITY_SEARCH_PARAM } from 'lib/components/ActivityLog/activityLogLogic'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'+import { FEATURE_FLAGS } from 'lib/constants'import { describeCron } from 'lib/cron'import { Dayjs, dayjs } from 'lib/dayjs'import { scrollToFormError } from 'lib/forms/scrollToFormError'-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { stringifyWithBigInts } from 'lib/utils/json'@@ -93,6 +93,7 @@ import {FeatureFlagConfigFormat,STALE_ROW_VERSION_RELOADED_MESSAGE,featureFlagConfigFormat,+ isRulesV2EditableConfig,isStaleRowVersionError,isV1FeatureFlagConfig,rowVersionToken,@@ -111,6 +112,7 @@ import type {} from 'products/feature_flags/frontend/generated/api.schemas'import type { CopyFlagsResponseApi } from '../../../../products/feature_flags/frontend/generated/api.schemas'+import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'import type { ProductIntentProperties } from '../../lib/utils/product-intents'import type { Noun } from '../../models/groupsModel'import type { Node } from '../../queries/schema/schema-general'@@ -137,6 +139,7 @@ import { uniformAggregationGroupTypeIndex } from './defaultReleaseConditionsUtilimport { FeatureFlagArchivedSource, reportFeatureFlagArchived } from './featureFlagArchiveDialog'import { checkFeatureFlagConfirmation } from './featureFlagConfirmationLogic'import type { FlagIntent } from './featureFlagIntentWarningLogic'+import { confirmFeatureFlagKeyChange } from './featureFlagKeyChangeDialog'import { featureFlagReleaseConditionsLogic } from './featureFlagReleaseConditionsLogic'import {ProjectSelectOption,@@ -561,6 +564,9 @@ function validatePayloadRequired(is_remote_configuration: boolean, payload?: Jsoreturn undefined}+/** The editor the flag scene mounts, if any; a document never reaches the editor of another config format. */+export type FeatureFlagEditorKind = 'v1' | 'rules_v2' | null+export interface FeatureFlagLogicProps {id: number | 'new' | 'link'}@@ -927,6 +933,7 @@ function cleanFilterGroups(groups?: FeatureFlagGroupType[]): FeatureFlagGroupTypexport interface featureFlagLogicValues {defaultEvaluationContexts: DefaultEvaluationContextsResponse | null // defaultEvaluationContextsLogicdefaultReleaseConditions: DefaultReleaseConditionsResponse | null // defaultReleaseConditionsLogic+ enabledFeatures: FeatureFlagsSet // enabledFeaturesLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModelcurrentOrganization: OrganizationType | null // organizationLogiccurrentOrganizationId: string // organizationLogic@@ -965,6 +972,7 @@ export interface featureFlagLogicValues {dependentFlagsLoading: booleandisableCopiedFlag: booleanearlyAccessFeaturesList: MinimalEarlyAccessFeatureType[]+ editorKind: FeatureFlagEditorKindemailDomain: stringendDate: Dayjs | nullexpandAdvancedOnEdit: boolean@@ -1121,6 +1129,7 @@ export interface featureFlagLogicValues {rowVersionToken: {version?: number}+ rulesV2DraftDirty: booleanscheduleDateMarker: anyscheduleDefaultsAppliedFromFlag: booleanscheduleFormCollapsible: boolean@@ -1800,6 +1809,9 @@ export interface featureFlagLogicActions {setRepeatsValue: (value: RecurrenceInterval | 'cron' | 'none') => {value: RecurrenceInterval | 'cron' | 'none'}+ setRulesV2DraftDirty: (dirty: boolean) => {+ dirty: boolean+ }setScheduleDateMarker: (dateMarker: any) => {dateMarker: any}@@ -2143,6 +2155,13 @@ export interface featureFlagLogicMeta {props: (arg: any) => anyavailableTabs: (featureFlag: FeatureFlagType, props: any) => FeatureFlagsTab[]configFormat: (featureFlag: FeatureFlagType) => FeatureFlagConfigFormat+ editorKind: (+ props: any,+ isEditingFlag: boolean,+ featureFlag: FeatureFlagType,+ enabledFeatures: FeatureFlagsSet,+ searchParams: Record<string, any>+ ) => FeatureFlagEditorKindrowVersionToken: (featureFlag: FeatureFlagType) => {version?: number}@@ -2264,6 +2283,8 @@ export const featureFlagLogic = kea<featureFlagLogicType>([['hasAvailableFeature', 'user'],organizationLogic,['currentOrganization', 'currentOrganizationId'],+ enabledFeaturesLogic,+ ['featureFlags as enabledFeatures'],defaultEvaluationContextsLogic,['defaultEvaluationContexts'],defaultReleaseConditionsLogic,@@ -2293,6 +2314,8 @@ export const featureFlagLogic = kea<featureFlagLogicType>([setFeatureFlagMissing: true,deleteFeatureFlag: (featureFlag: Partial<FeatureFlagType>) => ({ featureFlag }),setRemoteConfigEnabled: (enabled: boolean) => ({ enabled }),+ // The rules v2 editor keeps its draft in its own logic; this mirrors whether it has unsaved edits.+ setRulesV2DraftDirty: (dirty: boolean) => ({ dirty }),resetEncryptedPayload: () => ({}),setMultivariateEnabled: (enabled: boolean) => ({ enabled }),setMultivariateOptions: (multivariateOptions: MultivariateFlagOptions | null) => ({ multivariateOptions }),@@ -2419,6 +2442,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},})),reducers({+ rulesV2DraftDirty: [false, { setRulesV2DraftDirty: (_, { dirty }) => dirty }],// Read by the refresh loader, which samples it around its request to tell whether newer// state landed while the request was open.flagMutationCount: [@@ -4692,31 +4716,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([const keyChanged = originalFlag && featureFlag.id && originalFlag.key !== featureFlag.keyif (keyChanged) {- const confirmed = await new Promise<boolean>((resolve) => {- LemonDialog.open({- title: 'Change flag key?',- description: createElement(- 'span',- null,- 'Renaming this key will break any existing code that references it (e.g. ',- createElement(- 'code',- { className: 'text-xs bg-fill-secondary rounded px-1 py-0.5' },- `getFeatureFlag('${originalFlag.key}')`- ),- '). Make sure to update all SDK calls and integrations.'- ),- primaryButton: {- children: 'Change key',- status: 'danger',- onClick: () => resolve(true),- },- secondaryButton: {- children: 'Cancel',- },- onAfterClose: () => resolve(false),- })- })+ const confirmed = await confirmFeatureFlagKeyChange(originalFlag.key)if (!confirmed) {return}@@ -4791,6 +4791,28 @@ export const featureFlagLogic = kea<featureFlagLogicType>([(s) => [s.featureFlag],(featureFlag: FeatureFlagType): FeatureFlagConfigFormat => featureFlagConfigFormat(featureFlag.filters),],+ editorKind: [+ (s) => [s.props, s.isEditingFlag, s.featureFlag, s.enabledFeatures, router.selectors.searchParams],+ (+ props: FeatureFlagLogicProps,+ isEditingFlag: boolean,+ featureFlag: FeatureFlagType,+ enabledFeatures: FeatureFlagsSet,+ searchParams: Record<string, any>+ ): FeatureFlagEditorKind => {+ const rulesV2 = !!enabledFeatures[FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR]+ if (props.id === 'new') {+ return rulesV2 && searchParams.format === 'rules_v2' ? 'rules_v2' : 'v1'+ }+ if (!isEditingFlag) {+ return null+ }+ if (isV1FeatureFlagConfig(featureFlag.filters)) {+ return 'v1'+ }+ return isRulesV2EditableConfig(featureFlag.filters, enabledFeatures) ? 'rules_v2' : null+ },+ ],rowVersionToken: [(s) => [s.featureFlag],(featureFlag: FeatureFlagType): { version?: number } => rowVersionToken(featureFlag),@@ -5310,7 +5332,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// because its listener calls `loadFeatureFlag()` whenever `editing === true` —// which would wipe the form on any re-push carrying `?edit=true`.// The `initial` mount must still run so first-load setup happens.- if (method === 'PUSH' && values.isFormDirty) {+ if (method === 'PUSH' && (values.isFormDirty || values.rulesV2DraftDirty)) {return}diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.tsnew file mode 100644index 000000000000..2528d35942d6--- /dev/null+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts@@ -0,0 +1,409 @@+import { MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+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 { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { FeatureFlagType, PropertyFilterType, PropertyOperator } from '~/types'++import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'+import {+ NEW_TARGETED_RELEASE_RULE,+ featureFlagRulesV2EditorLogic,+ rulesV2DraftFromFlag,+ rulesV2SaveError,+ rulesV2WriteBody,+ withRuleType,+} from './featureFlagRulesV2EditorLogic'++jest.mock('~/layout/panel-layout/ProjectTree/projectTreeLogic', () => ({+ ...jest.requireActual('~/layout/panel-layout/ProjectTree/projectTreeLogic'),+ refreshTreeItem: jest.fn(),+}))++const V2_FLAG = {+ ...NEW_FLAG,+ id: 7,+ key: 'new-checkout',+ name: 'Checkout redesign',+ version: 3,+ filters: {+ version: 2,+ return_type: 'boolean',+ default_value: false,+ rules: [+ {+ id: 'rule-beta',+ rule_type: 'targeted_release',+ targeting: { properties: [{ key: 'plan', type: 'person', operator: 'exact', value: ['beta'] }] },+ value: true,+ },+ {+ id: 'rule-rollout',+ rule_type: 'percentage_rollout',+ description: 'Everyone else',+ targeting: { properties: [] },+ value: true,+ rollout_percentage: 20,+ on_rollout_miss: 'return_default',+ assignment_algorithm: 'sha1_60_v1',+ assign_by: 'person',+ seed: 'stored-seed',+ },+ ],+ },+} as unknown as FeatureFlagType++describe('featureFlagRulesV2EditorLogic', () => {+ beforeEach(() => {+ silenceKeaLoadersErrors()+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [200, V2_FLAG],+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ resumeKeaLoadersErrors()+ jest.restoreAllMocks()+ })++ describe('rules v2 editor documents', () => {+ it('keeps stored rule ids, never holds a seed, and sends new rules without an id', () => {+ const draft = rulesV2DraftFromFlag(V2_FLAG)+ const body = rulesV2WriteBody({+ ...draft,+ config: { ...draft.config, rules: [...draft.config.rules, NEW_TARGETED_RELEASE_RULE] },+ })++ expect(body.filters.rules.map((rule) => rule.id)).toEqual(['rule-beta', 'rule-rollout', undefined])+ expect(JSON.stringify(body)).not.toContain('seed')+ expect(body).toMatchObject({ key: 'new-checkout', name: 'Checkout redesign', version: 3 })+ expect(body.filters).toMatchObject({ version: 2, return_type: 'boolean', default_value: false })+ })++ it('adds the rollout fields when a rule becomes a percentage rollout and drops them when it stops', () => {+ const rule = { ...NEW_TARGETED_RELEASE_RULE, id: 'rule-beta', description: 'Beta users' }+ const rollout = withRuleType(rule, 'percentage_rollout')+ expect(rollout).toEqual({+ ...rule,+ rule_type: 'percentage_rollout',+ rollout_percentage: 0,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ assign_by: 'person',+ })+ expect(withRuleType(rollout, 'targeted_release')).toEqual(rule)+ })++ it.each([+ [+ { attr: 'key', detail: 'There is already a feature flag with this key.' },+ 'key',+ 'There is already a feature flag with this key.',+ ],+ [+ { detail: 'filters.rules[1].rollout_percentage: Must be at most 100.' },+ 'filters.rules[1].rollout_percentage',+ 'Must be at most 100.',+ ],+ [+ { detail: 'filters.rules[0].targeting.properties[0].value: Must be a string.' },+ 'filters.rules[0].targeting',+ 'filters.rules[0].targeting.properties[0].value: Must be a string.',+ ],+ [+ { detail: 'filters.rules[2].id: Rule ids are server-assigned.' },+ 'filters.rules[2]',+ 'filters.rules[2].id: Rule ids are server-assigned.',+ ],+ [+ { attr: 'tags', detail: 'Add at least one tag. This project requires new feature flags to be tagged.' },+ 'tags',+ 'Add at least one tag. This project requires new feature flags to be tagged.',+ ],+ [+ { attr: 'active', detail: 'A flag with this configuration format is created disabled.' },+ null,+ 'A flag with this configuration format is created disabled.',+ ],+ [+ { detail: 'This flag cannot be written while an approval policy is enabled.' },+ null,+ 'This flag cannot be written while an approval policy is enabled.',+ ],+ ])('maps %j to the field that owns it', (error, field, message) => {+ expect(rulesV2SaveError(error)).toEqual({ field, message })+ })+ })++ it('creates without a row version and lands on the new flag', async () => {+ const create = jest.spyOn(api, 'create').mockResolvedValue({ ...V2_FLAG, id: 8 })+ const logic = featureFlagRulesV2EditorLogic({ id: 'new' })+ logic.mount()++ logic.actions.setDraft({ key: 'new-checkout', tags: ['checkout'] })+ logic.actions.addRule()+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagSuccess'])+ .toFinishAllListeners()++ const body = create.mock.calls[0][1] as Record<string, any>+ expect(body).not.toHaveProperty('version')+ expect(body).not.toHaveProperty('active')+ expect(body.tags).toEqual(['checkout'])+ expect(body.filters.rules).toEqual([NEW_TARGETED_RELEASE_RULE])+ expect(router.values.location.pathname).toContain(urls.featureFlag(8))+ expect(refreshTreeItem).toHaveBeenCalledWith('feature_flag', '8')+ })++ it('blocks a create in a project that requires evaluation contexts, which a rules v2 create cannot set', () => {+ enabledFeaturesLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.FLAG_EVALUATION_TAGS]: true })+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, require_evaluation_contexts: true })+ const logic = featureFlagRulesV2EditorLogic({ id: 'new' })+ logic.mount()++ logic.actions.setDraft({ key: 'new-checkout' })+ expect(logic.values.saveDisabledReason).toContain('requires evaluation contexts')+ })++ describe('editing a stored flag', () => {+ let logic: ReturnType<typeof featureFlagRulesV2EditorLogic.build>++ let pageLogic: ReturnType<typeof featureFlagLogic.build>++ beforeEach(async () => {+ // The editor mounts once the flag page has loaded the row and entered edit mode.+ pageLogic = featureFlagLogic({ id: 7 })+ pageLogic.mount()+ await expectLogic(pageLogic, () => pageLogic.actions.editFeatureFlag(true))+ .toDispatchActions(['loadFeatureFlagSuccess'])+ .toFinishAllListeners()+ logic = featureFlagRulesV2EditorLogic({ id: 7 })+ logic.mount()+ })++ it('replaces the whole document, carries the row version and shows the saved flag', async () => {+ const update = jest.spyOn(api, 'update').mockResolvedValue({ ...V2_FLAG, version: 4 })++ const [firstKey, secondKey] = logic.values.ruleKeys+ logic.actions.moveRule(1, 0)+ expect(logic.values.ruleKeys).toEqual([secondKey, firstKey])+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagSuccess', 'loadFeatureFlagSuccess', 'editFeatureFlag'])+ .toNotHaveDispatchedActions(['loadFeatureFlag'])+ .toFinishAllListeners()++ const body = update.mock.calls[0][1] as Record<string, any>+ expect(body.version).toBe(3)+ expect(body.filters.rules.map((rule: { id: string }) => rule.id)).toEqual(['rule-rollout', 'rule-beta'])+ expect(JSON.stringify(body)).not.toContain('seed')+ expect(refreshTreeItem).toHaveBeenCalledWith('feature_flag', '7')+ expect(pageLogic.values).toMatchObject({ isEditingFlag: false, featureFlag: { version: 4 } })+ })++ it.each([+ {+ edit: 'a rule move',+ confirmation: true,+ dialog: 'Confirm changes to feature flag "new-checkout"?',+ apply: () => logic.actions.moveRule(1, 0),+ },+ {+ edit: 'a name change',+ confirmation: true,+ dialog: null,+ apply: () => logic.actions.setDraft({ name: 'Renamed' }),+ },+ {+ edit: 'a key change',+ confirmation: false,+ dialog: 'Change flag key?',+ apply: () => logic.actions.setDraft({ key: 'checkout-v2' }),+ },+ ])('with project confirmation $confirmation, $edit asks $dialog', async ({ confirmation, dialog, apply }) => {+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ feature_flag_confirmation_enabled: confirmation,+ })+ const openDialog = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const update = jest.spyOn(api, 'update').mockResolvedValue({ ...V2_FLAG, version: 4 })++ apply()+ logic.actions.saveRulesV2Flag()+ expect(openDialog.mock.calls.map(([props]) => props.title)).toEqual(dialog ? [dialog] : [])+ if (dialog) {+ expect(update).not.toHaveBeenCalled()+ openDialog.mock.calls[0][0].primaryButton?.onClick?.(undefined as any)+ }+ await expectLogic(logic).toDispatchActions(['saveRulesV2FlagSuccess']).toFinishAllListeners()+ expect(update).toHaveBeenCalledTimes(1)+ })++ it('does not save a key change whose confirmation is cancelled', async () => {+ const openDialog = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})+ const update = jest.spyOn(api, 'update')++ logic.actions.setDraft({ key: 'checkout-v2' })+ logic.actions.saveRulesV2Flag()+ expect(openDialog.mock.calls.map(([props]) => props.title)).toEqual(['Change flag key?'])+ openDialog.mock.calls[0][0].onAfterClose?.()+ await expectLogic(logic).toFinishAllListeners()++ expect(update).not.toHaveBeenCalled()+ expect(logic.values.saving).toBe(false)+ })++ it('saves with the version its draft was loaded from, even after the page refreshed underneath', async () => {+ const update = jest.spyOn(api, 'update').mockResolvedValue({ ...V2_FLAG, version: 6 })+ // A background refresh (for example after an AI change) replaces the page's flag while the draft is open.+ featureFlagLogic({ id: 7 }).actions.setFeatureFlag({ ...V2_FLAG, version: 5 })++ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagSuccess'])+ .toFinishAllListeners()++ expect((update.mock.calls[0][1] as Record<string, any>).version).toBe(3)+ })++ it('asks before navigating away from unsaved edits, and not after saving', async () => {+ const confirm = jest.spyOn(window, 'confirm').mockReturnValue(false)+ expect(logic.values.hasUnsavedChanges).toBe(false)++ logic.actions.setConfig({ default_value: null })+ router.actions.push(urls.featureFlags())+ expect(confirm).toHaveBeenCalledTimes(1)++ jest.spyOn(api, 'update').mockResolvedValue({ ...V2_FLAG, version: 4 })+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagSuccess'])+ .toFinishAllListeners()+ expect(logic.values.hasUnsavedChanges).toBe(false)+ })++ it('keeps unsaved edits when the flag page URL is pushed again', async () => {+ router.actions.push(urls.featureFlag(7))+ await expectLogic(pageLogic).toDispatchActions(['loadFeatureFlagSuccess']).toFinishAllListeners()+ pageLogic.actions.editFeatureFlag(true)++ logic.actions.setConfig({ default_value: null })+ // The project-prefixed path passes the editor's unload prompt, so only featureFlagLogic's guard keeps the draft.+ await expectLogic(pageLogic, () => router.actions.push(router.values.location.pathname))+ .toFinishAllListeners()+ .toMatchValues({ isEditingFlag: true })+ expect(logic.values.draft.config.default_value).toBeNull()++ // Cancel leaves the draft dirty, so closing the editor is what lets later pushes reach the page.+ expect(pageLogic.values.rulesV2DraftDirty).toBe(true)+ logic.unmount()+ expect(pageLogic.values.rulesV2DraftDirty).toBe(false)+ })++ it.each([+ {+ condition: 'an exact match with no value',+ operator: PropertyOperator.Exact,+ value: null,+ reason: 'Choose a value for every condition in rule 2.',+ },+ {+ condition: 'an exact match with every value removed',+ operator: PropertyOperator.Exact,+ value: [],+ reason: 'Choose a value for every condition in rule 2.',+ },+ {+ condition: 'a membership check with no values',+ operator: PropertyOperator.In,+ value: [],+ reason: 'Choose a value for every condition in rule 2.',+ },+ { condition: 'an is-set check', operator: PropertyOperator.IsSet, value: null, reason: null },+ { condition: 'an is-not-set check', operator: PropertyOperator.IsNotSet, value: null, reason: null },+ ])('with $condition, the save guard says $reason', ({ operator, value, reason }) => {+ const rule = logic.values.draft.config.rules[1]+ logic.actions.updateRule(1, {+ ...rule,+ targeting: { properties: [{ key: 'email', type: PropertyFilterType.Person, operator, value }] },+ })+ expect(logic.values.saveDisabledReason).toBe(reason)+ })++ it.each([+ { key: '', reason: 'Please set a key' },+ { key: 'a'.repeat(401), reason: 'Key must be 400 characters or less.' },+ ])('with the key $key.length characters long, the save guard says $reason', ({ key, reason }) => {+ logic.actions.setDraft({ key })+ expect(logic.values.saveDisabledReason).toBe(reason)+ })++ it('saves a stored flag in a project that requires evaluation contexts, which only a create must set', () => {+ enabledFeaturesLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.FLAG_EVALUATION_TAGS]: true })+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, require_evaluation_contexts: true })++ logic.actions.setDraft({ name: 'Renamed' })+ expect(logic.values.saveDisabledReason).toBeNull()+ })++ it('shows a validation error against its field and in a toast, and clears it on the next edit', async () => {+ const toastError = jest.spyOn(lemonToast, 'error')+ jest.spyOn(api, 'update').mockRejectedValue({+ status: 400,+ detail: 'filters.rules[1].rollout_percentage: Must be at most 100.',+ })++ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())+ .toDispatchActions(['saveRulesV2FlagFailure'])+ .toMatchValues({+ saveError: { field: 'filters.rules[1].rollout_percentage', message: 'Must be at most 100.' },+ saving: false,+ })+ expect(toastError).toHaveBeenCalledWith('Flag not saved: Must be at most 100.')++ logic.actions.updateRule(1, { ...logic.values.draft.config.rules[1] })+ expect(logic.values).toMatchObject({+ hasUnsavedChanges: false,+ saveError: { message: 'Must be at most 100.' },+ })++ logic.actions.setConfig({ default_value: null })+ expect(logic.values.saveError).toBeNull()+ })++ it('reloads the flag and leaves the editor when the row version is stale', async () => {+ jest.spyOn(api, 'update').mockRejectedValue({ status: 409, detail: 'This feature flag has changed.' })+ useMocks({+ get: {+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [+ 200,+ { ...V2_FLAG, name: 'Renamed elsewhere', version: 4 },+ ],+ },+ })++ await expectLogic(logic, () => logic.actions.saveRulesV2Flag()).toDispatchActions([+ 'editFeatureFlag',+ 'refreshFeatureFlag',+ ])+ await expectLogic(pageLogic).toDispatchActions(['refreshFeatureFlagSuccess']).toFinishAllListeners()+ expect(logic.values).toMatchObject({ saveError: null, saving: false })+ expect(pageLogic.values).toMatchObject({+ isEditingFlag: false,+ featureFlag: { name: 'Renamed elsewhere', version: 4 },+ })+ })+ })+})diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.tsnew file mode 100644index 000000000000..5e029860b515--- /dev/null+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts@@ -0,0 +1,559 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { beforeUnload, router } from 'kea-router'+import { CombinedLocation } from 'kea-router/lib/utils'+import { subscriptions } from 'kea-subscriptions'++import { readableErrorMessage } from 'lib/api-error'+import { isEmptyProperty, isPropertyFilterWithOperator } from 'lib/components/PropertyFilters/utils'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { objectsEqual } from 'lib/utils/objects'+import { projectLogic } from 'scenes/projectLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'+import {+ FeatureFlagConfig,+ FeatureFlagRulesV2DraftConfig,+ FeatureFlagRulesV2DraftRule,+ FeatureFlagRulesV2Rule,+ FeatureFlagType,+ PropertyOperator,+ TeamPublicType,+ TeamType,+} from '~/types'++import {+ isRulesV2FeatureFlagConfig,+ isStaleRowVersionError,+ rulesV2CreateDisabledReason,+} from 'products/feature_flags/frontend/featureFlagConfigFormat'+import { featureFlagsCreate, featureFlagsPartialUpdate } from 'products/feature_flags/frontend/generated/api'+import type {+ FeatureFlagCreateRequestSchemaApi,+ PatchedFeatureFlagPartialUpdateRequestSchemaApi,+} from 'products/feature_flags/frontend/generated/api.schemas'++import { checkFeatureFlagConfirmation } from './featureFlagConfirmationLogic'+import { confirmFeatureFlagKeyChange } from './featureFlagKeyChangeDialog'+import {+ FeatureFlagLogicProps,+ featureFlagLogic,+ validateFeatureFlagKey,+ variantKeyToIndexFeatureFlagPayloads,+} from './featureFlagLogic'++export interface FeatureFlagRulesV2Draft {+ key: string+ name: string+ tags: string[]+ config: FeatureFlagRulesV2DraftConfig+ /** The row version the draft was loaded from, so a save never pairs old rules with a newer version. */+ version: number | null+}++/** The first save error, keyed to the editor field its path names; `field` is null when no field owns it. */+export interface RulesV2SaveError {+ field: string | null+ message: string+}++export interface RulesV2WriteBody {+ key: string+ name: string+ tags: string[]+ filters: FeatureFlagRulesV2DraftConfig+ version?: number+}++export const NEW_RULES_V2_DRAFT: FeatureFlagRulesV2Draft = {+ key: '',+ name: '',+ tags: [],+ config: { version: 2, return_type: 'boolean', default_value: false, rules: [] },+ version: null,+}++export const BOOLEAN_OPTIONS = [+ { value: 'true', label: 'true' },+ { value: 'false', label: 'false' },+]++export const NEW_TARGETED_RELEASE_RULE: FeatureFlagRulesV2DraftRule = {+ rule_type: 'targeted_release',+ targeting: { properties: [] },+ value: true,+}++// The rollout fields a rule gains when it becomes a percentage rollout; the server assigns its seed.+export const NEW_ROLLOUT_FIELDS = {+ rollout_percentage: 0,+ on_rollout_miss: 'continue',+ assignment_algorithm: 'sha1_60_v1',+ assign_by: 'person',+} as const++// React keys for rule cards: new rules have no id, and index keys would follow a moved rule's position.+let lastRuleKey = 0+const nextRuleKey = (): number => ++lastRuleKey++function moved<T>(items: T[], from: number, to: number): T[] {+ const result = [...items]+ result.splice(to, 0, ...result.splice(from, 1))+ return result+}++const RULE_FIELDS = new Set(['rule_type', 'description', 'targeting', 'value', 'rollout_percentage', 'on_rollout_miss'])++/** Keeps the rule's identity and shared fields; rollout fields come and go with the type. */+export function withRuleType(+ rule: FeatureFlagRulesV2DraftRule,+ ruleType: FeatureFlagRulesV2DraftRule['rule_type']+): FeatureFlagRulesV2DraftRule {+ if (rule.rule_type === ruleType) {+ return rule+ }+ const { id, targeting, description, metadata, value } = rule+ const shared = { id, targeting, description, metadata, value }+ return ruleType === 'percentage_rollout'+ ? { ...shared, rule_type: ruleType, ...NEW_ROLLOUT_FIELDS }+ : { ...shared, rule_type: ruleType }+}++function toDraftRule(rule: FeatureFlagRulesV2Rule): FeatureFlagRulesV2DraftRule {+ if (rule.rule_type === 'targeted_release') {+ return rule+ }+ if (rule.rule_type === 'percentage_rollout') {+ const { seed: _seed, ...draftRule } = rule+ return draftRule+ }+ // Only editable documents reach the editor; dropping a rule here would delete it on save.+ throw new Error('Experiment rules cannot be edited here.')+}++export function rulesV2DraftFromFlag(flag: FeatureFlagType): FeatureFlagRulesV2Draft {+ if (!isRulesV2FeatureFlagConfig(flag.filters)) {+ return NEW_RULES_V2_DRAFT+ }+ return {+ key: flag.key,+ name: flag.name ?? '',+ tags: flag.tags ?? [],+ config: { ...flag.filters, rules: flag.filters.rules.map(toDraftRule) },+ version: flag.version,+ }+}++/** A create carries no row version; an update replaces the whole document and must carry it. */+export function rulesV2WriteBody(draft: FeatureFlagRulesV2Draft): RulesV2WriteBody {+ return {+ key: draft.key,+ name: draft.name,+ tags: draft.tags,+ filters: draft.config,+ ...(draft.version != null ? { version: draft.version } : {}),+ }+}++function editorField(path: string): string | null {+ if (path === 'key' || path === 'name' || path === 'tags' || path === 'filters.default_value') {+ return path+ }+ const rule = /^filters\.rules\[(\d+)\](?:\.(\w+))?/.exec(path)+ if (!rule) {+ return null+ }+ return rule[2] && RULE_FIELDS.has(rule[2]) ? `filters.rules[${rule[1]}].${rule[2]}` : `filters.rules[${rule[1]}]`+}++/** Field errors arrive with `attr`; document errors arrive as `detail` prefixed with their `filters…` path. */+export function rulesV2SaveError(error: any): RulesV2SaveError {+ const detail = readableErrorMessage(error) ?? 'This flag could not be saved.'+ const prefixed = error?.attr ? null : /^(filters(?:\.\w+|\[\d+\])*): (.+)$/s.exec(detail)+ const path: string | null = error?.attr || prefixed?.[1] || null+ const field = path ? editorField(path) : null+ // Only an exact field match drops the path; everything else is shown verbatim.+ const exact = field !== null && field === path+ return { field, message: exact && prefixed ? prefixed[2] : detail }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureFlagRulesV2EditorLogicValues {+ enabledFeatures: FeatureFlagsSet // featureFlagLogic+ featureFlag: FeatureFlagType // featureFlagLogic+ currentProjectId: number | null // projectLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ draft: FeatureFlagRulesV2Draft+ fieldError: (field: string) => string | null+ hasUnsavedChanges: boolean+ ruleKeys: number[]+ saveDisabledReason: string | null+ saveError: RulesV2SaveError | null+ saving: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureFlagRulesV2EditorLogicActions {+ editFeatureFlag: (+ editing: boolean,+ options?:+ | {+ expandAdvanced?: boolean+ }+ | undefined+ ) => {+ editing: boolean+ expandAdvanced: boolean+ } // featureFlagLogic+ loadFeatureFlagSuccess: (+ featureFlag: FeatureFlagType,+ payload?: any+ ) => {+ featureFlag: FeatureFlagType+ payload?: any+ } // featureFlagLogic+ refreshFeatureFlag: (+ payload?:+ | {+ afterAgentChange?: boolean+ }+ | undefined+ ) => {+ afterAgentChange?: boolean+ } // featureFlagLogic+ setRulesV2DraftDirty: (dirty: boolean) => {+ dirty: boolean+ } // featureFlagLogic+ addRule: () => {+ value: true+ }+ loadDraft: (draft: FeatureFlagRulesV2Draft) => {+ draft: FeatureFlagRulesV2Draft+ }+ moveRule: (+ from: number,+ to: number+ ) => {+ from: number+ to: number+ }+ removeRule: (index: number) => {+ index: number+ }+ saveRulesV2Flag: () => {+ value: true+ }+ saveRulesV2FlagFailure: (error: RulesV2SaveError | null) => {+ error: RulesV2SaveError | null+ }+ saveRulesV2FlagSuccess: (flag: FeatureFlagType) => {+ flag: FeatureFlagType+ }+ setConfig: (config: Partial<FeatureFlagRulesV2DraftConfig>) => {+ config: Partial<FeatureFlagRulesV2DraftConfig>+ }+ setDraft: (draft: Partial<FeatureFlagRulesV2Draft>) => {+ draft: Partial<FeatureFlagRulesV2Draft>+ }+ setRule: (+ index: number,+ rule: FeatureFlagRulesV2DraftRule+ ) => {+ index: number+ rule: FeatureFlagRulesV2DraftRule+ }+ submitRulesV2Flag: () => {+ value: true+ }+ updateRule: (+ index: number,+ rule: FeatureFlagRulesV2DraftRule+ ) => {+ index: number+ rule: FeatureFlagRulesV2DraftRule+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureFlagRulesV2EditorLogicMeta {+ key: number | 'link' | 'new'+ __keaTypeGenInternalSelectorTypes: {+ fieldError: (saveError: RulesV2SaveError | null) => (field: string) => string | null+ saveDisabledReason: (+ draft: FeatureFlagRulesV2Draft,+ currentTeam: TeamPublicType | TeamType | null,+ enabledFeatures: FeatureFlagsSet,+ id: number | 'link' | 'new'+ ) => string | null+ }+}++export type featureFlagRulesV2EditorLogicType = MakeLogicType<+ featureFlagRulesV2EditorLogicValues,+ featureFlagRulesV2EditorLogicActions,+ FeatureFlagLogicProps,+ featureFlagRulesV2EditorLogicMeta+>++export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicType>([+ path(['scenes', 'feature-flags', 'featureFlagRulesV2EditorLogic']),+ props({} as FeatureFlagLogicProps),+ key(({ id }) => id),+ connect((props: FeatureFlagLogicProps) => ({+ values: [+ featureFlagLogic(props),+ ['featureFlag', 'enabledFeatures'],+ projectLogic,+ ['currentProjectId'],+ teamLogic,+ ['currentTeam'],+ ],+ actions: [+ featureFlagLogic(props),+ ['editFeatureFlag', 'loadFeatureFlagSuccess', 'refreshFeatureFlag', 'setRulesV2DraftDirty'],+ ],+ })),+ actions({+ loadDraft: (draft: FeatureFlagRulesV2Draft) => ({ draft }),+ setDraft: (draft: Partial<FeatureFlagRulesV2Draft>) => ({ draft }),+ setConfig: (config: Partial<FeatureFlagRulesV2DraftConfig>) => ({ config }),+ addRule: true,+ updateRule: (index: number, rule: FeatureFlagRulesV2DraftRule) => ({ index, rule }),+ setRule: (index: number, rule: FeatureFlagRulesV2DraftRule) => ({ index, rule }),+ removeRule: (index: number) => ({ index }),+ moveRule: (from: number, to: number) => ({ from, to }),+ saveRulesV2Flag: true,+ submitRulesV2Flag: true,+ saveRulesV2FlagSuccess: (flag: FeatureFlagType) => ({ flag }),+ saveRulesV2FlagFailure: (error: RulesV2SaveError | null) => ({ error }),+ }),+ reducers({+ draft: [+ NEW_RULES_V2_DRAFT,+ {+ loadDraft: (_, { draft }) => draft,+ setDraft: (state, { draft }) => ({ ...state, ...draft }),+ setConfig: (state, { config }) => ({ ...state, config: { ...state.config, ...config } }),+ addRule: (state) => ({+ ...state,+ config: { ...state.config, rules: [...state.config.rules, NEW_TARGETED_RELEASE_RULE] },+ }),+ setRule: (state, { index, rule }) => ({+ ...state,+ config: { ...state.config, rules: state.config.rules.map((r, i) => (i === index ? rule : r)) },+ }),+ removeRule: (state, { index }) => ({+ ...state,+ config: { ...state.config, rules: state.config.rules.filter((_, i) => i !== index) },+ }),+ moveRule: (state, { from, to }) => ({+ ...state,+ config: { ...state.config, rules: moved(state.config.rules, from, to) },+ }),+ },+ ],+ ruleKeys: [+ [] as number[],+ {+ loadDraft: (_, { draft }) => draft.config.rules.map(nextRuleKey),+ setDraft: (state, { draft }) => (draft.config ? draft.config.rules.map(nextRuleKey) : state),+ setConfig: (state, { config }) => (config.rules ? config.rules.map(nextRuleKey) : state),+ addRule: (state) => [...state, nextRuleKey()],+ removeRule: (state, { index }) => state.filter((_, i) => i !== index),+ moveRule: (state, { from, to }) => moved(state, from, to),+ },+ ],+ // Rule indices shift on any edit, so an error is only shown against the document it came from.+ saveError: [+ null as RulesV2SaveError | null,+ {+ saveRulesV2FlagFailure: (_, { error }) => error,+ saveRulesV2Flag: () => null,+ setDraft: () => null,+ setConfig: () => null,+ addRule: () => null,+ setRule: () => null,+ removeRule: () => null,+ moveRule: () => null,+ },+ ],+ hasUnsavedChanges: [+ false,+ {+ loadDraft: () => false,+ saveRulesV2FlagSuccess: () => false,+ setDraft: () => true,+ setConfig: () => true,+ addRule: () => true,+ setRule: () => true,+ removeRule: () => true,+ moveRule: () => true,+ },+ ],+ saving: [+ false,+ {+ submitRulesV2Flag: () => true,+ saveRulesV2FlagSuccess: () => false,+ saveRulesV2FlagFailure: () => false,+ },+ ],+ }),+ selectors({+ fieldError: [+ (s) => [s.saveError],+ (saveError: RulesV2SaveError | null) =>+ (field: string): string | null =>+ saveError?.field === field ? saveError.message : null,+ ],+ saveDisabledReason: [+ (s, p) => [s.draft, s.currentTeam, s.enabledFeatures, p.id],+ (+ draft: FeatureFlagRulesV2Draft,+ currentTeam: TeamPublicType | TeamType | null,+ enabledFeatures: FeatureFlagsSet,+ id: FeatureFlagLogicProps['id']+ ): string | null => {+ // The list disables this entry point, but a direct link still opens the editor.+ const createDisabledReason =+ id === 'new' ? rulesV2CreateDisabledReason(currentTeam, enabledFeatures) : null+ if (createDisabledReason) {+ return createDisabledReason+ }+ const keyError = validateFeatureFlagKey(draft.key)+ if (keyError) {+ return keyError+ }+ const badRollout = draft.config.rules.some(+ (rule) =>+ rule.rule_type === 'percentage_rollout' &&+ !(rule.rollout_percentage >= 0 && rule.rollout_percentage <= 100)+ )+ if (badRollout) {+ return 'Rollout percentages must be between 0 and 100.'+ }+ // The server accepts a condition with no value, but the condition never matches.+ // Set and not-set conditions take no value, so they are not incomplete.+ const emptyConditionIndex = draft.config.rules.findIndex((rule) =>+ rule.targeting.properties.some(+ (property) =>+ isEmptyProperty(property) &&+ !(+ isPropertyFilterWithOperator(property) &&+ [PropertyOperator.IsSet, PropertyOperator.IsNotSet].includes(property.operator)+ )+ )+ )+ return emptyConditionIndex >= 0+ ? `Choose a value for every condition in rule ${emptyConditionIndex + 1}.`+ : null+ },+ ],+ }),+ listeners(({ actions, values, props }) => ({+ // Inputs such as PercentageInput report a change on every blur, and an unchanged rule is not an edit.+ updateRule: ({ index, rule }) => {+ if (!objectsEqual(values.draft.config.rules[index], rule)) {+ actions.setRule(index, rule)+ }+ },+ saveRulesV2Flag: async () => {+ const storedFlag = values.featureFlag+ if (+ storedFlag.id &&+ storedFlag.key !== values.draft.key &&+ !(await confirmFeatureFlagKeyChange(storedFlag.key))+ ) {+ return+ }+ // The server does not enforce the project's confirmation setting, so this check is the only gate.+ // Both sides are compared without seeds, because the draft never holds one and a stored seed would count as a change.+ const confirmationEnabled = !!values.currentTeam?.feature_flag_confirmation_enabled+ const confirmationShown = checkFeatureFlagConfirmation(+ { ...storedFlag, filters: rulesV2DraftFromFlag(storedFlag).config as FeatureFlagConfig },+ { ...storedFlag, key: values.draft.key, filters: values.draft.config as FeatureFlagConfig },+ confirmationEnabled,+ confirmationEnabled ? values.currentTeam?.feature_flag_confirmation_message : undefined,+ confirmationEnabled,+ actions.submitRulesV2Flag+ )+ if (!confirmationShown) {+ actions.submitRulesV2Flag()+ }+ },+ submitRulesV2Flag: async () => {+ const projectId = String(values.currentProjectId)+ const body = rulesV2WriteBody(values.draft)+ try {+ // The wire types describe the v1 document; the v2 document travels under the same `filters` key.+ const saved =+ props.id === 'new'+ ? await featureFlagsCreate(projectId, body as unknown as FeatureFlagCreateRequestSchemaApi)+ : await featureFlagsPartialUpdate(+ projectId,+ props.id as number,+ body as unknown as PatchedFeatureFlagPartialUpdateRequestSchemaApi+ )+ actions.saveRulesV2FlagSuccess(saved as unknown as FeatureFlagType)+ } catch (error: any) {+ if (isStaleRowVersionError(body, error)) {+ lemonToast.error(+ 'This flag changed while you were editing it. It has been reloaded; your edits were not saved.'+ )+ actions.saveRulesV2FlagFailure(null)+ actions.editFeatureFlag(false)+ actions.refreshFeatureFlag()+ return+ }+ const saveError = rulesV2SaveError(error)+ actions.saveRulesV2FlagFailure(saveError)+ // The inline error can sit off-screen and is not announced, so a toast reports the rejection too.+ lemonToast.error(`Flag not saved: ${saveError.message}`)+ }+ },+ saveRulesV2FlagSuccess: ({ flag }) => {+ lemonToast.success('Flag saved')+ if (flag.id) {+ refreshTreeItem('feature_flag', String(flag.id))+ }+ if (props.id === 'new') {+ router.actions.push(urls.featureFlag(flag.id ?? 'new'))+ return+ }+ // The response is the stored flag, so the page takes it without a second request.+ actions.loadFeatureFlagSuccess(variantKeyToIndexFeatureFlagPayloads(flag))+ actions.editFeatureFlag(false)+ },+ })),+ // featureFlagLogic resets the page on a same-URL navigation unless it knows the draft is dirty.+ subscriptions(({ actions }) => ({+ hasUnsavedChanges: (dirty: boolean) => actions.setRulesV2DraftDirty(dirty),+ })),+ beforeUnmount(({ actions }) => actions.setRulesV2DraftDirty(false)),+ beforeUnload(({ values }) => ({+ // In-page URL updates such as opening the side panel keep the pathname and the draft.+ enabled: (newLocation?: CombinedLocation) =>+ values.hasUnsavedChanges && newLocation?.pathname !== router.values.location.pathname,+ message: 'Leave this flag?\nChanges you made will be discarded.',+ })),+ afterMount(({ actions, values, props }) => {+ if (typeof props.id === 'number') {+ actions.loadDraft(rulesV2DraftFromFlag(values.featureFlag))+ }+ }),+])diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 8ed284a08982..316cc0af9039 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4541,6 +4541,15 @@ export interface FeatureFlagUnsupportedConfig extends WithoutFeatureFlagFiltersKaggregation_group_type_index?: never}+/** A rule while the editor drafts it: a new rule has no `id` until the server assigns one, and no draft holds a `seed`. */+export type FeatureFlagRulesV2DraftRule =+ | (Omit<FeatureFlagRulesV2TargetedReleaseRule, 'id'> & { id?: string })+ | (Omit<FeatureFlagRulesV2PercentageRolloutRule, 'id' | 'seed'> & { id?: string })++export interface FeatureFlagRulesV2DraftConfig extends Omit<FeatureFlagRulesV2Config, 'rules'> {+ rules: FeatureFlagRulesV2DraftRule[]+}+/** What the API stores under a flag's `filters`, discriminated by `version` (absent means 1). */export type FeatureFlagConfig = FeatureFlagFilters | FeatureFlagRulesV2Config | FeatureFlagUnsupportedConfigdiff --git a/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx b/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsxindex e3b8acd46dd7..0fc5d635e87a 100644--- a/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx+++ b/products/feature_flags/frontend/FeatureFlagConfigReadonlyNotice.tsx@@ -1,21 +1,47 @@+import { useValues } from 'kea'+import { LemonBanner } from '@posthog/lemon-ui'+import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'+import { FeatureFlagConfig } from '~/types'-import { featureFlagConfigFormat, featureFlagConfigFormatLabel } from './featureFlagConfigFormat'+import {+ featureFlagConfigFormat,+ featureFlagConfigFormatLabel,+ isRulesV2EditableConfig,+} from './featureFlagConfigFormat'-export function FeatureFlagConfigReadonlyNotice({ filters }: { filters: FeatureFlagConfig }): JSX.Element {+export function FeatureFlagConfigReadonlyNotice({+ filters,+ hasEditButton = false,+}: {+ filters: FeatureFlagConfig+ hasEditButton?: boolean+}): JSX.Element {+ const { featureFlags } = useValues(enabledFeaturesLogic)const label = featureFlagConfigFormatLabel(filters)+ const editable = isRulesV2EditableConfig(filters, featureFlags)return (<LemonBanner type="info">- {featureFlagConfigFormat(filters) === 'v2' ? (+ {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.+ </>+ ) : editable && hasEditButton ? (+ <>+ This flag is stored as <strong>{label}</strong>. Use Edit to change its rules; archiving is not+ available yet.+ </>+ ) : editable ? (+ <>+ This flag is stored as <strong>{label}</strong> and is shown read-only here. Open the flag page to+ change its rules; archiving is not available yet.</>) : (<>- This flag is stored as <strong>{label}</strong>, which this page cannot display or change.+ 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.</>)}</LemonBanner>diff --git a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsxindex 2f608c898778..5056efe803b3 100644--- a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx+++ b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx@@ -111,7 +111,7 @@ export function FeatureFlagRulesV2Readonly({ config }: { config: FeatureFlagRulereturn (<div className="flex flex-col gap-4" data-attr="feature-flag-rules-v2-readonly">- <FeatureFlagConfigReadonlyNotice filters={config} />+ <FeatureFlagConfigReadonlyNotice filters={config} hasEditButton /><div className="flex flex-wrap gap-6 text-sm"><div className="flex flex-col gap-1"><span className="font-semibold">Return type</span>diff --git a/products/feature_flags/frontend/featureFlagConfigFormat.ts b/products/feature_flags/frontend/featureFlagConfigFormat.tsindex 61ed2a253446..6c5dd84b8c57 100644--- a/products/feature_flags/frontend/featureFlagConfigFormat.ts+++ b/products/feature_flags/frontend/featureFlagConfigFormat.ts@@ -1,6 +1,8 @@import { isApprovalRequiredError } from 'lib/api-error'+import { FEATURE_FLAGS } from 'lib/constants'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'-import { FeatureFlagConfig, FeatureFlagFilters, FeatureFlagRulesV2Config } from '~/types'+import { FeatureFlagConfig, FeatureFlagFilters, FeatureFlagRulesV2Config, TeamPublicType, TeamType } from '~/types'export type FeatureFlagConfigFormat = 'v1' | 'v2' | 'unsupported'@@ -61,3 +63,24 @@ export function featureFlagConfigFormatLabel(filters: FeatureFlagConfig | null |return typeof version === 'number' ? `Config v${version} (unsupported)` : 'Unsupported config'}}++/** The rules v2 create contract rejects `evaluation_contexts`, so a project that requires them rejects every rules v2 create. */+export function rulesV2CreateDisabledReason(+ team: TeamPublicType | TeamType | null,+ enabledFeatures: FeatureFlagsSet+): string | null {+ return enabledFeatures[FEATURE_FLAGS.FLAG_EVALUATION_TAGS] && team?.require_evaluation_contexts+ ? "This project requires evaluation contexts on new flags, and rules v2 flags can't set them yet."+ : null+}++/** Whether the rules v2 editor is on and can edit this document: boolean return type, person assignment, no experiment rules. */+export function isRulesV2EditableConfig(filters: FeatureFlagConfig, enabledFeatures: FeatureFlagsSet): boolean {+ return (+ !!enabledFeatures[FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR] &&+ isRulesV2FeatureFlagConfig(filters) &&+ filters.return_type === 'boolean' &&+ filters.aggregation_group_type_index == null &&+ filters.rules.every((rule) => rule.rule_type !== 'experiment' && typeof rule.value === 'boolean')+ )+}diff --git a/products/feature_flags/manifest.tsx b/products/feature_flags/manifest.tsxindex 2bb03349c9e7..f8b44cac14ca 100644--- a/products/feature_flags/manifest.tsx+++ b/products/feature_flags/manifest.tsx@@ -35,11 +35,13 @@ export const manifest: ProductManifest = {sourceId,template,intent,+ format,}: {type?: 'boolean' | 'multivariate' | 'remote_config'sourceId?: number | string | nulltemplate?: 'simple' | 'targeted' | 'multivariate' | 'targeted-multivariate'intent?: 'local-eval' | 'first-page-load'+ format?: 'rules_v2'}): string => {const params = new URLSearchParams()if (type) {@@ -54,6 +56,9 @@ export const manifest: ProductManifest = {if (intent) {params.set('intent', intent)}+ if (format) {+ params.set('format', format)+ }return `/feature_flags/new?${params.toString()}`},},