: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): make a realtime cohort the only audience condition in the pickers (#117870)
Harley Alexanderf93d41f7611b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c85ced34e656..dac5b36fb992 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8286,6 +8286,10 @@ snapshots:hash: v1.k794b7964.9e7a12c3094416ddf703121095bc7eba5189420cab88d6967618bf43139069fe.UZSvEld_DwpzTPi6QpbRfxOtDYP7S_gR0F03DJcFMpMproducts-workflows-steps-delay--fixed-duration--light:hash: v1.k794b7964.f394f1e00c55c84136a291d5acb646dc12e0b27951a99e493137f7bad05a2082.zj4h9BHlkIR9RBHiB6nkO0QjDgPC1UKa08uSHemhjSQ+ products-workflows-steps-realtime-cohort-audience-notice--realtime-cohort-alone--dark:+ hash: v1.k794b7964.bc8c9c0ad8929ea53bb3df4da624383c361c01a651ec9bfa66663fcbcc122f05.Bu2CuSIJZsg2Spq21yzbDjK6v6oN8tdaNqFZ0VEyjsk+ products-workflows-steps-realtime-cohort-audience-notice--realtime-cohort-alone--light:+ hash: v1.k794b7964.4a9ff2c4e3f5e66013529fadb77e518d71710b07c4e9781bb1f5b6b5b50948b0.B0FigYdVbojq_vkX7nU1Apbg8EwbOfVVcGR4Fpe32xcproducts-workflows-steps-realtime-cohort-calculating-banner--calculating--dark:hash: v1.k794b7964.f8d96220904631c8b3272c69f05c32ae18aaa1f6ab885595fa093914fb4b9585.vMfQ-MPIZHxlUj7bQT739aLrmXkrNzq0avGb2p0mwmEproducts-workflows-steps-realtime-cohort-calculating-banner--calculating--light:diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 4578b6ae2184..d00664260d76 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -235,6 +235,8 @@ class AudienceSize:dedupe_key: str | None# Set when the audience is one realtime cohort. A send waits until that cohort is ready.realtime_cohort: RealtimeCohortStatus | None = None+ # Set when a realtime cohort shares the audience with other conditions, which a save rejects.+ realtime_cohort_with_other_conditions: RealtimeAudienceCohort | None = None@frozendiff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 97c1dca356f1..1b5aa5efc0dd 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -1069,6 +1069,11 @@ class RealtimeCohortStatusSerializer(serializers.Serializer):)+class RealtimeCohortRefSerializer(serializers.Serializer):+ id = serializers.IntegerField(help_text="ID of the realtime cohort.")+ name = serializers.CharField(help_text="Name of the realtime cohort.")++class BlastRadiusSerializer(serializers.Serializer):affected = serializers.IntegerField(help_text="Number of users matching the filters")total = serializers.IntegerField(help_text="Total number of users")@@ -1092,6 +1097,14 @@ class BlastRadiusSerializer(serializers.Serializer):"size, and a batch run waits until the cohort is ready."),)+ realtime_cohort_with_other_conditions = RealtimeCohortRefSerializer(+ required=False,+ allow_null=True,+ help_text=(+ "Set when a realtime cohort shares the audience with other conditions. Saving that audience fails: "+ "a realtime cohort has to be the only condition."+ ),+ )class InternalBlastRadiusPersonsSerializer(serializers.Serializer):@@ -6220,6 +6233,14 @@ class HogFlowViewSet(if realtime_cohortelse None),+ "realtime_cohort_with_other_conditions": (+ {+ "id": size.realtime_cohort_with_other_conditions.id,+ "name": size.realtime_cohort_with_other_conditions.name,+ }+ if size.realtime_cohort_with_other_conditions+ else None+ ),}).data)diff --git a/products/workflows/backend/services/blast_radius.py b/products/workflows/backend/services/blast_radius.pyindex edaac0836e93..9001b2c0d1c9 100644--- a/products/workflows/backend/services/blast_radius.py+++ b/products/workflows/backend/services/blast_radius.py@@ -8,7 +8,7 @@ from posthog.models.team.team import Teamfrom products.feature_flags.backend.person_sampling import bounded_memory_settingsfrom products.feature_flags.backend.user_blast_radius import get_user_blast_radius-from products.workflows.backend.facade.contracts import AudiencePage, AudienceSize+from products.workflows.backend.facade.contracts import AudiencePage, AudienceSize, RealtimeAudienceCohortfrom products.workflows.backend.services.account_audience import (ACCOUNT_BATCH_SIZE,get_account_audience_count,@@ -17,7 +17,13 @@ from products.workflows.backend.services.account_audience import ()from products.workflows.backend.services.audience_v2 import get_dedupe_audience_count_v2, get_person_audience_count_v2from products.workflows.backend.services.batch_audience import audience_page_size, get_batch_audience_person_ids-from products.workflows.backend.services.batch_audience_cohorts import realtime_audience_cohort, realtime_cohort_status+from products.workflows.backend.services.batch_audience_cohorts import (+ find_realtime_behavioral_cohort,+ realtime_audience_cohort,+ realtime_cohort_can_finish,+ realtime_cohort_is_ready,+ realtime_cohort_status,+)from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit# An open send screen re-sizes a realtime cohort audience every few seconds while the cohort calculates. The@@ -34,6 +40,20 @@ def _realtime_audience_total(team: Team) -> int:return total+def _top_level_cohort_ids(filters: dict) -> list[int | str]:+ """Cohort ids of the audience's top-level conditions, the only ones the pickers can show and clear."""+ properties = filters.get("properties")+ if not isinstance(properties, list):+ return []+ return [+ condition["value"]+ for condition in properties+ if isinstance(condition, dict)+ and condition.get("type") == "cohort"+ and isinstance(condition.get("value"), int | str)+ ]++def get_audience_size(*,team_id: int,@@ -68,11 +88,26 @@ def get_audience_size(else:blast_radius = get_person_audience_count_v2(team, filters)+ mixed_realtime_cohort = (+ find_realtime_behavioral_cohort(team.project_id, _top_level_cohort_ids(filters))+ if group_type_index is None+ else None+ )return AudienceSize(affected=blast_radius.affected,total=blast_radius.total,limit=get_hogflow_batch_trigger_limit(team_id, sends_email=sends_email),dedupe_key=applied_dedupe_key,+ realtime_cohort_with_other_conditions=(+ RealtimeAudienceCohort(+ id=mixed_realtime_cohort.pk,+ name=str(mixed_realtime_cohort.name),+ ready=realtime_cohort_is_ready(mixed_realtime_cohort),+ can_finish=realtime_cohort_can_finish(mixed_realtime_cohort),+ )+ if mixed_realtime_cohort is not None+ else None+ ),)diff --git a/products/workflows/backend/test/test_batch_audience.py b/products/workflows/backend/test/test_batch_audience.pyindex 7d5308ecb396..6f9fba4036b3 100644--- a/products/workflows/backend/test/test_batch_audience.py+++ b/products/workflows/backend/test/test_batch_audience.py@@ -148,3 +148,52 @@ class TestBatchAudience(ClickhouseTestMixin, BaseTest):assert (size.affected, size.total, size.dedupe_key) == (2, 3, None)assert size.realtime_cohort is not Noneassert (size.realtime_cohort.id, size.realtime_cohort.state) == (cohort.pk, expected_state)++ @parameterized.expand(+ [+ ("realtime", True, False, True),+ ("not_realtime", False, False, False),+ # The pickers can only show and clear top-level conditions, so a nested cohort isn't flagged.+ ("realtime_nested_in_a_group", True, True, False),+ ]+ )+ def test_audience_size_flags_a_realtime_cohort_mixed_with_other_conditions(+ self, _name, realtime, nested, expect_flagged+ ):+ self._create_audience(["[email protected]"])+ cohort = Cohort.objects.create(+ team=self.team,+ name="c",+ cohort_type=CohortType.REALTIME if realtime else None,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "key": "$pageview",+ "event_type": "events",+ "time_value": 30,+ "time_interval": "day",+ "value": "performed_event",+ "type": "behavioral",+ }+ ],+ }+ },+ )++ conditions = [+ {"key": "id", "type": "cohort", "value": cohort.pk, "operator": "in"},+ {"key": "email", "type": "person", "value": "x.com", "operator": "icontains"},+ ]+ size = get_audience_size(+ team_id=self.team.pk,+ filters={"properties": [{"type": "AND", "values": conditions}] if nested else conditions},+ group_type_index=None,+ dedupe_key=None,+ sends_email=True,+ )++ assert size.realtime_cohort is None+ mixed = size.realtime_cohort_with_other_conditions+ assert (mixed.id if mixed else None) == (cohort.pk if expect_flagged else None)diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.tsindex 818038813c07..e49ac15888b1 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts@@ -82,6 +82,7 @@ import type { UtmTagValues } from '../Workflows/hogflows/steps/components/UtmTagimport {REALTIME_COHORT_STATUS_POLL_MS,isRealtimeCohortUnresolved,+ keepOnlyRealtimeCohort,} from '../Workflows/hogflows/steps/realtimeCohortStatus'import { recipientEmailProperty } from '../Workflows/hogflows/steps/recipientEmail'import { ResourceSaveQueue } from '../Workflows/resourceSaveQueue'@@ -811,6 +812,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([})),reducers(({ props }) => ({+ blastRadius: {+ // A stale result would keep a realtime cohort's restrictions on an audience that no longer has one.+ loadBlastRadiusFailure: () => null,+ },broadcast: {saveBroadcastFinished: (state: HogFlowApi | null, { broadcast }: { broadcast: HogFlowApi | null }) =>broadcast ?? state,@@ -1356,6 +1361,14 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([}),listeners(({ actions, values, props, cache }) => ({+ loadBlastRadiusSuccess: ({ blastRadius }) => {+ // A realtime cohort has to be the only condition, so picking one replaces the others.+ const mixed = blastRadius?.realtime_cohort_with_other_conditions+ const onlyCohort = mixed ? keepOnlyRealtimeCohort(values.audienceProperties, mixed.id) : null+ if (onlyCohort) {+ actions.setAudienceProperties(onlyCohort)+ }+ },applyDefaultSender: () => {// Only fills an empty sender on a broadcast that is still being written. It is not an// edit, so it does not autosave; the next save or launch carries it.diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsxindex 51dd03bcd149..23a3a1a45ac9 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx@@ -18,6 +18,7 @@ import { AnyPersonScopeFilter, PropertyFilterType } from '~/types'import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'import { WORKFLOW_OPERATOR_ALLOWLIST } from '../../Workflows/hogflows/filters/HogFlowFilters'+import { RealtimeCohortAudienceNotice } from '../../Workflows/hogflows/steps/components/RealtimeCohortAudienceNotice'import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'import { broadcastAudienceListLogic } from '../audience/broadcastAudienceListLogic'import { BroadcastAudienceListModal } from '../audience/BroadcastAudienceListModal'@@ -145,7 +146,9 @@ function AudienceListModal({ isOpen, onClose }: { isOpen: boolean; onClose: () =export function BroadcastRecipientsStep(): JSX.Element {const cohortConditionsEnabled = useFeatureFlag('WORKFLOWS_COHORT_CONDITIONS')- const { audienceProperties, linkAudienceRejected } = useValues(broadcastWizardLogic)+ const { audienceProperties, linkAudienceRejected, blastRadius } = useValues(broadcastWizardLogic)+ // A realtime cohort has to be the audience's only condition.+ const realtimeCohortAlone = !!blastRadius?.realtime_cohort || !!blastRadius?.realtime_cohort_with_other_conditionsconst { setAudienceProperties, sendToEveryoneAfterRejectedLink } = useActions(broadcastWizardLogic)const { props } = useMountedLogic(broadcastWizardLogic)const { openListModal } = useActions(broadcastAudienceListLogic(props))@@ -191,6 +194,7 @@ export function BroadcastRecipientsStep(): JSX.Element {pageKey="broadcast-wizard-recipients"propertyFilters={audienceProperties}addText="Add condition"+ allowNew={!realtimeCohortAlone}orFilteringsendAllKeyUpdatesallowRelativeDateOptions@@ -211,17 +215,20 @@ export function BroadcastRecipientsStep(): JSX.Element {hasRowOperator={false}operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}/>- <div>- <LemonButton- type="secondary"- size="small"- icon={<IconUpload />}- onClick={openListModal}- data-attr="broadcast-audience-add-list"- >- Upload a list- </LemonButton>- </div>+ <RealtimeCohortAudienceNotice blastRadius={blastRadius} />+ {!realtimeCohortAlone && (+ <div>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconUpload />}+ onClick={openListModal}+ data-attr="broadcast-audience-add-list"+ >+ Upload a list+ </LemonButton>+ </div>+ )}<BroadcastAudienceCohorts /><BroadcastAudienceListModal /><MessageCategoryPicker />diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 372ea1753493..ade969814fd5 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -62,13 +62,15 @@ import {} from '../registry/triggers/triggerTypeRegistry'import { HogFlowAction } from '../types'import { createAccountAssignmentFilterUpdate, parseAccountAssignmentFilter } from './accountAssignmentFilter'-import { batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './batchTriggerLogic'+import { BatchTriggerLogicProps, batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './batchTriggerLogic'import { ConversionGoalEditor } from './components/ConversionGoalEditor'import { EmailSendingRateLimitPicker } from './components/EmailSendingRateLimitPicker'import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'+import { RealtimeCohortAudienceNotice } from './components/RealtimeCohortAudienceNotice'import { RecurringSchedulePicker } from './components/RecurringSchedulePicker'import { ScheduleStatusBadge } from './components/ScheduleStatusBadge'import { TriggerVolumeEstimate } from './components/TriggerVolumeEstimate'+import { keepOnlyRealtimeCohort } from './realtimeCohortStatus'type TriggerAction = Extract<HogFlowAction, { type: 'trigger' }>type EventTriggerConfig = {@@ -562,18 +564,25 @@ function WorkflowRecurringSchedulePicker(): JSX.Element {)}-function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; filters: any }): JSX.Element | null {- const { workflow } = useValues(workflowLogic)+function batchTriggerLogicProps(+ actionId: string,+ filters: any,+ workflow: { actions?: HogFlowAction[] } | null+): BatchTriggerLogicProps {const isAccountAudience = filters?.audience_type === 'accounts'- // Account audiences carry no person, so email dedup never applies to them.- const dedupeKey = isAccountAudience ? undefined : getAudienceDedupeKey(workflow)- const logic = batchTriggerLogic({+ return {id: actionId,filters,- dedupeKey,+ // Account audiences carry no person, so email dedup never applies to them.+ dedupeKey: isAccountAudience ? undefined : getAudienceDedupeKey(workflow),sendsEmail: hogFlowSendsEmail(workflow),- })- const { blastRadiusLoading, blastRadius, blastRadiusError } = useValues(logic)+ }+}++function StepTriggerAffectedUsers({ logicProps }: { logicProps: BatchTriggerLogicProps }): JSX.Element | null {+ const { workflow } = useValues(workflowLogic)+ const isAccountAudience = logicProps.filters?.audience_type === 'accounts'+ const { blastRadiusLoading, blastRadius, blastRadiusError } = useValues(batchTriggerLogic(logicProps))if (blastRadiusLoading) {return <Spinner className="mt-1" />@@ -718,8 +727,20 @@ function StepTriggerConfigurationBatch({config: Extract<HogFlowAction['config'], { type: 'batch' }>}): JSX.Element {const { partialSetWorkflowActionConfig } = useActions(workflowLogic)+ const { workflow } = useValues(workflowLogic)const { featureFlags } = useValues(featureFlagLogic)const { currentTeam } = useValues(teamLogic)+ const logicProps: BatchTriggerLogicProps = {+ ...batchTriggerLogicProps(action.id, config.filters, workflow),+ // A realtime cohort has to be the only condition, so picking one replaces the others.+ onRealtimeCohortWithOtherConditions: (cohortId) => {+ const onlyCohort = keepOnlyRealtimeCohort(config.filters.properties ?? [], cohortId)+ if (onlyCohort) {+ partialSetWorkflowActionConfig(action.id, { filters: { properties: onlyCohort } })+ }+ },+ }+ const { blastRadius } = useValues(batchTriggerLogic(logicProps))const accountAudienceAvailable =!!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] &&@@ -747,16 +768,17 @@ function StepTriggerConfigurationBatch({)}<div><span className="font-semibold">This batch will include</span>{' '}- <StepTriggerAffectedUsers actionId={action.id} filters={config.filters} />+ <StepTriggerAffectedUsers logicProps={logicProps} /></div>{isAccountAudience ? (<StepTriggerBatchAccountFilters actionId={action.id} filters={config.filters} />) : (- <div>+ <div className="flex flex-col gap-2"><PropertyFilterspageKey={`workflows-batch-trigger-property-filters-${action.id}`}propertyFilters={config.filters.properties}addText="Add condition"+ allowNew={!blastRadius?.realtime_cohort && !blastRadius?.realtime_cohort_with_other_conditions}orFilteringsendAllKeyUpdatesallowRelativeDateOptions@@ -783,6 +805,7 @@ function StepTriggerConfigurationBatch({hasRowOperator={false}operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}/>+ <RealtimeCohortAudienceNotice blastRadius={blastRadius} /></div>)}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.tsindex a5fc3615a849..88682e6f8b55 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts@@ -169,4 +169,41 @@ describe('batchTriggerLogic', () => {logic.unmount()})})++ describe('blastRadius', () => {+ it('drops a realtime cohort result when the next size check fails', async () => {+ let fail = false+ useMocks({+ post: {+ '/api/projects/:team_id/hog_flows/user_blast_radius/': () =>+ fail+ ? [500, { detail: 'boom' }]+ : [+ 200,+ {+ affected: 3,+ total: 5,+ limit: 1000,+ dedupe_key: null,+ confirm_token: 'token',+ realtime_cohort: { id: 2, name: 'c', state: 'ready', percent_complete: null },+ },+ ],+ },+ })+ initKeaTests()+ const logic = batchTriggerLogic({+ id: 'test-stale',+ filters: { properties: [{ key: 'id', type: 'cohort', value: 2, operator: 'in' }] as any },+ })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadBlastRadiusSuccess'])+ expect(logic.values.blastRadius?.realtime_cohort?.id).toBe(2)++ fail = true+ logic.actions.loadBlastRadius()+ await expectLogic(logic).toDispatchActions(['loadBlastRadiusFailure']).toMatchValues({ blastRadius: null })+ logic.unmount()+ })+ })})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.tsindex 5919d573ad63..7e41a0e400d0 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts@@ -58,6 +58,8 @@ export interface BatchTriggerLogicProps {sendsEmail?: boolean/** Person properties the email steps send to. Each costs one extra audience query, so pass them only where shown. */recipientEmailProperties?: string[]+ /** Called when a realtime cohort shares the audience with other conditions, so the caller can drop them. */+ onRealtimeCohortWithOtherConditions?: (cohortId: number) => void}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -218,11 +220,21 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([},],})),+ reducers({+ blastRadius: {+ // A stale result would keep a realtime cohort's restrictions on an audience that no longer has one.+ loadBlastRadiusFailure: () => null,+ },+ }),listeners(({ actions, props, values }) => ({loadBlastRadius: () => {actions.loadRecipientsWithoutEmail(null)},loadBlastRadiusSuccess: async ({ blastRadius }, breakpoint) => {+ const mixed = blastRadius?.realtime_cohort_with_other_conditions+ if (mixed) {+ props.onRealtimeCohortWithOtherConditions?.(mixed.id)+ }// Run reads the realtime cohort's status from the audience size, and the cohort can finish or recover// while the popover stays open. Only the size is refreshed, not the recipient check.if (!props.filters || !isRealtimeCohortUnresolved(blastRadius?.realtime_cohort)) {diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/RealtimeCohortAudienceNotice.stories.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/RealtimeCohortAudienceNotice.stories.tsxnew file mode 100644index 000000000000..81304fc8daba--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/RealtimeCohortAudienceNotice.stories.tsx@@ -0,0 +1,27 @@+import { Meta, StoryFn } from '@storybook/react'++import { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'++import { RealtimeCohortAudienceNotice } from './RealtimeCohortAudienceNotice'++const meta: Meta<typeof RealtimeCohortAudienceNotice> = {+ title: 'Products/Workflows/Steps/Realtime cohort audience notice',+ component: RealtimeCohortAudienceNotice,+}+export default meta++const base: BlastRadiusApi = { affected: 3, total: 5, limit: 1000, dedupe_key: null, confirm_token: 'token' }++const Template: StoryFn<{ blastRadius: BlastRadiusApi }> = ({ blastRadius }) => (+ <div className="w-120">+ <RealtimeCohortAudienceNotice blastRadius={blastRadius} />+ </div>+)++export const RealtimeCohortAlone = Template.bind({})+RealtimeCohortAlone.args = {+ blastRadius: {+ ...base,+ realtime_cohort: { id: 2, name: 'Viewed pricing', state: 'ready', percent_complete: null },+ },+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/RealtimeCohortAudienceNotice.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/RealtimeCohortAudienceNotice.tsxnew file mode 100644index 000000000000..810c298e4923--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/RealtimeCohortAudienceNotice.tsx@@ -0,0 +1,30 @@+import { LemonBanner, Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'++export interface RealtimeCohortAudienceNoticeProps {+ blastRadius: BlastRadiusApi | null | undefined+}++/** Explains why an audience that holds a realtime cohort takes no other conditions. */+export function RealtimeCohortAudienceNotice({ blastRadius }: RealtimeCohortAudienceNoticeProps): JSX.Element | null {+ if (blastRadius?.realtime_cohort || blastRadius?.realtime_cohort_with_other_conditions) {+ return (+ <LemonBanner type="info">+ Realtime cohorts can't be combined with other conditions. To narrow this audience,{' '}+ <Link+ to={urls.cohort('new')}+ // A new tab keeps an unsaved broadcast or workflow open.+ target="_blank"+ data-attr="workflows-realtime-cohort-create-cohort"+ >+ create a cohort+ </Link>{' '}+ with the extra conditions.+ </LemonBanner>+ )+ }+ return null+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/realtimeCohortStatus.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/realtimeCohortStatus.test.tsnew file mode 100644index 000000000000..7558f2e6e684--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/realtimeCohortStatus.test.ts@@ -0,0 +1,30 @@+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'++import { keepOnlyRealtimeCohort } from './realtimeCohortStatus'++const cohort = (id: number): AnyPropertyFilter =>+ ({ key: 'id', type: PropertyFilterType.Cohort, value: id, operator: PropertyOperator.In }) as AnyPropertyFilter+const email: AnyPropertyFilter = {+ key: 'email',+ type: PropertyFilterType.Person,+ value: 'example.com',+ operator: PropertyOperator.IContains,+}++describe('keepOnlyRealtimeCohort', () => {+ it.each([+ ['condition before the cohort', [email, cohort(2)], [cohort(2)]],+ ['another cohort beside it', [cohort(3), cohort(2)], [cohort(2)]],+ ])('keeps only the realtime cohort with %s', (_name, properties, expected) => {+ expect(keepOnlyRealtimeCohort(properties, 2)).toEqual(expected)+ })++ it.each([+ // A stale preview can name a cohort the author already removed.+ ['the cohort no longer in the audience', [email, cohort(3)]],+ ['the cohort alone already', [cohort(2)]],+ ['an empty audience', []],+ ])('changes nothing, never emptying the audience, with %s', (_name, properties) => {+ expect(keepOnlyRealtimeCohort(properties, 2)).toBeNull()+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/realtimeCohortStatus.ts b/products/workflows/frontend/Workflows/hogflows/steps/realtimeCohortStatus.tsindex c79a3a0535d4..deec12b9ed87 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/realtimeCohortStatus.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/realtimeCohortStatus.ts@@ -1,3 +1,5 @@+import { AnyPropertyFilter, PropertyFilterType } from '~/types'+import { RealtimeCohortStatusApi } from 'products/workflows/frontend/generated/api.schemas'/** How often an open send screen refreshes a realtime cohort's status until the cohort is ready. */@@ -8,6 +10,18 @@ export function isRealtimeCohortUnresolved(status: RealtimeCohortStatusApi | nulreturn !!status && status.state !== 'ready'}+/**+ * The audience reduced to its realtime cohort, which has to be the only condition. Null when the cohort is+ * not one of the audience's top-level conditions, for example when a preview response is stale or the+ * cohort sits in a nested group, so a caller never empties the audience to everyone.+ */+export function keepOnlyRealtimeCohort(properties: AnyPropertyFilter[], cohortId: number): AnyPropertyFilter[] | null {+ const cohort = properties.find(+ (property) => property.type === PropertyFilterType.Cohort && Number(property.value) === cohortId+ )+ return cohort && properties.length > 1 ? [cohort] : null+}+/** Whether the audience's realtime cohort is still calculating, so a send waits for it. */export function isRealtimeCohortCalculating(status: RealtimeCohortStatusApi | null | undefined): boolean {return status?.state === 'building' || status?.state === 'rebuilding'diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 27a8f7da96f0..9cce32d16882 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -2217,6 +2217,13 @@ export interface RealtimeCohortStatusApi {percent_complete: number | null}+export interface RealtimeCohortRefApi {+ /** ID of the realtime cohort. */+ id: number+ /** Name of the realtime cohort. */+ name: string+}+export interface BlastRadiusApi {/** Number of users matching the filters */affected: number@@ -2232,6 +2239,8 @@ export interface BlastRadiusApi {confirm_token: string/** Set when the audience is one realtime cohort. 'affected' is then the cohort's last calculated size, and a batch run waits until the cohort is ready. */realtime_cohort?: RealtimeCohortStatusApi | null+ /** Set when a realtime cohort shares the audience with other conditions. Saving that audience fails: a realtime cohort has to be the only condition. */+ realtime_cohort_with_other_conditions?: RealtimeCohortRefApi | null}export interface DataSuggestionBuildRequestApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d3cb048030d5..52191d938716 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18883,6 +18883,13 @@ export namespace Schemas {percent_complete: number | null;}+ export interface RealtimeCohortRef {+ /** ID of the realtime cohort. */+ id: number;+ /** Name of the realtime cohort. */+ name: string;+ }+export interface BlastRadius {/** Number of users matching the filters */affected: number;@@ -18898,6 +18905,8 @@ export namespace Schemas {confirm_token: string;/** Set when the audience is one realtime cohort. 'affected' is then the cohort's last calculated size, and a batch run waits until the cohort is ready. */realtime_cohort?: RealtimeCohortStatus | null;+ /** Set when a realtime cohort shares the audience with other conditions. Saving that audience fails: a realtime cohort has to be the only condition. */+ realtime_cohort_with_other_conditions?: RealtimeCohortRef | null;}/**