: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(cohorts): add activity log and edit history tracking (#57702)
Dylan Martin4e781252b755
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 70798bce4c53..d2a3a8cd7c5a 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4983,13 +4983,13 @@ snapshots:scenes-app-oauth-authorize--with-scopes--light:hash: v1.k794b7964.f6622d5cb9de7b6445a03231c4ce1a2ed977ffce1d563a8c2c6b3ca8a0c9950d.OwEV2W5b_VlbYpNS1SD1ei8W88X56wHaqY3Y9Ut3RkUscenes-app-people-cohorts--cohort-edit-dynamic--dark:- hash: v1.k794b7964.b40a75e5ac7f8174ecec121dfff246dfc1d9023559e206f6f326d551ddcae87c.6TsOlrLEQ6KJapDnr3RX-iHuciUPOHm1VMJpLmrDHEE+ hash: v1.k794b7964.b2c0b065af8c58ca547c691cc880221f64d0ac70a103bf0e47efada7300527f5.xrfnDLtIQxSP-8Ga0knhjf6CHtW0ZfBXqgI2god2ZlEscenes-app-people-cohorts--cohort-edit-dynamic--light:- hash: v1.k794b7964.cdceb0ec89f083784cc5c0abd8fd8d4e1c88cc5b3cac0438dd46a17ce64d47d3.GBh1qp6J1ICWzdNevh_T1AgPF-dyxNfME6bJ6Ul8QI8+ hash: v1.k794b7964.ef269f27ee087e74dd9c08f47224c3323ffb8b2819bbd23cd61edeaa21d521bc.Am-fJN-N4gi15GqtSPYpO1TLaHN9fRJPi_7iTJzoUl0scenes-app-people-cohorts--cohort-edit-static--dark:- hash: v1.k794b7964.d403189559e173b4519b1c86a7e4016928fa92a687948c2a3c044c89f23b06f9.37kBUULoqK-P1IJ52KhyiOzGue7DSjCbJCX3z_3KtPY+ hash: v1.k794b7964.2ec9bdfe13dc355444a9a23ac92938cf91b2121b43360f0722e774ab745ef70b.qGM0lVIiDK6g5_o57UK69X9MJzInGQJKj5EkH1UijK8scenes-app-people-cohorts--cohort-edit-static--light:- hash: v1.k794b7964.b785390a8b203b1ce78b7dcc878d69d8817e3497d89ae23dcf65ff783eff626d.Z-xb1SZ8DSHr8TzOvWctYLfARweivy3pJGw7n2IQ-S8+ hash: v1.k794b7964.fb6d6c9874a736f201686a0f406b1d559662fffce609b3846909cc54141a4c05.DZYJw5qSU62bhe5c0Ce6f1fFz4eZs1HD71xxPFcWx3gscenes-app-people-cohorts--cohort-new--dark:hash: v1.k794b7964.0d1749c42adbd57711015b1083bedf746ea51b3216268fcfddead5b18417d485.SixdjsDB2NAVWE06mAFx8Sx1GuZzOYiyb11rg4cjUoMscenes-app-people-cohorts--cohort-new--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex ea4aef035b98..367d55490956 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2626,6 +2626,7 @@ const api = {ActivityScope.ENDPOINT,ActivityScope.PRODUCT_TOUR,ActivityScope.TICKET,+ ActivityScope.COHORT,].includes(scopes[0]) ||scopes.length > 1) {diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsxindex 62c09b3eef83..c7f759accdc3 100644--- a/frontend/src/scenes/cohorts/CohortEdit.tsx+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx@@ -3,8 +3,9 @@ import { Form } from 'kea-forms'import { router } from 'kea-router'import { IconClock, IconCopy, IconRefresh, IconTrash, IconUpload, IconWarning } from '@posthog/icons'-import { LemonBanner, LemonDialog, LemonDivider, LemonFileInput, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonBanner, LemonDialog, LemonDivider, LemonFileInput, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'+import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { NotFound } from 'lib/components/NotFound'import { SceneAddToNotebookDropdownMenu } from 'lib/components/Scenes/InsightOrDashboard/SceneAddToNotebookDropdownMenu'import { SceneFile } from 'lib/components/Scenes/SceneFile'@@ -38,7 +39,7 @@ import {} from '~/layout/scenes/SceneLayout'import { AndOrFilterSelect } from '~/queries/nodes/InsightViz/PropertyGroupFilters/AndOrFilterSelect'import { Query } from '~/queries/Query/Query'-import { CohortType, SidePanelTab } from '~/types'+import { ActivityScope, CohortType, SidePanelTab } from '~/types'import { AddPersonToCohortModal } from './AddPersonToCohortModal'import { addPersonToCohortModalLogic } from './addPersonToCohortModalLogic'@@ -82,6 +83,7 @@ export function CohortEdit({ id, attachTo, tabId }: CohortEditProps): JSX.ElemenremovePersonFromCreateStaticCohort,setCreationPersonQuery,setStaticCohortMode,+ setActiveTab,submitCohort,} = useActions(logic)const modalLogic = addPersonToCohortModalLogic(logicProps)@@ -97,6 +99,7 @@ export function CohortEdit({ id, attachTo, tabId }: CohortEditProps): JSX.ElemenisPendingCalculation,isCalculatingOrPending,staticCohortMode,+ activeTab,} = useValues(logic)const { featureFlags } = useValues(featureFlagLogic)const { canCopyToProject } = useValues(interProjectCopyLogic)@@ -290,361 +293,390 @@ export function CohortEdit({ id, attachTo, tabId }: CohortEditProps): JSX.Elemen/></LemonField>- <SceneSection- title="Type"- description="Static cohorts are created once and never updated, while dynamic cohorts are recalculated based on the latest data."- className="max-w-200 flex flex-col gap-y-2"- hideTitleAndDescription- >- <div className="flex gap-4 flex-wrap">- <div className={cn('flex-1 flex flex-col gap-y-4')}>- <LemonField name="is_static" label={null}>- {({ value, onChange }) => (- <LemonSelect- disabledReason={- isNewCohort- ? null- : 'Create a new cohort to use a different type of cohort.'- }- options={COHORT_TYPE_OPTIONS}- value={value ? CohortTypeEnum.Static : CohortTypeEnum.Dynamic}- onChange={(cohortType) => {- onChange(cohortType === CohortTypeEnum.Static)- }}- fullWidth- data-attr="cohort-type"- />- )}- </LemonField>+ {!isNewCohort && (+ <LemonTabs+ activeKey={activeTab}+ onChange={(key) => setActiveTab(key)}+ tabs={[+ { key: 'overview', label: 'Overview' },+ { key: 'history', label: 'History' },+ ]}+ />+ )}- {cohort.is_static && (- <div className="flex flex-col gap-y-2">- <h2 className="text-base mb-0">Populate from</h2>- <p className="text-sm text-secondary my-0 max-w-prose">- {staticCohortMode === 'criteria'- ? 'People matching the criteria below will be snapshotted into a fixed list when the cohort is created. Unlike a dynamic cohort, the list will not update as people change.'- : 'Manually add people via CSV upload or by selecting them individually.'}- </p>- <LemonSelect- disabledReason={- isNewCohort- ? undefined- : 'Create a new cohort to change how a static cohort is populated.'- }- options={[- {- label: 'Criteria · One-time snapshot',- value: 'criteria' as const,- },- {- label: 'Upload or add people',- value: 'people' as const,- },- ]}- value={staticCohortMode}- onChange={(value) => setStaticCohortMode(value)}- fullWidth- data-attr="static-cohort-mode"- />- </div>- )}+ {activeTab === 'history' && typeof cohort.id === 'number' ? (+ <SceneSection+ title="History"+ description="Track changes made to this cohort over time."+ hideTitleAndDescription+ >+ <ActivityLog scope={ActivityScope.COHORT} id={cohort.id} />+ </SceneSection>+ ) : null}- {!isNewCohort && !cohort?.is_static && (- <div className="flex flex-col gap-y-2">- <div className="flex items-center gap-x-2 my-0">- <strong>Last calculated:</strong>- {isCalculatingOrPending ? (- <div className="flex items-center gap-x-2">- <Spinner size="small" />- <span className="text-muted">In progress...</span>- </div>- ) : cohort.last_calculation ? (- <TZLabel time={cohort.last_calculation} />- ) : (- <span className="text-muted">Not yet calculated</span>- )}+ <div className={cn(activeTab === 'overview' ? 'contents' : 'hidden')}>+ <SceneSection+ title="Type"+ description="Static cohorts are created once and never updated, while dynamic cohorts are recalculated based on the latest data."+ className="max-w-200 flex flex-col gap-y-2"+ hideTitleAndDescription+ >+ <div className="flex gap-4 flex-wrap">+ <div className={cn('flex-1 flex flex-col gap-y-4')}>+ <LemonField name="is_static" label={null}>+ {({ value, onChange }) => (+ <LemonSelect+ disabledReason={+ isNewCohort+ ? null+ : 'Create a new cohort to use a different type of cohort.'+ }+ options={COHORT_TYPE_OPTIONS}+ value={value ? CohortTypeEnum.Static : CohortTypeEnum.Dynamic}+ onChange={(cohortType) => {+ onChange(cohortType === CohortTypeEnum.Static)+ }}+ fullWidth+ data-attr="cohort-type"+ />+ )}+ </LemonField>++ {cohort.is_static && (+ <div className="flex flex-col gap-y-2">+ <h2 className="text-base mb-0">Populate from</h2>+ <p className="text-sm text-secondary my-0 max-w-prose">+ {staticCohortMode === 'criteria'+ ? 'People matching the criteria below will be snapshotted into a fixed list when the cohort is created. Unlike a dynamic cohort, the list will not update as people change.'+ : 'Manually add people via CSV upload or by selecting them individually.'}+ </p>+ <LemonSelect+ disabledReason={+ isNewCohort+ ? undefined+ : 'Create a new cohort to change how a static cohort is populated.'+ }+ options={[+ {+ label: 'Criteria · One-time snapshot',+ value: 'criteria' as const,+ },+ {+ label: 'Upload or add people',+ value: 'people' as const,+ },+ ]}+ value={staticCohortMode}+ onChange={(value) => setStaticCohortMode(value)}+ fullWidth+ data-attr="static-cohort-mode"+ /></div>+ )}- {isCalculatingOrPending ? (- <LemonBanner type="warning">- {isPendingCalculation && !cohort.is_calculating- ? cohort.last_calculation- ? "We're queuing a recalculation. The table below shows results from the previous calculation."- : "We're queuing the calculation. It should be ready in a few minutes."- : cohort.last_calculation- ? "We're recalculating the cohort. The table below shows results from the previous calculation."- : "We're calculating the cohort. It should be ready in a few minutes."}- </LemonBanner>- ) : cohort.errors_calculating ? (- <LemonBanner- type="error"- action={{- onClick: () => submitCohort(),- children: 'Retry',- }}- >- <strong>Calculation failed:</strong>{' '}- {cohort.last_error_message ||- 'Unable to calculate this cohort. Please check your matching criteria and try again.'}{' '}- If it fails again,{' '}- <Link- onClick={() =>- openSidePanel(SidePanelTab.Support, 'bug:cohorts::true')- }+ {!isNewCohort && !cohort?.is_static && (+ <div className="flex flex-col gap-y-2">+ <div className="flex items-center gap-x-2 my-0">+ <strong>Last calculated:</strong>+ {isCalculatingOrPending ? (+ <div className="flex items-center gap-x-2">+ <Spinner size="small" />+ <span className="text-muted">In progress...</span>+ </div>+ ) : cohort.last_calculation ? (+ <TZLabel time={cohort.last_calculation} />+ ) : (+ <span className="text-muted">Not yet calculated</span>+ )}+ </div>++ {isCalculatingOrPending ? (+ <LemonBanner type="warning">+ {isPendingCalculation && !cohort.is_calculating+ ? cohort.last_calculation+ ? "We're queuing a recalculation. The table below shows results from the previous calculation."+ : "We're queuing the calculation. It should be ready in a few minutes."+ : cohort.last_calculation+ ? "We're recalculating the cohort. The table below shows results from the previous calculation."+ : "We're calculating the cohort. It should be ready in a few minutes."}+ </LemonBanner>+ ) : cohort.errors_calculating ? (+ <LemonBanner+ type="error"+ action={{+ onClick: () => submitCohort(),+ children: 'Retry',+ }}>- contact support- </Link>- .- </LemonBanner>- ) : null}- </div>- )}- </div>- </div>- </SceneSection>- {cohort.is_static && staticCohortMode === 'criteria' ? (- <>- <SceneDivider />- <SceneSection hideTitleAndDescription>- {!isNewCohort && (- <LemonBanner type="info" className="mb-4">- This static cohort was snapshotted from criteria at creation time. Editing- these criteria is not supported. Create a new cohort to use different- criteria.- </LemonBanner>- )}- <AndOrFilterSelect- value={cohort.filters.properties.type}- onChange={(value) => {- setOuterGroupsType(value)- }}- topLevelFilter={true}- suffix={['criterion', 'criteria']}- disabledReason={- isNewCohort ? undefined : 'Create a new cohort to use different criteria.'- }- />- <div- className={cn(- 'w-full [&>div]:my-0 [&>div]:w-full',- !isNewCohort && 'pointer-events-none opacity-60'+ <strong>Calculation failed:</strong>{' '}+ {cohort.last_error_message ||+ 'Unable to calculate this cohort. Please check your matching criteria and try again.'}{' '}+ If it fails again,{' '}+ <Link+ onClick={() =>+ openSidePanel(SidePanelTab.Support, 'bug:cohorts::true')+ }+ >+ contact support+ </Link>+ .+ </LemonBanner>+ ) : null}+ </div>)}- aria-disabled={!isNewCohort}- >- <CohortCriteriaGroups id={logicProps.id} /></div>- </SceneSection>- </>- ) : cohort.is_static ? (- <>- <SceneDivider />- <SceneSection- title={isNewCohort ? 'Upload users' : 'Add users'}- description={- isNewCohort- ? `Upload a CSV file to add users to your cohort. For single-column files, include+ </div>+ </SceneSection>+ {cohort.is_static && staticCohortMode === 'criteria' ? (+ <>+ <SceneDivider />+ <SceneSection hideTitleAndDescription>+ {!isNewCohort && (+ <LemonBanner type="info" className="mb-4">+ This static cohort was snapshotted from criteria at creation time.+ Editing these criteria is not supported. Create a new cohort to use+ different criteria.+ </LemonBanner>+ )}+ <AndOrFilterSelect+ value={cohort.filters.properties.type}+ onChange={(value) => {+ setOuterGroupsType(value)+ }}+ topLevelFilter={true}+ suffix={['criterion', 'criteria']}+ disabledReason={+ isNewCohort+ ? undefined+ : 'Create a new cohort to use different criteria.'+ }+ />+ <div+ className={cn(+ 'w-full [&>div]:my-0 [&>div]:w-full',+ !isNewCohort && 'pointer-events-none opacity-60'+ )}+ aria-disabled={!isNewCohort}+ >+ <CohortCriteriaGroups id={logicProps.id} />+ </div>+ </SceneSection>+ </>+ ) : cohort.is_static ? (+ <>+ <SceneDivider />+ <SceneSection+ title={isNewCohort ? 'Upload users' : 'Add users'}+ description={+ isNewCohort+ ? `Upload a CSV file to add users to your cohort. For single-column files, includeone distinct ID per row (all rows will be processed as data). For multi-columnfiles, include a header row with a 'person_id', 'distinct_id', or 'email' columncontaining the user identifiers.`- : undefined- }- className={cn('ph-ignore-input')}- >+ : undefined+ }+ className={cn('ph-ignore-input')}+ >+ {!isNewCohort && (+ <div className="flex flex-col gap-y-0 flex-1 justify-center">+ <h3 className="text-sm">Upload a CSV</h3>+ <span className="max-w-prose">+ Upload a CSV file to add users to your cohort. For single-column+ files, include one distinct ID per row (all rows will be processed+ as data). For multi-column files, include a header row with a+ 'person_id', 'distinct_id', or 'email' column containing the user+ identifiers.+ </span>+ </div>+ )}+ {/* TODO: @adamleithp Allow users to download a template CSV file */}+ {/* TODO: @adamleithp Tell users that adding ANOTHER file will NOT(?) replace the current one */}+ {/* TODO: @adamleithp Render the csv file and validate it */}+ {/* TODO: @adamleithp Adding a csv file doesn't show up with cohort.csv... */}+ <LemonField name="csv" data-attr="cohort-csv">+ {({ onChange }) => (+ <LemonFileInput+ accept=".csv"+ multiple={false}+ value={cohort.csv ? [cohort.csv] : []}+ onChange={(files) => onChange(files[0])}+ showUploadedFiles={false}+ callToAction={+ <div+ className={cn(+ 'flex flex-col items-center justify-center flex-1 cohort-csv-dragger text-text-3000 deprecated-space-y-1',+ 'text-primary mt-0 bg-transparent border border-dashed border-primary hover:border-secondary p-8',+ cohort.csv?.name && 'border-success'+ )}+ >+ {cohort.csv ? (+ <>+ <IconUpload+ style={{+ fontSize: '3rem',+ color: 'var(--color-text-primary)',+ }}+ />+ <div>{cohort.csv?.name ?? 'File chosen'}</div>+ </>+ ) : (+ <>+ <IconUpload+ style={{+ fontSize: '3rem',+ color: 'var(--color-text-primary)',+ }}+ />+ <div>+ Drag a file here or click to browse for a file+ </div>+ <div className="text-secondary text-xs">+ Accepts .csv files only+ </div>+ </>+ )}+ </div>+ }+ />+ )}+ </LemonField>+ </SceneSection>+ {isNewCohort && (+ <>+ <LemonDivider label="OR" />+ <div>+ <h3 className="font-semibold my-0 mb-1 max-w-prose">+ Add users manually+ </h3>+ <span className="max-w-prose">+ Select the users that you would like to add to the new cohort.+ </span>+ </div>+ <PersonSelectList+ query={creationPersonQuery}+ setQuery={setCreationPersonQuery}+ selectedPersons={personsToCreateStaticCohort}+ onAddPerson={addPersonToCreateStaticCohort}+ onRemovePerson={removePersonFromCreateStaticCohort}+ dataNodeKey="createStaticCohort"+ />+ </>+ )}{!isNewCohort && (- <div className="flex flex-col gap-y-0 flex-1 justify-center">- <h3 className="text-sm">Upload a CSV</h3>- <span className="max-w-prose">- Upload a CSV file to add users to your cohort. For single-column files,- include one distinct ID per row (all rows will be processed as data).- For multi-column files, include a header row with a 'person_id',- 'distinct_id', or 'email' column containing the user identifiers.- </span>- </div>+ <>+ <LemonDivider label="OR" />+ <div>+ <h3 className="text-sm">Add users manually</h3>+ <span className="max-w-prose">+ Select the users that you would like to add to the cohort.+ </span>+ <LemonButton+ className="w-fit mt-4"+ type="primary"+ onClick={showAddPersonToCohortModal}+ data-attr="cohort-add-users-modal-open"+ >+ Add Users+ </LemonButton>+ </div>+ </>)}- {/* TODO: @adamleithp Allow users to download a template CSV file */}- {/* TODO: @adamleithp Tell users that adding ANOTHER file will NOT(?) replace the current one */}- {/* TODO: @adamleithp Render the csv file and validate it */}- {/* TODO: @adamleithp Adding a csv file doesn't show up with cohort.csv... */}- <LemonField name="csv" data-attr="cohort-csv">- {({ onChange }) => (- <LemonFileInput- accept=".csv"- multiple={false}- value={cohort.csv ? [cohort.csv] : []}- onChange={(files) => onChange(files[0])}- showUploadedFiles={false}- callToAction={- <div- className={cn(- 'flex flex-col items-center justify-center flex-1 cohort-csv-dragger text-text-3000 deprecated-space-y-1',- 'text-primary mt-0 bg-transparent border border-dashed border-primary hover:border-secondary p-8',- cohort.csv?.name && 'border-success'- )}- >- {cohort.csv ? (- <>- <IconUpload- style={{- fontSize: '3rem',- color: 'var(--color-text-primary)',- }}- />- <div>{cohort.csv?.name ?? 'File chosen'}</div>- </>- ) : (- <>- <IconUpload- style={{- fontSize: '3rem',- color: 'var(--color-text-primary)',- }}- />- <div>- Drag a file here or click to browse for a file- </div>- <div className="text-secondary text-xs">- Accepts .csv files only- </div>- </>- )}- </div>- }- />- )}- </LemonField>- </SceneSection>- {isNewCohort && (- <>- <LemonDivider label="OR" />- <div>- <h3 className="font-semibold my-0 mb-1 max-w-prose">Add users manually</h3>- <span className="max-w-prose">- Select the users that you would like to add to the new cohort.- </span>- </div>- <PersonSelectList- query={creationPersonQuery}- setQuery={setCreationPersonQuery}- selectedPersons={personsToCreateStaticCohort}- onAddPerson={addPersonToCreateStaticCohort}- onRemovePerson={removePersonFromCreateStaticCohort}- dataNodeKey="createStaticCohort"+ </>+ ) : (+ <>+ <SceneDivider />+ {!isNewCohort && cohort.experiment_set && cohort.experiment_set.length > 0 && (+ <LemonBanner type="info">+ This cohort manages exposure for an experiment. Editing this cohort may+ change experiment metrics. If unsure,{' '}+ <Link to={urls.experiment(cohort.experiment_set[0])}>+ check the experiment details.+ </Link>+ </LemonBanner>+ )}+ <SceneSection+ // TODO: @adamleithp Add a number of matching persons to the title "Matching criteria (100)"+ title="Matching criteria"+ description="Actors who match the following criteria will be part of the cohort. Continuously updated automatically."+ className={cn('flex items-start justify-between')}+ hideTitleAndDescription+ >+ <AndOrFilterSelect+ value={cohort.filters.properties.type}+ onChange={(value) => {+ setOuterGroupsType(value)+ }}+ topLevelFilter={true}+ suffix={['criterion', 'criteria']}/>- </>- )}- {!isNewCohort && (- <>- <LemonDivider label="OR" />- <div>- <h3 className="text-sm">Add users manually</h3>- <span className="max-w-prose">- Select the users that you would like to add to the cohort.- </span>- <LemonButton- className="w-fit mt-4"- type="primary"- onClick={showAddPersonToCohortModal}- data-attr="cohort-add-users-modal-open"- >- Add Users- </LemonButton>+ <div className={cn('w-full [&>div]:my-0 [&>div]:w-full')}>+ <CohortCriteriaGroups id={logicProps.id} /></div>- </>- )}- </>- ) : (- <>- <SceneDivider />- {!isNewCohort && cohort.experiment_set && cohort.experiment_set.length > 0 && (- <LemonBanner type="info">- This cohort manages exposure for an experiment. Editing this cohort may change- experiment metrics. If unsure,{' '}- <Link to={urls.experiment(cohort.experiment_set[0])}>- check the experiment details.- </Link>- </LemonBanner>- )}- <SceneSection- // TODO: @adamleithp Add a number of matching persons to the title "Matching criteria (100)"- title="Matching criteria"- description="Actors who match the following criteria will be part of the cohort. Continuously updated automatically."- className={cn('flex items-start justify-between')}- hideTitleAndDescription- >- <AndOrFilterSelect- value={cohort.filters.properties.type}- onChange={(value) => {- setOuterGroupsType(value)- }}- topLevelFilter={true}- suffix={['criterion', 'criteria']}- />- <div className={cn('w-full [&>div]:my-0 [&>div]:w-full')}>- <CohortCriteriaGroups id={logicProps.id} />- </div>- </SceneSection>- </>- )}+ </SceneSection>+ </>+ )}- {/* The typeof here is needed to pass the cohort id to the query below. Using `isNewCohort` won't work */}- {typeof cohort.id === 'number' && (- <>- <SceneDivider />- <SceneSection- title={- <>- Persons in this cohort- <span className="text-secondary ml-2">- {!isCalculatingOrPending &&- cohort.count != undefined &&- `(${cohort.count})`}- </span>- {shouldShowCountWarning && (- <Tooltip title="The displayed number of persons is less than the cohort count due to deleted persons. This is expected behavior for dynamic cohorts where persons may be deleted after being counted.">- <IconWarning className="text-warning ml-2" />- </Tooltip>+ {/* The typeof here is needed to pass the cohort id to the query below. Using `isNewCohort` won't work */}+ {typeof cohort.id === 'number' && (+ <>+ <SceneDivider />+ <SceneSection+ title={+ <>+ Persons in this cohort+ <span className="text-secondary ml-2">+ {!isCalculatingOrPending &&+ cohort.count != undefined &&+ `(${cohort.count})`}+ </span>+ {shouldShowCountWarning && (+ <Tooltip title="The displayed number of persons is less than the cohort count due to deleted persons. This is expected behavior for dynamic cohorts where persons may be deleted after being counted.">+ <IconWarning className="text-warning ml-2" />+ </Tooltip>+ )}+ </>+ }+ description="Persons who match the following criteria will be part of the cohort."+ hideTitleAndDescription+ >+ <div className="relative min-h-[400px]">+ {isCalculatingOrPending && !cohort.last_calculation ? (+ <div className="absolute inset-0 flex flex-col items-center justify-center bg-bg-light">+ <Spinner size="large" />+ <p className="text-muted mt-4">+ {isPendingCalculation && !cohort.is_calculating+ ? "We're queuing the calculation. It should be ready in a few minutes."+ : "We're calculating the cohort. It should be ready in a few minutes."}+ </p>+ </div>+ ) : (+ <Query+ query={query}+ setQuery={setQuery}+ context={{+ refresh: 'force_blocking',+ fileNameForExport: cohort.name,+ cohortId: cohortId,+ dataNodeLogicKey: dataNodeLogicKey,+ columns: canRemovePersonFromCohort+ ? {+ 'person.$delete': {+ render: renderRemovePersonFromCohortButton,+ },+ }+ : undefined,+ emptyStateHeading:+ 'There are no matching persons for this cohort',+ emptyStateDetail:+ 'Try adjusting your matching criteria or search to see more results.',+ }}+ />)}- </>- }- description="Persons who match the following criteria will be part of the cohort."- hideTitleAndDescription- >- <div className="relative min-h-[400px]">- {isCalculatingOrPending && !cohort.last_calculation ? (- <div className="absolute inset-0 flex flex-col items-center justify-center bg-bg-light">- <Spinner size="large" />- <p className="text-muted mt-4">- {isPendingCalculation && !cohort.is_calculating- ? "We're queuing the calculation. It should be ready in a few minutes."- : "We're calculating the cohort. It should be ready in a few minutes."}- </p>- </div>- ) : (- <Query- query={query}- setQuery={setQuery}- context={{- refresh: 'force_blocking',- fileNameForExport: cohort.name,- cohortId: cohortId,- dataNodeLogicKey: dataNodeLogicKey,- columns: canRemovePersonFromCohort- ? {- 'person.$delete': {- render: renderRemovePersonFromCohortButton,- },- }- : undefined,- emptyStateHeading: 'There are no matching persons for this cohort',- emptyStateDetail:- 'Try adjusting your matching criteria or search to see more results.',- }}- />- )}- </div>- </SceneSection>- </>- )}+ </div>+ </SceneSection>+ </>+ )}+ </div></SceneContent></Form></div>diff --git a/frontend/src/scenes/cohorts/activityDescriptions.test.tsx b/frontend/src/scenes/cohorts/activityDescriptions.test.tsxnew file mode 100644index 000000000000..e06773c7629f--- /dev/null+++ b/frontend/src/scenes/cohorts/activityDescriptions.test.tsx@@ -0,0 +1,252 @@+import { render } from '@testing-library/react'++import { ActivityChange, ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'++import { initKeaTests } from '~/test/init'+import { ActivityScope, FilterLogicalOperator } from '~/types'++import { cohortActivityDescriber } from './activityDescriptions'++function makeLogItem(overrides: Partial<ActivityLogItem> & { detail: ActivityLogItem['detail'] }): ActivityLogItem {+ return {+ user: { first_name: 'Max', last_name: 'Hog', email: '[email protected]' },+ activity: 'updated',+ created_at: '2026-03-01T00:00:00Z',+ scope: ActivityScope.COHORT,+ item_id: '7',+ ...overrides,+ }+}++function describeText(logItem: ActivityLogItem): string {+ const { description } = cohortActivityDescriber(logItem)+ if (!description) {+ return ''+ }+ const { container } = render(<>{description}</>)+ return container.textContent ?? ''+}++const change = (field: string, before: unknown, after: unknown): ActivityChange => ({+ type: ActivityScope.COHORT,+ action: 'changed',+ field,+ before: before as ActivityChange['before'],+ after: after as ActivityChange['after'],+})++const filtersWith = (numCriteria: number): { properties: { type: FilterLogicalOperator; values: any[] } } => ({+ properties: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: Array.from({ length: numCriteria }, (_, i) => ({ key: `prop_${i}` })),+ },+ ],+ },+})++describe('cohortActivityDescriber', () => {+ beforeEach(() => {+ // describer returns JSX containing <Link> which relies on kea-router+ initKeaTests()+ })++ it('returns null for non-cohort scope', () => {+ const result = cohortActivityDescriber({+ ...makeLogItem({ detail: { name: 'x', merge: null, trigger: null, changes: [] } }),+ scope: ActivityScope.FEATURE_FLAG,+ })+ expect(result.description).toBeNull()+ })++ it.each([+ ['created', 'High value users', 'Max Hog created the cohort: High value users'],+ ['deleted', 'High value users', 'Max Hog deleted the cohort: High value users'],+ ['restored', 'High value users', 'Max Hog restored the cohort: High value users'],+ ['persons_added_manually', 'Beta testers', 'Max Hog added users to the cohort: Beta testers'],+ ['person_removed_manually', 'Beta testers', 'Max Hog removed a user from the cohort: Beta testers'],+ ])('describes %s activity', (activity, name, expected) => {+ expect(+ describeText(+ makeLogItem({+ activity,+ detail: { name, merge: null, trigger: null, changes: [] },+ })+ )+ ).toBe(expected)+ })++ describe('updated activity', () => {+ it('describes a rename', () => {+ const text = describeText(+ makeLogItem({+ detail: {+ name: 'New name',+ merge: null,+ trigger: null,+ changes: [change('name', 'Old name', 'New name')],+ },+ })+ )+ expect(text).toContain('renamed from Old name to New name')+ expect(text).toContain('on New name')+ })++ it.each([+ ['adding', null, 'Some description', 'added a description'],+ ['clearing', 'Some description', '', 'cleared the description'],+ ['editing', 'Old text', 'New text', 'updated the description'],+ ])('describes %s a description', (_label, before, after, expected) => {+ expect(+ describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('description', before, after)],+ },+ })+ )+ ).toContain(expected)+ })++ it('describes a criteria count change', () => {+ expect(+ describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('filters', filtersWith(2), filtersWith(5))],+ },+ })+ )+ ).toContain('changed the matching criteria from 2 to 5')+ })++ it('describes a criteria edit when count is unchanged', () => {+ expect(+ describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('filters', filtersWith(3), filtersWith(3))],+ },+ })+ )+ ).toContain('updated the matching criteria')+ })++ it('describes a query change', () => {+ expect(+ describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('query', { kind: 'a' }, { kind: 'b' })],+ },+ })+ )+ ).toContain('updated the cohort query')+ })++ it('dedupes is_static when cohort_type is also present', () => {+ const text = describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('is_static', false, true), change('cohort_type', 'person', 'static')],+ },+ })+ )+ const occurrences = text.match(/changed the cohort type/g) ?? []+ expect(occurrences).toHaveLength(1)+ expect(text).toContain('changed the cohort type to static')+ })++ it('describes is_static alone when cohort_type is not present', () => {+ expect(+ describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('is_static', false, true)],+ },+ })+ )+ ).toContain('changed the cohort type to static')+ })++ it('surfaces unknown fields generically rather than dumping JSON', () => {+ const text = describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('newly_added_field', 'a', 'b')],+ },+ })+ )+ expect(text).toContain('updated newly_added_field')+ expect(text).not.toContain('"a"')+ })++ it('combines multiple known field changes', () => {+ const text = describeText(+ makeLogItem({+ detail: {+ name: 'New name',+ merge: null,+ trigger: null,+ changes: [+ change('name', 'Old', 'New name'),+ change('description', null, 'Some description'),+ change('filters', filtersWith(1), filtersWith(2)),+ ],+ },+ })+ )+ expect(text).toContain('renamed from Old to New name')+ expect(text).toContain('added a description')+ expect(text).toContain('changed the matching criteria from 1 to 2')+ })++ it('falls back to a generic line when changes array is empty', () => {+ expect(+ describeText(+ makeLogItem({+ detail: { name: 'My cohort', merge: null, trigger: null, changes: [] },+ })+ )+ ).toBe('Max Hog updated the cohort: My cohort')+ })++ it('skips excluded fields without rendering them', () => {+ const text = describeText(+ makeLogItem({+ detail: {+ name: 'My cohort',+ merge: null,+ trigger: null,+ changes: [change('id', 1, 2), change('team_id', 1, 2), change('created_at', 'a', 'b')],+ },+ })+ )+ // all three are excluded -> falls back to the generic "updated" line+ expect(text).toBe('Max Hog updated the cohort: My cohort')+ })+ })+})diff --git a/frontend/src/scenes/cohorts/activityDescriptions.tsx b/frontend/src/scenes/cohorts/activityDescriptions.tsxindex b94362c17e6b..38ec5b35663c 100644--- a/frontend/src/scenes/cohorts/activityDescriptions.tsx+++ b/frontend/src/scenes/cohorts/activityDescriptions.tsx@@ -1,31 +1,124 @@import '../../lib/components/Cards/InsightCard/InsightCard.scss'import {+ ActivityChange,ActivityLogItem,+ ChangeMapping,+ Description,HumanizedChange,defaultDescriber,+ detectBoolean,userNameForLogItem,} from 'lib/components/ActivityLog/humanizeActivity'+import { SentenceList } from 'lib/components/ActivityLog/SentenceList'import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'+import { CohortType } from '~/types'+const nameOrLinkToCohort = (id?: string | null, name?: string | null): string | JSX.Element => {const displayName = name || '(empty string)'return id ? <Link to={urls.cohort(id)}>{displayName}</Link> : displayName}+const countCohortCriteria = (filters: CohortType['filters'] | undefined): number => {+ const groups = filters?.properties?.values ?? []+ return groups.reduce((total, group) => {+ const values = (group as { values?: unknown[] })?.values+ return total + (Array.isArray(values) ? values.length : 0)+ }, 0)+}++const cohortFieldMapping: Record<string, (change?: ActivityChange) => ChangeMapping | null> = {+ name: function onName(change) {+ const before = change?.before as string | null | undefined+ const after = change?.after as string | null | undefined+ return {+ description: [+ <>+ renamed from <strong>{before || '(empty string)'}</strong> to{' '}+ <strong>{after || '(empty string)'}</strong>+ </>,+ ],+ }+ },+ description: function onDescription(change) {+ const before = (change?.before as string | null | undefined) || ''+ const after = (change?.after as string | null | undefined) || ''+ if (!before && after) {+ return { description: [<>added a description</>] }+ }+ if (before && !after) {+ return { description: [<>cleared the description</>] }+ }+ return { description: [<>updated the description</>] }+ },+ filters: function onFilters(change) {+ const before = countCohortCriteria(change?.before as CohortType['filters'])+ const after = countCohortCriteria(change?.after as CohortType['filters'])+ if (before === after) {+ return { description: [<>updated the matching criteria</>] }+ }+ return {+ description: [+ <>+ changed the matching criteria from <strong>{before}</strong> to <strong>{after}</strong>+ </>,+ ],+ }+ },+ query: function onQuery() {+ return { description: [<>updated the cohort query</>] }+ },+ is_static: function onIsStatic(change) {+ const isStatic = detectBoolean(change?.after)+ return {+ description: [+ <>+ changed the cohort type to <strong>{isStatic ? 'static' : 'dynamic'}</strong>+ </>,+ ],+ }+ },+ cohort_type: function onCohortType(change) {+ const after = change?.after as string | null | undefined+ if (!after) {+ return null+ }+ return {+ description: [+ <>+ changed the cohort type to <strong>{after}</strong>+ </>,+ ],+ }+ },+ groups: function onGroups() {+ return { description: [<>updated the matching criteria</>] }+ },+ // fields that we don't want to surface (excluded on backend or noisy)+ id: () => null,+ team_id: () => null,+ deleted: () => null,+ created_by_id: () => null,+ created_at: () => null,+ last_error_at: () => null,+}+export function cohortActivityDescriber(logItem: ActivityLogItem, asNotification?: boolean): HumanizedChange {if (logItem.scope != 'Cohort') {console.error('cohort describer received a non-cohort activity')return { description: null }}+ const actor = <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>+ const cohortLink = nameOrLinkToCohort(logItem?.item_id, logItem?.detail.name)+if (logItem.activity == 'created') {return {description: (<>- <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong> created the cohort:{' '}- {nameOrLinkToCohort(logItem?.item_id, logItem?.detail.name)}+ {actor} created the cohort: {cohortLink}</>),}@@ -35,8 +128,7 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotificationreturn {description: (<>- <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong> deleted the cohort:{' '}- {nameOrLinkToCohort(logItem?.item_id, logItem?.detail.name)}+ {actor} deleted the cohort: {cohortLink}</>),}@@ -46,22 +138,84 @@ export function cohortActivityDescriber(logItem: ActivityLogItem, asNotificationreturn {description: (<>- <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong> restored the cohort:{' '}- {nameOrLinkToCohort(logItem?.item_id, logItem?.detail.name)}+ {actor} restored the cohort: {cohortLink}+ </>+ ),+ }+ }++ if (logItem.activity == 'persons_added_manually') {+ return {+ description: (+ <>+ {actor} added users to the cohort: {cohortLink}+ </>+ ),+ }+ }++ if (logItem.activity == 'person_removed_manually') {+ return {+ description: (+ <>+ {actor} removed a user from the cohort: {cohortLink}</>),}}if (logItem.activity == 'updated') {+ const detailChanges = logItem.detail.changes || []+ // is_static and cohort_type both render as "changed the cohort type to X" — when a flip+ // co-emits both, drop is_static so we don't print the line twice.+ const fieldsPresent = new Set(detailChanges.map((c) => c?.field))+ const changes: Description[] = []+ for (const change of detailChanges) {+ if (!change?.field) {+ continue+ }+ if (change.field === 'is_static' && fieldsPresent.has('cohort_type')) {+ continue+ }+ const handler = cohortFieldMapping[change.field]+ const result = handler ? handler(change) : null+ if (result?.description) {+ changes.push(...result.description)+ } else if (!handler) {+ // unknown field — surface it generically rather than dumping JSON+ changes.push(+ <>+ updated <strong>{change.field}</strong>+ </>+ )+ }+ }++ if (changes.length) {+ return {+ description: (+ <SentenceList+ listParts={changes}+ prefix={actor}+ suffix={+ <>+ on {asNotification ? 'the cohort ' : ''}+ {cohortLink}+ </>+ }+ />+ ),+ }+ }+return {description: (<>- <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong> updated the cohort:{' '}- {nameOrLinkToCohort(logItem?.item_id, logItem?.detail.name)}+ {actor} updated the cohort: {cohortLink}</>),}}- return defaultDescriber(logItem, asNotification, nameOrLinkToCohort(logItem?.item_id, logItem?.detail.name))++ return defaultDescriber(logItem, asNotification, cohortLink)}diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.tsindex 89fe547b7bfe..3d5a82fef236 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts@@ -1129,4 +1129,54 @@ describe('cohortEditLogic', () => {})}, 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')+ })+ })})diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.tsindex cf6317a1cdfd..43402052c758 100644--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts@@ -1,7 +1,7 @@import { actions, afterMount, beforeUnmount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { forms } from 'kea-forms'import { loaders } from 'kea-loaders'-import { router } from 'kea-router'+import { actionToUrl, router, urlToAction } from 'kea-router'import posthog from 'posthog-js'import { v4 as uuidv4 } from 'uuid'@@ -54,6 +54,10 @@ export type CohortLogicProps = {export type StaticCohortMode = 'criteria' | 'people'+export type CohortEditTab = 'overview' | 'history'++const isCohortEditTab = (value: unknown): value is CohortEditTab => value === 'overview' || value === 'history'+const checkIsPendingCalculation = (cohort: CohortType): boolean =>cohort.pending_version != null && (cohort.version == null || cohort.pending_version !== cohort.version)@@ -118,6 +122,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([resetPersonsToCreateStaticCohort: true,refreshPersonsData: true,setStaticCohortMode: (mode: StaticCohortMode) => ({ mode }),+ setActiveTab: (tab: CohortEditTab) => ({ tab }),}),reducers(({ props }) => ({@@ -286,6 +291,12 @@ export const cohortEditLogic = kea<cohortEditLogicType>([setStaticCohortMode: (_, { mode }) => mode,},],+ activeTab: [+ 'overview' as CohortEditTab,+ {+ setActiveTab: (_, { tab }) => tab,+ },+ ],})),selectors({@@ -653,9 +664,36 @@ export const cohortEditLogic = kea<cohortEditLogicType>([},})),- afterMount(({ actions, props }) => {+ actionToUrl(({ values }) => ({+ setActiveTab: () => {+ const { tab: _, ...restHash } = router.values.hashParams+ const nextHash = values.activeTab === 'overview' ? restHash : { ...restHash, tab: values.activeTab }+ return [router.values.location.pathname, router.values.searchParams, nextHash, { replace: true }]+ },+ })),++ urlToAction(({ actions, values }) => ({+ '/cohorts/:id': (_, __, { tab }) => {+ const next = isCohortEditTab(tab) ? tab : 'overview'+ if (values.activeTab !== next) {+ actions.setActiveTab(next)+ }+ },+ })),++ afterMount(({ actions, props, values }) => {if (!props.id || props.id === 'new') {actions.setCohort(NEW_COHORT)+ // Tabs aren't shown for new cohorts; clear any stale `#tab=…` hash so the URL reflects reality+ // and reset the in-memory tab so the Overview content (the only thing rendered for new cohorts)+ // is actually visible — otherwise the user lands on a blank page.+ if (router.values.hashParams.tab) {+ const { tab: _, ...restHash } = router.values.hashParams+ router.actions.replace(router.values.location.pathname, router.values.searchParams, restHash)+ }+ if (values.activeTab !== 'overview') {+ actions.setActiveTab('overview')+ }} else {actions.fetchCohort(props.id)}