: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
perf(cohorts): keep the cohort editor and persons logic off the shell (#127262)
Paul D'Ambraace8c476dfb6
diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex d5571e39ab0b..38a3421d9083 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -162,6 +162,10 @@ const ROOTS = [// The login scene's logics. Shell code reads the login redirect from lib/utils/loginRedirect.'src/scenes/authentication/auth/loginLogic.ts','src/scenes/authentication/shared/passkeyLogic.ts',+ // The cohort criteria normalizer belongs to the cohort scenes. It pulls in the cohort row editor.+ 'src/scenes/cohorts/CohortFilters/constants.tsx',+ // The persons scene loads its own logic. The shared cohorts model has no reason to import it.+ 'products/persons/frontend/logics/personsLogic.tsx',// The surveys scene constants hold the question type tables. lib/api reads its page size from lib/constants.'src/scenes/surveys/constants.tsx',// The rich text editor stack is for the scenes that edit text. Rendered markdown needs none of it.diff --git a/frontend/bin/layer-baseline.txt b/frontend/bin/layer-baseline.txtindex 0dd6e95b87a9..6cd80b398f5f 100644--- a/frontend/bin/layer-baseline.txt+++ b/frontend/bin/layer-baseline.txt@@ -310,9 +310,6 @@ frontend/src/lib/utils/eventUsageLogic.ts -> products/experiments/frontend/experfrontend/src/lib/utils/events.ts -> frontend/src/taxonomy/taxonomy.tsxfrontend/src/loadPostHogJS.tsx -> products/webmcp/frontend/webmcpToolError.tsfrontend/src/models/cohortsModel.ts -> frontend/src/exporter/exporterViewLogic.ts-frontend/src/models/cohortsModel.ts -> frontend/src/scenes/cohorts/CohortFilters/constants.tsx-frontend/src/models/cohortsModel.ts -> frontend/src/scenes/cohorts/CohortFilters/types.ts-frontend/src/models/cohortsModel.ts -> products/persons/frontend/logics/personsLogic.tsxfrontend/src/models/insightsModel.tsx -> frontend/src/scenes/insights/utils/api.tsfrontend/src/models/notebooksModel.ts -> frontend/src/scenes/analytics/analyticsBackLink.tsfrontend/src/models/notebooksModel.ts -> frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.tsdiff --git a/frontend/src/models/cohortsModel.test.ts b/frontend/src/models/cohortsModel.test.tsindex caea9c418f0f..89ec33623950 100644--- a/frontend/src/models/cohortsModel.test.ts+++ b/frontend/src/models/cohortsModel.test.ts@@ -11,7 +11,7 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { CohortType, FilterLogicalOperator } from '~/types'-import { cohortsModel, getReferencedCohortIds, processCohort } from './cohortsModel'+import { cohortsModel, getReferencedCohortIds } from './cohortsModel'jest.unmock('lib/utils/concurrencyController')@@ -97,9 +97,6 @@ describe('cohortsModel', () => {await expectLogic(logic, () => logic.actions.loadAllCohorts()).toDispatchActions(['loadAllCohortsSuccess'])expect(logic.values.allCohorts.results.map(({ id }) => id)).toEqual([1, 2])-- await expectLogic(logic, () => logic.actions.loadCohorts()).toDispatchActions(['loadCohortsSuccess'])- expect(logic.values.cohorts.results.map(({ id }) => id)).toEqual([1, 2])})it('sets polling timeout for calculating cohorts when on cohorts page', async () => {@@ -473,158 +470,4 @@ describe('cohortsModel', () => {})})})-- describe('processCohort', () => {- it.each([- {- name: 'wraps flat criteria into nested group format',- cohort: {- id: 3,- name: 'Flat format cohort',- count: 0,- groups: [],- is_calculating: false,- is_static: false,- filters: {- properties: {- type: FilterLogicalOperator.And,- values: [- {- type: 'behavioral',- key: 'purchase',- value: 'performed_event',- event_type: 'events',- operator: 'gte',- operator_value: 2,- time_value: 30,- time_interval: 'day',- negation: false,- },- ],- },- },- } as CohortType,- expectedType: FilterLogicalOperator.And,- expectedCriteriaKey: 'purchase',- },- {- name: 'leaves already nested criteria unchanged',- cohort: {- id: 4,- name: 'Nested format cohort',- count: 0,- groups: [],- is_calculating: false,- is_static: false,- filters: {- properties: {- type: FilterLogicalOperator.And,- values: [- {- type: FilterLogicalOperator.And,- values: [- {- type: 'behavioral',- key: 'purchase',- value: 'performed_event',- event_type: 'events',- explicit_datetime: '-30d',- },- ],- },- ],- },- },- } as CohortType,- expectedType: FilterLogicalOperator.And,- expectedCriteriaKey: 'purchase',- },- ])('$name', ({ cohort, expectedType, expectedCriteriaKey }) => {- const result = processCohort(cohort)- const group = result.filters.properties.values[0]- expect(group).toHaveProperty('type', expectedType)- expect(group).toHaveProperty('values')- expect((group as any).values).toHaveLength(1)- expect((group as any).values[0]).toMatchObject({- type: 'behavioral',- key: expectedCriteriaKey,- })- })-- it('restores a saved person_metadata criterion to editor format (value -> value_property)', () => {- const cohort = {- id: 5,- name: 'First seen cohort',- count: 0,- groups: [],- is_calculating: false,- is_static: false,- filters: {- properties: {- type: FilterLogicalOperator.And,- values: [- {- type: 'person_metadata',- key: 'created_at',- operator: 'is_date_after',- value: '2024-01-01',- negation: false,- },- ],- },- },- } as unknown as CohortType-- const result = processCohort(cohort)- const group = result.filters.properties.values[0]- // value carries the behavioral row key the editor renders against; the actual- // filter value moves to value_property. Without this, criteriaToBehavioralFilterType- // returns the raw date and ROWS[date] is undefined, crashing CohortCriteriaRowBuilder.- expect((group as any).values[0]).toMatchObject({- type: 'person_metadata',- key: 'created_at',- value: 'have_property',- value_property: '2024-01-01',- })- })-- it('canonicalizes a behavioral value the backend only accepts as an alias', () => {- const cohort = {- id: 6,- name: 'Aliased criterion cohort',- count: 0,- groups: [],- is_calculating: false,- is_static: false,- filters: {- properties: {- type: FilterLogicalOperator.And,- values: [- {- type: 'behavioral',- key: 'purchase',- value: 'performed_event_multiple_times',- event_type: 'events',- operator: 'gte',- operator_value: 2,- time_value: 30,- time_interval: 'day',- },- ],- },- },- } as unknown as CohortType-- const result = processCohort(cohort)- const group = result.filters.properties.values[0]- // The alias has no ROWS entry, so leaving it verbatim renders the criterion as- // unsupported even though the backend resolves and queries it. explicit_datetime only- // gets converted once the value is canonical, and without it validateGroup rejects the- // row for a missing time window the criterion already carried.- expect((group as any).values[0]).toMatchObject({- value: 'performed_event_multiple',- explicit_datetime: '-30d',- })- })- })})diff --git a/frontend/src/models/cohortsModel.ts b/frontend/src/models/cohortsModel.tsindex 748175ad8351..7991ab9cb95c 100644--- a/frontend/src/models/cohortsModel.ts+++ b/frontend/src/models/cohortsModel.ts@@ -13,30 +13,19 @@ import {import { loaders } from 'kea-loaders'import { router } from 'kea-router'import type { LocationChangedPayload } from 'kea-router/lib/types'-import { v4 as uuidv4 } from 'uuid'import api, { CountedPaginatedResponse } from 'lib/api'import { ConcurrencyController } from 'lib/utils/concurrencyController'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { permanentlyMount } from 'lib/utils/kea-logic-builders'-import { COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME } from 'scenes/cohorts/CohortFilters/constants'-import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { getCurrentExporterData } from '~/exporter/exporterViewLogic'import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'-import {- AnyCohortCriteriaType,- BehavioralCohortType,- BehavioralEventType,- CohortCriteriaGroupFilter,- CohortType,- FilterLogicalOperator,-} from '~/types'+import { CohortType, FilterLogicalOperator } from '~/types'import * as cohortsApi from 'products/cohorts/frontend/generated/api'-import { personsLogic } from 'products/persons/frontend/logics/personsLogic'import type { TeamPublicType, TeamType } from '../types'@@ -113,101 +102,12 @@ async function loadAllCohortPages<T>(return { count, results }}-export function processCohort(cohort: CohortType): CohortType {- return {- ...cohort,-- /* Populate value_property with value and overwrite value with corresponding behavioral filter type */- filters: {- properties: {- ...cohort.filters.properties,- values: (cohort.filters.properties?.values?.map((group) =>- 'values' in group- ? {- ...group,- values: (group.values as AnyCohortCriteriaType[]).map((c) => processCohortCriteria(c)),- sort_key: uuidv4(),- }- : // Wrap flat API criteria (no nested `values` array) into a group- // so CohortCriteriaGroups can render them via isCohortCriteriaGroup()- {- type: FilterLogicalOperator.And,- values: [processCohortCriteria(group as AnyCohortCriteriaType)],- sort_key: uuidv4(),- }- ) ?? []) as CohortCriteriaGroupFilter[] | AnyCohortCriteriaType[],- },- },- }-}--function convertTimeValueToRelativeTime(criteria: AnyCohortCriteriaType): string | undefined {- const timeValue = criteria?.time_value- const timeInterval = criteria?.time_interval-- if (timeValue && timeInterval) {- return `-${timeValue}${timeInterval[0]}`- }-}--// Mirrors BEHAVIORAL_VALUE_ALIASES in posthog/models/property/property.py: values older cohort-// builders stored that the backend still resolves to a canonical behavioral type. The API hands-// them back verbatim, so without this the frontend treats them as unmapped and renders no fields.-// A Map, not an object literal: a stored value of 'constructor' or 'toString' resolves to an-// Object.prototype member on a plain lookup.-const BEHAVIORAL_VALUE_ALIASES = new Map<string, BehavioralEventType>([- ['performed_event_multiple_times', BehavioralEventType.PerformMultipleEvents],-])--function processCohortCriteria(criteria: AnyCohortCriteriaType): AnyCohortCriteriaType {- if (!criteria.type) {- return criteria- }-- const processedCriteria = { ...criteria }-- if (criteria.type === BehavioralFilterKey.Behavioral && typeof criteria.value === 'string') {- processedCriteria.value = BEHAVIORAL_VALUE_ALIASES.get(criteria.value) ?? criteria.value- }-- if (- [BehavioralFilterKey.Cohort, BehavioralFilterKey.Person, BehavioralFilterKey.PersonMetadata].includes(- criteria.type- ) &&- !('value_property' in criteria)- ) {- processedCriteria.value_property = criteria.value- processedCriteria.value =- criteria.type === BehavioralFilterKey.Cohort- ? BehavioralCohortType.InCohort- : BehavioralEventType.HaveProperty- }-- if (- [BehavioralFilterKey.Behavioral].includes(criteria.type) &&- !('explicit_datetime' in criteria) &&- processedCriteria.value &&- COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME.includes(processedCriteria.value)- ) {- processedCriteria.explicit_datetime = convertTimeValueToRelativeTime(criteria)- }-- if (processedCriteria.sort_key == null) {- processedCriteria.sort_key = uuidv4()- }-- return processedCriteria-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface cohortsModelValues {currentTeam: TeamPublicType | TeamType | null // teamLogicallCohorts: CountedPaginatedResponse<CohortType>allCohortsLoading: boolean- cohorts: CountedPaginatedResponse<CohortType>cohortsById: Partial<Record<number | string, CohortType>>- cohortsLoading: boolean- count: numberpollTimeout: number | null}@@ -261,7 +161,6 @@ export interface cohortsModelActions {allCohorts: CountedPaginatedResponse<CohortType>payload?: any}- loadCohorts: () => anyloadCohortsByIds: ({ ids }: { ids: number[] }) => {ids: number[]}@@ -283,20 +182,6 @@ export interface cohortsModelActions {ids: number[]}}- loadCohortsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadCohortsSuccess: (- cohorts: CountedPaginatedResponse<CohortType>,- payload?: any- ) => {- cohorts: CountedPaginatedResponse<CohortType>- payload?: any- }setPollTimeout: (pollTimeout: number | null) => {pollTimeout: number | null}@@ -309,7 +194,6 @@ export interface cohortsModelActions {export interface cohortsModelMeta {__keaTypeGenInternalSelectorTypes: {cohortsById: (allCohorts: CountedPaginatedResponse<CohortType>) => Partial<Record<number | string, CohortType>>- count: (cohorts: CountedPaginatedResponse<CohortType>) => number}}@@ -335,22 +219,6 @@ export const cohortsModel = kea<cohortsModelType>([hydrateAllCohortsFromExport: (cohorts: Pick<CohortType, 'id' | 'name'>[]) => ({ cohorts }),})),loaders(({ actions, values, cache }) => ({- cohorts: {- __default: { count: 0, results: [] } as CountedPaginatedResponse<CohortType>,- loadCohorts: async () => {- if (!isAuthenticatedTeam(values.currentTeam)) {- return values.cohorts- }- const projectId = String(values.currentTeam.project_id)- const response = await loadAllCohortPages((params) => cohortsApi.cohortsList(projectId, params))- personsLogic.findMounted({ syncWithUrl: true })?.actions.loadCohorts()- return {- count: response.count,- // The shared cache still exposes the legacy shape to its consumers.- results: response.results.map((cohort) => processCohort(cohort as unknown as CohortType)),- }- },- },allCohorts: {__default: { count: 0, results: [] } as CountedPaginatedResponse<CohortType>,loadCohortsByIds: async ({ ids }: { ids: number[] }) => {@@ -429,39 +297,8 @@ export const cohortsModel = kea<cohortsModelType>([setPollTimeout: (_, { pollTimeout }) => pollTimeout,},],- cohorts: {- updateCohort: (state, { cohort }) => {- if (!cohort) {- return state- }- return {- ...state,- results: state.results.map((existingCohort) =>- existingCohort.id === cohort.id ? cohort : existingCohort- ),- }- },- cohortCreated: (state, { cohort }) => {- if (!cohort) {- return state- }- return {- ...state,- results: [cohort, ...state.results],- }- },- deleteCohort: (state, { cohort }) => {- if (!cohort.id) {- return state- }- return {- ...state,- results: state.results.filter((c) => c.id !== cohort.id),- }- },- },// Update allCohorts state to keep breadcrumbs in sync when cohorts are modified- // The cohortsById selector depends on allCohorts, not cohorts+ // The cohortsById selector depends on allCohortsallCohorts: {cacheCohort: (state, { cohort }) => ({...state,@@ -523,7 +360,6 @@ export const cohortsModel = kea<cohortsModelType>([(allCohorts: CountedPaginatedResponse<CohortType>): Partial<Record<string | number, CohortType>> =>Object.fromEntries(allCohorts.results.map((cohort) => [cohort.id, cohort])),],- count: [(selectors) => [selectors.cohorts], (cohorts: CountedPaginatedResponse<CohortType>) => cohorts.count],}),listeners(({ actions, values, cache }) => ({loadAllCohortsFailure: () => {@@ -538,13 +374,6 @@ export const cohortsModel = kea<cohortsModelType>([actions.loadAllCohorts()}},- loadCohortsSuccess: async ({ cohorts }: { cohorts: CountedPaginatedResponse<CohortType> }) => {- const is_calculating = cohorts.results.filter((cohort) => cohort.is_calculating).length > 0- if (!is_calculating || !router.values.location.pathname.includes(urls.cohorts())) {- return- }- actions.setPollTimeout(window.setTimeout(actions.loadCohorts, POLL_TIMEOUT))- },loadAllCohortsSuccess: async ({ allCohorts }: { allCohorts: CountedPaginatedResponse<CohortType> }) => {const is_calculating = allCohorts.results.filter((cohort) => cohort.is_calculating).length > 0if (!is_calculating || !router.values.location.pathname.includes(urls.cohorts())) {@@ -558,7 +387,7 @@ export const cohortsModel = kea<cohortsModelType>([object: cohort,callback: (undo) => {// Refresh `allCohorts` (the source for `cohortsById`) so an undo restores- // the row's name to breadcrumbs and pickers, not just the `cohorts` list.+ // the row's name to breadcrumbs and pickers.actions.loadAllCohorts()if (cohort.id && cohort.id !== 'new') {if (undo) {diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.tsindex 12e612ded027..c3955d6ce509 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts@@ -50,11 +50,12 @@ import {cohortCsvMaxBytes,cohortCsvTooLargeMessage,} from 'scenes/cohorts/cohortUtils'+import { processCohort } from 'scenes/cohorts/processCohort'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'-import { cohortsModel, processCohort } from '~/models/cohortsModel'+import { cohortsModel } from '~/models/cohortsModel'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { isDataTableNode } from '~/queries/schema/node-guards'diff --git a/frontend/src/scenes/cohorts/cohortsSceneLogic.ts b/frontend/src/scenes/cohorts/cohortsSceneLogic.tsindex f2530c93a31a..ebcd196145f2 100644--- a/frontend/src/scenes/cohorts/cohortsSceneLogic.ts+++ b/frontend/src/scenes/cohorts/cohortsSceneLogic.ts@@ -10,11 +10,11 @@ import { exportsLogic } from 'lib/components/ExportButton/exportsLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { objectsEqual } from 'lib/utils/objects'+import { processCohort } from 'scenes/cohorts/processCohort'import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'import { deleteFromTree, refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'-import { processCohort } from '~/models/cohortsModel'import { ActivityScope, Breadcrumb, CohortType, ExporterFormat } from '~/types'import { personsLogic } from 'products/persons/frontend/logics/personsLogic'diff --git a/frontend/src/scenes/cohorts/processCohort.test.ts b/frontend/src/scenes/cohorts/processCohort.test.tsnew file mode 100644index 000000000000..607feefa33b2--- /dev/null+++ b/frontend/src/scenes/cohorts/processCohort.test.ts@@ -0,0 +1,157 @@+import { CohortType, FilterLogicalOperator } from '~/types'++import { processCohort } from './processCohort'++describe('processCohort', () => {+ it.each([+ {+ name: 'wraps flat criteria into nested group format',+ cohort: {+ id: 3,+ name: 'Flat format cohort',+ count: 0,+ groups: [],+ is_calculating: false,+ is_static: false,+ filters: {+ properties: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: 'behavioral',+ key: 'purchase',+ value: 'performed_event',+ event_type: 'events',+ operator: 'gte',+ operator_value: 2,+ time_value: 30,+ time_interval: 'day',+ negation: false,+ },+ ],+ },+ },+ } as CohortType,+ expectedType: FilterLogicalOperator.And,+ expectedCriteriaKey: 'purchase',+ },+ {+ name: 'leaves already nested criteria unchanged',+ cohort: {+ id: 4,+ name: 'Nested format cohort',+ count: 0,+ groups: [],+ is_calculating: false,+ is_static: false,+ filters: {+ properties: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: 'behavioral',+ key: 'purchase',+ value: 'performed_event',+ event_type: 'events',+ explicit_datetime: '-30d',+ },+ ],+ },+ ],+ },+ },+ } as CohortType,+ expectedType: FilterLogicalOperator.And,+ expectedCriteriaKey: 'purchase',+ },+ ])('$name', ({ cohort, expectedType, expectedCriteriaKey }) => {+ const result = processCohort(cohort)+ const group = result.filters.properties.values[0]+ expect(group).toHaveProperty('type', expectedType)+ expect(group).toHaveProperty('values')+ expect((group as any).values).toHaveLength(1)+ expect((group as any).values[0]).toMatchObject({+ type: 'behavioral',+ key: expectedCriteriaKey,+ })+ })++ it('restores a saved person_metadata criterion to editor format (value -> value_property)', () => {+ const cohort = {+ id: 5,+ name: 'First seen cohort',+ count: 0,+ groups: [],+ is_calculating: false,+ is_static: false,+ filters: {+ properties: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: 'person_metadata',+ key: 'created_at',+ operator: 'is_date_after',+ value: '2024-01-01',+ negation: false,+ },+ ],+ },+ },+ } as unknown as CohortType++ const result = processCohort(cohort)+ const group = result.filters.properties.values[0]+ // value carries the behavioral row key the editor renders against; the actual+ // filter value moves to value_property. Without this, criteriaToBehavioralFilterType+ // returns the raw date and ROWS[date] is undefined, crashing CohortCriteriaRowBuilder.+ expect((group as any).values[0]).toMatchObject({+ type: 'person_metadata',+ key: 'created_at',+ value: 'have_property',+ value_property: '2024-01-01',+ })+ })++ it('canonicalizes a behavioral value the backend only accepts as an alias', () => {+ const cohort = {+ id: 6,+ name: 'Aliased criterion cohort',+ count: 0,+ groups: [],+ is_calculating: false,+ is_static: false,+ filters: {+ properties: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: 'behavioral',+ key: 'purchase',+ value: 'performed_event_multiple_times',+ event_type: 'events',+ operator: 'gte',+ operator_value: 2,+ time_value: 30,+ time_interval: 'day',+ },+ ],+ },+ },+ } as unknown as CohortType++ const result = processCohort(cohort)+ const group = result.filters.properties.values[0]+ // The alias has no ROWS entry, so leaving it verbatim renders the criterion as+ // unsupported even though the backend resolves and queries it. explicit_datetime only+ // gets converted once the value is canonical, and without it validateGroup rejects the+ // row for a missing time window the criterion already carried.+ expect((group as any).values[0]).toMatchObject({+ value: 'performed_event_multiple',+ explicit_datetime: '-30d',+ })+ })+})diff --git a/frontend/src/scenes/cohorts/processCohort.ts b/frontend/src/scenes/cohorts/processCohort.tsnew file mode 100644index 000000000000..125ca0f2f93c--- /dev/null+++ b/frontend/src/scenes/cohorts/processCohort.ts@@ -0,0 +1,99 @@+import { v4 as uuidv4 } from 'uuid'++import { COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME } from 'scenes/cohorts/CohortFilters/constants'+import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'++import {+ AnyCohortCriteriaType,+ BehavioralCohortType,+ BehavioralEventType,+ CohortCriteriaGroupFilter,+ CohortType,+ FilterLogicalOperator,+} from '~/types'++export function processCohort(cohort: CohortType): CohortType {+ return {+ ...cohort,++ /* Populate value_property with value and overwrite value with corresponding behavioral filter type */+ filters: {+ properties: {+ ...cohort.filters.properties,+ values: (cohort.filters.properties?.values?.map((group) =>+ 'values' in group+ ? {+ ...group,+ values: (group.values as AnyCohortCriteriaType[]).map((c) => processCohortCriteria(c)),+ sort_key: uuidv4(),+ }+ : // Wrap flat API criteria (no nested `values` array) into a group+ // so CohortCriteriaGroups can render them via isCohortCriteriaGroup()+ {+ type: FilterLogicalOperator.And,+ values: [processCohortCriteria(group as AnyCohortCriteriaType)],+ sort_key: uuidv4(),+ }+ ) ?? []) as CohortCriteriaGroupFilter[] | AnyCohortCriteriaType[],+ },+ },+ }+}++function convertTimeValueToRelativeTime(criteria: AnyCohortCriteriaType): string | undefined {+ const timeValue = criteria?.time_value+ const timeInterval = criteria?.time_interval++ if (timeValue && timeInterval) {+ return `-${timeValue}${timeInterval[0]}`+ }+}++// Mirrors BEHAVIORAL_VALUE_ALIASES in posthog/models/property/property.py: values older cohort+// builders stored that the backend still resolves to a canonical behavioral type. The API hands+// them back verbatim, so without this the frontend treats them as unmapped and renders no fields.+// A Map, not an object literal: a stored value of 'constructor' or 'toString' resolves to an+// Object.prototype member on a plain lookup.+const BEHAVIORAL_VALUE_ALIASES = new Map<string, BehavioralEventType>([+ ['performed_event_multiple_times', BehavioralEventType.PerformMultipleEvents],+])++function processCohortCriteria(criteria: AnyCohortCriteriaType): AnyCohortCriteriaType {+ if (!criteria.type) {+ return criteria+ }++ const processedCriteria = { ...criteria }++ if (criteria.type === BehavioralFilterKey.Behavioral && typeof criteria.value === 'string') {+ processedCriteria.value = BEHAVIORAL_VALUE_ALIASES.get(criteria.value) ?? criteria.value+ }++ if (+ [BehavioralFilterKey.Cohort, BehavioralFilterKey.Person, BehavioralFilterKey.PersonMetadata].includes(+ criteria.type+ ) &&+ !('value_property' in criteria)+ ) {+ processedCriteria.value_property = criteria.value+ processedCriteria.value =+ criteria.type === BehavioralFilterKey.Cohort+ ? BehavioralCohortType.InCohort+ : BehavioralEventType.HaveProperty+ }++ if (+ [BehavioralFilterKey.Behavioral].includes(criteria.type) &&+ !('explicit_datetime' in criteria) &&+ processedCriteria.value &&+ COHORT_EVENT_TYPES_WITH_EXPLICIT_DATETIME.includes(processedCriteria.value)+ ) {+ processedCriteria.explicit_datetime = convertTimeValueToRelativeTime(criteria)+ }++ if (processedCriteria.sort_key == null) {+ processedCriteria.sort_key = uuidv4()+ }++ return processedCriteria+}