: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): send a broadcast to people who have a feature flag (#113009)
Daniel Marchuk2b8ca36a962f
diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex f82686996aef..8539ea5ea1b1 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -4,7 +4,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { Suspense, lazy, useEffect, useMemo, useState } from 'react'-import { IconArchive, IconCopy, IconPlusSmall, IconRewind, IconTrash } from '@posthog/icons'+import { IconArchive, IconCopy, IconPlusSmall, IconRewind, IconSend, IconTrash } from '@posthog/icons'import { LemonSkeleton } from '@posthog/lemon-ui'import { Badge, Button } from '@posthog/quill'@@ -29,7 +29,7 @@ import 'lib/lemon-ui/Lettermark'import { Link } from 'lib/lemon-ui/Link'import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'-import { userHasAccess } from 'lib/utils/accessControlUtils'+import { getAccessControlDisabledReason, userHasAccess } from 'lib/utils/accessControlUtils'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { addProductIntentForCrossSell } from 'lib/utils/product-intents'import { retryImport } from 'lib/utils/retryImport'@@ -98,7 +98,12 @@ import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'import { ExperimentsTab } from './FeatureFlagExperimentsTab'import { FeedbackTab } from './FeatureFlagFeedbackTab'import { FeatureFlagLoadError } from './FeatureFlagLoadError'-import { FeatureFlagLogicProps, featureFlagLogic } from './featureFlagLogic'+import {+ FINDING_FLAG_PEOPLE_MESSAGE,+ FeatureFlagLogicProps,+ broadcastNoOneReason,+ featureFlagLogic,+} from './featureFlagLogic'import { FeatureFlagOverview } from './FeatureFlagOverview'import FeatureFlagProjects from './FeatureFlagProjects'import { FeatureFlagRulesV2Editor } from './FeatureFlagRulesV2Editor'@@ -153,6 +158,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {dependentFlags,configFormat,editorKind,+ broadcastCohortLoading,} = useValues(featureFlagLogic)const isV1Config = configFormat === 'v1'const canRestore = canRestoreFeatureFlag(featureFlag.filters)@@ -163,6 +169,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {restoreFeatureFlag,editFeatureFlag,createStaticCohort,+ findOrCreateBroadcastCohort,setSelectedTab,saveDescriptionInline,saveTagsInline,@@ -202,6 +209,10 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {}const isNewFeatureFlag = id === 'new' || id === undefined+ const canCreateFlagCohort = isV1Config && !!featureFlags[FEATURE_FLAGS.FEATURE_FLAG_COHORT_CREATION]+ const broadcastDisabledReason =+ getAccessControlDisabledReason(AccessControlResourceType.Workflow, AccessControlLevel.Editor) ??+ (broadcastCohortLoading ? FINDING_FLAG_PEOPLE_MESSAGE : broadcastNoOneReason(featureFlag))// Expose the flag's release conditions to PostHog AI so it can answer "who does this match?"// and build an equivalent insight. The blast-radius endpoint only returns counts, so without@@ -432,7 +443,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {</ButtonPrimitive>)}<SceneAddToNotebookDropdownMenu dataAttrKey={RESOURCE_TYPE} />- {isV1Config && featureFlags[FEATURE_FLAGS.FEATURE_FLAG_COHORT_CREATION] && (+ {canCreateFlagCohort && (<ButtonPrimitivemenuItemdata-attr={`${RESOURCE_TYPE}-create-cohort`}@@ -442,6 +453,18 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {Create cohort</ButtonPrimitive>)}+ {canCreateFlagCohort && (+ <ButtonPrimitive+ menuItem+ data-attr={`${RESOURCE_TYPE}-message-audience-broadcast`}+ onClick={() => findOrCreateBroadcastCohort()}+ disabled={!!broadcastDisabledReason}+ tooltip={broadcastDisabledReason}+ >+ <IconSend />+ Send a broadcast+ </ButtonPrimitive>+ )}<ButtonPrimitivemenuItemdata-attr={`${RESOURCE_TYPE}-create-survey`}@@ -599,7 +622,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {}}/>)}- {isV1Config && featureFlags[FEATURE_FLAGS.FEATURE_FLAG_COHORT_CREATION] && (+ {canCreateFlagCohort && (<SceneMenuBarItemonClick={() => createStaticCohort()}data-attr={`${RESOURCE_TYPE}-menubar-create-cohort`}@@ -608,6 +631,17 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {Cohort</SceneMenuBarItem>)}+ {canCreateFlagCohort && (+ <SceneMenuBarItem+ onClick={() => findOrCreateBroadcastCohort()}+ disabled={!!broadcastDisabledReason}+ tooltip={broadcastDisabledReason}+ data-attr={`${RESOURCE_TYPE}-menubar-message-audience-broadcast`}+ >+ <IconSend />+ Broadcast+ </SceneMenuBarItem>+ )}<SceneMenuBarItemopensFloatingUionClick={() => handleGetFeedback()}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 16260a348188..41a8df5696e2 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -1,5 +1,6 @@import {MOCK_DEFAULT_BASIC_USER,+ MOCK_DEFAULT_USER,MOCK_DEFAULT_ORGANIZATION,MOCK_DEFAULT_PROJECT,MOCK_DEFAULT_TEAM,@@ -110,6 +111,8 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({error: jest.fn(),warning: jest.fn(),info: jest.fn(),+ loading: jest.fn((_message, options) => options?.toastId),+ dismiss: jest.fn(),},}))@@ -1262,6 +1265,318 @@ describe('featureFlagLogic', () => {})})+ describe('send a broadcast to the people who have the flag', () => {+ const COHORT = { id: 42, name: 'Users with feature flag test-flag enabled' }+ const FILLING = { ...COHORT, is_calculating: true, errors_calculating: 0 }+ const READY = { ...COHORT, is_calculating: false, errors_calculating: 0 }+ const FAILED = { ...COHORT, is_calculating: false, errors_calculating: 1 }++ it.each([+ {+ scenario: 'opens the broadcast once the cohort fills on the third check',+ polls: [FILLING, FILLING, READY],+ expectedPolls: 3,+ outcome: 'opened',+ },+ {+ scenario: 'shows an error when the cohort fails to fill',+ polls: [FAILED],+ expectedPolls: 1,+ outcome: 'error',+ },+ {+ scenario: 'points to the cohort when it is still filling after the wait',+ polls: [FILLING],+ expectedPolls: 31,+ outcome: 'still filling',+ },+ {+ scenario: 'points to the cohort when a status check stalls past the wait',+ polls: [FILLING],+ expectedPolls: 2,+ outcome: 'still filling',+ stallAfter: 1,+ },+ {+ scenario: 'offers the broadcast in a toast when the person left the flag page',+ polls: [READY],+ expectedPolls: 1,+ outcome: 'offered',+ startPath: urls.cohorts(),+ },+ {+ scenario: 'offers the broadcast in a toast after leaving the flag page unmounts its logic',+ polls: [FILLING, READY],+ expectedPolls: 2,+ outcome: 'offered',+ startPath: urls.cohorts(),+ unmountOnLeave: true,+ },+ ])('$scenario', async ({ polls, expectedPolls, outcome, startPath, unmountOnLeave, stallAfter }) => {+ jest.useFakeTimers()+ router.actions.push(urls.featureFlag(MOCK_FEATURE_FLAG.id))+ let pollCount = 0+ useMocks({+ post: {+ '/api/projects/:projectId/feature_flags/:id/create_static_cohort_for_flag/': () => [+ 201,+ { cohort: FILLING },+ ],+ },+ get: {+ '/api/projects/:projectId/cohorts/': () => [200, { count: 0, results: [] }],+ '/api/projects/:projectId/cohorts/42/': () => {+ const poll = pollCount+++ if (stallAfter !== undefined && poll >= stallAfter) {+ return new Promise(() => {})+ }+ return [200, polls[Math.min(poll, polls.length - 1)]]+ },+ },+ })++ logic.actions.findOrCreateBroadcastCohort()+ if (startPath) {+ router.actions.push(startPath)+ }+ if (unmountOnLeave) {+ await jest.advanceTimersByTimeAsync(500)+ logic.unmount()+ }+ await jest.advanceTimersByTimeAsync(61_000)+ if (unmountOnLeave) {+ logic.mount()+ }+ await expectLogic(logic).toFinishAllListeners()++ expect(pollCount).toBe(expectedPolls)+ expect(capturesOf('message audience clicked')).toEqual([+ ['message audience clicked', { source: 'feature_flag', destination: 'broadcast' }],+ ])+ expect(lemonToast.loading).toHaveBeenCalledTimes(1)+ expect(lemonToast.dismiss).toHaveBeenCalledWith((lemonToast.loading as jest.Mock).mock.results[0].value)+ const broadcastDetails = { name: 'test-flag announcement', source: 'feature_flag' }+ if (outcome === 'opened') {+ expect(router.values.location.pathname).toContain('/broadcasts/new')+ expect(JSON.parse(router.values.searchParams.audience)).toEqual([+ expect.objectContaining({ type: 'cohort', value: 42 }),+ ])+ expect(router.values.searchParams).toMatchObject(broadcastDetails)+ return+ }+ expect(router.values.location.pathname).toContain(startPath ?? urls.featureFlag(MOCK_FEATURE_FLAG.id))+ if (outcome === 'error') {+ expect(lemonToast.error).toHaveBeenCalledWith(+ "Couldn't find the people who have this flag. Try again in a few minutes."+ )+ } else if (outcome === 'still filling') {+ const [message, { button }] = (lemonToast.info as jest.Mock).mock.calls[0]+ expect(message).toContain('Still finding the people who have this flag')+ button.action()+ expect(router.values.location.pathname).toContain(urls.cohort(42))+ } else {+ const [, { button }] = (lemonToast.success as jest.Mock).mock.calls[0]+ expect(button.label).toBe('Open broadcast')+ button.action()+ expect(router.values.location.pathname).toContain('/broadcasts/new')+ expect(router.values.searchParams).toMatchObject(broadcastDetails)+ }+ })++ it.each([+ ['a dropped connection', {}, 1],+ ['an HTTP error the shared loader toast already reports', { status: 500 }, 0],+ ])('reports a failed broadcast lookup after %s', (_, errorObject, errorToasts) => {+ logic.actions.findOrCreateBroadcastCohortFailure('failed', errorObject)++ expect(lemonToast.error).toHaveBeenCalledTimes(errorToasts)+ })++ it.each([+ {+ scenario: 'targets groups',+ flag: { filters: { ...MOCK_FEATURE_FLAG.filters, aggregation_group_type_index: 0 } },+ message: 'This flag targets groups, not people, so there is no one to email.',+ },+ {+ scenario: 'was archived after the page loaded',+ flag: { archived: true, active: false },+ message: 'This flag is archived, so no one has it. Unarchive and enable it first.',+ },+ {+ scenario: 'was disabled after the page loaded',+ flag: { active: false },+ message: 'This flag is disabled, so no one has it. Enable it first.',+ },+ ])('makes no cohort when the saved flag $scenario', async ({ flag, message }) => {+ const createStaticCohort = jest.fn(() => [201, { cohort: FILLING }])+ useMocks({+ post: {+ '/api/projects/:projectId/feature_flags/:id/create_static_cohort_for_flag/': createStaticCohort,+ },+ get: { [FLAG_URL]: () => [200, { ...MOCK_FEATURE_FLAG, ...flag }] },+ })++ logic.actions.findOrCreateBroadcastCohort()+ await expectLogic(logic).toFinishAllListeners()++ expect(lemonToast.error).toHaveBeenCalledWith(message)+ expect(createStaticCohort).not.toHaveBeenCalled()+ expect(router.values.location.pathname).not.toContain('/broadcasts/new')+ })++ const NOW = new Date('2026-10-07T12:00:00Z')+ const minutesAgo = (minutes: number): string => new Date(NOW.getTime() - minutes * 60_000).toISOString()+ const listedCohort = (+ flagKey: string,+ createdAt: string,+ createdByUuid: string = MOCK_DEFAULT_BASIC_USER.uuid+ ): Record<string, any> => ({+ id: 7,+ name: `Users with feature flag ${flagKey} enabled at 2026-10-07 11:50:00`,+ created_by: { id: 1, uuid: createdByUuid },+ is_static: true,+ deleted: false,+ errors_calculating: 0,+ is_calculating: false,+ created_at: createdAt,+ })++ it.each([+ {+ scenario: 'reuses a recent cohort for this flag',+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10)),+ usesCohortId: 7,+ },+ {+ scenario: 'creates a cohort when the existing one is over an hour old',+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(61)),+ usesCohortId: 42,+ },+ {+ scenario: 'creates a cohort when the flag was saved after the recent one was made',+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10)),+ flagUpdatedAt: minutesAgo(5),+ usesCohortId: 42,+ },+ {+ scenario: 'creates a cohort when the flag changed on the server after this page loaded it',+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10)),+ serverUpdatedAt: minutesAgo(5),+ usesCohortId: 42,+ },+ {+ scenario: 'reuses a cohort still filling past the hour instead of starting a second scan',+ listed: () => ({ ...listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(90)), is_calculating: true }),+ usesCohortId: 7,+ },+ {+ scenario: 'creates a cohort when the one still filling is past the fill limit',+ listed: () => ({ ...listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(241)), is_calculating: true }),+ usesCohortId: 42,+ },+ {+ scenario: 'finds a reusable cohort past a first page of newer cohorts',+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10)),+ newerPage: true,+ usesCohortId: 7,+ },+ {+ scenario: 'creates a cohort when the recent one failed to fill',+ listed: () => ({ ...listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10)), errors_calculating: 1 }),+ usesCohortId: 42,+ },+ {+ scenario: 'creates a cohort when someone changed who is in the recent one',+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10)),+ edited: true,+ usesCohortId: 42,+ },+ {+ scenario: "creates a cohort when the recent one's history can't be read",+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10)),+ activityFails: true,+ usesCohortId: 42,+ },+ {+ scenario: 'creates a cohort when another user made the recent one',+ listed: () => listedCohort(MOCK_FEATURE_FLAG.key, minutesAgo(10), 'another-user-uuid'),+ usesCohortId: 42,+ },+ {+ scenario: 'creates a cohort when the recent one belongs to a flag whose key extends this one',+ listed: () => listedCohort(`${MOCK_FEATURE_FLAG.key}-2`, minutesAgo(10)),+ usesCohortId: 42,+ },+ ])(+ '$scenario',+ async ({ listed, usesCohortId, flagUpdatedAt, serverUpdatedAt, newerPage, edited, activityFails }) => {+ jest.useFakeTimers()+ jest.setSystemTime(NOW)+ router.actions.push(urls.featureFlag(MOCK_FEATURE_FLAG.id))+ const createStaticCohort = jest.fn(() => [201, { cohort: FILLING }])+ const existing = listed()+ const listParams: URLSearchParams[] = []+ let flagLoads = 0+ useMocks({+ post: {+ '/api/projects/:projectId/feature_flags/:id/create_static_cohort_for_flag/': createStaticCohort,+ },+ get: {+ [FLAG_URL]: () => {+ const updatedAt = flagLoads++ === 0 ? flagUpdatedAt : (serverUpdatedAt ?? flagUpdatedAt)+ return [200, { ...MOCK_FEATURE_FLAG, updated_at: updatedAt ?? minutesAgo(120) }]+ },+ '/api/projects/:projectId/cohorts/': ({ request }) => {+ const params = new URL(request.url).searchParams+ listParams.push(params)+ if (newerPage && params.get('offset') === '0') {+ const others = Array.from({ length: 20 }, (_, index) => ({+ ...listedCohort(`other-flag-${index}`, minutesAgo(5)),+ id: 100 + index,+ }))+ return [200, { count: 21, next: 'more', results: others }]+ }+ return [200, { count: 1, results: [existing] }]+ },+ '/api/projects/:projectId/cohorts/7/activity/': () =>+ activityFails+ ? [402, { detail: 'This feature is part of the premium PostHog offering.' }]+ : [+ 200,+ {+ next: null,+ previous: null,+ results: edited ? [{ activity: 'persons_added_manually' }] : [],+ },+ ],+ '/api/projects/:projectId/cohorts/7/': () => [200, { ...existing, is_calculating: false }],+ '/api/projects/:projectId/cohorts/42/': () => [200, READY],+ },+ })++ logic.unmount()+ logic = featureFlagLogic({ id: 1 })+ logic.mount()+ await jest.advanceTimersByTimeAsync(1_000)++ logic.actions.findOrCreateBroadcastCohort()+ await jest.advanceTimersByTimeAsync(5_000)+ await expectLogic(logic).toFinishAllListeners()+ expect(Object.fromEntries(listParams[0])).toEqual({+ type: 'static',+ created_by_id: String(MOCK_DEFAULT_USER.id),+ limit: '20',+ offset: '0',+ })+ expect(createStaticCohort).toHaveBeenCalledTimes(usesCohortId === 7 ? 0 : 1)+ expect(JSON.parse(router.values.searchParams.audience)).toEqual([+ expect.objectContaining({ type: 'cohort', value: usesCohortId }),+ ])+ }+ )+ })+describe('setMultivariateEnabled functionality', () => {it('adds default variants when enabling multivariate', async () => {await expectLogic(logic).toMatchValues({diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 9812688bf78b..c1857ecee363 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -24,7 +24,7 @@ import { CombinedLocation } from 'kea-router/lib/utils'import posthog from 'posthog-js'import { toast } from 'react-toastify'-import api, { PaginatedResponse } from 'lib/api'+import api, { PaginatedResponse, isAbortError } from 'lib/api'import { isAccessDeniedError, isApprovalRequiredError } from 'lib/api-error'import { handleApprovalRequired } from 'lib/approvals/utils'import { ACTIVITY_SEARCH_PARAM } from 'lib/components/ActivityLog/activityLogLogic'@@ -89,6 +89,9 @@ import {SurveyQuestionType,} from '~/types'+import { cohortsList, cohortsRetrieve } from 'products/cohorts/frontend/generated/api'+import { cohortsActivityRetrieve } from 'products/cohorts/frontend/generated/api'+import type { CohortApi } from 'products/cohorts/frontend/generated/api.schemas'import { NEW_EARLY_ACCESS_FEATURE } from 'products/early_access_features/frontend/earlyAccessFeatureLogic'import {FeatureFlagConfigFormat,@@ -103,6 +106,7 @@ import { TEMPLATE_NAMES } from 'products/feature_flags/frontend/featureFlagTemplimport {featureFlagsCopyFlagsCreate,featureFlagsCopyFlagsDependencyRequirementsCreate,+ featureFlagsCreateStaticCohortForFlagCreate,featureFlagsList,featureFlagsRetrieve,featureFlagsStatusRetrieve,@@ -111,6 +115,11 @@ import type {CopyFlagsDependencyRequirementsResponseApi,FeatureFlagStatusResponseApi,} from 'products/feature_flags/frontend/generated/api.schemas'+import {+ captureMessageAudienceClicked,+ cohortAudienceProperties,+ messageAudienceUrl,+} from 'products/workflows/frontend/MessageAudience/messageAudience'import type { CopyFlagsResponseApi } from '../../../../products/feature_flags/frontend/generated/api.schemas'import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'@@ -157,6 +166,83 @@ import {} from './scheduleOccurrences'import { flagToggleKey, updateFlagActiveInProject } from './updateFlagActiveInProject'+const BROADCAST_COHORT_POLL_MS = 2000+const BROADCAST_COHORT_WAIT_MS = 60_000+const BROADCAST_COHORT_PAGE_SIZE = 20+// A flag cohort is a snapshot, so reuse it only while it still reflects who has the flag now.+const REUSABLE_FLAG_COHORT_MAX_AGE_MS = 60 * 60 * 1000+// insert_cohort_from_feature_flag stops at a 4-hour soft limit, so a cohort still calculating after that is stuck.+const FLAG_COHORT_MAX_FILL_MS = 4 * 60 * 60 * 1000+// pinned: sent as the broadcast's entry_source and the click event's source, so renaming it splits the history+const FLAG_BROADCAST_SOURCE = 'feature_flag'+export const FINDING_FLAG_PEOPLE_MESSAGE = 'Finding the people who have this flag…'++function flagCohortNamePrefix(flagKey: string): string {+ // Matches the name that create_static_cohort_for_flag gives its cohort. Renaming it there stops reuse here.+ return `Users with feature flag ${flagKey} enabled at`+}++function reusableFlagCohorts(+ cohorts: CohortApi[],+ flag: Pick<FeatureFlagType, 'key' | 'updated_at'>,+ userUuid: string,+ now: number+): CohortApi[] {+ // A cohort made before the flag's last save can hold people the current conditions no longer match.+ if (!flag.updated_at) {+ return []+ }+ const flagUpdatedAt = new Date(flag.updated_at).getTime()+ const prefix = `${flagCohortNamePrefix(flag.key)} `+ const reusable = cohorts.filter(+ (cohort) =>+ !!cohort.name?.startsWith(prefix) &&+ // Any project member can create a cohort with this name, so only the current user's own snapshot is trusted.+ cohort.created_by?.uuid === userUuid &&+ cohort.is_static === true &&+ !cohort.deleted &&+ cohort.errors_calculating === 0 &&+ !!cohort.created_at &&+ new Date(cohort.created_at).getTime() >= flagUpdatedAt &&+ // A cohort still filling shares its running scan, so a later click doesn't start a second one.+ now - new Date(cohort.created_at).getTime() <+ (cohort.is_calculating ? FLAG_COHORT_MAX_FILL_MS : REUSABLE_FLAG_COHORT_MAX_AGE_MS)+ )+ reusable.sort((a, b) => new Date(b.created_at as string).getTime() - new Date(a.created_at as string).getTime())+ return reusable+}++async function flagCohortWasEdited(projectId: string, cohortId: number): Promise<boolean> {+ // Creating and filling the snapshot logs no activity, so any entry means someone edited its people by hand.+ // When the history can't be read, a fresh snapshot is the safe choice.+ try {+ const { results } = await cohortsActivityRetrieve(projectId, cohortId, { limit: 1 })+ return results.length > 0+ } catch {+ return true+ }+}++/** Why a broadcast to this flag's audience would reach no one, if it would. */+export function broadcastNoOneReason(+ flag: Pick<FeatureFlagType, 'deleted' | 'archived' | 'active' | 'filters'> | null | undefined+): string | undefined {+ if (flag?.deleted) {+ return 'This flag is deleted'+ }+ if (flag?.archived) {+ return 'This flag is archived, so no one has it. Unarchive and enable it first.'+ }+ if (!flag?.active) {+ return 'This flag is disabled, so no one has it. Enable it first.'+ }+ // The cohort task skips group-targeted flags, so their cohort stays empty.+ if (flag.filters?.aggregation_group_type_index != null) {+ return 'This flag targets groups, not people, so there is no one to email.'+ }+ return undefined+}+function reportFailedToCreateFeatureFlagWithCohort(code: string, detail: string): void {posthog.capture('failed to create feature flag with cohort', { detail, code })}@@ -587,10 +673,84 @@ export interface FeatureFlagLogicProps {id: number | 'new' | 'link'}+function dismissBroadcastProgress(cache: Record<string, any>): void {+ if (cache.broadcastToastId) {+ lemonToast.dismiss(cache.broadcastToastId)+ cache.broadcastToastId = null+ }+}+function isOnFeatureFlagPage(id: FeatureFlagLogicProps['id']): boolean {return removeProjectIdIfPresent(router.values.location.pathname) === urls.featureFlag(id)}+// Leaving the flag page unmounts its logic, so the wait and its outcome avoid breakpoints and the logic's values.+async function waitForFlagCohort(projectId: string, cohortId: number): Promise<CohortApi> {+ const deadline = Date.now() + BROADCAST_COHORT_WAIT_MS+ // Each request gets what is left of the wait, so a stalled one cannot hold the toast past the deadline.+ const retrieve = async (): Promise<CohortApi> => {+ // A plain abort, because the API client passes AbortError through but wraps a TimeoutError.+ const controller = new AbortController()+ const timer = window.setTimeout(+ () => controller.abort(),+ Math.max(deadline - Date.now(), BROADCAST_COHORT_POLL_MS)+ )+ try {+ return await cohortsRetrieve(projectId, cohortId, { signal: controller.signal })+ } finally {+ window.clearTimeout(timer)+ }+ }+ let status = await retrieve()+ while (status.is_calculating && Date.now() < deadline) {+ await new Promise((resolve) => window.setTimeout(resolve, BROADCAST_COHORT_POLL_MS))+ try {+ status = await retrieve()+ } catch (error) {+ if (isAbortError(error)) {+ return status+ }+ throw error+ }+ }+ return status+}++function showFlagCohortOutcome(cohort: CohortApi, flagId: FeatureFlagLogicProps['id'], flagKey: string): void {+ if (cohort.errors_calculating > 0) {+ lemonToast.error("Couldn't find the people who have this flag. Try again in a few minutes.")+ return+ }+ if (cohort.is_calculating) {+ lemonToast.info(+ 'Still finding the people who have this flag. Send the broadcast from the cohort once it is ready.',+ {+ button: {+ label: 'View cohort',+ action: () => router.actions.push(urls.cohort(cohort.id)),+ },+ }+ )+ return+ }+ const broadcastUrl = messageAudienceUrl(+ {+ source: FLAG_BROADCAST_SOURCE,+ properties: cohortAudienceProperties(cohort),+ broadcastName: `${flagKey} announcement`,+ },+ 'broadcast'+ )+ if (isOnFeatureFlagPage(flagId)) {+ router.actions.push(broadcastUrl)+ return+ }+ // The wait can outlast the visit, so don't pull someone off the page they moved to.+ lemonToast.success('The people who have this flag are ready for your broadcast.', {+ button: { label: 'Open broadcast', action: () => router.actions.push(broadcastUrl) },+ })+}+/*** Copies a just-created flag into the extra projects picked on the creation form.* Reports the per-project outcome itself and never throws: the flag already exists,@@ -959,6 +1119,8 @@ export interface featureFlagLogicValues {alsoCreateInProjects: number[]availableTabs: FeatureFlagsTab[]breadcrumbs: Breadcrumb[]+ broadcastCohort: CohortApi | null+ broadcastCohortLoading: booleancanCreateEarlyAccessFeature: booleancanCreatePairedSchedule: booleancompletedSchedules: ScheduledChangeType[]@@ -1351,6 +1513,21 @@ export interface featureFlagLogicActions {editing: booleanexpandAdvanced: boolean}+ findOrCreateBroadcastCohort: (_: void) => void+ findOrCreateBroadcastCohortFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ findOrCreateBroadcastCohortSuccess: (+ broadcastCohort: CohortApi | null,+ payload?: void+ ) => {+ broadcastCohort: CohortApi | null+ payload?: void+ }loadCopyDependencyRequirements: () => {value: true}@@ -3151,7 +3328,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},})),- loaders(({ values, props, actions }) => ({+ loaders(({ values, props, actions, cache }) => ({featureFlag: {loadFeatureFlag: async () => {const sourceId = router.values.searchParams.sourceId@@ -3646,6 +3823,62 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},},],+ broadcastCohort: [+ null as CohortApi | null,+ {+ findOrCreateBroadcastCohort: async (_: void, breakpoint) => {+ if (!props.id || props.id === 'new' || props.id === 'link' || !values.currentProjectId) {+ return null+ }+ const projectId = String(values.currentProjectId)+ // The tab's copy of the flag can be older than a teammate's edit or a scheduled change.+ const flag = (await featureFlagsRetrieve(projectId, props.id)) as unknown as FeatureFlagType+ breakpoint()+ const noOneReason = broadcastNoOneReason(flag)+ if (noOneReason) {+ lemonToast.error(noOneReason)+ return null+ }+ const user = values.user+ let cohortId: number | null = null+ if (user) {+ const now = Date.now()+ // Newest first, so paging stops once a page reaches cohorts too old to reuse.+ for (let offset = 0; cohortId === null; offset += BROADCAST_COHORT_PAGE_SIZE) {+ const { results, next } = await cohortsList(projectId, {+ type: 'static',+ created_by_id: user.id,+ limit: BROADCAST_COHORT_PAGE_SIZE,+ offset,+ })+ breakpoint()+ for (const candidate of reusableFlagCohorts(results, flag, user.uuid, now)) {+ const edited = await flagCohortWasEdited(projectId, candidate.id)+ breakpoint()+ if (!edited) {+ cohortId = candidate.id+ break+ }+ }+ const oldest = results[results.length - 1]?.created_at+ if (!next || !oldest || now - new Date(oldest).getTime() >= FLAG_COHORT_MAX_FILL_MS) {+ break+ }+ }+ }+ if (cohortId === null) {+ const { cohort } = await featureFlagsCreateStaticCohortForFlagCreate(projectId, props.id)+ breakpoint()+ cohortId = cohort.id+ }+ // The cohort fills in the background. Opening the broadcast earlier would let it send to no one.+ const status = await waitForFlagCohort(projectId, cohortId)+ dismissBroadcastProgress(cache)+ showFlagCohortOutcome(status, props.id, flag.key)+ return status+ },+ },+ ],projectsWithCurrentFlag: {__default: [] as OrganizationFeatureFlag[],loadProjectsWithCurrentFlag: async () => {@@ -4656,6 +4889,22 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.loadCopyDependencyRequirements()}},+ findOrCreateBroadcastCohort: () => {+ captureMessageAudienceClicked(FLAG_BROADCAST_SOURCE, 'broadcast')+ dismissBroadcastProgress(cache)+ cache.broadcastToastId = lemonToast.loading(FINDING_FLAG_PEOPLE_MESSAGE, {+ // A fresh id per click: a dismissed id stays cancelled, which would hide the next click's toast.+ toastId: `flag-broadcast-${props.id}-${Date.now()}`,+ autoClose: false,+ })+ },+ findOrCreateBroadcastCohortFailure: ({ errorObject }) => {+ dismissBroadcastProgress(cache)+ // The shared loader error toast needs an HTTP status, which a dropped connection never has.+ if (errorObject?.status === undefined) {+ lemonToast.error("Couldn't reach PostHog to find the people who have this flag. Try again.")+ }+ },createStaticCohortSuccess: ({ newCohort }) => {if (newCohort) {lemonToast.success('Static cohort created successfully', {@@ -5676,5 +5925,6 @@ export const featureFlagLogic = kea<featureFlagLogicType>([beforeUnmount(({ props, cache }) => {// A notice that survives navigation has a button that reloads an unmounted logic.dismissAgentNotices(props.id, cache)+ dismissBroadcastProgress(cache)}),])diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 21bbd6eae9b0..c9eb6d2fdce5 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -72,7 +72,12 @@ from posthog.models.activity_logging.activity_log import (load_activity,log_activity,)-from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params+from posthog.models.activity_logging.activity_page import (+ ActivityLogPaginatedResponseSerializer,+ ActivityQueryParamsSerializer,+ activity_page_response,+ parse_activity_page_params,+)from posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.filters.utils import earliest_timestamp_funcfrom posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist@@ -2147,6 +2152,19 @@ def get_cohorts_using_cohort(cohort: Cohort) -> QuerySet[Cohort]:location=OpenApiParameter.QUERY,description="Set true to exclude behavioral (event-based) cohorts, which can't be used in feature flags or batch workflow audiences.",),+ OpenApiParameter(+ name="type",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ enum=["static", "dynamic"],+ description="Optional. `static` returns only static cohorts, `dynamic` only dynamic ones.",+ ),+ OpenApiParameter(+ name="created_by_id",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ description="Optional. Return only cohorts created by the user with this id.",+ ),OpenApiParameter(name="basic",type=bool,@@ -2487,6 +2505,10 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVireturn activity_page_response(activity_page, page_params.limit, page_params.page, request)+ @extend_schema(+ parameters=[ActivityQueryParamsSerializer],+ responses={200: ActivityLogPaginatedResponseSerializer, 404: None},+ )@action(methods=["GET"], detail=True, required_scopes=["activity_log:read"])def activity(self, request: request.Request, **kwargs):page_params = parse_activity_page_params(request)diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.tsindex 24c1709edd0a..1d0be7a7e6ce 100644--- a/products/cohorts/frontend/generated/api.schemas.ts+++ b/products/cohorts/frontend/generated/api.schemas.ts@@ -520,6 +520,73 @@ export interface PatchedCohortApi {_create_static_person_ids?: string[]}+export interface ChangeApi {+ readonly type: string+ readonly action: string+ readonly field: string+ readonly before: unknown+ readonly after: unknown+}++export interface MergeApi {+ readonly type: string+ readonly source: unknown+ readonly target: unknown+}++export interface TriggerApi {+ readonly job_type: string+ readonly job_id: string+ readonly payload: unknown+}++export interface DetailApi {+ readonly id: string+ changes?: ChangeApi[]+ merge?: MergeApi+ trigger?: TriggerApi+ readonly name: string+ readonly short_id: string+ readonly type: string+}++/**+ * @nullable+ */+export type ActivityLogEntryApiUser = { [key: string]: unknown } | null++export interface ActivityLogEntryApi {+ readonly id: string+ /** @nullable */+ readonly user: ActivityLogEntryApiUser+ readonly activity: string+ readonly scope: string+ readonly item_id: string+ detail?: DetailApi+ readonly created_at: string+ /** Whether the activity was performed by the system rather than a user. */+ readonly is_system: boolean+ /** Whether the acting user was being impersonated by PostHog staff. */+ readonly was_impersonated: boolean+ /**+ * API client that triggered the activity. Self-reported through the x-posthog-client request header (e.g. 'mcp'), or 'scout:<skill_name>' when a scout run made the change, which the server derives from the run's own token. Null for requests that did neither.+ * @nullable+ */+ readonly client: string | null+}++/**+ * Response shape for paginated activity log endpoints.+ */+export interface ActivityLogPaginatedResponseApi {+ results: ActivityLogEntryApi[]+ /** @nullable */+ next: string | null+ /** @nullable */+ previous: string | null+ total_count: number+}+export interface PatchedAddPersonsToStaticCohortRequestApi {/** List of person UUIDs to add to the cohort */person_ids?: string[]@@ -682,6 +749,10 @@ export type CohortsListParams = {* Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id/name/count.*/basic?: boolean+ /**+ * Optional. Return only cohorts created by the user with this id.+ */+ created_by_id?: number/*** Set true to exclude behavioral (event-based) cohorts, which can't be used in feature flags or batch workflow audiences.*/@@ -698,6 +769,30 @@ export type CohortsListParams = {* Optional. Match against cohort `name`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, transpositions, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`. Results are ordered by relevance. When omitted, cohorts are ordered newest-first. Capped at 200 characters; longer queries return a 400 error.*/search?: string+ /**+ * Optional. `static` returns only static cohorts, `dynamic` only dynamic ones.+ */+ type?: CohortsListType+}++export type CohortsListType = (typeof CohortsListType)[keyof typeof CohortsListType]++export const CohortsListType = {+ Dynamic: 'dynamic',+ Static: 'static',+} as const++export type CohortsActivityRetrieveParams = {+ /**+ * Number of items per page+ * @minimum 1+ */+ limit?: number+ /**+ * Page number+ * @minimum 1+ */+ page?: number}export type CohortsPersonsRetrieveParams = {diff --git a/products/cohorts/frontend/generated/api.ts b/products/cohorts/frontend/generated/api.tsindex 8d6179d054f2..00246ec08315 100644--- a/products/cohorts/frontend/generated/api.ts+++ b/products/cohorts/frontend/generated/api.ts@@ -9,10 +9,12 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ ActivityLogPaginatedResponseApi,CohortApi,CohortPersonsResponseApi,CohortUsedInResponseApi,CohortUsedInWorkflowsBlockApi,+ CohortsActivityRetrieveParams,CohortsListParams,CohortsPersonsRetrieveParams,CohortsStaffListParams,@@ -235,12 +237,33 @@ export const cohortsDestroy = async (projectId: string, id: number, options?: Re})}-export const getCohortsActivityRetrieveUrl = (projectId: string, id: number) => {- return `/api/projects/${projectId}/cohorts/${id}/activity/`+export const getCohortsActivityRetrieveUrl = (+ projectId: string,+ id: number,+ params?: CohortsActivityRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/cohorts/${id}/activity/?${stringifiedParams}`+ : `/api/projects/${projectId}/cohorts/${id}/activity/`}-export const cohortsActivityRetrieve = async (projectId: string, id: number, options?: RequestInit): Promise<void> => {- return apiMutator<void>(getCohortsActivityRetrieveUrl(projectId, id), {+export const cohortsActivityRetrieve = async (+ projectId: string,+ id: number,+ params?: CohortsActivityRetrieveParams,+ options?: RequestInit+): Promise<ActivityLogPaginatedResponseApi> => {+ return apiMutator<ActivityLogPaginatedResponseApi>(getCohortsActivityRetrieveUrl(projectId, id, params), {...options,method: 'GET',})diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex eb723c64a5c7..a4e9dfe8b072 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -5524,6 +5524,7 @@ class FeatureFlagViewSet(data={"is_static": True,"key": feature_flag_key,+ # flagCohortNamePrefix in featureFlagLogic.ts matches this name to reuse the cohort. Rename both together."name": f"Users with feature flag {feature_flag_key} enabled at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}","is_calculating": True,},diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 41fd3dbdabaa..78006c9ce1a1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -122971,6 +122971,10 @@ export namespace Schemas {* Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id/name/count.*/basic?: boolean;+ /**+ * Optional. Return only cohorts created by the user with this id.+ */+ created_by_id?: number;/*** Set true to exclude behavioral (event-based) cohorts, which can't be used in feature flags or batch workflow audiences.*/@@ -122987,6 +122991,31 @@ export namespace Schemas {* Optional. Match against cohort `name`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, transpositions, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`. Results are ordered by relevance. When omitted, cohorts are ordered newest-first. Capped at 200 characters; longer queries return a 400 error.*/search?: string;+ /**+ * Optional. `static` returns only static cohorts, `dynamic` only dynamic ones.+ */+ type?: CohortsListType;+ };++ export type CohortsListType = typeof CohortsListType[keyof typeof CohortsListType];+++ export const CohortsListType = {+ Dynamic: 'dynamic',+ Static: 'static',+ } as const;++ export type CohortsActivityRetrieveParams = {+ /**+ * Number of items per page+ * @minimum 1+ */+ limit?: number;+ /**+ * Page number+ * @minimum 1+ */+ page?: number;};export type CohortsPersonsRetrieveParams = {diff --git a/services/mcp/src/generated/cohorts/api.ts b/services/mcp/src/generated/cohorts/api.tsindex 6889875ab9d8..bdc5d118789e 100644--- a/services/mcp/src/generated/cohorts/api.ts+++ b/services/mcp/src/generated/cohorts/api.ts@@ -23,6 +23,7 @@ export const CohortsListQueryParams = () => zod.object({.describe('Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id\/name\/count.'),+ created_by_id: zod.number().optional().describe('Optional. Return only cohorts created by the user with this id.'),hide_behavioral_cohorts: zod.boolean().optional()@@ -37,6 +38,10 @@ export const CohortsListQueryParams = () => zod.object({.describe("Optional. Match against cohort `name`. Returns exact (case-insensitive substring) matches only; if no exact match exists, returns similar (fuzzy trigram — typos, transpositions, prefix-as-you-type) matches instead. Each result's `search_match_type` is `exact` or `similar`. Results are ordered by relevance. When omitted, cohorts are ordered newest-first. Capped at 200 characters; longer queries return a 400 error."),+ type: zod+ .enum(['dynamic', 'static'])+ .optional()+ .describe('Optional. `static` returns only static cohorts, `dynamic` only dynamic ones.'),})export const CohortsCreateParams = () => zod.object({diff --git a/services/mcp/src/tools/generated/cohorts.ts b/services/mcp/src/tools/generated/cohorts.tsindex f7b2806c372e..7cda351ec002 100644--- a/services/mcp/src/tools/generated/cohorts.ts+++ b/services/mcp/src/tools/generated/cohorts.ts@@ -106,10 +106,12 @@ const cohortsList = (): ToolBase<ReturnType<typeof CohortsListSchema>, WithPostHpath: `/api/projects/${encodeURIComponent(String(projectId))}/cohorts/`,query: {basic: params.basic,+ created_by_id: params.created_by_id,hide_behavioral_cohorts: params.hide_behavioral_cohorts,limit: params.limit,offset: params.offset,search: params.search,+ type: params.type,},})const filtered = {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.jsonindex 1ea14386a307..fac4a582419b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/cohorts-list.json@@ -5,6 +5,10 @@"description": "Return a basic payload that omits the `query`, `groups`, `last_error_message`, and `experiment_set` fields (`filters` is kept). Useful for pickers that only need id/name/count.","type": "boolean"},+ "created_by_id": {+ "description": "Optional. Return only cohorts created by the user with this id.",+ "type": "number"+ },"hide_behavioral_cohorts": {"description": "Set true to exclude behavioral (event-based) cohorts — not usable in batch workflow audiences.","type": "boolean"@@ -20,6 +24,11 @@"search": {"description": "Find cohorts by name. Fuzzy trigram match (tolerates typos and partial words), exact matches ordered first.","type": "string"+ },+ "type": {+ "description": "Optional. `static` returns only static cohorts, `dynamic` only dynamic ones.",+ "enum": ["dynamic", "static"],+ "type": "string"}},"type": "object"