Skip to content

: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.

feat(workflows): let other products open a broadcast or workflow for an audience (#112985)

Daniel Marchuk0fe88d339832
diff --git a/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.test.ts b/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.test.ts
new file mode 100644
index 000000000000..d9dbdb790bfc
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.test.ts
@@ -0,0 +1,71 @@
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import {
+ AUDIENCE_PREFILL_PARAM,
+ parseBroadcastAudiencePrefill,
+ urlForNewBroadcastWithAudience,
+} from './broadcastAudiencePrefill'
+
+const COHORT_AUDIENCE: AnyPropertyFilter[] = [
+ { key: 'id', type: PropertyFilterType.Cohort, value: 7, operator: PropertyOperator.In },
+]
+
+describe('broadcastAudiencePrefill', () => {
+ it('round-trips an audience through the URL', () => {
+ const url = urlForNewBroadcastWithAudience({ properties: COHORT_AUDIENCE, source: 'cohort' })
+ const raw = new URLSearchParams(url.split('?')[1]).get(AUDIENCE_PREFILL_PARAM)
+
+ expect(parseBroadcastAudiencePrefill(raw)).toEqual(COHORT_AUDIENCE)
+ })
+
+ it.each([
+ ['nothing', undefined],
+ ['a non-JSON string', 'not-json'],
+ ['an empty audience', '[]'],
+ ['an object instead of a list', '{"key":"email"}'],
+ ['an event filter, which a broadcast audience cannot use', '[{"key":"$browser","type":"event","value":"x"}]'],
+ ['a person filter missing its value', '[{"key":"email","type":"person","operator":"exact"}]'],
+ ['a cohort filter without a cohort id', '[{"key":"id","type":"cohort","operator":"in"}]'],
+ ['a person filter missing its operator', '[{"key":"email","type":"person","value":"[email protected]"}]'],
+ [
+ 'an operator the backend does not know',
+ '[{"key":"email","type":"person","operator":"nonsense","value":"x"}]',
+ ],
+ ['a cohort filter with a negative id', '[{"key":"id","type":"cohort","value":-3}]'],
+ [
+ 'one bad filter next to a good one',
+ '[{"key":"id","type":"cohort","value":7},{"key":"email","type":"person","operator":"exact","value":[]}]',
+ ],
+ ])('returns null for %s', (_label, raw) => {
+ expect(parseBroadcastAudiencePrefill(raw)).toBeNull()
+ })
+
+ it('keeps only the fields the audience uses, so a hidden field cannot make the backend drop the filter', () => {
+ const raw = JSON.stringify([
+ { key: 'email', type: 'person', operator: 'exact', value: '[email protected]', group_type_index: -1 },
+ { key: 'id', type: 'cohort', value: 7, operator: 'in', cohort_name: 'Beta', group_type_index: -1 },
+ ])
+
+ expect(parseBroadcastAudiencePrefill(raw)).toEqual([
+ {
+ key: 'email',
+ type: PropertyFilterType.Person,
+ operator: PropertyOperator.Exact,
+ value: '[email protected]',
+ },
+ {
+ key: 'id',
+ type: PropertyFilterType.Cohort,
+ value: 7,
+ operator: PropertyOperator.In,
+ cohort_name: 'Beta',
+ },
+ ])
+ })
+
+ it('accepts a person filter that needs no value', () => {
+ const audience = [{ key: 'email', type: PropertyFilterType.Person, operator: PropertyOperator.IsSet }]
+
+ expect(parseBroadcastAudiencePrefill(JSON.stringify(audience))).toEqual(audience)
+ })
+})
diff --git a/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts b/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts
new file mode 100644
index 000000000000..22656a0ae763
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts
@@ -0,0 +1,96 @@
+import { combineUrl } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+// pinned: URL search params, other products link to /broadcasts/new with these
+export const AUDIENCE_PREFILL_PARAM = 'audience'
+export const NAME_PREFILL_PARAM = 'name'
+export const SOURCE_PREFILL_PARAM = 'source'
+
+export interface BroadcastPrefill {
+ properties: AnyPropertyFilter[]
+ name?: string
+ /** The product surface the person came from, reported on the launch event. */
+ source?: string
+}
+
+export function urlForNewBroadcastWithAudience({ properties, name, source }: BroadcastPrefill): string {
+ return combineUrl(urls.broadcastNew(), {
+ [AUDIENCE_PREFILL_PARAM]: JSON.stringify(properties),
+ ...(name ? { [NAME_PREFILL_PARAM]: name } : {}),
+ ...(source ? { [SOURCE_PREFILL_PARAM]: source } : {}),
+ }).url
+}
+
+/** The audience a link asked for, or null when it is missing or any filter in it can't be applied. */
+export function parseBroadcastAudiencePrefill(raw: unknown): AnyPropertyFilter[] | null {
+ let value = raw
+ if (typeof raw === 'string') {
+ try {
+ value = JSON.parse(raw)
+ } catch {
+ return null
+ }
+ }
+ if (!Array.isArray(value) || value.length === 0) {
+ return null
+ }
+ const filters = value.map(toAudienceFilter)
+ return filters.every((filter): filter is AnyPropertyFilter => filter !== null) ? filters : null
+}
+
+const PERSON_OPERATORS: string[] = Object.values(PropertyOperator)
+const COHORT_OPERATORS: string[] = [PropertyOperator.In, PropertyOperator.NotIn]
+
+function isFilterValue(value: unknown): boolean {
+ return (
+ typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)) || typeof value === 'boolean'
+ )
+}
+
+// Rebuilt from known fields only: the backend drops a filter with a field it rejects, which would widen the
+// audience to everyone while the wizard still shows the filter.
+function toAudienceFilter(filter: unknown): AnyPropertyFilter | null {
+ if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
+ return null
+ }
+ const { key, type, operator, value, cohort_name } = filter as Record<string, unknown>
+ if (typeof key !== 'string' || key === '') {
+ return null
+ }
+ if (type === PropertyFilterType.Cohort) {
+ if (key !== 'id' || typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
+ return null
+ }
+ if (operator !== undefined && (typeof operator !== 'string' || !COHORT_OPERATORS.includes(operator))) {
+ return null
+ }
+ return {
+ key: 'id',
+ type: PropertyFilterType.Cohort,
+ value,
+ operator: (operator as PropertyOperator | undefined) ?? PropertyOperator.In,
+ ...(typeof cohort_name === 'string' ? { cohort_name } : {}),
+ }
+ }
+ if (type !== PropertyFilterType.Person || typeof operator !== 'string' || !PERSON_OPERATORS.includes(operator)) {
+ return null
+ }
+ if (operator === PropertyOperator.IsSet || operator === PropertyOperator.IsNotSet) {
+ return { key, type: PropertyFilterType.Person, operator: operator as PropertyOperator }
+ }
+ const hasValue = Array.isArray(value)
+ ? value.length > 0 && value.every(isFilterValue)
+ : isFilterValue(value) && value !== ''
+ if (!hasValue) {
+ return null
+ }
+ return {
+ key,
+ type: PropertyFilterType.Person,
+ operator: operator as PropertyOperator,
+ value: value as string | number | boolean | (string | number | boolean)[],
+ } as AnyPropertyFilter
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastUsage.ts b/products/workflows/frontend/Broadcasts/broadcastUsage.ts
index 32b5a45cf775..d1b836804ee9 100644
--- a/products/workflows/frontend/Broadcasts/broadcastUsage.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastUsage.ts
@@ -6,6 +6,8 @@ export const COMPOSER_DRAFT_PARAM = 'from'
export const COMPOSER_DRAFT_VALUE = 'ai_composer'
const COMPOSER_DRAFTS_STORAGE_KEY = 'broadcasts-ai-composer-drafts'
+// pinned: session storage key
+const ENTRY_SOURCES_STORAGE_KEY = 'broadcasts-entry-sources'
export type BroadcastPath = 'composer' | 'manual'
@@ -101,3 +103,28 @@ export function advanceAgentDraft(
export function editedFields(agentDraft: BroadcastFieldSnapshot, current: BroadcastFieldSnapshot): BroadcastField[] {
return BROADCAST_FIELDS.filter((field) => !objectsEqual(agentDraft[field], current[field]))
}
+
+function readEntrySources(): Record<string, string> {
+ try {
+ const stored = JSON.parse(sessionStorage.getItem(ENTRY_SOURCES_STORAGE_KEY) || '{}')
+ return stored && typeof stored === 'object' && !Array.isArray(stored) ? stored : {}
+ } catch {
+ return {}
+ }
+}
+
+/** Kept for the tab, because saving the draft remounts the wizard under the draft's own URL. */
+export function saveEntrySource(broadcastId: string, source: string): void {
+ try {
+ sessionStorage.setItem(
+ ENTRY_SOURCES_STORAGE_KEY,
+ JSON.stringify({ ...readEntrySources(), [broadcastId]: source })
+ )
+ } catch {
+ // Storage can be blocked. The launch then reports no entry source.
+ }
+}
+
+export function loadEntrySource(broadcastId: string | null | undefined): string | null {
+ return broadcastId ? (readEntrySources()[broadcastId] ?? null) : null
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index 48fd619f6de4..c2cc0c364cf7 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -9,6 +9,7 @@ import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types
import type { HogFlowApi } from 'products/workflows/frontend/generated/api.schemas'
+import { urlForNewBroadcastWithAudience } from './broadcastAudiencePrefill'
import { DEFAULT_BROADCAST_EMAIL, DELETED_SENDER_ERROR, broadcastWizardLogic } from './broadcastWizardLogic'
const LOCAL_AUDIENCE: AnyPropertyFilter[] = [
@@ -128,6 +129,47 @@ describe('broadcastWizardLogic', () => {
logic.unmount()
})
+ it('prefills the audience, name and source from a link without creating a draft', async () => {
+ const properties: AnyPropertyFilter[] = [
+ { key: 'id', type: PropertyFilterType.Cohort, value: 7, operator: PropertyOperator.In },
+ ]
+ logic.unmount()
+ router.actions.push(urlForNewBroadcastWithAudience({ properties, name: 'Fix shipped', source: 'cohort' }))
+ logic = broadcastWizardLogic({ id: 'new' })
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions(['prefillFromLink', 'loadBlastRadius'])
+ .toNotHaveDispatchedActions(['ensureDraft'])
+ expect(logic.values.audienceProperties).toEqual(properties)
+ expect(logic.values.name).toEqual('Fix shipped')
+ expect(logic.values.entrySource).toEqual('cohort')
+ expect(router.values.searchParams).toEqual({})
+ })
+
+ it('blocks the recipients step until the person chooses, when a link has an audience it cannot use', async () => {
+ logic.unmount()
+ router.actions.push(
+ `/broadcasts/new?audience=${encodeURIComponent('[{"key":"email","type":"person","operator":"exact"}]')}&name=Fix%20shipped`
+ )
+ logic = broadcastWizardLogic({ id: 'new' })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['rejectLinkAudience']).toNotHaveDispatchedActions(['ensureDraft'])
+ expect(logic.values.name).toEqual('Fix shipped')
+ expect(logic.values.stepValidationErrors.recipients).toEqual(['Choose who gets this email'])
+
+ logic.actions.setAudienceProperties([
+ { key: 'email', type: PropertyFilterType.Person, operator: PropertyOperator.IsSet },
+ ])
+ expect(logic.values.stepValidationErrors.recipients).toEqual([])
+ logic.actions.setAudienceProperties([])
+ expect(logic.values.stepValidationErrors.recipients).toEqual(['Choose who gets this email'])
+
+ logic.actions.sendToEveryoneAfterRejectedLink()
+ expect(logic.values.stepValidationErrors.recipients).toEqual([])
+ })
+
test.each([
{ edited: 'only the email', latestName: 'Spring sale', expectedName: 'Spring sale, final' },
{ edited: 'the name too', latestName: 'Spring promo', expectedName: 'Spring promo' },
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index fe60f956ed93..518865c80046 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -49,6 +49,13 @@ import {
} from '../Workflows/hogflows/steps/components/rrule-helpers'
import type { UtmTagValues } from '../Workflows/hogflows/steps/components/UtmTagFields'
import { ResourceSaveQueue } from '../Workflows/resourceSaveQueue'
+import {
+ AUDIENCE_PREFILL_PARAM,
+ type BroadcastPrefill,
+ NAME_PREFILL_PARAM,
+ parseBroadcastAudiencePrefill,
+ SOURCE_PREFILL_PARAM,
+} from './broadcastAudiencePrefill'
import { confirmArchiveBroadcast, confirmDeleteBroadcast, restoreBroadcast } from './broadcastLifecycle'
import {
BroadcastStatus,
@@ -58,13 +65,15 @@ import {
getBroadcastStatus,
} from './broadcastsLogic'
import {
- COMPOSER_DRAFT_PARAM,
- COMPOSER_DRAFT_VALUE,
advanceAgentDraft,
broadcastPath,
+ COMPOSER_DRAFT_PARAM,
+ COMPOSER_DRAFT_VALUE,
editedFields,
loadComposerDraft,
+ loadEntrySource,
saveComposerDraft,
+ saveEntrySource,
snapshotBroadcast,
} from './broadcastUsage'
@@ -219,6 +228,7 @@ export interface broadcastWizardLogicValues {
email: BroadcastEmailValue
emailRateLimit: HogFlowEmailSendingRateLimitApi | null
emailSettings: BroadcastEmailSettings
+ entrySource: string | null
expandedRunIds: string[]
expandedRunOverride: string[] | null
firstInvalidStep: BroadcastWizardStep | null
@@ -227,6 +237,7 @@ export interface broadcastWizardLogicValues {
hasLoadedBatchJobs: boolean
isReadOnly: boolean
launching: boolean
+ linkAudienceRejected: boolean
movingToDraft: boolean
name: string
rateLimitedSendDuration: string
@@ -349,9 +360,15 @@ export interface broadcastWizardLogicActions {
nextStep: () => {
value: true
}
+ prefillFromLink: (prefill: BroadcastPrefill) => {
+ prefill: BroadcastPrefill
+ }
prevStep: () => {
value: true
}
+ rejectLinkAudience: () => {
+ value: true
+ }
replayDeferredEdit: () => {
value: true
}
@@ -367,6 +384,9 @@ export interface broadcastWizardLogicActions {
saveName: () => {
value: true
}
+ sendToEveryoneAfterRejectedLink: () => {
+ value: true
+ }
setAudienceProperties: (properties: AnyPropertyFilter[]) => {
properties: AnyPropertyFilter[]
}
@@ -472,7 +492,9 @@ export interface broadcastWizardLogicMeta {
sendAt: string | null,
recurringStartsAt: string | null,
integrations: IntegrationType[] | null,
- integrationsLoading: boolean
+ integrationsLoading: boolean,
+ linkAudienceRejected: boolean,
+ audienceProperties: AnyPropertyFilter[]
) => Record<BroadcastWizardStep, string[]>
currentStepHasErrors: (
stepValidationErrors: Record<BroadcastWizardStep, string[]>,
@@ -526,8 +548,11 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
continueStep: true,
reportReviewVisit: true,
setName: (name: string) => ({ name }),
+ prefillFromLink: (prefill: BroadcastPrefill) => ({ prefill }),
saveName: true,
setAudienceProperties: (properties: AnyPropertyFilter[]) => ({ properties }),
+ rejectLinkAudience: true,
+ sendToEveryoneAfterRejectedLink: true,
setGoalEnabled: (enabled: boolean) => ({ enabled }),
setConversion: (conversion: HogFlowConversionApi) => ({ conversion }),
setEmailRateLimit: (emailRateLimit: HogFlowEmailSendingRateLimitApi | null) => ({ emailRateLimit }),
@@ -644,15 +669,32 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
'New broadcast',
{
setName: (_, { name }) => name,
+ prefillFromLink: (state, { prefill }) => prefill.name || state,
hydrateFromBroadcast: (state, { broadcast }) => broadcast.name || state,
applyExternalEdit: (state, { broadcast, base }) =>
changedElsewhere(broadcast, base, (b) => b.name) ? broadcast.name || state : state,
},
],
+ // Kept for the launch event, so a launch counts toward the product it started from.
+ // Set when a link's audience couldn't be used. While the audience is empty, sending to everyone needs an explicit choice.
+ linkAudienceRejected: [
+ false,
+ {
+ rejectLinkAudience: () => true,
+ sendToEveryoneAfterRejectedLink: () => false,
+ },
+ ],
+ entrySource: [
+ null as string | null,
+ {
+ prefillFromLink: (_, { prefill }) => prefill.source ?? null,
+ },
+ ],
audienceProperties: [
[] as AnyPropertyFilter[],
{
setAudienceProperties: (_, { properties }) => properties,
+ prefillFromLink: (_, { prefill }) => prefill.properties,
hydrateFromBroadcast: (state, { broadcast }) => {
const trigger = findAction(broadcast, 'trigger')
return (trigger?.config?.filters?.properties as AnyPropertyFilter[]) ?? state
@@ -938,6 +980,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
s.recurringStartsAt,
s.integrations,
s.integrationsLoading,
+ s.linkAudienceRejected,
+ s.audienceProperties,
],
(
goalEnabled: boolean,
@@ -947,7 +991,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
sendAt: string | null,
recurringStartsAt: string | null,
integrations: IntegrationType[] | null,
- integrationsLoading: boolean
+ integrationsLoading: boolean,
+ linkAudienceRejected: boolean,
+ audienceProperties: AnyPropertyFilter[]
): Record<BroadcastWizardStep, string[]> => {
const errors: Record<BroadcastWizardStep, string[]> = {
recipients: [],
@@ -957,6 +1003,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
review: [],
}
+ if (linkAudienceRejected && audienceProperties.length === 0) {
+ errors.recipients.push('Choose who gets this email')
+ }
+
if (goalEnabled) {
const hasEventGoal = (conversion.events?.[0]?.filters?.events?.length ?? 0) > 0
const hasPropertyGoal = (conversion.filters?.length ?? 0) > 0
@@ -1182,6 +1232,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
values.broadcastId &&
values.broadcast?.status === 'draft'
) {
+ if (values.entrySource) {
+ saveEntrySource(values.broadcastId, values.entrySource)
+ }
router.actions.replace(urls.broadcast(values.broadcastId), { step: values.currentStep })
}
},
@@ -1526,6 +1579,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
schedule_mode: values.scheduleMode,
audience_filter_count: values.audienceProperties.length,
has_goal: values.goalEnabled,
+ entry_source: values.entrySource ?? loadEntrySource(broadcastId),
seconds_since_created: activated
? Math.round((Date.now() - new Date(activated.created_at).getTime()) / 1000)
: null,
@@ -1684,9 +1738,38 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
afterMount(({ actions, props }) => {
if (props.id !== 'new') {
actions.loadBroadcast()
- } else {
- actions.loadBlastRadius()
+ return
+ }
+ const {
+ [AUDIENCE_PREFILL_PARAM]: audience,
+ [NAME_PREFILL_PARAM]: name,
+ [SOURCE_PREFILL_PARAM]: source,
+ ...searchParams
+ } = router.values.searchParams
+ const properties = parseBroadcastAudiencePrefill(audience)
+ if (audience !== undefined || name !== undefined || source !== undefined) {
+ const prefill: BroadcastPrefill = {
+ properties: properties ?? [],
+ name: typeof name === 'string' ? name : undefined,
+ source: typeof source === 'string' ? source : undefined,
+ }
+ // Not setAudienceProperties: opening /broadcasts/new must not create a draft.
+ actions.prefillFromLink(prefill)
+ if (properties) {
+ // pinned: analytics event name
+ posthog.capture('broadcast prefilled from link', {
+ entry_source: prefill.source ?? null,
+ audience_filter_count: properties.length,
+ })
+ }
+ }
+ if (audience !== undefined && !properties) {
+ actions.rejectLinkAudience()
+ }
+ if (audience !== undefined || name !== undefined || source !== undefined) {
+ router.actions.replace(router.values.location.pathname, searchParams, router.values.hashParams)
}
+ actions.loadBlastRadius()
}),
])
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
index abfebb8060fb..b6e7b8a15c5c 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconWarning } from '@posthog/icons'
-import { LemonButton, LemonModal, LemonSelect, Link, Spinner } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonModal, LemonSelect, Link, Spinner } from '@posthog/lemon-ui'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
@@ -141,8 +141,8 @@ function AudienceListModal({ isOpen, onClose }: { isOpen: boolean; onClose: () =
}
export function BroadcastRecipientsStep(): JSX.Element {
- const { audienceProperties } = useValues(broadcastWizardLogic)
- const { setAudienceProperties } = useActions(broadcastWizardLogic)
+ const { audienceProperties, linkAudienceRejected } = useValues(broadcastWizardLogic)
+ const { setAudienceProperties, sendToEveryoneAfterRejectedLink } = useActions(broadcastWizardLogic)
const [audienceListOpen, setAudienceListOpen] = useState(false)
return (
@@ -153,6 +153,19 @@ export function BroadcastRecipientsStep(): JSX.Element {
Filter by person properties or cohorts. Without filters, the broadcast goes to everyone.
</p>
</div>
+ {linkAudienceRejected && audienceProperties.length === 0 && (
+ <LemonBanner
+ type="warning"
+ action={{
+ children: 'Send to everyone',
+ onClick: sendToEveryoneAfterRejectedLink,
+ 'data-attr': 'broadcast-rejected-link-send-to-everyone',
+ }}
+ >
+ The link you followed had recipients we couldn't read, so none were added. Add a condition below, or
+ send to everyone.
+ </LemonBanner>
+ )}
<div className="flex items-start justify-between gap-2">
<div>
<span className="font-semibold">This broadcast will reach</span> <AudienceSizePreview />
diff --git a/products/workflows/frontend/MessageAudience/MessageAudienceButton.tsx b/products/workflows/frontend/MessageAudience/MessageAudienceButton.tsx
new file mode 100644
index 000000000000..610ec4ca1744
--- /dev/null
+++ b/products/workflows/frontend/MessageAudience/MessageAudienceButton.tsx
@@ -0,0 +1,66 @@
+import { router } from 'kea-router'
+
+import { IconSend } from '@posthog/icons'
+import { LemonButton, LemonButtonProps, LemonMenu } from '@posthog/lemon-ui'
+
+import {
+ MessageAudience,
+ MessageAudienceDestination,
+ captureMessageAudienceClicked,
+ messageAudienceUrl,
+} from './messageAudience'
+
+const DESTINATION_LABELS: Record<MessageAudienceDestination, string> = {
+ broadcast: 'Send a broadcast',
+ workflow: 'Start a workflow',
+}
+
+export interface MessageAudienceButtonProps extends Pick<
+ LemonButtonProps,
+ 'type' | 'size' | 'disabledReason' | 'fullWidth'
+> {
+ audience: MessageAudience
+ destinations?: MessageAudienceDestination[]
+ label?: string
+}
+
+export function MessageAudienceButton({
+ audience,
+ destinations = ['broadcast', 'workflow'],
+ label = 'Message these people',
+ type = 'secondary',
+ size = 'small',
+ disabledReason,
+ fullWidth,
+}: MessageAudienceButtonProps): JSX.Element {
+ const open = (destination: MessageAudienceDestination): void => {
+ captureMessageAudienceClicked(audience.source, destination)
+ router.actions.push(messageAudienceUrl(audience, destination))
+ }
+ const buttonProps = { type, size, disabledReason, fullWidth, icon: <IconSend /> }
+
+ if (destinations.length === 1) {
+ return (
+ <LemonButton
+ {...buttonProps}
+ onClick={() => open(destinations[0])}
+ data-attr={`message-audience-${audience.source}-${destinations[0]}`}
+ >
+ {label}
+ </LemonButton>
+ )
+ }
+ return (
+ <LemonMenu
+ items={destinations.map((destination) => ({
+ label: DESTINATION_LABELS[destination],
+ onClick: () => open(destination),
+ 'data-attr': `message-audience-${audience.source}-${destination}`,
+ }))}
+ >
+ <LemonButton {...buttonProps} data-attr={`message-audience-${audience.source}`}>
+ {label}
+ </LemonButton>
+ </LemonMenu>
+ )
+}
diff --git a/products/workflows/frontend/MessageAudience/messageAudience.ts b/products/workflows/frontend/MessageAudience/messageAudience.ts
new file mode 100644
index 000000000000..afea67f00b14
--- /dev/null
+++ b/products/workflows/frontend/MessageAudience/messageAudience.ts
@@ -0,0 +1,46 @@
+import posthog from 'posthog-js'
+
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { urlForNewBroadcastWithAudience } from '../Broadcasts/broadcastAudiencePrefill'
+import { type WorkflowTriggerConfig, urlForNewWorkflowWithTrigger } from '../Workflows/workflowTriggerPrefill'
+
+export type MessageAudienceDestination = 'broadcast' | 'workflow'
+
+export interface MessageAudience {
+ properties: AnyPropertyFilter[]
+ source: string
+ broadcastName?: string
+ /** The workflow to start. Without one, the workflow sends to the same people with a batch trigger. */
+ workflowTrigger?: WorkflowTriggerConfig
+}
+
+export function cohortAudienceProperties(cohort: { id: number; name?: string | null }): AnyPropertyFilter[] {
+ return [
+ {
+ key: 'id',
+ type: PropertyFilterType.Cohort,
+ value: cohort.id,
+ operator: PropertyOperator.In,
+ cohort_name: cohort.name ?? undefined,
+ },
+ ]
+}
+
+export function messageAudienceUrl(audience: MessageAudience, destination: MessageAudienceDestination): string {
+ if (destination === 'broadcast') {
+ return urlForNewBroadcastWithAudience({
+ properties: audience.properties,
+ name: audience.broadcastName,
+ source: audience.source,
+ })
+ }
+ return urlForNewWorkflowWithTrigger(
+ audience.workflowTrigger ?? { type: 'batch', filters: { properties: audience.properties } }
+ )
+}
+
+export function captureMessageAudienceClicked(source: string, destination: MessageAudienceDestination): void {
+ // pinned: analytics event name
+ posthog.capture('message audience clicked', { source, destination })
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index de9b480ad762..fae9f4f79d91 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -67,7 +67,11 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
const { searchParams } = useValues(router)
const templateId = searchParams.templateId as string | undefined
const editTemplateId = searchParams.editTemplateId as string | undefined
- const triggerPrefill = searchParams[TRIGGER_PREFILL_PARAM] as string | undefined
+ const rawTriggerPrefill = searchParams[TRIGGER_PREFILL_PARAM]
+ const triggerPrefill =
+ rawTriggerPrefill && typeof rawTriggerPrefill !== 'string'
+ ? JSON.stringify(rawTriggerPrefill)
+ : rawTriggerPrefill
const workflowProps: WorkflowLogicProps = {
id: workflowSceneProps.id,
templateId,
diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
index 28151b5c3d60..e1d7254eb7b9 100644
--- a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
@@ -30,6 +30,7 @@ import { SaveAsTemplateModal } from './templates/SaveAsTemplateModal'
import { workflowTemplateLogic } from './templates/workflowTemplateLogic'
import { workflowLogic } from './workflowLogic'
import { WorkflowSceneLogicProps } from './workflowSceneLogic'
+import { parseWorkflowTriggerPrefill, TRIGGER_PREFILL_PARAM } from './workflowTriggerPrefill'
export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.Element => {
const {
@@ -63,6 +64,7 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El
const isSavedWorkflow = props.id && props.id !== 'new'
const isCreatedFromTemplate = props.id === 'new' && !!templateId
+ const isCreatedFromLink = props.id === 'new' && !!parseWorkflowTriggerPrefill(searchParams[TRIGGER_PREFILL_PARAM])
const isManualWorkflow = ['manual', 'batch'].includes(workflow?.trigger?.type || '')
const { featureFlags } = useValues(featureFlagLogic)
const sceneMenuBarEnabled = !!featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]
@@ -335,7 +337,7 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El
disabledReason={
workflowHasErrors
? 'Some fields still need work'
- : isCreatedFromTemplate
+ : isCreatedFromTemplate || isCreatedFromLink
? undefined
: hasUnsavedChanges
? undefined
diff --git a/products/workflows/frontend/Workflows/workflowTriggerPrefill.test.ts b/products/workflows/frontend/Workflows/workflowTriggerPrefill.test.ts
index b385ca41acd2..4102e287b033 100644
--- a/products/workflows/frontend/Workflows/workflowTriggerPrefill.test.ts
+++ b/products/workflows/frontend/Workflows/workflowTriggerPrefill.test.ts
@@ -16,6 +16,7 @@ describe('workflowTriggerPrefill', () => {
const raw = new URLSearchParams(url.split('?')[1]).get(TRIGGER_PREFILL_PARAM)
expect(parseWorkflowTriggerPrefill(raw ?? undefined)).toEqual(config)
+ expect(parseWorkflowTriggerPrefill(JSON.parse(raw ?? ''))).toEqual(config)
})
it.each([
@@ -23,6 +24,10 @@ describe('workflowTriggerPrefill', () => {
['a non-JSON string', 'not-json'],
['an unknown trigger type', '{"type":"nonsense"}'],
['a batch trigger missing its filters', '{"type":"batch"}'],
+ [
+ 'a batch audience with a filter the backend would drop',
+ '{"type":"batch","filters":{"properties":[{"key":"email","type":"person","operator":"exact"}]}}',
+ ],
])('returns null for %s', (_label, raw) => {
expect(parseWorkflowTriggerPrefill(raw)).toBeNull()
})
diff --git a/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts b/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts
index a3bba23e55c4..96d756c3d742 100644
--- a/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts
+++ b/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts
@@ -2,6 +2,7 @@ import { combineUrl } from 'kea-router'
import { urls } from 'scenes/urls'
+import { parseBroadcastAudiencePrefill } from '../Broadcasts/broadcastAudiencePrefill'
import { HogFlowTriggerSchema } from './hogflows/steps/types'
import type { HogFlowAction } from './hogflows/types'
@@ -13,13 +14,23 @@ export function urlForNewWorkflowWithTrigger(config: WorkflowTriggerConfig): str
return combineUrl(urls.workflowNew(), { [TRIGGER_PREFILL_PARAM]: JSON.stringify(config) }).url
}
-export function parseWorkflowTriggerPrefill(raw: string | undefined): WorkflowTriggerConfig | null {
+// kea-router hands over JSON-looking search params already parsed, so accept an object too.
+export function parseWorkflowTriggerPrefill(raw: unknown): WorkflowTriggerConfig | null {
if (!raw) {
return null
}
try {
- const result = HogFlowTriggerSchema.safeParse(JSON.parse(raw))
- return result.success ? (result.data as WorkflowTriggerConfig) : null
+ const result = HogFlowTriggerSchema.safeParse(typeof raw === 'string' ? JSON.parse(raw) : raw)
+ if (!result.success) {
+ return null
+ }
+ const config = result.data as WorkflowTriggerConfig
+ if (config.type !== 'batch' || !config.filters.properties?.length) {
+ return config
+ }
+ // A batch audience gets the same check as a broadcast link, so a filter the backend drops can't widen it.
+ const properties = parseBroadcastAudiencePrefill(config.filters.properties)
+ return properties ? { ...config, filters: { ...config.filters, properties } } : null
} catch {
return null
}