: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): add enable/disable toggle to feature flags projects tab (#69314)
Gustavo H. Strassburgercd0d8ecfada0
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 799a6fa6e012..e9f90bb0e960 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -174,8 +174,8 @@ import {MediaUploadResponse,NewEarlyAccessFeatureType,ObjectMediaPreview,+ OrganizationFeatureFlag,OrganizationFeatureFlagKeysResponse,- OrganizationFeatureFlags,OrganizationFeatureFlagsCopyBody,OrganizationMemberScopedApiKeysResponse,OrganizationMemberType,@@ -2589,7 +2589,7 @@ const api = {async get(orgId: OrganizationType['id'] = ApiConfig.getCurrentOrganizationId(),featureFlagKey: FeatureFlagType['key']- ): Promise<OrganizationFeatureFlags> {+ ): Promise<OrganizationFeatureFlag[]> {return await new ApiRequest().organizationFeatureFlags(orgId, featureFlagKey).get()},async copy(diff --git a/frontend/src/scenes/feature-flags/FeatureFlagProjects.tsx b/frontend/src/scenes/feature-flags/FeatureFlagProjects.tsxindex 39a689980673..45d257490308 100644--- a/frontend/src/scenes/feature-flags/FeatureFlagProjects.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlagProjects.tsx@@ -19,6 +19,8 @@ import { CohortType, FeatureFlagType, OrganizationFeatureFlag, OrganizationTypeimport { organizationLogic } from '../organizationLogic'import { featureFlagLogic } from './featureFlagLogic'import { groupFilters } from './FeatureFlags'+import { FlagActiveToggleTag } from './FlagActiveToggleTag'+import { confirmFlagActiveToggleInProject, flagToggleKey } from './updateFlagActiveInProject'function checkHasStaticCohort(featureFlag: FeatureFlagType, cohorts: CohortType[]): boolean {const staticCohorts = new Set()@@ -42,10 +44,14 @@ const getColumns = ({aggregationLabel,currentTeamId,currentOrganization,+ projectFlagsToggling,+ onToggleFlagActive,}: {aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => NouncurrentTeamId: number | nullcurrentOrganization: OrganizationType | null+ projectFlagsToggling: Record<string, boolean>+ onToggleFlagActive: (record: OrganizationFeatureFlag, active: boolean) => void}): LemonTableColumns<OrganizationFeatureFlag> => {return [{@@ -89,15 +95,19 @@ const getColumns = ({{title: 'Status',dataIndex: 'active',- render: (dataValue) => {- return dataValue ? (- <LemonTag type="success" className="uppercase">- Enabled- </LemonTag>- ) : (- <LemonTag type="default" className="uppercase">- Disabled- </LemonTag>+ render: (_, record) => {+ const canToggle = record.team_id !== null && record.flag_id !== null+ const toggling =+ record.team_id !== null &&+ record.flag_id !== null &&+ !!projectFlagsToggling[flagToggleKey(record.team_id, record.flag_id)]+ return (+ <FlagActiveToggleTag+ active={record.active}+ toggling={toggling}+ onToggle={canToggle ? (active) => onToggleFlagActive(record, active) : undefined}+ data-attr="feature-flag-projects-toggle"+ />)},},@@ -229,8 +239,8 @@ function FeatureFlagCopySection(): JSX.Element {}export default function FeatureFlagProjects(): JSX.Element {- const { projectsWithCurrentFlag, featureFlag } = useValues(featureFlagLogic)- const { loadProjectsWithCurrentFlag, loadScheduledChanges } = useActions(featureFlagLogic)+ const { projectsWithCurrentFlag, featureFlag, projectFlagsToggling } = useValues(featureFlagLogic)+ const { loadProjectsWithCurrentFlag, loadScheduledChanges, toggleProjectFlagActive } = useActions(featureFlagLogic)const { currentTeamId } = useValues(teamLogic)const { currentOrganization } = useValues(organizationLogic)const { aggregationLabel } = useValues(groupsModel)@@ -242,6 +252,19 @@ export default function FeatureFlagProjects(): JSX.Element {}})+ const onToggleFlagActive = (record: OrganizationFeatureFlag, active: boolean): void => {+ if (record.team_id === null || record.flag_id === null) {+ return+ }+ const teamId = record.team_id+ const flagId = record.flag_id+ confirmFlagActiveToggleInProject({+ teamName: currentOrganization?.teams?.find((t) => t.id === teamId)?.name ?? `Project ${teamId}`,+ active,+ onConfirm: () => toggleProjectFlagActive(teamId, flagId, active),+ })+ }+return (<div><InfoBanner />@@ -249,7 +272,13 @@ export default function FeatureFlagProjects(): JSX.Element {<LemonTableloading={false}dataSource={projectsWithCurrentFlag}- columns={getColumns({ currentTeamId, currentOrganization, aggregationLabel })}+ columns={getColumns({+ currentTeamId,+ currentOrganization,+ aggregationLabel,+ projectFlagsToggling,+ onToggleFlagActive,+ })}emptyState="This feature flag is not being used in any other project."/></div>diff --git a/frontend/src/scenes/feature-flags/FlagActiveToggleTag.test.tsx b/frontend/src/scenes/feature-flags/FlagActiveToggleTag.test.tsxnew file mode 100644index 000000000000..b647a11abdc3--- /dev/null+++ b/frontend/src/scenes/feature-flags/FlagActiveToggleTag.test.tsx@@ -0,0 +1,25 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { FlagActiveToggleTag } from './FlagActiveToggleTag'++describe('FlagActiveToggleTag', () => {+ afterEach(() => {+ cleanup()+ })++ it('resolves a click to the opposite state', () => {+ const onToggle = jest.fn()+ render(<FlagActiveToggleTag active={true} onToggle={onToggle} />)++ fireEvent.click(screen.getByRole('switch'))+ expect(onToggle).toHaveBeenCalledWith(false)+ })++ it('drops clicks while a toggle is in flight', () => {+ const onToggle = jest.fn()+ render(<FlagActiveToggleTag active={true} toggling onToggle={onToggle} />)++ fireEvent.click(screen.getByRole('switch'))+ expect(onToggle).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/scenes/feature-flags/FlagActiveToggleTag.tsx b/frontend/src/scenes/feature-flags/FlagActiveToggleTag.tsxnew file mode 100644index 000000000000..0430f1d22a85--- /dev/null+++ b/frontend/src/scenes/feature-flags/FlagActiveToggleTag.tsx@@ -0,0 +1,44 @@+import { LemonSwitch, LemonTag } from '@posthog/lemon-ui'++export function FlagActiveToggleTag({+ active,+ toggling,+ onToggle,+ 'data-attr': dataAttr,+}: {+ active: boolean+ toggling?: boolean+ onToggle?: (active: boolean) => void+ 'data-attr'?: string+}): JSX.Element {+ const label = active ? 'Enabled' : 'Disabled'+ if (!onToggle) {+ return (+ <LemonTag type={active ? 'success' : 'default'} className="uppercase" data-attr={dataAttr}>+ {label}+ </LemonTag>+ )+ }++ return (+ <LemonTag+ type={active ? 'success' : 'default'}+ className="uppercase"+ aria-busy={toggling || undefined}+ data-attr={dataAttr}+ >+ <LemonSwitch+ checked={active}+ onChange={() => onToggle(!active)}+ size="xxsmall"+ loading={toggling}+ disabledReason={toggling ? 'Updating…' : undefined}+ sliderColorOverrideChecked="success"+ aria-label="Feature flag active in this project"+ label={label}+ // LemonSwitch renders the label before the switch; reverse to keep the switch on the left+ className="flex-row-reverse"+ />+ </LemonTag>+ )+}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 72b85385a42f..2804de8e7fae 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -1,4 +1,4 @@-import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_PROJECT } from 'lib/api.mock'+import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_PROJECT, MOCK_TEAM_ID } from 'lib/api.mock'import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'@@ -12,6 +12,7 @@ import { initKeaTests } from '~/test/init'import {FeatureFlagGroupType,FeatureFlagType,+ OrganizationFeatureFlag,PropertyFilterType,PropertyOperator,ScheduledChangeModels,@@ -1205,6 +1206,78 @@ describe('featureFlagLogic', () => {})})})++ describe('toggleProjectFlagActive', () => {+ const projectRow = (teamId: number, flagId: number): OrganizationFeatureFlag => ({+ flag_id: flagId,+ team_id: teamId,+ filters: { groups: [] },+ active: true,+ created_by: null,+ created_at: '',+ })++ beforeEach(() => {+ useMocks({+ patch: {+ '/api/projects/:team_id/feature_flags/:id/': async ({ request, params }) => {+ const body = (await request.json()) as { active: boolean }+ return [200, { id: Number(params.id), active: body.active }]+ },+ },+ })+ })++ it.each([false, true])(+ 'updates the toggled project row without touching the current flag (active → %s)',+ async (active) => {+ logic.actions.loadProjectsWithCurrentFlagSuccess([+ projectRow(MOCK_TEAM_ID, 1),+ { ...projectRow(555, 42), active: !active },+ ])++ logic.actions.toggleProjectFlagActive(555, 42, active)+ expect(logic.values.projectFlagsToggling).toEqual({ '555:42': true })++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.projectsWithCurrentFlag).toMatchObject([+ { team_id: MOCK_TEAM_ID, active: true },+ { team_id: 555, active },+ ])+ expect(logic.values.featureFlag.active).toBe(true)+ expect(logic.values.projectFlagsToggling).toEqual({})+ }+ )++ it('syncs featureFlag.active when the current project row is toggled', async () => {+ logic.actions.loadProjectsWithCurrentFlagSuccess([projectRow(MOCK_TEAM_ID, 1)])++ logic.actions.toggleProjectFlagActive(MOCK_TEAM_ID, 1, false)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.projectsWithCurrentFlag).toMatchObject([{ team_id: MOCK_TEAM_ID, active: false }])+ expect(logic.values.featureFlag.active).toBe(false)+ })++ it('clears the in-flight marker and keeps state when the update fails', async () => {+ useMocks({+ patch: {+ '/api/projects/:team_id/feature_flags/:id/': () => [403, { detail: 'No edit access' }],+ },+ })+ logic.actions.loadProjectsWithCurrentFlagSuccess([projectRow(MOCK_TEAM_ID, 1), projectRow(555, 42)])++ logic.actions.toggleProjectFlagActive(555, 42, false)+ await expectLogic(logic).toDispatchActions(['projectFlagActiveUpdateFailed']).toFinishAllListeners()++ expect(logic.values.projectsWithCurrentFlag).toMatchObject([+ { team_id: MOCK_TEAM_ID, active: true },+ { team_id: 555, active: true },+ ])+ expect(logic.values.featureFlag.active).toBe(true)+ expect(logic.values.projectFlagsToggling).toEqual({})+ })+ })})const createFilters = (overrides: Partial<FeatureFlagFilters> = {}): FeatureFlagFilters => ({diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex db5b5efd36d6..5e3468800318 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -89,6 +89,7 @@ import { uniformAggregationGroupTypeIndex } from './defaultReleaseConditionsUtilimport { checkFeatureFlagConfirmation } from './featureFlagConfirmationLogic'import type { FlagIntent } from './featureFlagIntentWarningLogic'import type { featureFlagLogicType } from './featureFlagLogicType'+import { flagToggleKey, updateFlagActiveInProject } from './updateFlagActiveInProject'const VALID_INTENTS: FlagIntent[] = ['local-eval', 'first-page-load']@@ -645,6 +646,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([createPairedSchedule: true,setAccessDeniedToFeatureFlag: true,toggleFeatureFlagActive: (active: boolean) => ({ active }),+ 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 }),submitFeatureFlagWithValidation: (featureFlag: Partial<FeatureFlagType>) => ({ featureFlag }),setBucketingIdentifier: (bucketingIdentifier: FeatureFlagBucketingIdentifier | null) => ({bucketingIdentifier,@@ -979,6 +983,23 @@ export const featureFlagLogic = kea<featureFlagLogicType>([setCopyDestinationProject: (_, { id }) => id,},],+ projectFlagsToggling: [+ {} as Record<string, boolean>,+ {+ toggleProjectFlagActive: (state, { teamId, flagId }) => ({+ ...state,+ [flagToggleKey(teamId, flagId)]: true,+ }),+ projectFlagActiveUpdated: (state, { teamId, flagId }) => {+ const { [flagToggleKey(teamId, flagId)]: _, ...rest } = state+ return rest+ },+ projectFlagActiveUpdateFailed: (state, { teamId, flagId }) => {+ const { [flagToggleKey(teamId, flagId)]: _, ...rest } = state+ return rest+ },+ },+ ],copySchedule: [false as boolean,{@@ -1568,10 +1589,10 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// Put current project first. We need teamIdsInCurrentProject here, because as of Feb 2025,// FeatureFlag only has `team_id`, but not `project_id`return organizationFeatureFlags.sort((a, b) => {- if (teamIdsInCurrentProject.includes(a.team_id)) {+ if (a.team_id !== null && teamIdsInCurrentProject.includes(a.team_id)) {return -1}- if (teamIdsInCurrentProject.includes(b.team_id)) {+ if (b.team_id !== null && teamIdsInCurrentProject.includes(b.team_id)) {return 1}return 0@@ -1695,6 +1716,15 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},],})),+ // Extends the projectsWithCurrentFlag loader's reducer. Must stay after loaders(); do NOT merge+ // into the reducers() block above — it runs before the loader defines projectsWithCurrentFlag,+ // so the extension would be silently dropped.+ reducers({+ projectsWithCurrentFlag: {+ projectFlagActiveUpdated: (state, { teamId, flagId, active }) =>+ state.map((p) => (p.team_id === teamId && p.flag_id === flagId ? { ...p, active } : p)),+ },+ }),listeners(({ actions, values, props, sharedListeners }) => ({setCronExpression: ({ cronExpression }) => {if (!cronExpression) {@@ -1945,6 +1975,28 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.updateFlag(featureFlagActiveUpdate)}},+ toggleProjectFlagActive: async ({ teamId, flagId, active }) => {+ const updatedFlag = await updateFlagActiveInProject({ teamId, flagId, active })+ if (!updatedFlag) {+ actions.projectFlagActiveUpdateFailed(teamId, flagId)+ return+ }+ const newActive = updatedFlag.active ?? active+ actions.projectFlagActiveUpdated(teamId, flagId, newActive)+ // Keep the flag page and the flags list in sync when the toggled row is this page's flag.+ // Flag ids are globally unique, so the id match alone identifies the page's flag even+ // when it lives in a sibling environment of the current project.+ if (flagId === values.featureFlag.id) {+ const syncedFlag = {+ ...values.featureFlag,+ active: newActive,+ version: updatedFlag.version ?? values.featureFlag.version,+ }+ actions.setFeatureFlag(syncedFlag)+ actions.updateFlag(syncedFlag)+ refreshTreeItem('feature_flag', String(flagId))+ }+ },updateFeatureFlagArchivedSuccess: ({ featureFlagActiveUpdate }) => {if (featureFlagActiveUpdate) {lemonToast.success(`Feature flag ${featureFlagActiveUpdate.archived ? 'archived' : 'unarchived'}`)diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.tsindex c9ac4885feb5..173ffc41439c 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts@@ -8,8 +8,7 @@ import api, { CountedPaginatedResponse } from 'lib/api'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { objectsEqual } from 'lib/utils/objects'import { parseNumericArrayFilter, parseTagsFilter, toParams } from 'lib/utils/url'-import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'-import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'+import { handleFlagApprovalRequired } from 'scenes/feature-flags/updateFlagActiveInProject'import { projectLogic } from 'scenes/projectLogic'import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -201,16 +200,13 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([)return { ...values.featureFlags, results: updatedFlags, lastUpdatedFlagId: id }} catch (e: any) {- if (e.status === 409 && e.data?.change_request_id) {- const actionDescription =- payload.active === true- ? 'enable this feature flag'- : payload.active === false- ? 'disable this feature flag'- : 'update this feature flag'- showApprovalRequiredToast(e.data.change_request_id, actionDescription)- dispatchChangeRequestCreated({ resourceType: 'feature_flag', resourceId: id })- }+ const actionDescription =+ payload.active === true+ ? 'enable this feature flag'+ : payload.active === false+ ? 'disable this feature flag'+ : 'update this feature flag'+ handleFlagApprovalRequired(e, id, actionDescription)throw e}},diff --git a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsxindex 8f79f4187a76..378540c4a1fa 100644--- a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx+++ b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx@@ -12,6 +12,7 @@ import { urls } from 'scenes/urls'import { SceneSection } from '~/layout/scenes/components/SceneSection'import { OrganizationFeatureFlag, OrganizationFeatureFlagRow } from '~/types'+import { confirmFlagActiveToggleInProject, flagToggleKey } from '../updateFlagActiveInProject'import { CellState, ProjectsGridCell } from './ProjectsGridCell'import { projectsGridLogic } from './projectsGridLogic'import { ProjectsGridToolbar } from './ProjectsGridToolbar'@@ -65,8 +66,9 @@ export function ProjectsGrid(): JSX.Element {accessibleTeamIds,siblingsByFlagKey,siblingsLoadingKeys,+ togglingFlagIds,} = useValues(projectsGridLogic)- const { loadMoreFlags } = useActions(projectsGridLogic)+ const { loadMoreFlags, toggleFlagActive } = useActions(projectsGridLogic)const { currentOrganization } = useValues(organizationLogic)const { currentTeamId } = useValues(teamLogic)@@ -124,18 +126,33 @@ export function ProjectsGrid(): JSX.Element {),key: `project-${teamId}`,width: columnWidth,- render: (_: unknown, flag: OrganizationFeatureFlagRow) => (- <ProjectsGridCell- state={cellStateFor(- flag,- teamId,- currentTeamId,- accessibleTeamIds,- siblingsByFlagKey[flag.key],- siblingsLoadingKeys.includes(flag.key)- )}- />- ),+ render: (_: unknown, flag: OrganizationFeatureFlagRow) => {+ const state = cellStateFor(+ flag,+ teamId,+ currentTeamId,+ accessibleTeamIds,+ siblingsByFlagKey[flag.key],+ siblingsLoadingKeys.includes(flag.key)+ )+ const flagId = state.kind === 'present' ? state.sibling.flag_id : null+ return (+ <ProjectsGridCell+ state={state}+ toggling={flagId !== null ? togglingFlagIds[flagToggleKey(teamId, flagId)] : false}+ onToggle={+ flagId !== null+ ? (active) =>+ confirmFlagActiveToggleInProject({+ teamName: teamsById.get(teamId)?.name ?? `Project ${teamId}`,+ active,+ onConfirm: () => toggleFlagActive(flag.key, teamId, flagId, active),+ })+ : undefined+ }+ />+ )+ },})),]diff --git a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridCell.tsx b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridCell.tsxindex 3fd87e758e60..92f197ec2764 100644--- a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridCell.tsx+++ b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridCell.tsx@@ -1,11 +1,10 @@import { IconLock } from '@posthog/icons'-import { LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'--import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { LemonSkeleton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { OrganizationFeatureFlag } from '~/types'import { groupFilters } from '../FeatureFlags'+import { FlagActiveToggleTag } from '../FlagActiveToggleTag'export type CellState =| { kind: 'loading' }@@ -13,7 +12,15 @@ export type CellState =| { kind: 'no-access' }| { kind: 'present'; sibling: OrganizationFeatureFlag }-export function ProjectsGridCell({ state }: { state: CellState }): JSX.Element {+export function ProjectsGridCell({+ state,+ onToggle,+ toggling,+}: {+ state: CellState+ onToggle?: (active: boolean) => void+ toggling?: boolean+}): JSX.Element {if (state.kind === 'loading') {return <LemonSkeleton className="h-6 w-24" data-attr="projects-grid-cell-loading" />}@@ -44,18 +51,18 @@ export function ProjectsGridCell({ state }: { state: CellState }): JSX.Element {const evals = typeof sibling.evaluations_7d === 'number' ? sibling.evaluations_7d.toLocaleString() : '—'return (- <LemonTableLink- to={`/project/${sibling.team_id}/feature_flags/${sibling.flag_id}`}- title={- <LemonTag type={sibling.active ? 'success' : 'default'} className="uppercase">- {sibling.active ? 'Enabled' : 'Disabled'}- </LemonTag>- }- description={+ <div className="flex flex-col items-start py-1">+ <FlagActiveToggleTag+ active={sibling.active}+ toggling={toggling}+ onToggle={onToggle}+ data-attr="projects-grid-cell-toggle"+ />+ <Link to={`/project/${sibling.team_id}/feature_flags/${sibling.flag_id}`} className="text-xs mt-1"><span data-attr="projects-grid-cell-present">{rollout} · {evals} evals · 7d</span>- }- />+ </Link>+ </div>)}diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.tsindex 59ae23524b4c..0fc86360de4f 100644--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts@@ -209,6 +209,92 @@ describe('projectsGridLogic', () => {})})+ describe('toggling flags', () => {+ let patchedUrls: string[]++ beforeEach(() => {+ patchedUrls = []+ useMocks({+ get: {+ '/api/organizations/:org/feature_flags/keys/': {+ count: 1,+ next: null,+ previous: null,+ results: [buildFlag(1)],+ },+ '/api/organizations/:org/feature_flags/:key/': [],+ },+ patch: {+ '/api/projects/:team_id/feature_flags/:id/': async ({ request, params }) => {+ patchedUrls.push(new URL(request.url).pathname)+ if (params.team_id === '99') {+ return [403, { detail: "You don't have edit access" }]+ }+ const body = (await request.json()) as { active: boolean }+ return [200, { id: Number(params.id), active: body.active }]+ },+ },+ })+ initKeaTests()+ logic = projectsGridLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it.each([false, true])(+ 'PATCHes the flag in its own project and syncs grid state (active → %s)',+ async (active) => {+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.siblingsLoaded('flag_1', [+ { flag_id: 1, team_id: 1, filters: { groups: [] }, active: true, created_by: null, created_at: '' },+ {+ flag_id: 42,+ team_id: 2,+ filters: { groups: [] },+ active: !active,+ created_by: null,+ created_at: '',+ },+ ])++ logic.actions.toggleFlagActive('flag_1', 2, 42, active)+ expect(logic.values.togglingFlagIds).toEqual({ '2:42': true })++ await expectLogic(logic).toDispatchActions(['flagActiveUpdated']).toFinishAllListeners()+ expect(patchedUrls).toEqual(['/api/projects/2/feature_flags/42/'])+ expect(logic.values.siblingsByFlagKey['flag_1']).toMatchObject([+ { team_id: 1, active: true },+ { team_id: 2, active },+ ])+ expect(logic.values.togglingFlagIds).toEqual({})+ }+ )++ it('syncs the representative row when the toggled flag backs it', async () => {+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.siblingsLoaded('flag_1', [+ { flag_id: 1, team_id: 1, filters: { groups: [] }, active: true, created_by: null, created_at: '' },+ ])++ logic.actions.toggleFlagActive('flag_1', 1, 1, false)+ await expectLogic(logic).toDispatchActions(['flagActiveUpdated']).toFinishAllListeners()+ expect(logic.values.flags[0].active).toBe(false)+ })++ it('clears the in-flight marker and keeps state when the update fails', async () => {+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.siblingsLoaded('flag_1', [+ { flag_id: 7, team_id: 99, filters: { groups: [] }, active: true, created_by: null, created_at: '' },+ ])++ logic.actions.toggleFlagActive('flag_1', 99, 7, false)+ await expectLogic(logic).toDispatchActions(['flagActiveUpdateFailed']).toFinishAllListeners()+ expect(logic.values.siblingsByFlagKey['flag_1']).toMatchObject([{ team_id: 99, active: true }])+ expect(logic.values.togglingFlagIds).toEqual({})+ })+ })+describe('afterMount hydration', () => {let keysCalls: numberdiff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.tsindex ec17de030b35..ddf3c9548224 100644--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts@@ -8,6 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'import { OrganizationFeatureFlag, OrganizationFeatureFlagRow, OrganizationType } from '~/types'+import { flagToggleKey, updateFlagActiveInProject } from '../updateFlagActiveInProject'import type { projectsGridLogicType } from './projectsGridLogicType'export const PAGE_SIZE = 25@@ -38,6 +39,19 @@ export const projectsGridLogic = kea<projectsGridLogicType>([siblingsFailed: (flagKey: string) => ({ flagKey }),setPickedTeamIds: (teamIds: number[]) => ({ teamIds }),resetPickedTeamIds: true,+ toggleFlagActive: (flagKey: string, teamId: number, flagId: number, active: boolean) => ({+ flagKey,+ teamId,+ flagId,+ active,+ }),+ flagActiveUpdated: (flagKey: string, teamId: number, flagId: number, active: boolean) => ({+ flagKey,+ teamId,+ flagId,+ active,+ }),+ flagActiveUpdateFailed: (teamId: number, flagId: number) => ({ teamId, flagId }),}),reducers({search: ['', { setSearch: (_, { search }) => search }],@@ -49,6 +63,9 @@ export const projectsGridLogic = kea<projectsGridLogicType>([setSearch: () => [],setPickedTeamIds: () => [],resetPickedTeamIds: () => [],+ // Keep the representative row in sync, since it renders the current team's cell before siblings load.+ flagActiveUpdated: (state, { teamId, flagId, active }) =>+ state.map((f) => (f.id === flagId && f.team_id === teamId ? { ...f, active } : f)),},],flagsOffset: [@@ -74,6 +91,18 @@ export const projectsGridLogic = kea<projectsGridLogicType>([{} as Record<string, OrganizationFeatureFlag[]>,{siblingsLoaded: (state, { flagKey, siblings }) => ({ ...state, [flagKey]: siblings }),+ flagActiveUpdated: (state, { flagKey, teamId, flagId, active }) => {+ const siblings = state[flagKey]+ if (!siblings) {+ return state+ }+ return {+ ...state,+ [flagKey]: siblings.map((s) =>+ s.team_id === teamId && s.flag_id === flagId ? { ...s, active } : s+ ),+ }+ },},],siblingsLoadingKeys: [@@ -103,6 +132,20 @@ export const projectsGridLogic = kea<projectsGridLogicType>([resetPickedTeamIds: () => [],},],+ togglingFlagIds: [+ {} as Record<string, boolean>,+ {+ toggleFlagActive: (state, { teamId, flagId }) => ({ ...state, [flagToggleKey(teamId, flagId)]: true }),+ flagActiveUpdated: (state, { teamId, flagId }) => {+ const { [flagToggleKey(teamId, flagId)]: _, ...rest } = state+ return rest+ },+ flagActiveUpdateFailed: (state, { teamId, flagId }) => {+ const { [flagToggleKey(teamId, flagId)]: _, ...rest } = state+ return rest+ },+ },+ ],}),loaders(({ values }) => ({flagsPage: [@@ -171,6 +214,14 @@ export const projectsGridLogic = kea<projectsGridLogicType>([localStorage.removeItem(storageKey(getCurrentTeamId()))actions.loadFlagsPage({ offset: 0, search: values.search })},+ toggleFlagActive: async ({ flagKey, teamId, flagId, active }) => {+ const updatedFlag = await updateFlagActiveInProject({ teamId, flagId, active })+ if (updatedFlag) {+ actions.flagActiveUpdated(flagKey, teamId, flagId, updatedFlag.active ?? active)+ } else {+ actions.flagActiveUpdateFailed(teamId, flagId)+ }+ },})),afterMount(({ actions }) => {const raw = localStorage.getItem(storageKey(getCurrentTeamId()))@@ -210,12 +261,7 @@ async function drainQueue(actions.siblingsFailed(nextKey)return}- // The wrapper is typed as `OrganizationFeatureFlags` (a legacy name), but the- // endpoint actually returns a list of `OrganizationFeatureFlag`. Narrow once here.- const siblings = (await api.organizationFeatureFlags.get(- orgId,- nextKey- )) as unknown as OrganizationFeatureFlag[]+ const siblings = await api.organizationFeatureFlags.get(orgId, nextKey)actions.siblingsLoaded(nextKey, siblings)} catch {actions.siblingsFailed(nextKey)diff --git a/frontend/src/scenes/feature-flags/updateFlagActiveInProject.test.ts b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.test.tsnew file mode 100644index 000000000000..cdb70184bc87--- /dev/null+++ b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.test.ts@@ -0,0 +1,30 @@+import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'+import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'++import { useMocks } from '~/mocks/jest'++import { updateFlagActiveInProject } from './updateFlagActiveInProject'++jest.mock('scenes/approvals/ApprovalRequiredBanner', () => ({+ showApprovalRequiredToast: jest.fn(),+}))+jest.mock('scenes/approvals/utils', () => ({+ ...jest.requireActual('scenes/approvals/utils'),+ dispatchChangeRequestCreated: jest.fn(),+}))++describe('updateFlagActiveInProject', () => {+ it('shows the approval toast and announces the change request on an approval-required 409', async () => {+ useMocks({+ patch: {+ '/api/projects/:team_id/feature_flags/:id/': () => [409, { change_request_id: 'cr-1' }],+ },+ })++ const result = await updateFlagActiveInProject({ teamId: 2, flagId: 42, active: true })++ expect(result).toBeNull()+ expect(showApprovalRequiredToast).toHaveBeenCalledWith('cr-1', 'enable this feature flag')+ expect(dispatchChangeRequestCreated).toHaveBeenCalledWith({ resourceType: 'feature_flag', resourceId: 42 })+ })+})diff --git a/frontend/src/scenes/feature-flags/updateFlagActiveInProject.ts b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.tsnew file mode 100644index 000000000000..a56eee60de58--- /dev/null+++ b/frontend/src/scenes/feature-flags/updateFlagActiveInProject.ts@@ -0,0 +1,82 @@+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'+import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'++import { featureFlagsPartialUpdate } from 'products/feature_flags/frontend/generated/api'+import type { FeatureFlagApi } from 'products/feature_flags/frontend/generated/api.schemas'++/** Key for the per-row in-flight maps shared by the Projects tab toggles. */+export function flagToggleKey(teamId: number, flagId: number): string {+ return `${teamId}:${flagId}`+}++/** Confirmation dialog shared by the Projects tab toggles, naming the target project. */+export function confirmFlagActiveToggleInProject({+ teamName,+ active,+ onConfirm,+}: {+ teamName: string+ active: boolean+ onConfirm: () => void+}): void {+ LemonDialog.open({+ title: `${active ? 'Enable' : 'Disable'} this flag in ${teamName}?`,+ description: `This flag will be immediately ${+ active ? 'rolled out to' : 'rolled back from'+ } the users matching the release conditions in ${teamName}.`,+ primaryButton: {+ children: 'Confirm',+ type: 'primary',+ status: active ? 'default' : 'danger',+ size: 'small',+ onClick: onConfirm,+ },+ secondaryButton: {+ children: 'Cancel',+ type: 'tertiary',+ size: 'small',+ },+ })+}++/**+ * Handle an approval-required 409 from a flag update: show the approval toast and announce+ * the created change request. Returns whether the error was an approval-required response.+ */+export function handleFlagApprovalRequired(e: any, flagId: number, actionDescription: string): boolean {+ if (e?.status === 409 && e?.data?.change_request_id) {+ showApprovalRequiredToast(e.data.change_request_id, actionDescription)+ dispatchChangeRequestCreated({ resourceType: 'feature_flag', resourceId: flagId })+ return true+ }+ return false+}++/**+ * Toggle a flag's `active` state in any project of the current organization, with shared+ * toast handling (success, approval-required 409, permission/other errors).+ * Returns the updated flag, or `null` if the update did not go through.+ */+export async function updateFlagActiveInProject({+ teamId,+ flagId,+ active,+}: {+ teamId: number+ flagId: number+ active: boolean+}): Promise<FeatureFlagApi | null> {+ const actionDescription = `${active ? 'enable' : 'disable'} this feature flag`+ try {+ const updatedFlag = await featureFlagsPartialUpdate(String(teamId), flagId, { active })+ lemonToast.success(`Feature flag ${active ? 'enabled' : 'disabled'}`)+ return updatedFlag+ } catch (e: any) {+ if (!handleFlagApprovalRequired(e, flagId, actionDescription)) {+ lemonToast.error(e?.detail || e?.data?.detail || `Failed to ${actionDescription}`)+ }+ return null+ }+}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex dd0eff59b9ff..98961d7fd8f5 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4367,12 +4367,6 @@ export interface OrganizationFeatureFlagsCopyBody {disable_copied_flag?: boolean}-export type OrganizationFeatureFlags = {- flag_id: FeatureFlagType['id']- team_id: TeamType['id']- active: FeatureFlagType['active']-}[]-export enum FeatureFlagStatus {ACTIVE = 'active',STALE = 'stale',