: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): bulk copy flags to other projects from the flags list (#69044)
ruby childs0f0b6f572f58
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex ba2c587e740a..35e6a14df1ad 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -236,6 +236,7 @@ import type {} from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/types'import type { SymbolSetOrder } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/symbolSetLogic'import type { ErrorTrackingRecommendation } from 'products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/types'+import type { CopyFlagsResponseApi } from 'products/feature_flags/frontend/generated/api.schemas'import type {GitHubBranchesResponseApi,GitHubReposResponseApi,@@ -2595,10 +2596,7 @@ const api = {async copy(orgId: OrganizationType['id'] = ApiConfig.getCurrentOrganizationId(),data: OrganizationFeatureFlagsCopyBody- ): Promise<{- success: (FeatureFlagType & { flag_dependency_warnings?: string[]; schedule_copy_warning?: string })[]- failed: any- }> {+ ): Promise<CopyFlagsResponseApi> {return await new ApiRequest().copyOrganizationFeatureFlags(orgId).create({ data })},async keys(diff --git a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsxindex 8357a32fe9d4..7644c961e3f7 100644--- a/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/BulkSelectionBar.tsx@@ -1,4 +1,5 @@import clsx from 'clsx'+import { createPortal } from 'react-dom'import { LemonButton } from 'lib/lemon-ui/LemonButton'@@ -21,7 +22,7 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSeconst [singular, plural] = nounconst word = context.selectedCount === 1 ? singular : plural- return (+ const bar = (<divclassName={clsx('flex items-center justify-end gap-2 min-h-9 px-1 LemonTable__bulk-selection-bar',@@ -37,4 +38,6 @@ export function BulkSelectionBar<T extends Record<string, any>, K extends BulkSe{config.renderActions(context)}</div>)++ return config.barPortalTarget ? createPortal(bar, config.barPortalTarget) : bar}diff --git a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.tsindex 4bbeb771d64c..cba871adf259 100644--- a/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts+++ b/frontend/src/lib/lemon-ui/LemonTable/useBulkSelection.ts@@ -38,6 +38,10 @@ export interface BulkSelectionConfig<T extends Record<string, any>, K extends BuinitialSelectedKeys?: ReadonlyArray<K>/** Extra classes for the bulk-action bar wrapper (e.g. spacing). Opt-in so other tables are unaffected. */barClassName?: string+ /** Render the bar into this element (via portal) instead of above the table — lets callers place+ * it inline with an existing toolbar row. While the element is null (not mounted yet), the bar+ * falls back to its default position above the table. */+ barPortalTarget?: HTMLElement | null}export interface UseBulkSelectionResult<T, K extends BulkSelectionKey = BulkSelectionKey> {diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 2ddcdba1ee2a..d8b4730d40d7 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -894,6 +894,11 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportFailedToCreateFeatureFlagWithCohort: (code: string, detail: string) => ({ code, detail }),reportFeatureFlagCopySuccess: true,reportFeatureFlagCopyFailure: (error) => ({ error }),+ reportFeatureFlagBulkCopy: (flagCount: number, projectCount: number, failedCount: number) => ({+ flagCount,+ projectCount,+ failedCount,+ }),reportFeatureFlagScheduleSuccess: true,reportFeatureFlagScheduleFailure: (error) => ({ error }),reportInviteMembersButtonClicked: true,@@ -2046,6 +2051,13 @@ export const eventUsageLogic = kea<eventUsageLogicType>([reportFeatureFlagCopyFailure: ({ error }) => {posthog.capture('feature flag copy failure', { error })},+ reportFeatureFlagBulkCopy: ({ flagCount, projectCount, failedCount }) => {+ posthog.capture('feature flags bulk copied', {+ flag_count: flagCount,+ project_count: projectCount,+ failed_count: failedCount,+ })+ },reportFeatureFlagScheduleSuccess: () => {posthog.capture('feature flag scheduled')},diff --git a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.test.ts b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.test.tsnew file mode 100644index 000000000000..82db972514f8--- /dev/null+++ b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.test.ts@@ -0,0 +1,31 @@+import { splitCopiedByOverwrite } from './BulkCopyFlagsModal'++describe('splitCopiedByOverwrite', () => {+ it('returns no entries when nothing was copied', () => {+ expect(splitCopiedByOverwrite([])).toEqual({ newCopies: [], overwrites: [] })+ })++ it('puts a target with no overwrite entirely under newCopies', () => {+ const result = splitCopiedByOverwrite([{ key: 'flag-a', projectIds: [1, 2], updatedProjectIds: [] }])+ expect(result).toEqual({+ newCopies: [{ key: 'flag-a', projectIds: [1, 2] }],+ overwrites: [],+ })+ })++ it('puts a fully overwritten target entirely under overwrites', () => {+ const result = splitCopiedByOverwrite([{ key: 'flag-a', projectIds: [1, 2], updatedProjectIds: [1, 2] }])+ expect(result).toEqual({+ newCopies: [],+ overwrites: [{ key: 'flag-a', projectIds: [1, 2] }],+ })+ })++ it('splits a single key across both groups when only some of its targets were overwritten', () => {+ const result = splitCopiedByOverwrite([{ key: 'flag-a', projectIds: [1, 2, 3], updatedProjectIds: [2] }])+ expect(result).toEqual({+ newCopies: [{ key: 'flag-a', projectIds: [1, 3] }],+ overwrites: [{ key: 'flag-a', projectIds: [2] }],+ })+ })+})diff --git a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsxnew file mode 100644index 000000000000..023dcb6dd4b0--- /dev/null+++ b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx@@ -0,0 +1,308 @@+import { useActions, useValues } from 'kea'++import { IconCheck, IconWarning, IconX } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonCheckbox,+ LemonInputSelect,+ LemonModal,+ LemonSelect,+ LemonTag,+} from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'+import { organizationLogic } from 'scenes/organizationLogic'++import {+ BULK_COPY_MAX_TARGET_PROJECTS,+ BulkCopyFailure,+ BulkCopyResult,+ flagSelectionLogic,+} from './flagSelectionLogic'++/** Splits each copied entry's projectIds into freshly created flags vs. overwrites of flags that already existed in the target. */+export function splitCopiedByOverwrite(copied: BulkCopyResult['copied']): {+ newCopies: Array<{ key: string; projectIds: number[] }>+ overwrites: Array<{ key: string; projectIds: number[] }>+} {+ const newCopies = copied+ .map((entry) => ({+ key: entry.key,+ projectIds: entry.projectIds.filter((id) => !entry.updatedProjectIds.includes(id)),+ }))+ .filter((entry) => entry.projectIds.length > 0)+ const overwrites = copied+ .map((entry) => ({ key: entry.key, projectIds: entry.updatedProjectIds }))+ .filter((entry) => entry.projectIds.length > 0)+ return { newCopies, overwrites }+}++function CopiedFlagsList({+ entries,+ teamNameById,+}: {+ entries: Array<{ key: string; projectIds: number[] }>+ teamNameById: Map<number, string>+}): JSX.Element {+ return (+ <ul className="list-none pl-6 space-y-1">+ {entries.map((entry) => (+ <li key={entry.key} className="text-sm">+ <span className="font-medium">{entry.key}</span>+ <span className="text-muted">+ {' → '}+ {entry.projectIds.map((id) => teamNameById.get(id) ?? `Project ${id}`).join(', ')}+ </span>+ </li>+ ))}+ </ul>+ )+}++function FailureList({+ failures,+ teamNameById,+}: {+ failures: BulkCopyFailure[]+ teamNameById: Map<number, string>+}): JSX.Element {+ return (+ <ul className="list-none pl-6 space-y-1">+ {failures.map((failure, index) => (+ <li key={`${failure.key}-${failure.projectId}-${index}`} className="text-sm">+ <span className="font-medium">{failure.key}</span>+ <span className="text-muted">+ {' → '}+ {failure.projectId !== null+ ? (teamNameById.get(failure.projectId) ?? `Project ${failure.projectId}`)+ : 'unknown project'}+ </span>+ <span className="text-muted-alt"> — {failure.errorMessage}</span>+ </li>+ ))}+ </ul>+ )+}++export function BulkCopyFlagsModal(): JSX.Element | null {+ const {+ bulkCopyModalVisible,+ bulkCopyParams,+ bulkCopySourceProjectId,+ bulkCopyTargetProjectIds,+ bulkCopySchedule,+ bulkCopyDisableCopiedFlag,+ bulkCopyRunning,+ bulkCopyProgress,+ bulkCopyResult,+ bulkCopyFlagCount,+ } = useValues(flagSelectionLogic)+ const {+ closeBulkCopyModal,+ setBulkCopySourceProjectId,+ setBulkCopyTargetProjectIds,+ setBulkCopySchedule,+ setBulkCopyDisableCopiedFlag,+ bulkCopyFlags,+ } = useActions(flagSelectionLogic)+ const { currentOrganization } = useValues(organizationLogic)++ if (!bulkCopyModalVisible || !bulkCopyParams) {+ return null+ }++ const teams = [...(currentOrganization?.teams ?? [])].sort((a, b) => a.name.localeCompare(b.name))+ const teamNameById = new Map(teams.map((team) => [team.id, team.name]))+ const destinationOptions = teams+ .filter((team) => team.id !== bulkCopySourceProjectId)+ .map((team) => ({ key: String(team.id), label: team.name, value: team.id }))++ const pendingApproval = bulkCopyResult?.failed.filter((failure) => failure.approvalPending) ?? []+ const hardFailures = bulkCopyResult?.failed.filter((failure) => !failure.approvalPending) ?? []+ const { newCopies, overwrites } = splitCopiedByOverwrite(bulkCopyResult?.copied ?? [])++ const submitDisabledReason =+ bulkCopyTargetProjectIds.length === 0+ ? 'Select at least one destination project'+ : bulkCopyTargetProjectIds.length > BULK_COPY_MAX_TARGET_PROJECTS+ ? `Bulk copy supports up to ${BULK_COPY_MAX_TARGET_PROJECTS} destination projects at once`+ : undefined++ return (+ <LemonModal+ isOpen={bulkCopyModalVisible}+ onClose={() => {+ if (!bulkCopyRunning) {+ closeBulkCopyModal()+ }+ }}+ title={bulkCopyResult ? 'Copy results' : `Copy ${pluralize(bulkCopyFlagCount, 'flag')} to other projects`}+ width={600}+ footer={+ bulkCopyResult ? (+ <LemonButton type="primary" onClick={closeBulkCopyModal} data-attr="bulk-copy-flags-done">+ Done+ </LemonButton>+ ) : (+ <>+ <LemonButton+ type="secondary"+ onClick={closeBulkCopyModal}+ disabledReason={bulkCopyRunning ? 'Copy in progress' : undefined}+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={bulkCopyFlags}+ loading={bulkCopyRunning}+ disabledReason={submitDisabledReason}+ data-attr="bulk-copy-flags-submit"+ >+ {bulkCopyRunning && bulkCopyProgress+ ? `Copying ${bulkCopyProgress.done} of ${bulkCopyProgress.total}…`+ : 'Copy flags'}+ </LemonButton>+ <span aria-live="polite" aria-atomic="true" className="sr-only">+ {bulkCopyRunning && bulkCopyProgress+ ? `Copying ${bulkCopyProgress.done} of ${bulkCopyProgress.total}`+ : ''}+ </span>+ </>+ )+ }+ >+ {bulkCopyResult ? (+ <div className="space-y-4">+ {newCopies.length > 0 && (+ <div className="space-y-2">+ <div className="flex items-center gap-2 text-success font-medium">+ <IconCheck className="text-lg" />+ <span>Copied {pluralize(newCopies.length, 'new flag')}</span>+ </div>+ <CopiedFlagsList entries={newCopies} teamNameById={teamNameById} />+ </div>+ )}+ {overwrites.length > 0 && (+ <div className="space-y-2">+ <div className="flex items-center gap-2 text-warning font-medium">+ <IconWarning className="text-lg" />+ <span>Updated {pluralize(overwrites.length, 'existing flag')}</span>+ </div>+ <p className="text-sm text-muted pl-6 mb-0">+ These flags already existed in the destination project and were overwritten with the+ copied configuration.+ </p>+ <CopiedFlagsList entries={overwrites} teamNameById={teamNameById} />+ </div>+ )}+ {pendingApproval.length > 0 && (+ <div className="space-y-2">+ <div className="flex items-center gap-2 text-warning font-medium">+ <IconWarning className="text-lg" />+ <span>+ {pluralize(pendingApproval.length, 'copy', 'copies')} pending approval+ <LemonTag type="warning" className="ml-2 uppercase">+ Not applied yet+ </LemonTag>+ </span>+ </div>+ <p className="text-sm text-muted pl-6 mb-0">+ These projects require approval for flag changes. A change request was created for each+ and the copy will apply once approved.+ </p>+ <FailureList failures={pendingApproval} teamNameById={teamNameById} />+ </div>+ )}+ {hardFailures.length > 0 && (+ <div className="space-y-2">+ <div className="flex items-center gap-2 text-danger font-medium">+ <IconX className="text-lg" />+ <span>{pluralize(hardFailures.length, 'copy', 'copies')} failed</span>+ </div>+ <FailureList failures={hardFailures} teamNameById={teamNameById} />+ </div>+ )}+ {bulkCopyResult.skippedFlagCount > 0 && (+ <p className="text-sm text-muted mb-0">+ {pluralize(bulkCopyResult.skippedFlagCount, 'selected flag')} could not be resolved and{' '}+ {bulkCopyResult.skippedFlagCount === 1 ? 'was' : 'were'} skipped — possibly deleted since+ selection.+ </p>+ )}+ {bulkCopyResult.warnings.length > 0 && (+ <LemonBanner type="warning">+ <div className="space-y-1">+ {bulkCopyResult.warnings.map((warning) => (+ <div key={warning} className="text-sm">+ {warning}+ </div>+ ))}+ </div>+ </LemonBanner>+ )}+ </div>+ ) : (+ <div className="space-y-4">+ <LemonBanner type="warning">+ <ul className="list-disc pl-4 space-y-1">+ <li>If a flag with the same key exists in a destination, it will be overwritten.</li>+ <li>+ If your flag uses a static cohort, it will get an empty cohort if a cohort with the same+ name does not exist in the destination.+ </li>+ </ul>+ </LemonBanner>+ {bulkCopyParams.sourceSelectable && (+ <div className="space-y-1">+ <div className="font-semibold">Source project</div>+ <LemonSelect+ value={bulkCopySourceProjectId}+ onChange={(id) => id !== null && setBulkCopySourceProjectId(id)}+ options={teams.map((team) => ({ value: team.id, label: team.name }))}+ dropdownMatchSelectWidth={false}+ data-attr="bulk-copy-flags-source"+ />+ <p className="text-sm text-muted mb-0">+ Flags that don't exist in the source project are skipped and reported.+ </p>+ </div>+ )}+ <div className="space-y-1">+ <div className="font-semibold">Destination projects</div>+ <LemonInputSelect<number>+ mode="multiple"+ value={bulkCopyTargetProjectIds}+ onChange={setBulkCopyTargetProjectIds}+ options={destinationOptions}+ placeholder="Select projects to copy to"+ disabled={bulkCopyRunning}+ data-attr="bulk-copy-flags-destinations"+ />+ </div>+ <LemonCheckbox+ checked={bulkCopySchedule}+ onChange={setBulkCopySchedule}+ disabled={bulkCopyRunning}+ label="Copy pending scheduled changes"+ data-attr="bulk-copy-flags-schedule"+ />+ <LemonCheckbox+ checked={bulkCopyDisableCopiedFlag}+ onChange={setBulkCopyDisableCopiedFlag}+ disabled={bulkCopyRunning}+ label="Copy as disabled"+ data-attr="bulk-copy-flags-disable"+ />+ {bulkCopyDisableCopiedFlag && (+ <p className="text-sm text-muted mb-0">+ Copied flags will be disabled in the destination projects regardless of their status here —+ useful when staging config shouldn't go live in production immediately.+ </p>+ )}+ </div>+ )}+ </LemonModal>+ )+}diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsxindex 0d1108de4185..b058bfb9953c 100644--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { combineUrl, router } from 'kea-router'import { useEffect, useRef, useState } from 'react'-import { IconLock, IconPlusSmall, IconTrash } from '@posthog/icons'+import { IconCopy, IconLock, IconPlusSmall, IconTrash } from '@posthog/icons'import { LemonButton, LemonDialog, LemonTag, lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'@@ -33,6 +33,7 @@ import stringWithWBR from 'lib/utils/stringWithWBR'import { toParams } from 'lib/utils/url'import { PendingApprovalsBanner } from 'scenes/approvals/PendingApprovalsBanner'import { NotificationsPane } from 'scenes/hog-functions/list/NotificationsPane'+import { organizationLogic } from 'scenes/organizationLogic'import { projectLogic } from 'scenes/projectLogic'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'@@ -57,12 +58,13 @@ import {} from '~/types'import { ApprovalsPromoBanner } from './ApprovalsPromoBanner'+import { BulkCopyFlagsModal } from './BulkCopyFlagsModal'import { BulkDeleteResultsModal } from './BulkDeleteResultsModal'import { openFeatureFlagArchiveDialog } from './featureFlagArchiveDialog'import { openFeatureFlagDeleteDialog } from './featureFlagDeleteDialog'import { FeatureFlagFiltersSection } from './FeatureFlagFilters'import { FLAGS_PER_PAGE, FeatureFlagsTab, featureFlagsLogic, flagMatchesType } from './featureFlagsLogic'-import { flagSelectionLogic } from './flagSelectionLogic'+import { BULK_COPY_MAX_FLAGS, flagSelectionLogic } from './flagSelectionLogic'import { OverlayForNewFeatureFlagMenu } from './NewFeatureFlagMenu'import ProjectsGrid from './projects-grid/ProjectsGrid'@@ -394,9 +396,10 @@ export function OverviewTab({const isProductIntroVisible = shouldShowEmptyState || !user?.has_seen_product_intro_for?.[ProductKey.FEATURE_FLAGS]const { currentProjectId } = useValues(projectLogic)+ const { currentOrganization } = useValues(organizationLogic)const { paramsFromFilters } = useValues(featureFlagsLogic({}))const { bulkDeleteResponseLoading } = useValues(flagSelectionLogic)- const { bulkDeleteFlags } = useActions(flagSelectionLogic)+ const { bulkDeleteFlags, openBulkCopyModal } = useActions(flagSelectionLogic)const [matchingFlagIds, setMatchingFlagIds] = useState<readonly number[] | null>(null)const [matchingFlagIdsLoading, setMatchingFlagIdsLoading] = useState(false)@@ -597,6 +600,7 @@ export function OverviewTab({<PendingApprovalsBanner /><div>{filtersSection}</div><BulkDeleteResultsModal />+ <BulkCopyFlagsModal /><LemonTabledataSource={displayedFlags}@@ -671,6 +675,29 @@ export function OverviewTab({Select all {totalMatchingCount} matching flags</LemonButton>)}+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconCopy />}+ data-attr="bulk-copy-flags-button"+ disabledReason={+ (currentOrganization?.teams?.length ?? 0) <= 1+ ? 'Your organization has only one project'+ : ctx.selectedCount > BULK_COPY_MAX_FLAGS+ ? `Bulk copy supports up to ${BULK_COPY_MAX_FLAGS} flags at once`+ : undefined+ }+ onClick={() => {+ if (currentProjectId) {+ openBulkCopyModal({+ sourceProjectId: currentProjectId,+ flagIds: [...ctx.selectedKeys],+ })+ }+ }}+ >+ Copy to projects+ </LemonButton><BulkUpdateTagsButtonresource="feature_flags"selectedIds={ctx.selectedKeys}diff --git a/frontend/src/scenes/feature-flags/flagSelectionLogic.test.ts b/frontend/src/scenes/feature-flags/flagSelectionLogic.test.tsnew file mode 100644index 000000000000..4eb6b692cb53--- /dev/null+++ b/frontend/src/scenes/feature-flags/flagSelectionLogic.test.ts@@ -0,0 +1,209 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { BULK_COPY_MAX_FLAGS, flagSelectionLogic } from './flagSelectionLogic'++const TARGET_A = 500+const TARGET_B = 501++describe('flagSelectionLogic bulk copy', () => {+ let logic: ReturnType<typeof flagSelectionLogic.build>+ let copyRequests: Record<string, any>[]++ function useCopyMocks(+ copyHandler: (body: Record<string, any>) => [number, any],+ bulkKeys: Record<string, string> = {}+ ): void {+ copyRequests = []+ useMocks({+ get: {+ '/api/projects/:team/feature_flags/': { count: 0, results: [] },+ },+ post: {+ '/api/projects/:team/feature_flags/bulk_keys/': [200, { keys: bulkKeys }],+ '/api/organizations/:org/feature_flags/copy_flags/': async ({ request }) => {+ const body = (await request.json()) as Record<string, any>+ copyRequests.push(body)+ return copyHandler(body)+ },+ },+ })+ }++ function successResponse(key: string, extra: Record<string, any> = {}): [number, any] {+ return [200, { success: [{ id: 1, key, name: key, active: true, ...extra }], failed: [] }]+ }++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => logic?.unmount())++ it('resolves flag IDs to keys and issues one copy request per key with the configured payload', async () => {+ useCopyMocks((body) => successResponse(body.feature_flag_key), { '1': 'flag-a', '2': 'flag-b' })+ logic = flagSelectionLogic()+ logic.mount()++ logic.actions.openBulkCopyModal({ sourceProjectId: MOCK_TEAM_ID, flagIds: [1, 2, 3] })+ logic.actions.setBulkCopyTargetProjectIds([TARGET_A, TARGET_B])+ logic.actions.setBulkCopySchedule(true)+ logic.actions.bulkCopyFlags()+ await expectLogic(logic).toFinishAllListeners()++ expect(copyRequests).toEqual([+ {+ feature_flag_key: 'flag-a',+ from_project: MOCK_TEAM_ID,+ target_project_ids: [TARGET_A, TARGET_B],+ copy_schedule: true,+ disable_copied_flag: false,+ },+ {+ feature_flag_key: 'flag-b',+ from_project: MOCK_TEAM_ID,+ target_project_ids: [TARGET_A, TARGET_B],+ copy_schedule: true,+ disable_copied_flag: false,+ },+ ])+ expect(logic.values.bulkCopyResult).toEqual({+ copied: [+ { key: 'flag-a', projectIds: [TARGET_A, TARGET_B], updatedProjectIds: [] },+ { key: 'flag-b', projectIds: [TARGET_A, TARGET_B], updatedProjectIds: [] },+ ],+ failed: [],+ warnings: [],+ // ID 3 didn't resolve to a key (e.g. deleted since selection)+ skippedFlagCount: 1,+ })+ expect(logic.values.bulkCopyRunning).toBe(false)+ expect(logic.values.bulkCopyProgress).toEqual({ done: 2, total: 2 })+ })++ it('aggregates per-project failures, approval-pending entries, and warnings without blocking other targets', async () => {+ useCopyMocks((body) => {+ if (body.feature_flag_key === 'flag-a') {+ return [+ 200,+ {+ success: [+ {+ id: 1,+ key: 'flag-a',+ name: '',+ active: false,+ team_id: TARGET_A,+ updated_existing: true,+ flag_dependency_warnings: ['dropped'],+ },+ ],+ failed: [+ {+ project_id: TARGET_B,+ error_message: 'Approval required',+ approval_pending: true,+ change_request_id: 'cr-1',+ },+ ],+ },+ ]+ }+ return [+ 200,+ {+ success: [+ {+ id: 2,+ key: 'flag-b',+ name: '',+ active: true,+ team_id: TARGET_B,+ updated_existing: false,+ schedule_copy_warning: 'no schedules',+ },+ ],+ failed: [{ project_id: TARGET_A, error_message: 'Project not found.' }],+ },+ ]+ })+ logic = flagSelectionLogic()+ logic.mount()++ logic.actions.openBulkCopyModal({ sourceProjectId: MOCK_TEAM_ID, flagKeys: ['flag-a', 'flag-b'] })+ logic.actions.setBulkCopyTargetProjectIds([TARGET_A, TARGET_B])+ logic.actions.bulkCopyFlags()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.bulkCopyResult).toEqual({+ copied: [+ // flag-a overwrote an existing flag in its surviving target+ { key: 'flag-a', projectIds: [TARGET_A], updatedProjectIds: [TARGET_A] },+ { key: 'flag-b', projectIds: [TARGET_B], updatedProjectIds: [] },+ ],+ failed: [+ { key: 'flag-a', projectId: TARGET_B, errorMessage: 'Approval required', approvalPending: true },+ { key: 'flag-b', projectId: TARGET_A, errorMessage: 'Project not found.', approvalPending: undefined },+ ],+ warnings: ['flag-a: dropped', 'flag-b: no schedules'],+ skippedFlagCount: 0,+ })+ })++ it('records failures for every target of a key whose request throws and continues with the remaining keys', async () => {+ useCopyMocks((body) =>+ body.feature_flag_key === 'flag-a' ? [500, { detail: 'Server error' }] : successResponse('flag-b')+ )+ logic = flagSelectionLogic()+ logic.mount()++ logic.actions.openBulkCopyModal({ sourceProjectId: MOCK_TEAM_ID, flagKeys: ['flag-a', 'flag-b'] })+ logic.actions.setBulkCopyTargetProjectIds([TARGET_A, TARGET_B])+ logic.actions.bulkCopyFlags()+ await expectLogic(logic).toFinishAllListeners()++ expect(copyRequests).toHaveLength(2)+ expect(logic.values.bulkCopyResult?.copied).toEqual([+ { key: 'flag-b', projectIds: [TARGET_A, TARGET_B], updatedProjectIds: [] },+ ])+ expect(logic.values.bulkCopyResult?.failed).toEqual([+ { key: 'flag-a', projectId: TARGET_A, errorMessage: 'Server error' },+ { key: 'flag-a', projectId: TARGET_B, errorMessage: 'Server error' },+ ])+ })++ it('refuses to run above the flag cap without issuing any copy requests', async () => {+ useCopyMocks((body) => successResponse(body.feature_flag_key))+ logic = flagSelectionLogic()+ logic.mount()++ const tooManyKeys = Array.from({ length: BULK_COPY_MAX_FLAGS + 1 }, (_, i) => `flag-${i}`)+ logic.actions.openBulkCopyModal({ sourceProjectId: MOCK_TEAM_ID, flagKeys: tooManyKeys })+ logic.actions.setBulkCopyTargetProjectIds([TARGET_A])+ logic.actions.bulkCopyFlags()+ await expectLogic(logic).toFinishAllListeners()++ expect(copyRequests).toHaveLength(0)+ expect(logic.values.bulkCopyResult).toBeNull()+ expect(logic.values.bulkCopyRunning).toBe(false)+ })++ it('stops before issuing any copy request when none of the selected flags resolve to a key', async () => {+ useCopyMocks((body) => successResponse(body.feature_flag_key), {})+ logic = flagSelectionLogic()+ logic.mount()++ logic.actions.openBulkCopyModal({ sourceProjectId: MOCK_TEAM_ID, flagIds: [1, 2] })+ logic.actions.setBulkCopyTargetProjectIds([TARGET_A])+ logic.actions.bulkCopyFlags()+ await expectLogic(logic).toFinishAllListeners()++ expect(copyRequests).toHaveLength(0)+ expect(logic.values.bulkCopyResult).toBeNull()+ expect(logic.values.bulkCopyRunning).toBe(false)+ })+})diff --git a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts b/frontend/src/scenes/feature-flags/flagSelectionLogic.tsindex 6a2c4c6290d0..fa14cfc5635b 100644--- a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts+++ b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts@@ -2,7 +2,12 @@ import { actions, connect, kea, listeners, path, reducers, selectors } from 'keaimport { loaders } from 'kea-loaders'import { beforeUnload } from 'kea-router'+import { lemonToast } from '@posthog/lemon-ui'+import api from 'lib/api'+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'+import { pluralize } from 'lib/utils/strings'+import { organizationLogic } from 'scenes/organizationLogic'import { projectLogic } from 'scenes/projectLogic'import { featureFlagsLogic } from './featureFlagsLogic'@@ -22,17 +27,110 @@ export interface BulkDeleteResult {errors: Array<{ id: number; key?: string; reason: string }>}+export const BULK_COPY_MAX_FLAGS = 100+export const BULK_COPY_MAX_TARGET_PROJECTS = 50++export interface BulkCopyParams {+ /** Project the flags are copied from. */+ sourceProjectId: number+ /** Selected flag IDs (overview tab) — resolved to keys via bulk_keys at submit time. */+ flagIds?: number[]+ /** Selected flag keys (projects grid) — used as-is. */+ flagKeys?: string[]+ /** Whether the modal lets the user change the source project (projects grid rows are org-level). */+ sourceSelectable?: boolean+}++export interface BulkCopyFailure {+ key: string+ projectId: number | null+ errorMessage: string+ /** The copy wasn't applied because the target project requires approval — a change request was created. */+ approvalPending?: boolean+}++export interface BulkCopyResult {+ copied: Array<{+ key: string+ projectIds: number[]+ /** Subset of projectIds where a flag with this key already existed and was overwritten. */+ updatedProjectIds: number[]+ }>+ failed: BulkCopyFailure[]+ warnings: string[]+ /** Selected flags that no longer resolved to a key (e.g. deleted between selection and submit). */+ skippedFlagCount: number+}++function summarizeBulkCopy(+ copied: BulkCopyResult['copied'],+ failed: BulkCopyFailure[],+ targetCount: number+): { level: 'success' | 'warning' | 'error'; message: string } {+ const pendingApprovalCount = failed.filter((failure) => failure.approvalPending).length+ const hardFailureCount = failed.length - pendingApprovalCount+ const updatedPairCount = copied.reduce((count, entry) => count + entry.updatedProjectIds.length, 0)+ const summary =+ `Copied ${pluralize(copied.length, 'flag')} to ${pluralize(targetCount, 'project')}` ++ (updatedPairCount > 0 ? ` (${pluralize(updatedPairCount, 'existing flag')} overwritten)` : '')+ if (failed.length === 0 && copied.length > 0) {+ return { level: 'success', message: summary }+ }+ if (copied.length > 0 || pendingApprovalCount > 0) {+ return {+ level: 'warning',+ message: `${summary}${pendingApprovalCount > 0 ? `, ${pendingApprovalCount} pending approval` : ''}${+ hardFailureCount > 0 ? `, ${hardFailureCount} failed` : ''+ }`,+ }+ }+ return { level: 'error', message: 'No flags were copied' }+}++function errorMessageFrom(error: unknown): string {+ if (typeof error === 'string') {+ return error+ }+ if (error && typeof error === 'object') {+ const { detail, message } = error as { detail?: unknown; message?: unknown }+ if (typeof detail === 'string') {+ return detail+ }+ if (typeof message === 'string') {+ return message+ }+ return JSON.stringify(error)+ }+ return 'Request failed'+}+export const flagSelectionLogic = kea<flagSelectionLogicType>([path(['scenes', 'feature-flags', 'flagSelectionLogic']),connect(() => ({- values: [projectLogic, ['currentProjectId'], featureFlagsLogic({}), ['paramsFromFilters']],- actions: [featureFlagsLogic({}), ['loadFeatureFlags']],+ values: [+ projectLogic,+ ['currentProjectId'],+ featureFlagsLogic({}),+ ['paramsFromFilters'],+ organizationLogic,+ ['currentOrganization'],+ ],+ actions: [featureFlagsLogic({}), ['loadFeatureFlags'], eventUsageLogic, ['reportFeatureFlagBulkCopy']],})),actions({showResultsModal: (result: BulkDeleteResult) => ({ result }),hideResultsModal: true,+ openBulkCopyModal: (params: BulkCopyParams) => ({ params }),+ closeBulkCopyModal: true,+ setBulkCopySourceProjectId: (projectId: number) => ({ projectId }),+ setBulkCopyTargetProjectIds: (projectIds: number[]) => ({ projectIds }),+ setBulkCopySchedule: (copySchedule: boolean) => ({ copySchedule }),+ setBulkCopyDisableCopiedFlag: (disableCopiedFlag: boolean) => ({ disableCopiedFlag }),+ setBulkCopyProgress: (done: number, total: number) => ({ done, total }),+ bulkCopyFlags: true,+ bulkCopyFlagsFinished: (result: BulkCopyResult | null) => ({ result }),}),reducers({@@ -43,6 +141,64 @@ export const flagSelectionLogic = kea<flagSelectionLogicType>([hideResultsModal: () => null,},],+ bulkCopyParams: [+ null as BulkCopyParams | null,+ {+ openBulkCopyModal: (_, { params }) => params,+ closeBulkCopyModal: () => null,+ },+ ],+ bulkCopySourceProjectId: [+ null as number | null,+ {+ openBulkCopyModal: (_, { params }) => params.sourceProjectId,+ setBulkCopySourceProjectId: (_, { projectId }) => projectId,+ },+ ],+ bulkCopyTargetProjectIds: [+ [] as number[],+ {+ openBulkCopyModal: () => [],+ setBulkCopyTargetProjectIds: (_, { projectIds }) => projectIds,+ // A project can't be both source and destination of the same copy+ setBulkCopySourceProjectId: (state, { projectId }) => state.filter((id) => id !== projectId),+ },+ ],+ bulkCopySchedule: [+ false,+ {+ openBulkCopyModal: () => false,+ setBulkCopySchedule: (_, { copySchedule }) => copySchedule,+ },+ ],+ bulkCopyDisableCopiedFlag: [+ false,+ {+ openBulkCopyModal: () => false,+ setBulkCopyDisableCopiedFlag: (_, { disableCopiedFlag }) => disableCopiedFlag,+ },+ ],+ bulkCopyRunning: [+ false,+ {+ bulkCopyFlags: () => true,+ bulkCopyFlagsFinished: () => false,+ },+ ],+ bulkCopyProgress: [+ null as { done: number; total: number } | null,+ {+ openBulkCopyModal: () => null,+ setBulkCopyProgress: (_, { done, total }) => ({ done, total }),+ },+ ],+ bulkCopyResult: [+ null as BulkCopyResult | null,+ {+ openBulkCopyModal: () => null,+ bulkCopyFlagsFinished: (_, { result }) => result,+ },+ ],}),loaders(({ values }) => ({@@ -70,19 +226,122 @@ export const flagSelectionLogic = kea<flagSelectionLogicType>([selectors({resultsModalVisible: [(s) => [s.bulkDeleteResult], (result: BulkDeleteResult | null) => result !== null],+ bulkCopyModalVisible: [(s) => [s.bulkCopyParams], (params: BulkCopyParams | null) => params !== null],+ bulkCopyFlagCount: [+ (s) => [s.bulkCopyParams],+ (params: BulkCopyParams | null): number => params?.flagKeys?.length ?? params?.flagIds?.length ?? 0,+ ],}),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({bulkDeleteFlagsSuccess: ({ bulkDeleteResponse }) => {if (bulkDeleteResponse) {actions.showResultsModal(bulkDeleteResponse)actions.loadFeatureFlags()}},+ bulkCopyFlags: async () => {+ const params = values.bulkCopyParams+ const sourceProjectId = values.bulkCopySourceProjectId+ const targetProjectIds = values.bulkCopyTargetProjectIds+ if (!params || !sourceProjectId || targetProjectIds.length === 0) {+ actions.bulkCopyFlagsFinished(null)+ return+ }++ let keys: string[] = []+ let skippedFlagCount = 0+ try {+ if (params.flagKeys?.length) {+ keys = Array.from(new Set(params.flagKeys))+ } else if (params.flagIds?.length) {+ const response = await api.featureFlags.bulkKeys(params.flagIds)+ keys = Array.from(new Set(Object.values(response.keys)))+ skippedFlagCount = params.flagIds.length - Object.keys(response.keys).length+ }+ } catch (error) {+ lemonToast.error(`Failed to resolve selected flags: ${errorMessageFrom(error)}`)+ actions.bulkCopyFlagsFinished(null)+ return+ }+ if (keys.length === 0) {+ lemonToast.error('None of the selected flags could be resolved — they may have been deleted.')+ actions.bulkCopyFlagsFinished(null)+ return+ }+ if (keys.length > BULK_COPY_MAX_FLAGS) {+ lemonToast.error(`Bulk copy supports up to ${BULK_COPY_MAX_FLAGS} flags at once.`)+ actions.bulkCopyFlagsFinished(null)+ return+ }++ const copied: BulkCopyResult['copied'] = []+ const failed: BulkCopyFailure[] = []+ const warnings = new Set<string>()++ actions.setBulkCopyProgress(0, keys.length)+ // Sequential on purpose: each call already fans out to every target project server-side+ // (and may create cohorts there), so parallel calls would multiply write load and risk+ // rate limiting without improving perceived progress.+ for (const [index, key] of keys.entries()) {+ try {+ const response = await api.organizationFeatureFlags.copy(values.currentOrganization?.id, {+ feature_flag_key: key,+ from_project: sourceProjectId,+ target_project_ids: targetProjectIds,+ copy_schedule: values.bulkCopySchedule,+ disable_copied_flag: values.bulkCopyDisableCopiedFlag,+ })+ const failedEntries = response.failed+ // Copied targets are inferred as requested-minus-failed (robust to success items+ // missing team_id during deploy skew); overwrites come from the per-item flag.+ const failedProjectIds = new Set(failedEntries.map((entry) => entry.project_id))+ const copiedProjectIds = targetProjectIds.filter((id) => !failedProjectIds.has(id))+ const updatedProjectIds = response.success+ .filter((item) => item.updated_existing && item.team_id != null)+ .map((item) => item.team_id)+ if (copiedProjectIds.length > 0) {+ copied.push({ key, projectIds: copiedProjectIds, updatedProjectIds })+ }+ for (const entry of failedEntries) {+ failed.push({+ key,+ projectId: entry.project_id ?? null,+ errorMessage: errorMessageFrom(entry.error_message ?? 'Copy failed'),+ approvalPending: entry.approval_pending,+ })+ }+ for (const successItem of response.success) {+ for (const warning of successItem.flag_dependency_warnings ?? []) {+ warnings.add(`${key}: ${warning}`)+ }+ if (successItem.schedule_copy_warning) {+ warnings.add(`${key}: ${successItem.schedule_copy_warning}`)+ }+ }+ } catch (error) {+ for (const projectId of targetProjectIds) {+ failed.push({ key, projectId, errorMessage: errorMessageFrom(error) })+ }+ }+ actions.setBulkCopyProgress(index + 1, keys.length)+ }++ actions.bulkCopyFlagsFinished({+ copied,+ failed,+ warnings: Array.from(warnings),+ skippedFlagCount,+ })+ actions.reportFeatureFlagBulkCopy(keys.length, targetProjectIds.length, failed.length)++ const { level, message } = summarizeBulkCopy(copied, failed, targetProjectIds.length)+ lemonToast[level](message)+ },})),beforeUnload(({ values }) => ({- enabled: () => values.bulkDeleteResponseLoading,- message: 'Bulk delete is in progress. Leaving may result in incomplete deletion.',+ enabled: () => values.bulkDeleteResponseLoading || values.bulkCopyRunning,+ message: 'A bulk flag operation is in progress. Leaving may interrupt it.',})),])diff --git a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsxindex 378540c4a1fa..3741ffeffb43 100644--- a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx+++ b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx@@ -1,7 +1,8 @@import { useActions, useValues } from 'kea'-import { useEffect, useMemo, useRef } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'-import { LemonSkeleton } from '@posthog/lemon-ui'+import { IconCopy } from '@posthog/icons'+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'@@ -12,6 +13,8 @@ import { urls } from 'scenes/urls'import { SceneSection } from '~/layout/scenes/components/SceneSection'import { OrganizationFeatureFlag, OrganizationFeatureFlagRow } from '~/types'+import { BulkCopyFlagsModal } from '../BulkCopyFlagsModal'+import { BULK_COPY_MAX_FLAGS, flagSelectionLogic } from '../flagSelectionLogic'import { confirmFlagActiveToggleInProject, flagToggleKey } from '../updateFlagActiveInProject'import { CellState, ProjectsGridCell } from './ProjectsGridCell'import { projectsGridLogic } from './projectsGridLogic'@@ -71,8 +74,11 @@ export function ProjectsGrid(): JSX.Element {const { loadMoreFlags, toggleFlagActive } = useActions(projectsGridLogic)const { currentOrganization } = useValues(organizationLogic)const { currentTeamId } = useValues(teamLogic)+ const { openBulkCopyModal } = useActions(flagSelectionLogic)const sentinelRef = useRef<HTMLDivElement>(null)+ // State (not a ref) so the table re-renders once the toolbar slot mounts and the bar can portal into it+ const [bulkBarTarget, setBulkBarTarget] = useState<HTMLDivElement | null>(null)useEffect(() => {const el = sentinelRef.current@@ -161,7 +167,8 @@ export function ProjectsGrid(): JSX.Element {title="Feature flags across projects"description="Compare each flag's status, rollout, and recent usage across your organization's projects.">- <ProjectsGridToolbar />+ <ProjectsGridToolbar bulkSelectionBarRef={setBulkBarTarget} />+ <BulkCopyFlagsModal /><LemonTablecolumns={columns}dataSource={flags}@@ -170,6 +177,35 @@ export function ProjectsGrid(): JSX.Element {emptyState="No flags match your search."data-attr="projects-grid-table"className="[&_table]:table-fixed"+ bulkSelection={{+ getKey: (flag: OrganizationFeatureFlagRow): string => flag.key,+ rowAriaLabel: (flag: OrganizationFeatureFlagRow) => `Select feature flag ${flag.key}`,+ headerAriaLabel: 'Select all loaded feature flags',+ noun: ['flag', 'flags'],+ barPortalTarget: bulkBarTarget,+ renderActions: (ctx) => (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconCopy />}+ data-attr="projects-grid-bulk-copy-button"+ disabledReason={+ ctx.selectedCount > BULK_COPY_MAX_FLAGS+ ? `Bulk copy supports up to ${BULK_COPY_MAX_FLAGS} flags at once`+ : undefined+ }+ onClick={() => {+ openBulkCopyModal({+ sourceProjectId: currentTeamId,+ flagKeys: ctx.selectedKeys.map(String),+ sourceSelectable: true,+ })+ }}+ >+ Copy to projects+ </LemonButton>+ ),+ }}/>{flagsPageLoading && flags.length > 0 && <LemonSkeleton className="h-8 my-2" />}<div ref={sentinelRef} className="h-1" />diff --git a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridToolbar.tsx b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridToolbar.tsxindex 4e9e4fd92609..10738db588aa 100644--- a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridToolbar.tsx+++ b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGridToolbar.tsx@@ -5,7 +5,12 @@ import { LemonInput } from '@posthog/lemon-ui'import { projectsGridLogic } from './projectsGridLogic'import { ProjectsGridPicker } from './ProjectsGridPicker'-export function ProjectsGridToolbar(): JSX.Element {+export function ProjectsGridToolbar({+ bulkSelectionBarRef,+}: {+ /** Slot the table's bulk selection bar is portaled into, so it shares this row. */+ bulkSelectionBarRef?: (element: HTMLDivElement | null) => void+}): JSX.Element {const { search } = useValues(projectsGridLogic)const { setSearch } = useActions(projectsGridLogic)@@ -19,7 +24,10 @@ export function ProjectsGridToolbar(): JSX.Element {className="max-w-80 grow"data-attr="projects-grid-search"/>- <ProjectsGridPicker />+ <div className="flex flex-wrap items-center gap-2">+ <div ref={bulkSelectionBarRef} className="flex items-center empty:hidden" />+ <ProjectsGridPicker />+ </div></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 0fc86360de4f..9a94ff49cd7c 100644--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts@@ -127,6 +127,25 @@ describe('projectsGridLogic', () => {expect(maxInFlight).toBe(1)})+ it('re-fetches siblings of loaded rows after a bulk copy finishes', async () => {+ await expectLogic(logic).toFinishAllListeners()+ callOrder = []++ logic.actions.bulkCopyFlagsFinished({+ copied: [+ { key: 'flag_2', projectIds: [2], updatedProjectIds: [] },+ { key: 'not_in_grid', projectIds: [2], updatedProjectIds: [] },+ ],+ failed: [],+ warnings: [],+ skippedFlagCount: 0,+ })+ await expectLogic(logic).toFinishAllListeners()++ // Only the key shown in the grid is re-fetched; keys outside the loaded rows are skipped.+ expect(callOrder).toEqual(['flag_2'])+ })+it('resets sibling queue when search changes', async () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.siblingQueue).toHaveLength(0)diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.tsindex ddf3c9548224..dca8828f65c7 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 { flagSelectionLogic } from '../flagSelectionLogic'import { flagToggleKey, updateFlagActiveInProject } from '../updateFlagActiveInProject'import type { projectsGridLogicType } from './projectsGridLogicType'@@ -26,6 +27,7 @@ export const projectsGridLogic = kea<projectsGridLogicType>([path(['scenes', 'feature-flags', 'projects-grid', 'projectsGridLogic']),connect(() => ({values: [teamLogic, ['currentTeamId'], organizationLogic, ['currentOrganization']],+ actions: [flagSelectionLogic, ['bulkCopyFlagsFinished']],})),actions({setSearch: (search: string) => ({ search }),@@ -214,6 +216,15 @@ export const projectsGridLogic = kea<projectsGridLogicType>([localStorage.removeItem(storageKey(getCurrentTeamId()))actions.loadFlagsPage({ offset: 0, search: values.search })},+ bulkCopyFlagsFinished: ({ result }) => {+ // A bulk copy changes which projects the copied flags exist in, so the cached sibling+ // data for those keys is stale — re-fetch the ones currently shown in the grid.+ const loadedKeys = new Set(values.flags.map((f) => f.key))+ const copiedKeys = (result?.copied ?? []).map((entry) => entry.key).filter((key) => loadedKeys.has(key))+ if (copiedKeys.length) {+ actions.enqueueSiblingFetches(copiedKeys)+ }+ },toggleFlagActive: async ({ flagKey, teamId, flagId, active }) => {const updatedFlag = await updateFlagActiveInProject({ teamId, flagId, active })if (updatedFlag) {diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 456f3d0f4185..f39cb9d0c54e 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -59,6 +59,14 @@ class CopyFlagsRequestSerializer(serializers.Serializer):class CopyFlagsResultSerializer(serializers.Serializer):project_id = serializers.IntegerField(required=False, help_text="Project ID (present on failure)")error_message = serializers.CharField(required=False, help_text="Error message (present on failure)")+ approval_pending = serializers.BooleanField(+ required=False,+ help_text="True when the copy was not applied because the target project's approval policy requires approval; a change request has been created and the copy will apply once approved",+ )+ change_request_id = serializers.CharField(+ required=False,+ help_text="ID of the pending change request created in the target project (present when approval_pending is true)",+ )class CopyFlagsSuccessItemSerializer(serializers.Serializer):@@ -67,6 +75,9 @@ class CopyFlagsSuccessItemSerializer(serializers.Serializer):name = serializers.CharField(help_text="Name of the feature flag")active = serializers.BooleanField(help_text="Whether the flag is active")team_id = serializers.IntegerField(help_text="Team ID the flag was copied to")+ updated_existing = serializers.BooleanField(+ help_text="True when a flag with the same key already existed in the target project and was overwritten with the copied configuration, false when a new flag was created"+ )flag_dependency_warnings = serializers.ListField(child=serializers.CharField(),required=False,@@ -332,6 +343,26 @@ class OrganizationFeatureFlagView()continue+ # Being able to see a team isn't the same as being able to write flags into it. Check+ # editor access against the specific flag when one already exists at this key (an+ # overwrite), or against the feature_flag resource type in general when this would be a+ # fresh copy (no object to check access against yet).+ existing_flag = FeatureFlag.objects.filter(key=feature_flag_key, team__project_id=target_project_id).first()+ target_user_access_control = UserAccessControl(request.user, target_team)+ target_has_access = (+ target_user_access_control.check_access_level_for_object(existing_flag, "editor")+ if existing_flag is not None+ else target_user_access_control.check_access_level_for_resource("feature_flag", required_level="editor")+ )+ if not target_has_access:+ failed_projects.append(+ {+ "project_id": target_project_id,+ "error_message": "You do not have permission to create or edit feature flags in this project.",+ }+ )+ continue+# get all linked cohorts, sorted by creation orderseen_cohorts_cache: dict[int, CohortOrEmpty] = {}sorted_cohort_ids = flag_to_copy.get_cohort_ids(@@ -456,7 +487,6 @@ class OrganizationFeatureFlagView("is_remote_configuration": flag_to_copy.is_remote_configuration,"has_encrypted_payloads": flag_to_copy.has_encrypted_payloads,}- existing_flag = FeatureFlag.objects.filter(key=feature_flag_key, team__project_id=target_project_id).first()context = {"request": request,@@ -500,11 +530,27 @@ class OrganizationFeatureFlagView(schedule_copy_error = str(e)result = feature_flag_serializer.data+ # FeatureFlagSerializer doesn't expose team_id, but callers need to know which+ # target each success item belongs to, and whether it overwrote an existing flag.+ result["team_id"] = saved_flag.team_id+ result["updated_existing"] = existing_flag is not Noneif schedule_copy_error:result["schedule_copy_warning"] = f"Flag copied but schedules failed: {schedule_copy_error}"if flag_dependency_warnings:result["flag_dependency_warnings"] = flag_dependency_warningssuccessful_projects.append(result)+ except ApprovalRequired as e:+ # The target project's approval policy gated this write: the copy hasn't been applied,+ # but a change request was already created and will apply it once approved. Report it+ # structurally so callers can distinguish "pending approval" from a hard failure.+ failed_entry = {+ "project_id": target_project_id,+ "error_message": e.message,+ "approval_pending": True,+ }+ if e.change_request is not None:+ failed_entry["change_request_id"] = str(e.change_request.id)+ failed_projects.append(failed_entry)except Exception as e:failed_projects.append({diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex c4a71f48daed..009bb63b0748 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -224,6 +224,57 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.12+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.13'''SELECT 1 AS "a"FROM "posthog_featureflag"@@ -234,7 +285,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.13+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.14'''SELECT COUNT(*) AS "__count"FROM "posthog_featureflag"@@ -249,7 +300,7 @@AND "posthog_featureflag"."team_id" = 99999)))'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.14+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.15'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -352,7 +403,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.15+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -394,7 +445,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -426,7 +477,7 @@AND "posthog_team"."project_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -528,7 +579,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -553,25 +604,6 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19- '''- SELECT "posthog_integration"."id",- "posthog_integration"."team_id",- "posthog_integration"."kind",- "posthog_integration"."integration_id",- "posthog_integration"."config",- "posthog_integration"."sensitive_config",- "posthog_integration"."repository_cache",- "posthog_integration"."repository_cache_updated_at",- "posthog_integration"."errors",- "posthog_integration"."created_at",- "posthog_integration"."created_by_id"- FROM "posthog_integration"- WHERE ("posthog_integration"."kind" = 'vercel'- AND "posthog_integration"."team_id" = 99999)- LIMIT 21- '''-# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.2'''SELECT "posthog_organization"."id",@@ -615,6 +647,25 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.20+ '''+ SELECT "posthog_integration"."id",+ "posthog_integration"."team_id",+ "posthog_integration"."kind",+ "posthog_integration"."integration_id",+ "posthog_integration"."config",+ "posthog_integration"."sensitive_config",+ "posthog_integration"."repository_cache",+ "posthog_integration"."repository_cache_updated_at",+ "posthog_integration"."errors",+ "posthog_integration"."created_at",+ "posthog_integration"."created_by_id"+ FROM "posthog_integration"+ WHERE ("posthog_integration"."kind" = 'vercel'+ AND "posthog_integration"."team_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -656,7 +707,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22'''SELECT "posthog_organizationintegration"."id","posthog_organizationintegration"."organization_id",@@ -673,7 +724,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -696,7 +747,7 @@AND "posthog_filesystem"."type" = 'dashboard')'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24'''SELECT "posthog_tag"."id","posthog_tag"."name",@@ -714,7 +765,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -816,7 +867,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26'''SELECT 1 AS "a"FROM "posthog_tag"@@ -824,7 +875,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27'''SELECT 1 AS "a"FROM "posthog_dashboard"@@ -832,7 +883,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28'''SELECT 1 AS "a"FROM "posthog_taggeditem"@@ -840,7 +891,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29'''SELECT 1 AS "_check"WHERE COALESCE((EXISTS@@ -852,12 +903,6 @@LIMIT 1)), true)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29- '''- SELECT 1 AS "_check"- WHERE COALESCE(true, true)- '''-# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3'''SELECT 1 AS "a"@@ -868,6 +913,12 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30+ '''+ SELECT 1 AS "_check"+ WHERE COALESCE(true, true)+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31'''SELECT "posthog_tag"."id","posthog_tag"."name",@@ -877,7 +928,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -979,7 +1030,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -1009,7 +1060,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.34'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -1032,7 +1083,7 @@AND "posthog_filesystem"."type" = 'dashboard')'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.34+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.35'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1133,7 +1184,7 @@WHERE "posthog_team"."primary_dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.35+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.36'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1234,7 +1285,7 @@WHERE "posthog_team"."primary_dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.36+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.37'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -1252,7 +1303,7 @@WHERE "posthog_taggeditem"."dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.37+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.38'''SELECT "posthog_tag"."id","posthog_tag"."name",@@ -1262,7 +1313,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.38+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.39'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -1280,16 +1331,6 @@WHERE "posthog_taggeditem"."dashboard_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.39- '''- SELECT "posthog_tag"."id",- "posthog_tag"."name",- "posthog_tag"."team_id"- FROM "posthog_tag"- WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid- LIMIT 21- '''-# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.4'''SELECT "posthog_featureflag"."id",@@ -1325,6 +1366,16 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.40+ '''+ SELECT "posthog_tag"."id",+ "posthog_tag"."name",+ "posthog_tag"."team_id"+ FROM "posthog_tag"+ WHERE "posthog_tag"."id" = '00000000000000000000000000000000'::uuid+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.41'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -1351,7 +1402,7 @@AND "posthog_dashboardtile"."dashboard_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.41+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.42'''SELECT "posthog_dashboardtile"."id","posthog_dashboardtile"."dashboard_id",@@ -1378,7 +1429,7 @@AND "posthog_dashboardtile"."dashboard_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.42+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.43'''SELECT "posthog_dashboarditem"."id","posthog_dashboarditem"."name",@@ -1414,7 +1465,7 @@AND "posthog_dashboarditem"."dashboard_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.43+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.44'''SELECT "posthog_dashboarditem"."id","posthog_dashboarditem"."name",@@ -1450,7 +1501,7 @@AND "posthog_dashboarditem"."dashboard_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.44+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.45'''SELECT "posthog_dashboarditem"."id","posthog_dashboarditem"."name",@@ -1487,7 +1538,7 @@AND "posthog_dashboardtile"."dashboard_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.45+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.46'''SELECT "posthog_dashboarditem"."id","posthog_dashboarditem"."name",@@ -1524,7 +1575,7 @@AND "posthog_dashboardtile"."dashboard_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.46+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.47'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -1549,7 +1600,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.47+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.48'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -1574,7 +1625,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.48+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.49'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -1606,31 +1657,6 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.49- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'feature_flag'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.5'''SELECT "posthog_team"."id",@@ -1734,6 +1760,31 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.50+ '''+ SELECT "posthog_filesystem"."team_id",+ "posthog_filesystem"."id",+ "posthog_filesystem"."path",+ "posthog_filesystem"."depth",+ "posthog_filesystem"."type",+ "posthog_filesystem"."ref",+ "posthog_filesystem"."href",+ "posthog_filesystem"."shortcut",+ "posthog_filesystem"."meta",+ "posthog_filesystem"."created_at",+ "posthog_filesystem"."created_by_id",+ "posthog_filesystem"."surface",+ "posthog_filesystem"."project_id"+ FROM "posthog_filesystem"+ WHERE (("posthog_filesystem"."surface" IS NULL+ OR "posthog_filesystem"."surface" = 'web')+ AND "posthog_filesystem"."ref" = '0001'+ AND "posthog_filesystem"."team_id" = 99999+ AND "posthog_filesystem"."type" = 'feature_flag'+ AND NOT ("posthog_filesystem"."shortcut"+ AND "posthog_filesystem"."shortcut" IS NOT NULL))+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.51'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -1756,7 +1807,7 @@AND "posthog_filesystemshortcut"."href" IS NOT NULL))'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.51+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.52'''SELECT "posthog_integration"."id","posthog_integration"."team_id",@@ -1775,7 +1826,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.52+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.53'''SELECT "posthog_organizationintegration"."id","posthog_organizationintegration"."organization_id",@@ -1792,7 +1843,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.53+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.54'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -1810,7 +1861,7 @@WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.54+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.55'''SELECT "posthog_taggeditem"."id","posthog_taggeditem"."tag_id",@@ -1828,7 +1879,7 @@WHERE "posthog_taggeditem"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.55+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.56'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -1873,7 +1924,7 @@WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.56+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.57'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -1918,7 +1969,7 @@WHERE "posthog_survey"."internal_response_sampling_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.57+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.58'''SELECT "ee_featureflagroleaccess"."id","ee_featureflagroleaccess"."feature_flag_id",@@ -1929,7 +1980,7 @@WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.58+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.59'''SELECT "ee_featureflagroleaccess"."id","ee_featureflagroleaccess"."feature_flag_id",@@ -1940,46 +1991,6 @@WHERE "ee_featureflagroleaccess"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.59- '''- SELECT "posthog_experiment"."id",- "posthog_experiment"."name",- "posthog_experiment"."description",- "posthog_experiment"."team_id",- "posthog_experiment"."filters",- "posthog_experiment"."parameters",- "posthog_experiment"."secondary_metrics",- "posthog_experiment"."created_by_id",- "posthog_experiment"."feature_flag_id",- "posthog_experiment"."exposure_cohort_id",- "posthog_experiment"."holdout_id",- "posthog_experiment"."start_date",- "posthog_experiment"."end_date",- "posthog_experiment"."created_at",- "posthog_experiment"."updated_at",- "posthog_experiment"."archived",- "posthog_experiment"."feature_flag_auto_archived",- "posthog_experiment"."deleted",- "posthog_experiment"."type",- "posthog_experiment"."variants",- "posthog_experiment"."exposure_criteria",- "posthog_experiment"."metrics",- "posthog_experiment"."metrics_secondary",- "posthog_experiment"."primary_metrics_ordered_uuids",- "posthog_experiment"."secondary_metrics_ordered_uuids",- "posthog_experiment"."stats_config",- "posthog_experiment"."scheduling_config",- "posthog_experiment"."running_time_calculation",- "posthog_experiment"."excluded_variants",- "posthog_experiment"."only_count_matured_users",- "posthog_experiment"."status",- "posthog_experiment"."conclusion",- "posthog_experiment"."conclusion_comment"- FROM "posthog_experiment"- WHERE ("posthog_experiment"."feature_flag_id" = 99999- AND NOT "posthog_experiment"."deleted")- '''-# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.6'''SELECT "posthog_user"."id",@@ -2067,6 +2078,46 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.61+ '''+ SELECT "posthog_experiment"."id",+ "posthog_experiment"."name",+ "posthog_experiment"."description",+ "posthog_experiment"."team_id",+ "posthog_experiment"."filters",+ "posthog_experiment"."parameters",+ "posthog_experiment"."secondary_metrics",+ "posthog_experiment"."created_by_id",+ "posthog_experiment"."feature_flag_id",+ "posthog_experiment"."exposure_cohort_id",+ "posthog_experiment"."holdout_id",+ "posthog_experiment"."start_date",+ "posthog_experiment"."end_date",+ "posthog_experiment"."created_at",+ "posthog_experiment"."updated_at",+ "posthog_experiment"."archived",+ "posthog_experiment"."feature_flag_auto_archived",+ "posthog_experiment"."deleted",+ "posthog_experiment"."type",+ "posthog_experiment"."variants",+ "posthog_experiment"."exposure_criteria",+ "posthog_experiment"."metrics",+ "posthog_experiment"."metrics_secondary",+ "posthog_experiment"."primary_metrics_ordered_uuids",+ "posthog_experiment"."secondary_metrics_ordered_uuids",+ "posthog_experiment"."stats_config",+ "posthog_experiment"."scheduling_config",+ "posthog_experiment"."running_time_calculation",+ "posthog_experiment"."excluded_variants",+ "posthog_experiment"."only_count_matured_users",+ "posthog_experiment"."status",+ "posthog_experiment"."conclusion",+ "posthog_experiment"."conclusion_comment"+ FROM "posthog_experiment"+ WHERE ("posthog_experiment"."feature_flag_id" = 99999+ AND NOT "posthog_experiment"."deleted")+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.62'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -2111,7 +2162,7 @@WHERE "posthog_survey"."linked_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.62+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.63'''SELECT "posthog_earlyaccessfeature"."id","posthog_earlyaccessfeature"."team_id",@@ -2126,7 +2177,7 @@WHERE "posthog_earlyaccessfeature"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.63+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.64'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -2177,7 +2228,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.64+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.65'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -2206,7 +2257,7 @@AND "posthog_featureflagdashboards"."feature_flag_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.65+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.66'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -2257,7 +2308,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.66+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.67'''SELECT 1 AS "a"FROM "posthog_team"@@ -2266,7 +2317,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.67+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.68'''SELECT "posthog_featureflagevaluationcontext"."id","posthog_featureflagevaluationcontext"."feature_flag_id",@@ -2282,7 +2333,7 @@WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.68+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.69'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 673254984c72..36200f9710e9 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -466,6 +466,8 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"evaluation_runtime": "all","bucketing_identifier": "distinct_id","is_used_in_replay_settings": False,+ "team_id": target_project.id,+ "updated_existing": False,}flag_response = response.json()["success"][0]@@ -561,6 +563,8 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"evaluation_runtime": "all","bucketing_identifier": "distinct_id","is_used_in_replay_settings": False,+ "team_id": target_project.id,+ "updated_existing": True,}flag_response = response.json()["success"][0]@@ -701,6 +705,9 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):"evaluation_runtime": "all","bucketing_identifier": "distinct_id","is_used_in_replay_settings": False,+ "team_id": target_project.id,+ # A soft-deleted flag doesn't count as existing: the copy replaces it with a fresh flag+ "updated_existing": False,}flag_response = response.json()["success"][0]@@ -875,6 +882,107 @@ class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):self.assertEqual(response.json()["failed"][0]["project_id"], self.team_2.id)self.assertEqual(response.json()["failed"][0]["error_message"], "Project not found.")+ def test_copy_feature_flag_to_team_without_flag_editor_access_fails(self):+ from posthog.constants import AvailableFeature++ from ee.models.rbac.access_control import AccessControl++ self.organization.available_product_features = [+ {+ "name": AvailableFeature.ACCESS_CONTROL,+ "key": AvailableFeature.ACCESS_CONTROL,+ }+ ]+ self.organization.save()++ # team_2 stays visible, but feature_flag write access there is restricted+ AccessControl.objects.create(+ team=self.team_2,+ resource="feature_flag",+ resource_id=None,+ organization_member=None,+ role=None,+ access_level="viewer",+ )++ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"+ data = {+ "feature_flag_key": self.feature_flag_key,+ "from_project": self.team_1.id,+ "target_project_ids": [self.team_2.id],+ }+ response = self.client.post(url, data)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(response.json()["success"]), 0)+ self.assertEqual(+ response.json()["failed"],+ [+ {+ "project_id": self.team_2.id,+ "error_message": "You do not have permission to create or edit feature flags in this project.",+ }+ ],+ )+ self.assertFalse(FeatureFlag.objects.filter(team=self.team_2, key=self.feature_flag_key).exists())++ def test_copy_feature_flag_approval_required_reports_pending_and_continues(self):+ from products.approvals.backend.exceptions import ApprovalRequired+ from products.approvals.backend.models import ChangeRequest+ from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer++ team_3 = Team.objects.create(organization=self.organization)+ change_request = ChangeRequest.objects.create(+ action_key="feature_flag.update",+ team=self.team_2,+ organization=self.organization,+ resource_type="feature_flag",+ intent={},+ intent_display={},+ policy_snapshot={},+ expires_at=timezone.now() + timedelta(days=7),+ created_by=self.user,+ )++ real_save = FeatureFlagSerializer.save++ def gated_save(serializer_self, **kwargs):+ if kwargs.get("team_id") == self.team_2.id:+ raise ApprovalRequired(+ change_request=change_request,+ message="Approval required",+ required_approvers={},+ )+ return real_save(serializer_self, **kwargs)++ url = f"/api/organizations/{self.organization.id}/feature_flags/copy_flags"+ data = {+ "feature_flag_key": self.feature_flag_key,+ "from_project": self.team_1.id,+ "target_project_ids": [self.team_2.id, team_3.id],+ }+ with patch.object(FeatureFlagSerializer, "save", autospec=True, side_effect=gated_save):+ response = self.client.post(url, data)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ result = response.json()+ self.assertEqual(+ result["failed"],+ [+ {+ "project_id": self.team_2.id,+ "error_message": "Approval required",+ "approval_pending": True,+ "change_request_id": str(change_request.id),+ }+ ],+ )+ # The gated target must not block the remaining targets from copying.+ self.assertEqual(len(result["success"]), 1)+ self.assertEqual(result["success"][0]["key"], self.feature_flag_key)+ self.assertTrue(FeatureFlag.objects.filter(team=team_3, key=self.feature_flag_key).exists())+ self.assertFalse(FeatureFlag.objects.filter(team=self.team_2, key=self.feature_flag_key).exists())+def test_copy_feature_flag_cohort_nonexistent_in_destination(self):cohorts = {}creation_order = []diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex f824bf5a40df..cacf58351814 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -238,6 +238,8 @@ export interface CopyFlagsSuccessItemApi {active: boolean/** Team ID the flag was copied to */team_id: number+ /** True when a flag with the same key already existed in the target project and was overwritten with the copied configuration, false when a new flag was created */+ updated_existing: boolean/** Warnings for flag dependencies that were dropped because no matching active flag exists in the target project */flag_dependency_warnings?: string[]/** Warning emitted when the flag was copied but its scheduled changes failed to copy */@@ -249,6 +251,10 @@ export interface CopyFlagsResultApi {project_id?: number/** Error message (present on failure) */error_message?: string+ /** True when the copy was not applied because the target project's approval policy requires approval; a change request has been created and the copy will apply once approved */+ approval_pending?: boolean+ /** ID of the pending change request created in the target project (present when approval_pending is true) */+ change_request_id?: string}export interface CopyFlagsResponseApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex be63a6be71ad..bdb947eacb08 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14465,6 +14465,8 @@ export namespace Schemas {active: boolean;/** Team ID the flag was copied to */team_id: number;+ /** True when a flag with the same key already existed in the target project and was overwritten with the copied configuration, false when a new flag was created */+ updated_existing: boolean;/** Warnings for flag dependencies that were dropped because no matching active flag exists in the target project */flag_dependency_warnings?: string[];/** Warning emitted when the flag was copied but its scheduled changes failed to copy */@@ -14476,6 +14478,10 @@ export namespace Schemas {project_id?: number;/** Error message (present on failure) */error_message?: string;+ /** True when the copy was not applied because the target project's approval policy requires approval; a change request has been created and the copy will apply once approved */+ approval_pending?: boolean;+ /** ID of the pending change request created in the target project (present when approval_pending is true) */+ change_request_id?: string;}export interface CopyFlagsResponse {