: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
fix(feature-flags): preserve in-progress edits when navigation is cancelled (#58658)
praneya00288341fe063a5e
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 3cd40fd9df7a..055770d45291 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -1,8 +1,10 @@import { MOCK_DEFAULT_PROJECT } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'import { dayjs } from 'lib/dayjs'+import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -531,6 +533,84 @@ describe('featureFlagLogic', () => {})})+ describe('urlToAction preserves in-progress edits', () => {+ // Regression for https://github.com/PostHog/posthog/issues/58656 — when the user+ // dismisses the beforeUnload prompt, urlToAction must not silently reload the+ // flag and wipe their in-progress edits. The guard must sit *above* the+ // editFeatureFlag dispatch, because its listener also calls loadFeatureFlag()+ // whenever editing === true.++ it('preserves an in-progress edit on a PUSH navigation when the form is dirty', async () => {+ await expectLogic(logic, () => {+ logic.actions.setFeatureFlagValue('name', 'Edited but not saved')+ }).toMatchValues({ hasUnsavedChanges: true, isFormDirty: true })++ await expectLogic(logic, () => {+ router.actions.push(urls.featureFlag(1))+ })+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['editFeatureFlag'])++ expect(logic.values.featureFlag.name).toBe('Edited but not saved')+ expect(logic.values.hasUnsavedChanges).toBe(true)+ })++ it('preserves an in-progress edit on a PUSH to the same URL with ?edit=true', async () => {+ // Realistic visibilitychange / re-push path: the user is already in edit mode,+ // so the URL carries `?edit=true`. Without the early-return above editFeatureFlag,+ // its listener (`if (editing) loadFeatureFlag()`) would still wipe the form.+ await expectLogic(logic, () => {+ logic.actions.setFeatureFlagValue('name', 'Edited with edit=true in url')+ }).toMatchValues({ hasUnsavedChanges: true, isFormDirty: true })++ await expectLogic(logic, () => {+ router.actions.push(`${urls.featureFlag(1)}?edit=true`)+ })+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['editFeatureFlag'])++ expect(logic.values.featureFlag.name).toBe('Edited with edit=true in url')+ expect(logic.values.hasUnsavedChanges).toBe(true)+ })++ it.each([+ ['sourceId=42', `${urls.featureFlag('new')}?sourceId=42`],+ ['type=multivariate', `${urls.featureFlag('new')}?type=multivariate`],+ ['template=experiment', `${urls.featureFlag('new')}?template=experiment`],+ ['intent=remote-config', `${urls.featureFlag('new')}?intent=remote-config`],+ ])('skips the new-flag template re-load on a dirty PUSH carrying %s', async (_label, targetUrl) => {+ // Pin that the dirty guard also short-circuits the special new-flag+ // re-load branches (sourceId / type / template / intent) inside `urlToAction`.+ // Park the router at a non-matching path first so the `new`-keyed logic's+ // afterMount doesn't see those query params at mount time and prefetch.+ router.actions.push('/')+ const newLogic = featureFlagLogic({ id: 'new' })+ newLogic.mount()+ await expectLogic(newLogic).toFinishAllListeners()++ await expectLogic(newLogic, () => {+ newLogic.actions.setFeatureFlagValue('name', 'Draft new flag')+ }).toMatchValues({ isFormDirty: true })++ await expectLogic(newLogic, () => {+ router.actions.push(targetUrl)+ })+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(['editFeatureFlag'])++ expect(newLogic.values.featureFlag.name).toBe('Draft new flag')+ newLogic.unmount()+ })++ it('still reloads the flag on a PUSH navigation when the form is clean', async () => {+ await expectLogic(logic).toMatchValues({ hasUnsavedChanges: false })++ await expectLogic(logic, () => {+ router.actions.push(urls.featureFlag(1))+ }).toDispatchActions(['loadFeatureFlag'])+ })+ })+describe('experiment loading', () => {it('loads experiment data when feature flag has an experiment linked', async () => {const flagWithExperiment = {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 2f8e766d87cb..047c568ac37a 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -2275,6 +2275,13 @@ export const featureFlagLogic = kea<featureFlagLogicType>([return !objectsEqual(currentCleaned, originalFeatureFlag)},],+ isFormDirty: [+ (s) => [s.originalFeatureFlag, s.hasUnsavedChanges, s.featureFlagChanged],+ (originalFeatureFlag, hasUnsavedChanges, featureFlagChanged): boolean =>+ // Existing flags compare against server state; new flags fall back to the+ // form-defaults check from kea-forms (NEW_FLAG would otherwise always read dirty).+ originalFeatureFlag ? hasUnsavedChanges : featureFlagChanged,+ ],multivariateEnabled: [(s) => [s.featureFlag], (featureFlag) => !!featureFlag?.filters.multivariate],flagType: [(s) => [s.featureFlag],@@ -2607,6 +2614,16 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}),urlToAction(({ actions, props, values }) => ({[urls.featureFlag(props.id ?? 'new')]: (_, searchParams, ___, { method, initial }) => {+ // Don't disturb in-progress edits when a same-pathname PUSH slips through+ // (e.g. the beforeUnload prompt was shown and cancelled, but the route still+ // reaches this handler). This must run before `editFeatureFlag` is dispatched,+ // because its listener calls `loadFeatureFlag()` whenever `editing === true` —+ // which would wipe the form on any re-push carrying `?edit=true`.+ // The `initial` mount must still run so first-load setup happens.+ if (method === 'PUSH' && values.isFormDirty) {+ return+ }+// Set editing state on initial mount or PUSH navigationif (method === 'PUSH' || initial) {actions.editFeatureFlag(searchParams.edit === true || searchParams.edit === 'true')@@ -2653,16 +2670,12 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},})),+ // TODO(#58936): this block is missing the scene-tab-cache guard that+ // `actionEditLogic.tsx` (L305-332) uses, so the prompt can fire twice on tab+ // switches. Fix requires making this scene tab-aware (`/making-scenes-tab-aware`).beforeUnload((logic) => ({enabled: (newLocation?: CombinedLocation) => {- // For existing flags, compare against server state to avoid false positives.- // featureFlagChanged (from kea-forms) compares against form defaults (NEW_FLAG),- // which is always true for loaded flags.- const isDirty = logic.values.originalFeatureFlag- ? logic.values.hasUnsavedChanges- : logic.values.featureFlagChanged-- if (!isDirty) {+ if (!logic.values.isFormDirty) {return false}