: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): ask why on the flag page when a save lowers exposure (#125678)
Gustavo H. Strassburgera44e0f15dbe3
diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.tsindex c472d664a6f3..f10d895a2d0f 100644--- a/frontend/src/lib/api-error.test.ts+++ b/frontend/src/lib/api-error.test.ts@@ -147,6 +147,7 @@ describe('api-error', () => {['a re-auth gate', { status: 403, code: 'sensitive_action_required_reauth' }, false],['an approvals 409', { status: 409, data: { change_request_id: 'abc' } }, false],['an optimistic-concurrency 409', { status: 409, data: { current_version: 5 } }, false],+ ['a rollback reason 409', { status: 409, code: 'rollback_reason_required' }, false],['a 502', { status: 502 }, false],['a 503', { status: 503 }, false],['a 504', { status: 504 }, false],diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex 9ca0f2b3f0b3..e9c650f46a85 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -34,6 +34,13 @@ export function isApprovalRequiredError(error: { status?: number; data?: any } |return error?.status === 409 && Boolean(error?.data?.change_request_id)}+/** The flag API refuses an edit that lowers exposure when the request asks for a reason and sends none. */+export function isRollbackReasonRequiredError(+ error: { status?: number; code?: string | null } | null | undefined+): boolean {+ return error?.status === 409 && error?.code === 'rollback_reason_required'+}+/** Potentially transient failures; a gateway error does not prove that the backend did no work. */const TRANSIENT_GATEWAY_STATUSES: ReadonlySet<number> = new Set([502, 503, 504])@@ -234,6 +241,9 @@ export function shouldReportApiFailure(error: unknown): boolean {if (status === 409 && failure.data?.current_version !== undefined) {return false}+ if (isRollbackReasonRequiredError(failure)) {+ return false+ }return !isApprovalRequiredError(failure)}diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 2ed450eeb619..4fbb21481efa 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -343,6 +343,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_ROLLBACK_REASON: 'feature-flag-rollback-reason', // owner: @gustavo #team-feature-flags, asks why when a save on the flag page lowers the flag's exposureFEATURE_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_CALLED_MOVE_NOTICES: 'flag-called-move-notices', // owner: #team-feature-flags, shows in-app warnings about the upcoming $feature_flag_called move. Turn on only after the move is announced, because the warnings describe it as planneddiff --git a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.test.tsx b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.test.tsxindex 8f028de82584..f0947e93abcb 100644--- a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.test.tsx+++ b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.test.tsx@@ -32,12 +32,15 @@ describe('LemonFormDialog', () => {jest.restoreAllMocks()})- function renderDialog(onSubmit: (values: Record<string, any>) => void | Promise<void>): void {+ function renderDialog(+ onSubmit: (values: Record<string, any>) => void | Promise<void>,+ shouldAwaitSubmit = true+ ): void {render(<LemonFormDialogdialogKey="test-dialog"title="Test dialog"- shouldAwaitSubmit+ shouldAwaitSubmit={shouldAwaitSubmit}initialValues={{ name: 'a name' }}content={<LemonField name="name">@@ -103,6 +106,25 @@ describe('LemonFormDialog', () => {expect(captureException).not.toHaveBeenCalled()})+ it.each([+ ['Cancel', true, 0],+ ['Submit', true, 1],+ ['Cancel', false, 0],+ ['Submit', false, 1],+ ])(+ 'pressing Enter on the focused %s button only clicks it (await submit: %s)',+ async (button, awaitSubmit, submits) => {+ const onSubmit = jest.fn().mockResolvedValue(undefined)++ renderDialog(onSubmit, awaitSubmit)+ screen.getByText(button).closest('button')?.focus()+ await userEvent.keyboard('{Enter}')++ await waitForElementToBeRemoved(() => screen.queryByText('Submit'))+ expect(onSubmit).toHaveBeenCalledTimes(submits)+ }+ )+it.each(['Cancel', 'Submit'])('calls the imperative form close callback after %s', async (button) => {const onAfterClose = jest.fn()act(() => {diff --git a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsxindex edc88a09fe41..6ad031b2fabf 100644--- a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx+++ b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx@@ -179,6 +179,12 @@ const LemonDialogComponent = forwardRef<LemonDialogRef, LemonDialogProps>(functi)})+// The browser turns Enter on a focused button into a click on that button. Submitting the form as well would run+// Submit twice, or run it for Cancel.+function isEnterOnField(e: React.KeyboardEvent<HTMLFormElement>): boolean {+ return e.key === 'Enter' && !(e.target as HTMLElement).closest('button')+}+export const LemonFormDialog = ({initialValues = {},onSubmit,@@ -232,7 +238,7 @@ export const LemonFormDialog = ({onKeyDown={props.shouldAwaitSubmit? async (e: React.KeyboardEvent<HTMLFormElement>): Promise<void> => {- if (e.key === 'Enter' && primaryButton?.htmlType === 'submit' && isFormValid) {+ if (isEnterOnField(e) && primaryButton?.htmlType === 'submit' && isFormValid) {try {await onSubmit(form)} catch (error) {@@ -246,7 +252,7 @@ export const LemonFormDialog = ({}}: (e: React.KeyboardEvent<HTMLFormElement>): void => {- if (e.key === 'Enter' && primaryButton?.htmlType === 'submit' && isFormValid) {+ if (isEnterOnField(e) && primaryButton?.htmlType === 'submit' && isFormValid) {void onSubmit(form)ref?.current?.closeDialog()}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 89ed84609ca1..d3be3a0feaa5 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -69,6 +69,7 @@ import {import { detectFeatureFlagChanges } from './featureFlagConfirmationLogic'import {NEW_FLAG,+ RollbackReasonSource,convertIndexBasedPayloadsToVariantKeys,dependencyActionLabel,dependencyDisabledReason,@@ -3889,6 +3890,184 @@ describe('featureFlagLogic', () => {})})+ describe('rollback reason question', () => {+ const rollbackReasonRequired = (): ApiError =>+ new ApiError(undefined, 409, undefined, {+ type: 'invalid_request',+ code: 'rollback_reason_required',+ detail: "This edit lowers the flag's exposure.",+ })++ // The save sends tags the form does not hold, as the sidebar tags save does, so a resend of the form fails.+ const saveFrom: Record<RollbackReasonSource, (l: typeof logic) => void> = {+ save: (l) => l.actions.saveFeatureFlag({ ...l.values.featureFlag, tags: ['from-the-sidebar'] }),+ toggle: (l) => l.actions.updateFeatureFlagActive(false),+ }+ const sentBy: Record<RollbackReasonSource, Record<string, unknown>> = {+ save: { tags: ['from-the-sidebar'] },+ toggle: { active: false },+ }++ const withRollbackReasonFlag = (enabled: boolean): void => {+ enabledFeaturesLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.FEATURE_FLAG_ROLLBACK_REASON]: enabled })+ }++ let openForm: jest.SpyInstance++ beforeEach(() => {+ silenceKeaLoadersErrors()+ openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})+ logic.actions.setFeatureFlag({ ...MOCK_FEATURE_FLAG, active: true })+ })++ afterEach(() => {+ resumeKeaLoadersErrors()+ openForm.mockRestore()+ })++ it.each([+ [+ 'save',+ 'an answer',+ { reason: 'errors', note: 'Checkout broke' },+ { rollback_reason: 'errors', rollback_reason_note: 'Checkout broke' },+ ],+ [+ 'toggle',+ 'an answer',+ { reason: 'metrics', note: '' },+ { rollback_reason: 'metrics', rollback_reason_note: null },+ ],+ ['save', 'a skip', 'skipped', {}],+ ['toggle', 'a skip', 'skipped', {}],+ ] as const)(+ 'a %s save that lowers exposure asks why, then saves with %s',+ async (source, _label, choice, resentFields) => {+ withRollbackReasonFlag(true)+ const update = jest+ .spyOn(api, 'update')+ .mockRejectedValueOnce(rollbackReasonRequired())+ .mockResolvedValue({ ...MOCK_FEATURE_FLAG, active: source !== 'toggle' })++ await expectLogic(logic, () => saveFrom[source](logic)).toFinishAllListeners()++ expect(update).toHaveBeenCalledTimes(1)+ expect(update.mock.calls[0][1]).toEqual(expect.objectContaining({ ask_rollback_reason: true }))+ expect(capturesOf('feature flag rollback reason asked')).toEqual([+ ['feature flag rollback reason asked', { source }],+ ])++ const dialog = openForm.mock.calls[0][0]+ if (choice === 'skipped') {+ dialog.tertiaryButton.onClick()+ } else {+ dialog.onSubmit(choice)+ }+ dialog.onAfterClose()+ await expectLogic(logic).toFinishAllListeners()++ expect(update).toHaveBeenCalledTimes(2)+ const resent = update.mock.calls[1][1] as Record<string, unknown>+ expect(resent).not.toHaveProperty('ask_rollback_reason')+ expect(resent).toEqual(expect.objectContaining({ ...sentBy[source], ...resentFields }))+ expect(capturesOf('feature flag rollback reason skipped')).toEqual(+ choice === 'skipped' ? [['feature flag rollback reason skipped', { source }]] : []+ )+ expect(capturesOf('feature flag rollback reason canceled')).toEqual([])++ // The answer belongs to that edit only, so the next save asks again.+ await expectLogic(logic, () => saveFrom[source](logic)).toFinishAllListeners()+ expect(update.mock.calls[2][1]).toEqual(expect.objectContaining({ ask_rollback_reason: true }))+ expect(update.mock.calls[2][1]).not.toHaveProperty('rollback_reason')+ }+ )++ it.each(['save', 'toggle'] as const)(+ 'a %s retried after the resend fails on the network keeps the answer',+ async (source) => {+ withRollbackReasonFlag(true)+ const update = jest+ .spyOn(api, 'update')+ .mockRejectedValueOnce(rollbackReasonRequired())+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))+ .mockResolvedValue({ ...MOCK_FEATURE_FLAG, active: source !== 'toggle' })++ await expectLogic(logic, () => saveFrom[source](logic)).toFinishAllListeners()+ const dialog = openForm.mock.calls[0][0]+ dialog.onSubmit({ reason: 'errors', note: '' })+ dialog.onAfterClose()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => saveFrom[source](logic)).toFinishAllListeners()++ expect(update).toHaveBeenCalledTimes(3)+ expect(update.mock.calls[2][1]).toEqual(expect.objectContaining({ rollback_reason: 'errors' }))+ expect(openForm).toHaveBeenCalledTimes(1)+ }+ )++ it.each([+ ['the edit is canceled', 'save', (l: typeof logic) => l.actions.editFeatureFlag(false), 'save'],+ ['the flag is reloaded', 'save', (l: typeof logic) => l.actions.loadFeatureFlag(), 'save'],+ ['the next edit comes from the other source', 'toggle', () => {}, 'save'],+ ] as const)(+ 'an answer whose resend failed does not ride on the next edit when %s',+ async (_label, answeredFrom, discard, nextFrom) => {+ withRollbackReasonFlag(true)+ const update = jest+ .spyOn(api, 'update')+ .mockRejectedValueOnce(rollbackReasonRequired())+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))+ .mockResolvedValue({ ...MOCK_FEATURE_FLAG, active: true })++ await expectLogic(logic, () => saveFrom[answeredFrom](logic)).toFinishAllListeners()+ const dialog = openForm.mock.calls[0][0]+ dialog.onSubmit({ reason: 'errors', note: '' })+ dialog.onAfterClose()+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(logic, () => discard(logic)).toFinishAllListeners()++ await expectLogic(logic, () => saveFrom[nextFrom](logic)).toFinishAllListeners()++ expect(update.mock.calls[2][1]).toEqual(expect.objectContaining({ ask_rollback_reason: true }))+ expect(update.mock.calls[2][1]).not.toHaveProperty('rollback_reason')+ }+ )++ it('saves nothing when the question is closed without an answer', async () => {+ withRollbackReasonFlag(true)+ const update = jest.spyOn(api, 'update').mockRejectedValueOnce(rollbackReasonRequired())+ const toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ try {+ await expectLogic(logic, () => saveFrom.save(logic)).toFinishAllListeners()++ openForm.mock.calls[0][0].onAfterClose()+ await expectLogic(logic).toFinishAllListeners()++ expect(update).toHaveBeenCalledTimes(1)+ expect(capturesOf('feature flag rollback reason canceled')).toEqual([+ ['feature flag rollback reason canceled', { source: 'save' }],+ ])+ // The 409 must not read as a version conflict.+ expect(toastSpy).not.toHaveBeenCalled()+ } finally {+ toastSpy.mockRestore()+ }+ })++ it.each([+ ['the feature flag is off', false, () => logic.actions.saveFeatureFlag(logic.values.featureFlag)],+ ['the flag is turned on', true, () => logic.actions.updateFeatureFlagActive(true)],+ ])('does not ask when %s', async (_label, enabled, save) => {+ withRollbackReasonFlag(enabled)+ const update = jest.spyOn(api, 'update').mockResolvedValueOnce({ ...MOCK_FEATURE_FLAG, active: true })++ await expectLogic(logic, save).toFinishAllListeners()++ expect(update.mock.calls[0][1]).not.toHaveProperty('ask_rollback_reason')+ })+ })+describe('saveSidebarTags', () => {it('saves a v1 flag through the full save, evaluation contexts included', async () => {const update = jestdiff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 053ebb87352c..87aca80b8a2a 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, isAbortError } from 'lib/api'-import { isAccessDeniedError, isApprovalRequiredError } from 'lib/api-error'+import { isAccessDeniedError, isApprovalRequiredError, isRollbackReasonRequiredError } 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'@@ -123,6 +123,12 @@ import type {CopyFlagsDependencyRequirementsResponseApi,FeatureFlagStatusResponseApi,} from 'products/feature_flags/frontend/generated/api.schemas'+import {+ RollbackReasonAnswer,+ RollbackReasonRequestFields,+ rollbackReasonRequestFields,+} from 'products/feature_flags/frontend/rollbackReason'+import { openRollbackReasonDialog } from 'products/feature_flags/frontend/rollbackReasonDialog'import {captureMessageAudienceClicked,cohortAudienceProperties,@@ -1153,6 +1159,24 @@ function queueInlineSave<T>(cache: Record<string, any>, send: () => Promise<T>):return request}+// pinned: the `source` property value of the rollback reason events.+export type RollbackReasonSource = 'save' | 'toggle'++/**+ * The answer from the rollback reason question rides on every save from the same source until one succeeds, so a+ * retry after a failed save does not ask again. The success listeners clear it, and so do the listeners that discard+ * the refused edit, so it never rides on an unrelated edit.+ */+function rollbackReasonFields(+ cache: Record<string, any>,+ source: RollbackReasonSource,+ ask: boolean+): RollbackReasonRequestFields {+ const pending: { source: RollbackReasonSource; answer: RollbackReasonAnswer } | undefined =+ cache.rollbackReasonAnswer+ return rollbackReasonRequestFields(pending?.source === source ? pending.answer : undefined, ask)+}+function cleanFlag(flag: Partial<FeatureFlagType>): Partial<FeatureFlagType> {const { created_at, id, created_by, last_modified_by, ...cleanedFlag } = flagif (cleanedFlag.filters && !isV1FeatureFlagConfig(cleanedFlag.filters)) {@@ -1228,6 +1252,7 @@ export interface featureFlagLogicValues {aggregationTargetName: stringalsoCreateInProjectOptions: ProjectSelectOption[]alsoCreateInProjects: number[]+ asksRollbackReason: booleanavailableTabs: FeatureFlagsTab[]breadcrumbs: Breadcrumb[]broadcastCohort: CohortApi | null@@ -1481,6 +1506,9 @@ export interface featureFlagLogicActions {applyUrlTemplate: (templateId: string) => {templateId: string}+ askRollbackReason: (source: RollbackReasonSource) => {+ source: RollbackReasonSource+ }checkKeyConflict: (key: string) => stringcheckKeyConflictFailure: (error: string,@@ -2483,6 +2511,7 @@ export interface featureFlagLogicMeta {props: (arg: any) => anyavailableTabs: (featureFlag: FeatureFlagType, props: any) => FeatureFlagsTab[]configFormat: (featureFlag: FeatureFlagType) => FeatureFlagConfigFormat+ asksRollbackReason: (enabledFeatures: FeatureFlagsSet, configFormat: FeatureFlagConfigFormat) => booleaneditorKind: (props: any,isEditingFlag: boolean,@@ -2701,6 +2730,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([createPairedSchedule: true,setAccessDeniedToFeatureFlag: true,toggleFeatureFlagActive: (active: boolean) => ({ active }),+ askRollbackReason: (source: RollbackReasonSource) => ({ source }),toggleProjectFlagActive: (teamId: number, flagId: number, active: boolean) => ({ teamId, flagId, active }),projectFlagActiveUpdated: (teamId: number, flagId: number, active: boolean) => ({ teamId, flagId, active }),projectFlagActiveUpdateFailed: (teamId: number, flagId: number) => ({ teamId, flagId }),@@ -3678,6 +3708,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([{...preparedFlag,original_flag: values.originalFeatureFlag,+ ...rollbackReasonFields(cache, 'save', values.asksRollbackReason),})}@@ -3746,7 +3777,12 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use featureFlagsPartialUpdate() from 'products/feature_flags/frontend/generated/api' instead.const savedFlag = await api.update(`api/projects/${values.currentProjectId}/feature_flags/${values.featureFlag.id}`,- { active, ...values.rowVersionToken }+ {+ active,+ ...values.rowVersionToken,+ // Turning a flag on never lowers its exposure, so only turning it off asks.+ ...rollbackReasonFields(cache, 'toggle', values.asksRollbackReason && !active),+ })savedFlag.id && refreshTreeItem('feature_flag', String(savedFlag.id))return variantKeyToIndexFeatureFlagPayloads(savedFlag)@@ -4460,6 +4496,10 @@ export const featureFlagLogic = kea<featureFlagLogicType>([})},updateFeatureFlagActiveFailure: ({ errorObject }) => {+ if (isRollbackReasonRequiredError(errorObject)) {+ actions.askRollbackReason('toggle')+ return+ }if (reloadIfStaleRowVersion(values.rowVersionToken, errorObject, actions.refreshFeatureFlag)) {return}@@ -4470,6 +4510,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// For non-approval errors, let the global error handler show the toast to avoid duplicates},saveFeatureFlagSuccess: ({ featureFlag }) => {+ delete cache.rollbackReasonAnswerlemonToast.success('Feature flag saved',liveFlagToastOptions(@@ -4525,6 +4566,10 @@ export const featureFlagLogic = kea<featureFlagLogicType>([globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(completedTasks)},saveFeatureFlagFailure: async ({ errorObject }) => {+ if (isRollbackReasonRequiredError(errorObject)) {+ actions.askRollbackReason('save')+ return+ }if (isApprovalRequiredError(errorObject)) {const changeRequestId: string = errorObject.data.change_request_idshowApprovalRequiredToast(changeRequestId, undefined, errorObject.data.code)@@ -4625,6 +4670,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},updateFeatureFlagActiveSuccess: ({ featureFlagActiveUpdate }) => {+ delete cache.rollbackReasonAnswerif (featureFlagActiveUpdate) {lemonToast.success(`Feature flag ${featureFlagActiveUpdate.active ? 'enabled' : 'disabled'}`,@@ -4884,11 +4930,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},})},- // The payload a non-form save retries with. Read in saveFeatureFlagFailure.+ // The payload a non-form save retries with. Read in saveFeatureFlagFailure and askRollbackReason.saveFeatureFlag: (updatedFlag) => {cache.lastSaveAttempt = updatedFlag},loadFeatureFlagSuccess: async ({ featureFlag }) => {+ // The page now shows the stored flag, so a refused edit and its answer are gone.+ delete cache.rollbackReasonAnswerdismissAgentNotices(props.id, cache)// A ?tab=schedule deep link selects the tab before this load finishes, so the// schedule form's default was computed against the NEW_FLAG placeholder. Correct@@ -5310,6 +5358,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([editFeatureFlag: async ({ editing }) => {if (editing) {actions.loadFeatureFlag()+ } else {+ // Leaving the editor discards a refused save, and its answer with it.+ delete cache.rollbackReasonAnswer}},submitFeatureFlagWithValidation: async (_payload, breakpoint, action, previousState) => {@@ -5341,6 +5392,26 @@ export const featureFlagLogic = kea<featureFlagLogicType>([previousState)},+ askRollbackReason: ({ source }) => {+ // pinned: analytics event names. The server captures `feature flag rollback reason given`.+ posthog.capture('feature flag rollback reason asked', { source })+ // Read now: a save dispatched while the question is open overwrites lastSaveAttempt.+ const refusedSave = cache.lastSaveAttempt+ openRollbackReasonDialog({+ onAnswer: (answer) => {+ if (answer === 'skipped') {+ posthog.capture('feature flag rollback reason skipped', { source })+ }+ cache.rollbackReasonAnswer = { source, answer }+ if (source === 'toggle') {+ actions.updateFeatureFlagActive(false)+ } else {+ actions.saveFeatureFlag(refusedSave)+ }+ },+ onCancel: () => posthog.capture('feature flag rollback reason canceled', { source }),+ })+ },toggleFeatureFlagActive: async ({ active }, breakpoint, action, previousState) => {const updatedFlag = { ...values.featureFlag, active }await sharedListeners.checkDependentFlagsAndConfirm(@@ -5393,6 +5464,12 @@ export const featureFlagLogic = kea<featureFlagLogicType>([(s) => [s.featureFlag],(featureFlag: FeatureFlagType): FeatureFlagConfigFormat => featureFlagConfigFormat(featureFlag.filters),],+ // The server ignores the question for a flag in another config version.+ asksRollbackReason: [+ (s) => [s.enabledFeatures, s.configFormat],+ (enabledFeatures: FeatureFlagsSet, configFormat: FeatureFlagConfigFormat): boolean =>+ !!enabledFeatures[FEATURE_FLAGS.FEATURE_FLAG_ROLLBACK_REASON] && configFormat === 'v1',+ ],editorKind: [(s) => [s.props, s.isEditingFlag, s.featureFlag, s.enabledFeatures, router.selectors.searchParams],(diff --git a/products/feature_flags/frontend/rollbackReason.ts b/products/feature_flags/frontend/rollbackReason.tsnew file mode 100644index 000000000000..cb88b684e224--- /dev/null+++ b/products/feature_flags/frontend/rollbackReason.ts@@ -0,0 +1,26 @@+import type { PatchedFeatureFlagPartialUpdateRequestSchemaApi, RollbackReasonEnumApi } from './generated/api.schemas'++/** What the person chose when a save asked why the edit lowers the flag's exposure. */+export type RollbackReasonAnswer = { reason: RollbackReasonEnumApi; note: string } | 'skipped'++export type RollbackReasonRequestFields = Pick<+ PatchedFeatureFlagPartialUpdateRequestSchemaApi,+ 'ask_rollback_reason' | 'rollback_reason' | 'rollback_reason_note'+>++/**+ * The PATCH body fields for an edit. A resend after the question carries the answer, or nothing when the person+ * skipped it, so the server always saves the resend.+ */+export function rollbackReasonRequestFields(+ answer: RollbackReasonAnswer | undefined,+ ask: boolean+): RollbackReasonRequestFields {+ if (answer === 'skipped') {+ return {}+ }+ if (answer) {+ return { rollback_reason: answer.reason, rollback_reason_note: answer.note || null }+ }+ return ask ? { ask_rollback_reason: true } : {}+}diff --git a/products/feature_flags/frontend/rollbackReasonDialog.tsx b/products/feature_flags/frontend/rollbackReasonDialog.tsxnew file mode 100644index 000000000000..918c0c5a8b9a--- /dev/null+++ b/products/feature_flags/frontend/rollbackReasonDialog.tsx@@ -0,0 +1,78 @@+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonRadio, LemonRadioOption } from 'lib/lemon-ui/LemonRadio'+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'++import { RollbackReasonEnumApi } from './generated/api.schemas'+import { RollbackReasonAnswer } from './rollbackReason'++const REASON_OPTIONS: LemonRadioOption<RollbackReasonEnumApi>[] = [+ { value: RollbackReasonEnumApi.Errors, label: 'Errors or bugs' },+ { value: RollbackReasonEnumApi.Metrics, label: 'Metrics got worse' },+ { value: RollbackReasonEnumApi.Planned, label: 'It was planned' },+ { value: RollbackReasonEnumApi.WrongConfiguration, label: 'Wrong configuration' },+ { value: RollbackReasonEnumApi.Other, label: 'Other' },+]++interface OpenRollbackReasonDialogParams {+ /** Called with the reason, or with `'skipped'`, when the person chooses to save. */+ onAnswer: (answer: RollbackReasonAnswer) => void+ /** Called when the dialog closes without an answer. The edit is not saved. */+ onCancel: () => void+}++export function openRollbackReasonDialog({ onAnswer, onCancel }: OpenRollbackReasonDialogParams): void {+ let answered = false+ const answer = (value: RollbackReasonAnswer): void => {+ if (answered) {+ return+ }+ answered = true+ onAnswer(value)+ }+ const primaryButtonProps = { children: 'Save', 'data-attr': 'feature-flag-rollback-reason-save' }++ LemonDialog.openForm({+ title: 'Why are you rolling back this flag?',+ description: "Fewer people get this flag after this change. Your answer is saved in the flag's history.",+ maxWidth: '32rem',+ initialValues: { reason: null as RollbackReasonEnumApi | null, note: '' },+ content: (+ <div className="flex flex-col gap-3">+ <LemonField name="reason" label="Reason">+ {({ value, onChange }) => (+ <LemonRadio aria-label="Reason" value={value} onChange={onChange} options={REASON_OPTIONS} />+ )}+ </LemonField>+ <LemonField name="note" label="Note" showOptional>+ <LemonTextArea+ // Enter in this multi-line note must not submit the dialog form. Escape still closes it.+ onKeyDown={(e) => e.key === 'Enter' && e.stopPropagation()}+ maxLength={1000}+ minRows={2}+ maxRows={6}+ />+ </LemonField>+ </div>+ ),+ errors: {+ reason: (reason) => (!reason ? 'Pick a reason, or skip the question' : undefined),+ },+ primaryButtonProps,+ tertiaryButton: {+ children: 'Skip and save',+ 'data-attr': 'feature-flag-rollback-reason-skip',+ onClick: () => answer('skipped'),+ },+ onSubmit: ({ reason, note }) => {+ if (reason) {+ answer({ reason, note: (note ?? '').trim() })+ }+ },+ onAfterClose: () => {+ if (!answered) {+ onCancel()+ }+ },+ })+}