Skip to content

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

feat(flags): create a new flag in additional projects in one step (#94319)

James Gill1480d2dcb720
diff --git a/SPIKE-NOTES.md b/SPIKE-NOTES.md
new file mode 100644
index 000000000000..6395ec1a5ec1
--- /dev/null
+++ b/SPIKE-NOTES.md
@@ -0,0 +1,63 @@
+# Spike notes: create a flag in additional projects at creation time
+
+Frontend-only spike.
+The new-flag form gets an "Also create in these projects" multi-select; after the normal create, the client calls the org-level `copy_flags` endpoint with the chosen targets.
+
+## What the UX feels like
+
+- The picker sits in the main settings card under the Enabled switch, marked optional.
+ It only renders during creation and only when the user can access more than one project, so the common single-project case is untouched.
+- One decision at create time replaces the create-then-copy round trip through the Projects tab.
+ That is the point of the feature and it holds up: the flow reads as "create here, and also there".
+- Double-submission through the copy phase is blocked, but not by a button spinner: `featureFlagLoading` makes `FeatureFlag.tsx` swap the whole form for a skeleton while the save and copies run.
+ A button-level loading state would need a dedicated save loader key (today `loadFeatureFlag` and `saveFeatureFlag` share one), which changes what every flag save looks like - a follow-up PR, not spike scope.
+ With many targets the skeleton just sits there with no per-project progress.
+- Outcomes are toasts: success lists the projects the flag landed in; approval-pending targets and hard failures come out as separate clauses of a warning toast.
+ For 2-3 targets a toast is enough. For more, the `BulkCopyFlagsModal` results view (per-project list, overwrite markers, warnings) is the better shape.
+- Verified in the local app (dev stack pointed at the spike commit, extra projects seeded) plus jest and code reading.
+ Setup note: the master checkout's database had drifted 52 migrations behind and 500'd every page until `manage.py migrate` ran - unrelated to this change.
+
+## Rough edges found
+
+1. **Copy semantics, not create semantics.**
+ `copy_flags` overwrites an existing flag with the same key in a target project (`update_existing_target` defaults to true).
+ The spike now surfaces this: the picker's info text warns about it, and the toast reports overwrites in their own clause at warning level (`updated_existing` from the response).
+ Still, an overwrite after the fact is not consent: before shipping, either pre-check colliding keys via `api.organizationFeatureFlags.get` and mark those options, or give the backend a create-only mode (see below).
+2. **The copy is client-side and non-atomic.**
+ The create returns, then the browser issues the copy.
+ Closing the tab in between leaves the flag in one project only - the exact failure this feature exists to prevent, just with a smaller window.
+ There is also no retry affordance: a failed copy leaves only a toast, and the user has to find the Projects tab and copy manually.
+3. **Toast ordering.** The copy-outcome toast fires before "Feature flag saved" because the copy runs inside the save loader. Cosmetic.
+4. **Target cap.** The picker caps selection at 50 (`BULK_COPY_MAX_TARGET_PROJECTS`, mirroring the backend's `max_length`), so an over-limit request can no longer be submitted.
+5. **Targets are not permission-filtered.**
+ The picker lists every team in the org; per-target RBAC is enforced by the backend and surfaces as a failed entry.
+ Correct, but pre-filtering (or a disabled reason) would be kinder.
+6. **Teams vs projects.**
+ The picker filters `team.id !== currentProjectId`, the same convention `FeatureFlagProjects` and `BulkCopyFlagsModal` use.
+ With environments, sibling teams of the current project would appear as targets - a pre-existing ambiguity in all three surfaces, not introduced here.
+7. **Telemetry** (resolved): the flow now emits `feature flag created in additional projects` with target and outcome counts, following the sibling copy surfaces.
+8. **Experiment sidebar create path** (`saveSidebarExperimentFeatureFlag`) intentionally not covered, per the brief.
+
+## What should change before shipping for real
+
+- **Customers expect edits to carry over.**
+ The CS follow-up on the originating Slack thread asked whether a config change after creation applies to the other projects.
+ It does not: each copy is an independent flag, and pushing a change means a manual re-copy that overwrites the target.
+ This is the strongest signal yet that the real product answer is linked flags or environments, not one-shot copy.
+- **Move the operation server-side.**
+ The create endpoint should accept `additional_project_ids` (or an org-level create should exist) and return per-project results in one response.
+ That removes the client-side window in (2), makes approval routing consistent, and gives one place to enforce create-only semantics.
+ The PR reviewer independently suggested the same shape and approved shipping the client version first.
+ The same change closes the `copy_flags` evaluation-contexts gap the review bot found: running the flag serializer per target carries `evaluation_contexts` and applies the target's `require_evaluation_contexts` rule.
+- **Backend need discovered: a create-only mode on `copy_flags`** (e.g. `fail_if_exists: true`), so "also create in" can never overwrite.
+ Today the frontend cannot distinguish "created" from "overwrote" until the response comes back (`updated_existing`).
+- Replace the outcome toast with a results dialog (reuse the `BulkCopyFlagsModal` result section) once targets can exceed 2-3.
+- Decide whether the copy should inherit `_create_in_folder` and the product-intent reporting per target project.
+
+## Implementation notes
+
+- State lives in `featureFlagLogic`: `alsoCreateInProjects` reducer + `alsoCreateInProjectOptions` selector; reset on `saveFeatureFlagSuccess`.
+- The copy runs inside the `saveFeatureFlag` loader creation branch and never throws (the flag already exists, so a copy failure must not fail the save).
+- Result handling reuses `aggregateCopyResponse` / `errorMessageFrom` from `flagSelectionLogic` (exported, no behavior change there).
+- Uses the generated `featureFlagsCopyFlagsCreate` client (already imported in `featureFlagLogic`) rather than the legacy `api.organizationFeatureFlags.copy` wrapper.
+- Jest coverage in `featureFlagLogic.test.ts` under "creating a flag in additional projects": copy params (asserted before the loader resolves), no-copy-without-targets, copy-request failure keeping the save successful, overwrite reporting, dependency warnings, and partial failure / approval-pending surfacing.
diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsx
index d2c5ad68afd8..bac61a59c8c4 100644
--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsx
@@ -416,4 +416,38 @@ describe('LemonInputSelect', () => {
const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1]
expect(lastCall[0]).toContain('[email protected]')
})
+
+ it.each([
+ {
+ name: 'adds nothing when the limit is reached',
+ keys: '{ArrowDown}{ArrowDown}{Enter}',
+ expectedSelections: [],
+ },
+ {
+ name: 'still removes a selected value when the limit is reached',
+ keys: '{Enter}',
+ expectedSelections: [['apricot']],
+ },
+ ])('multiple-select mode: pressing Enter $name', async ({ keys, expectedSelections }) => {
+ const onChange = jest.fn()
+
+ const { container } = render(
+ <LemonInputSelect<string>
+ mode="multiple"
+ options={[
+ { key: 'apple', label: 'Apple' },
+ { key: 'apricot', label: 'Apricot' },
+ { key: 'zucchini', label: 'Zucchini' },
+ ]}
+ value={['apple', 'apricot']}
+ onChange={onChange}
+ limit={2}
+ />
+ )
+
+ await openDropdown(container)
+ await userEvent.keyboard(keys)
+
+ expect(onChange.mock.calls.map((call) => call[0])).toEqual(expectedSelections)
+ })
})
diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
index 12ec9f59d2b4..016cf449f17d 100644
--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
@@ -465,6 +465,11 @@ export function LemonInputSelect<T = string>({
onChange?.([actualTypedValue])
return
}
+ // Option rows disable themselves at the limit, but Enter and blur add values without
+ // going through a row, so the cap has to hold here as well.
+ if (currentValues.length >= limit && !currentValues.includes(actualTypedValue)) {
+ return
+ }
if (mode === 'multiple' && inputValue) {
setFrozenOptions(visibleOptions.filter((o) => !o.__isInput))
}
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 35375728c7ca..c072280e224c 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1544,6 +1544,19 @@ export interface eventUsageLogicActions {
reportFeatureFlagCopySuccess: () => {
value: true
}
+ reportFeatureFlagCreatedInAdditionalProjects: (
+ targetCount: number,
+ createdCount: number,
+ overwrittenCount: number,
+ pendingApprovalCount: number,
+ failedCount: number
+ ) => {
+ createdCount: number
+ failedCount: number
+ overwrittenCount: number
+ pendingApprovalCount: number
+ targetCount: number
+ }
reportFeatureFlagScheduleFailure: (error: any) => {
error: any
}
@@ -2942,6 +2955,13 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
projectCount,
failedCount,
}),
+ reportFeatureFlagCreatedInAdditionalProjects: (
+ targetCount: number,
+ createdCount: number,
+ overwrittenCount: number,
+ pendingApprovalCount: number,
+ failedCount: number
+ ) => ({ targetCount, createdCount, overwrittenCount, pendingApprovalCount, failedCount }),
reportFeatureFlagsBulkArchived: (archivedCount: number, pendingApprovalCount: number, failedCount: number) => ({
archivedCount,
pendingApprovalCount,
@@ -4262,6 +4282,21 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
failed_count: failedCount,
})
},
+ reportFeatureFlagCreatedInAdditionalProjects: ({
+ targetCount,
+ createdCount,
+ overwrittenCount,
+ pendingApprovalCount,
+ failedCount,
+ }) => {
+ posthog.capture('feature flag created in additional projects', {
+ target_count: targetCount,
+ created_count: createdCount,
+ overwritten_count: overwrittenCount,
+ pending_approval_count: pendingApprovalCount,
+ failed_count: failedCount,
+ })
+ },
reportFeatureFlagsBulkArchived: ({ archivedCount, pendingApprovalCount, failedCount }) => {
posthog.capture('feature flags bulk archived', {
archived_count: archivedCount,
diff --git a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx
index 00b9a13e95aa..933fea10dd45 100644
--- a/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx
+++ b/frontend/src/scenes/feature-flags/BulkCopyFlagsModal.tsx
@@ -15,7 +15,12 @@ import {
import { pluralize } from 'lib/utils/strings'
import { organizationLogic } from 'scenes/organizationLogic'
-import { BulkCopyFailure, flagSelectionLogic, getBulkCopyDisabledReason } from './flagSelectionLogic'
+import {
+ BulkCopyFailure,
+ flagSelectionLogic,
+ getBulkCopyDisabledReason,
+ projectSelectOptions,
+} from './flagSelectionLogic'
/** "Copy to projects" bulk action button shared by the flags overview table and the projects grid. */
export function BulkCopyToProjectsButton({
@@ -128,10 +133,7 @@ export function BulkCopyFlagsModal(): JSX.Element | null {
)
const teamNameById = useMemo(() => new Map(teams.map((team) => [team.id, team.name])), [teams])
const destinationOptions = useMemo(
- () =>
- teams
- .filter((team) => team.id !== bulkCopySourceProjectId)
- .map((team) => ({ key: String(team.id), label: team.name, value: team.id })),
+ () => projectSelectOptions(teams, bulkCopySourceProjectId),
[teams, bulkCopySourceProjectId]
)
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
index c77b8f76e7fb..e232cffac4c1 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
@@ -32,11 +32,13 @@ import {
IconTrash,
} from '@posthog/icons'
import {
+ LemonBanner,
LemonButton,
LemonCheckbox,
LemonCollapse,
LemonDivider,
LemonInput,
+ LemonInputSelect,
LemonLabel,
LemonSelect,
LemonSwitch,
@@ -62,6 +64,7 @@ import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { cohortsModel } from '~/models/cohortsModel'
import { tagsModel } from '~/models/tagsModel'
import { FeatureFlagBucketingIdentifier, FeatureFlagEvaluationRuntime, MultivariateFlagVariant } from '~/types'
@@ -70,10 +73,12 @@ import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'
import {
FeatureFlagLogicProps,
featureFlagLogic,
+ hasStaticCohortDependency,
slugifyFeatureFlagKey,
validateVariantRolloutSum,
} from './featureFlagLogic'
import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'
+import { BULK_COPY_MAX_TARGET_PROJECTS } from './flagSelectionLogic'
import { PercentageInput } from './PercentageInput'
interface SortableVariantHeaderProps {
@@ -166,6 +171,8 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {
advancedPanelOpen,
hasEncryptedPayloadBeenSaved,
hasEarlyAccessFeatures,
+ alsoCreateInProjects,
+ alsoCreateInProjectOptions,
} = useValues(featureFlagLogic)
const {
setMultivariateEnabled,
@@ -184,9 +191,11 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {
setPayloadExpanded,
setAdvancedExpanded,
resetEncryptedPayload,
+ setAlsoCreateInProjects,
} = useActions(featureFlagLogic)
const { tags: availableTags } = useValues(tagsModel)
const { isApprovalRequired } = useValues(approvalsGateLogic)
+ const { allCohorts } = useValues(cohortsModel)
const hasEvaluationContexts = useFeatureFlag('FLAG_EVALUATION_TAGS') // NB: the tag was named "flag-evaluation-tags" before we renamed the concept – i.e. this powers evaluation contexts even though the name implies tags
const isNewFeatureFlag = id === 'new' || id === undefined
const implementationRef = useRef<HTMLDivElement>(null)
@@ -517,6 +526,38 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {
)
}}
</LemonField>
+
+ {isNewFeatureFlag && alsoCreateInProjectOptions.length > 0 && (
+ <>
+ <LemonDivider />
+ <LemonField.Pure
+ label="Also create in these projects"
+ info="The flag is created in the current project, then copied to each selected project. If a project already has a flag with this key, that flag is overwritten. If a project requires approval for flag changes, a change request is created there instead."
+ showOptional
+ >
+ <LemonInputSelect<number>
+ mode="multiple"
+ value={alsoCreateInProjects}
+ onChange={setAlsoCreateInProjects}
+ options={alsoCreateInProjectOptions}
+ limit={BULK_COPY_MAX_TARGET_PROJECTS}
+ placeholder="Select projects"
+ data-attr="feature-flag-also-create-in-projects"
+ />
+ </LemonField.Pure>
+ {alsoCreateInProjects.length > 0 &&
+ hasStaticCohortDependency(featureFlag, allCohorts.results) && (
+ <LemonBanner
+ type="warning"
+ data-attr="feature-flag-also-create-in-projects-static-cohort-warning"
+ >
+ This flag targets a static cohort. Projects that don't have a cohort
+ with the same name get an empty copy of it, so that condition
+ matches nobody there until you add people to it.
+ </LemonBanner>
+ )}
+ </>
+ )}
</div>
{/* Advanced options - collapsed by default. Controlled rather than seeded,
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
index 9d43c3e45cc4..fb5e9ca8c35a 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
@@ -1,5 +1,6 @@
import {
MOCK_DEFAULT_BASIC_USER,
+ MOCK_DEFAULT_ORGANIZATION,
MOCK_DEFAULT_PROJECT,
MOCK_DEFAULT_TEAM,
MOCK_ORGANIZATION_ID,
@@ -15,6 +16,7 @@ import { dayjs } from 'lib/dayjs'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -1501,6 +1503,219 @@ describe('featureFlagLogic', () => {
})
})
+ describe('creating a flag in additional projects', () => {
+ const TARGET_A = MOCK_TEAM_ID + 1
+ const TARGET_B = MOCK_TEAM_ID + 2
+
+ let newLogic: ReturnType<typeof featureFlagLogic.build>
+ let copyRequests: Record<string, unknown>[]
+
+ function createAndCopyMocks(
+ copyResult: [number, CopyFlagsResponseApi | Record<string, unknown>]
+ ): Parameters<typeof useMocks>[0] {
+ return {
+ post: {
+ '/api/projects/:team_id/feature_flags/': () => [201, MOCK_FEATURE_FLAG],
+ '/api/organizations/:organization_id/feature_flags/copy_flags': async ({ request }) => {
+ copyRequests.push((await request.json()) as Record<string, unknown>)
+ return copyResult
+ },
+ },
+ }
+ }
+
+ function copiedFlagInProject(teamId: number): CopyFlagsResponseApi['success'][number] {
+ return {
+ id: teamId,
+ key: MOCK_FEATURE_FLAG.key,
+ name: MOCK_FEATURE_FLAG.name,
+ active: true,
+ team_id: teamId,
+ updated_existing: false,
+ }
+ }
+
+ beforeEach(() => {
+ copyRequests = []
+ eventUsageLogic.mount()
+ newLogic = featureFlagLogic({ id: 'new' })
+ newLogic.mount()
+ // Named teams so the toasts resolve real project names instead of the "Project N" fallback
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ teams: [
+ MOCK_DEFAULT_TEAM,
+ { ...MOCK_DEFAULT_TEAM, id: TARGET_A, name: 'Marketing' },
+ { ...MOCK_DEFAULT_TEAM, id: TARGET_B, name: 'Docs' },
+ ],
+ })
+ })
+
+ afterEach(() => {
+ newLogic.unmount()
+ eventUsageLogic.unmount()
+ })
+
+ it('copies the created flag to each selected project and reports where it landed', async () => {
+ useMocks(
+ createAndCopyMocks([
+ 200,
+ {
+ success: [copiedFlagInProject(TARGET_A), copiedFlagInProject(TARGET_B)],
+ failed: [],
+ },
+ ])
+ )
+
+ await expectLogic(newLogic, () => {
+ newLogic.actions.setAlsoCreateInProjects([TARGET_A, TARGET_B])
+ newLogic.actions.saveFeatureFlag({ ...NEW_FLAG, key: MOCK_FEATURE_FLAG.key })
+ }).toDispatchActions(['saveFeatureFlagSuccess'])
+
+ // Asserted at the point saveFeatureFlagSuccess dispatched, without draining listeners
+ // first: the copy must complete inside the saveFeatureFlag loader, or featureFlagLoading
+ // drops mid-copy and a second submit can fire a second create.
+ expect(copyRequests).toHaveLength(1)
+ expect(copyRequests[0]).toEqual({
+ feature_flag_key: MOCK_FEATURE_FLAG.key,
+ from_project: MOCK_TEAM_ID,
+ target_project_ids: [TARGET_A, TARGET_B],
+ })
+ expect(lemonToast.success).toHaveBeenCalledWith(
+ expect.stringContaining('Flag also created in Marketing and Docs')
+ )
+ // The picker resets so the next new-flag form starts empty
+ expect(newLogic.values.alsoCreateInProjects).toEqual([])
+
+ await expectLogic(newLogic).toFinishAllListeners()
+ })
+
+ it('makes no copy call when no additional projects are selected', async () => {
+ useMocks(createAndCopyMocks([200, { success: [], failed: [] }]))
+
+ await expectLogic(newLogic, () => {
+ newLogic.actions.saveFeatureFlag({ ...NEW_FLAG, key: MOCK_FEATURE_FLAG.key })
+ })
+ .toDispatchActions(['saveFeatureFlagSuccess'])
+ .toFinishAllListeners()
+
+ expect(copyRequests).toHaveLength(0)
+ })
+
+ it('keeps the save successful and reports an error when the copy request itself fails', async () => {
+ useMocks(createAndCopyMocks([500, { type: 'server_error', detail: 'Copy failed' }]))
+
+ await expectLogic(newLogic, () => {
+ newLogic.actions.setAlsoCreateInProjects([TARGET_A, TARGET_B])
+ newLogic.actions.saveFeatureFlag({ ...NEW_FLAG, key: MOCK_FEATURE_FLAG.key })
+ })
+ .toDispatchActions(['saveFeatureFlagSuccess'])
+ .toFinishAllListeners()
+
+ expect(lemonToast.error).toHaveBeenCalledWith(
+ expect.stringContaining('Copy to Marketing and Docs failed: Copy failed')
+ )
+ })
+
+ it('reports an overwritten same-key flag separately from created ones', async () => {
+ useMocks(
+ createAndCopyMocks([
+ 200,
+ {
+ success: [
+ { ...copiedFlagInProject(TARGET_A), updated_existing: true },
+ copiedFlagInProject(TARGET_B),
+ ],
+ failed: [],
+ },
+ ])
+ )
+
+ await expectLogic(newLogic, () => {
+ newLogic.actions.setAlsoCreateInProjects([TARGET_A, TARGET_B])
+ newLogic.actions.saveFeatureFlag({ ...NEW_FLAG, key: MOCK_FEATURE_FLAG.key })
+ })
+ .toDispatchActions(['saveFeatureFlagSuccess'])
+ .toFinishAllListeners()
+
+ expect(lemonToast.warning).toHaveBeenCalledWith(expect.stringContaining('Flag also created in Docs'))
+ expect(lemonToast.warning).toHaveBeenCalledWith(
+ expect.stringContaining('an existing flag with this key was overwritten in Marketing')
+ )
+ expect(capturesOf('feature flag created in additional projects')).toEqual([
+ [
+ 'feature flag created in additional projects',
+ {
+ target_count: 2,
+ created_count: 1,
+ overwritten_count: 1,
+ pending_approval_count: 0,
+ failed_count: 0,
+ },
+ ],
+ ])
+ })
+
+ it('surfaces dependency warnings from an otherwise successful copy', async () => {
+ useMocks(
+ createAndCopyMocks([
+ 200,
+ {
+ success: [
+ {
+ ...copiedFlagInProject(TARGET_A),
+ flag_dependency_warnings: ['Dependency "parent-flag" is missing in the target'],
+ },
+ ],
+ failed: [],
+ },
+ ])
+ )
+
+ await expectLogic(newLogic, () => {
+ newLogic.actions.setAlsoCreateInProjects([TARGET_A])
+ newLogic.actions.saveFeatureFlag({ ...NEW_FLAG, key: MOCK_FEATURE_FLAG.key })
+ })
+ .toDispatchActions(['saveFeatureFlagSuccess'])
+ .toFinishAllListeners()
+
+ expect(lemonToast.warning).toHaveBeenCalledWith(expect.stringContaining('parent-flag'))
+ })
+
+ it.each([
+ [
+ 'a failed project',
+ { project_id: TARGET_B, error_message: 'No access to this project', approval_pending: false },
+ 'copy to Docs failed: No access to this project',
+ ],
+ [
+ 'an approval-pending project',
+ { project_id: TARGET_B, error_message: 'Approval required', approval_pending: true },
+ 'copy to Docs needs approval (a change request was created)',
+ ],
+ ])('surfaces %s distinctly instead of swallowing it', async (_desc, failedEntry, expectedFragment) => {
+ useMocks(
+ createAndCopyMocks([
+ 200,
+ {
+ success: [copiedFlagInProject(TARGET_A)],
+ failed: [failedEntry],
+ },
+ ])
+ )
+
+ await expectLogic(newLogic, () => {
+ newLogic.actions.setAlsoCreateInProjects([TARGET_A, TARGET_B])
+ newLogic.actions.saveFeatureFlag({ ...NEW_FLAG, key: MOCK_FEATURE_FLAG.key })
+ })
+ .toDispatchActions(['saveFeatureFlagSuccess'])
+ .toFinishAllListeners()
+
+ expect(lemonToast.warning).toHaveBeenCalledWith(expect.stringContaining(expectedFragment))
+ expect(lemonToast.warning).toHaveBeenCalledWith(expect.stringContaining('Flag also created in Marketing'))
+ })
+ })
+
describe('copying flags', () => {
it('sends dependency copy options and resets them after success', async () => {
const targetProjectId = MOCK_DEFAULT_PROJECT.id + 1
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index ff8a1fa22d23..9941ef1c5120 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -40,7 +40,7 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { stringifyWithBigInts } from 'lib/utils/json'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
-import { slugify } from 'lib/utils/strings'
+import { capitalizeFirstLetter, humanList, slugify } from 'lib/utils/strings'
import { experimentLogic } from 'scenes/experiments/experimentLogic'
import { FeatureFlagsTab, featureFlagsLogic, isFeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'
import { projectLogic } from 'scenes/projectLogic'
@@ -112,6 +112,7 @@ import type {
MinimalEarlyAccessFeatureType,
OrganizationType,
SidePanelTab,
+ TeamBasicType,
TeamPublicType,
TeamType,
UserBasicType,
@@ -127,6 +128,12 @@ import { uniformAggregationGroupTypeIndex } from './defaultReleaseConditionsUtil
import { FeatureFlagArchivedSource, reportFeatureFlagArchived } from './featureFlagArchiveDialog'
import { checkFeatureFlagConfirmation } from './featureFlagConfirmationLogic'
import type { FlagIntent } from './featureFlagIntentWarningLogic'
+import {
+ ProjectSelectOption,
+ aggregateCopyResponse,
+ errorMessageFrom,
+ projectSelectOptions,
+} from './flagSelectionLogic'
import {
ScheduleOccurrence,
expandScheduleOccurrences,
@@ -523,6 +530,89 @@ function isOnFeatureFlagPage(id: FeatureFlagLogicProps['id']): boolean {
return removeProjectIdIfPresent(router.values.location.pathname) === urls.featureFlag(id)
}
+/**
+ * Copies a just-created flag into the extra projects picked on the creation form.
+ * Reports the per-project outcome itself and never throws: the flag already exists,
+ * so a copy failure must not fail the save.
+ */
+async function copyNewFlagToAdditionalProjects(
+ organizationId: string,
+ flagKey: string,
+ fromProjectId: number,
+ targetProjectIds: number[],
+ teams: TeamBasicType[] | null | undefined
+): Promise<void> {
+ const projectName = (projectId: number | null): string =>
+ (projectId !== null && teams?.find((team) => team.id === projectId)?.name) || `Project ${projectId}`
+
+ let aggregated: ReturnType<typeof aggregateCopyResponse>
+ try {
+ const response = await featureFlagsCopyFlagsCreate(organizationId, {
+ feature_flag_key: flagKey,
+ from_project: fromProjectId,
+ target_project_ids: targetProjectIds,
+ })
+ aggregated = aggregateCopyResponse(flagKey, targetProjectIds, response)
+ } catch (error) {
+ aggregated = {
+ copied: null,
+ failed: targetProjectIds.map((projectId) => ({
+ key: flagKey,
+ projectId,
+ errorMessage: errorMessageFrom(error),
+ })),
+ warnings: [],
+ }
+ }
+
+ const pendingApproval = aggregated.failed.filter((failure) => failure.approvalPending)
+ const hardFailures = aggregated.failed.filter((failure) => !failure.approvalPending)
+ // The endpoint overwrites a same-key flag in a target project instead of creating one,
+ // so overwrites get their own clause and downgrade the toast to a warning.
+ const overwritten = aggregated.copied?.updatedProjectIds ?? []
+ const created = aggregated.copied?.projectIds.filter((projectId) => !overwritten.includes(projectId)) ?? []
+ // Group hard failures that share a message (e.g. one rejected request expanded per
+ // target), so the toast says it once instead of once per project.
+ const failuresByMessage = new Map<string, string[]>()
+ for (const failure of hardFailures) {
+ const names = failuresByMessage.get(failure.errorMessage) ?? []
+ names.push(projectName(failure.projectId))
+ failuresByMessage.set(failure.errorMessage, names)
+ }
+ const parts = [
+ created.length > 0 ? `flag also created in ${humanList(created.map(projectName))}` : null,
+ overwritten.length > 0
+ ? `an existing flag with this key was overwritten in ${humanList(overwritten.map(projectName))}`
+ : null,
+ pendingApproval.length > 0
+ ? `copy to ${humanList(pendingApproval.map((failure) => projectName(failure.projectId)))} needs approval (a change request was created)`
+ : null,
+ ...Array.from(
+ failuresByMessage,
+ ([errorMessage, names]) => `copy to ${humanList(names)} failed: ${errorMessage}`
+ ),
+ ].filter((part): part is string => part !== null)
+
+ eventUsageLogic.actions.reportFeatureFlagCreatedInAdditionalProjects(
+ targetProjectIds.length,
+ created.length,
+ overwritten.length,
+ pendingApproval.length,
+ hardFailures.length
+ )
+
+ const level =
+ aggregated.failed.length === 0 && overwritten.length === 0
+ ? 'success'
+ : aggregated.copied || pendingApproval.length > 0
+ ? 'warning'
+ : 'error'
+ lemonToast[level](capitalizeFirstLetter(parts.join(', ')))
+ if (aggregated.warnings.length > 0) {
+ lemonToast.warning(aggregated.warnings.join(' '))
+ }
+}
+
// KLUDGE: Payloads are returned in a <variant-key>: <payload> mapping.
// This doesn't work for forms because variant-keys can be updated too which would invalidate the dictionary entry.
// If a multivariant flag is returned, the payload dictionary will be transformed to be <variant-key-index>: <payload>
@@ -765,6 +855,8 @@ export interface featureFlagLogicValues {
advancedExpanded: boolean | null
advancedPanelOpen: boolean
aggregationTargetName: string
+ alsoCreateInProjectOptions: ProjectSelectOption[]
+ alsoCreateInProjects: number[]
availableTabs: FeatureFlagsTab[]
breadcrumbs: Breadcrumb[]
canCreateEarlyAccessFeature: boolean
@@ -1420,6 +1512,9 @@ export interface featureFlagLogicActions {
setAdvancedExpanded: (expanded: boolean) => {
expanded: boolean
}
+ setAlsoCreateInProjects: (projectIds: number[]) => {
+ projectIds: number[]
+ }
setBucketingIdentifier: (bucketingIdentifier: FeatureFlagBucketingIdentifier | null) => {
bucketingIdentifier: FeatureFlagBucketingIdentifier | null
}
@@ -1964,6 +2059,10 @@ export interface featureFlagLogicMeta {
featureFlagKey: (featureFlag: FeatureFlagType) => string
canCreateEarlyAccessFeature: (featureFlag: FeatureFlagType, variants: MultivariateFlagVariant[]) => boolean
hasSurveys: (featureFlag: FeatureFlagType) => boolean | null
+ alsoCreateInProjectOptions: (
+ currentOrganization: OrganizationType | null,
+ currentProjectId: number | null
+ ) => ProjectSelectOption[]
hasEncryptedPayloadBeenSaved: (featureFlag: FeatureFlagType, props: any) => boolean | undefined
hasExperiment: (featureFlag: FeatureFlagType) => boolean | null
showStaleFlagBanner: (featureFlag: FeatureFlagType, flagStatus: FeatureFlagStatusResponseApi | null) => boolean
@@ -2085,6 +2184,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
distributeVariantsEqually: true,
enrichUsageDashboard: true,
setCopyDestinationProject: (id: number | null) => ({ id }),
+ setAlsoCreateInProjects: (projectIds: number[]) => ({ projectIds }),
setCopySchedule: (copySchedule: boolean) => ({ copySchedule }),
setDisableCopiedFlag: (disableCopiedFlag: boolean) => ({ disableCopiedFlag }),
setCopyDependencies: (copyDependencies: boolean) => ({ copyDependencies }),
@@ -2462,6 +2562,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
setCopyDestinationProject: (_, { id }) => id,
},
],
+ alsoCreateInProjects: [
+ [] as number[],
+ {
+ setAlsoCreateInProjects: (_, { projectIds }) => projectIds,
+ saveFeatureFlagSuccess: () => [],
+ },
+ ],
projectFlagsToggling: [
{} as Record<string, boolean>,
{
@@ -2985,6 +3092,22 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
product_type: ProductKey.FEATURE_FLAGS,
intent_context: ProductIntentContext.FEATURE_FLAG_CREATED,
})
+ // Copy into the extra projects inside this loader so featureFlagLoading
+ // stays true until the copies resolve. FeatureFlag.tsx swaps the form for
+ // a skeleton while that flag is set, which blocks a second submit through
+ // the copy phase.
+ const alsoCreateIn = values.alsoCreateInProjects.filter(
+ (projectId) => projectId !== values.currentProjectId
+ )
+ if (alsoCreateIn.length > 0 && values.currentOrganizationId && values.currentProjectId) {
+ await copyNewFlagToAdditionalProjects(
+ String(values.currentOrganizationId),
+ savedFlag.key,
+ values.currentProjectId,
+ alsoCreateIn,
+ values.currentOrganization?.teams
+ )
+ }
} else {
// Updating an existing flag - include version in preparedFlag
const cachedFlag = featureFlagsLogic
@@ -4509,6 +4632,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
return featureFlag?.surveys && featureFlag.surveys.length > 0
},
],
+ // Projects the creation form can also create the flag in. Empty when the user
+ // only has access to one project, which hides the picker.
+ alsoCreateInProjectOptions: [
+ (s) => [s.currentOrganization, s.currentProjectId],
+ (currentOrganization: OrganizationType | null, currentProjectId: number | null): ProjectSelectOption[] =>
+ projectSelectOptions(currentOrganization?.teams, currentProjectId),
+ ],
hasEncryptedPayloadBeenSaved: [
(s) => [s.featureFlag, s.props],
(featureFlag: FeatureFlagType, props) => {
diff --git a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
index a77a5afeb4de..68a8c4cd96e5 100644
--- a/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
+++ b/frontend/src/scenes/feature-flags/flagSelectionLogic.ts
@@ -15,7 +15,7 @@ import { projectLogic } from 'scenes/projectLogic'
import { featureFlagsPartialUpdate } from 'products/feature_flags/frontend/generated/api'
import type { CopyFlagsResponseApi } from 'products/feature_flags/frontend/generated/api.schemas'
-import type { OrganizationType } from '../../types'
+import type { OrganizationType, TeamBasicType } from '../../types'
import { featureFlagsLogic } from './featureFlagsLogic'
export type FlagRolloutState = 'fully_rolled_out' | 'not_rolled_out' | 'partial'
@@ -139,7 +139,7 @@ function summarizeBulkArchive(
return { level: 'error', message: 'No flags were archived' }
}
-function errorMessageFrom(error: unknown): string {
+export function errorMessageFrom(error: unknown): string {
if (typeof error === 'string') {
return error
}
@@ -150,7 +150,7 @@ function errorMessageFrom(error: unknown): string {
}
/** Turns one key's copy response into the copied/failed/warning entries the bulk-copy listener accumulates. */
-function aggregateCopyResponse(
+export function aggregateCopyResponse(
key: string,
targetProjectIds: number[],
response: CopyFlagsResponseApi
@@ -203,6 +203,23 @@ export function splitCopiedByOverwrite(copied: BulkCopyResult['copied']): {
return { newCopies, overwrites }
}
+export interface ProjectSelectOption {
+ key: string
+ label: string
+ value: number
+}
+
+/** Copy-destination options for a project picker: the org's teams minus one excluded project, sorted by name. */
+export function projectSelectOptions(
+ teams: TeamBasicType[] | null | undefined,
+ excludeProjectId: number | null
+): ProjectSelectOption[] {
+ return (teams ?? [])
+ .filter((team) => team.id !== excludeProjectId)
+ .map((team) => ({ key: String(team.id), label: team.name, value: team.id }))
+ .sort((a, b) => a.label.localeCompare(b.label))
+}
+
export function getBulkCopyDisabledReason(selectedCount: number, extraReason?: string | null): string | undefined {
if (extraReason) {
return extraReason