Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): list deleted flags and restore them from the flag list (#125725)

ruby childsad4a7d7ae301
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagFilters.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagFilters.test.tsx
index ddc14be7b247..3d910fe6300b 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagFilters.test.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagFilters.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom'
import { render } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { FeatureFlagFiltersSection } from './FeatureFlagFilters'
@@ -157,6 +158,28 @@ describe('FeatureFlagFiltersSection', () => {
expect(container.querySelector('[data-attr="feature-flag-select-runtime"]')).toBeInTheDocument()
})
+ it.each([
+ ['into deleted from archived', { archived: 'true', active: 'false' }, 'deleted', { deleted: 'true' }],
+ ['out of deleted to all', { deleted: 'true' }, 'all', {}],
+ ['out of deleted to archived', { deleted: 'true' }, 'archived', { archived: 'true' }],
+ ])('switches status %s and drops the other status filters', async (_label, start, option, expected) => {
+ const { container } = render(
+ <FeatureFlagFiltersSection
+ filters={{ ...mockFilters, ...start }}
+ setFeatureFlagsFilters={mockSetFilters}
+ searchPlaceholder="Search"
+ filtersConfig={{ status: true }}
+ />
+ )
+
+ await userEvent.click(container.querySelector('[data-attr="feature-flag-select-status"]')!)
+ // Dropdowns opened by earlier cases can linger in the body, so click the option in the newest one.
+ const options = document.querySelectorAll(`[data-attr="feature-flag-select-status-${option}"]`)
+ await userEvent.click(options[options.length - 1])
+
+ expect(mockSetFilters).toHaveBeenCalledWith({ search: '', page: 1, ...expected }, true)
+ })
+
it('ignores false values in config', () => {
const { container } = render(
<FeatureFlagFiltersSection
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
index a3b07a64376c..2037b72a2865 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
@@ -105,11 +105,13 @@ export function FeatureFlagFiltersSection({
dropdownMatchSelectWidth={false}
size="small"
onChange={(status) => {
- const { active, archived, ...restFilters } = filters || {}
+ const { active, archived, deleted, ...restFilters } = filters || {}
if (status === 'all') {
setFeatureFlagsFilters({ ...restFilters, page: 1 }, true)
} else if (status === 'ARCHIVED') {
setFeatureFlagsFilters({ ...restFilters, archived: 'true', page: 1 }, true)
+ } else if (status === 'DELETED') {
+ setFeatureFlagsFilters({ ...restFilters, deleted: 'true', page: 1 }, true)
} else {
setFeatureFlagsFilters({ ...restFilters, active: status, page: 1 }, true)
}
@@ -132,8 +134,19 @@ export function FeatureFlagFiltersSection({
value: 'ARCHIVED',
'data-attr': 'feature-flag-select-status-archived',
},
+ {
+ label: 'Deleted',
+ value: 'DELETED',
+ 'data-attr': 'feature-flag-select-status-deleted',
+ },
]}
- value={filters.archived === 'true' ? 'ARCHIVED' : (filters.active ?? 'all')}
+ value={
+ filters.deleted === 'true'
+ ? 'DELETED'
+ : filters.archived === 'true'
+ ? 'ARCHIVED'
+ : (filters.active ?? 'all')
+ }
data-attr="feature-flag-select-status"
/>
</>
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
index 18a9f7b60627..75955e78755c 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
@@ -60,12 +60,15 @@ import {
cohortCanBeRestored,
deletedCohortDisabledReason,
deletedCohortFilters,
+ restoreChecksCohorts,
} from 'products/feature_flags/frontend/deletedCohortFilters'
import { featureFlagsEmptyState } from 'products/feature_flags/frontend/emptyState/featureFlagsEmptyState'
import {
ARCHIVE_UNAVAILABLE_DISABLED_REASON,
+ RESTORE_UNAVAILABLE_DISABLED_REASON,
UNSUPPORTED_CONFIG_DISABLED_REASON,
canArchiveFeatureFlag,
+ canRestoreFeatureFlag,
featureFlagConfigFormat,
featureFlagConfigFormatLabel,
featureFlagDeleteOptions,
@@ -134,6 +137,14 @@ function FeatureFlagStatusCell({ featureFlag }: { featureFlag: FeatureFlagType }
Updating
</span>
</LemonTag>
+ ) : featureFlag.deleted ? (
+ <Tooltip title="This flag is deleted, so it can't be evaluated. Restore it from the row menu to use it again.">
+ <span>
+ <LemonTag type="danger" className="uppercase cursor-default">
+ Deleted
+ </LemonTag>
+ </span>
+ </Tooltip>
) : featureFlag.archived ? (
<Tooltip title="This flag is done for good. It's hidden from the flag list by default, but linked experiments and surveys keep their data.">
<span>
@@ -193,12 +204,20 @@ function WarningStatusTag({ label, heading, detail }: { label: string; heading:
)
}
+// Deleting a flag that an experiment uses renames its key to `<key>:deleted:<id>`. Code still calls the flag by
+// its old key, so that's the key to copy.
+function keyBeforeDelete(featureFlag: FeatureFlagType): string {
+ const suffix = `:deleted:${featureFlag.id}`
+ return featureFlag.key.endsWith(suffix) ? featureFlag.key.slice(0, -suffix.length) : featureFlag.key
+}
+
// Component for feature flag row actions that needs to use hooks
function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Element {
const { currentProjectId } = useValues(projectLogic)
const flagLogic = featureFlagsLogic({})
const { featureFlagsUpdating, filters } = useValues(flagLogic)
- const { toggleFeatureFlagActive, updateFeatureFlagArchived, loadFeatureFlags } = useActions(flagLogic)
+ const { toggleFeatureFlagActive, updateFeatureFlagArchived, loadFeatureFlags, restoreFeatureFlag } =
+ useActions(flagLogic)
const isUpdating = featureFlag.id ? featureFlagsUpdating[featureFlag.id] : false
const [isQuickSurveyModalOpen, setIsQuickSurveyModalOpen] = useState(false)
@@ -228,29 +247,76 @@ function FeatureFlagRowActions({ featureFlag }: { featureFlag: FeatureFlagType }
return urls.insightNew({ query })
}
- return (
+ // Both menus open with these, so a deleted row's View keeps the list's filters like a live row's does.
+ const viewAndCopyKeyItems = (
<>
+ {featureFlag.id && (
+ <LemonButton
+ to={featureFlagUrlFromList(featureFlag.id, filters)}
+ data-attr="feature-flag-view"
+ fullWidth
+ >
+ View
+ </LemonButton>
+ )}
+ <LemonButton
+ onClick={() => {
+ void copyToClipboard(keyBeforeDelete(featureFlag), 'feature flag key')
+ }}
+ fullWidth
+ >
+ Copy key
+ </LemonButton>
+ </>
+ )
+
+ // A deleted flag serves nobody, so the only change it takes is a restore.
+ if (featureFlag.deleted) {
+ return (
<More
overlay={
<>
+ {viewAndCopyKeyItems}
{featureFlag.id && (
- <LemonButton
- to={featureFlagUrlFromList(featureFlag.id, filters)}
- data-attr="feature-flag-view"
- fullWidth
- >
- View
- </LemonButton>
+ <>
+ <LemonDivider />
+ <AccessControlAction
+ resourceType={AccessControlResourceType.FeatureFlag}
+ minAccessLevel={AccessControlLevel.Editor}
+ userAccessLevel={featureFlag.user_access_level}
+ >
+ <LemonButton
+ data-attr={`feature-flag-${featureFlag.key}-restore`}
+ onClick={() => featureFlag.id && restoreFeatureFlag({ id: featureFlag.id })}
+ fullWidth
+ loading={isUpdating}
+ disabledReason={
+ isUpdating
+ ? 'Updating…'
+ : !canRestoreFeatureFlag(featureFlag.filters)
+ ? RESTORE_UNAVAILABLE_DISABLED_REASON
+ : restoreChecksCohorts(featureFlag)
+ ? deletedCohortReason
+ : undefined
+ }
+ >
+ Restore
+ </LemonButton>
+ </AccessControlAction>
+ </>
)}
+ </>
+ }
+ />
+ )
+ }
- <LemonButton
- onClick={() => {
- void copyToClipboard(featureFlag.key, 'feature flag key')
- }}
- fullWidth
- >
- Copy key
- </LemonButton>
+ return (
+ <>
+ <More
+ overlay={
+ <>
+ {viewAndCopyKeyItems}
{featureFlag.id && isV1Config && (
<AccessControlAction
@@ -443,6 +509,7 @@ export function OverviewTab({
shouldShowEmptyState,
filtersChanged,
hasActiveFilters,
+ switchingDeletedView,
} = useValues(flagLogic)
const { setFeatureFlagsFilters, resetFilters } = useActions(flagLogic)
@@ -697,15 +764,21 @@ export function OverviewTab({
})
}
bulkSelection={{
+ // Deleted rows can't be selected, so a selection carried in from another view would act on hidden live flags.
+ clearSelectionKey: filters.deleted,
getKey: (flag: FeatureFlagType): number => flag.id ?? -1,
isRowSelectable: (flag: FeatureFlagType) =>
flag.id === null
? false
- : !isV1FeatureFlagConfig(flag.filters)
- ? { disabledReason: 'Bulk actions are not available for this flag yet.' }
- : flag.can_edit
- ? true
- : { disabledReason: "You don't have permission to edit this feature flag." },
+ : switchingDeletedView
+ ? { disabledReason: 'Wait for the list to finish loading.' }
+ : flag.deleted
+ ? { disabledReason: 'Restore deleted flags one at a time from the row menu.' }
+ : !isV1FeatureFlagConfig(flag.filters)
+ ? { disabledReason: 'Bulk actions are not available for this flag yet.' }
+ : flag.can_edit
+ ? true
+ : { disabledReason: "You don't have permission to edit this feature flag." },
rowAriaLabel: (flag: FeatureFlagType) => `Select feature flag ${flag.key}`,
headerAriaLabel: 'Select all feature flags on this page',
noun: ['flag', 'flags'],
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
index 57cb848a76d0..c4be27c2e0de 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
@@ -26,6 +26,7 @@ import {
import { urls } from 'scenes/urls'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { FeatureFlagType } from '~/types'
@@ -34,6 +35,11 @@ jest.mock('scenes/approvals/ApprovalRequiredBanner', () => ({
showApprovalRequiredToast: jest.fn(),
}))
jest.mock('posthog-js')
+jest.mock('~/layout/panel-layout/ProjectTree/projectTreeLogic', () => ({
+ ...jest.requireActual('~/layout/panel-layout/ProjectTree/projectTreeLogic'),
+ deleteFromTree: jest.fn(),
+ refreshTreeItem: jest.fn(),
+}))
function capturesOf(event: string): any[][] {
return (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === event)
@@ -201,6 +207,22 @@ describe('flagMatchesFilters', () => {
})
})
+ describe('deleted filter', () => {
+ const liveFlag = { ...base, deleted: false } as FeatureFlagType
+ const deletedFlag = { ...base, deleted: true } as FeatureFlagType
+ const archivedDeletedFlag = { ...base, deleted: true, archived: true } as FeatureFlagType
+
+ it.each<[string, FeatureFlagType, Partial<FeatureFlagsFilters>, boolean]>([
+ ['hides deleted by default', deletedFlag, {}, false],
+ ['shows deleted when deleted=true', deletedFlag, { deleted: 'true' }, true],
+ ['hides live when deleted=true', liveFlag, { deleted: 'true' }, false],
+ ['shows a flag archived before its delete', archivedDeletedFlag, { deleted: 'true' }, true],
+ ['hides a deleted flag under archived=true', archivedDeletedFlag, { archived: 'true' }, false],
+ ])('%s', (_label, flag, filters, expected) => {
+ expect(flagMatchesFilters(flag, filters as FeatureFlagsFilters)).toBe(expected)
+ })
+ })
+
describe('excluded_tags filter', () => {
const flagWithTag = { ...base, archived: false, tags: ['beta', 'internal'] } as FeatureFlagType
const flagWithoutTag = { ...base, archived: false, tags: ['beta'] } as FeatureFlagType
@@ -392,12 +414,13 @@ describe('the feature flags logic', () => {
expect(listFilterParamsFromCarried(flagPageParams)).toEqual({ search: 'checkout', page: '3' })
})
- it('restores search, creator, and sort filters when the crumb hands them back', async () => {
+ it('restores search, creator, sort, and deleted filters when the crumb hands them back', async () => {
await expectLogic(logic, () => {
logic.actions.setFeatureFlagsFilters({
search: 'checkout',
created_by_id: [42],
order: '-created_at',
+ deleted: 'true',
})
}).toFinishAllListeners()
@@ -426,6 +449,7 @@ describe('the feature flags logic', () => {
expect(logic.values.filters.search).toBe('checkout')
expect(logic.values.filters.created_by_id).toEqual([42])
expect(logic.values.filters.order).toBe('-created_at')
+ expect(logic.values.filters.deleted).toBe('true')
})
it('resets to defaults when the bare list URL is visited directly', async () => {
@@ -655,6 +679,194 @@ describe('updateFeatureFlag 409 handling', () => {
})
})
+describe('restoreFeatureFlag', () => {
+ let logic: ReturnType<typeof featureFlagsLogic.build>
+ let restoreBodies: unknown[]
+
+ beforeEach(() => {
+ restoreBodies = []
+ const deletedFlags = [
+ { id: 1, key: 'checkout-flag:deleted:1', deleted: true, active: true },
+ { id: 3, key: 'pricing-flag', deleted: true, active: true },
+ ]
+ const restoredIds: number[] = []
+ const restored = (flag: (typeof deletedFlags)[number]): Partial<FeatureFlagType> => ({
+ ...flag,
+ key: flag.key.replace(`:deleted:${flag.id}`, ''),
+ deleted: false,
+ })
+ useMocks({
+ get: {
+ // Answer like the API: a restored flag leaves the deleted view and joins the live one. The deleted
+ // view serves one row per page, so a restore leaves the next deleted flag on the server.
+ '/api/projects/:projectId/feature_flags/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('deleted') === 'true') {
+ const stillDeleted = deletedFlags.filter((flag) => !restoredIds.includes(flag.id))
+ return [200, { results: stillDeleted.slice(0, 1), count: stillDeleted.length }]
+ }
+ const live = [
+ ...deletedFlags.filter((flag) => restoredIds.includes(flag.id)).map(restored),
+ { id: 2, key: 'live-flag', deleted: false, active: true },
+ ]
+ return [200, { results: live, count: live.length }]
+ },
+ },
+ patch: {
+ '/api/projects/:projectId/feature_flags/:id': async ({ request, params }) => {
+ restoreBodies.push(await request.json())
+ const flag = deletedFlags.find(({ id }) => id === Number(params.id))!
+ restoredIds.push(flag.id)
+ return [200, restored(flag)]
+ },
+ },
+ })
+ initKeaTests()
+ logic = featureFlagsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.restoreAllMocks()
+ })
+
+ beforeEach(silenceKeaLoadersErrors)
+ afterEach(resumeKeaLoadersErrors)
+
+ it('restores the flag, drops it from the deleted view, and refetches the page', async () => {
+ logic.actions.setFeatureFlagsFilters({ deleted: 'true' }, true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ expect(logic.values.displayedFlags.map((flag) => flag.id)).toEqual([1])
+ expect(logic.values.count).toBe(2)
+
+ logic.actions.restoreFeatureFlag({ id: 1 })
+ expect(logic.values.featureFlagsUpdating[1]).toBe(true)
+ await expectLogic(logic).toDispatchActions(['restoreFeatureFlagSuccess'])
+
+ expect(restoreBodies).toEqual([{ deleted: false }])
+ expect(logic.values.displayedFlags).toEqual([])
+ expect(logic.values.count).toBe(1)
+ expect(logic.values.featureFlagsUpdating[1]).toBeUndefined()
+ expect(deleteFromTree).toHaveBeenCalledWith('feature_flag', '1')
+ expect(refreshTreeItem).toHaveBeenCalledWith('feature_flag', '1')
+
+ // Without the refetch the page stays empty with a count of 1, and the flag that was on the next page
+ // can't be reached.
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlags', 'loadFeatureFlagsSuccess'])
+ expect(logic.values.displayedFlags.map((flag) => flag.id)).toEqual([3])
+ expect(logic.values.count).toBe(1)
+ })
+
+ it('lists the restored flag once the person leaves the deleted view', async () => {
+ logic.actions.setFeatureFlagsFilters({ deleted: 'true' }, true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ logic.actions.restoreFeatureFlag({ id: 1 })
+ await expectLogic(logic).toDispatchActions(['restoreFeatureFlagSuccess', 'loadFeatureFlagsSuccess'])
+
+ logic.actions.setFeatureFlagsFilters({ deleted: undefined }, true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+
+ expect(logic.values.displayedFlags.map((flag) => [flag.id, flag.key])).toEqual([
+ [1, 'checkout-flag'],
+ [2, 'live-flag'],
+ ])
+ })
+
+ // Regression guard: the restore used to take one off the count of whatever list was cached when it
+ // resolved, so leaving the deleted view mid-restore lowered the live list's total.
+ it('leaves a view loaded during the restore alone and refetches it', async () => {
+ logic.actions.setFeatureFlagsFilters({ deleted: 'true' }, true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ let finishRestore = (_flag: Partial<FeatureFlagType>): void => {}
+ jest.spyOn(api, 'update').mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishRestore = resolve
+ })
+ )
+
+ logic.actions.restoreFeatureFlag({ id: 1 })
+ logic.actions.setFeatureFlagsFilters({}, true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ expect(logic.values.count).toBe(1)
+
+ finishRestore({ id: 1, key: 'checkout-flag', deleted: false, active: true })
+ await expectLogic(logic).toDispatchActions(['restoreFeatureFlagSuccess'])
+
+ expect(logic.values.count).toBe(1)
+ expect(logic.values.displayedFlags.map((flag) => flag.id)).toEqual([2])
+ expect(logic.values.featureFlagsUpdating[1]).toBeUndefined()
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlags', 'loadFeatureFlagsSuccess'])
+ })
+
+ it.each([
+ // The global loader toast skips errors without a status, so the loader shows its own.
+ ['without an HTTP status', new TypeError('Failed to fetch'), true],
+ ['with an HTTP status', { status: 400, detail: 'This flag uses a deleted cohort.' }, false],
+ ])('handles a failed restore %s', async (_label, error, expectOwnToast) => {
+ const toastError = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')
+ logic.actions.setFeatureFlagsFilters({ deleted: 'true' }, true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ jest.spyOn(api, 'update').mockRejectedValueOnce(error)
+
+ logic.actions.restoreFeatureFlag({ id: 1 })
+ await expectLogic(logic).toDispatchActions(['restoreFeatureFlagFailure'])
+
+ expect(
+ toastError.mock.calls.some(([message]) => message === "Couldn't restore this feature flag. Try again.")
+ ).toBe(expectOwnToast)
+ expect(logic.values.featureFlagsUpdating[1]).toBeUndefined()
+ expect(logic.values.displayedFlags.map((flag) => flag.id)).toEqual([1])
+ })
+})
+
+describe('switching into and out of the deleted view', () => {
+ let logic: ReturnType<typeof featureFlagsLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:projectId/feature_flags/': ({ request }) =>
+ new URL(request.url).searchParams.get('deleted') === 'true'
+ ? [200, { results: [{ id: 1, key: 'old-flag:deleted:1', deleted: true }], count: 1 }]
+ : [200, { results: [{ id: 2, key: 'live-flag', deleted: false, active: true }], count: 1 }],
+ },
+ })
+ initKeaTests()
+ logic = featureFlagsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ // Regression guard: the table blocks row selection on this flag. Without it, live rows picked while the
+ // deleted view loads stay selected once it lands, and bulk actions then act on flags the view hides.
+ it('flags the switch until the new view lands', async () => {
+ logic.actions.setFeatureFlagsFilters({}, true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ expect(logic.values.switchingDeletedView).toBe(false)
+
+ logic.actions.setFeatureFlagsFilters({ deleted: 'true' }, true)
+ expect(logic.values.displayedFlags.map((flag) => flag.id)).toEqual([2])
+ expect(logic.values.switchingDeletedView).toBe(true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ expect(logic.values.displayedFlags.map((flag) => flag.id)).toEqual([1])
+ expect(logic.values.switchingDeletedView).toBe(false)
+
+ // A search inside the deleted view keeps showing deleted rows, so it isn't a switch.
+ logic.actions.setFeatureFlagsFilters({ search: 'old' })
+ expect(logic.values.switchingDeletedView).toBe(false)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+
+ logic.actions.setFeatureFlagsFilters({}, true)
+ expect(logic.values.switchingDeletedView).toBe(true)
+ await expectLogic(logic).toDispatchActions(['loadFeatureFlagsSuccess'])
+ expect(logic.values.switchingDeletedView).toBe(false)
+ })
+})
+
describe('updateFeatureFlagArchived', () => {
let logic: ReturnType<typeof featureFlagsLogic.build>
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
index aeb885ba9284..e944ef2f03aa 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
@@ -16,6 +16,7 @@ import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
+import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { ActivityScope, Breadcrumb, FeatureFlagType } from '~/types'
import {
@@ -120,8 +121,10 @@ export function flagMatchesFilters(flag: FeatureFlagType, filters: FeatureFlagsF
flagMatchesSearch(flag, filters.search) &&
flagMatchesStatus(flag, filters.active) &&
flagMatchesType(flag, filters.type) &&
- // Archived flags are hidden unless explicitly filtered for, mirroring the API default
- (filters.archived === 'true' ? !!flag.archived : !flag.archived) &&
+ // Deleted and archived flags are hidden unless explicitly filtered for, mirroring the API defaults.
+ // The deleted view lists a flag whether or not it was archived before the delete.
+ (filters.deleted === 'true' ? !!flag.deleted : !flag.deleted) &&
+ (filters.deleted === 'true' || (filters.archived === 'true' ? !!flag.archived : !flag.archived)) &&
(!filters.created_by_id?.length ||
(flag.created_by != null && filters.created_by_id.includes(flag.created_by.id))) &&
(!filters.tags?.length || filters.tags.some((tag) => flag.tags?.includes(tag))) &&
@@ -160,6 +163,8 @@ export interface FeatureFlagsFilters {
active?: string
/** 'true' shows only archived flags; when unset, archived flags are excluded */
archived?: string
+ /** 'true' shows only deleted flags, which can be restored; when unset, deleted flags are excluded */
+ deleted?: string
created_by_id?: number[]
type?: string
search?: string
@@ -173,6 +178,7 @@ export interface FeatureFlagsFilters {
const DEFAULT_FILTERS: FeatureFlagsFilters = {
active: undefined,
archived: undefined,
+ deleted: undefined,
created_by_id: undefined,
type: undefined,
search: undefined,
@@ -186,7 +192,8 @@ const DEFAULT_FILTERS: FeatureFlagsFilters = {
const FILTER_PARAM_KEYS = Object.keys(DEFAULT_FILTERS) as (keyof FeatureFlagsFilters)[]
function filtersFromSearchParams(searchParams: Record<string, any>): FeatureFlagsFilters {
- const { page, created_by_id, active, archived, type, search, order, evaluation_runtime, tags } = searchParams
+ const { page, created_by_id, active, archived, deleted, type, search, order, evaluation_runtime, tags } =
+ searchParams
return {
...DEFAULT_FILTERS,
created_by_id: parseNumericArrayFilter(created_by_id),
@@ -197,6 +204,7 @@ function filtersFromSearchParams(searchParams: Record<string, any>): FeatureFlag
excluded_tags: parseTagsFilter(searchParams['excluded_tags']),
active: active !== undefined ? String(active) : undefined,
archived: archived !== undefined ? String(archived) : undefined,
+ deleted: deleted !== undefined ? String(deleted) : undefined,
page: page !== undefined ? parseInt(page) : undefined,
search: search !== undefined ? String(search) : undefined,
}
@@ -268,8 +276,7 @@ export interface FlagLogicProps {
type FlagsUpdatingState = Record<number, boolean>
-// Shared by the updateFeatureFlag and updateFeatureFlagArchived reducer cases, which track the
-// per-row spinner identically.
+// Shared by the per-row write loaders (update, archive, restore), which track the per-row spinner identically.
const markFlagUpdating = (state: FlagsUpdatingState, { id }: { id: number }): FlagsUpdatingState => ({
...state,
[id]: true,
@@ -307,6 +314,7 @@ export interface featureFlagsLogicValues {
active?: string | undefined
archived?: string | undefined
created_by_id?: number[] | undefined
+ deleted?: string | undefined
evaluation_runtime?: string | undefined
excluded_tags?: string[] | undefined
limit: number
@@ -319,6 +327,7 @@ export interface featureFlagsLogicValues {
}
shouldShowEmptyState: boolean
sidePanelContext: SidePanelSceneContext
+ switchingDeletedView: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -354,6 +363,41 @@ export interface featureFlagsLogicActions {
resetFilters: () => {
value: true
}
+ restoreFeatureFlag: ({ id }: { id: number }) => {
+ id: number
+ }
+ restoreFeatureFlagFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ restoreFeatureFlagSuccess: (
+ featureFlags: {
+ count: number
+ filters?: FeatureFlagsFilters | null | undefined
+ lastUpdatedFlagId: number
+ next?: string | null | undefined
+ previous?: string | null | undefined
+ results: any[]
+ },
+ payload?: {
+ id: number
+ }
+ ) => {
+ featureFlags: {
+ count: number
+ filters?: FeatureFlagsFilters | null | undefined
+ lastUpdatedFlagId: number
+ next?: string | null | undefined
+ previous?: string | null | undefined
+ results: any[]
+ }
+ payload?: {
+ id: number
+ }
+ }
setActiveTab: (tabKey: FeatureFlagsTab) => {
tabKey: FeatureFlagsTab
}
@@ -494,10 +538,12 @@ export interface featureFlagsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
count: (featureFlags: FeatureFlagsResult) => number
filtersChanged: (filters: FeatureFlagsFilters, featureFlags: FeatureFlagsResult) => boolean
+ switchingDeletedView: (filters: FeatureFlagsFilters, featureFlags: FeatureFlagsResult) => boolean
paramsFromFilters: (filters: FeatureFlagsFilters) => {
active?: string | undefined
archived?: string | undefined
created_by_id?: number[] | undefined
+ deleted?: string | undefined
evaluation_runtime?: string | undefined
excluded_tags?: string[] | undefined
limit: number
@@ -658,6 +704,40 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
throw e
}
},
+ restoreFeatureFlag: async ({ id }: { id: number }) => {
+ try {
+ // nosemgrep: prefer-codegen-api -- The generated partial update request type has no `deleted` field.
+ const response = await api.update(
+ `api/projects/${values.currentProjectId}/feature_flags/${id}`,
+ { deleted: false }
+ )
+ // Restore gives the flag a new tree entry. A delete from another tab or the API leaves the old entry in this tab's tree.
+ deleteFromTree('feature_flag', String(id))
+ refreshTreeItem('feature_flag', String(id))
+ // The response carries the restored key, not the one the delete renamed it to.
+ lemonToast.success(`${response.key} has been restored`)
+ const cached = values.featureFlags
+ // Restore is only offered in the deleted view, but the user can switch views while the
+ // request is in flight. Only the deleted view loses the restored flag, so any other cached
+ // list stays as it is, and the success listener refetches it.
+ if (cached.filters?.deleted !== 'true') {
+ return { ...cached, lastUpdatedFlagId: id }
+ }
+ return {
+ ...cached,
+ results: cached.results.map((flag) => (flag.id === response.id ? response : flag)),
+ count: Math.max(0, cached.count - 1),
+ lastUpdatedFlagId: id,
+ }
+ } catch (e: any) {
+ actions.setFeatureFlagUpdating(id, false)
+ // The global loader toast only covers errors with an HTTP status. A dropped connection has none.
+ if (e?.status === undefined) {
+ lemonToast.error("Couldn't restore this feature flag. Try again.")
+ }
+ throw e
+ }
+ },
},
],
})),
@@ -718,6 +798,8 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
updateFeatureFlagSuccess: clearFlagUpdating,
updateFeatureFlagArchived: markFlagUpdating,
updateFeatureFlagArchivedSuccess: clearFlagUpdating,
+ restoreFeatureFlag: markFlagUpdating,
+ restoreFeatureFlagSuccess: clearFlagUpdating,
},
],
}),
@@ -732,6 +814,14 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
return !objectsEqual({ ...featureFlags.filters, page: undefined }, { ...filters, page: undefined })
},
],
+ // True from a switch into or out of the deleted view until that view's rows arrive. Until then the
+ // table still shows the previous view's rows, and a selection made on them would carry into a view
+ // that hides them, where bulk actions would act on flags the user can't see.
+ switchingDeletedView: [
+ (s) => [s.filters, s.featureFlags],
+ (filters: FeatureFlagsFilters, featureFlags: FeatureFlagsResult): boolean =>
+ (filters.deleted === 'true') !== (featureFlags.filters?.deleted === 'true'),
+ ],
paramsFromFilters: [
(s) => [s.filters],
(filters: FeatureFlagsFilters) => ({
@@ -762,6 +852,7 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
filters.search?.trim() ||
filters.active ||
filters.archived ||
+ filters.deleted ||
filters.type ||
filters.evaluation_runtime ||
filters.created_by_id?.length ||
@@ -867,6 +958,11 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
resetFilters: () => {
actions.setFeatureFlagsFilters({ ...DEFAULT_FILTERS, order: values.filters.order }, true)
},
+ restoreFeatureFlagSuccess: () => {
+ // The deleted view drops the restored row at once, but its page is then a row short of its count, so the
+ // first flag of the next page can't be reached. Any other view may have loaded without the restored flag.
+ actions.loadFeatureFlags()
+ },
loadFeatureFlagsSuccess: () => {
if (values.featureFlags.results.length > 0) {
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.CreateFeatureFlag)
diff --git a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
index ec65753e4f27..fcacf7317d29 100644
--- a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
+++ b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
@@ -236,6 +236,7 @@ export interface flagSelectionLogicValues {
active?: string | undefined
archived?: string | undefined
created_by_id?: number[] | undefined
+ deleted?: string | undefined
evaluation_runtime?: string | undefined
excluded_tags?: string[] | undefined
limit: number
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index aae92abb7ec8..66063014003f 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -22661,6 +22661,7 @@ export namespace Endpoints {
active: "STALE" | "false" | "true";
archived: "false" | "true";
created_by_id: string;
+ deleted: "false" | "true";
eligible_for_experiment: "true";
evaluation_runtime: "all" | "client" | "server";
excluded_properties: string;
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 4c9376cfd5ef..b05418cdc8bd 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -4378,8 +4378,10 @@ class FeatureFlagViewSet(
# never read the field.
queryset = queryset.annotate(is_used_in_replay_settings_annotation=self._replay_gates.as_q())
+ # Soft-deleted flags can be restored, so the list returns them when asked for them, and only them.
+ show_deleted = str_to_bool(self.request.GET.get("deleted", False))
queryset = (
- queryset.filter(deleted=False)
+ queryset.filter(deleted=show_deleted)
.prefetch_related("analytics_dashboards")
.prefetch_related(
Prefetch(
@@ -4402,7 +4404,10 @@ class FeatureFlagViewSet(
Q(id__in=product_tour_internal_targeting_flags)
)
- queryset = exclude_archived_unless_requested(queryset, requested="archived" in self.request.GET)
+ # A flag that was archived before it was deleted still belongs in the deleted list.
+ queryset = exclude_archived_unless_requested(
+ queryset, requested="archived" in self.request.GET or show_deleted
+ )
# add additional filters provided by the client
queryset = self._filter_request(self.request, queryset)
@@ -4496,6 +4501,17 @@ class FeatureFlagViewSet(
enum=["true", "false"],
description="Filter by archived state. When omitted, archived flags are excluded.",
),
+ OpenApiParameter(
+ "deleted",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ enum=["true", "false"],
+ description=(
+ "Pass `true` to list only soft-deleted flags, which can be restored, archived or not. "
+ "When omitted, deleted flags are excluded."
+ ),
+ ),
OpenApiParameter(
"has_evaluation_contexts",
OpenApiTypes.STR,
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index d577559f0b14..643c4b080759 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -4523,6 +4523,35 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert ("visible-flag" in keys) is expect_visible
assert ("archived-flag" in keys) is expect_archived
+ @parameterized.expand(
+ [
+ ("default", "", {"visible-flag"}),
+ ("deleted_false", "?deleted=false", {"visible-flag"}),
+ # A flag archived before its delete is listed too, without asking for archived flags.
+ ("deleted_true", "?deleted=true", {"deleted-flag", "archived-deleted-flag"}),
+ ("deleted_and_search", "?deleted=true&search=archived", {"archived-deleted-flag"}),
+ # An explicit archived value still narrows the deleted list.
+ ("deleted_and_archived_false", "?deleted=true&archived=false", {"deleted-flag"}),
+ ("deleted_and_archived_true", "?deleted=true&archived=true", {"archived-deleted-flag"}),
+ ("archived_true_hides_deleted", "?archived=true", set()),
+ ]
+ )
+ def test_list_deleted_filtering(self, _name, query, expected_keys):
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="visible-flag")
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="deleted-flag", deleted=True)
+ FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="archived-deleted-flag",
+ active=False,
+ archived=True,
+ deleted=True,
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{query}")
+ assert response.status_code == 200
+ assert {flag["key"] for flag in response.json()["results"]} == expected_keys
+ assert response.json()["count"] == len(expected_keys)
+
def test_list_excluded_tags_filtering(self):
for key, tags in [
("deprecated-flag", ["deprecated"]),
diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.py
index 908e38067bd0..b3cbac288a30 100644
--- a/products/feature_flags/backend/flag_status.py
+++ b/products/feature_flags/backend/flag_status.py
@@ -61,8 +61,10 @@ def exclude_archived_unless_requested(queryset: QuerySet, *, requested: bool) ->
This is the API's default for the list, `matching_ids`, and filter-based `bulk_delete`
paths — archived flags stay out of "select all" / bulk-delete sets unless `archived` is
- passed. `requested` is whether the caller provided an `archived` param (the value filter
- itself is applied separately). The frontend `flagMatchesFilters` keeps its own mirror.
+ passed. `requested` is whether the caller asked to see archived flags: an `archived` param,
+ or the list's `deleted=true` view, which shows a deleted flag whether or not it was archived
+ first. The value filter itself is applied separately. The frontend `flagMatchesFilters` keeps
+ its own mirror.
"""
if not requested:
return queryset.filter(archived=False)
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 3f61a7539e29..9b312a28581f 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -2474,6 +2474,10 @@ export type FeatureFlagsListParams = {
* Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
created_by_id?: string
+ /**
+ * Pass `true` to list only soft-deleted flags, which can be restored, archived or not. When omitted, deleted flags are excluded.
+ */
+ deleted?: FeatureFlagsListDeleted
/**
* When 'true', only return flags that can back an experiment: multivariate with 2-20 variants. Any other value is ignored.
*/
@@ -2532,6 +2536,13 @@ export const FeatureFlagsListArchived = {
True: 'true',
} as const
+export type FeatureFlagsListDeleted = (typeof FeatureFlagsListDeleted)[keyof typeof FeatureFlagsListDeleted]
+
+export const FeatureFlagsListDeleted = {
+ False: 'false',
+ True: 'true',
+} as const
+
export type FeatureFlagsListEligibleForExperiment =
(typeof FeatureFlagsListEligibleForExperiment)[keyof typeof FeatureFlagsListEligibleForExperiment]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9c380f213e0d..a316566486df 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -137718,6 +137718,10 @@ export namespace Schemas {
* Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
created_by_id?: string;
+ /**
+ * Pass `true` to list only soft-deleted flags, which can be restored, archived or not. When omitted, deleted flags are excluded.
+ */
+ deleted?: FeatureFlagsListDeleted;
/**
* When 'true', only return flags that can back an experiment: multivariate with 2-20 variants. Any other value is ignored.
*/
@@ -137778,6 +137782,14 @@ export namespace Schemas {
True: 'true',
} as const;
+ export type FeatureFlagsListDeleted = typeof FeatureFlagsListDeleted[keyof typeof FeatureFlagsListDeleted];
+
+
+ export const FeatureFlagsListDeleted = {
+ False: 'false',
+ True: 'true',
+ } as const;
+
export type FeatureFlagsListEligibleForExperiment = typeof FeatureFlagsListEligibleForExperiment[keyof typeof FeatureFlagsListEligibleForExperiment];
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index e99b09b77719..ab2f8940a0af 100644
--- a/services/mcp/src/generated/feature_flags/api.ts
+++ b/services/mcp/src/generated/feature_flags/api.ts
@@ -96,6 +96,12 @@ export const FeatureFlagsListQueryParams = () => zod.object({
.describe(
'Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded \/ comma-separated list of user IDs to match any of them.'
),
+ deleted: zod
+ .enum(['false', 'true'])
+ .optional()
+ .describe(
+ 'Pass `true` to list only soft-deleted flags, which can be restored, archived or not. When omitted, deleted flags are excluded.'
+ ),
eligible_for_experiment: zod
.enum(['true'])
.optional()
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index cd3ebdefe5a4..12e2a8af5db0 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -283,6 +283,7 @@ const featureFlagGetAll = (): ToolBase<
active: params.active,
archived: params.archived,
created_by_id: params.created_by_id,
+ deleted: params.deleted,
eligible_for_experiment: params.eligible_for_experiment,
evaluation_runtime: params.evaluation_runtime,
excluded_properties: params.excluded_properties,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
index b3bf0fdc237a..6d12b2fef0de 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
@@ -15,6 +15,11 @@
"description": "Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.",
"type": "string"
},
+ "deleted": {
+ "description": "Pass `true` to list only soft-deleted flags, which can be restored, archived or not. When omitted, deleted flags are excluded.",
+ "enum": ["false", "true"],
+ "type": "string"
+ },
"eligible_for_experiment": {
"description": "When 'true', only return flags that can back an experiment: multivariate with 2-20 variants. Any other value is ignored.",
"enum": ["true"],