:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { useEffect } from 'react'
import { IconChevronDown, IconLetter } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonDialog, LemonDivider, LemonInput } from '@posthog/lemon-ui'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
import { TZLabel } from 'lib/components/TZLabel'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import type { HogFlowBatchJobApi, HogFlowConversionApi } from 'products/workflows/frontend/generated/api.schemas'
import { EmailViewerModal } from '../Workflows/EmailViewerModal'
import type { MessageAsset } from '../Workflows/messageAssetsApi'
import { BroadcastAudienceCohorts } from './audience/BroadcastAudienceCohorts'
import { broadcastAudienceCohortsLogic } from './audience/broadcastAudienceCohortsLogic'
import { BroadcastEmailPreview } from './BroadcastEmailPreview'
import { archiveDisabledReason, manageDisabledReason } from './broadcastLifecycle'
import { BroadcastPerformance } from './BroadcastPerformance'
import { broadcastPerformanceLogic } from './broadcastPerformanceLogic'
import { BroadcastPushPerformance } from './BroadcastPushPerformance'
import { BroadcastPushPreview } from './BroadcastPushPreview'
import { BroadcastSceneHeader } from './BroadcastSceneHeader'
import type { BroadcastSendErrorAction } from './BroadcastSendErrorBanner'
import { broadcastSentLogic } from './broadcastSentLogic'
import { type BroadcastChannel, type BroadcastRunStatus, getRunStatus } from './broadcastsLogic'
import { BroadcastStatusTag } from './BroadcastStatusTag'
import { broadcastPath } from './broadcastUsage'
import { broadcastWizardLogic } from './broadcastWizardLogic'
import { ComposerDraftFeedback } from './ComposerDraftFeedback'
import { QuillBroadcastActionsMenu } from './QuillBroadcastActionsMenu'
/**
* The recipients of one run. Each run binds its own broadcastSentLogic (keyed on the run id), so
* expanding a second run loads that run's sends instead of replacing the first one's.
*/
function RunRecipients({
workflowId,
runId,
runCreatedAt,
runFinished,
channel,
}: {
workflowId: string
runId: string
runCreatedAt: string
runFinished: boolean
channel: BroadcastChannel
}): JSX.Element {
const { sendCounts } = useValues(broadcastPerformanceLogic({ runId, runStartedAt: runCreatedAt, channel }))
return (
<div className="bg-surface-secondary border-t px-4 py-3 w-0 min-w-full flex flex-col gap-3">
<BindLogic logic={broadcastSentLogic} props={{ id: workflowId || 'new', parentRunId: runId, runCreatedAt }}>
<RunRecipientsTable workflowId={workflowId} runFinished={runFinished} sent={sendCounts?.sent ?? null} />
</BindLogic>
</div>
)
}
function RunRecipientsTable({
workflowId,
runFinished,
sent,
}: {
workflowId: string
runFinished: boolean
sent: number | null
}): JSX.Element {
const {
sends,
sendsLoading,
sendsFailed,
selectedSend,
recipientCount,
recipientSearch,
hasMoreRecipients,
runPastRetention,
} = useValues(broadcastSentLogic)
const { loadSends, loadMoreSends, selectInvocation, setRecipientSearch } = useActions(broadcastSentLogic)
useEffect(() => {
loadSends()
}, [loadSends])
const noSendsMessage = runPastRetention
? "Recipient details are kept for 30 days after sending, so this run's list is no longer available."
: !runFinished
? 'No sends recorded for this run yet.'
: sent === 0
? "This run didn't send to anyone."
: "Recipient details aren't available for this run."
const columns: LemonTableColumns<MessageAsset> = [
{
title: 'Sent',
key: 'sent_at',
render: (_, row) => <TZLabel time={row.sent_at} />,
},
{
title: 'Subject',
key: 'subject',
render: (_, row) => <span className="wrap-anywhere">{row.subject || '-'}</span>,
},
{
title: 'Recipient',
key: 'recipient',
// An address has no break points, so without break-all its full length would widen the
// table past the panel and push the View email button out of sight.
render: (_, row) => <span className="font-mono text-xs break-all">{row.recipient}</span>,
},
{
title: '',
key: 'actions',
width: 0,
render: (_, row) => (
<div className="flex justify-end whitespace-nowrap">
<LemonButton
size="xsmall"
type="secondary"
icon={<IconLetter />}
onClick={() => selectInvocation(row.invocation_id)}
data-attr="broadcast-view-recipient-email"
>
View email
</LemonButton>
</div>
),
},
]
if (!sendsLoading && recipientCount === 0 && !recipientSearch) {
return (
<span className="text-sm text-muted">
{sendsFailed ? "Couldn't load recipients. Refresh the page to try again." : noSendsMessage}
</span>
)
}
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-semibold whitespace-nowrap">
{sendsFailed
? "Couldn't load recipients"
: sendsLoading && recipientCount === 0
? 'Loading recipients'
: `${humanFriendlyNumber(recipientCount)}${hasMoreRecipients ? '+' : ''} ${
recipientCount === 1 ? 'recipient' : 'recipients'
}${recipientSearch ? ' matching' : ''}`}
</span>
<LemonDivider vertical />
<LemonInput
size="small"
type="search"
placeholder="Search by email or subject"
value={recipientSearch}
onChange={setRecipientSearch}
className="w-full min-w-40 max-w-64 flex-1"
data-attr="broadcast-sent-search"
/>
</div>
{/* Each day of sends expires separately. A run that sent over several days still lists its later
days after its first day expires, so a non-empty list can be incomplete. */}
{runPastRetention && !sendsFailed ? (
<span className="text-xs text-muted">
Recipient details are kept for 30 days after sending, so this list may not include everyone this run
reached.
</span>
) : null}
<LemonTable
// The loader keeps the previous rows on failure, and they no longer match the search.
dataSource={sendsFailed ? [] : sends}
loading={sendsLoading}
rowKey="invocation_id"
columns={columns}
nouns={['recipient', 'recipients']}
emptyState={
sendsFailed
? "Couldn't load recipients. Change the search to try again, or refresh the page."
: recipientSearch
? 'No recipients match. Clear the search to see everyone.'
: noSendsMessage
}
/>
{hasMoreRecipients && !sendsFailed ? (
<div className="flex justify-center">
<LemonButton
type="secondary"
size="small"
loading={sendsLoading}
onClick={loadMoreSends}
data-attr="broadcast-sent-load-more"
>
Load more recipients
</LemonButton>
</div>
) : null}
{selectedSend ? (
<EmailViewerModal
workflowId={workflowId}
invocationId={selectedSend.invocation_id}
actionId={selectedSend.action_id}
isOpen
onClose={() => selectInvocation(null)}
title={`Email sent to ${selectedSend.recipient}`}
description={selectedSend.subject}
/>
) : null}
</div>
)
}
function RunsTable({
workflowId,
batchJobs,
batchJobsLoading,
columns,
channel,
}: {
workflowId: string
batchJobs: HogFlowBatchJobApi[]
batchJobsLoading: boolean
columns: LemonTableColumns<HogFlowBatchJobApi>
channel: BroadcastChannel
}): JSX.Element {
const { expandedRunIds } = useValues(broadcastWizardLogic)
const { expandRun, collapseRun } = useActions(broadcastWizardLogic)
return (
<LemonTable
dataSource={batchJobs}
loading={batchJobsLoading}
rowKey="id"
columns={columns}
nouns={['run', 'runs']}
expandable={{
expandedRowRender: (job) => (
<RunRecipients
workflowId={workflowId}
runId={job.id}
runCreatedAt={job.created_at}
runFinished={getRunStatus(job.status) !== 'sending'}
channel={channel}
/>
),
rowExpandable: (job) => !!job.id,
// A table inside a table runs out of room first. Dropping the indent cell gives the
// recipients back the width the toggle column would otherwise take.
noIndent: true,
isRowExpanded: (job) => (expandedRunIds.includes(job.id) ? 1 : 0),
onRowExpand: (job) => expandRun(job.id),
onRowCollapse: (job) => collapseRun(job.id),
}}
emptyState="No runs yet. Scheduled broadcasts appear here after they send."
/>
)
}
const LATEST_RUN_LABEL: Record<BroadcastRunStatus, string> = {
sent: 'Sent',
partially_failed: 'Partly sent',
sending: 'Sending, started',
failed: 'Last send failed, started',
cancelled: 'Last send was cancelled, started',
}
function LatestRunLabel({ job }: { job: HogFlowBatchJobApi }): JSX.Element {
return (
<span>
<span>{LATEST_RUN_LABEL[getRunStatus(job.status)]}</span> <TZLabel time={job.created_at} />
</span>
)
}
export function BroadcastSummary(): JSX.Element {
const {
broadcast,
broadcastId,
audienceProperties,
email,
scheduleSummary,
batchJobs,
batchJobsLoading,
hasLoadedBatchJobs,
canMoveToDraft,
movingToDraft,
canEditContent,
duplicating,
summaryStatus,
summaryTab,
goalEnabled,
conversion,
channel,
push,
} = useValues(broadcastWizardLogic)
const { moveToDraft, duplicateBroadcast, setSummaryTab, archiveBroadcast, restoreBroadcast, deleteBroadcast } =
useActions(broadcastWizardLogic)
const { props } = useMountedLogic(broadcastWizardLogic)
const { nonCohortAudience } = useValues(broadcastAudienceCohortsLogic(props))
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
const pendingSchedule = broadcast?.schedules?.find((schedule) => schedule.status === 'active')
const confirmMoveToDraft = (): void => {
LemonDialog.open({
title: pendingSchedule ? 'Stop this broadcast and edit it?' : 'Move this broadcast to draft?',
description: pendingSchedule
? 'The scheduled send stops and the broadcast goes back to draft. Nothing sends until you launch it again.'
: 'The broadcast goes back to draft, so you can check it and launch it again.',
primaryButton: {
children: 'Stop and edit',
onClick: moveToDraft,
'data-attr': 'broadcast-move-to-draft-confirm',
},
secondaryButton: { children: 'Cancel' },
})
}
// A sent broadcast can't change, so a fix goes into a copy. A broadcast with sends still scheduled is edited in place.
const fixAction: BroadcastSendErrorAction | undefined = canMoveToDraft
? { label: 'Stop and edit', onClick: confirmMoveToDraft }
: canEditContent
? { label: 'Fix and send again', onClick: duplicateBroadcast }
: undefined
const resendAction: BroadcastSendErrorAction | undefined = canEditContent
? { label: 'Send again', onClick: duplicateBroadcast }
: undefined
const latestBatchJob = batchJobs[0]
const latestBatchJobId = latestBatchJob?.id
const batchJobColumns: LemonTableColumns<HogFlowBatchJobApi> = [
{
title: 'Started',
key: 'created_at',
render: (_, job) => <TZLabel time={job.created_at} />,
},
{
title: 'Status',
key: 'status',
render: (_, job) => <BroadcastStatusTag status={getRunStatus(job.status)} />,
},
{
title: 'Started by',
key: 'created_by',
render: (_, job) => <span>{job.created_by?.first_name || job.created_by?.email || 'Schedule'}</span>,
},
]
const isArchived = broadcast?.status === 'archived'
const accessReason = manageDisabledReason(broadcast?.user_access_level)
const actionItems = [
canMoveToDraft
? { label: 'Stop and edit', onClick: confirmMoveToDraft, 'data-attr': 'broadcast-move-to-draft' }
: null,
canEditContent
? {
label: 'Send again as a new broadcast',
onClick: duplicateBroadcast,
'data-attr': 'broadcast-send-again',
}
: null,
isArchived
? {
label: 'Restore as draft',
onClick: restoreBroadcast,
disabledReason: accessReason,
'data-attr': 'broadcast-restore',
}
: {
label: 'Archive',
status: 'danger' as const,
onClick: archiveBroadcast,
disabledReason:
accessReason ??
archiveDisabledReason(hasLoadedBatchJobs ? batchJobs.map((job) => job.status) : null),
'data-attr': 'broadcast-archive',
},
isArchived
? {
label: 'Delete',
status: 'danger' as const,
onClick: deleteBroadcast,
disabledReason: accessReason,
'data-attr': 'broadcast-delete',
}
: null,
]
const actionsMenu = todayRailNav ? (
<QuillBroadcastActionsMenu
items={actionItems.flatMap((item) =>
item
? [
{
label: item.label,
onClick: item.onClick,
disabledReason: 'disabledReason' in item ? item.disabledReason : undefined,
danger: 'status' in item && item.status === 'danger',
'data-attr': item['data-attr'],
},
]
: []
)}
loading={movingToDraft || duplicating}
/>
) : (
<LemonMenu items={actionItems}>
<LemonButton
type="secondary"
size="small"
sideIcon={<IconChevronDown />}
loading={movingToDraft || duplicating}
data-attr="broadcast-actions"
>
Actions
</LemonButton>
</LemonMenu>
)
return (
<SceneContent className="@container min-h-full w-full shrink-0" data-attr="broadcast-summary">
<BroadcastSceneHeader nameSuffix={<BroadcastStatusTag status={summaryStatus} />} actions={actionsMenu} />
<div className="mx-auto w-full max-w-6xl space-y-4">
{broadcastPath(broadcastId) === 'composer' ? <ComposerDraftFeedback /> : null}
{broadcast?.status === 'draft' ? (
<LemonBanner
type="info"
action={{
children: 'Open in workflow editor',
to: urls.workflow(broadcastId ?? '', 'workflow'),
'data-attr': 'broadcast-draft-open-in-workflow-editor',
}}
>
This draft has steps or an audience the broadcast editor can't show, so it opens here read-only.
Edit it in the workflow editor.
</LemonBanner>
) : null}
{summaryStatus === 'failed' && !latestBatchJob && !batchJobsLoading ? (
<LemonBanner
type="warning"
action={
canMoveToDraft
? {
children: 'Move to draft',
onClick: confirmMoveToDraft,
'data-attr': 'broadcast-unfinished-launch-to-draft',
}
: undefined
}
>
This broadcast didn't send, and nothing is scheduled.
{canMoveToDraft ? ' Move it back to draft to launch it again.' : null}
</LemonBanner>
) : null}
<LemonTabs
activeKey={summaryTab}
onChange={setSummaryTab}
tabs={[
{
key: 'overview',
'data-attr': 'broadcast-summary-tab-overview',
label: 'Overview',
content: (
<div className="flex flex-col gap-4">
<div
className={cn(
'grid grid-cols-1 gap-4 rounded-lg border border-border bg-surface-primary p-4',
goalEnabled ? '@2xl:grid-cols-4' : '@2xl:grid-cols-3'
)}
>
<SummaryRow label="Audience">
{audienceProperties.length > 0 ? (
<div className="flex flex-col gap-2">
{nonCohortAudience.length > 0 ? (
<PropertyFiltersDisplay filters={nonCohortAudience} />
) : null}
<BroadcastAudienceCohorts />
</div>
) : (
<span className="text-muted">Everyone</span>
)}
</SummaryRow>
<SummaryRow label="Schedule">
{pendingSchedule ? (
<div className="flex flex-col gap-0.5">
<span>{scheduleSummary}</span>
{pendingSchedule.next_run_at ? (
<span className="text-xs text-muted">
Next send <TZLabel time={pendingSchedule.next_run_at} />
</span>
) : null}
</div>
) : latestBatchJob ? (
<LatestRunLabel job={latestBatchJob} />
) : (
<span>{scheduleSummary}</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 && channel === 'push' ? (
<BroadcastPushPerformance
runId={latestBatchJob.id}
runStartedAt={latestBatchJob.created_at}
hasGoal={goalEnabled}
channel={channel}
fixAction={fixAction}
resendAction={resendAction}
content={`${push.title}\n${push.body}`}
/>
) : latestBatchJob ? (
<BroadcastPerformance
runId={latestBatchJob.id}
runStartedAt={latestBatchJob.created_at}
hasGoal={goalEnabled}
channel={channel}
fixAction={fixAction}
resendAction={resendAction}
content={`${email.subject}\n${email.preheader ?? ''}\n${email.html}`}
/>
) : (
<span className="text-muted">
Numbers show up here once the first send goes out.
</span>
)}
</div>
</div>
),
},
{
key: 'content',
'data-attr': 'broadcast-summary-tab-content',
label: 'Content',
content:
channel === 'push' ? (
<BroadcastPushPreview />
) : (
<BroadcastEmailPreview intro="Preview the email for anyone in the audience, or send yourself a test." />
),
},
{
key: 'runs',
'data-attr': 'broadcast-summary-tab-runs',
label: 'Runs',
content: (
<RunsTable
workflowId={broadcastId ?? ''}
batchJobs={batchJobs}
batchJobsLoading={batchJobsLoading}
columns={batchJobColumns}
channel={channel}
/>
),
},
]}
/>
</div>
</SceneContent>
)
}
const WINDOW_UNITS: Record<string, string> = { m: 'minute', h: 'hour', d: 'day', w: 'week' }
function goalSummary(conversion: HogFlowConversionApi): string {
const events = (conversion.events?.[0]?.filters?.events ?? []).map(
(event: { name?: string; id?: string }) => event.name || String(event.id)
)
const target = events.length > 0 ? events.join(' or ') : 'Matches the goal filters'
const match = /^(\d+)([mhdw])$/.exec(conversion.window ?? '')
if (!match) {
return target
}
const amount = Number(match[1])
const unit = WINDOW_UNITS[match[2]]
return `${target} within ${amount} ${unit}${amount === 1 ? '' : 's'}`
}
function SummaryRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {
return (
<div className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wide text-muted">{label}</span>
{children}
</div>
)
}