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.

86.2 KB
Raw Blame
import { api } from 'lib/api.mock'

import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import posthog from 'posthog-js'
import { v4 as uuidv4 } from 'uuid'

import { ApiError } from 'lib/api-error'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { scrollToFormError } from 'lib/forms/scrollToFormError'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { cohortBlockingWorkflowsModalLogic } from 'scenes/cohorts/cohortBlockingWorkflowsModalLogic'
import { CohortLogicProps, REALTIME_POLL_INTERVAL_MS, cohortEditLogic } from 'scenes/cohorts/cohortEditLogic'
import { CRITERIA_VALIDATIONS, NEW_CRITERIA, ROWS } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { toPaginatedResponse } from '~/mocks/handlers'
import { useMocks } from '~/mocks/jest'
import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { ActorsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { mockCohort } from '~/test/mocks'
import {
    AccessControlLevel,
    AccessControlResourceType,
    AppContext,
    BehavioralEventType,
    BehavioralLifecycleType,
    CohortCriteriaGroupFilter,
    FilterLogicalOperator,
    PropertyFilterType,
    PropertyOperator,
    PropertyType,
    TimeUnitType,
} from '~/types'

import type {
    CohortRealtimeReadinessApi,
    CohortUsedInResponseApi,
} from 'products/cohorts/frontend/generated/api.schemas'

jest.mock('uuid', () => ({
    v4: jest.fn().mockReturnValue('mocked-uuid'),
}))

jest.mock('lib/forms/scrollToFormError', () => ({
    scrollToFormError: jest.fn(),
}))

jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
    lemonToast: {
        error: jest.fn(),
        success: jest.fn(),
    },
}))

const mockUsedInResponse: CohortUsedInResponseApi = {
    feature_flags: {
        results: [{ id: 7, key: 'my-flag', name: 'My Flag', archived: false }],
        total: 1,
        hidden: 0,
        has_more: false,
    },
    insights: { results: [], total: 0, hidden: 0, has_more: false },
    cohorts: { results: [], total: 0, hidden: 0, has_more: false },
    test_account_filters: { results: [], total: 0, has_more: false },
    workflows: { results: [], total: 0, hidden: 0, has_more: false },
}

describe('cohortEditLogic', () => {
    let logic: ReturnType<typeof cohortEditLogic.build>
    async function initCohortLogic(props: CohortLogicProps = { id: 'new' }): Promise<void> {
        await expectLogic(teamLogic).toFinishAllListeners()
        cohortsModel.mount()
        await expectLogic(cohortsModel).toFinishAllListeners()
        jest.spyOn(api, 'get')
        jest.spyOn(api, 'update')
        jest.spyOn(api, 'create')
        api.get.mockClear()
        api.create.mockClear()
        logic = cohortEditLogic(props)
        logic.mount()
        await expectLogic(logic).toFinishAllListeners()
    }

    beforeEach(async () => {
        // Persisted column selection lives in localStorage keyed by cohort id — clear it so
        // column state doesn't leak between tests that reuse the same cohort id.
        window.localStorage.clear()
        useMocks({
            get: {
                '/api/projects/:team_id/cohorts/': toPaginatedResponse([mockCohort]),
                '/api/projects/:team_id/cohorts/:id/': mockCohort,
                '/api/projects/:team_id/cohorts/:id/used_in/': mockUsedInResponse,
            },
            post: {
                '/api/projects/:team_id/cohorts/': mockCohort,
                '/api/projects/:team_id/cohorts/:id/': mockCohort,
            },
            patch: {
                '/api/projects/:team_id/cohorts/:id/': mockCohort,
            },
        })
        initKeaTests()
    })

    describe('initial load', () => {
        it('loads existing cohort on mount', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic).toDispatchActions(['fetchCohort'])

            // One call for the cohort itself, one for its used-in references
            expect(api.get).toHaveBeenCalledTimes(2)
        })

        it('loads used-in references on mount before the cohort has resolved', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])

            expect(logic.values.usedIn).toEqual(mockUsedInResponse)
        })

        it('treats a used-in response without a workflows block as no workflows', async () => {
            const { workflows: _, ...olderResponse } = mockUsedInResponse
            useMocks({ get: { '/api/projects/:team_id/cohorts/:id/used_in/': olderResponse } })
            await initCohortLogic({ id: 1 })
            await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])

            expect(logic.values.usedIn).toEqual(mockUsedInResponse)
        })

        it('swallows used-in 404s without reporting them', async () => {
            useMocks({
                get: {
                    '/api/projects/:team_id/cohorts/:id/used_in/': () => [404, { detail: 'Not found.' }],
                },
            })
            await initCohortLogic({ id: 1 })
            // The loader swallows the error and returns a value, so Success (not Failure) fires.
            await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])

            expect(logic.values.usedIn).toEqual(null)
            expect(posthog.captureException).not.toHaveBeenCalled()
        })

        it('reports non-404 used-in failures', async () => {
            useMocks({
                get: {
                    '/api/projects/:team_id/cohorts/:id/used_in/': () => [500, { detail: 'Server error' }],
                },
            })
            await initCohortLogic({ id: 1 })
            // The loader still returns a value on non-404 errors, so Success (not Failure) fires.
            await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])

            expect(logic.values.usedIn).toEqual(null)
            expect(posthog.captureException).toHaveBeenCalled()
        })

        it('keeps the previously loaded value when a refresh fails', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])
            expect(logic.values.usedIn).toEqual(mockUsedInResponse)

            useMocks({
                get: {
                    '/api/projects/:team_id/cohorts/:id/used_in/': () => [500, { detail: 'Server error' }],
                },
            })
            await expectLogic(logic, () => {
                logic.actions.loadUsedIn()
            }).toDispatchActions(['loadUsedIn', 'loadUsedInSuccess'])

            // The failed refresh returns the prior value instead of blanking the banner.
            expect(logic.values.usedIn).toEqual(mockUsedInResponse)
        })

        it('loads new cohort on mount', async () => {
            await initCohortLogic({ id: 'new' })
            await expectLogic(logic).toDispatchActions(['setCohort'])

            expect(api.get).toHaveBeenCalledTimes(0)
            expect(logic.values.staticCohortMode).toEqual('people')
        })

        it('loads new cohort on mount with undefined id', async () => {
            await initCohortLogic({ id: undefined })
            await expectLogic(logic).toDispatchActions(['setCohort'])

            expect(api.get).toHaveBeenCalledTimes(0)
        })
    })

    describe('calculation polling', () => {
        // The final poll response is the only thing that refreshes these fields while the page
        // stays open, so a field the merge drops keeps its stale value until a reload.
        it.each([
            ['import counts', { last_import_total_count: 5, last_import_unmatched_count: 3 }],
            [
                'failure reason',
                {
                    errors_calculating: 1,
                    last_error_message: 'Cohort calculation was terminated for reading too much data.',
                },
            ],
        ])('refreshes %s when calculation finishes', async (_, finishedFields) => {
            await initCohortLogic({ id: 1 })

            await expectLogic(logic, () => {
                logic.actions.checkIfFinishedCalculating({
                    ...mockCohort,
                    is_calculating: false,
                    ...finishedFields,
                })
            }).toMatchValues({
                cohort: partial(finishedFields),
            })
        })
    })

    describe('realtime history build polling', () => {
        // No feature flag setup: the API only sends `realtime` inside the rollout, so gating the
        // poll on the flag as well would strand a build whose flags resolve after the page fetch.
        afterEach(() => {
            // One case varies the generated criteria keys; the rest of the file reads the constant.
            ;(uuidv4 as jest.Mock).mockReturnValue('mocked-uuid')
        })

        const buildingRealtime: CohortRealtimeReadinessApi = {
            state: 'building',
            ready_at: null,
            build: { phase: 'scanning', percent_complete: 40, updated_at: '2026-09-15T10:00:00Z' },
        }
        const readyRealtime: CohortRealtimeReadinessApi = {
            state: 'ready',
            ready_at: '2026-09-15T10:20:00Z',
            build: null,
        }
        const criteriaGroupKeys = (): (string | undefined)[] =>
            logic.values.cohort.filters.properties.values.map((group) => (group as CohortCriteriaGroupFilter).sort_key)
        const setPageHidden = (hidden: boolean): void => {
            Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
            document.dispatchEvent(new Event('visibilitychange'))
        }

        it('merges the readiness without discarding unsaved criteria', async () => {
            // The build runs for tens of minutes, so every poll lands on a form the user may be
            // part-way through editing. Merging the whole cohort back would throw those edits away,
            // and re-keying the criteria groups would remount the fields they are typing in.
            let nextKey = 0
            ;(uuidv4 as jest.Mock).mockImplementation(() => `criteria-key-${nextKey++}`)
            useMocks({
                get: { '/api/projects/:team_id/cohorts/:id/': { ...mockCohort, realtime: readyRealtime } },
            })
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, () => {
                logic.actions.setCohort({ ...mockCohort, realtime: buildingRealtime })
                logic.actions.setOuterGroupsType(FilterLogicalOperator.And)
            }).toMatchValues({ cohort: partial({ realtime: buildingRealtime }) })
            const keysBeforePoll = criteriaGroupKeys()

            await expectLogic(logic, () => {
                logic.actions.pollRealtimeReadiness()
            })
                .toDispatchActions(['pollRealtimeReadiness', 'armRealtimeReadinessPoll'])
                .toFinishAllListeners()
                .toMatchValues({
                    cohort: partial({
                        realtime: readyRealtime,
                        filters: partial({ properties: partial({ type: FilterLogicalOperator.And }) }),
                    }),
                })
            expect(criteriaGroupKeys()).toEqual(keysBeforePoll)
        })

        it('drops a readiness the save it crossed has already replaced', async () => {
            // A poll in flight answers for the definition before the save, so letting it land would
            // report the old build as ready and stop watching the one the save just started.
            useMocks({
                get: { '/api/projects/:team_id/cohorts/:id/': { ...mockCohort, realtime: readyRealtime } },
            })
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, () => {
                logic.actions.setCohort({ ...mockCohort, realtime: buildingRealtime })
            }).toMatchValues({ cohort: partial({ realtime: buildingRealtime }) })

            const rebuildingRealtime: CohortRealtimeReadinessApi = { ...buildingRealtime, state: 'rebuilding' }
            await expectLogic(logic, () => {
                logic.actions.pollRealtimeReadiness()
                logic.actions.saveCohortSuccess({ ...mockCohort, realtime: rebuildingRealtime })
            }).toFinishAllListeners()

            expect(logic.values.cohort.realtime).toEqual(rebuildingRealtime)
            expect(lemonToast.success).not.toHaveBeenCalled()
        })

        it('keeps checking while the build runs, and stops once it is ready', async () => {
            // Both halves matter. A loop that never stops refetches the cohort every 15 seconds for
            // as long as the tab is open; one that stops early freezes the progress row until reload.
            let served: CohortRealtimeReadinessApi = buildingRealtime
            let detailFetches = 0
            useMocks({
                get: {
                    '/api/projects/:team_id/cohorts/:id/': () => {
                        detailFetches += 1
                        return [200, { ...mockCohort, realtime: served }]
                    },
                },
            })
            await initCohortLogic({ id: 1 })
            const afterMount = detailFetches

            jest.useFakeTimers()
            try {
                // The mount armed the poll on a real timer. Arming again replaces that disposable
                // with one on the fake clock, which is the same timer the loop re-arms below.
                logic.actions.armRealtimeReadinessPoll()

                await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
                expect(detailFetches).toBe(afterMount + 1)

                served = readyRealtime
                await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
                expect(detailFetches).toBe(afterMount + 2)
                // The flag picker rows and the condition link read readiness off the shared model,
                // so without this push they keep showing the cohort as unprepared all session.
                expect(cohortsModel.values.cohortsById[mockCohort.id]?.realtime).toEqual(readyRealtime)

                await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS * 4)
                expect(detailFetches).toBe(afterMount + 2)

                // Stopping means disposing, not just declining to re-arm. The disposables manager
                // re-runs every registered setup when the tab comes back, so a poll left on it
                // refetches the cohort 15 seconds after each return to a page that is long done.
                setPageHidden(true)
                setPageHidden(false)
                await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
                expect(detailFetches).toBe(afterMount + 2)
            } finally {
                jest.useRealTimers()
                delete (document as any).hidden
            }
        })

        it('keeps watching across the gap between the queued build and its run row', async () => {
            // The debounce key expires exactly when the run-creation task fires, and the run row
            // lands a moment later. A poll in between answers `needs_attention` for a build that is
            // fine, so stopping there would leave the page on "Unavailable" until a reload.
            let served: CohortRealtimeReadinessApi = buildingRealtime
            let detailFetches = 0
            useMocks({
                get: {
                    '/api/projects/:team_id/cohorts/:id/': () => {
                        detailFetches += 1
                        return [200, { ...mockCohort, realtime: served }]
                    },
                },
            })
            await initCohortLogic({ id: 1 })
            const afterMount = detailFetches

            jest.useFakeTimers()
            try {
                logic.actions.armRealtimeReadinessPoll()

                served = { state: 'needs_attention', ready_at: null, build: null }
                await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
                expect(detailFetches).toBe(afterMount + 1)

                served = readyRealtime
                await jest.advanceTimersByTimeAsync(REALTIME_POLL_INTERVAL_MS)
                expect(detailFetches).toBe(afterMount + 2)
                expect(logic.values.cohort.realtime).toEqual(readyRealtime)
            } finally {
                jest.useRealTimers()
            }
        })

        it('announces the ready moment once, not on every check after it', async () => {
            useMocks({
                get: { '/api/projects/:team_id/cohorts/:id/': { ...mockCohort, realtime: readyRealtime } },
            })
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, () => {
                logic.actions.setCohort({ ...mockCohort, realtime: buildingRealtime })
            }).toMatchValues({ cohort: partial({ realtime: buildingRealtime }) })

            await expectLogic(logic, () => {
                logic.actions.pollRealtimeReadiness()
            }).toFinishAllListeners()
            expect(lemonToast.success).toHaveBeenCalledWith('This cohort is ready. Feature flags can target it now.')

            ;(lemonToast.success as jest.Mock).mockClear()
            await expectLogic(logic, () => {
                logic.actions.pollRealtimeReadiness()
            }).toFinishAllListeners()
            expect(lemonToast.success).not.toHaveBeenCalled()
        })
    })

    it('delete cohort', async () => {
        await initCohortLogic({ id: 1 })
        await expectLogic(logic, async () => {
            logic.actions.setCohort(mockCohort)
            logic.actions.deleteCohort()
        })
            .toFinishAllListeners()
            .toDispatchActions(['setCohort', 'deleteCohort', router.actionCreators.push(urls.cohorts())])
        expect(api.update).toHaveBeenCalledTimes(1)
    })

    it('restore cohort', async () => {
        await initCohortLogic({ id: 1 })
        await expectLogic(logic, async () => {
            logic.actions.setCohort({ ...mockCohort, deleted: true })
            logic.actions.restoreCohort()
        })
            .toFinishAllListeners()
            .toDispatchActions(['setCohort', 'restoreCohort'])
        expect(api.update).toHaveBeenCalledTimes(1)
        expect(api.update).toHaveBeenCalledWith(
            expect.anything(),
            {
                deleted: false,
            },
            expect.anything()
        )
    })

    describe('workflows that rely on the cohort', () => {
        const blockingWorkflows = {
            results: [{ id: 'flow-1', name: 'Welcome series', status: 'active' }],
            total: 2,
            hidden: 1,
            has_more: true,
        }

        beforeEach(() => {
            useMocks({
                get: {
                    '/api/projects/:team_id/cohorts/:id/used_in/': {
                        ...mockUsedInResponse,
                        workflows: blockingWorkflows,
                    },
                    '/api/projects/:team_id/cohorts/:id/blocking_workflows/': blockingWorkflows,
                },
                patch: {
                    '/api/projects/:team_id/cohorts/:id/': () => [
                        400,
                        { type: 'validation_error', code: 'cohort_used_by_workflows', detail: 'Blocked', attr: null },
                    ],
                },
            })
        })

        it('lists the blocking workflows instead of deleting the cohort', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic).toMatchValues({
                usedIn: expect.objectContaining({ workflows: blockingWorkflows }),
            })

            await expectLogic(logic, () => logic.actions.deleteCohort())
                .toFinishAllListeners()
                .toNotHaveDispatchedActions([cohortsModel.actionTypes.deleteCohort])
            expect(cohortBlockingWorkflowsModalLogic.values.blocking).toEqual({
                action: 'delete',
                workflows: blockingWorkflows,
            })
        })

        it('deletes on the next attempt once the blocking workflows are gone', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic).toMatchValues({
                usedIn: expect.objectContaining({ workflows: blockingWorkflows }),
            })
            useMocks({ get: { '/api/projects/:team_id/cohorts/:id/used_in/': mockUsedInResponse } })

            await expectLogic(logic, () => logic.actions.deleteCohort()).toDispatchActions([
                'deleteCohort',
                'loadUsedIn',
                'loadUsedInSuccess',
            ])
            await expectLogic(logic, () => logic.actions.deleteCohort()).toDispatchActions([
                cohortsModel.actionTypes.deleteCohort,
            ])
        })

        it('does nothing after the blocked save workflow check when the editor has closed', async () => {
            let releaseLookup: () => void = () => {}
            const lookupHeld = new Promise<void>((resolve) => {
                releaseLookup = resolve
            })
            let lookupStarted: () => void = () => {}
            const started = new Promise<void>((resolve) => {
                lookupStarted = resolve
            })
            let lookupAnswered: () => void = () => {}
            const answered = new Promise<void>((resolve) => {
                lookupAnswered = resolve
            })
            useMocks({
                get: {
                    '/api/projects/:team_id/cohorts/:id/blocking_workflows/': async () => {
                        lookupStarted()
                        await lookupHeld
                        lookupAnswered()
                        return [200, blockingWorkflows]
                    },
                },
            })
            await initCohortLogic({ id: 1 })
            // The cohorts list keeps the modal logic mounted after the editor closes.
            cohortBlockingWorkflowsModalLogic.mount()
            const deleteSpy = jest.spyOn(cohortsModel.actions, 'deleteCohort')

            logic.actions.saveCohort()
            await started
            logic.unmount()
            releaseLookup()
            await answered
            await expectLogic(cohortsModel).toFinishAllListeners()

            expect(deleteSpy).not.toHaveBeenCalled()
            expect(cohortBlockingWorkflowsModalLogic.values.blocking).toEqual(null)
        })

        it('lists the blocking workflows when the API refuses an edit that stops realtime updates', async () => {
            await initCohortLogic({ id: 1 })

            await expectLogic(logic, () => logic.actions.saveCohort()).toFinishAllListeners()
            expect(cohortBlockingWorkflowsModalLogic.values.blocking).toEqual({
                action: 'edit',
                workflows: blockingWorkflows,
            })
            expect(lemonToast.error).not.toHaveBeenCalledWith('Blocked')
        })
    })

    describe('form validation', () => {
        it('save with valid cohort', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    filters: {
                        properties: {
                            ...mockCohort.filters.properties,
                            values: [
                                {
                                    id: '70427',
                                    type: FilterLogicalOperator.Or,
                                    values: [
                                        {
                                            type: BehavioralFilterKey.Behavioral,
                                            value: BehavioralEventType.PerformEvent,
                                            event_type: TaxonomicFilterGroupType.Events,
                                            time_value: 30,
                                            time_interval: TimeUnitType.Day,
                                            key: 'dashboard date range changed',
                                        },
                                    ],
                                },
                            ],
                        },
                    },
                })
                logic.actions.submitCohort()
            })
                .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortSuccess', 'saveCohortSuccess'])
                .toNotHaveDispatchedActions(['loadUsedIn'])
            expect(api.update).toHaveBeenCalledTimes(1)
            expect(lemonToast.success).toHaveBeenCalledWith(
                expect.stringContaining('Cohort saved'),
                expect.objectContaining({ button: undefined })
            )
        })

        it('do not save with invalid name', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    name: '',
                })
                logic.actions.submitCohort()
            }).toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
            expect(api.update).toHaveBeenCalledTimes(0)
        })

        describe('negation errors', () => {
            it('do not save on OR operator', async () => {
                await initCohortLogic({ id: 1 })
                await expectLogic(logic, async () => {
                    logic.actions.setCohort({
                        ...mockCohort,
                        filters: {
                            properties: {
                                id: '39777',
                                type: FilterLogicalOperator.Or,
                                values: [
                                    {
                                        id: '70427',
                                        type: FilterLogicalOperator.Or,
                                        values: [
                                            {
                                                type: BehavioralFilterKey.Behavioral,
                                                value: BehavioralEventType.PerformEvent,
                                                event_type: TaxonomicFilterGroupType.Events,
                                                time_value: 30,
                                                time_interval: TimeUnitType.Day,
                                                key: 'dashboard date range changed',
                                                negation: true,
                                            },
                                            {
                                                type: BehavioralFilterKey.Behavioral,
                                                value: BehavioralEventType.PerformEvent,
                                                event_type: TaxonomicFilterGroupType.Events,
                                                time_value: 30,
                                                time_interval: TimeUnitType.Day,
                                                key: '$rageclick',
                                            },
                                        ],
                                    },
                                ],
                            },
                        },
                    })
                    logic.actions.submitCohort()
                })
                    .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
                    .toMatchValues({
                        cohortErrors: partial({
                            filters: {
                                properties: {
                                    values: [
                                        {
                                            id: "'Did not complete event' is a negative cohort criteria. Negation criteria can only be used when matching all criteria (AND), and must be accompanied by at least one positive matching criteria.",
                                            values: [
                                                {
                                                    value: "'Did not complete event' is a negative cohort criteria. Negation criteria can only be used when matching all criteria (AND), and must be accompanied by at least one positive matching criteria.",
                                                },
                                                {},
                                            ],
                                        },
                                    ],
                                },
                            },
                        }),
                    })
                expect(api.update).toHaveBeenCalledTimes(0)
            })

            it('do not save on less than one positive matching criteria', async () => {
                await initCohortLogic({ id: 1 })
                await expectLogic(logic, async () => {
                    logic.actions.setCohort({
                        ...mockCohort,
                        filters: {
                            properties: {
                                id: '39777',
                                type: FilterLogicalOperator.Or,
                                values: [
                                    {
                                        id: '70427',
                                        type: FilterLogicalOperator.And,
                                        values: [
                                            {
                                                type: BehavioralFilterKey.Behavioral,
                                                value: BehavioralEventType.PerformEvent,
                                                event_type: TaxonomicFilterGroupType.Events,
                                                time_value: 30,
                                                time_interval: TimeUnitType.Day,
                                                key: 'dashboard date range changed',
                                                negation: true,
                                            },
                                        ],
                                    },
                                ],
                            },
                        },
                    })
                    logic.actions.submitCohort()
                })
                    .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
                    .toMatchValues({
                        cohortErrors: partial({
                            filters: {
                                properties: {
                                    values: [
                                        {
                                            id: "'Did not complete event' is a negative cohort criteria. Negation criteria can only be used when matching all criteria (AND), and must be accompanied by at least one positive matching criteria.",
                                            values: [
                                                {
                                                    value: "'Did not complete event' is a negative cohort criteria. Negation criteria can only be used when matching all criteria (AND), and must be accompanied by at least one positive matching criteria.",
                                                },
                                            ],
                                        },
                                    ],
                                },
                            },
                        }),
                    })
                expect(api.update).toHaveBeenCalledTimes(0)
            })

            it('do not save on criteria cancelling each other out', async () => {
                await initCohortLogic({ id: 1 })
                await expectLogic(logic, async () => {
                    logic.actions.setCohort({
                        ...mockCohort,
                        filters: {
                            properties: {
                                id: '39777',
                                type: FilterLogicalOperator.Or,
                                values: [
                                    {
                                        id: '70427',
                                        type: FilterLogicalOperator.And,
                                        values: [
                                            {
                                                type: BehavioralFilterKey.Behavioral,
                                                value: BehavioralEventType.PerformEvent,
                                                event_type: TaxonomicFilterGroupType.Events,
                                                time_value: 30,
                                                time_interval: TimeUnitType.Day,
                                                key: 'dashboard date range changed',
                                                negation: true,
                                            },
                                            {
                                                type: BehavioralFilterKey.Behavioral,
                                                value: BehavioralEventType.PerformEvent,
                                                event_type: TaxonomicFilterGroupType.Events,
                                                time_value: 30,
                                                time_interval: TimeUnitType.Day,
                                                key: 'dashboard date range changed',
                                            },
                                        ],
                                    },
                                ],
                            },
                        },
                    })
                    logic.actions.submitCohort()
                })
                    .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
                    .toMatchValues({
                        cohortErrors: partial({
                            filters: {
                                properties: {
                                    values: [
                                        {
                                            id: 'These criteria cancel each other out, and would result in no matching persons.',
                                            values: [
                                                {
                                                    value: 'These criteria cancel each other out, and would result in no matching persons.',
                                                },
                                                {
                                                    value: 'These criteria cancel each other out, and would result in no matching persons.',
                                                },
                                            ],
                                        },
                                    ],
                                },
                            },
                        }),
                    })
                expect(api.update).toHaveBeenCalledTimes(0)
            })
        })

        it('do not save on invalid lower and upper bound period values - perform event regularly', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    filters: {
                        properties: {
                            id: '26585',
                            type: FilterLogicalOperator.Or,
                            values: [
                                {
                                    id: '6',
                                    type: FilterLogicalOperator.Or,
                                    values: [
                                        {
                                            type: BehavioralFilterKey.Behavioral,
                                            value: BehavioralLifecycleType.PerformEventRegularly,
                                            event_type: TaxonomicFilterGroupType.Events,
                                            time_value: 1,
                                            time_interval: TimeUnitType.Day,
                                            operator: PropertyOperator.Exact,
                                            operator_value: 5,
                                            min_periods: 6,
                                            total_periods: 5,
                                            negation: false,
                                        },
                                    ],
                                },
                            ],
                        },
                    },
                })
                logic.actions.submitCohort()
            })
                .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
                .toMatchValues({
                    cohortErrors: partial({
                        filters: {
                            properties: {
                                values: [
                                    {
                                        values: [
                                            {
                                                id: 'The lower bound period value must not be greater than the upper bound value.',
                                                min_periods:
                                                    'The lower bound period value must not be greater than the upper bound value.',
                                                total_periods:
                                                    'The lower bound period value must not be greater than the upper bound value.',
                                            },
                                        ],
                                    },
                                ],
                            },
                        },
                    }),
                })
            expect(api.update).toHaveBeenCalledTimes(0)
        })

        it('do not save on invalid lower and upper bound period values - perform events in sequence', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    filters: {
                        properties: {
                            type: FilterLogicalOperator.Or,
                            values: [
                                {
                                    type: FilterLogicalOperator.Or,
                                    values: [
                                        {
                                            type: BehavioralFilterKey.Behavioral,
                                            value: BehavioralEventType.PerformSequenceEvents,
                                            negation: false,
                                            key: '$groupidentify',
                                            event_type: TaxonomicFilterGroupType.Events,
                                            time_value: '28',
                                            time_interval: TimeUnitType.Day,
                                            seq_event: '$groupidentify',
                                            seq_time_value: '30',
                                            seq_time_interval: TimeUnitType.Day,
                                        },
                                    ],
                                },
                            ],
                        },
                    },
                })
                logic.actions.submitCohort()
            })
                .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
                .toMatchValues({
                    cohortErrors: partial({
                        filters: {
                            properties: {
                                values: [
                                    {
                                        values: [
                                            {
                                                id: 'The lower bound period sequential time value must not be greater than the upper bound time value.',
                                                time_value:
                                                    'The lower bound period sequential time value must not be greater than the upper bound time value.',
                                                seq_time_value:
                                                    'The lower bound period sequential time value must not be greater than the upper bound time value.',
                                            },
                                        ],
                                    },
                                ],
                            },
                        },
                    }),
                })
            expect(api.update).toHaveBeenCalledTimes(0)
        })

        it('do not save on partial event filters', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    filters: {
                        properties: {
                            id: '39777',
                            type: FilterLogicalOperator.Or,
                            values: [
                                {
                                    id: '70427',
                                    type: FilterLogicalOperator.And,
                                    values: [
                                        {
                                            type: BehavioralFilterKey.Behavioral,
                                            value: BehavioralEventType.PerformEvent,
                                            event_type: TaxonomicFilterGroupType.Events,
                                            explicit_datetime: '-14d',
                                            key: 'dashboard date range changed',
                                            event_filters: [
                                                {
                                                    key: '$browser',
                                                    value: null,
                                                    type: PropertyFilterType.Event,
                                                    operator: PropertyOperator.Exact,
                                                },
                                            ],
                                        },
                                        {
                                            type: BehavioralFilterKey.Behavioral,
                                            value: BehavioralEventType.PerformEvent,
                                            event_type: TaxonomicFilterGroupType.Events,
                                            time_value: '1',
                                            time_interval: TimeUnitType.Day,
                                            key: '$rageclick',
                                            negation: true,
                                            event_filters: [
                                                {
                                                    key: '$browser',
                                                    value: null,
                                                    type: PropertyFilterType.Event,
                                                    operator: PropertyOperator.Exact,
                                                },
                                            ],
                                        },
                                    ],
                                },
                            ],
                        },
                    },
                })
                logic.actions.submitCohort()
            })
                .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
                .toMatchValues({
                    cohortErrors: partial({
                        filters: {
                            properties: {
                                values: [
                                    {
                                        values: [
                                            {
                                                event_filters: 'Event filters cannot be empty.',
                                                id: 'Event filters cannot be empty.',
                                            },
                                            {
                                                event_filters: 'Event filters cannot be empty.',
                                                id: 'Event filters cannot be empty.',
                                            },
                                        ],
                                    },
                                ],
                            },
                        },
                    }),
                })
            expect(api.update).toHaveBeenCalledTimes(0)
        })

        describe('empty input errors', () => {
            Object.entries(ROWS).forEach(([key, row]) => {
                it(`${key} row missing all required fields`, async () => {
                    await initCohortLogic({ id: 1 })
                    await expectLogic(logic, async () => {
                        logic.actions.setCohort({
                            ...mockCohort,
                            filters: {
                                properties: {
                                    id: '26585',
                                    type: FilterLogicalOperator.Or,
                                    values: [
                                        {
                                            id: '6',
                                            type: FilterLogicalOperator.Or,
                                            values: [
                                                {
                                                    type: row.type,
                                                    value: row.value,
                                                    ...Object.fromEntries(
                                                        row.fields
                                                            .filter(({ fieldKey }) => !!fieldKey)
                                                            .map(({ fieldKey }) => [fieldKey, undefined])
                                                    ),
                                                },
                                            ],
                                        },
                                    ],
                                },
                            },
                        })
                        logic.actions.submitCohort()
                    })
                        .toDispatchActions(['setCohort', 'submitCohort', 'submitCohortFailure'])
                        .toMatchValues({
                            cohortErrors: partial({
                                filters: {
                                    properties: {
                                        values: [
                                            {
                                                values: [
                                                    partial(
                                                        Object.fromEntries(
                                                            row.fields
                                                                .filter(
                                                                    ({ fieldKey }) =>
                                                                        !!fieldKey &&
                                                                        fieldKey !== 'event_filters' &&
                                                                        fieldKey !== 'explicit_datetime_to'
                                                                ) // event_filters and explicit_datetime_to are optional
                                                                .map(({ fieldKey, type }) => [
                                                                    fieldKey,
                                                                    CRITERIA_VALIDATIONS[type](undefined),
                                                                ])
                                                        )
                                                    ),
                                                ],
                                            },
                                        ],
                                    },
                                },
                            }),
                        })
                    expect(api.update).toHaveBeenCalledTimes(0)
                })
            })
        })

        it('can save existing static cohort with empty csv', async () => {
            await initCohortLogic({ id: 1 })
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    is_static: true,
                    groups: [],
                    filters: { properties: {} as any },
                    csv: undefined,
                })
                logic.actions.setStaticCohortMode('people')
                logic.actions.submitCohort()
            }).toDispatchActions(['setCohort', 'setStaticCohortMode', 'submitCohort', 'submitCohortSuccess'])
            expect(api.update).toHaveBeenCalledTimes(1)
        })

        it('can create static cohort from criteria without csv', async () => {
            window.POSTHOG_APP_CONTEXT = {
                ...window.POSTHOG_APP_CONTEXT,
                resource_access_control: {
                    ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
                    [AccessControlResourceType.Workflow]: AccessControlLevel.Editor,
                },
            } as AppContext
            await initCohortLogic({ id: 'new' })
            const createdCohort = {
                ...mockCohort,
                id: 2,
                name: 'Static from criteria',
                is_static: true,
            }
            const createSpy = jest.spyOn(api.cohorts, 'create').mockResolvedValue(createdCohort)
            // Suppress only the 1s calculation poll — kea breakpoints schedule shorter
            // timers through setTimeout too, and those must still fire
            const realSetTimeout = window.setTimeout.bind(window)
            const setTimeoutSpy = jest
                .spyOn(window, 'setTimeout')
                .mockImplementation(((handler: TimerHandler, timeout?: number, ...args: any[]) =>
                    timeout === 1000 ? (0 as any) : realSetTimeout(handler, timeout, ...args)) as any)

            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    id: 'new',
                    name: 'Static from criteria',
                    is_static: true,
                    filters: {
                        properties: {
                            ...mockCohort.filters.properties,
                            values: [
                                {
                                    id: '70427',
                                    type: FilterLogicalOperator.Or,
                                    values: [
                                        {
                                            type: BehavioralFilterKey.Behavioral,
                                            value: BehavioralEventType.PerformEvent,
                                            event_type: TaxonomicFilterGroupType.Events,
                                            time_value: 30,
                                            time_interval: TimeUnitType.Day,
                                            key: 'dashboard date range changed',
                                        },
                                    ],
                                },
                            ],
                        },
                    },
                })
                logic.actions.setStaticCohortMode('criteria')
                logic.actions.submitCohort()
            }).toDispatchActions(['setCohort', 'setStaticCohortMode', 'submitCohort', 'submitCohortSuccess'])

            expect(createSpy).toHaveBeenCalledTimes(1)
            const createPayload = createSpy.mock.calls[0][0] as FormData
            expect(createPayload.get('is_static')).toEqual('true')
            expect(createPayload.get('filters')).toContain('"values"')
            expect(createPayload.get('filters')).not.toContain('"properties":{}')
            expect(lemonToast.success).toHaveBeenCalledWith(
                expect.stringContaining('Cohort saved'),
                expect.objectContaining({ button: expect.objectContaining({ label: 'Email this cohort' }) })
            )

            // Let the post-submit refreshPersonsData debounce finish before the test ends
            await expectLogic(logic).toFinishAllListeners()
            setTimeoutSpy.mockRestore()
        })

        it('offers no email button for a new cohort a broadcast cannot send to', async () => {
            window.POSTHOG_APP_CONTEXT = {
                ...window.POSTHOG_APP_CONTEXT,
                resource_access_control: {
                    ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
                    [AccessControlResourceType.Workflow]: AccessControlLevel.Editor,
                },
            } as AppContext
            await initCohortLogic({ id: 'new' })
            const behavioralFilters = {
                properties: {
                    ...mockCohort.filters.properties,
                    values: [
                        {
                            id: '70427',
                            type: FilterLogicalOperator.Or,
                            values: [
                                {
                                    type: BehavioralFilterKey.Behavioral,
                                    value: BehavioralEventType.PerformEvent,
                                    event_type: TaxonomicFilterGroupType.Events,
                                    time_value: 30,
                                    time_interval: TimeUnitType.Day,
                                    key: 'dashboard date range changed',
                                },
                            ],
                        },
                    ],
                },
            }
            jest.spyOn(api.cohorts, 'create').mockResolvedValue({
                ...mockCohort,
                id: 3,
                is_static: false,
                filters: behavioralFilters,
            })

            await expectLogic(logic, async () => {
                logic.actions.setCohort({ ...mockCohort, id: 'new', is_static: false, filters: behavioralFilters })
                logic.actions.submitCohort()
            }).toDispatchActions(['setCohort', 'submitCohort', 'submitCohortSuccess'])

            expect(lemonToast.success).toHaveBeenCalledWith(
                expect.stringContaining('Cohort saved'),
                expect.objectContaining({ button: undefined })
            )
            await expectLogic(logic).toFinishAllListeners()
        })

        it('do not save static cohort with empty csv', async () => {
            await initCohortLogic({ id: 'new' })
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    is_static: true,
                    groups: [],
                    csv: undefined,
                    id: 'new',
                })
                logic.actions.setStaticCohortMode('people')
                logic.actions.submitCohort()
            }).toDispatchActions(['setCohort', 'setStaticCohortMode', 'submitCohort'])
            expect(api.update).toHaveBeenCalledTimes(0)
        })

        const MB = 1024 * 1024

        it.each([
            { case: 'over the default limit', isStatic: true, configuredMax: undefined, blocked: true },
            { case: 'under a larger configured limit', isStatic: true, configuredMax: 50 * MB, blocked: false },
            { case: 'left on a cohort switched to dynamic', isStatic: false, configuredMax: undefined, blocked: false },
        ])('csv size check: $case', async ({ isStatic, configuredMax, blocked }) => {
            await initCohortLogic({ id: 1 })
            preflightLogic.actions.loadPreflightSuccess({
                ...preflightLogic.values.preflight,
                cohort_csv_upload_max_bytes: configuredMax,
            } as any)
            const csv = new File(['user_1'], 'ids.csv')
            Object.defineProperty(csv, 'size', { value: 20 * MB + 1 })
            logic.actions.setCohort({ ...mockCohort, is_static: isStatic, csv })
            expect(logic.values.cohortValidationErrors.csv).toEqual(
                blocked
                    ? 'CSV file is larger than the limit of 20 MB. Split the file into smaller parts and upload them one at a time.'
                    : undefined
            )
        })

        it('shows the size limit when the save is rejected with a 413', async () => {
            await initCohortLogic({ id: 1 })
            ;(api.update as jest.Mock).mockRejectedValueOnce(new ApiError('Payload too large', 413))
            await expectLogic(logic, async () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    is_static: true,
                    groups: [],
                    csv: new File(['user_1'], 'ids.csv'),
                })
                logic.actions.setStaticCohortMode('people')
                logic.actions.submitCohort()
            }).toDispatchActions(['submitCohort', 'saveCohortSuccess'])
            expect(lemonToast.error).toHaveBeenCalledWith(expect.stringContaining('larger than the limit of 20 MB'))
        })

        it('calls scrollToFormError with fallback message on submitCohortFailure', async () => {
            await initCohortLogic({ id: 1 })
            const mockScrollToFormError = scrollToFormError as jest.Mock

            const testError = new Error('Test cohort submission error')
            const testErrors = { name: 'Invalid name' }

            await expectLogic(logic, async () => {
                logic.actions.submitCohortFailure(testError, testErrors)
            }).toDispatchActions(['submitCohortFailure'])

            expect(mockScrollToFormError).toHaveBeenCalledWith({
                extraErrorSelectors: ['.CohortCriteriaRow__Criteria--error'],
                fallbackErrorMessage:
                    'There was an error submitting this cohort. Make sure the cohort filters are correct.',
            })
        })
    })

    describe('CSV upload', () => {
        const savedCohort = {
            ...mockCohort,
            id: 1,
            name: 'Saved name',
            description: 'Saved description',
            is_static: true,
        }

        it('uploads only the CSV, preserves unsaved cohort details and closes the modal', async () => {
            await initCohortLogic({ id: 1 })
            const updateSpy = jest.spyOn(api.cohorts, 'update').mockResolvedValue(savedCohort)
            const csv = new File(['[email protected]'], 'people.csv', { type: 'text/csv' })

            await expectLogic(logic, () => {
                logic.actions.setCohort({
                    ...savedCohort,
                    name: 'Unsaved name',
                    description: 'Unsaved description',
                    csv,
                })
                logic.actions.setCsvUploadModalOpen(true)
                logic.actions.uploadCohortCsv()
            }).toDispatchActions(['setCohort', 'uploadCohortCsv', 'saveCohort', 'saveCohortSuccess'])

            expect(updateSpy).toHaveBeenCalledTimes(1)
            const formData = updateSpy.mock.calls[0][1] as FormData
            expect([...formData.keys()]).toEqual(['csv'])
            expect(formData.get('csv')).toBe(csv)
            expect(logic.values.cohort.name).toBe('Unsaved name')
            expect(logic.values.cohort.description).toBe('Unsaved description')
            expect(logic.values.csvUploadModalOpen).toBe(false)

            updateSpy.mockRestore()
        })

        it('keeps the modal open when the upload fails', async () => {
            await initCohortLogic({ id: 1 })
            const updateSpy = jest.spyOn(api.cohorts, 'update').mockRejectedValue({ detail: 'Upload failed' })
            const csv = new File(['[email protected]'], 'people.csv', { type: 'text/csv' })

            await expectLogic(logic, () => {
                logic.actions.setCohort({ ...savedCohort, csv })
                logic.actions.setCsvUploadModalOpen(true)
                logic.actions.uploadCohortCsv()
            }).toDispatchActions(['uploadCohortCsv', 'saveCohort', 'saveCohortSuccess'])

            // The loader catch path keeps the csv on the cohort, which keeps the modal open for a retry.
            expect(logic.values.csvUploadModalOpen).toBe(true)
            expect(logic.values.cohort.csv).toBe(csv)

            updateSpy.mockRestore()
        })

        it('does not start the upload when the CSV exceeds the size limit', async () => {
            await initCohortLogic({ id: 1 })
            const updateSpy = jest.spyOn(api.cohorts, 'update').mockResolvedValue(savedCohort)
            const csv = new File(['[email protected]'], 'people.csv', { type: 'text/csv' })
            Object.defineProperty(csv, 'size', { value: logic.values.csvMaxBytes + 1 })

            await expectLogic(logic, () => {
                logic.actions.setCohort({ ...savedCohort, csv })
                logic.actions.setCsvUploadModalOpen(true)
                logic.actions.uploadCohortCsv()
            }).toDispatchActions(['uploadCohortCsv'])

            expect(updateSpy).not.toHaveBeenCalled()
            expect(logic.values.csvUploadModalOpen).toBe(true)

            updateSpy.mockRestore()
        })
    })

    describe('manual person selection for static cohort creation', () => {
        it('keeps the display name so it can be shown in the selected list, and forgets it on remove', async () => {
            await initCohortLogic({ id: 'new' })

            await expectLogic(logic, () => {
                logic.actions.addPersonToCreateStaticCohort('person-1', 'Jane Doe')
            }).toMatchValues({
                personsToCreateStaticCohort: { 'person-1': 'Jane Doe' },
            })

            await expectLogic(logic, () => {
                logic.actions.removePersonFromCreateStaticCohort('person-1')
            }).toMatchValues({
                personsToCreateStaticCohort: {},
            })
        })
    })

    describe('mutate filters', () => {
        beforeEach(async () => {
            await initCohortLogic({ id: 1 })
        })

        it.each([
            ['email', PropertyOperator.IsSet, PropertyOperator.IsSet],
            ['birth_date', PropertyOperator.IsDateBefore, PropertyOperator.IsDateBefore],
            ['email', PropertyOperator.IContains, PropertyOperator.IsDateExact],
        ])(
            'switching a %s row on %s to a DateTime property leaves the operator %s',
            async (startKey, startOperator, expectedOperator) => {
                propertyDefinitionsModel.mount()
                propertyDefinitionsModel.actions.updatePropertyDefinitions({
                    'person/email': { id: 'email', name: 'email', property_type: PropertyType.String },
                    'person/birth_date': { id: 'birth_date', name: 'birth_date', property_type: PropertyType.DateTime },
                    'person/signup_date': {
                        id: 'signup_date',
                        name: 'signup_date',
                        property_type: PropertyType.DateTime,
                    },
                })
                logic.actions.setCriteria(
                    {
                        type: BehavioralFilterKey.Person,
                        value: BehavioralEventType.HaveProperty,
                        key: startKey,
                        operator: startOperator,
                    },
                    0,
                    0
                )

                await expectLogic(logic, () => {
                    logic.actions.setCriteria({ key: 'signup_date' }, 0, 0)
                }).toFinishAllListeners()

                const group = logic.values.cohort.filters.properties.values[0] as CohortCriteriaGroupFilter
                expect(group.values[0]).toEqual(
                    expect.objectContaining({ key: 'signup_date', operator: expectedOperator })
                )
            }
        )

        it('duplicate group', async () => {
            const expectedGroupValue = partial({
                ...mockCohort.filters.properties.values[0],
                values: [
                    {
                        ...(mockCohort.filters.properties.values[0] as CohortCriteriaGroupFilter).values[0],
                        explicit_datetime: '-30d',
                        sort_key: uuidv4(),
                    },
                ],
            }) // Backwards compatible processing adds explicit_datetime

            await expectLogic(logic, () => {
                logic.actions.duplicateFilter(0)
            })
                .toDispatchActions(['duplicateFilter'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                values: [expectedGroupValue, expectedGroupValue],
                            }),
                        },
                    }),
                })
        })

        it('remove group', async () => {
            await expectLogic(logic, () => {
                logic.actions.removeFilter(0)
            })
                .toDispatchActions(['removeFilter'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                values: [],
                            }),
                        },
                    }),
                })
        })

        it('add group', async () => {
            await expectLogic(logic, () => {
                logic.actions.addFilter()
            })
                .toDispatchActions(['addFilter'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                values: [
                                    partial({
                                        ...mockCohort.filters.properties.values[0],
                                        values: [
                                            {
                                                ...(
                                                    mockCohort.filters.properties.values[0] as CohortCriteriaGroupFilter
                                                ).values[0],
                                                explicit_datetime: '-30d',
                                                sort_key: uuidv4(),
                                            },
                                        ],
                                    }), // Backwards compatible processing adds explicit_datetime
                                    partial({
                                        type: FilterLogicalOperator.Or,
                                        values: [NEW_CRITERIA],
                                    }),
                                ],
                            }),
                        },
                    }),
                })
        })

        it('duplicate criteria', async () => {
            await expectLogic(logic, () => {
                logic.actions.duplicateFilter(0, 0)
            })
                .toDispatchActions(['duplicateFilter'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                values: [
                                    partial({
                                        values: [
                                            partial(
                                                (mockCohort.filters.properties.values[0] as CohortCriteriaGroupFilter)
                                                    .values[0]
                                            ),
                                            partial(
                                                (mockCohort.filters.properties.values[0] as CohortCriteriaGroupFilter)
                                                    .values[0]
                                            ),
                                        ],
                                    }),
                                ],
                            }),
                        },
                    }),
                })
        })

        it('remove criteria', async () => {
            await expectLogic(logic, () => {
                logic.actions.removeFilter(0, 0)
            })
                .toDispatchActions(['removeFilter'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                values: [
                                    partial({
                                        values: [],
                                    }),
                                ],
                            }),
                        },
                    }),
                })
        })

        it('add criteria', async () => {
            await expectLogic(logic, () => {
                logic.actions.addFilter(0)
            })
                .toDispatchActions(['addFilter'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                values: [
                                    partial({
                                        values: [
                                            partial(
                                                (mockCohort.filters.properties.values[0] as CohortCriteriaGroupFilter)
                                                    .values[0]
                                            ),
                                            { ...NEW_CRITERIA, sort_key: uuidv4() },
                                        ],
                                    }),
                                ],
                            }),
                        },
                    }),
                })
        })

        it('set outer logical operator', async () => {
            await expectLogic(logic, () => {
                logic.actions.setOuterGroupsType(FilterLogicalOperator.And)
            })
                .toDispatchActions(['setOuterGroupsType'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                type: FilterLogicalOperator.And,
                            }),
                        },
                    }),
                })
        })

        it('set inner logical operator', async () => {
            await expectLogic(logic, () => {
                logic.actions.setInnerGroupType(FilterLogicalOperator.And, 0)
            })
                .toDispatchActions(['setInnerGroupType'])
                .toMatchValues({
                    cohort: partial({
                        filters: {
                            properties: partial({
                                values: [
                                    partial({
                                        type: FilterLogicalOperator.And,
                                    }),
                                ],
                            }),
                        },
                    }),
                })
        })
    })

    describe('query state and column configuration', () => {
        it('preserves custom column configuration when setCohort is called', async () => {
            await initCohortLogic({ id: 1 })

            // Set custom columns via setQuery
            const customColumns = ['person_display_name -- Person', 'id', 'created_at', 'properties.$browser']
            const testQuery: DataTableNode = {
                kind: NodeKind.DataTableNode,
                source: {
                    kind: NodeKind.ActorsQuery,
                    fixedProperties: [
                        { type: PropertyFilterType.Cohort, key: 'id', value: 1, operator: PropertyOperator.In },
                    ],
                    select: customColumns,
                },
                full: true,
                showPropertyFilter: false,
                showEventFilter: false,
            }
            await expectLogic(logic, () => {
                logic.actions.setQuery(testQuery)
            })
                .toDispatchActions(['setQuery'])
                .toMatchValues({
                    query: testQuery,
                })

            // Now call setCohort (simulating what happens after saving)
            await expectLogic(logic, () => {
                logic.actions.setCohort(mockCohort)
            })
                .toDispatchActions(['setCohort'])
                .toMatchValues({
                    query: partial({
                        source: partial({
                            select: customColumns, // Custom columns should be preserved
                        }),
                    }),
                })
        })

        it('uses default columns when no custom columns have been set', async () => {
            await initCohortLogic({ id: 1 })

            // Call setCohort without setting custom columns first
            await expectLogic(logic, () => {
                logic.actions.setCohort(mockCohort)
            })
                .toDispatchActions(['setCohort'])
                .toMatchValues({
                    query: partial({
                        source: partial({
                            // For non-static cohorts, default is without the delete column
                            select: ['person_display_name -- Person', 'id', 'created_at'],
                        }),
                    }),
                })
        })

        it('preserves custom columns after saving cohort (simulating saveCohort flow)', async () => {
            await initCohortLogic({ id: 1 })

            // First, set the cohort (this happens on initial load via fetchCohort)
            await expectLogic(logic).toFinishAllListeners()

            // User configures custom columns via the "Configure columns" UI
            const customColumns = ['person_display_name -- Person', 'id', 'properties.$browser', 'properties.$os']
            const testQuery: DataTableNode = {
                kind: NodeKind.DataTableNode,
                source: {
                    kind: NodeKind.ActorsQuery,
                    fixedProperties: [
                        { type: PropertyFilterType.Cohort, key: 'id', value: 1, operator: PropertyOperator.In },
                    ],
                    select: customColumns,
                },
                full: true,
                showPropertyFilter: false,
                showEventFilter: false,
            }
            await expectLogic(logic, () => {
                logic.actions.setQuery(testQuery)
            }).toDispatchActions(['setQuery'])

            // Verify custom columns are set
            expect((logic.values.query.source as ActorsQuery).select).toEqual(customColumns)

            // User saves the cohort - this triggers setCohort with the updated cohort from API
            // (simulating what happens in saveCohort loader after API call)
            await expectLogic(logic, () => {
                logic.actions.setCohort({
                    ...mockCohort,
                    is_calculating: false,
                    last_calculation: '2024-01-01T00:00:00Z',
                })
            }).toDispatchActions(['setCohort'])

            // Custom columns should still be preserved after save
            expect((logic.values.query.source as ActorsQuery).select).toEqual(customColumns)
        })

        const defaultColumns = ['person_display_name -- Person', 'id', 'created_at']
        const customColumns = [...defaultColumns, 'properties.$browser']

        it.each([
            ['the same cohort restores the persisted columns', 1, customColumns],
            ["another cohort ignores the first cohort's columns and uses defaults", 2, defaultColumns],
        ])('after a refresh (remount), %s', async (_name, remountId, expectedSelect) => {
            await initCohortLogic({ id: 1 })

            await expectLogic(logic, () => {
                logic.actions.setQuery({
                    ...logic.values.query,
                    source: { ...(logic.values.query.source as ActorsQuery), select: customColumns },
                } as DataTableNode)
            }).toDispatchActions(['setQuery'])

            // Simulate a refresh: tear down and rebuild the logic
            logic.unmount()
            logic = cohortEditLogic({ id: remountId })
            logic.mount()
            await expectLogic(logic).toFinishAllListeners()

            expect((logic.values.effectiveQuery.source as ActorsQuery).select).toEqual(expectedSelect)
        })

        it('pins the cohort filter to the saved cohort after a draft is saved', async () => {
            await initCohortLogic({ id: 'new' })
            expect((logic.values.effectiveQuery.source as ActorsQuery).fixedProperties).toEqual([])

            await expectLogic(logic, () => {
                logic.actions.setCohort({ ...mockCohort, id: 42 })
            }).toDispatchActions(['setCohort'])

            expect((logic.values.effectiveQuery.source as ActorsQuery).fixedProperties).toEqual([
                { type: PropertyFilterType.Cohort, key: 'id', value: 42, operator: PropertyOperator.In },
            ])
        })

        it('does not carry columns from one unsaved draft cohort over to the next', async () => {
            await initCohortLogic({ id: 'new' })

            await expectLogic(logic, () => {
                logic.actions.setQuery({
                    ...logic.values.query,
                    source: { ...(logic.values.query.source as ActorsQuery), select: customColumns },
                } as DataTableNode)
            }).toDispatchActions(['setQuery'])

            // Abandon the draft and start a fresh one — both share the 'new' logic key
            logic.unmount()
            logic = cohortEditLogic({ id: 'new' })
            logic.mount()
            await expectLogic(logic).toFinishAllListeners()

            expect((logic.values.effectiveQuery.source as ActorsQuery).select).toEqual(defaultColumns)
        })
    })

    describe('cohort duplication', () => {
        it('duplicate static cohort as static', async () => {
            await initCohortLogic({ id: 1 })

            const staticCohort = {
                ...mockCohort,
                id: 1,
                name: 'Static Cohort',
                is_static: true,
            }

            const duplicatedCohort = {
                ...staticCohort,
                id: 2,
                name: 'Static Cohort (static copy)',
            }

            jest.spyOn(api, 'create').mockResolvedValue(duplicatedCohort)

            await expectLogic(logic, () => {
                logic.actions.setCohort(staticCohort)
                logic.actions.duplicateCohort(true)
            }).toFinishAllListeners()

            expect(api.create).toHaveBeenCalledWith('api/cohort', {
                is_static: true,
                name: 'Static Cohort (static copy)',
                query: {
                    kind: NodeKind.HogQLQuery,
                    query: 'SELECT person_id FROM static_cohort_people WHERE cohort_id = 1',
                },
            })
        })

        it('duplicate dynamic cohort as static', async () => {
            await initCohortLogic({ id: 1 })

            const dynamicCohort = {
                ...mockCohort,
                id: 1,
                name: 'Dynamic Cohort',
                is_static: false,
            }

            const duplicatedCohort = {
                ...dynamicCohort,
                id: 2,
                name: 'Dynamic Cohort (static copy)',
                is_static: true,
            }

            jest.spyOn(api, 'create').mockResolvedValue(duplicatedCohort)

            await expectLogic(logic, () => {
                logic.actions.setCohort(dynamicCohort)
                logic.actions.duplicateCohort(true)
            }).toFinishAllListeners()

            expect(api.create).toHaveBeenCalledWith('api/cohort', {
                is_static: true,
                name: 'Dynamic Cohort (static copy)',
                query: {
                    kind: NodeKind.HogQLQuery,
                    query: 'SELECT person_id FROM cohort_people WHERE cohort_id = 1',
                },
            })
        })

        it('duplicate dynamic cohort as dynamic', async () => {
            await initCohortLogic({ id: 1 })

            const dynamicCohort = {
                ...mockCohort,
                id: 1,
                name: 'Dynamic Cohort',
                is_static: false,
                filters: {
                    properties: {
                        type: FilterLogicalOperator.Or,
                        values: [
                            {
                                sort_key: 'mocked-uuid',
                                type: FilterLogicalOperator.Or,
                                values: [
                                    {
                                        sort_key: 'mocked-uuid',
                                        explicit_datetime: '-30d',
                                        type: BehavioralFilterKey.Behavioral,
                                        value: BehavioralEventType.PerformEvent,
                                        event_type: TaxonomicFilterGroupType.Events,
                                        time_value: 30,
                                        time_interval: TimeUnitType.Day,
                                        key: '$pageview',
                                    },
                                ],
                            },
                        ],
                    },
                },
            }

            await expectLogic(logic, () => {
                logic.actions.setCohort(dynamicCohort)
                logic.actions.duplicateCohort(false)
            })
                .toFinishAllListeners()
                .toMatchValues({
                    // The duplication should complete without errors
                    cohort: partial(dynamicCohort),
                })
        }, 15000)
    })

    describe('active tab URL routing', () => {
        beforeEach(async () => {
            await initCohortLogic({ id: 1 })
            router.actions.replace(urls.cohort(1))
        })

        it('defaults to overview when no hash is set', async () => {
            await expectLogic(logic).toMatchValues({ activeTab: 'overview' })
        })

        it('writes #tab=history when switching to history', async () => {
            await expectLogic(logic, () => {
                logic.actions.setActiveTab('history')
            }).toFinishAllListeners()
            expect(router.values.hashParams.tab).toBe('history')
        })

        it('strips the tab key from the hash when switching back to overview', async () => {
            logic.actions.setActiveTab('history')
            await expectLogic(logic).toFinishAllListeners()
            expect(router.values.hashParams.tab).toBe('history')

            await expectLogic(logic, () => {
                logic.actions.setActiveTab('overview')
            }).toFinishAllListeners()
            expect(router.values.hashParams.tab).toBeUndefined()
        })

        it('reads the tab from the URL on navigation', async () => {
            router.actions.replace(urls.cohort(1), {}, { tab: 'history' })
            await expectLogic(logic).toFinishAllListeners().toMatchValues({ activeTab: 'history' })
        })

        it('falls back to overview when the hash tab value is unrecognized', async () => {
            router.actions.replace(urls.cohort(1), {}, { tab: 'garbage' })
            await expectLogic(logic).toFinishAllListeners().toMatchValues({ activeTab: 'overview' })
        })
    })

    describe('new cohort hash hygiene', () => {
        it('clears a stale #tab=history hash on mount and resets activeTab to overview', async () => {
            router.actions.replace(urls.cohort('new'), {}, { tab: 'history' })
            await initCohortLogic({ id: 'new' })
            expect(router.values.hashParams.tab).toBeUndefined()
            // Without resetting activeTab, the user would land on a blank screen for new cohorts:
            // overview is hidden via `display:none` while history requires a saved cohort to render.
            expect(logic.values.activeTab).toBe('overview')
        })
    })

    describe('filter out test accounts', () => {
        it('setFilterTestAccounts toggles the flag in filters', async () => {
            await initCohortLogic({ id: 'new' })
            await expectLogic(logic, () => {
                logic.actions.setFilterTestAccounts(true)
            }).toMatchValues({
                cohort: partial({ filters: partial({ filterTestAccounts: true }) }),
            })
        })

        it('setOuterGroupsType preserves the filterTestAccounts flag', async () => {
            // Regression guard: setOuterGroupsType used to rebuild `filters` from scratch, dropping
            // sibling keys like filterTestAccounts.
            await initCohortLogic({ id: 'new' })
            await expectLogic(logic, () => {
                logic.actions.setFilterTestAccounts(true)
                logic.actions.setOuterGroupsType(FilterLogicalOperator.And)
            }).toMatchValues({
                cohort: partial({
                    filters: partial({
                        filterTestAccounts: true,
                        properties: partial({ type: FilterLogicalOperator.And }),
                    }),
                }),
            })
        })
    })
})