: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
feat(workflows): pick a cohort join or leave in conversion goals and waits (#122554)
Harley Alexanderfc52b42dbe85
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsxindex 8ba367b54a5d..c749704d8795 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepWaitUntilCondition.tsx@@ -1,14 +1,17 @@import { Node } from '@xyflow/react'import { useActions } from 'kea'-import { IconCursor, IconPerson } from '@posthog/icons'+import { IconCursor, IconPeople, IconPerson } from '@posthog/icons'import { LemonDivider, LemonLabel } from '@posthog/lemon-ui'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { workflowLogic } from '../../workflowLogic'import { HogFlowEventFilters, HogFlowPropertyFilters } from '../filters/HogFlowFilters'import { HogFlowAction } from '../types'+import { joinCohortMembershipEntry, splitCohortMembershipEntry } from './components/cohortMembershipEvent'+import { CohortMembershipEventPicker } from './components/CohortMembershipEventPicker'import { HogFlowDuration } from './components/HogFlowDuration'import { StepSchemaErrors } from './components/StepSchemaErrors'import { useDebouncedNameInput } from './utils'@@ -27,7 +30,9 @@ export function StepWaitUntilConditionConfiguration({partialSetWorkflowActionConfig(action.id, { condition: updatedCondition }))- const eventFilters = events?.[0]?.filters ?? {}+ const cohortConditionsEnabled = useFeatureFlag('WORKFLOWS_COHORT_CONDITIONS')+ const { eventEntries, cohort } = splitCohortMembershipEntry(events)+ const eventFilters = eventEntries[0]?.filters ?? {}return (<>@@ -46,7 +51,7 @@ export function StepWaitUntilConditionConfiguration({filters={eventFilters}setFilters={(newFilters) =>partialSetWorkflowActionConfig(action.id, {- events: newFilters ? [{ filters: newFilters }] : undefined,+ events: joinCohortMembershipEntry(newFilters ? [{ filters: newFilters }] : [], cohort),})}typeKey="workflow-wait-until-event"@@ -55,6 +60,36 @@ export function StepWaitUntilConditionConfiguration({/></div>+ {cohortConditionsEnabled || cohort ? (+ <>+ <div className="flex items-center gap-4 my-2">+ <div className="flex-1 border-t border-border" />+ <span className="text-xs text-tertiary uppercase tracking-wide">or</span>+ <div className="flex-1 border-t border-border" />+ </div>++ <div className="flex flex-col gap-3">+ <span className="flex gap-1">+ <IconPeople className="text-lg" />+ <span className="text-md font-semibold">Cohort change to wait for</span>+ </span>+ <span className="text-xs text-muted">+ The workflow continues on the matched path when the person joins or leaves this cohort. Only+ realtime cohorts report these changes.+ </span>+ <CohortMembershipEventPicker+ value={cohort}+ onChange={(nextCohort) =>+ partialSetWorkflowActionConfig(action.id, {+ events: joinCohortMembershipEntry(eventEntries, nextCohort),+ })+ }+ dataAttr="workflow-wait-until"+ />+ </div>+ </>+ ) : null}+<div className="flex items-center gap-4 my-2"><div className="flex-1 border-t border-border" /><span className="text-xs text-tertiary uppercase tracking-wide">or</span>diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/CohortMembershipEventPicker.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/CohortMembershipEventPicker.tsxnew file mode 100644index 000000000000..0767563f37ed--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/CohortMembershipEventPicker.tsx@@ -0,0 +1,78 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { LemonSegmentedButton } from '@posthog/lemon-ui'++import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'++import { cohortsModel } from '~/models/cohortsModel'++import { CohortTypeEnumApi } from 'products/cohorts/frontend/generated/api.schemas'++import { CohortMembershipEventValue } from './cohortMembershipEvent'++export interface CohortMembershipEventPickerProps {+ value: CohortMembershipEventValue | null+ onChange: (value: CohortMembershipEventValue | null) => void+ dataAttr: string+}++export function CohortMembershipEventPicker({+ value,+ onChange,+ dataAttr,+}: CohortMembershipEventPickerProps): JSX.Element {+ const { cohortsById } = useValues(cohortsModel)+ const { loadCohortsByIds } = useActions(cohortsModel)++ const cohortId = value?.cohortId+ useEffect(() => {+ if (cohortId) {+ loadCohortsByIds({ ids: [cohortId] })+ }+ }, [cohortId, loadCohortsByIds])++ // The cohorts endpoint returns cohort_type, which the shared CohortType does not declare.+ const cohort = cohortId ? (cohortsById[cohortId] as { cohort_type?: string | null } | undefined) : undefined+ // Only realtime cohorts emit membership changes, so any other cohort never converts or ends a wait.+ const notRealtime = !!cohort && cohort.cohort_type !== CohortTypeEnumApi.Realtime++ return (+ <div className="flex flex-col gap-1">+ <div className="flex flex-wrap gap-2 items-center">+ <TaxonomicPopover+ groupType={TaxonomicFilterGroupType.Cohorts}+ value={cohortId}+ onChange={(nextCohortId) =>+ onChange(+ nextCohortId+ ? { cohortId: Number(nextCohortId), transition: value?.transition ?? 'entered' }+ : null+ )+ }+ renderValue={(id) => <>{cohortsById[id]?.name ?? `Cohort ${id}`}</>}+ placeholder="Choose a cohort"+ allowClear+ data-attr={`${dataAttr}-cohort`}+ />+ {value ? (+ <LemonSegmentedButton+ size="small"+ value={value.transition}+ onChange={(transition) => onChange({ ...value, transition })}+ options={[+ { value: 'entered', label: 'Joins the cohort', 'data-attr': `${dataAttr}-joins` },+ { value: 'left', label: 'Leaves the cohort', 'data-attr': `${dataAttr}-leaves` },+ ]}+ />+ ) : null}+ </div>+ {notRealtime ? (+ <span className="text-xs text-danger">+ This cohort isn't realtime, so it never reports people joining or leaving. Choose a realtime cohort.+ </span>+ ) : null}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/ConversionGoalEditor.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/ConversionGoalEditor.tsxindex b831e6a67fbd..0941f7d4650c 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/ConversionGoalEditor.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/ConversionGoalEditor.tsx@@ -3,8 +3,11 @@ import { LemonLabel, Tooltip } from '@posthog/lemon-ui'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { HogFlowEventFilters, WORKFLOW_OPERATOR_ALLOWLIST } from '../../filters/HogFlowFilters'+import { joinCohortMembershipEntry, splitCohortMembershipEntry } from './cohortMembershipEvent'+import { CohortMembershipEventPicker } from './CohortMembershipEventPicker'import { HogFlowDuration, MAX_CONVERSION_WINDOW_FOR_DURATION_UNIT } from './HogFlowDuration'// Structural shape of a workflow conversion goal, compatible with both the frontend HogFlow@@ -26,7 +29,9 @@ export interface ConversionGoalEditorProps {const DEFAULT_CONVERSION_WINDOW = '90d'export function ConversionGoalEditor({ conversion, onChange, pageKey }: ConversionGoalEditorProps): JSX.Element {- const conversionEventFilters = conversion?.events?.[0]?.filters ?? {}+ const cohortConditionsEnabled = useFeatureFlag('WORKFLOWS_COHORT_CONDITIONS')+ const { eventEntries, cohort } = splitCohortMembershipEntry(conversion?.events)+ const conversionEventFilters = eventEntries[0]?.filters ?? {}const conversionWindow = conversion?.window ?? DEFAULT_CONVERSION_WINDOWreturn (@@ -58,7 +63,7 @@ export function ConversionGoalEditor({ conversion, onChange, pageKey }: ConversionChange({filters: [],...conversion,- events: newFilters ? [{ filters: newFilters }] : undefined,+ events: joinCohortMembershipEntry(newFilters ? [{ filters: newFilters }] : [], cohort),})}typeKey={`${pageKey}-event`}@@ -66,6 +71,27 @@ export function ConversionGoalEditor({ conversion, onChange, pageKey }: Conversi/></div>+ {cohortConditionsEnabled || cohort ? (+ <div className="flex flex-col gap-1 items-start w-full">+ <LemonLabel>Detect conversion from cohort membership</LemonLabel>+ <span className="text-xs text-muted">+ The person converts when they join or leave this cohort. Only realtime cohorts report these+ changes.+ </span>+ <CohortMembershipEventPicker+ value={cohort}+ onChange={(nextCohort) =>+ onChange({+ filters: [],+ ...conversion,+ events: joinCohortMembershipEntry(eventEntries, nextCohort),+ })+ }+ dataAttr={`${pageKey}-conversion`}+ />+ </div>+ ) : null}+<div className="flex flex-col gap-1 items-start"><span className="flex gap-1 items-center"><LemonLabel>Conversion window</LemonLabel>diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/cohortMembershipEvent.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/cohortMembershipEvent.test.tsnew file mode 100644index 000000000000..27a5f417e069--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/cohortMembershipEvent.test.ts@@ -0,0 +1,91 @@+import { joinCohortMembershipEntry, splitCohortMembershipEntry } from './cohortMembershipEvent'++describe('cohortMembershipEvent', () => {+ const pageviewEntry = { filters: { events: [{ id: '$pageview', name: '$pageview', type: 'events' }] } }++ it.each([+ ['a join next to an event entry', [pageviewEntry], { cohortId: 42, transition: 'entered' as const }],+ ['a leave on its own', [], { cohortId: 7, transition: 'left' as const }],+ ])('reads back %s', (_name, eventEntries, cohort) => {+ const stored = joinCohortMembershipEntry(eventEntries, cohort)++ expect(splitCohortMembershipEntry(stored)).toEqual({ eventEntries, cohort })+ })++ const cohortEvent = {+ id: '$cohort_membership_changed',+ type: 'events',+ properties: [+ { key: 'cohort_id', value: 42, operator: 'exact', type: 'event' },+ { key: 'status', value: 'entered', operator: 'exact', type: 'event' },+ ],+ }++ it.each([+ ['a second event', { filters: { events: [cohortEvent, pageviewEntry.filters.events[0]] } }],+ [+ 'an extra property filter',+ {+ filters: {+ events: [+ {+ ...cohortEvent,+ properties: [...cohortEvent.properties, { key: 'plan', value: 'pro', type: 'person' }],+ },+ ],+ },+ },+ ],+ [+ 'a negated cohort filter',+ {+ filters: {+ events: [+ {+ ...cohortEvent,+ properties: [+ { ...cohortEvent.properties[0], operator: 'is_not' },+ cohortEvent.properties[1],+ ],+ },+ ],+ },+ },+ ],+ [+ 'a person-scoped status filter',+ {+ filters: {+ events: [+ {+ ...cohortEvent,+ properties: [cohortEvent.properties[0], { ...cohortEvent.properties[1], type: 'person' }],+ },+ ],+ },+ },+ ],+ [+ 'a list of cohort ids',+ {+ filters: {+ events: [+ {+ ...cohortEvent,+ properties: [{ ...cohortEvent.properties[0], value: [42, 43] }, cohortEvent.properties[1]],+ },+ ],+ },+ },+ ],+ ])('leaves an API-written cohort entry with %s among the event entries', (_name, entry) => {+ expect(splitCohortMembershipEntry([entry])).toEqual({ eventEntries: [entry], cohort: null })+ })++ it.each([+ ['clearing the cohort keeps the event entry', [pageviewEntry], [pageviewEntry]],+ ['clearing both stores no entries', [], undefined],+ ])('%s', (_name, eventEntries, expected) => {+ expect(joinCohortMembershipEntry(eventEntries, null)).toEqual(expected)+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/cohortMembershipEvent.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/cohortMembershipEvent.tsnew file mode 100644index 000000000000..0947c0c7c4d9--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/cohortMembershipEvent.ts@@ -0,0 +1,89 @@+// pinned: the subscription matcher builds this event from realtime cohort membership changes.+// Renaming it breaks every saved conversion goal and wait step that uses a cohort.+export const COHORT_MEMBERSHIP_CHANGED_EVENT = '$cohort_membership_changed'++export type CohortTransition = 'entered' | 'left'++export interface CohortMembershipEventValue {+ cohortId: number+ transition: CohortTransition+}++export interface EventEntry {+ filters?: any+ name?: string+}++export function cohortMembershipEventEntry({ cohortId, transition }: CohortMembershipEventValue): EventEntry {+ return {+ filters: {+ events: [+ {+ id: COHORT_MEMBERSHIP_CHANGED_EVENT,+ name: COHORT_MEMBERSHIP_CHANGED_EVENT,+ type: 'events',+ order: 0,+ properties: [+ { key: 'cohort_id', value: cohortId, operator: 'exact', type: 'event' },+ { key: 'status', value: transition, operator: 'exact', type: 'event' },+ ],+ },+ ],+ },+ }+}++/**+ * Reads an entry only when it has exactly the shape the picker writes. Any other entry, for example one+ * written through the API with a second event or an extra filter, stays with the event filters, so that+ * saving from the picker cannot drop what it does not show.+ */+export function readCohortMembershipEventEntry(entry: EventEntry | undefined): CohortMembershipEventValue | null {+ const filters = entry?.filters+ const events = filters?.events ?? []+ if (events.length !== 1 || filters?.actions?.length || filters?.properties?.length) {+ return null+ }+ const [event] = events+ const properties: { key?: string; value?: unknown; operator?: string; type?: string }[] = event?.properties ?? []+ if (event?.id !== COHORT_MEMBERSHIP_CHANGED_EVENT || properties.length !== 2) {+ return null+ }+ // Rewriting a negated or person-scoped filter as an exact event match would change what the goal matches.+ if (properties.some((property) => property.operator !== 'exact' || property.type !== 'event')) {+ return null+ }+ const cohortValue = properties.find((property) => property.key === 'cohort_id')?.value+ const cohortId = typeof cohortValue === 'number' || typeof cohortValue === 'string' ? Number(cohortValue) : NaN+ const status = properties.find((property) => property.key === 'status')?.value+ if (!Number.isInteger(cohortId) || (status !== 'entered' && status !== 'left')) {+ return null+ }+ return { cohortId, transition: status }+}++/** Separates the cohort entry from the ordinary event entries, so each editor section changes only its own. */+export function splitCohortMembershipEntry(entries: EventEntry[] | null | undefined): {+ eventEntries: EventEntry[]+ cohort: CohortMembershipEventValue | null+} {+ const eventEntries: EventEntry[] = []+ let cohort: CohortMembershipEventValue | null = null+ for (const entry of entries ?? []) {+ const read: CohortMembershipEventValue | null = cohort ? null : readCohortMembershipEventEntry(entry)+ if (read) {+ cohort = read+ } else {+ eventEntries.push(entry)+ }+ }+ return { eventEntries, cohort }+}++export function joinCohortMembershipEntry(+ eventEntries: EventEntry[],+ cohort: CohortMembershipEventValue | null+): EventEntry[] | undefined {+ const entries = cohort ? [...eventEntries, cohortMembershipEventEntry(cohort)] : eventEntries+ return entries.length ? entries : undefined+}