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 broadcasts send a push notification instead of an email (#121798)

Daniel Marchukd59482fafeba
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7dee153dbacc..fb15260c8bc7 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -271,6 +271,7 @@ export const FEATURE_FLAGS = {
BILLING_ALERTS: 'billing-alerts', // owner: #team-billing, gates the Billing > Alerts tab
BILLING_REAL_TIME_USAGE: 'billing-real-time-usage', // owner: #team-billing, gates the Real-time usage scene
BROADCASTS_AI_FIRST_NEW: 'broadcasts-ai-first-new', // owner: @dmarchuk #team-workflows
+ BROADCASTS_PUSH_CHANNEL: 'broadcasts-push-channel', // owner: @dmarchuk #team-workflows, push as a broadcast channel
CANVAS_COMMENTS: 'posthog-desktop-canvas-comments', // owner: @k11kirky, shows canvas comments and selection comments on web canvases, shared with PostHog Desktop
CDP_DWH_TABLE_SOURCE: 'cdp-dwh-table-source', // owner: #team-workflows-cdp
CDP_DWH_VIEW_SOURCE: 'cdp-dwh-view-source', // owner: #team-workflows-cdp
diff --git a/products/workflows/frontend/Broadcasts/BroadcastPushPerformance.tsx b/products/workflows/frontend/Broadcasts/BroadcastPushPerformance.tsx
new file mode 100644
index 000000000000..d106fad8ecc1
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/BroadcastPushPerformance.tsx
@@ -0,0 +1,105 @@
+import { useActions, useValues } from 'kea'
+
+import { IconInfo } from '@posthog/icons'
+import { LemonBanner, LemonSkeleton, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+
+import { BroadcastPerformanceLogicProps, broadcastPerformanceLogic } from './broadcastPerformanceLogic'
+import { BroadcastSendActivity } from './BroadcastSendActivity'
+
+const PUSH_DOCS_URL = 'https://posthog.com/docs/workflows/push-notifications'
+
+function ofSent(part: number, sent: number): string {
+ return sent > 0 ? `${percentage(part / sent, 1)} of sent` : 'of sent'
+}
+
+function Stat({
+ label,
+ value,
+ detail,
+ info,
+}: {
+ label: string
+ value: number
+ detail: string
+ info?: string
+}): JSX.Element {
+ return (
+ <div className="flex flex-col" data-attr={`broadcast-push-stat-${label.toLowerCase().replace(' ', '-')}`}>
+ <span className="text-xs uppercase tracking-wide text-muted">{label}</span>
+ <span className="text-xl font-semibold">{humanFriendlyNumber(value)}</span>
+ <span className="flex items-center gap-1 text-xs text-muted">
+ {detail}
+ {info ? (
+ <Tooltip title={info}>
+ <IconInfo className="text-sm" />
+ </Tooltip>
+ ) : null}
+ </span>
+ </div>
+ )
+}
+
+/** A push send's numbers. Push providers confirm they accepted a notification, never that a phone showed it. */
+export function BroadcastPushPerformance({
+ hasGoal = false,
+ ...props
+}: BroadcastPerformanceLogicProps & { hasGoal?: boolean }): JSX.Element {
+ const logic = broadcastPerformanceLogic(props)
+ const { stats, totalsLoading, totalsFailed } = useValues(logic)
+ const { loadTotals } = useActions(logic)
+
+ if (totalsFailed && !totalsLoading) {
+ return (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: loadTotals, 'data-attr': 'broadcast-performance-retry' }}
+ >
+ Couldn't load this send's numbers.
+ </LemonBanner>
+ )
+ }
+ if (!stats) {
+ return <LemonSkeleton className="h-40" active={totalsLoading} />
+ }
+
+ const attempted = stats.sent + stats.skipped + stats.failed
+
+ return (
+ <div className="flex flex-col gap-4 rounded-lg border border-border bg-surface-primary p-4">
+ <div
+ className={
+ hasGoal ? 'grid grid-cols-2 gap-4 @xl:grid-cols-5' : 'grid grid-cols-2 gap-4 @xl:grid-cols-4'
+ }
+ >
+ <Stat
+ label="Sent"
+ value={stats.sent}
+ detail={`of ${humanFriendlyNumber(attempted)} attempted`}
+ info="Accepted by Apple or Google. They don't confirm the phone received it."
+ />
+ <Stat label="Opened" value={stats.opened} detail={ofSent(stats.opened, stats.sent)} />
+ <Stat
+ label="No device"
+ value={stats.skipped}
+ detail="no registered phone"
+ info="These people haven't registered a phone for this app yet, for example they never allowed notifications, turned them off, or reinstalled the app."
+ />
+ <Stat label="Failed" value={stats.failed} detail="errors" />
+ {hasGoal ? (
+ <Stat label="Converted" value={stats.converted} detail={ofSent(stats.converted, stats.sent)} />
+ ) : null}
+ </div>
+ <span className="text-xs text-muted">
+ Counts are notifications, one for each app a person is sent through. Opens are counted when your app
+ reports a tapped notification. Your app registers each phone for push,{' '}
+ <Link to={PUSH_DOCS_URL} target="_blank">
+ see the push setup guide
+ </Link>
+ .
+ </span>
+ <BroadcastSendActivity {...props} hideSingleBucket />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/BroadcastPushPreview.tsx b/products/workflows/frontend/Broadcasts/BroadcastPushPreview.tsx
new file mode 100644
index 000000000000..35522a532045
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/BroadcastPushPreview.tsx
@@ -0,0 +1,58 @@
+import { useActions, useValues } from 'kea'
+
+import { IconNotification, IconSend } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { broadcastPreviewLogic } from './broadcastPreviewLogic'
+import { broadcastTestSendLogic } from './broadcastTestSendLogic'
+import { SendTestBroadcastModal } from './SendTestBroadcastModal'
+
+/** The notification as a lock screen shows it, with one audience member's values filled in. */
+export function BroadcastPushPreview({ showTestButton = true }: { showTestButton?: boolean }): JSX.Element {
+ const { previewPerson, previewPushTitle, previewPushBody } = useValues(broadcastPreviewLogic)
+ const { setModalOpen } = useActions(broadcastTestSendLogic)
+
+ return (
+ <div className="flex flex-col gap-2" data-attr="broadcast-push-preview">
+ {showTestButton ? (
+ <div className="flex justify-end">
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconSend />}
+ onClick={() => setModalOpen(true)}
+ data-attr="broadcast-open-test-push"
+ >
+ Send test notification
+ </LemonButton>
+ </div>
+ ) : null}
+ <SendTestBroadcastModal />
+ <div className="flex justify-center rounded-lg border border-border bg-surface-secondary px-4 py-6">
+ <div className="flex w-full max-w-sm items-start gap-3 rounded-lg border border-border bg-surface-primary p-3 shadow-sm">
+ <span className="flex size-8 shrink-0 items-center justify-center rounded bg-surface-secondary text-lg">
+ <IconNotification />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="truncate font-semibold">
+ {previewPushTitle || <span className="text-muted">Notification title</span>}
+ </span>
+ <span className="shrink-0 text-xs text-muted">now</span>
+ </div>
+ {previewPushBody ? (
+ <span className="line-clamp-4 whitespace-pre-wrap wrap-anywhere text-sm">
+ {previewPushBody}
+ </span>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ <span className="text-xs text-muted">
+ {previewPerson
+ ? `Values come from ${previewPerson.displayName}. Each device shows the notification in its own style.`
+ : 'No one matches this audience yet, so variables stay unfilled. Each device shows the notification in its own style.'}
+ </span>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/BroadcastSendActivity.tsx b/products/workflows/frontend/Broadcasts/BroadcastSendActivity.tsx
index 3dbe31ab5a53..4258a22e706a 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastSendActivity.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastSendActivity.tsx
@@ -11,30 +11,49 @@ const METRIC_LABELS: Record<string, string> = {
email_delivered: 'Delivered',
email_opened: 'Opened',
email_link_clicked: 'Link clicked',
+ push_sent: 'Sent',
+ push_opened: 'Opened',
}
const SERIES_COLORS = Object.fromEntries(
Object.entries(METRIC_LABELS).map(([metricName, label]) => [metricName, METRIC_COLORS[label]])
)
-export function BroadcastSendActivity({ runId, runStartedAt }: BroadcastPerformanceLogicProps): JSX.Element {
+export function BroadcastSendActivity({
+ runId,
+ runStartedAt,
+ channel,
+ hideSingleBucket = false,
+}: BroadcastPerformanceLogicProps & {
+ hideSingleBucket?: boolean
+}): JSX.Element | null {
const { appMetricsTrends, appMetricsTrendsLoading } = useValues(
appMetricsLogic({
logicKey: `broadcast-send-activity-${runId}`,
loadOnMount: true,
loadOnChanges: true,
loadPreviousPeriod: false,
- forceParams: sendActivityParams(runId, runStartedAt),
+ forceParams: sendActivityParams(runId, runStartedAt, undefined, channel),
})
)
const hasActivity = !!appMetricsTrends?.series.some((series) => series.values.some((value) => value > 0))
+ const activeBuckets = new Set(
+ appMetricsTrends?.series.flatMap((series) =>
+ series.values.flatMap((value, index) => (value > 0 ? [index] : []))
+ )
+ )
+ if (hideSingleBucket && !appMetricsTrendsLoading && activeBuckets.size <= 1) {
+ return null
+ }
return (
<div className="flex flex-col gap-2">
<h3 className="m-0 text-sm font-semibold">Activity over time</h3>
{!appMetricsTrendsLoading && appMetricsTrends && !hasActivity ? (
- <span className="text-muted">No email activity recorded for this send yet.</span>
+ <span className="text-muted">
+ No {channel === 'push' ? 'push' : 'email'} activity recorded for this send yet.
+ </span>
) : (
<AppMetricsTrends
appMetricsTrends={appMetricsTrends}
diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
index a3a17680e9c0..bb2e00584219 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
@@ -34,6 +34,8 @@ import { broadcastAudienceCohortsLogic } from './audience/broadcastAudienceCohor
import { BroadcastEmailPreview } from './BroadcastEmailPreview'
import { archiveDisabledReason, manageDisabledReason } from './broadcastLifecycle'
import { BroadcastPerformance } from './BroadcastPerformance'
+import { BroadcastPushPerformance } from './BroadcastPushPerformance'
+import { BroadcastPushPreview } from './BroadcastPushPreview'
import { BroadcastSceneHeader } from './BroadcastSceneHeader'
import { broadcastSentLogic } from './broadcastSentLogic'
import { BroadcastStatusTag } from './BroadcastStatusTag'
@@ -279,6 +281,8 @@ export function BroadcastSummary(): JSX.Element {
summaryTab,
goalEnabled,
conversion,
+ channel,
+ push,
} = useValues(broadcastWizardLogic)
const { moveToDraft, duplicateBroadcast, setSummaryTab, archiveBroadcast, restoreBroadcast, deleteBroadcast } =
useActions(broadcastWizardLogic)
@@ -479,16 +483,29 @@ export function BroadcastSummary(): JSX.Element {
<span>{scheduleSummary}</span>
)}
</SummaryRow>
- <SummaryRow label="Subject">
- {email.subject || <span className="text-muted">No subject</span>}
- </SummaryRow>
+ {channel === 'push' ? (
+ <SummaryRow label="Notification title">
+ {push.title || <span className="text-muted">No title</span>}
+ </SummaryRow>
+ ) : (
+ <SummaryRow label="Subject">
+ {email.subject || <span className="text-muted">No subject</span>}
+ </SummaryRow>
+ )}
{goalEnabled && <SummaryRow label="Goal">{goalSummary(conversion)}</SummaryRow>}
</div>
<div className="flex flex-col gap-2">
<h2 className="m-0 text-base font-semibold">
{latestBatchJobId ? 'Performance (latest send)' : 'Performance'}
</h2>
- {latestBatchJob ? (
+ {latestBatchJob && channel === 'push' ? (
+ <BroadcastPushPerformance
+ runId={latestBatchJob.id}
+ runStartedAt={latestBatchJob.created_at}
+ hasGoal={goalEnabled}
+ channel={channel}
+ />
+ ) : latestBatchJob ? (
<BroadcastPerformance
runId={latestBatchJob.id}
runStartedAt={latestBatchJob.created_at}
@@ -507,9 +524,12 @@ export function BroadcastSummary(): JSX.Element {
key: 'content',
'data-attr': 'broadcast-summary-tab-content',
label: 'Content',
- content: (
- <BroadcastEmailPreview intro="Preview the email for anyone in the audience, or send yourself a test." />
- ),
+ content:
+ channel === 'push' ? (
+ <BroadcastPushPreview />
+ ) : (
+ <BroadcastEmailPreview intro="Preview the email for anyone in the audience, or send yourself a test." />
+ ),
},
{
key: 'runs',
diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
index def43d146453..abe2fb2c1995 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
@@ -17,15 +17,22 @@ import type { HogFlowMinimalApi } from 'products/workflows/frontend/generated/ap
import { archiveDisabledReason, manageDisabledReason } from './broadcastLifecycle'
import { BroadcastsEmptyState } from './BroadcastsEmptyState'
-import { BROADCASTS_PAGE_SIZE, BroadcastsStatusFilter, broadcastsLogic, getBroadcastStatus } from './broadcastsLogic'
+import {
+ BROADCASTS_PAGE_SIZE,
+ BroadcastsStatusFilter,
+ broadcastsLogic,
+ getBroadcastChannel,
+ getBroadcastStatus,
+} from './broadcastsLogic'
import { BroadcastStatusTag } from './BroadcastStatusTag'
-const METRIC_COLUMNS: { title: string; metricName: string }[] = [
- { title: 'Sent', metricName: 'email_sent' },
- { title: 'Delivered', metricName: 'email_delivered' },
- { title: 'Opened', metricName: 'email_opened' },
- { title: 'Clicked', metricName: 'email_link_clicked' },
- { title: 'Converted', metricName: 'conversion' },
+// Push has no delivery receipts or link tracking, so those columns stay empty for a push broadcast.
+const METRIC_COLUMNS: { title: string; metricName: string; pushMetricName: string | null }[] = [
+ { title: 'Sent', metricName: 'email_sent', pushMetricName: 'push_sent' },
+ { title: 'Delivered', metricName: 'email_delivered', pushMetricName: null },
+ { title: 'Opened', metricName: 'email_opened', pushMetricName: 'push_opened' },
+ { title: 'Clicked', metricName: 'email_link_clicked', pushMetricName: null },
+ { title: 'Converted', metricName: 'conversion', pushMetricName: 'conversion' },
]
export function BroadcastsTable(): JSX.Element {
@@ -105,19 +112,20 @@ export function BroadcastsTable(): JSX.Element {
)
},
},
- ...METRIC_COLUMNS.map(({ title, metricName }) => ({
+ ...METRIC_COLUMNS.map(({ title, metricName, pushMetricName }) => ({
title,
width: 0,
align: 'right' as const,
render: (_: unknown, item: HogFlowMinimalApi) => {
const details = rowDetailsById[item.id]
- if (item.status === 'draft') {
+ const metric = getBroadcastChannel(item.actions as any) === 'push' ? pushMetricName : metricName
+ if (item.status === 'draft' || !metric) {
return <span className="text-muted">-</span>
}
if (!details?.totals) {
return <span className="text-muted">…</span>
}
- return <span>{humanFriendlyNumber(details.totals[metricName] ?? 0)}</span>
+ return <span>{humanFriendlyNumber(details.totals[metric] ?? 0)}</span>
},
})),
createdByColumn() as LemonTableColumns<HogFlowMinimalApi>[number],
diff --git a/products/workflows/frontend/Broadcasts/SendTestBroadcastModal.tsx b/products/workflows/frontend/Broadcasts/SendTestBroadcastModal.tsx
index 331af0ba38f6..1bfcf81a675c 100644
--- a/products/workflows/frontend/Broadcasts/SendTestBroadcastModal.tsx
+++ b/products/workflows/frontend/Broadcasts/SendTestBroadcastModal.tsx
@@ -12,16 +12,25 @@ export function SendTestBroadcastModal(): JSX.Element {
sendDisabledReason,
testSendResult,
testSendSkipReason,
+ testSendPartialFailure,
testSendResultLoading,
+ channel,
+ recipientDistinctId,
} = useValues(broadcastTestSendLogic)
- const { setModalOpen, setRecipientEmail, sendTestEmail } = useActions(broadcastTestSendLogic)
+ const { setModalOpen, setRecipientEmail, setRecipientDistinctId, sendTestEmail } =
+ useActions(broadcastTestSendLogic)
+ const isPush = channel === 'push'
return (
<LemonModal
isOpen={isModalOpen}
onClose={() => setModalOpen(false)}
- title="Send a test email"
- description="Goes to this address only. Nobody in the audience receives it."
+ title={isPush ? 'Send a test notification' : 'Send a test email'}
+ description={
+ isPush
+ ? "Goes to this person's devices only. Nobody in the audience receives it."
+ : 'Goes to this address only. Nobody in the audience receives it.'
+ }
footer={
<>
<LemonButton type="secondary" onClick={() => setModalOpen(false)}>
@@ -40,17 +49,31 @@ export function SendTestBroadcastModal(): JSX.Element {
}
>
<div className="flex flex-col gap-3 max-w-160">
- <div className="flex flex-col gap-1">
- <LemonLabel>Send to</LemonLabel>
- <LemonInput
- type="email"
- value={recipientEmail}
- onChange={setRecipientEmail}
- placeholder="[email protected]"
- autoFocus
- data-attr="broadcast-test-email-recipient"
- />
- </div>
+ {isPush ? (
+ <div className="flex flex-col gap-1">
+ <LemonLabel info="Starts as your own PostHog user's distinct ID. Use the ID your app identifies you with.">
+ Send to distinct ID
+ </LemonLabel>
+ <LemonInput
+ value={recipientDistinctId}
+ onChange={setRecipientDistinctId}
+ autoFocus
+ data-attr="broadcast-test-push-recipient"
+ />
+ </div>
+ ) : (
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Send to</LemonLabel>
+ <LemonInput
+ type="email"
+ value={recipientEmail}
+ onChange={setRecipientEmail}
+ placeholder="[email protected]"
+ autoFocus
+ data-attr="broadcast-test-email-recipient"
+ />
+ </div>
+ )}
<span className="text-muted text-xs">
{previewPerson
@@ -60,15 +83,20 @@ export function SendTestBroadcastModal(): JSX.Element {
{testSendSkipReason ? (
<LemonBanner type="warning">{testSendSkipReason}</LemonBanner>
+ ) : testSendPartialFailure ? (
+ <LemonBanner type="warning">
+ Some apps took the notification, but at least one failed: {testSendPartialFailure}
+ </LemonBanner>
) : testSendResult?.status === 'skipped' ? (
<LemonBanner type="warning">
{testSendResult.logs?.map((log) => log.message).join(' ') ||
- 'The email step was skipped, so nothing was sent.'}
+ `The ${isPush ? 'push' : 'email'} step was skipped, so nothing was sent.`}
</LemonBanner>
) : null}
{testSendResult?.status === 'error' && (
<LemonBanner type="error">
- {testSendResult.errors?.join(', ') || 'Could not send the test email.'}
+ {testSendResult.errors?.join(', ') ||
+ `Could not send the test ${isPush ? 'notification' : 'email'}.`}
</LemonBanner>
)}
</div>
diff --git a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts
index e48c87d92826..a2810911821e 100644
--- a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts
@@ -7,11 +7,13 @@ import { teamLogic } from 'scenes/teamLogic'
import type { TeamPublicType, TeamType } from '../../../../frontend/src/types'
import { type EmailLinkRow, parseEmailLinkTotals } from '../Workflows/workflowMetricsSummaryLogic'
+import type { BroadcastChannel } from './broadcastsLogic'
export interface BroadcastPerformanceLogicProps {
/** The batch run the numbers belong to. A batch send's email metrics are recorded against the run, not the flow. */
runId: string
runStartedAt: string
+ channel?: BroadcastChannel
}
export interface BroadcastPerformanceStats {
@@ -27,6 +29,8 @@ export interface BroadcastPerformanceStats {
trackedSends: number
/** Recipients who met the broadcast's goal. */
converted: number
+ /** Push only: people with no device registered for the app. */
+ skipped: number
}
const TOTALS_METRICS = [
@@ -38,17 +42,27 @@ const TOTALS_METRICS = [
'email_blocked',
'email_failed',
'email_untracked',
+ 'push_sent',
+ 'push_skipped',
+ 'push_failed',
+ 'push_opened',
'email_unsubscribed',
'conversion',
]
+const SEND_ACTIVITY_METRICS: Record<BroadcastChannel, string[]> = {
+ email: ['email_sent', 'email_delivered', 'email_opened', 'email_link_clicked'],
+ push: ['push_sent', 'push_opened'],
+}
+
/** Hourly buckets read well for a few days after a send, then the tail of late opens needs daily ones. */
const HOURLY_WINDOW_DAYS = 3
export function sendActivityParams(
runId: string,
runStartedAt: string,
- now: Dayjs = dayjs()
+ now: Dayjs = dayjs(),
+ channel: BroadcastChannel = 'email'
): Partial<AppMetricsCommonParams> {
const started = dayjs(runStartedAt)
const interval = now.diff(started, 'day', true) <= HOURLY_WINDOW_DAYS ? 'hour' : 'day'
@@ -57,7 +71,7 @@ export function sendActivityParams(
appSource: 'hog_flow',
appSourceId: runId,
breakdownBy: 'metric_name',
- metricName: ['email_sent', 'email_delivered', 'email_opened', 'email_link_clicked'],
+ metricName: SEND_ACTIVITY_METRICS[channel],
interval,
dateFrom: started.toISOString(),
}
@@ -117,7 +131,10 @@ export interface broadcastPerformanceLogicActions {
export interface broadcastPerformanceLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
- stats: (totals: Record<string, number> | null) => BroadcastPerformanceStats | null
+ stats: (
+ totals: Record<string, number> | null,
+ arg: BroadcastChannel | undefined
+ ) => BroadcastPerformanceStats | null
trackingOff: (stats: BroadcastPerformanceStats | null) => boolean
}
}
@@ -198,11 +215,31 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([
}),
selectors({
stats: [
- (s) => [s.totals],
- (totals: Record<string, number> | null): BroadcastPerformanceStats | null => {
+ (s) => [s.totals, (_, props: BroadcastPerformanceLogicProps) => props.channel],
+ (
+ totals: Record<string, number> | null,
+ channel: BroadcastChannel | undefined
+ ): BroadcastPerformanceStats | null => {
if (!totals) {
return null
}
+ if (channel === 'push') {
+ const pushSent = totals.push_sent ?? 0
+ // Push has no delivery receipts or link tracking, so every send counts as tracked.
+ return {
+ sent: pushSent,
+ delivered: 0,
+ opened: totals.push_opened ?? 0,
+ clicked: 0,
+ bounced: 0,
+ markedAsSpam: 0,
+ failed: totals.push_failed ?? 0,
+ trackedSends: pushSent,
+ converted: totals.conversion ?? 0,
+ skipped: totals.push_skipped ?? 0,
+ unsubscribed: 0,
+ }
+ }
const sent = totals.email_sent ?? 0
return {
sent,
@@ -216,6 +253,7 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([
unsubscribed: totals.email_unsubscribed ?? 0,
trackedSends: Math.max(sent - (totals.email_untracked ?? 0), 0),
converted: totals.conversion ?? 0,
+ skipped: 0,
}
},
],
@@ -225,8 +263,10 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([
(stats: BroadcastPerformanceStats | null): boolean => !!stats && stats.sent > 0 && stats.trackedSends === 0,
],
}),
- afterMount(({ actions }) => {
+ afterMount(({ actions, props }) => {
actions.loadTotals()
- actions.loadLinks()
+ if (props.channel !== 'push') {
+ actions.loadLinks()
+ }
}),
])
diff --git a/products/workflows/frontend/Broadcasts/broadcastPreviewLogic.ts b/products/workflows/frontend/Broadcasts/broadcastPreviewLogic.ts
index 2b44163686f5..ffbb17340cd7 100644
--- a/products/workflows/frontend/Broadcasts/broadcastPreviewLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastPreviewLogic.ts
@@ -8,7 +8,12 @@ import { Scene } from 'scenes/sceneTypes'
import { ActorsQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { AnyPersonScopeFilter, AnyPropertyFilter } from '~/types'
-import { BroadcastEmailValue, BroadcastWizardLogicProps, broadcastWizardLogic } from './broadcastWizardLogic'
+import {
+ BroadcastEmailValue,
+ BroadcastPushValue,
+ BroadcastWizardLogicProps,
+ broadcastWizardLogic,
+} from './broadcastWizardLogic'
import { EmailPreviewPerson, renderEmailPreview } from './emailPreview'
const PREVIEW_PERSON_LIMIT = 25
@@ -46,11 +51,14 @@ function parsePerson(row: any[]): BroadcastPreviewPerson {
export interface broadcastPreviewLogicValues {
audienceProperties: AnyPropertyFilter[] // broadcastWizardLogic
email: BroadcastEmailValue // broadcastWizardLogic
+ push: BroadcastPushValue // broadcastWizardLogic
persons: BroadcastPreviewPerson[]
personsFailed: boolean
personsLoading: boolean
previewHtml: string
previewPerson: BroadcastPreviewPerson | null
+ previewPushBody: string
+ previewPushTitle: string
previewSubject: string
previewText: string
previewTo: string
@@ -90,6 +98,8 @@ export interface broadcastPreviewLogicMeta {
previewSubject: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
previewHtml: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
previewText: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
+ previewPushTitle: (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null) => string
+ previewPushBody: (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null) => string
previewTo: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string
}
}
@@ -107,7 +117,7 @@ export const broadcastPreviewLogic = kea<broadcastPreviewLogicType>([
key((props) => props.id),
connect((props: BroadcastWizardLogicProps) => ({
- values: [broadcastWizardLogic(props), ['audienceProperties', 'email']],
+ values: [broadcastWizardLogic(props), ['audienceProperties', 'email', 'push']],
})),
actions({
@@ -188,6 +198,16 @@ export const broadcastPreviewLogic = kea<broadcastPreviewLogicType>([
(email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>
renderEmailPreview(email.text, previewPerson),
],
+ previewPushTitle: [
+ (s) => [s.push, s.previewPerson],
+ (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null): string =>
+ renderEmailPreview(push.title, previewPerson),
+ ],
+ previewPushBody: [
+ (s) => [s.push, s.previewPerson],
+ (push: BroadcastPushValue, previewPerson: BroadcastPreviewPerson | null): string =>
+ renderEmailPreview(push.body, previewPerson),
+ ],
previewTo: [
(s) => [s.email, s.previewPerson],
(email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>
diff --git a/products/workflows/frontend/Broadcasts/broadcastTestSend.test.ts b/products/workflows/frontend/Broadcasts/broadcastTestSend.test.ts
index 953830604fab..ff19c556a730 100644
--- a/products/workflows/frontend/Broadcasts/broadcastTestSend.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastTestSend.test.ts
@@ -1,12 +1,12 @@
import { HogflowTestResult } from '../Workflows/hogflows/steps/types'
-import { findTestSendSkipReason } from './broadcastTestSendLogic'
+import { findPushTestPartialFailure, findPushTestSkipReason, findTestSendSkipReason } from './broadcastTestSendLogic'
const result = (partial: Partial<HogflowTestResult>): HogflowTestResult =>
({ status: 'success', nextActionId: null, ...partial }) as HogflowTestResult
-const log = (message: string): any => ({ level: 'info', timestamp: '2026-01-01T00:00:00Z', message })
+const log = (message: string, level = 'info'): any => ({ level, timestamp: '2026-01-01T00:00:00Z', message })
-describe('findTestSendSkipReason', () => {
+describe('test send skip reasons', () => {
it('finds the reason a declined send reports, even though the run says success', () => {
// The worker declines the send but finishes the step, so status alone would read as sent.
const reason =
@@ -25,4 +25,45 @@ describe('findTestSendSkipReason', () => {
])('reports no reason for %s', (_name, input) => {
expect(findTestSendSkipReason(input)).toBeUndefined()
})
+
+ it.each([
+ [
+ 'a person with no registered device',
+ result({ logs: [log('No active FCM device token found for distinct_id: me', 'warn')] }),
+ 'No active FCM device token found for distinct_id: me',
+ ],
+ [
+ 'an app that took the notification',
+ result({ logs: [log('Push notification accepted by FCM for 1 of 1 device(s).')] }),
+ undefined,
+ ],
+ ['a failed run, which reports its own error', result({ status: 'error' }), undefined],
+ ])('reports whether a push test reached a device for %s', (_name, input, expected) => {
+ expect(findPushTestSkipReason(input)).toBe(expected)
+ })
+
+ it.each([
+ [
+ 'one app accepted and another failed',
+ result({
+ logs: [
+ log('[Action:a] Push notification accepted by FCM for 1 of 1 device(s).'),
+ log('[Action:a] APNs: BadDeviceToken', 'warn'),
+ ],
+ }),
+ '[Action:a] APNs: BadDeviceToken',
+ ],
+ [
+ 'one app accepted and the other had no device',
+ result({
+ logs: [
+ log('[Action:a] Push notification accepted by FCM for 1 of 1 device(s).'),
+ log('[Action:a] No active APNS device token found for distinct_id: me', 'warn'),
+ ],
+ }),
+ undefined,
+ ],
+ ])('reports app errors behind a delivered push test when %s', (_name, input, expected) => {
+ expect(findPushTestPartialFailure(input)).toBe(expected)
+ })
})
diff --git a/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts b/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts
index d16e80655dbc..c68ef6b93cbd 100644
--- a/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts
@@ -16,16 +16,21 @@ import { createExampleEvent } from '../Workflows/hogflows/testEventFactory'
import type { HogFlow, HogFlowAction, HogFlowEdge } from '../Workflows/hogflows/types'
import { EXIT_NODE_ID, NEW_WORKFLOW, TRIGGER_NODE_ID } from '../Workflows/workflowLogic'
import { BroadcastPreviewPerson, broadcastPreviewLogic } from './broadcastPreviewLogic'
+import { BroadcastChannel } from './broadcastsLogic'
import {
BroadcastEmailSettings,
BroadcastEmailValue,
+ BroadcastPushValue,
BroadcastWizardLogicProps,
broadcastWizardLogic,
+ findPushInputs,
+ pushInputs,
} from './broadcastWizardLogic'
// Fixed id for the single email action in the synthetic test flow. The edges below reference it,
// and it goes over as `current_action_id` so the worker runs just this node.
const TEST_EMAIL_ACTION_ID = 'send_test_email'
+const TEST_PUSH_ACTION_ID = 'send_test_push'
// Every reason the email worker declines a send is logged behind this prefix
// (nodejs/src/cdp/services/messaging/email-validation.service.ts).
@@ -42,23 +47,64 @@ export function findTestSendSkipReason(result: HogflowTestResult | null): string
return result?.logs?.find((log) => log.message?.includes(SKIP_LOG_PREFIX))?.message
}
+// The push worker logs this once per app that took the notification
+// (nodejs/src/cdp/services/messaging/push-notification.service.ts).
+const PUSH_ACCEPTED_LOG = /accepted by (FCM|APNs)/
+
+/** Why a push test reached no device. A push with no registered device still finishes cleanly. */
+export function findPushTestSkipReason(result: HogflowTestResult | null): string | undefined {
+ if (result?.status !== 'success' || result.logs?.some((log) => PUSH_ACCEPTED_LOG.test(log.message ?? ''))) {
+ return undefined
+ }
+ const warnings = result.logs
+ ?.filter((log) => String(log.level).toLowerCase().startsWith('warn'))
+ .map((log) => log.message)
+ return warnings?.length
+ ? warnings.join(' ')
+ : 'No device took the notification. Check that this person has push turned on in your app.'
+}
+
+// Per-app delivery errors from the same worker. A missing token on one app is not one of them.
+const PUSH_APP_FAILURE_LOG = /(FCM|APNs): /
+
+export function findPushTestPartialFailure(result: HogflowTestResult | null): string | undefined {
+ if (result?.status !== 'success' || !result.logs?.some((log) => PUSH_ACCEPTED_LOG.test(log.message ?? ''))) {
+ return undefined
+ }
+ const failures = result.logs
+ .filter((log) => String(log.level).toLowerCase() === 'error' || PUSH_APP_FAILURE_LOG.test(log.message ?? ''))
+ .map((log) => log.message)
+ return failures.length ? failures.join(' ') : undefined
+}
+
+/** Liquid prints a raw block as typed, so braces in a distinct ID never run as a template. */
+export function literalDistinctIdInput(distinctId: string): { value: string; templating: 'liquid' } {
+ return { value: `{% raw %}${distinctId}{% endraw %}`, templating: 'liquid' }
+}
+
+type TestedContent = BroadcastEmailValue | BroadcastPushValue
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastTestSendLogicValues {
previewPerson: BroadcastPreviewPerson | null // broadcastPreviewLogic
broadcast: HogFlowApi | null // broadcastWizardLogic
+ channel: BroadcastChannel // broadcastWizardLogic
email: BroadcastEmailValue // broadcastWizardLogic
emailSettings: BroadcastEmailSettings // broadcastWizardLogic
name: string // broadcastWizardLogic
+ push: BroadcastPushValue // broadcastWizardLogic
currentTeamId: number | null // teamLogic
user: UserType | null // userLogic
isModalOpen: boolean
lastTestSent: {
- email: BroadcastEmailValue
+ content: TestedContent
to: string
} | null
lastTestSentTo: string | null
+ recipientDistinctId: string
recipientEmail: string
sendDisabledReason: string | undefined
+ testSendPartialFailure: string | undefined
testSendResult: HogflowTestResult | null
testSendResultLoading: boolean
testSendSkipReason: string | undefined
@@ -89,9 +135,9 @@ export interface broadcastTestSendLogicActions {
}
markTestSent: (
to: string,
- email: BroadcastEmailValue
+ content: TestedContent
) => {
- email: BroadcastEmailValue
+ content: TestedContent
to: string
}
sendTestEmail: () => any
@@ -112,6 +158,9 @@ export interface broadcastTestSendLogicActions {
setModalOpen: (open: boolean) => {
open: boolean
}
+ setRecipientDistinctId: (distinctId: string) => {
+ distinctId: string
+ }
setRecipientEmail: (email: string) => {
email: string
}
@@ -123,13 +172,25 @@ export interface broadcastTestSendLogicMeta {
__keaTypeGenInternalSelectorTypes: {
lastTestSentTo: (
lastTestSent: {
- email: BroadcastEmailValue
+ content: TestedContent
to: string
} | null,
- email: BroadcastEmailValue
+ email: BroadcastEmailValue,
+ push: BroadcastPushValue,
+ channel: BroadcastChannel
) => string | null
- testSendSkipReason: (testSendResult: HogflowTestResult | null) => string | undefined
- sendDisabledReason: (email: BroadcastEmailValue, recipientEmail: string) => string | undefined
+ testSendPartialFailure: (
+ testSendResult: HogflowTestResult | null,
+ channel: BroadcastChannel
+ ) => string | undefined
+ testSendSkipReason: (testSendResult: HogflowTestResult | null, channel: BroadcastChannel) => string | undefined
+ sendDisabledReason: (
+ email: BroadcastEmailValue,
+ recipientEmail: string,
+ channel: BroadcastChannel,
+ push: BroadcastPushValue,
+ recipientDistinctId: string
+ ) => string | undefined
}
}
@@ -153,7 +214,7 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
connect((props: BroadcastWizardLogicProps) => ({
values: [
broadcastWizardLogic(props),
- ['broadcast', 'email', 'emailSettings', 'name'],
+ ['broadcast', 'email', 'emailSettings', 'name', 'channel', 'push'],
broadcastPreviewLogic(props),
['previewPerson'],
teamLogic,
@@ -166,16 +227,18 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
actions({
setModalOpen: (open: boolean) => ({ open }),
setRecipientEmail: (email: string) => ({ email }),
+ setRecipientDistinctId: (distinctId: string) => ({ distinctId }),
clearTestSendResult: true,
- markTestSent: (to: string, email: BroadcastEmailValue) => ({ to, email }),
+ markTestSent: (to: string, content: TestedContent) => ({ to, content }),
}),
reducers({
isModalOpen: [false, { setModalOpen: (_, { open }) => open }],
recipientEmail: ['', { setRecipientEmail: (_, { email }) => email }],
+ recipientDistinctId: ['', { setRecipientDistinctId: (_, { distinctId }) => distinctId }],
lastTestSent: [
- null as { to: string; email: BroadcastEmailValue } | null,
- { markTestSent: (_, { to, email }) => ({ to, email }) },
+ null as { to: string; content: TestedContent } | null,
+ { markTestSent: (_, { to, content }) => ({ to, content }) },
],
}),
@@ -187,8 +250,11 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
sendTestEmail: async (): Promise<HogflowTestResult> => {
const { broadcast, email, emailSettings, name, previewPerson, recipientEmail, currentTeamId } =
values
+ if (values.channel === 'push') {
+ return await sendTestPush(values, cache)
+ }
// The recipient field stays editable while the send runs, so remember what this send used.
- cache.pendingTest = { to: recipientEmail, email }
+ cache.pendingTest = { to: recipientEmail, content: email }
const emailAction: HogFlowAction = {
id: TEST_EMAIL_ACTION_ID,
@@ -268,19 +334,48 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
selectors({
// Only vouches for the email as it was tested. Any later change, typed or from another editor, clears it.
lastTestSentTo: [
- (s) => [s.lastTestSent, s.email],
+ (s) => [s.lastTestSent, s.email, s.push, s.channel],
(
- lastTestSent: { to: string; email: BroadcastEmailValue } | null,
- email: BroadcastEmailValue
- ): string | null => (lastTestSent && objectsEqual(lastTestSent.email, email) ? lastTestSent.to : null),
+ lastTestSent: { to: string; content: TestedContent } | null,
+ email: BroadcastEmailValue,
+ push: BroadcastPushValue,
+ channel: BroadcastChannel
+ ): string | null =>
+ lastTestSent && objectsEqual(lastTestSent.content, channel === 'push' ? push : email)
+ ? lastTestSent.to
+ : null,
+ ],
+ testSendPartialFailure: [
+ (s) => [s.testSendResult, s.channel],
+ (testSendResult: HogflowTestResult | null, channel: BroadcastChannel): string | undefined =>
+ channel === 'push' ? findPushTestPartialFailure(testSendResult) : undefined,
],
testSendSkipReason: [
- (s) => [s.testSendResult],
- (testSendResult: HogflowTestResult | null): string | undefined => findTestSendSkipReason(testSendResult),
+ (s) => [s.testSendResult, s.channel],
+ (testSendResult: HogflowTestResult | null, channel: BroadcastChannel): string | undefined =>
+ channel === 'push' ? findPushTestSkipReason(testSendResult) : findTestSendSkipReason(testSendResult),
],
sendDisabledReason: [
- (s) => [s.email, s.recipientEmail],
- (email: BroadcastEmailValue, recipientEmail: string): string | undefined => {
+ (s) => [s.email, s.recipientEmail, s.channel, s.push, s.recipientDistinctId],
+ (
+ email: BroadcastEmailValue,
+ recipientEmail: string,
+ channel: BroadcastChannel,
+ push: BroadcastPushValue,
+ recipientDistinctId: string
+ ): string | undefined => {
+ if (channel === 'push') {
+ if (push.channels.length === 0) {
+ return 'Choose a push channel first'
+ }
+ if (!push.title.trim()) {
+ return 'Add a notification title first'
+ }
+ if (recipientDistinctId.includes('{% endraw')) {
+ return 'This distinct ID contains text that cannot be sent'
+ }
+ return recipientDistinctId.trim() ? undefined : 'Enter a distinct ID'
+ }
if (!email.from?.integrationId) {
return 'Choose an email sender first'
}
@@ -305,25 +400,91 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
if (open && !values.recipientEmail && values.user?.email) {
actions.setRecipientEmail(values.user.email)
}
+ if (open && !values.recipientDistinctId && values.user?.distinct_id) {
+ actions.setRecipientDistinctId(values.user.distinct_id)
+ }
},
sendTestEmailSuccess: ({ testSendResult }) => {
// A declined send finishes the step cleanly, so check the reason before the status.
if (values.testSendSkipReason) {
lemonToast.warning('Nothing was sent, see why below')
+ } else if (values.testSendPartialFailure) {
+ lemonToast.warning('Sent through some apps only, see the errors below')
+ if (cache.pendingTest) {
+ actions.markTestSent(cache.pendingTest.to, cache.pendingTest.content)
+ }
} else if (testSendResult?.status === 'success') {
- lemonToast.success(`Test email sent to ${cache.pendingTest?.to ?? values.recipientEmail}`)
+ const to = cache.pendingTest?.to ?? values.recipientEmail
+ lemonToast.success(
+ values.channel === 'push' ? `Test notification sent to ${to}'s devices` : `Test email sent to ${to}`
+ )
if (cache.pendingTest) {
- actions.markTestSent(cache.pendingTest.to, cache.pendingTest.email)
+ actions.markTestSent(cache.pendingTest.to, cache.pendingTest.content)
}
actions.setModalOpen(false)
} else if (testSendResult?.status === 'skipped') {
- lemonToast.warning('The email step was skipped, so nothing was sent')
+ lemonToast.warning(
+ `The ${values.channel === 'push' ? 'push' : 'email'} step was skipped, so nothing was sent`
+ )
} else {
- lemonToast.error('Could not send the test email')
+ lemonToast.error(`Could not send the test ${values.channel === 'push' ? 'notification' : 'email'}`)
}
},
sendTestEmailFailure: () => {
- lemonToast.error('Could not send the test email')
+ lemonToast.error(`Could not send the test ${values.channel === 'push' ? 'notification' : 'email'}`)
},
})),
])
+
+/** Runs the push step once against one person, so the sender sees it on their own phone first. */
+async function sendTestPush(
+ values: broadcastTestSendLogicType['values'],
+ cache: Record<string, any>
+): Promise<HogflowTestResult> {
+ const { push, name, currentTeamId } = values
+ const distinctId = values.recipientDistinctId.trim()
+ cache.pendingTest = { to: distinctId, content: push }
+ const pushAction: HogFlowAction = {
+ id: TEST_PUSH_ACTION_ID,
+ type: 'function_push',
+ name: 'Send test push',
+ description: '',
+ created_at: 0,
+ updated_at: 0,
+ config: {
+ template_id: 'template-native-push',
+ inputs: {
+ ...pushInputs(push, findPushInputs(values.broadcast)),
+ // Not the example event's distinct id, so the worker looks up this person's own devices.
+ distinctId: literalDistinctIdInput(distinctId),
+ },
+ },
+ } as HogFlowAction
+ const configuration: HogFlow = {
+ ...NEW_WORKFLOW,
+ team_id: currentTeamId ?? NEW_WORKFLOW.team_id,
+ name: name || 'Test broadcast',
+ actions: [NEW_WORKFLOW.actions[0], pushAction, NEW_WORKFLOW.actions[1]],
+ edges: [
+ { from: TRIGGER_NODE_ID, to: TEST_PUSH_ACTION_ID, type: 'continue' },
+ { from: TEST_PUSH_ACTION_ID, to: EXIT_NODE_ID, type: 'continue' },
+ ],
+ }
+ const globals = createExampleEvent(currentTeamId ?? undefined, configuration.name, '$pageview')
+ if (values.previewPerson) {
+ // Variables render as they do in the preview.
+ globals.person = {
+ id: values.previewPerson.id,
+ properties: values.previewPerson.properties,
+ name: values.previewPerson.displayName,
+ url: globals.person?.url ?? '',
+ }
+ }
+ // nosemgrep: prefer-codegen-api-namespaced-workflows -- The generated hogFlowsInvocationsCreate returns void, and this caller needs the test result.
+ return await api.hogFlows.createTestInvocation('new', {
+ configuration,
+ globals,
+ mock_async_functions: false,
+ current_action_id: TEST_PUSH_ACTION_ID,
+ })
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 45a03938e08e..27a46c677390 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -3,8 +3,9 @@ import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'
-import { lemonToast } from '@posthog/lemon-ui'
+import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -42,6 +43,7 @@ import {
} from 'products/workflows/frontend/generated/api'
import type {
BlastRadiusApi,
+ BlastRadiusRequestApi,
HogFlowApi,
HogFlowBatchJobApi,
HogFlowConversionApi,
@@ -110,10 +112,13 @@ import {
restoreBroadcast,
} from './broadcastLifecycle'
import {
+ BROADCAST_MESSAGE_ACTION_TYPES,
+ BroadcastChannel,
BroadcastStatus,
StoppableBroadcast,
canEditInWizard,
canMoveToDraft,
+ getBroadcastChannel,
getBroadcastStatus,
} from './broadcastsLogic'
import {
@@ -196,8 +201,90 @@ export const DEFAULT_BROADCAST_EMAIL_SETTINGS: BroadcastEmailSettings = {
utmParams: {},
}
+/** The push step's inputs the wizard edits, mirroring the `template-native-push` template. */
+export interface BroadcastPushValue {
+ /** Firebase and Apple push integrations to send through. */
+ channels: number[]
+ title: string
+ body: string
+}
+
+export const DEFAULT_BROADCAST_PUSH: BroadcastPushValue = { channels: [], title: '', body: '' }
+
+export const PUSH_INTEGRATION_KINDS = ['firebase', 'apns']
+export const NO_PUSH_CHANNELS_REASON = "Your project doesn't have push set up yet"
+export const PUSH_CHANNELS_LOAD_FAILED_REASON = "Couldn't check your push setup"
+
+// A person with any registered device has a person property under this prefix.
+const PUSH_SUBSCRIBED_HOGQL =
+ "arrayExists(k -> startsWith(k, '$device_push_subscription_'), JSONExtractKeys(properties))"
+
+export interface BroadcastChannelReach {
+ channel: BroadcastChannel
+ /** People who match the audience. */
+ total: number
+ /** People who match and can get the message: an email address, or a device registered for push. */
+ reachable: number
+}
+
+interface BroadcastChannelReachCounts extends Omit<BroadcastChannelReach, 'total'> {
+ /** Null for push, whose total is the blast radius count. */
+ total: number | null
+}
+
+export function findPushInputs(broadcast: HogFlowApi | null): Record<string, any> | undefined {
+ return broadcast ? findAction(broadcast, BROADCAST_MESSAGE_ACTION_TYPES.push)?.config?.inputs : undefined
+}
+
+function readPush(broadcast: HogFlowApi): BroadcastPushValue | null {
+ const inputs = findPushInputs(broadcast)
+ if (!inputs) {
+ return null
+ }
+ return {
+ channels: inputs.channels?.value ?? [],
+ title: inputs.title?.value ?? '',
+ body: inputs.body?.value ?? '',
+ }
+}
+
+// A saved input without `templating` renders as Hog in the worker, so only a new input defaults to Liquid.
+function pushTemplating(existing: { templating?: string } | undefined): string {
+ return existing ? (existing.templating ?? 'hog') : 'liquid'
+}
+
+// Inputs the wizard does not show, such as a custom recipient or extra data keys set in the workflow
+// editor, keep their saved values.
+export function pushInputs(push: BroadcastPushValue, existing: Record<string, any> = {}): Record<string, any> {
+ return {
+ ...existing,
+ // A batch run's person is the recipient, as in the template's default.
+ distinctId: existing.distinctId ?? { value: '{event.distinct_id}' },
+ channels: { value: push.channels },
+ title: { value: push.title, templating: pushTemplating(existing.title) },
+ body: { value: push.body, templating: pushTemplating(existing.body) },
+ data: existing.data ?? { value: {} },
+ }
+}
+
+export function hasMessageContent(
+ channel: BroadcastChannel,
+ email: BroadcastEmailValue,
+ push: BroadcastPushValue
+): boolean {
+ return channel === 'push'
+ ? !!(push.title || push.body)
+ : !!(email.subject || email.html || email.text || email.design)
+}
+
+function readChannel(broadcast: HogFlowApi): BroadcastChannel {
+ return getBroadcastChannel(broadcast.actions as any)
+}
+
function readEmailSettings(broadcast: HogFlowApi): BroadcastEmailSettings | null {
- const config = findAction(broadcast, 'function_email')?.config
+ const config =
+ findAction(broadcast, 'function_email')?.config ??
+ findAction(broadcast, BROADCAST_MESSAGE_ACTION_TYPES.push)?.config
if (!config) {
return null
}
@@ -234,6 +321,7 @@ export const DEFAULT_BROADCAST_CONVERSION: HogFlowConversionApi = {
// pinned: action node ids referenced by saved broadcasts — renaming breaks resume of existing drafts
const TRIGGER_ACTION_ID = 'trigger_node'
export const EMAIL_ACTION_ID = 'email_node'
+const PUSH_ACTION_ID = 'push_node'
const EXIT_ACTION_ID = 'exit_node'
function findAction(broadcast: HogFlowApi, type: string): Record<string, any> | undefined {
@@ -283,6 +371,10 @@ export interface broadcastWizardLogicValues {
broadcastLoading: boolean
canEditContent: boolean
canMoveToDraft: boolean
+ channel: BroadcastChannel
+ channelReach: BroadcastChannelReach | null
+ channelReachCounts: BroadcastChannelReachCounts | null
+ channelReachCountsLoading: boolean
conversion: HogFlowConversionApi
currentStep: BroadcastWizardStep
currentStepHasErrors: boolean
@@ -300,12 +392,15 @@ export interface broadcastWizardLogicValues {
goalEnabled: boolean
hasHydrated: boolean
hasLoadedBatchJobs: boolean
+ hasPushChannels: boolean
isReadOnly: boolean
launching: boolean
linkAudienceRejected: boolean
missingRecipientEmail: MissingRecipientEmailBannerProps | null
movingToDraft: boolean
name: string
+ push: BroadcastPushValue
+ pushUnavailableReason: "Couldn't check your push setup" | "Your project doesn't have push set up yet" | null
rateLimitedSendDuration: string
recipientEmailProperty: string | null
recipientsWithoutEmail: number | null
@@ -452,6 +547,29 @@ export interface broadcastWizardLogicActions {
broadcast: HogFlowApi | null
payload?: any
}
+ loadChannelReach: (_: any) => any
+ loadChannelReachFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadChannelReachSuccess: (
+ channelReachCounts: {
+ channel: BroadcastChannel
+ reachable: number
+ total: number
+ } | null,
+ payload?: any
+ ) => {
+ channelReachCounts: {
+ channel: BroadcastChannel
+ reachable: number
+ total: number
+ } | null
+ payload?: any
+ }
loadEmailBrand: () => any
loadEmailBrandFailure: (
error: string,
@@ -515,6 +633,9 @@ export interface broadcastWizardLogicActions {
reportReviewVisit: () => {
value: true
}
+ requestChannel: (channel: BroadcastChannel) => {
+ channel: BroadcastChannel
+ }
restoreBroadcast: () => {
value: true
}
@@ -538,6 +659,9 @@ export interface broadcastWizardLogicActions {
setAudienceProperties: (properties: AnyPropertyFilter[]) => {
properties: AnyPropertyFilter[]
}
+ setChannel: (channel: BroadcastChannel) => {
+ channel: BroadcastChannel
+ }
setConversion: (conversion: HogFlowConversionApi) => {
conversion: HogFlowConversionApi
}
@@ -559,6 +683,9 @@ export interface broadcastWizardLogicActions {
setName: (name: string) => {
name: string
}
+ setPush: (push: BroadcastPushValue) => {
+ push: BroadcastPushValue
+ }
setRecurringRepeating: (repeating: boolean) => {
repeating: boolean
}
@@ -609,6 +736,10 @@ export interface broadcastWizardLogicActions {
export interface broadcastWizardLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ channelReach: (
+ channelReachCounts: BroadcastChannelReachCounts | null,
+ blastRadius: BlastRadiusApi | null
+ ) => BroadcastChannelReach | null
aiEmailDraftStatus: (
aiEmailDraftLoading: boolean,
aiEmailDraftApplied: boolean,
@@ -622,7 +753,9 @@ export interface broadcastWizardLogicMeta {
conversion: HogFlowConversionApi,
email: BroadcastEmailValue,
emailRateLimit: HogFlowEmailSendingRateLimitApi | null,
- emailSettings: BroadcastEmailSettings
+ emailSettings: BroadcastEmailSettings,
+ channel: BroadcastChannel,
+ push: BroadcastPushValue
) => HogFlowApi | null
broadcastId: (broadcast: HogFlowApi | null, id: string) => string | null
expandedRunIds: (expandedRunOverride: string[] | null, batchJobs: HogFlowBatchJobApi[]) => string[]
@@ -639,7 +772,13 @@ export interface broadcastWizardLogicMeta {
) => BroadcastStatus
isReadOnly: (broadcast: HogFlowApi | null) => boolean
effectiveTimezone: (scheduleTimezone: string | null, currentTeam: TeamPublicType | TeamType | null) => string
- recipientEmailProperty: (email: BroadcastEmailValue) => string | null
+ recipientEmailProperty: (email: BroadcastEmailValue, channel: BroadcastChannel) => string | null
+ hasPushChannels: (integrations: IntegrationType[] | null) => boolean
+ pushUnavailableReason: (
+ hasPushChannels: boolean,
+ integrations: IntegrationType[] | null,
+ integrationsLoading: boolean
+ ) => "Couldn't check your push setup" | "Your project doesn't have push set up yet" | null
missingRecipientEmail: (
recipientEmailProperty: string | null,
recipientsWithoutEmail: number | null,
@@ -658,7 +797,9 @@ export interface broadcastWizardLogicMeta {
linkAudienceRejected: boolean,
audienceProperties: AnyPropertyFilter[],
audienceCohortLaunchErrors: AudienceCohortLaunchError[],
- blastRadius: BlastRadiusApi | null
+ blastRadius: BlastRadiusApi | null,
+ channel: BroadcastChannel,
+ push: BroadcastPushValue
) => Record<BroadcastWizardStep, string[]>
currentStepHasErrors: (
stepValidationErrors: Record<BroadcastWizardStep, string[]>,
@@ -675,7 +816,8 @@ export interface broadcastWizardLogicMeta {
) => string
rateLimitedSendDuration: (
emailRateLimit: HogFlowEmailSendingRateLimitApi | null,
- blastRadius: BlastRadiusApi | null
+ blastRadius: BlastRadiusApi | null,
+ channel: BroadcastChannel
) => string
breadcrumbs: (name: string) => Breadcrumb[]
}
@@ -730,6 +872,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
settings: Pick<BroadcastEmailSettings, 'utmTagsEnabled' | 'utmParams' | 'utmParamsFromDefault'>
) => ({ settings }),
setEmail: (email: BroadcastEmailValue) => ({ email }),
+ setChannel: (channel: BroadcastChannel) => ({ channel }),
+ requestChannel: (channel: BroadcastChannel) => ({ channel }),
+ setPush: (push: BroadcastPushValue) => ({ push }),
brandApplied: (content: Pick<BroadcastEmailValue, 'html' | 'design'>) => ({ content }),
applyAiEmailDraft: (draft: MessageDraft) => ({ draft }),
applyDefaultSender: true,
@@ -790,10 +935,57 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
if (!values.currentProjectId) {
return null
}
- return await hogFlowsUserBlastRadiusCreate(String(values.currentProjectId), {
- filters: { properties: values.audienceProperties },
- dedupe_key: 'email',
- })
+ return await hogFlowsUserBlastRadiusCreate(
+ String(values.currentProjectId),
+ audiencePreviewRequest(values.audienceProperties, values.channel)
+ )
+ },
+ },
+ ],
+ channelReachCounts: [
+ null as BroadcastChannelReachCounts | null,
+ {
+ loadChannelReach: async (_, breakpoint) => {
+ await breakpoint(500)
+ // Never for an unfiltered audience, where both counts would scan every person in the project.
+ if (
+ !values.currentProjectId ||
+ !values.featureFlags[FEATURE_FLAGS.BROADCASTS_PUSH_CHANNEL] ||
+ values.audienceProperties.length === 0
+ ) {
+ return null
+ }
+ const projectId = String(values.currentProjectId)
+ const reachableFilter: AnyPropertyFilter =
+ values.channel === 'push'
+ ? ({ type: PropertyFilterType.HogQL, key: PUSH_SUBSCRIBED_HOGQL } as AnyPropertyFilter)
+ : {
+ key: values.recipientEmailProperty ?? 'email',
+ type: PropertyFilterType.Person,
+ operator: PropertyOperator.IsSet,
+ }
+ const channel = values.channel
+ // The push audience size is the blast radius count already, so only email asks for its total.
+ const countRequests =
+ channel === 'push'
+ ? [[...values.audienceProperties, reachableFilter]]
+ : [[...values.audienceProperties, reachableFilter], values.audienceProperties]
+ try {
+ const [reachable, all] = await Promise.all(
+ countRequests.map((properties) =>
+ hogFlowsUserBlastRadiusCreate(projectId, {
+ filters: { properties },
+ sends_email: false,
+ })
+ )
+ )
+ breakpoint()
+ return { channel, reachable: reachable.affected, total: all?.affected ?? null }
+ } catch {
+ breakpoint()
+ // Only an estimate, so a failed count drops the line rather than blocking anything.
+ return null
+ }
},
},
],
@@ -1026,6 +1218,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
DEFAULT_BROADCAST_EMAIL,
{
setEmail: (_, { email }) => email,
+ setChannel: (state, { channel }) =>
+ channel === 'email' ? state : { ...DEFAULT_BROADCAST_EMAIL, from: state.from },
brandApplied: (state, { content }) => ({ ...state, ...content }),
prefillFromLink: (state, { prefill }) =>
prefill.email ? { ...state, ...messageDraftEmail(prefill.email) } : state,
@@ -1043,6 +1237,27 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
},
},
],
+ channel: [
+ 'email' as BroadcastChannel,
+ {
+ setChannel: (_, { channel }) => channel,
+ hydrateFromBroadcast: (_, { broadcast }) => readChannel(broadcast),
+ applyExternalEdit: (state, { broadcast, base }) =>
+ changedElsewhere(broadcast, base, readChannel) ? readChannel(broadcast) : state,
+ },
+ ],
+ push: [
+ DEFAULT_BROADCAST_PUSH,
+ {
+ setPush: (_, { push }) => push,
+ // Switching away drops the content, as the switch dialog says. The chosen apps stay.
+ setChannel: (state, { channel }) =>
+ channel === 'push' ? state : { ...DEFAULT_BROADCAST_PUSH, channels: state.channels },
+ hydrateFromBroadcast: (state, { broadcast }) => readPush(broadcast) ?? state,
+ applyExternalEdit: (state, { broadcast, base }) =>
+ changedElsewhere(broadcast, base, readPush) ? (readPush(broadcast) ?? state) : state,
+ },
+ ],
scheduleMode: [
'now' as BroadcastScheduleMode,
{
@@ -1146,6 +1361,16 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
})),
selectors({
+ channelReach: [
+ (s) => [s.channelReachCounts, s.blastRadius],
+ (
+ counts: BroadcastChannelReachCounts | null,
+ blastRadius: BlastRadiusApi | null
+ ): BroadcastChannelReach | null => {
+ const total = counts?.total ?? blastRadius?.affected
+ return counts && total != null ? { ...counts, total } : null
+ },
+ ],
aiEmailDraftStatus: [
(s) => [s.aiEmailDraftLoading, s.aiEmailDraftApplied, s.aiEmailDraft],
(loading: boolean, applied: boolean, result: AiEmailDraftResult | null): AiEmailDraftStatusProps | null => {
@@ -1170,6 +1395,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
s.email,
s.emailRateLimit,
s.emailSettings,
+ s.channel,
+ s.push,
],
(
broadcast: HogFlowApi | null,
@@ -1179,7 +1406,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
conversion: HogFlowConversionApi,
email: BroadcastEmailValue,
emailRateLimit: HogFlowEmailSendingRateLimitApi | null,
- emailSettings: BroadcastEmailSettings
+ emailSettings: BroadcastEmailSettings,
+ channel: BroadcastChannel,
+ push: BroadcastPushValue
): HogFlowApi | null =>
broadcast
? ({
@@ -1192,6 +1421,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
email,
emailRateLimit,
emailSettings,
+ channel,
+ push,
// A workflow shaped like a broadcast keeps its own step ids in the agent's view.
broadcast,
}),
@@ -1251,8 +1482,23 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
scheduleTimezone ?? currentTeam?.timezone ?? dayjs.tz.guess(),
],
recipientEmailProperty: [
- (s) => [s.email],
- (email: BroadcastEmailValue): string | null => recipientEmailProperty(email.to?.email),
+ (s) => [s.email, s.channel],
+ (email: BroadcastEmailValue, channel: BroadcastChannel): string | null =>
+ channel === 'email' ? recipientEmailProperty(email.to?.email) : null,
+ ],
+ hasPushChannels: [
+ (s) => [s.integrations],
+ (integrations: IntegrationType[] | null): boolean =>
+ !!integrations?.some((integration) => PUSH_INTEGRATION_KINDS.includes(integration.kind)),
+ ],
+ pushUnavailableReason: [
+ (s) => [s.hasPushChannels, s.integrations, s.integrationsLoading],
+ (hasPushChannels: boolean, integrations: IntegrationType[] | null, integrationsLoading: boolean) =>
+ hasPushChannels || integrationsLoading
+ ? null
+ : integrations === null
+ ? PUSH_CHANNELS_LOAD_FAILED_REASON
+ : NO_PUSH_CHANNELS_REASON,
],
missingRecipientEmail: [
(s) => [s.recipientEmailProperty, s.recipientsWithoutEmail, s.blastRadius],
@@ -1284,6 +1530,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
s.audienceProperties,
s.audienceCohortLaunchErrors,
s.blastRadius,
+ s.channel,
+ s.push,
],
(
goalEnabled: boolean,
@@ -1297,7 +1545,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
linkAudienceRejected: boolean,
audienceProperties: AnyPropertyFilter[],
audienceCohortLaunchErrors: AudienceCohortLaunchError[],
- blastRadius: BlastRadiusApi | null
+ blastRadius: BlastRadiusApi | null,
+ channel: BroadcastChannel,
+ push: BroadcastPushValue
): Record<BroadcastWizardStep, string[]> => {
const errors: Record<BroadcastWizardStep, string[]> = {
recipients: [],
@@ -1319,17 +1569,31 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}
}
- if (!email.from?.integrationId) {
- errors.content.push('Choose an email sender')
- } else if (integrations && getMissingSenderIds(email.from, integrations).length > 0) {
- // Shown on the content step, where the sender is picked, rather than first at launch.
- errors.content.push(DELETED_SENDER_ERROR)
- }
- if (!email.subject) {
- errors.content.push('Add a subject line')
- }
- if (!email.html && !email.text && !email.design) {
- errors.content.push('Add email content')
+ if (channel === 'push') {
+ if (push.channels.length === 0) {
+ errors.content.push('Choose a push channel')
+ } else if (
+ integrations &&
+ push.channels.some((id) => !integrations.some((integration) => integration.id === id))
+ ) {
+ errors.content.push(DELETED_PUSH_CHANNEL_ERROR)
+ }
+ if (!push.title.trim()) {
+ errors.content.push('Add a notification title')
+ }
+ } else {
+ if (!email.from?.integrationId) {
+ errors.content.push('Choose an email sender')
+ } else if (integrations && getMissingSenderIds(email.from, integrations).length > 0) {
+ // Shown on the content step, where the sender is picked, rather than first at launch.
+ errors.content.push(DELETED_SENDER_ERROR)
+ }
+ if (!email.subject) {
+ errors.content.push('Add a subject line')
+ }
+ if (!email.html && !email.text && !email.design) {
+ errors.content.push('Add email content')
+ }
}
if (scheduleMode === 'later') {
@@ -1344,7 +1608,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}
errors.review = [...errors.recipients, ...errors.goal, ...errors.content, ...errors.schedule]
- const senderError = getSenderLaunchError(email.from, integrations, integrationsLoading)
+ const senderError =
+ channel === 'email' ? getSenderLaunchError(email.from, integrations, integrationsLoading) : null
if (senderError && !errors.review.includes(senderError)) {
errors.review.push(senderError)
}
@@ -1401,10 +1666,14 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
},
],
rateLimitedSendDuration: [
- (s) => [s.emailRateLimit, s.blastRadius],
- (emailRateLimit: HogFlowEmailSendingRateLimitApi | null, blastRadius: BlastRadiusApi | null): string => {
+ (s) => [s.emailRateLimit, s.blastRadius, s.channel],
+ (
+ emailRateLimit: HogFlowEmailSendingRateLimitApi | null,
+ blastRadius: BlastRadiusApi | null,
+ channel: BroadcastChannel
+ ): string => {
const recipients = blastRadius?.affected
- if (!emailRateLimit || !recipients) {
+ if (!emailRateLimit || !recipients || channel !== 'email') {
return ''
}
// An estimate: the worker holds sends under the limit by rescheduling them, and it
@@ -1673,6 +1942,38 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
// Tracking and category live on the email step, so they share its autosave and pending flag.
actions.setEmail(values.email)
},
+ requestChannel: ({ channel }) => {
+ const current = values.channel
+ if (channel === current) {
+ return
+ }
+ if (!hasMessageContent(current, values.email, values.push)) {
+ actions.setChannel(channel)
+ return
+ }
+ LemonDialog.open({
+ title: `Switch to ${channel}?`,
+ description: `A broadcast sends on one channel, so the ${
+ current === 'email' ? 'email' : 'push notification'
+ } you wrote is removed from this broadcast.`,
+ primaryButton: {
+ children: 'Switch',
+ status: 'danger',
+ onClick: () => actions.setChannel(channel),
+ 'data-attr': 'broadcast-channel-switch-confirm',
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
+ setPush: () => {
+ // The push step saves through the same autosave as the email.
+ actions.setEmail(values.email)
+ },
+ setChannel: () => {
+ // The audience limit and its count depend on the channel.
+ actions.loadBlastRadius()
+ actions.setEmail(values.email)
+ },
setEmail: async (_, breakpoint) => {
// Keeps the saved draft in step with the editor, so an AI edit starts from what the user
// sees rather than from the last Continue.
@@ -1937,10 +2238,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.saveBroadcastFinished(saved)
// A fresh audience preview mints the confirm token the batch dispatch expects.
- const blastRadius = await hogFlowsUserBlastRadiusCreate(projectId, {
- filters: { properties: values.audienceProperties },
- dedupe_key: 'email',
- })
+ const blastRadius = await hogFlowsUserBlastRadiusCreate(
+ projectId,
+ audiencePreviewRequest(values.audienceProperties, values.channel)
+ )
// The resolver silently caps the batch at this limit, so dispatching an audience over
// it would confirm N recipients and deliver to the first slice. Stop at the step that
@@ -2244,6 +2545,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
listeners(({ actions, values, cache }) => ({
loadBlastRadius: () => {
actions.loadRecipientsWithoutEmail(null)
+ actions.loadChannelReach(null)
},
loadBlastRadiusSuccess: async ({ blastRadius }, breakpoint) => {
// The send button reads the realtime cohort's status from the audience size, and the cohort can
@@ -2255,10 +2557,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
await breakpoint(REALTIME_COHORT_STATUS_POLL_MS)
let refreshed: BlastRadiusApi | null = null
try {
- refreshed = await hogFlowsUserBlastRadiusCreate(String(values.currentProjectId), {
- filters: { properties: values.audienceProperties },
- dedupe_key: 'email',
- })
+ refreshed = await hogFlowsUserBlastRadiusCreate(
+ String(values.currentProjectId),
+ audiencePreviewRequest(values.audienceProperties, values.channel)
+ )
} catch {
// A failed check tries again on the next interval.
}
@@ -2486,6 +2788,17 @@ async function patchWithoutClobbering(
export const SENDERS_LOAD_FAILED_ERROR = "Couldn't load your email senders. Reload them to launch."
export const DELETED_SENDER_ERROR = 'The chosen sender was deleted. Choose another sender.'
+export const DELETED_PUSH_CHANNEL_ERROR = 'A chosen push channel was deleted. Choose another channel.'
+
+/** The email channel counts each address once and is held to the email sending limit. Push is not. */
+function audiencePreviewRequest(
+ audienceProperties: AnyPropertyFilter[],
+ channel: BroadcastChannel
+): BlastRadiusRequestApi {
+ return channel === 'push'
+ ? { filters: { properties: audienceProperties }, sends_email: false }
+ : { filters: { properties: audienceProperties }, dedupe_key: 'email', sends_email: true }
+}
/**
* Why the chosen sender can't send yet, if it can't. A draft can be written with any sender, but a
@@ -2530,8 +2843,71 @@ export function getMissingSenderIds(
)
}
+function messageAction(
+ channel: BroadcastChannel,
+ values: { email: BroadcastEmailValue; emailSettings?: BroadcastEmailSettings; push?: BroadcastPushValue },
+ existing?: Record<string, any>
+): Record<string, any> {
+ if (channel === 'push') {
+ const settings = values.emailSettings
+ const config = existing?.type === BROADCAST_MESSAGE_ACTION_TYPES.push ? existing.config : {}
+ return {
+ ...(existing?.type === BROADCAST_MESSAGE_ACTION_TYPES.push
+ ? existing
+ : {
+ created_at: 0,
+ updated_at: 0,
+ // Step-level settings such as conditions do not depend on the channel.
+ ...existing,
+ id: existing?.id ?? PUSH_ACTION_ID,
+ name: 'Send push',
+ description: 'The broadcast push notification.',
+ }),
+ type: BROADCAST_MESSAGE_ACTION_TYPES.push,
+ config: {
+ ...config,
+ template_id: 'template-native-push',
+ message_category_id: settings?.messageCategoryId ?? undefined,
+ message_category_type: settings?.messageCategoryType ?? undefined,
+ inputs: pushInputs(values.push ?? DEFAULT_BROADCAST_PUSH, config?.inputs),
+ },
+ }
+ }
+ if (existing?.type === 'function_email') {
+ return {
+ ...existing,
+ config: {
+ ...existing.config,
+ ...emailSettingsConfig(values.emailSettings),
+ inputs: {
+ ...existing.config?.inputs,
+ email: { ...existing.config?.inputs?.email, value: values.email },
+ },
+ },
+ }
+ }
+ return {
+ created_at: 0,
+ updated_at: 0,
+ ...existing,
+ id: existing?.id ?? EMAIL_ACTION_ID,
+ type: 'function_email',
+ name: 'Send email',
+ description: 'The broadcast email.',
+ config: {
+ template_id: 'template-email',
+ ...emailSettingsConfig(values.emailSettings),
+ inputs: {
+ email: { value: values.email },
+ },
+ },
+ }
+}
+
+const MESSAGE_ACTION_TYPES = Object.values(BROADCAST_MESSAGE_ACTION_TYPES)
+
// Serializes the wizard state into the HogFlow the broadcast is stored as: a batch trigger
-// (the audience), one email action, and an exit node.
+// (the audience), one email or push action, and an exit node.
export function buildBroadcastPayload(values: {
name: string
audienceProperties: AnyPropertyFilter[]
@@ -2540,21 +2916,27 @@ export function buildBroadcastPayload(values: {
email: BroadcastEmailValue
emailRateLimit: HogFlowEmailSendingRateLimitApi | null
emailSettings?: BroadcastEmailSettings
+ channel?: BroadcastChannel
+ push?: BroadcastPushValue
// Left out of the payload when undefined: the API clears tags on an empty list, so only a
// caller that carries the wizard's tags state may write them.
tags?: string[]
broadcast?: HogFlowApi | null
}): Record<string, any> {
const existing = values.broadcast
+ const channel = values.channel ?? 'email'
+ // The email sending limit means nothing to a push send.
+ const emailRateLimit = channel === 'email' ? values.emailRateLimit : null
if (existing) {
// A saved broadcast keeps its own steps: its ids, names and any setting the wizard does not manage
// survive, such as step conditions or a test-account exclusion on a workflow moved to broadcasts.
- // origin_product and the exit condition stay as they were.
+ // origin_product and the exit condition stay as they were. A channel switch replaces the message
+ // step under the same id, so the edges still hold.
return {
name: values.name,
...(values.tags !== undefined ? { tags: values.tags } : {}),
conversion: values.goalEnabled ? values.conversion : null,
- email_sending_rate_limit: values.emailRateLimit,
+ email_sending_rate_limit: emailRateLimit,
actions: (existing.actions as Record<string, any>[]).map((action) =>
action.type === 'trigger'
? {
@@ -2564,23 +2946,14 @@ export function buildBroadcastPayload(values: {
filters: { ...action.config?.filters, properties: values.audienceProperties },
},
}
- : action.type === 'function_email'
- ? {
- ...action,
- config: {
- ...action.config,
- ...emailSettingsConfig(values.emailSettings),
- inputs: {
- ...action.config?.inputs,
- email: { ...action.config?.inputs?.email, value: values.email },
- },
- },
- }
+ : MESSAGE_ACTION_TYPES.includes(action.type)
+ ? messageAction(channel, values, action)
: action
),
edges: existing.edges,
}
}
+ const message = messageAction(channel, values)
return {
origin_product: 'broadcasts',
status: 'draft',
@@ -2588,7 +2961,7 @@ export function buildBroadcastPayload(values: {
...(values.tags !== undefined ? { tags: values.tags } : {}),
exit_condition: 'exit_only_at_end',
conversion: values.goalEnabled ? values.conversion : null,
- email_sending_rate_limit: values.emailRateLimit,
+ email_sending_rate_limit: emailRateLimit,
actions: [
{
id: TRIGGER_ACTION_ID,
@@ -2602,21 +2975,7 @@ export function buildBroadcastPayload(values: {
filters: { properties: values.audienceProperties },
},
},
- {
- id: EMAIL_ACTION_ID,
- type: 'function_email',
- name: 'Send email',
- description: 'The broadcast email.',
- created_at: 0,
- updated_at: 0,
- config: {
- template_id: 'template-email',
- ...emailSettingsConfig(values.emailSettings),
- inputs: {
- email: { value: values.email },
- },
- },
- },
+ message,
{
id: EXIT_ACTION_ID,
type: 'exit',
@@ -2628,8 +2987,8 @@ export function buildBroadcastPayload(values: {
},
],
edges: [
- { from: TRIGGER_ACTION_ID, to: EMAIL_ACTION_ID, type: 'continue' },
- { from: EMAIL_ACTION_ID, to: EXIT_ACTION_ID, type: 'continue' },
+ { from: TRIGGER_ACTION_ID, to: message.id, type: 'continue' },
+ { from: message.id, to: EXIT_ACTION_ID, type: 'continue' },
],
}
}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
index 933af92a2721..f057bc6ff784 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
@@ -20,7 +20,14 @@ const email = (to = '{{ person.properties.email }}'): Record<string, any> => ({
on_error: 'continue',
config: { template_id: 'template-email', inputs: { email: { value: { to: { email: to } } }, extra: { value: 1 } } },
})
+const push = (): Record<string, any> => ({
+ id: 'email_1',
+ type: 'function_push',
+ name: 'Send push',
+ config: { template_id: 'template-native-push', inputs: { title: { value: 'Hi' } } },
+})
const exit = { id: 'exit_node', type: 'exit', name: 'Exit', config: {} }
+const stepCondition = { properties: [{ key: 'plan', value: ['pro'], operator: 'exact', type: 'person' }] }
const edges = [
{ from: 'trigger_node', to: 'email_1', type: 'continue' },
{ from: 'email_1', to: 'exit_node', type: 'continue' },
@@ -32,6 +39,8 @@ describe('broadcast edits to broadcast-shaped workflows', () => {
['an account audience', [trigger({ audience_type: 'accounts', properties: [] }), email(), exit], edges, false],
['a custom recipient expression', [trigger(), email('{{ inputs.owner_email }}'), exit], edges, true],
['a fixed recipient address', [trigger(), email('[email protected]'), exit], edges, true],
+ ['a push notification', [trigger(), push(), exit], edges, true],
+ ['an email and a push together', [trigger(), email(), push(), exit], edges, false],
[
'a trigger that skips the email',
[trigger(), email(), exit],
@@ -156,4 +165,90 @@ describe('broadcast edits to broadcast-shaped workflows', () => {
utm_params: { utm_campaign: '{{ person.properties.plan }}' },
})
})
+
+ it.each([
+ [
+ 'email to push',
+ [trigger(), { ...email(), filters: stepCondition }, exit],
+ 'push',
+ null,
+ {
+ type: 'function_push',
+ config: {
+ inputs: {
+ channels: { value: [7] },
+ title: { value: 'Hello {{ person.properties.name }}', templating: 'liquid' },
+ },
+ },
+ },
+ ],
+ [
+ 'push to email',
+ [trigger(), { ...push(), filters: stepCondition }, exit],
+ 'email',
+ { count: 10, period: 'minute' },
+ { type: 'function_email', config: { inputs: { email: { value: { subject: 'Hello' } } } } },
+ ],
+ ] as const)(
+ 'replaces the message step under the same id when switching %s',
+ (_, actions, channel, rateLimit, messageStep) => {
+ const payload = buildBroadcastPayload({
+ name: 'Launch',
+ audienceProperties: [],
+ goalEnabled: false,
+ conversion: DEFAULT_BROADCAST_CONVERSION,
+ email: { ...DEFAULT_BROADCAST_EMAIL, subject: 'Hello' },
+ emailRateLimit: { count: 10, period: 'minute' } as any,
+ channel,
+ push: { channels: [7], title: 'Hello {{ person.properties.name }}', body: '' },
+ broadcast: { actions, edges } as unknown as HogFlowApi,
+ })
+
+ expect(payload.edges).toEqual(edges)
+ expect(payload.actions.map((action: any) => action.id)).toEqual(['trigger_node', 'email_1', 'exit_node'])
+ expect(payload.actions[1]).toMatchObject({ ...messageStep, filters: stepCondition })
+ expect(payload.email_sending_rate_limit).toEqual(rateLimit)
+ }
+ )
+
+ it('keeps the push inputs the wizard does not edit, such as a custom recipient or saved data keys', () => {
+ const customized = {
+ ...push(),
+ config: {
+ template_id: 'template-native-push',
+ inputs: {
+ distinctId: { value: '{person.properties.device_owner}' },
+ title: { value: 'Old {person.properties.name}' },
+ data: {
+ value: { url: 'myapp://old', campaign: '{{ person.properties.plan }}' },
+ templating: 'liquid',
+ },
+ ios_sound: { value: 'chime' },
+ },
+ },
+ }
+ const payload = buildBroadcastPayload({
+ name: 'Launch',
+ audienceProperties: [],
+ goalEnabled: false,
+ conversion: DEFAULT_BROADCAST_CONVERSION,
+ email: DEFAULT_BROADCAST_EMAIL,
+ emailRateLimit: null,
+ channel: 'push',
+ push: { channels: [7], title: 'New', body: '' },
+ broadcast: { actions: [trigger(), customized, exit], edges } as unknown as HogFlowApi,
+ })
+
+ expect(payload.actions[1].config.inputs).toEqual({
+ distinctId: { value: '{person.properties.device_owner}' },
+ channels: { value: [7] },
+ title: { value: 'New', templating: 'hog' },
+ body: { value: '', templating: 'liquid' },
+ data: {
+ value: { url: 'myapp://old', campaign: '{{ person.properties.plan }}' },
+ templating: 'liquid',
+ },
+ ios_sound: { value: 'chime' },
+ })
+ })
})
diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
index 5629cf14e4e8..2504e34c3e92 100644
--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
@@ -89,29 +89,43 @@ export function isBroadcastShaped(actions: FlowStep[] | null | undefined): boole
type FlowEdge = { from?: string; to?: string }
+export type BroadcastChannel = 'email' | 'push'
+
+export const BROADCAST_MESSAGE_ACTION_TYPES: Record<BroadcastChannel, string> = {
+ email: 'function_email',
+ push: 'function_push',
+}
+
+const MESSAGE_TYPES = Object.values(BROADCAST_MESSAGE_ACTION_TYPES)
+
+/** The channel a broadcast sends on, read from its one message step. */
+export function getBroadcastChannel(actions: FlowStep[] | null | undefined): BroadcastChannel {
+ return (actions ?? []).some((step) => step.type === BROADCAST_MESSAGE_ACTION_TYPES.push) ? 'push' : 'email'
+}
+
/**
* Whether the broadcast wizard can edit a broadcast-shaped workflow without misdescribing it. The
- * wizard only models a person audience along trigger, email, exit. Its Content step edits the email's
- * "To" like any other field, so a custom recipient is fine;
- * anything else opens as the read-only summary instead.
+ * wizard only models a person audience along trigger, message, exit, where the message is one email
+ * or one push step. Its Content step edits the email's "To" like any other field, so a custom
+ * recipient is fine; anything else opens as the read-only summary instead.
*/
export function canEditInWizard(actions: FlowStep[] | null | undefined, edges: FlowEdge[] | null | undefined): boolean {
const steps = actions ?? []
- const [trigger, email, exit] = ['trigger', 'function_email', 'exit'].map((type) =>
- steps.filter((step) => step.type === type)
- )
+ const trigger = steps.filter((step) => step.type === 'trigger')
+ const message = steps.filter((step) => MESSAGE_TYPES.includes(step.type ?? ''))
+ const exit = steps.filter((step) => step.type === 'exit')
// One of each and nothing else, so the steps the wizard edits are the only ones there are.
- if (steps.length !== 3 || trigger.length !== 1 || email.length !== 1 || exit.length !== 1) {
+ if (steps.length !== 3 || trigger.length !== 1 || message.length !== 1 || exit.length !== 1) {
return false
}
- // Exactly trigger -> email -> exit: any other edge is a path the wizard cannot show, such as one
- // that skips the email.
+ // Exactly trigger -> message -> exit: any other edge is a path the wizard cannot show, such as one
+ // that skips the message.
const paths = new Set((edges ?? []).map((edge) => `${edge.from}->${edge.to}`))
return (
trigger[0].config?.filters?.audience_type !== 'accounts' &&
paths.size === 2 &&
- paths.has(`${trigger[0].id}->${email[0].id}`) &&
- paths.has(`${email[0].id}->${exit[0].id}`)
+ paths.has(`${trigger[0].id}->${message[0].id}`) &&
+ paths.has(`${message[0].id}->${exit[0].id}`)
)
}
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastChannelPicker.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastChannelPicker.tsx
new file mode 100644
index 000000000000..a44402a442bb
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastChannelPicker.tsx
@@ -0,0 +1,68 @@
+import { useActions, useValues } from 'kea'
+
+import { IconBell, IconCheckCircle, IconLetter } from '@posthog/icons'
+import { LemonButton, Link } from '@posthog/lemon-ui'
+
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { urls } from 'scenes/urls'
+
+import { BroadcastChannel } from '../broadcastsLogic'
+import {
+ NO_PUSH_CHANNELS_REASON,
+ PUSH_CHANNELS_LOAD_FAILED_REASON,
+ broadcastWizardLogic,
+} from '../broadcastWizardLogic'
+
+const CHANNELS: { channel: BroadcastChannel; label: string; description: string; icon: JSX.Element }[] = [
+ { channel: 'email', label: 'Email', description: "Lands in each person's inbox", icon: <IconLetter /> },
+ { channel: 'push', label: 'Push', description: "Shows on each person's phone", icon: <IconBell /> },
+]
+
+export function BroadcastChannelPicker(): JSX.Element {
+ const { channel, pushUnavailableReason } = useValues(broadcastWizardLogic)
+ const { requestChannel } = useActions(broadcastWizardLogic)
+ const { loadIntegrations } = useActions(integrationsLogic)
+
+ const pushUnavailable = channel !== 'push' ? pushUnavailableReason : null
+
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="font-semibold">Send as</span>
+ <div className="grid grid-cols-1 gap-2 @md:grid-cols-2">
+ {CHANNELS.map((option) => (
+ <LemonButton
+ key={option.channel}
+ type="secondary"
+ active={channel === option.channel}
+ icon={option.icon}
+ onClick={() => requestChannel(option.channel)}
+ disabledReason={option.channel === 'push' ? pushUnavailable : undefined}
+ sideIcon={channel === option.channel ? <IconCheckCircle className="text-success" /> : null}
+ fullWidth
+ data-attr={`broadcast-channel-${option.channel}`}
+ >
+ <div className="flex flex-col items-start py-1">
+ <span className="font-semibold">{option.label}</span>
+ <span className="text-xs font-normal text-secondary">{option.description}</span>
+ </div>
+ </LemonButton>
+ ))}
+ </div>
+ {pushUnavailable === PUSH_CHANNELS_LOAD_FAILED_REASON ? (
+ <span className="text-xs text-warning">
+ {PUSH_CHANNELS_LOAD_FAILED_REASON}.{' '}
+ <Link onClick={() => loadIntegrations()} data-attr="broadcast-channel-reload-push">
+ Try again
+ </Link>
+ </span>
+ ) : pushUnavailable ? (
+ <span className="text-xs text-secondary">
+ {NO_PUSH_CHANNELS_REASON}.{' '}
+ <Link to={urls.workflows('channels')} target="_blank" data-attr="broadcast-channel-set-up-push">
+ Set it up
+ </Link>
+ </span>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastChannelSwitch.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastChannelSwitch.tsx
new file mode 100644
index 000000000000..cab11ae9fe45
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastChannelSwitch.tsx
@@ -0,0 +1,32 @@
+import { useActions, useValues } from 'kea'
+
+import { IconBell, IconLetter } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import { broadcastWizardLogic } from '../broadcastWizardLogic'
+
+/** A late change of channel on the Content step. The channel is picked first, on the Recipients step. */
+export function BroadcastChannelSwitch(): JSX.Element | null {
+ const pushChannelEnabled = useFeatureFlag('BROADCASTS_PUSH_CHANNEL')
+ const { channel, pushUnavailableReason } = useValues(broadcastWizardLogic)
+ const { requestChannel } = useActions(broadcastWizardLogic)
+
+ if (!pushChannelEnabled) {
+ return null
+ }
+ const next = channel === 'push' ? 'email' : 'push'
+ return (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ icon={next === 'push' ? <IconBell /> : <IconLetter />}
+ onClick={() => requestChannel(next)}
+ disabledReason={next === 'push' ? pushUnavailableReason : undefined}
+ data-attr={`broadcast-channel-switch-${next}`}
+ >
+ {next === 'push' ? 'Send as push instead' : 'Send as email instead'}
+ </LemonButton>
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
index e86b968e06a2..788ea6637795 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
@@ -22,9 +22,11 @@ import {
getMissingSenderIds,
getSenderIds,
} from '../broadcastWizardLogic'
+import { BroadcastChannelSwitch } from './BroadcastChannelSwitch'
+import { BroadcastPushComposer } from './BroadcastPushComposer'
export function BroadcastContentStep(): JSX.Element {
- const { broadcast, email, name, stepValidationErrors, selectedSender, emailSettings, aiEmailDraftStatus } =
+ const { broadcast, email, name, stepValidationErrors, selectedSender, emailSettings, aiEmailDraftStatus, channel } =
useValues(broadcastWizardLogic)
const { setEmail, setEmailSettings } = useActions(broadcastWizardLogic)
const { integrations, integrationsLoading } = useValues(integrationsLogic)
@@ -73,6 +75,24 @@ export function BroadcastContentStep(): JSX.Element {
body: errors.find((error) => error.includes('content')),
}
+ // A push broadcast keeps its composer even with the flag off, so it can still be read and fixed.
+ if (channel === 'push') {
+ return (
+ <div className="flex flex-col gap-4 min-h-[36rem] @container">
+ <div className="flex items-start justify-between gap-2">
+ <div>
+ <h2 className="m-0 text-xl font-semibold">Write your push notification</h2>
+ <p className="m-0 text-secondary">
+ Pick the apps to send through, then add a title and message.
+ </p>
+ </div>
+ <BroadcastChannelSwitch />
+ </div>
+ <BroadcastPushComposer />
+ </div>
+ )
+ }
+
return (
<div className="flex flex-col gap-2 min-h-[36rem]">
<div className="flex items-start justify-between gap-2">
@@ -80,14 +100,17 @@ export function BroadcastContentStep(): JSX.Element {
<h2 className="m-0 text-xl font-semibold">Write your email</h2>
<p className="m-0 text-secondary">Pick a sender, add a subject, and design the email.</p>
</div>
- <LemonButton
- type="secondary"
- size="small"
- onClick={() => setTemplatePickerOpen(true)}
- data-attr="broadcast-wizard-template-picker"
- >
- Start from template
- </LemonButton>
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <BroadcastChannelSwitch />
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => setTemplatePickerOpen(true)}
+ data-attr="broadcast-wizard-template-picker"
+ >
+ Start from template
+ </LemonButton>
+ </div>
</div>
<TemplatePickerModal isOpen={templatePickerOpen} onClose={() => setTemplatePickerOpen(false)} />
{!integrationsLoading && integrations && !hasSenders ? (
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastGoalStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastGoalStep.tsx
index d88a1525ba14..b967b283a321 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastGoalStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastGoalStep.tsx
@@ -11,7 +11,7 @@ import { ConversionGoalEditor } from '../../Workflows/hogflows/steps/components/
import { DEFAULT_BROADCAST_CONVERSION, broadcastWizardLogic } from '../broadcastWizardLogic'
export function BroadcastGoalStep(): JSX.Element {
- const { goalEnabled, conversion, stepValidationErrors, tags } = useValues(broadcastWizardLogic)
+ const { goalEnabled, conversion, stepValidationErrors, tags, channel } = useValues(broadcastWizardLogic)
const { setGoalEnabled, setConversion, setTags } = useActions(broadcastWizardLogic)
const { tags: allTags } = useValues(tagsModel)
const { loadTagsIfNeeded } = useActions(tagsModel)
@@ -21,8 +21,8 @@ export function BroadcastGoalStep(): JSX.Element {
<div>
<h2 className="m-0 text-xl font-semibold">Do you want to measure a conversion goal?</h2>
<p className="m-0 text-secondary">
- A goal counts recipients who do something after receiving the email, like signing up or making a
- purchase.
+ A goal counts recipients who do something after receiving the{' '}
+ {channel === 'push' ? 'notification' : 'email'}, like signing up or making a purchase.
</p>
</div>
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastPushComposer.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastPushComposer.tsx
new file mode 100644
index 000000000000..94e5489bdb44
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastPushComposer.tsx
@@ -0,0 +1,73 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonInput, LemonLabel, LemonTextArea } from '@posthog/lemon-ui'
+
+import { CyclotronJobInputIntegrationMulti } from 'lib/components/CyclotronJob/integrations/CyclotronJobInputIntegrationMulti'
+
+import { CyclotronJobInputSchemaType } from '~/types'
+
+import { BroadcastPushPreview } from '../BroadcastPushPreview'
+import { PUSH_INTEGRATION_KINDS, broadcastWizardLogic } from '../broadcastWizardLogic'
+
+const CHANNELS_SCHEMA: CyclotronJobInputSchemaType = {
+ key: 'channels',
+ type: 'integration_multi',
+ integration: PUSH_INTEGRATION_KINDS.join(','),
+ label: 'Push channels',
+ required: true,
+}
+
+export function BroadcastPushComposer(): JSX.Element {
+ const { push, stepValidationErrors } = useValues(broadcastWizardLogic)
+ const { setPush } = useActions(broadcastWizardLogic)
+ const errors = stepValidationErrors.content
+ const channelsError = errors.find((error) => error.includes('channel'))
+ const titleError = errors.find((error) => error.includes('title'))
+
+ return (
+ <div className="grid grid-cols-1 gap-4 @3xl:grid-cols-2">
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1">
+ <LemonLabel info="Each person gets the notification on the devices they registered with these apps.">
+ Send through
+ </LemonLabel>
+ <CyclotronJobInputIntegrationMulti
+ schema={CHANNELS_SCHEMA}
+ value={push.channels}
+ onChange={(channels) => setPush({ ...push, channels })}
+ />
+ {channelsError ? <span className="text-xs text-danger">{channelsError}</span> : null}
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel htmlFor="broadcast-push-title">Title</LemonLabel>
+ <LemonInput
+ id="broadcast-push-title"
+ value={push.title}
+ onChange={(title) => setPush({ ...push, title })}
+ placeholder="Your order has shipped"
+ status={titleError ? 'danger' : undefined}
+ data-attr="broadcast-push-title"
+ />
+ {titleError ? <span className="text-xs text-danger">{titleError}</span> : null}
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel
+ htmlFor="broadcast-push-body"
+ info="Supports variables such as {{ person.properties.name }}."
+ >
+ Message
+ </LemonLabel>
+ <LemonTextArea
+ id="broadcast-push-body"
+ value={push.body}
+ onChange={(body) => setPush({ ...push, body })}
+ placeholder="Optional"
+ minRows={3}
+ data-attr="broadcast-push-body"
+ />
+ </div>
+ </div>
+ <BroadcastPushPreview />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
index 23a3a1a45ac9..2389d0feeba6 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx
@@ -23,9 +23,10 @@ import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'
import { broadcastAudienceListLogic } from '../audience/broadcastAudienceListLogic'
import { BroadcastAudienceListModal } from '../audience/BroadcastAudienceListModal'
import { broadcastWizardLogic } from '../broadcastWizardLogic'
+import { BroadcastChannelPicker } from './BroadcastChannelPicker'
function AudienceSizePreview(): JSX.Element | null {
- const { blastRadius, blastRadiusLoading } = useValues(broadcastWizardLogic)
+ const { blastRadius, blastRadiusLoading, channel, channelReach } = useValues(broadcastWizardLogic)
if (blastRadiusLoading) {
return <Spinner className="mt-1" />
@@ -48,11 +49,27 @@ function AudienceSizePreview(): JSX.Element | null {
<span className={exceeded ? 'text-danger font-semibold' : undefined}>
approximately {humanFriendlyNumber(affected)} of {humanFriendlyNumber(total)} people.
</span>
+ {channelReach?.channel === channel ? (
+ <div className="text-xs" data-attr="broadcast-audience-channel-reach">
+ {humanFriendlyNumber(channelReach.reachable)} of {humanFriendlyNumber(channelReach.total)}{' '}
+ {channelReach.total === 1 ? 'person' : 'people'}{' '}
+ {channel === 'push'
+ ? 'can receive push'
+ : `${channelReach.total === 1 ? 'has' : 'have'} an email address`}
+ .
+ </div>
+ ) : channel === 'push' ? (
+ <div className="text-xs" data-attr="broadcast-audience-push-reach">
+ Only people with push turned on in your app get the notification.
+ </div>
+ ) : null}
{exceeded && (
<div className="text-danger text-xs" data-attr="broadcast-audience-over-limit">
- This project can send a broadcast to up to {humanFriendlyNumber(limit)} people right now. The limit
- can rise as the project keeps sending with low bounce and spam complaint rates. Add filters to
- narrow the audience, or{' '}
+ This project can send a broadcast to up to {humanFriendlyNumber(limit)} people right now.
+ {channel === 'email'
+ ? ' The limit can rise as the project keeps sending with low bounce and spam complaint rates.'
+ : ''}{' '}
+ Add filters to narrow the audience, or{' '}
<Link
to={urls.workflows('reputation')}
target="_blank"
@@ -68,7 +85,7 @@ function AudienceSizePreview(): JSX.Element | null {
}
function MessageCategoryPicker(): JSX.Element {
- const { emailSettings } = useValues(broadcastWizardLogic)
+ const { emailSettings, channel } = useValues(broadcastWizardLogic)
const { setEmailSettings } = useActions(broadcastWizardLogic)
const { categories, categoriesLoading } = useValues(optOutCategoriesLogic())
const selected = categories.find((category) => category.id === emailSettings.messageCategoryId)
@@ -77,7 +94,8 @@ function MessageCategoryPicker(): JSX.Element {
<div className="flex flex-col gap-1 mt-4">
<span className="font-semibold">Message category</span>
<span className="text-secondary text-sm">
- People who unsubscribed from this category don't get the email.{' '}
+ People who unsubscribed from this category don't get the {channel === 'push' ? 'notification' : 'email'}
+ .{' '}
<Link to={urls.workflows('opt-outs')} target="_blank">
Manage categories
</Link>
@@ -146,7 +164,8 @@ function AudienceListModal({ isOpen, onClose }: { isOpen: boolean; onClose: () =
export function BroadcastRecipientsStep(): JSX.Element {
const cohortConditionsEnabled = useFeatureFlag('WORKFLOWS_COHORT_CONDITIONS')
- const { audienceProperties, linkAudienceRejected, blastRadius } = useValues(broadcastWizardLogic)
+ const pushChannelEnabled = useFeatureFlag('BROADCASTS_PUSH_CHANNEL')
+ const { audienceProperties, linkAudienceRejected, blastRadius, channel } = useValues(broadcastWizardLogic)
// A realtime cohort has to be the audience's only condition.
const realtimeCohortAlone = !!blastRadius?.realtime_cohort || !!blastRadius?.realtime_cohort_with_other_conditions
const { setAudienceProperties, sendToEveryoneAfterRejectedLink } = useActions(broadcastWizardLogic)
@@ -155,9 +174,12 @@ export function BroadcastRecipientsStep(): JSX.Element {
const [audienceListOpen, setAudienceListOpen] = useState(false)
return (
- <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-2 @container">
+ {pushChannelEnabled ? <BroadcastChannelPicker /> : null}
<div>
- <h2 className="m-0 text-xl font-semibold">Who should receive this email?</h2>
+ <h2 className="m-0 text-xl font-semibold">
+ Who should receive this {channel === 'push' ? 'notification' : 'email'}?
+ </h2>
<p className="m-0 text-secondary">
Filter by person properties or cohorts, or upload a list. Without filters, the broadcast goes to
everyone.
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
index 8d3577530cda..ca59e5dab3ce 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
@@ -16,6 +16,7 @@ import { isRealtimeCohortCalculating } from '../../Workflows/hogflows/steps/real
import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'
import { broadcastAudienceCohortsLogic } from '../audience/broadcastAudienceCohortsLogic'
import { BroadcastEmailPreview } from '../BroadcastEmailPreview'
+import { BroadcastPushPreview } from '../BroadcastPushPreview'
import { BroadcastWizardStep, SENDERS_LOAD_FAILED_ERROR, broadcastWizardLogic } from '../broadcastWizardLogic'
import { BroadcastReviewTestEmail } from './BroadcastReviewTestEmail'
@@ -80,6 +81,7 @@ export function BroadcastReviewStep(): JSX.Element {
aiEmailDraftStatus,
email,
launching,
+ channel,
} = useValues(broadcastWizardLogic)
const { categories } = useValues(optOutCategoriesLogic())
const category = categories.find((item) => item.id === emailSettings.messageCategoryId)
@@ -108,7 +110,9 @@ export function BroadcastReviewStep(): JSX.Element {
<div className="flex flex-col gap-4">
<div>
<h2 className="m-0 text-xl font-semibold">Review and confirm</h2>
- <p className="m-0 text-secondary">Check everything before sending. Emails can't be unsent.</p>
+ <p className="m-0 text-secondary">
+ Check everything before sending. {channel === 'push' ? 'Notifications' : 'Emails'} can't be unsent.
+ </p>
</div>
<BroadcastReviewTestEmail />
@@ -121,6 +125,7 @@ export function BroadcastReviewStep(): JSX.Element {
<span>
Approximately {humanFriendlyNumber(blastRadius.affected)} of{' '}
{humanFriendlyNumber(blastRadius.total)} people
+ {channel === 'push' ? '. Only people with push turned on in your app get it.' : ''}
</span>
) : (
<span className="text-warning">Couldn't estimate the audience size</span>
@@ -158,52 +163,60 @@ export function BroadcastReviewStep(): JSX.Element {
)}
</ReviewRow>
- <ReviewRow label="Email" step="content">
- {missingRecipientEmail ? <MissingRecipientEmailBanner {...missingRecipientEmail} /> : null}
- {!emailSettings.trackingEnabled && (
- <div className="text-xs text-secondary">Open and click tracking is off.</div>
- )}
- {emailSettings.utmTagsEnabled && <div className="text-xs text-secondary">Links get UTM tags.</div>}
- {aiEmailDraftStatus ? <AiEmailDraftStatus {...aiEmailDraftStatus} /> : null}
- <div className="@container">
- <div className="grid grid-cols-1 gap-2 @lg:grid-cols-2">
- <div className="flex flex-col gap-1">
- <LemonLabel htmlFor="broadcast-review-subject">Subject</LemonLabel>
- <LemonInput
- id="broadcast-review-subject"
- value={email.subject ?? ''}
- onChange={(subject) => setEmail({ ...email, subject })}
- placeholder="Add a subject"
- disabledReason={launching ? 'Sending the broadcast' : undefined}
- data-attr="broadcast-review-subject"
- />
- </div>
- <div className="flex flex-col gap-1">
- <LemonLabel
- htmlFor="broadcast-review-preheader"
- info="The preview text inboxes show next to the subject."
- >
- Preheader
- </LemonLabel>
- <LemonInput
- id="broadcast-review-preheader"
- value={email.preheader ?? ''}
- onChange={(preheader) => setEmail({ ...email, preheader })}
- placeholder="Optional"
- disabledReason={launching ? 'Sending the broadcast' : undefined}
- data-attr="broadcast-review-preheader"
- />
+ {channel === 'push' ? (
+ <ReviewRow label="Push notification" step="content">
+ <BroadcastPushPreview showTestButton={false} />
+ </ReviewRow>
+ ) : (
+ <ReviewRow label="Email" step="content">
+ {missingRecipientEmail ? <MissingRecipientEmailBanner {...missingRecipientEmail} /> : null}
+ {!emailSettings.trackingEnabled && (
+ <div className="text-xs text-secondary">Open and click tracking is off.</div>
+ )}
+ {emailSettings.utmTagsEnabled && (
+ <div className="text-xs text-secondary">Links get UTM tags.</div>
+ )}
+ {aiEmailDraftStatus ? <AiEmailDraftStatus {...aiEmailDraftStatus} /> : null}
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-2 @lg:grid-cols-2">
+ <div className="flex flex-col gap-1">
+ <LemonLabel htmlFor="broadcast-review-subject">Subject</LemonLabel>
+ <LemonInput
+ id="broadcast-review-subject"
+ value={email.subject ?? ''}
+ onChange={(subject) => setEmail({ ...email, subject })}
+ placeholder="Add a subject"
+ disabledReason={launching ? 'Sending the broadcast' : undefined}
+ data-attr="broadcast-review-subject"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel
+ htmlFor="broadcast-review-preheader"
+ info="The preview text inboxes show next to the subject."
+ >
+ Preheader
+ </LemonLabel>
+ <LemonInput
+ id="broadcast-review-preheader"
+ value={email.preheader ?? ''}
+ onChange={(preheader) => setEmail({ ...email, preheader })}
+ placeholder="Optional"
+ disabledReason={launching ? 'Sending the broadcast' : undefined}
+ data-attr="broadcast-review-preheader"
+ />
+ </div>
</div>
</div>
- </div>
- <BroadcastEmailPreview showTestButton={false} />
- </ReviewRow>
+ <BroadcastEmailPreview showTestButton={false} />
+ </ReviewRow>
+ )}
<ReviewRow label="Schedule" step="schedule">
{scheduleSummary}
</ReviewRow>
- {emailRateLimit && (
+ {emailRateLimit && channel === 'email' && (
<ReviewRow label="Sending rate" step="schedule" showErrors={false}>
At most {humanFriendlyNumber(emailRateLimit.count)} emails per {emailRateLimit.period}
{rateLimitedSendDuration ? `, so about ${rateLimitedSendDuration} to reach everyone` : ''}
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewTestEmail.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewTestEmail.tsx
index e132fa35c0f4..110d020b25e0 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewTestEmail.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewTestEmail.tsx
@@ -8,7 +8,8 @@ import { broadcastWizardLogic } from '../broadcastWizardLogic'
export function BroadcastReviewTestEmail(): JSX.Element {
const { props } = useMountedLogic(broadcastWizardLogic)
- const { lastTestSentTo } = useValues(broadcastTestSendLogic(props))
+ const { lastTestSentTo, channel } = useValues(broadcastTestSendLogic(props))
+ const isPush = channel === 'push'
const { setModalOpen } = useActions(broadcastTestSendLogic(props))
return (
@@ -20,12 +21,18 @@ export function BroadcastReviewTestEmail(): JSX.Element {
{lastTestSentTo ? <IconCheckCircle className="mt-0.5 shrink-0 text-success text-lg" /> : null}
<div className="flex min-w-0 flex-col">
<span className="font-semibold">
- {lastTestSentTo ? `Test sent to ${lastTestSentTo}` : 'Send yourself a test first'}
+ {lastTestSentTo
+ ? `Test sent to ${lastTestSentTo}${isPush ? "'s devices" : ''}`
+ : 'Send yourself a test first'}
</span>
<span className="text-secondary text-xs">
- {lastTestSentTo
- ? 'Check it in your inbox, on desktop and mobile, before you send.'
- : 'Read the email in a real inbox and click its links before it reaches your audience.'}
+ {isPush
+ ? lastTestSentTo
+ ? 'Check it on your phone and tap it before you send.'
+ : 'See the notification on a real phone before it reaches your audience.'
+ : lastTestSentTo
+ ? 'Check it in your inbox, on desktop and mobile, before you send.'
+ : 'Read the email in a real inbox and click its links before it reaches your audience.'}
</span>
</div>
</div>
@@ -35,7 +42,7 @@ export function BroadcastReviewTestEmail(): JSX.Element {
onClick={() => setModalOpen(true)}
data-attr="broadcast-review-send-test"
>
- {lastTestSentTo ? 'Send another test' : 'Send test email'}
+ {lastTestSentTo ? 'Send another test' : isPush ? 'Send test notification' : 'Send test email'}
</LemonButton>
</div>
)
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx
index 6063d854ab48..7e039c490233 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx
@@ -13,10 +13,13 @@ import { EmailSendingRateLimitPicker } from '../../Workflows/hogflows/steps/comp
import { RecurringSchedulePicker } from '../../Workflows/hogflows/steps/components/RecurringSchedulePicker'
import { broadcastWizardLogic } from '../broadcastWizardLogic'
-function SendingRateLimit(): JSX.Element {
- const { emailRateLimit } = useValues(broadcastWizardLogic)
+function SendingRateLimit(): JSX.Element | null {
+ const { emailRateLimit, channel } = useValues(broadcastWizardLogic)
const { setEmailRateLimit } = useActions(broadcastWizardLogic)
+ if (channel !== 'email') {
+ return null
+ }
return (
<div className="max-w-160">
<EmailSendingRateLimitPicker value={emailRateLimit} onChange={setEmailRateLimit} />
@@ -55,6 +58,7 @@ export function BroadcastScheduleStep(): JSX.Element {
recurringRepeating,
effectiveTimezone,
stepValidationErrors,
+ channel,
} = useValues(broadcastWizardLogic)
const {
setScheduleMode,
@@ -68,7 +72,9 @@ export function BroadcastScheduleStep(): JSX.Element {
return (
<div className="flex flex-col gap-4">
<div>
- <h2 className="m-0 text-xl font-semibold">When should this email go out?</h2>
+ <h2 className="m-0 text-xl font-semibold">
+ When should this {channel === 'push' ? 'notification' : 'email'} go out?
+ </h2>
<p className="m-0 text-secondary">Send it right away, pick a time, or set up a repeating schedule.</p>
</div>