: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): show the cohorts in a broadcast's audience as cards (#110048)
Daniel Marchukaf095d44dbee
diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsxindex 6e3f20babecd..9987de7259bc 100644--- a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx@@ -1,4 +1,4 @@-import { BindLogic, useActions, useValues } from 'kea'+import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'import { useEffect } from 'react'import { IconChevronDown, IconLetter } from '@posthog/icons'@@ -26,6 +26,8 @@ import type { HogFlowBatchJobApi } from 'products/workflows/frontend/generated/aimport { EmailViewerModal } from '../Workflows/EmailViewerModal'import type { MessageAsset } from '../Workflows/messageAssetsApi'+import { BroadcastAudienceCohorts } from './audience/BroadcastAudienceCohorts'+import { broadcastAudienceCohortsLogic } from './audience/broadcastAudienceCohortsLogic'import { BroadcastEmailPreview } from './BroadcastEmailPreview'import { archiveDisabledReason, manageDisabledReason } from './broadcastLifecycle'import { BroadcastPerformance } from './BroadcastPerformance'@@ -274,6 +276,8 @@ export function BroadcastSummary(): JSX.Element {} = useValues(broadcastWizardLogic)const { moveToDraft, duplicateBroadcast, setSummaryTab, archiveBroadcast, restoreBroadcast, deleteBroadcast } =useActions(broadcastWizardLogic)+ const { props } = useMountedLogic(broadcastWizardLogic)+ const { nonCohortAudience } = useValues(broadcastAudienceCohortsLogic(props))const pendingSchedule = broadcast?.schedules?.find((schedule) => schedule.status === 'active')const confirmMoveToDraft = (): void => {@@ -404,7 +408,12 @@ export function BroadcastSummary(): JSX.Element {<div className="grid grid-cols-1 gap-4 rounded-lg border border-border bg-surface-primary p-4 @2xl:grid-cols-3"><SummaryRow label="Audience">{audienceProperties.length > 0 ? (- <PropertyFiltersDisplay filters={audienceProperties} />+ <div className="flex flex-col gap-2">+ {nonCohortAudience.length > 0 ? (+ <PropertyFiltersDisplay filters={nonCohortAudience} />+ ) : null}+ <BroadcastAudienceCohorts />+ </div>) : (<span className="text-muted">Everyone</span>)}diff --git a/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceCohorts.tsx b/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceCohorts.tsxnew file mode 100644index 000000000000..244a7354c30f--- /dev/null+++ b/products/workflows/frontend/Broadcasts/audience/BroadcastAudienceCohorts.tsx@@ -0,0 +1,95 @@+import { useMountedLogic, useValues } from 'kea'++import { IconWarning } from '@posthog/icons'+import { LemonButton, LemonTag, Spinner } from '@posthog/lemon-ui'++import { IconCohort, IconOpenInNew } from 'lib/lemon-ui/icons'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import { broadcastWizardLogic } from '../broadcastWizardLogic'+import { AudienceCohort, broadcastAudienceCohortsLogic } from './broadcastAudienceCohortsLogic'++function CohortMembers({ cohort }: { cohort: AudienceCohort }): JSX.Element {+ if (cohort.isCalculating) {+ return (+ <span className="flex items-center gap-1 text-secondary">+ <Spinner className="text-sm" /> Matching people…+ </span>+ )+ }+ if (cohort.failed) {+ return (+ <span className="flex items-center gap-1 text-warning">+ <IconWarning /> Couldn't match the people on this list. Open the cohort to see why.+ </span>+ )+ }+ const people = `${humanFriendlyNumber(cohort.count ?? 0)} ${cohort.count === 1 ? 'person' : 'people'}`+ if (cohort.importTotal && cohort.importUnmatched) {+ return (+ <span className="text-secondary">+ {people}. {humanFriendlyNumber(cohort.importUnmatched)} of {humanFriendlyNumber(cohort.importTotal)} on+ the list aren't in PostHog and won't get this email.+ </span>+ )+ }+ return <span className="text-secondary">{people}</span>+}++/** The cohorts in a broadcast's audience, each with its size and a link to the full cohort. */+export function BroadcastAudienceCohorts(): JSX.Element | null {+ const { props } = useMountedLogic(broadcastWizardLogic)+ const { cohortIds, audienceCohorts } = useValues(broadcastAudienceCohortsLogic(props))++ if (cohortIds.length === 0) {+ return null+ }++ return (+ <div className="flex flex-col gap-1" data-attr="broadcast-audience-cohorts">+ {cohortIds.map((id) => {+ const cohort = audienceCohorts[id]+ return (+ <div+ key={id}+ className="flex flex-wrap items-center justify-between gap-2 rounded border bg-surface-primary px-3 py-2"+ >+ <div className="flex min-w-0 items-center gap-2">+ <IconCohort className="shrink-0 text-lg text-secondary" />+ <div className="flex min-w-0 flex-col">+ <div className="flex items-center gap-2">+ <span className="truncate font-semibold">{cohort?.name ?? `Cohort ${id}`}</span>+ {cohort ? (+ <LemonTag type="muted" size="small">+ {cohort.isStatic ? 'List' : 'Dynamic'}+ </LemonTag>+ ) : null}+ </div>+ <div className="text-xs">+ {cohort ? (+ <CohortMembers cohort={cohort} />+ ) : cohort === null ? (+ <span className="text-secondary">Couldn't load this cohort.</span>+ ) : (+ <Spinner className="text-sm" />+ )}+ </div>+ </div>+ </div>+ <LemonButton+ size="small"+ type="secondary"+ to={urls.cohort(id)}+ targetBlank+ sideIcon={<IconOpenInNew />}+ data-attr="broadcast-audience-open-cohort"+ >+ Open cohort+ </LemonButton>+ </div>+ )+ })}+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.test.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.test.tsnew file mode 100644index 000000000000..4ac505deded6--- /dev/null+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.test.ts@@ -0,0 +1,71 @@+import { ApiError } from 'lib/api-error'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { PropertyFilterType, PropertyOperator } from '~/types'++import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'++import { broadcastWizardLogic } from '../broadcastWizardLogic'+import { broadcastAudienceCohortsLogic } from './broadcastAudienceCohortsLogic'++jest.mock('products/cohorts/frontend/generated/api', () => ({ cohortsRetrieve: jest.fn() }))++const cohort = (isCalculating: boolean): any => ({+ id: 42,+ name: 'Spring sale recipients',+ is_static: true,+ is_calculating: isCalculating,+ errors_calculating: 0,+ count: isCalculating ? null : 2,+})++describe('broadcastAudienceCohortsLogic', () => {+ let audienceSizeRequests: number++ beforeEach(() => {+ audienceSizeRequests = 0+ useMocks({+ post: {+ '/api/projects/:team_id/hog_flows/user_blast_radius/': () => {+ audienceSizeRequests += 1+ return [200, { affected: 2, total: 10 }]+ },+ },+ })+ initKeaTests()+ })++ it('keeps a matching cohort through a failed poll and refreshes the audience size when matching ends', async () => {+ jest.useFakeTimers()+ try {+ jest.mocked(cohortsRetrieve)+ .mockResolvedValueOnce(cohort(true))+ .mockRejectedValueOnce(new ApiError('Server error', 500))+ .mockResolvedValueOnce(cohort(false))++ const wizard = broadcastWizardLogic({ id: 'new' })+ wizard.mount()+ wizard.actions.setAudienceProperties([+ { type: PropertyFilterType.Cohort, key: 'id', value: 42, operator: PropertyOperator.In },+ ])+ const logic = broadcastAudienceCohortsLogic({ id: 'new' })+ logic.mount()++ await jest.advanceTimersByTimeAsync(1000)+ expect(logic.values.audienceCohorts[42]).toMatchObject({ isCalculating: true })+ const requestsWhileMatching = audienceSizeRequests++ await jest.advanceTimersByTimeAsync(3500)+ expect(cohortsRetrieve).toHaveBeenCalledTimes(2)+ expect(logic.values.audienceCohorts[42]).toMatchObject({ isCalculating: true })++ await jest.advanceTimersByTimeAsync(3500)+ expect(cohortsRetrieve).toHaveBeenCalledTimes(3)+ expect(logic.values.audienceCohorts[42]).toMatchObject({ isCalculating: false, count: 2 })+ expect(audienceSizeRequests).toBeGreaterThan(requestsWhileMatching)+ } finally {+ jest.useRealTimers()+ }+ })+})diff --git a/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.tsnew file mode 100644index 000000000000..b91b9afb4c9b--- /dev/null+++ b/products/workflows/frontend/Broadcasts/audience/broadcastAudienceCohortsLogic.ts@@ -0,0 +1,158 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { subscriptions } from 'kea-subscriptions'++import { projectLogic } from 'scenes/projectLogic'++import { AnyPropertyFilter, PropertyFilterType } from '~/types'++import { cohortsRetrieve } from 'products/cohorts/frontend/generated/api'++import { BroadcastWizardLogicProps, broadcastWizardLogic } from '../broadcastWizardLogic'++export interface AudienceCohort {+ id: number+ name: string+ isStatic: boolean+ isCalculating: boolean+ failed: boolean+ count: number | null+ // Set for a cohort made from a list: how many people were on it and how many of them PostHog didn't find.+ importTotal: number | null+ importUnmatched: number | null+}++const POLL_MS = 3000++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastAudienceCohortsLogicValues {+ audienceProperties: AnyPropertyFilter[] // broadcastWizardLogic+ currentProjectId: number | null // projectLogic+ audienceCohorts: Record<number, AudienceCohort | null>+ cohortIds: number[]+ nonCohortAudience: AnyPropertyFilter[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastAudienceCohortsLogicActions {+ loadBlastRadius: () => any // broadcastWizardLogic+ loadAudienceCohorts: () => {+ value: true+ }+ setAudienceCohorts: (cohorts: Record<number, AudienceCohort | null>) => {+ cohorts: Record<number, AudienceCohort | null>+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastAudienceCohortsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ nonCohortAudience: (audienceProperties: AnyPropertyFilter[]) => AnyPropertyFilter[]+ cohortIds: (audienceProperties: AnyPropertyFilter[]) => number[]+ }+}++export type broadcastAudienceCohortsLogicType = MakeLogicType<+ broadcastAudienceCohortsLogicValues,+ broadcastAudienceCohortsLogicActions,+ BroadcastWizardLogicProps,+ broadcastAudienceCohortsLogicMeta+>++export const broadcastAudienceCohortsLogic = kea<broadcastAudienceCohortsLogicType>([+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'audience', 'broadcastAudienceCohortsLogic']),+ props({} as BroadcastWizardLogicProps),+ key((props) => props.id),+ connect((props: BroadcastWizardLogicProps) => ({+ values: [broadcastWizardLogic(props), ['audienceProperties'], projectLogic, ['currentProjectId']],+ actions: [broadcastWizardLogic(props), ['loadBlastRadius']],+ })),+ actions({+ loadAudienceCohorts: true,+ setAudienceCohorts: (cohorts: Record<number, AudienceCohort | null>) => ({ cohorts }),+ }),+ reducers({+ audienceCohorts: [+ {} as Record<number, AudienceCohort | null>,+ {+ setAudienceCohorts: (_, { cohorts }) => cohorts,+ },+ ],+ }),+ selectors({+ // The audience's other conditions. The cohorts in it are shown as cards with a link instead.+ nonCohortAudience: [+ (s) => [s.audienceProperties],+ (audienceProperties: AnyPropertyFilter[]): AnyPropertyFilter[] =>+ audienceProperties.filter((filter) => filter.type !== PropertyFilterType.Cohort),+ ],+ cohortIds: [+ (s) => [s.audienceProperties],+ (audienceProperties: AnyPropertyFilter[]): number[] => [+ ...new Set(+ audienceProperties+ .filter((filter) => filter.type === PropertyFilterType.Cohort)+ .map((filter) => Number(filter.value))+ .filter((id) => Number.isFinite(id))+ ),+ ],+ ],+ }),+ listeners(({ actions, values }) => ({+ loadAudienceCohorts: async (_, breakpoint) => {+ await breakpoint(100)+ const ids = values.cohortIds+ if (!values.currentProjectId || ids.length === 0) {+ actions.setAudienceCohorts({})+ return+ }+ const projectId = String(values.currentProjectId)+ const loaded = await Promise.all(+ ids.map(async (id): Promise<[number, AudienceCohort | null]> => {+ try {+ const cohort = await cohortsRetrieve(projectId, id)+ return [+ id,+ {+ id,+ name: cohort.name ?? `Cohort ${id}`,+ isStatic: !!cohort.is_static,+ isCalculating: !!cohort.is_calculating,+ failed: (cohort.errors_calculating ?? 0) > 0 && !cohort.is_calculating,+ count: cohort.count ?? null,+ importTotal: cohort.last_import_total_count ?? null,+ importUnmatched: cohort.last_import_unmatched_count ?? null,+ },+ ]+ } catch (error: any) {+ // A failed poll keeps the last card, so a cohort that is still matching keeps polling.+ // A deleted cohort has nothing left to show.+ return [id, error?.status === 404 ? null : (values.audienceCohorts[id] ?? null)]+ }+ })+ )+ breakpoint()+ const previous = values.audienceCohorts+ const cohorts = Object.fromEntries(loaded)+ actions.setAudienceCohorts(cohorts)+ // The audience size counts a cohort's members, so it is stale until matching finishes.+ if (ids.some((id) => previous[id]?.isCalculating && cohorts[id] && !cohorts[id]!.isCalculating)) {+ actions.loadBlastRadius()+ }+ if (Object.values(cohorts).some((cohort) => cohort?.isCalculating)) {+ await breakpoint(POLL_MS)+ actions.loadAudienceCohorts()+ }+ },+ })),+ subscriptions(({ actions }) => ({+ cohortIds: (next: number[], previous?: number[]) => {+ if (previous !== undefined && next.join() !== previous.join()) {+ actions.loadAudienceCohorts()+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadAudienceCohorts()+ }),+])diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsxindex 69aec3020cb5..9cf4e11b9c4f 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx@@ -11,6 +11,7 @@ import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohorimport { PropertyFilterType } from '~/types'import { WORKFLOW_OPERATOR_ALLOWLIST } from '../../Workflows/hogflows/filters/HogFlowFilters'+import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'import { broadcastWizardLogic } from '../broadcastWizardLogic'function AudienceSizePreview(): JSX.Element | null {@@ -56,7 +57,7 @@ export function BroadcastRecipientsStep(): JSX.Element {<div><h2 className="m-0 text-xl font-semibold">Who should receive this email?</h2><p className="m-0 text-secondary">- Filter by person properties or static cohorts. Without filters, the broadcast goes to everyone.+ Filter by person properties or cohorts. Without filters, the broadcast goes to everyone.</p></div><div>@@ -86,6 +87,7 @@ export function BroadcastRecipientsStep(): JSX.Element {hasRowOperator={false}operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}/>+ <BroadcastAudienceCohorts /></div>)}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsxindex cc1824e01808..497932748806 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { LemonButton, Spinner } from '@posthog/lemon-ui'@@ -6,6 +6,8 @@ import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/Primport { integrationsLogic } from 'lib/integrations/integrationsLogic'import { humanFriendlyNumber } from 'lib/utils/numbers'+import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'+import { broadcastAudienceCohortsLogic } from '../audience/broadcastAudienceCohortsLogic'import { BroadcastEmailPreview } from '../BroadcastEmailPreview'import { SENDERS_LOAD_FAILED_ERROR, broadcastWizardLogic } from '../broadcastWizardLogic'@@ -30,6 +32,8 @@ export function BroadcastReviewStep(): JSX.Element {rateLimitedSendDuration,stepValidationErrors,} = useValues(broadcastWizardLogic)+ const { props } = useMountedLogic(broadcastWizardLogic)+ const { nonCohortAudience } = useValues(broadcastAudienceCohortsLogic(props))const { integrationsLoading } = useValues(integrationsLogic)const { loadIntegrations } = useActions(integrationsLogic)@@ -59,7 +63,12 @@ export function BroadcastReviewStep(): JSX.Element {<span className="text-warning">Couldn't estimate the audience size</span>)}{audienceProperties.length > 0 ? (- <PropertyFiltersDisplay filters={audienceProperties} />+ <div className="flex flex-col gap-2">+ {nonCohortAudience.length > 0 ? (+ <PropertyFiltersDisplay filters={nonCohortAudience} />+ ) : null}+ <BroadcastAudienceCohorts />+ </div>) : (<div className="text-muted text-xs">No filters. This broadcast goes to everyone.</div>)}