: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): keep dialogs open when an experiment save fails (#113853)
Andersa2c27d38ebc4
diff --git a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsx b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsxindex 0c701c33d3de..462a207e5968 100644--- a/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsx+++ b/frontend/src/lib/lemon-ui/LemonCalendar/LemonCalendarSelect.tsx@@ -89,6 +89,8 @@ export interface LemonCalendarSelectProps {use24HourFormat?: boolean/** Extra "Apply" variants shown in a dropdown next to the Apply button. Each receives the selected date. */applyActions?: { label: string; onClick: (date: dayjs.Dayjs) => void }[]+ /** For a caller that saves on Apply: shows Apply as loading and disables Cancel, dates and times while it saves. */+ loading?: boolean}export function LemonCalendarSelect({@@ -103,6 +105,7 @@ export function LemonCalendarSelect({onToggleTime,use24HourFormat = false,applyActions,+ loading,}: LemonCalendarSelectProps): JSX.Element {const calendarRef = useRef<HTMLDivElement | null>(null)const [selectValue, setSelectValue] = useState<dayjs.Dayjs | null>(value ? value.startOf(granularity) : null)@@ -110,6 +113,7 @@ export function LemonCalendarSelect({// Evaluate "now" as the timezone's wall clock (naive local Dayjs) so it's comparable to picked dates.const now = selectionPeriodTimezone ? dayjsNowInTimezone(selectionPeriodTimezone) : dayjs()const today = now.startOf('day')+ const savingReason = loading ? 'Saving in progress' : undefinedconst scrollToTime = (date: dayjs.Dayjs, skipAnimation: boolean): void => {const calendarEl = calendarRef.current@@ -179,7 +183,7 @@ export function LemonCalendarSelect({}}- return { disabledReason, selected: date.isSame(selectValue, 'd') }+ return { disabledReason: savingReason ?? disabledReason, selected: date.isSame(selectValue, 'd') }}}getTimeState={(props) => {const selected = selectValue@@ -199,7 +203,7 @@ export function LemonCalendarSelect({return {active: selected === String(props.value),- disabledReason,+ disabledReason: savingReason ?? disabledReason,onClick: () => {if (selected != props.value) {onTimeClick(props)@@ -226,19 +230,25 @@ export function LemonCalendarSelect({)}<div className="flex deprecated-space-x-2">{onClose && (- <LemonButton type="secondary" onClick={onClose} data-attr="lemon-calendar-select-cancel">+ <LemonButton+ type="secondary"+ onClick={onClose}+ disabledReason={savingReason}+ data-attr="lemon-calendar-select-cancel"+ >Cancel</LemonButton>)}<LemonButtontype="primary"disabled={!selectValue}+ loading={loading}onClick={() => selectValue && onChange && onChange(selectValue)}data-attr="lemon-calendar-select-apply"sideAction={applyActions?.length? {- disabled: !selectValue,+ disabled: !selectValue || loading,'aria-label': 'More apply options',dropdown: {placement: 'bottom-end',diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex c7be903f551d..2e9d0b052568 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -963,6 +963,39 @@ describe('experimentLogic', () => {expect(logic.values.experiment.description).toEqual('stale write')})+ it.each([+ {+ kind: 'an approval request',+ error: {+ status: 409,+ data: { change_request_id: 'cr-1', code: 'approval_required', detail: 'Approval required.' },+ },+ approvalToasts: [['cr-1', undefined, 'approval_required']],+ errorToasts: [],+ },+ {+ kind: 'another 409',+ error: {+ status: 409,+ detail: 'This experiment cannot change right now.',+ data: { detail: 'This experiment cannot change right now.' },+ },+ approvalToasts: [],+ errorToasts: [['This experiment cannot change right now.']],+ },+ ])('shows one message for $kind without a version conflict', async ({ error, approvalToasts, errorToasts }) => {+ api.update.mockRejectedValue(error)++ await expectLogic(logic, () => {+ logic.actions.updateExperiment({ description: 'rejected' })+ })+ .toDispatchActions(['updateExperimentFailure'])+ .toFinishAllListeners()++ expect(mockShowApprovalRequiredToast.mock.calls).toEqual(approvalToasts)+ expect(jest.mocked(lemonToast.error).mock.calls).toEqual(errorToasts)+ })+it('collapses identical concurrent dispatches into a single request', async () => {const snapshot = { ...experiment, version: 3 } as Experimentlogic.actions.setUnmodifiedExperiment(snapshot)diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 8ff4f409cc5e..1a1f5d5dfe82 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -142,6 +142,7 @@ import { sharedMetricsLogic } from './SharedMetrics/sharedMetricsLogic'import {type ExperimentSavedMetric,type ExperimentUpdatePayload,+ type ExperimentUpdateRequest,getDisplayOrderedIndices,getExperimentVariants,getOrderedMetricsWithResults,@@ -598,6 +599,7 @@ export interface experimentLogicValues {launchExperimentLoading: booleanminimumDetectableEffect: numbernotifyWhenResultsReady: boolean+ openDatePicker: 'end' | 'start' | nullorderedPrimaryMetricsWithResults: {displayIndex: numbererror: any@@ -734,6 +736,9 @@ export interface experimentLogicActions {id: number}} // featureFlagsLogic+ closeCupedModal: () => {+ value: true+ } // modalsLogiccloseFinishExperimentModal: () => {value: true} // modalsLogic@@ -749,6 +754,9 @@ export interface experimentLogicActions {closeSecondaryMetricModal: () => {value: true} // modalsLogic+ closeStatsEngineModal: () => {+ value: true+ } // modalsLogicopenPrimaryMetricModal: (uuid: string) => {uuid: string} // modalsLogic@@ -1131,6 +1139,9 @@ export interface experimentLogicActions {setNotifyWhenResultsReady: (notify: boolean) => {notify: boolean}+ setOpenDatePicker: (boundary: 'end' | 'start' | null) => {+ boundary: 'end' | 'start' | null+ }setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => {results: CachedNewExperimentQueryResponse[]}@@ -1222,7 +1233,7 @@ export interface experimentLogicActions {rolloutPercentage: number | undefinedvariants: MultivariateFlagVariant[]}- updateExperiment: (update: ExperimentUpdatePayload) => ExperimentUpdatePayload+ updateExperiment: (request: ExperimentUpdateRequest) => ExperimentUpdateRequestupdateExperimentFailure: (error: string,errorObject?: any@@ -1233,15 +1244,19 @@ export interface experimentLogicActions {updateExperimentMetrics: () => {value: true}- updateExperimentSettings: (update: Partial<Experiment>) => {+ updateExperimentSettings: (+ update: Partial<Experiment>,+ fromModal?: 'cuped' | 'statsMethod'+ ) => {+ fromModal: 'cuped' | 'statsMethod' | undefinedupdate: Partial<Experiment>}updateExperimentSuccess: (experimentUpdate: Experiment,- payload?: ExperimentUpdatePayload+ payload?: ExperimentUpdateRequest) => {experimentUpdate: Experiment- payload?: ExperimentUpdatePayload+ payload?: ExperimentUpdateRequest}updateExperimentVariantImages: (variantPreviewMediaIds: Record<string, string[]>) => {variantPreviewMediaIds: Record<string, string[]>@@ -1496,6 +1511,8 @@ export const experimentLogic = kea<experimentLogicType>(['closeResumeExperimentModal','closeFinishExperimentModal','openReleaseConditionsModal',+ 'closeCupedModal',+ 'closeStatsEngineModal',],],})),@@ -1547,9 +1564,13 @@ export const experimentLogic = kea<experimentLogicType>([}),updateExperimentMetrics: true,updateExposureCriteria: true,- updateExperimentSettings: (update: Partial<Experiment>) => ({ update }),+ updateExperimentSettings: (update: Partial<Experiment>, fromModal?: 'cuped' | 'statsMethod') => ({+ update,+ fromModal,+ }),changeExperimentStartDate: (startDate: string) => ({ startDate }),changeExperimentEndDate: (endDate: string) => ({ endDate }),+ setOpenDatePicker: (boundary: 'start' | 'end' | null) => ({ boundary }),launchExperiment: true,endExperiment: (openCleanupPr: boolean = false,@@ -2146,6 +2167,13 @@ export const experimentLogic = kea<experimentLogicType>([setIsCreatingExperimentDashboard: (_, { isCreating }) => isCreating,},],+ // In the logic, so that the date change listeners close the picker only after a successful save.+ openDatePicker: [+ null as 'start' | 'end' | null,+ {+ setOpenDatePicker: (_, { boundary }) => boundary,+ },+ ],launchExperimentLoading: [false,{@@ -2344,10 +2372,17 @@ export const experimentLogic = kea<experimentLogicType>([changeExperimentStartDate: async ({ startDate }) => {// Read the old date before the save, because the save stores the response in values.experiment.const oldStartDate = values.experiment?.start_date- actions.updateExperiment({ start_date: startDate, update_feature_flag_params: false })+ actions.updateExperiment({+ start_date: startDate,+ update_feature_flag_params: false,+ discardOnConflict: true,+ })if (!(await inflightUpdateSaved(cache))) {return}+ if (values.openDatePicker === 'start') {+ actions.setOpenDatePicker(null)+ }if (values.experiment) {posthog.capture('experiment start date changed', {...getEventPropertiesForExperiment(values.experiment),@@ -2360,10 +2395,13 @@ export const experimentLogic = kea<experimentLogicType>([changeExperimentEndDate: async ({ endDate }) => {// Read the old date before the save, because the save stores the response in values.experiment.const oldEndDate = values.experiment?.end_date- actions.updateExperiment({ end_date: endDate, update_feature_flag_params: false })+ actions.updateExperiment({ end_date: endDate, update_feature_flag_params: false, discardOnConflict: true })if (!(await inflightUpdateSaved(cache))) {return}+ if (values.openDatePicker === 'end') {+ actions.setOpenDatePicker(null)+ }if (values.experiment) {posthog.capture('experiment end date changed', {...getEventPropertiesForExperiment(values.experiment),@@ -2719,13 +2757,20 @@ export const experimentLogic = kea<experimentLogicType>([}actions.refreshExperimentResults(true, 'experiment_config_change')},- updateExperimentSettings: async ({ update }) => {+ updateExperimentSettings: async ({ update, fromModal }) => {// Settings like stats config, CUPED, and conversion-window handling change// how metrics and exposures are computed, so persist then re-query.- actions.updateExperiment({ ...update, update_feature_flag_params: false })+ // A save sends the whole stats_config object, also the keys that this user did not edit. After a conflict,+ // a kept copy would send those stale keys over the other edit, so the controls show the server's copy.+ actions.updateExperiment({ ...update, update_feature_flag_params: false, discardOnConflict: true })if (!(await inflightUpdateSaved(cache))) {return}+ if (fromModal === 'cuped') {+ actions.closeCupedModal()+ } else if (fromModal === 'statsMethod') {+ actions.closeStatsEngineModal()+ }// Unlaunched experiments have no results to recalculate, so don't promise a recalculation.lemonToast.success(values.isExperimentLaunched ? 'Settings saved. Recalculating results…' : 'Settings saved'@@ -3539,7 +3584,8 @@ export const experimentLogic = kea<experimentLogicType>([experimentUpdate: [null as Experiment | null,{- updateExperiment: async (update: ExperimentUpdatePayload) => {+ updateExperiment: async (request: ExperimentUpdateRequest) => {+ const { discardOnConflict, ...update } = request// The concurrency payload is built inside `send`, when the request actually// runs, so a queued update reads the version absorbed from its predecessor's// response instead of the one both dispatches started from.@@ -3569,7 +3615,7 @@ export const experimentLogic = kea<experimentLogicType>([// Reload so the next save carries the current version and base state,// but keep this update's rejected scalar fields in local state so the// user's edit isn't lost — they can review the fresh state and save again.- const preserved = conflictPreservedFields(update)+ const preserved = discardOnConflict ? {} : conflictPreservedFields(update)try {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentsRetrieve() from 'products/experiments/frontend/generated/api' instead.const fresh: Experiment = await api.get(@@ -3580,11 +3626,23 @@ export const experimentLogic = kea<experimentLogicType>([} catch {actions.loadExperiment()}+ } else if (isApprovalRequiredError(error)) {+ showApprovalRequiredToast(error.data.change_request_id, undefined, error.data.code)+ dispatchChangeRequestCreated({+ resourceType: 'feature_flag',+ resourceId: values.experiment.feature_flag?.id ?? '',+ })} else if (error?.status === undefined) {// The loader onFailure handler in initKea toasts only errors that carry an HTTP// status. Without this toast, a request that got no response (offline, blocked,// dropped) would fail with no feedback.lemonToast.error('Could not save the experiment. Check your connection and try again.')+ } else if (error.status === 409) {+ // The loader onFailure handler in initKea skips every 409, because the conflict and+ // approval flows above show their own message. This 409 is neither of them.+ lemonToast.error(+ error.detail || 'Could not save the experiment. Reload the page and try again.'+ )}throw error}@@ -3594,7 +3652,7 @@ export const experimentLogic = kea<experimentLogicType>([// carrying the same version, so the loser 409s even though its change saved.// A dispatch identical to the in-flight one (double click, twin listeners)// shares its request; a different one queues behind it.- const key = JSON.stringify(update)+ const key = JSON.stringify(request)const inflight: { key: string; promise: Promise<Experiment> } | undefined = cache.inflightUpdateif (inflight && inflight.key === key) {return inflight.promisediff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 36b2723c9ec0..63b16b133f87 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -1089,6 +1089,15 @@ export type ExperimentUpdatePayload = Omit<Partial<Experiment>, 'feature_flag'>original_experiment?: Record<string, any>}+export type ExperimentUpdateRequest = ExperimentUpdatePayload & {+ /**+ * After a 409 conflict, show the server's copy of the sent fields instead of keeping the rejected values for+ * review. A control that applies its value at once sets this. A kept value would look saved there, and the+ * next save would send it over the change that caused the conflict.+ */+ discardOnConflict?: boolean+}+/** The scalar fields experiment surfaces PATCH, sent as base values so the server can three-way* merge them per field: a stale write only conflicts when the same field changed on both sides. */const CONCURRENCY_SCALAR_BASE_FIELDS = [diff --git a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentDateRange.test.tsx b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentDateRange.test.tsxnew file mode 100644index 000000000000..5425dd95d05e--- /dev/null+++ b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentDateRange.test.tsx@@ -0,0 +1,150 @@+import '@testing-library/jest-dom'++import { act, cleanup, fireEvent, render, within } from '@testing-library/react'+import { BindLogic, Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { experimentLogic } from 'scenes/experiments/experimentLogic'++import { useMocks } from '~/mocks/jest'+import { getByDataAttr } from '~/test/byDataAttr'+import { initKeaTests } from '~/test/init'+import { Experiment } from '~/types'++import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'++import { ExperimentDateRange } from './ExperimentDateRange'++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn() },+}))++const EXPERIMENT_ID = 7+const VALIDATION_DETAIL = 'End date must be after start date'+const CONFLICT_DETAIL = 'This experiment was changed by someone else.'++const savedExperiment = {+ ...NEW_EXPERIMENT,+ id: EXPERIMENT_ID,+ version: 1,+ start_date: '2026-01-05T10:00:00Z',+ end_date: '2026-02-05T10:00:00Z',+} as Experiment+const serverExperiment = {+ ...savedExperiment,+ version: 2,+ start_date: '2026-01-03T10:00:00Z',+ end_date: '2026-02-20T10:00:00Z',+} as Experiment++const SHOWN_DATES = {+ start: { saved: 'Jan 5, 2026', picked: 'Jan 12, 2026', server: 'Jan 3, 2026' },+ end: { saved: 'Feb 5, 2026', picked: 'Feb 12, 2026', server: 'Feb 20, 2026' },+}++const echoSave = async ({ request }: { request: Request }): Promise<[number, Experiment]> => [+ 200,+ { ...savedExperiment, ...(await request.json()) },+]++const RESPONSES = {+ fails: () => [400, { type: 'validation_error', code: 'invalid_input', detail: VALIDATION_DETAIL, attr: null }],+ conflicts: () => [409, { type: 'validation_error', code: 'conflict', detail: CONFLICT_DETAIL, current_version: 2 }],+ succeeds: echoSave,+}++describe('ExperimentDateRange', () => {+ let logic: ReturnType<typeof experimentLogic.build>++ afterEach(() => {+ cleanup()+ logic.unmount()+ })++ function pickDay(boundary: 'start' | 'end'): HTMLElement {+ initKeaTests()+ logic = experimentLogic({ experimentId: EXPERIMENT_ID })+ logic.mount()+ logic.actions.setUnmodifiedExperiment(savedExperiment)+ logic.actions.setExperiment(savedExperiment)++ const { container } = render(+ <Provider>+ <BindLogic logic={experimentLogic} props={{ experimentId: EXPERIMENT_ID }}>+ <ExperimentDateRange />+ </BindLogic>+ </Provider>+ )+ const trigger = getByDataAttr(container, `experiment-${boundary}-date`)++ fireEvent.click(trigger)+ expect(trigger).toHaveClass('LemonButton--active')+ const month = document.querySelector('.LemonCalendar__month') as HTMLElement+ fireEvent.click(within(month).getByText('12'))+ return trigger+ }++ it.each([+ { boundary: 'start', outcome: 'fails', open: true, shown: 'saved', toasts: [VALIDATION_DETAIL] },+ { boundary: 'end', outcome: 'fails', open: true, shown: 'saved', toasts: [VALIDATION_DETAIL] },+ { boundary: 'start', outcome: 'conflicts', open: true, shown: 'server', toasts: [CONFLICT_DETAIL] },+ { boundary: 'end', outcome: 'conflicts', open: true, shown: 'server', toasts: [CONFLICT_DETAIL] },+ { boundary: 'start', outcome: 'succeeds', open: false, shown: 'picked', toasts: [] },+ { boundary: 'end', outcome: 'succeeds', open: false, shown: 'picked', toasts: [] },+ ] as const)(+ 'when the save $outcome, the $boundary date picker is open: $open, and the page shows the $shown date',+ async ({ boundary, outcome, open, shown, toasts }) => {+ useMocks({+ get: { '/api/projects/:team/experiments/:id': serverExperiment },+ patch: { '/api/projects/:team/experiments/:id': RESPONSES[outcome] },+ })+ const trigger = pickDay(boundary)++ fireEvent.click(getByDataAttr(document.body, 'lemon-calendar-select-apply'))+ await act(() => expectLogic(logic).toFinishAllListeners())++ expect(trigger).toHaveTextContent(SHOWN_DATES[boundary][shown])+ expect(trigger.classList.contains('LemonButton--active')).toBe(open)+ expect(jest.mocked(lemonToast.error).mock.calls).toEqual(+ toasts.map((text) => [expect.stringContaining(text)])+ )+ }+ )++ it('applies a date once, locks the picker while the save runs, and leaves the other picker open', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture')+ let finishSave = (): void => {}+ const saveFinished = new Promise<void>((resolve) => {+ finishSave = resolve+ })+ useMocks({+ patch: {+ '/api/projects/:team/experiments/:id': async (request: { request: Request }) => {+ await saveFinished+ return echoSave(request)+ },+ },+ })+ const trigger = pickDay('start')++ fireEvent.click(getByDataAttr(document.body, 'lemon-calendar-select-apply'))+ fireEvent.click(getByDataAttr(document.body, 'lemon-calendar-select-apply'))+ fireEvent.click(getByDataAttr(document.body, 'lemon-calendar-select-cancel'))++ expect(getByDataAttr(document.body, 'lemon-calendar-select-apply')).toHaveClass('LemonButton--loading')+ expect(trigger).toHaveClass('LemonButton--active')+ const month = document.querySelector('.LemonCalendar__month') as HTMLElement+ expect(within(month).getByText('15').closest('button')).toHaveAttribute('aria-disabled', 'true')++ const endTrigger = getByDataAttr(document.body, 'experiment-end-date')+ fireEvent.click(endTrigger)+ finishSave()+ await act(() => expectLogic(logic).toFinishAllListeners())++ expect(trigger).not.toHaveClass('LemonButton--active')+ expect(endTrigger).toHaveClass('LemonButton--active')+ expect(captureSpy.mock.calls.filter(([event]) => event === 'experiment start date changed')).toHaveLength(1)+ })+})diff --git a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentDateRange.tsx b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentDateRange.tsxindex 980bc9dfca84..766a3ead0793 100644--- a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentDateRange.tsx+++ b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentDateRange.tsx@@ -1,24 +1,32 @@-import { useAsyncActions, useValues } from 'kea'-import { useState } from 'react'+import { useActions, useValues } from 'kea'import { IconArrowRight, IconCalendar } from '@posthog/icons'-import { LemonButton, Tooltip, lemonToast } from '@posthog/lemon-ui'+import { LemonButton, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { LemonCalendarSelect } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'import { Popover } from 'lib/lemon-ui/Popover'import { experimentLogic } from 'scenes/experiments/experimentLogic'-import { isExperimentConflictError } from 'scenes/experiments/utils'interface DateTriggerProps {date: string | null | undefinedboundary: 'start' | 'end'- onChange: (date: string) => Promise<unknown>+ onApply: (date: string) => void}-function DateTrigger({ date, boundary, onChange }: DateTriggerProps): JSX.Element {- const [isOpen, setIsOpen] = useState(false)+function DateTrigger({ date, boundary, onApply }: DateTriggerProps): JSX.Element {+ const { openDatePicker, experimentUpdateLoading } = useValues(experimentLogic)+ const { setOpenDatePicker } = useActions(experimentLogic)+ const isOpen = openDatePicker === boundary++ // A successful save closes the picker. If the picker could close while the save runs, that save would close a+ // picker that the user opened again.+ const close = (): void => {+ if (!experimentUpdateLoading) {+ setOpenDatePicker(null)+ }+ }const label = date ? dayjs(date).format('MMM D, YYYY') : boundary === 'end' ? 'Present' : 'No date'const disabledReason = !date@@ -31,22 +39,13 @@ function DateTrigger({ date, boundary, onChange }: DateTriggerProps): JSX.Elemen<Popoveractionablevisible={isOpen}- onClickOutside={() => setIsOpen(false)}+ onClickOutside={close}overlay={<LemonCalendarSelectvalue={date ? dayjs(date) : null}- onChange={async (value) => {- try {- await onChange(value.toISOString())- setIsOpen(false)- } catch (error: any) {- // A conflict already toasts and reloads inside updateExperiment; keep the picker open either way.- if (!isExperimentConflictError(error)) {- lemonToast.error(error?.detail || `Could not save the ${boundary} date. Try again.`)- }- }- }}- onClose={() => setIsOpen(false)}+ onChange={(value) => onApply(value.toISOString())}+ onClose={close}+ loading={experimentUpdateLoading}granularity="minute"selectionPeriod={boundary === 'start' ? 'past' : undefined}/>@@ -56,7 +55,7 @@ function DateTrigger({ date, boundary, onChange }: DateTriggerProps): JSX.Elementype="tertiary"size="xsmall"sideIcon={null}- onClick={() => setIsOpen(true)}+ onClick={() => setOpenDatePicker(boundary)}disabledReason={disabledReason}data-attr={`experiment-${boundary}-date`}>@@ -79,16 +78,16 @@ function DateTrigger({ date, boundary, onChange }: DateTriggerProps): JSX.Elemenexport function ExperimentDateRange(): JSX.Element {const { experiment } = useValues(experimentLogic)- const { changeExperimentStartDate, changeExperimentEndDate } = useAsyncActions(experimentLogic)+ const { changeExperimentStartDate, changeExperimentEndDate } = useActions(experimentLogic)return (<div className="flex items-center gap-0.5" data-attr="experiment-date-range"><Tooltip title="Duration"><IconCalendar className="text-secondary text-base shrink-0 mr-1" /></Tooltip>- <DateTrigger date={experiment.start_date} boundary="start" onChange={changeExperimentStartDate} />+ <DateTrigger date={experiment.start_date} boundary="start" onApply={changeExperimentStartDate} /><IconArrowRight className="text-tertiary shrink-0" />- <DateTrigger date={experiment.end_date} boundary="end" onChange={changeExperimentEndDate} />+ <DateTrigger date={experiment.end_date} boundary="end" onApply={changeExperimentEndDate} /></div>)}diff --git a/products/experiments/frontend/modals/CupedModal/CupedModal.tsx b/products/experiments/frontend/modals/CupedModal/CupedModal.tsxindex 8e0c9f66521e..bac541c9b602 100644--- a/products/experiments/frontend/modals/CupedModal/CupedModal.tsx+++ b/products/experiments/frontend/modals/CupedModal/CupedModal.tsx@@ -1,4 +1,4 @@-import { useActions, useAsyncActions, useValues } from 'kea'+import { useActions, useValues } from 'kea'import { LemonButton, LemonInput, LemonLabel, LemonModal, LemonSelect } from '@posthog/lemon-ui'@@ -11,11 +11,11 @@ import { DEFAULT_LOOKBACK_DAYS, MAX_LOOKBACK_DAYS, MIN_LOOKBACK_DAYS } from 'proexport function CupedModal(): JSX.Element {const { experiment, experimentUpdateLoading } = useValues(experimentLogic)- const { setExperiment, restoreUnmodifiedExperiment } = useActions(experimentLogic)- const { updateExperimentSettings } = useAsyncActions(experimentLogic)+ const { setExperiment, restoreUnmodifiedExperiment, updateExperimentSettings } = useActions(experimentLogic)const { experimentsConfig } = useValues(experimentsConfigLogic)const { closeCupedModal } = useActions(modalsLogic)const { isCupedModalOpen } = useValues(modalsLogic)+ const savingReason = experimentUpdateLoading ? 'Saving in progress' : undefinedconst selection = getCupedSelection(experiment.stats_config?.cuped)const teamDefaultEnabled = experimentsConfig?.default_cuped_enabled ?? false@@ -61,28 +61,24 @@ export function CupedModal(): JSX.Element {})}- const onSave = async (): Promise<void> => {- try {- await updateExperimentSettings({ stats_config: experiment.stats_config })- } catch {- // Keep the modal open so the user can retry- return- }- closeCupedModal()- }-return (<LemonModalmaxWidth={600}isOpen={isCupedModalOpen}onClose={onClose}+ // Cancel does not stop a running save. The save still applies, and its response replaces any new edit.+ closable={!experimentUpdateLoading}title="CUPED variance reduction"footer={<div className="flex items-center gap-2 justify-end">- <LemonButton type="secondary" onClick={onClose}>+ <LemonButton type="secondary" onClick={onClose} disabledReason={savingReason}>Cancel</LemonButton>- <LemonButton type="primary" loading={experimentUpdateLoading} onClick={() => void onSave()}>+ <LemonButton+ type="primary"+ loading={experimentUpdateLoading}+ onClick={() => updateExperimentSettings({ stats_config: experiment.stats_config }, 'cuped')}+ >Save</LemonButton></div>@@ -98,6 +94,7 @@ export function CupedModal(): JSX.Element {<LemonSelect<CupedSelection>value={selection}onChange={updateSelection}+ disabledReason={savingReason}options={[{value: 'default',@@ -116,6 +113,7 @@ export function CupedModal(): JSX.Element {min={MIN_LOOKBACK_DAYS}max={MAX_LOOKBACK_DAYS}value={lookbackDays}+ disabledReason={savingReason}onChange={(value) => {if (typeof value !== 'number' || !Number.isFinite(value)) {returndiff --git a/products/experiments/frontend/modals/StatsMethodModal/StatsMethodModal.tsx b/products/experiments/frontend/modals/StatsMethodModal/StatsMethodModal.tsxindex ccb78c5aad3b..8fa1d7d1bf24 100644--- a/products/experiments/frontend/modals/StatsMethodModal/StatsMethodModal.tsx+++ b/products/experiments/frontend/modals/StatsMethodModal/StatsMethodModal.tsx@@ -1,4 +1,4 @@-import { useActions, useAsyncActions, useValues } from 'kea'+import { useActions, useValues } from 'kea'import { LemonButton, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'import { LemonModal } from '@posthog/lemon-ui'@@ -21,11 +21,11 @@ import { CONFIDENCE_LEVEL_OPTIONS } from 'products/experiments/frontend/constantexport function StatsMethodModal(): JSX.Element {const { experiment, statsMethod, experimentUpdateLoading } = useValues(experimentLogic)- const { setExperiment, restoreUnmodifiedExperiment } = useActions(experimentLogic)- const { updateExperimentSettings } = useAsyncActions(experimentLogic)+ const { setExperiment, restoreUnmodifiedExperiment, updateExperimentSettings } = useActions(experimentLogic)const { closeStatsEngineModal } = useActions(modalsLogic)const { isStatsEngineModalOpen } = useValues(modalsLogic)const { experimentsConfig } = useValues(experimentsConfigLogic)+ const savingReason = experimentUpdateLoading ? 'Saving in progress' : undefinedconst onClose = (): void => {restoreUnmodifiedExperiment()@@ -118,24 +118,20 @@ export function StatsMethodModal(): JSX.Element {maxWidth={600}isOpen={isStatsEngineModalOpen}onClose={onClose}+ // Cancel does not stop a running save. The save still applies, and its response replaces any new edit.+ closable={!experimentUpdateLoading}title="Statistics configuration"footer={<div className="flex items-center gap-2 justify-end">- <LemonButton type="secondary" onClick={onClose}>+ <LemonButton type="secondary" onClick={onClose} disabledReason={savingReason}>Cancel</LemonButton><LemonButtontype="primary"loading={experimentUpdateLoading}- onClick={async () => {- try {- await updateExperimentSettings({ stats_config: experiment.stats_config })- } catch {- // Keep the modal open so the user can retry- return- }- closeStatsEngineModal()- }}+ onClick={() =>+ updateExperimentSettings({ stats_config: experiment.stats_config }, 'statsMethod')+ }>Save</LemonButton>@@ -145,6 +141,8 @@ export function StatsMethodModal(): JSX.Element {<div className="mb-4"><StatsMethodSelectorvalue={statsMethod}+ disabled={experimentUpdateLoading}+ disabledReason={savingReason}onChange={(newStatsMethod) => {setExperiment({stats_config: {@@ -160,6 +158,7 @@ export function StatsMethodModal(): JSX.Element {<LemonSelectvalue={currentConfidenceLevel}onChange={handleConfidenceLevelChange}+ disabledReason={savingReason}options={CONFIDENCE_LEVEL_OPTIONS}className="w-24"/>@@ -175,6 +174,7 @@ export function StatsMethodModal(): JSX.Element {<LemonSelect<SequentialSelection>value={sequentialSelection}onChange={updateSequentialSelection}+ disabledReason={savingReason}options={[{value: 'default',@@ -198,6 +198,7 @@ export function StatsMethodModal(): JSX.Element {min={1}max={MAX_SEQUENTIAL_TUNING_PARAMETER}value={sequentialTuningParameter}+ disabledReason={savingReason}onChange={(value) => {if (typeof value !== 'number' ||diff --git a/products/experiments/frontend/modals/statsConfigModals.test.tsx b/products/experiments/frontend/modals/statsConfigModals.test.tsxnew file mode 100644index 000000000000..2b08cd512e8a--- /dev/null+++ b/products/experiments/frontend/modals/statsConfigModals.test.tsx@@ -0,0 +1,154 @@+import '@testing-library/jest-dom'++import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { BindLogic, Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { experimentLogic } from 'scenes/experiments/experimentLogic'+import { modalsLogic } from 'scenes/experiments/modalsLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { Experiment, ExperimentStatsMethod } from '~/types'++import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'+import { CupedModal } from 'products/experiments/frontend/modals/CupedModal/CupedModal'+import { StatsMethodModal } from 'products/experiments/frontend/modals/StatsMethodModal/StatsMethodModal'++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn() },+}))++const EXPERIMENT_ID = 7+const savedExperiment = {+ ...NEW_EXPERIMENT,+ id: EXPERIMENT_ID,+ version: 1,+ stats_config: { method: ExperimentStatsMethod.Bayesian },+} as Experiment+// Another editor changed the stats config while this user edited it, which is what makes the server reject the save.+const serverExperiment = {+ ...savedExperiment,+ version: 2,+ stats_config: { method: ExperimentStatsMethod.Bayesian, bayesian: { ci_level: 0.9 } },+} as Experiment++const MODALS = {+ CUPED: {+ Modal: CupedModal,+ open: () => modalsLogic.actions.openCupedModal(),+ isOpen: () => modalsLogic.values.isCupedModalOpen,+ edit: { method: ExperimentStatsMethod.Bayesian, cuped: { enabled: true } },+ control: 'Enabled',+ },+ stats: {+ Modal: StatsMethodModal,+ open: () => modalsLogic.actions.openStatsEngineModal(),+ isOpen: () => modalsLogic.values.isStatsEngineModalOpen,+ edit: { method: ExperimentStatsMethod.Frequentist },+ control: 'Frequentist',+ },+}++const echoSave = async ({ request }: { request: Request }): Promise<[number, Experiment]> => [+ 200,+ { ...savedExperiment, ...(await request.json()) },+]++const RESPONSES = {+ fails: () => [400, { type: 'validation_error', code: 'invalid_input', detail: 'Invalid stats config', attr: null }],+ conflicts: () => [+ 409,+ { type: 'validation_error', code: 'conflict', detail: 'Changed elsewhere', current_version: 2 },+ ],+ succeeds: echoSave,+}++describe('stats config modals', () => {+ let logic: ReturnType<typeof experimentLogic.build>++ afterEach(() => {+ cleanup()+ logic.unmount()+ })++ function renderModalWithEdit(modal: keyof typeof MODALS): void {+ const { Modal, open, edit } = MODALS[modal]+ initKeaTests()+ logic = experimentLogic({ experimentId: EXPERIMENT_ID })+ logic.mount()+ logic.actions.setUnmodifiedExperiment(savedExperiment)+ logic.actions.setExperiment(savedExperiment)+ open()+ render(+ <Provider>+ <BindLogic logic={experimentLogic} props={{ experimentId: EXPERIMENT_ID }}>+ <Modal />+ </BindLogic>+ </Provider>+ )+ // The modal options write the edit into the local experiment, as this does.+ act(() => logic.actions.setExperiment({ stats_config: edit }))+ }++ it.each([+ { modal: 'CUPED', outcome: 'fails', open: true, shows: 'edited' },+ { modal: 'stats', outcome: 'fails', open: true, shows: 'edited' },+ { modal: 'CUPED', outcome: 'conflicts', open: true, shows: 'server' },+ { modal: 'stats', outcome: 'conflicts', open: true, shows: 'server' },+ { modal: 'CUPED', outcome: 'succeeds', open: false, shows: 'edited' },+ { modal: 'stats', outcome: 'succeeds', open: false, shows: 'edited' },+ ] as const)(+ 'when the save $outcome, the $modal modal is open: $open, with the $shows settings',+ async ({ modal, outcome, open, shows }) => {+ const { isOpen, edit } = MODALS[modal]+ useMocks({+ get: { '/api/projects/:team/experiments/:id': serverExperiment },+ patch: { '/api/projects/:team/experiments/:id': RESPONSES[outcome] },+ })+ renderModalWithEdit(modal)++ fireEvent.click(screen.getByText('Save'))+ await act(() => expectLogic(logic).toFinishAllListeners())++ expect(isOpen()).toBe(open)+ // After a conflict, Save must send the other editor's change, so the modal shows the server's settings.+ expect(logic.values.experiment.stats_config).toEqual(+ shows === 'edited' ? edit : serverExperiment.stats_config+ )+ expect(lemonToast.success).toHaveBeenCalledTimes(open ? 0 : 1)+ expect(lemonToast.error).toHaveBeenCalledTimes(open ? 1 : 0)+ }+ )++ it.each(['CUPED', 'stats'] as const)('the %s modal locks its controls while its save runs', async (modal) => {+ const { isOpen, edit, control } = MODALS[modal]+ let finishSave = (): void => {}+ const saveFinished = new Promise<void>((resolve) => {+ finishSave = resolve+ })+ useMocks({+ patch: {+ '/api/projects/:team/experiments/:id': async (request: { request: Request }) => {+ await saveFinished+ return echoSave(request)+ },+ },+ })+ renderModalWithEdit(modal)++ fireEvent.click(screen.getByText('Save'))+ fireEvent.click(screen.getByText('Cancel'))++ expect(isOpen()).toBe(true)+ expect(logic.values.experiment.stats_config).toEqual(edit)+ expect(screen.getByText(control).closest('[aria-disabled]')).toHaveAttribute('aria-disabled', 'true')++ finishSave()+ await act(() => expectLogic(logic).toFinishAllListeners())++ expect(isOpen()).toBe(false)+ expect(logic.values.experiment.stats_config).toEqual(edit)+ })+})