: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
fix(flags): show approval and conflict outcomes in the flag editor (#114493)
Yasen00bf60a8d05f
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsxindex 47f5854c6fdf..18b53f38d1e5 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx@@ -15,7 +15,7 @@ import { CSS } from '@dnd-kit/utilities'import { useActions, useValues } from 'kea'import { Form, Group } from 'kea-forms'import { router } from 'kea-router'-import { useRef, useState } from 'react'+import { useEffect, useRef, useState } from 'react'import {IconBalance,@@ -202,14 +202,22 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {setAdvancedExpanded,resetEncryptedPayload,setAlsoCreateInProjects,+ startNewFlagDisabled,} = useActions(featureFlagLogic)const { tags: availableTags } = useValues(tagsModel)const { isApprovalRequired } = useValues(approvalsGateLogic)const { allCohorts } = useValues(cohortsModel)const hasEvaluationContexts = useFeatureFlag('FLAG_EVALUATION_TAGS') // NB: the tag was named "flag-evaluation-tags" before we renamed the concept – i.e. this powers evaluation contexts even though the name implies tagsconst isNewFeatureFlag = id === 'new' || id === undefined+ const requiresApprovalToEnable = isNewFeatureFlag && isApprovalRequired(ApprovalActionKey.FEATURE_FLAG_ENABLE)const implementationRef = useRef<HTMLDivElement>(null)+ useEffect(() => {+ if (requiresApprovalToEnable && featureFlag.active) {+ startNewFlagDisabled()+ }+ }, [requiresApprovalToEnable, featureFlag.active, startNewFlagDisabled])+const handleShowImplementation = (): void => {setShowImplementation(true)setTimeout(() => {@@ -504,14 +512,6 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {<LemonField name="active">{({ value, onChange }) => {- const requiresApprovalToEnable =- isNewFeatureFlag &&- isApprovalRequired(ApprovalActionKey.FEATURE_FLAG_ENABLE)-- if (requiresApprovalToEnable && value) {- queueMicrotask(() => onChange(false))- }-return (<LemonSwitchchecked={value}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex eaf0293e7f46..d46fdad5c9b9 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -24,6 +24,7 @@ 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 { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { organizationLogic } from 'scenes/organizationLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -1074,17 +1075,126 @@ describe('featureFlagLogic', () => {expect(router.values.location.pathname).toBe(embeddedPathname)})+ const approvalRequired = (): ApiError =>+ new ApiError(undefined, 409, undefined, {+ code: 'approval_required',+ status: 'approval_required',+ detail: 'A change request has been created and is pending approval.',+ change_request_id: 'cr-1',+ })++ const editOnFlagPage = async (name: string): Promise<void> => {+ router.actions.push(urls.featureFlag(MOCK_FEATURE_FLAG.id), { edit: true })+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setFeatureFlag({ ...logic.values.featureFlag, name })+ }+it('keeps the current route when an embedded editor save requires approval', async () => {const notebookUrl = urls.notebook('embedded-flag')router.actions.push(notebookUrl)const embeddedPathname = router.values.location.pathname+ jest.spyOn(sharedLemonToast, 'info').mockReturnValue('toast-id')await expectLogic(logic, () => {- logic.actions.saveFeatureFlagFailure('Approval required', { status: 409 })+ logic.actions.saveFeatureFlagFailure('Approval required', approvalRequired())}).toFinishAllListeners()expect(router.values.location.pathname).toBe(embeddedPathname)})++ it('shows the stored flag without a leave prompt when an edit needs approval', async () => {+ await editOnFlagPage('Unapproved name')+ jest.spyOn(api, 'update').mockRejectedValueOnce(approvalRequired())+ const confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(false)+ const approvalToast = jest.spyOn(sharedLemonToast, 'info').mockReturnValue('toast-id')++ await expectLogic(logic, () => {+ logic.actions.saveFeatureFlag(logic.values.featureFlag)+ })+ .toDispatchActions(['saveFeatureFlagFailure', 'loadFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(confirmSpy).not.toHaveBeenCalled()+ expect(approvalToast).toHaveBeenCalledTimes(1)+ expect(router.values.searchParams.edit).toBeUndefined()+ expect(logic.values).toMatchObject({+ isEditingFlag: false,+ hasUnsavedChanges: false,+ featureFlag: partial({ name: MOCK_FEATURE_FLAG.name }),+ })+ })++ it('opens the change request when creating a flag needs approval, and leaves the form clean', async () => {+ router.actions.push(urls.featureFlag('new'))+ const newLogic = featureFlagLogic({ id: 'new' })+ newLogic.mount()++ try {+ await expectLogic(newLogic).toFinishAllListeners()+ // A template loads a starting point that differs from the form defaults.+ await expectLogic(newLogic, () => {+ newLogic.actions.loadFeatureFlagSuccess({+ ...newLogic.values.featureFlag,+ filters: {+ ...NEW_FLAG.filters,+ groups: [{ properties: [], rollout_percentage: 50, variant: null }],+ },+ })+ }).toFinishAllListeners()+ newLogic.actions.startNewFlagDisabled()+ expect(newLogic.values).toMatchObject({ isFormDirty: false, featureFlag: partial({ active: false }) })+ newLogic.actions.setFeatureFlag({ ...newLogic.values.featureFlag, key: 'gated-flag' })+ jest.spyOn(api, 'create').mockRejectedValueOnce(approvalRequired())+ const confirmSpy = jest.spyOn(window, 'confirm').mockReturnValue(false)+ const approvalToast = jest.spyOn(sharedLemonToast, 'info').mockReturnValue('toast-id')++ await expectLogic(newLogic, () => {+ newLogic.actions.saveFeatureFlag(newLogic.values.featureFlag)+ })+ .toDispatchActions(['saveFeatureFlagFailure'])+ .toFinishAllListeners()++ expect(approvalToast).toHaveBeenCalledTimes(1)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe(urls.approval('cr-1'))++ router.actions.push(urls.featureFlags())+ expect(confirmSpy).not.toHaveBeenCalled()+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe(urls.featureFlags())+ } finally {+ newLogic.unmount()+ }+ })++ it.each([+ [+ 'a version conflict',+ new ApiError(undefined, 409, undefined, {+ code: 'conflict',+ detail: 'The feature flag was updated by another user since you started editing it.',+ }),+ 'The feature flag was updated by another user since you started editing it.',+ ],+ [+ 'a policy conflict',+ new ApiError(undefined, 400, undefined, {+ code: 'policy_conflict',+ error: 'This change matches multiple approval policies',+ }),+ "Couldn't save the flag. These changes need approval under more than one policy, so save them one at a time.",+ ],+ ])('keeps the edit open and explains %s', async (_, error, message) => {+ await editOnFlagPage('Edited name')+ jest.spyOn(api, 'update').mockRejectedValueOnce(error)++ await expectLogic(logic, () => {+ logic.actions.saveFeatureFlag(logic.values.featureFlag)+ })+ .toDispatchActions(['saveFeatureFlagFailure'])+ .toFinishAllListeners()++ expect(lemonToast.error).toHaveBeenCalledWith(message)+ expect(logic.values).toMatchObject({ isEditingFlag: true, featureFlag: partial({ name: 'Edited name' }) })+ })})describe('setMultivariateEnabled functionality', () => {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex a4b02744a796..d5eaab31cbaf 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -25,7 +25,7 @@ import posthog from 'posthog-js'import { toast } from 'react-toastify'import api, { PaginatedResponse } from 'lib/api'-import { isAccessDeniedError } from 'lib/api-error'+import { isAccessDeniedError, isApprovalRequiredError } from 'lib/api-error'import { handleApprovalRequired } from 'lib/approvals/utils'import { ACTIVITY_SEARCH_PARAM } from 'lib/components/ActivityLog/activityLogLogic'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'@@ -42,6 +42,8 @@ import { stringifyWithBigInts } from 'lib/utils/json'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { objectsEqual } from 'lib/utils/objects'import { capitalizeFirstLetter, humanList, slugify } from 'lib/utils/strings'+import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'+import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'import { experimentLogic } from 'scenes/experiments/experimentLogic'import { FeatureFlagsTab, featureFlagsLogic, isFeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'import { projectLogic } from 'scenes/projectLogic'@@ -1864,6 +1866,9 @@ export interface featureFlagLogicActions {requireStatusConfirmation?: boolean | undefinedupdatedFlag: Partial<FeatureFlagType>}+ startNewFlagDisabled: () => {+ value: true+ }stopRecurringScheduledChange: (scheduledChangeId: number) => {scheduledChangeId: number}@@ -2309,6 +2314,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// Re-establishes the saved-state baseline the unsaved-changes guard diffs against.// Only dispatch with server-authoritative state, so in-progress edits stay dirty.setOriginalFeatureFlag: (featureFlag: FeatureFlagType | null) => ({ featureFlag }),+ // A new flag starts disabled while enabling needs approval. The baseline follows, so the+ // unsaved-changes guard does not count the forced value as an edit.+ startNewFlagDisabled: true,refreshFeatureFlagAfterAgentChange: true,setFeatureFlagFilters: (filters: FeatureFlagFilters, errors: any) => ({ filters, errors }),setSelectedTab: (tab: FeatureFlagsTab) => ({ tab }),@@ -2472,6 +2480,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// navigation. Server-authoritative re-baselines flow through setOriginalFeatureFlag.loadFeatureFlagSuccess: (_, { featureFlag }) => toFeatureFlagBaseline(featureFlag),setOriginalFeatureFlag: (_, { featureFlag }) => featureFlag,+ startNewFlagDisabled: (state) => (state ? { ...state, active: false } : state),},],featureFlag: [@@ -2480,6 +2489,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([setFeatureFlag: (_, { featureFlag }) => {return featureFlag},+ startNewFlagDisabled: (state) => ({ ...state, active: false }),setFeatureFlagFilters: (state, { filters }) => {if (!state) {return state@@ -4085,15 +4095,57 @@ export const featureFlagLogic = kea<featureFlagLogicType>([globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(completedTasks)},saveFeatureFlagFailure: async ({ errorObject }) => {- if (values.featureFlag.id && handleApprovalRequired(errorObject, 'feature_flag', values.featureFlag.id)) {- if (isOnFeatureFlagPage(props.id)) {- // Redirect to detail page so user can see the CR banner- router.actions.replace(urls.featureFlag(values.featureFlag.id))+ if (isApprovalRequiredError(errorObject)) {+ const changeRequestId: string = errorObject.data.change_request_id+ showApprovalRequiredToast(changeRequestId, undefined, errorObject.data.code)+ const flagId = values.featureFlag.id+ if (flagId) {+ dispatchChangeRequestCreated({ resourceType: 'feature_flag', resourceId: flagId })+ }+ if (!isOnFeatureFlagPage(props.id)) {+ return+ }+ if (flagId) {+ // The unsaved-changes guard compares against the router's pathname, which carries the+ // project prefix that urls.featureFlag() lacks. Reuse it so the guard sees the same page.+ router.actions.replace(router.values.location.pathname)actions.editFeatureFlag(false)+ // The edit waits in the change request, so the page shows the stored flag again.+ actions.loadFeatureFlag()+ } else {+ // A gated create has no flag page yet, so open the change request instead. Reset the+ // form to the flag this page loaded, because the submitted values now live in the change+ // request. The hard-coded defaults would differ from a template's baseline and read as an edit.+ const baseline = values.originalFeatureFlag+ const loaded = baseline+ ? (variantKeyToIndexFeatureFlagPayloads(baseline) as FeatureFlagWithV1Config)+ : null+ actions.resetFeatureFlag(+ loaded+ ? { ...loaded, ensure_experience_continuity: loaded.ensure_experience_continuity ?? false }+ : undefined+ )+ router.actions.replace(urls.approval(changeRequestId))}return}+ if (errorObject?.status === 409) {+ // A version conflict. Keep the editor open, so the edit survives until the user reloads.+ lemonToast.error(+ errorObject.detail ||+ 'This flag changed after you started editing it. Refresh the page and try again.'+ )+ return+ }++ if (errorObject?.code === 'policy_conflict') {+ lemonToast.error(+ "Couldn't save the flag. These changes need approval under more than one policy, so save them one at a time."+ )+ return+ }+// initKea only toasts errors that carry a status, so a request that never reached the// server needs its own toast.if (errorObject?.status === undefined) {