: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(experiments): clear the new experiment form when abandoned (#86948)
Juraj Majerik32ce39d5621d
diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.tsindex 6d9b1ae88323..12d50d999e47 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts@@ -19,7 +19,7 @@ import type { Experiment } from '~/types'import { DEFAULT_MODEL, DEFAULT_PROVIDER } from 'products/replay_vision/frontend/replay_scanners/types'import { NEW_EXPERIMENT } from '../constants'-import { createExperimentLogic, DRAFT_STORAGE_KEY } from './createExperimentLogic'+import { createExperimentLogic } from './createExperimentLogic'jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({lemonToast: {@@ -511,102 +511,28 @@ describe('createExperimentLogic', () => {logic.unmount()})- it('draft from sessionStorage is loaded when creating a new experiment', async () => {- const storedDraft: Experiment = {- ...NEW_EXPERIMENT,- name: 'Stored Draft',- feature_flag_key: 'stored-draft',- }-- sessionStorage.setItem(- DRAFT_STORAGE_KEY,- JSON.stringify({ experiment: storedDraft, timestamp: Date.now() })- )-- const newLogic = createExperimentLogic()- newLogic.mount()-- await expectLogic(newLogic).toMatchValues({- experiment: partial({- id: 'new',- name: 'Stored Draft',- feature_flag_key: 'stored-draft',- }),- })-- newLogic.unmount()- })-- it('form state does not leak between new experiment sessions', async () => {+ it('abandoning the form and coming back starts fresh', async () => {const firstNew = createExperimentLogic()firstNew.mount()firstNew.actions.setExperimentValue('name', 'First Attempt')firstNew.actions.setExperimentValue('feature_flag_key', 'first-attempt')-- await expectLogic(firstNew).toMatchValues({- experiment: partial({ name: 'First Attempt', feature_flag_key: 'first-attempt' }),- })-- firstNew.unmount()-- sessionStorage.clear()-- const secondNew = createExperimentLogic()- secondNew.mount()-- await expectLogic(secondNew).toMatchValues({- experiment: partial({ id: 'new', name: '', feature_flag_key: '' }),- })-- secondNew.unmount()- })-- it('unmount/remount with no draft starts fresh', async () => {- const freshLogic = createExperimentLogic()- freshLogic.mount()-- freshLogic.actions.setExperiment({- ...NEW_EXPERIMENT,- id: 123,- name: 'Saved Experiment',- description: 'Already saved',- })-- freshLogic.unmount()-- const remounted = createExperimentLogic()- remounted.mount()-- await expectLogic(remounted).toMatchValues({- experiment: partial({ id: 'new', name: '', description: '' }),- })-- remounted.unmount()- })-- it('draft written on unmount is read back by a freshly-built logic', async () => {- const firstNew = createExperimentLogic()- firstNew.mount()-- firstNew.actions.setExperimentValue('name', 'Work In Progress')- firstNew.actions.setExperimentValue('feature_flag_key', 'wip-flag')firstNew.actions.setCreateReplayVisionScanner(true)await expectLogic(firstNew).toMatchValues({- experiment: partial({ name: 'Work In Progress', feature_flag_key: 'wip-flag' }),+ experiment: partial({ name: 'First Attempt', feature_flag_key: 'first-attempt' }),createReplayVisionScanner: true,})- // Navigating away without saving writes the draft to sessionStorage+ // User navigates away — no savefirstNew.unmount()const secondNew = createExperimentLogic()secondNew.mount()await expectLogic(secondNew).toMatchValues({- experiment: partial({ id: 'new', name: 'Work In Progress', feature_flag_key: 'wip-flag' }),- createReplayVisionScanner: true,+ experiment: partial({ id: 'new', name: '', feature_flag_key: '' }),+ createReplayVisionScanner: false,})secondNew.unmount()@@ -656,57 +582,6 @@ describe('createExperimentLogic', () => {secondLogic.unmount()})-- it('navigating away without saving preserves draft for next visit', async () => {- const firstLogic = createExperimentLogic()- firstLogic.mount()-- firstLogic.actions.setExperimentValue('name', 'Work In Progress')- firstLogic.actions.setExperimentValue('feature_flag_key', 'wip-flag')-- await expectLogic(firstLogic).toMatchValues({- experiment: partial({ name: 'Work In Progress', feature_flag_key: 'wip-flag' }),- })-- // User navigates away — no cancel, no save- firstLogic.unmount()-- // User comes back to /experiments/new- const secondLogic = createExperimentLogic()- secondLogic.mount()-- await expectLogic(secondLogic).toMatchValues({- experiment: partial({ id: 'new', name: 'Work In Progress', feature_flag_key: 'wip-flag' }),- })-- secondLogic.unmount()- })-- it('cancel clears draft so re-entering create mode starts fresh', async () => {- const firstLogic = createExperimentLogic()- firstLogic.mount()-- firstLogic.actions.setExperimentValue('name', 'Will Cancel')- firstLogic.actions.setExperimentValue('feature_flag_key', 'will-cancel')-- await expectLogic(firstLogic).toMatchValues({- experiment: partial({ name: 'Will Cancel', feature_flag_key: 'will-cancel' }),- })-- // User clicks cancel — clears draft then navigates away- firstLogic.actions.cancelForm()- firstLogic.unmount()-- // User navigates back to /experiments/new- const secondLogic = createExperimentLogic()- secondLogic.mount()-- await expectLogic(secondLogic).toMatchValues({- experiment: partial({ id: 'new', name: '', feature_flag_key: '' }),- })-- secondLogic.unmount()- })})describe('feature flag key auto-generation', () => {diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.tsindex 7a47ee8c30bf..d95ae4b490a0 100644--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.ts@@ -48,8 +48,6 @@ import type { FeatureFlagKeyValidation } from './variantsPanelLogic'import { variantsPanelLogic } from './variantsPanelLogic'import { validateVariants } from './variantsPanelValidation'-const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000-function experimentFromApi(experiment: ExperimentApi): Experiment {return experiment as unknown as Experiment}@@ -67,59 +65,6 @@ function experimentWritePayloadForApi(} as unknown as Parameters<typeof experimentsCreate>[1]}-// Scope the draft key per project so a draft started in one project can't prefill or be submitted in another within the same browser session.-export const DRAFT_STORAGE_KEY = `experiment-draft-${window.POSTHOG_APP_CONTEXT?.current_team?.id ?? 'unknown'}`--type ExperimentDraft = {- experiment: Experiment- createReplayVisionScanner?: boolean- timestamp: number-}--type RestoredDraft = {- experiment: Experiment- createReplayVisionScanner: boolean-}--const readDraftFromStorage = (): RestoredDraft | null => {- if (typeof sessionStorage === 'undefined') {- return null- }- const raw = sessionStorage.getItem(DRAFT_STORAGE_KEY)- if (!raw) {- return null- }- try {- const parsed = JSON.parse(raw) as ExperimentDraft | Experiment- if (parsed && typeof parsed === 'object' && 'experiment' in parsed && 'timestamp' in parsed) {- const { experiment, createReplayVisionScanner, timestamp } = parsed as ExperimentDraft- if (Date.now() - timestamp > DRAFT_TTL_MS) {- sessionStorage.removeItem(DRAFT_STORAGE_KEY)- return null- }- return { experiment, createReplayVisionScanner: createReplayVisionScanner ?? false }- }- return { experiment: parsed as Experiment, createReplayVisionScanner: false }- } catch {- return null- }-}--const writeDraftToStorage = (experiment: Experiment, createReplayVisionScanner: boolean): void => {- if (typeof sessionStorage === 'undefined') {- return- }- const draft: ExperimentDraft = { experiment, createReplayVisionScanner, timestamp: Date.now() }- sessionStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draft))-}--const clearDraftStorage = (): void => {- if (typeof sessionStorage === 'undefined') {- return- }- sessionStorage.removeItem(DRAFT_STORAGE_KEY)-}-export interface CreateExperimentLogicProps {}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -134,7 +79,6 @@ export interface createExperimentLogicValues {}experimentErrors: Record<string, string>experimentValidationErrors: string | undefined- formCanceled: booleanisExperimentSubmitting: booleanmode: 'create' | 'link'sharedMetrics: {@@ -167,9 +111,6 @@ export interface createExperimentLogicActions {} // featureFlagsLogicaddProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogicaddProductIntentForCrossSell: (properties: ProductCrossSellProperties) => ProductCrossSellProperties // teamLogic- cancelForm: () => {- value: true- }createExperimentSuccess: () => {value: true}@@ -290,7 +231,6 @@ export const createExperimentLogic = kea<createExperimentLogicType>([setExperiment: (experiment: Experiment) => ({ experiment }),setExperimentValue: (name: string, value: any) => ({ name, value }),resetExperiment: true,- cancelForm: true,setExposureCriteria: (criteria: ExperimentExposureCriteria) => ({ criteria }),setCreateReplayVisionScanner: (enabled: boolean) => ({ enabled }),setFeatureFlagConfig: (config: {@@ -381,12 +321,6 @@ export const createExperimentLogic = kea<createExperimentLogicType>([resetExperiment: () => ({}),},],- formCanceled: [- false,- {- cancelForm: () => true,- },- ],})),selectors(() => ({canSubmitExperiment: [@@ -456,31 +390,10 @@ export const createExperimentLogic = kea<createExperimentLogicType>([} catch (error) {console.error('Error parsing metric from URL', error)lemonToast.error('Error parsing metric from URL')- // Continue to draft fallback}-- const draft = readDraftFromStorage()- if (draft) {- actions.setExperiment(draft.experiment)- actions.setCreateReplayVisionScanner(draft.createReplayVisionScanner)- }- },- beforeUnmount: () => {- if (values.formCanceled || values.experiment.id !== 'new') {- return- }- // Use cases covered:- // - navigating away from the form without saving- writeDraftToStorage(values.experiment, values.createReplayVisionScanner)},})),listeners(({ values, actions }) => ({- cancelForm: () => {- if (values.experiment.id !== 'new') {- return- }- clearDraftStorage()- },setExperiment: () => {},setExperimentValue: () => {},validateField: ({ field }) => {@@ -662,7 +575,6 @@ export const createExperimentLogic = kea<createExperimentLogicType>([// Don't reset - we just set the fresh data aboveactions.saveExperimentSuccess()- clearDraftStorage()const sceneLogicInstance = experimentSceneLogic.findMounted()if (sceneLogicInstance) {diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsxindex 50a8a7727f41..f671796066f7 100644--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx@@ -592,37 +592,6 @@ describe('experimentWizardLogic', () => {})})- it('feature flag key is re-validated on remount', async () => {- // Set up: trigger a duplicate-key validation error- const vpLogic = variantsPanelLogic({ experiment: { ...NEW_EXPERIMENT }, disabled: false })- createLogic.actions.setExperimentValue('feature_flag_key', 'existing-flag')- vpLogic.actions.validateFeatureFlagKeySuccess({- valid: false,- error: 'A feature flag with this key already exists.',- key: 'existing-flag',- })-- await expectLogic(logic).toMatchValues({- featureFlagKeyValidation: partial({- valid: false,- error: 'A feature flag with this key already exists.',- }),- })-- // Unmount and remount- logic.unmount()- vpLogic.unmount()- createLogic.unmount()-- createLogic = createExperimentLogic()- createLogic.mount()- logic = experimentWizardLogic()- logic.mount()-- // afterMount should re-validate since feature_flag_key is set- await expectLogic(logic).toDispatchActions(['validateFeatureFlagKey'])- })-it('saveExperiment marks all steps as departed, revealing all errors', async () => {// Experiment has empty name and key — errors hidden until departureexpect(logic.values.stepValidationErrors.about).toEqual([])diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.tsindex 63f7339226ff..06028406416b 100644--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.ts@@ -478,13 +478,6 @@ export const experimentWizardLogic = kea<experimentWizardLogicType>([afterMount: () => {actions.reportExperimentWizardStarted(values.showGuide)actions.loadFeatureFlagsForAutocomplete()- // Re-validate the feature flag key if one is already set.- // variantsPanelLogic unmounts when leaving the form, so validation- // state is lost and needs to be re-checked on remount.- const key = values.experiment?.feature_flag_key- if (key) {- actions.validateFeatureFlagKey(key)- }},})),])