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.

fix(workflows): show why a broadcast's sends errored and how to fix it (#127227)

Harley Alexander63ac25e760da
diff --git a/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx b/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx
index 916ae3db282f..9628bcd20f28 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastPerformance.tsx
@@ -4,12 +4,14 @@ import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { cn } from 'lib/utils/css-classes'
import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { EmailMetricsIncidentBanner } from '../EmailMetricsIncidentBanner'
import { EmailLinksTable } from '../Workflows/EmailLinksTable'
import { BroadcastPerformanceLogicProps, broadcastPerformanceLogic } from './broadcastPerformanceLogic'
import { BroadcastSendActivity } from './BroadcastSendActivity'
+import { BroadcastSendErrorAction, BroadcastSendErrorBanner } from './BroadcastSendErrorBanner'
function share(part: number, whole: number): string {
return whole > 0 ? percentage(part / whole, 1) : '-'
@@ -17,12 +19,22 @@ function share(part: number, whole: number): string {
export function BroadcastPerformance({
hasGoal = false,
+ fixAction,
+ resendAction,
+ content,
...props
-}: BroadcastPerformanceLogicProps & { hasGoal?: boolean }): JSX.Element {
+}: BroadcastPerformanceLogicProps & {
+ hasGoal?: boolean
+ fixAction?: BroadcastSendErrorAction
+ resendAction?: BroadcastSendErrorAction
+ content?: string
+}): JSX.Element {
const logic = broadcastPerformanceLogic(props)
- const { stats, trackingOff, totalsLoading, totalsFailed, links, linksLoading } = useValues(logic)
+ const { stats, sendCounts, trackingOff, totalsLoading, totalsFailed, links, linksLoading } = useValues(logic)
const { loadTotals } = useActions(logic)
+ const showLinks = !!stats && stats.sent > 0 && !trackingOff
+
if (totalsFailed && !totalsLoading) {
return (
<LemonBanner
@@ -37,8 +49,10 @@ export function BroadcastPerformance({
return <LemonSkeleton className="h-40" active={totalsLoading} />
}
+ const notSent = sendCounts?.notSent ?? 0
const headline = [
{ label: 'Sent', value: humanFriendlyNumber(stats.sent), detail: null },
+ ...(notSent > 0 ? [{ label: 'Not sent', value: humanFriendlyNumber(notSent), detail: null }] : []),
{ label: 'Delivered', value: share(stats.delivered, stats.sent), detail: stats.delivered },
{ label: 'Bounced', value: share(stats.bounced, stats.sent), detail: stats.bounced },
{ label: 'Marked as spam', value: share(stats.markedAsSpam, stats.sent), detail: stats.markedAsSpam },
@@ -65,7 +79,13 @@ export function BroadcastPerformance({
return (
<div className="flex flex-col gap-4 rounded-lg border border-border bg-surface-primary p-4">
<EmailMetricsIncidentBanner dateFrom={dayjs(props.runStartedAt)} />
- <div className="grid grid-cols-2 gap-4 @xl:grid-cols-3 @4xl:grid-cols-6">
+ <BroadcastSendErrorBanner {...props} fixAction={fixAction} resendAction={resendAction} content={content} />
+ <div
+ className={cn(
+ 'grid grid-cols-2 gap-4',
+ notSent > 0 ? '@xl:grid-cols-4 @4xl:grid-cols-7' : '@xl:grid-cols-3 @4xl:grid-cols-6'
+ )}
+ >
{headline.map(({ label, value, detail }) => (
<div key={label} className="flex flex-col">
<span className="text-xl font-semibold">{value}</span>
@@ -76,7 +96,7 @@ export function BroadcastPerformance({
))}
</div>
- {trackingOff ? (
+ {stats.sent > 0 && trackingOff ? (
<LemonBanner type="info">
Open and click tracking was off for this send, so opens and clicks weren't recorded. Before the next
send, check the tracking setting on the email and the email tracking consent setting in your
@@ -84,29 +104,32 @@ export function BroadcastPerformance({
</LemonBanner>
) : null}
- <div className="flex flex-col gap-3">
- {engagement.map(({ label, part, whole }) => (
- <div key={label} className="grid grid-cols-[9rem_minmax(0,1fr)] items-center gap-3">
- <div className="flex flex-col text-right">
- <span className="font-semibold">{share(part, whole)}</span>
- <span className="text-xs text-muted">
- {humanFriendlyNumber(part)} {label.toLowerCase()}
- </span>
+ {/* With nothing sent there is nothing to engage with, so empty bars and charts would only add noise. */}
+ {stats.sent > 0 ? (
+ <div className="flex flex-col gap-3">
+ {engagement.map(({ label, part, whole }) => (
+ <div key={label} className="grid grid-cols-[9rem_minmax(0,1fr)] items-center gap-3">
+ <div className="flex flex-col text-right">
+ <span className="font-semibold">{share(part, whole)}</span>
+ <span className="text-xs text-muted">
+ {humanFriendlyNumber(part)} {label.toLowerCase()}
+ </span>
+ </div>
+ <LemonProgress percent={whole > 0 ? (part / whole) * 100 : 0} size="large" />
</div>
- <LemonProgress percent={whole > 0 ? (part / whole) * 100 : 0} size="large" />
- </div>
- ))}
- {footnote ? <span className="text-xs text-muted">{footnote}</span> : null}
- </div>
+ ))}
+ {footnote ? <span className="text-xs text-muted">{footnote}</span> : null}
+ </div>
+ ) : null}
- <BroadcastSendActivity {...props} />
+ {stats.sent > 0 ? <BroadcastSendActivity {...props} /> : null}
- {trackingOff ? null : (
+ {showLinks ? (
<div className="flex flex-col gap-2">
<h3 className="m-0 text-sm font-semibold">Top clicked links</h3>
<EmailLinksTable links={links} loading={linksLoading} emptyState="No link clicks yet" />
</div>
- )}
+ ) : null}
</div>
)
}
diff --git a/products/workflows/frontend/Broadcasts/BroadcastPushPerformance.tsx b/products/workflows/frontend/Broadcasts/BroadcastPushPerformance.tsx
index d106fad8ecc1..1a3a911d0b05 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastPushPerformance.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastPushPerformance.tsx
@@ -3,13 +3,22 @@ import { useActions, useValues } from 'kea'
import { IconInfo } from '@posthog/icons'
import { LemonBanner, LemonSkeleton, Link, Tooltip } from '@posthog/lemon-ui'
+import { cn } from 'lib/utils/css-classes'
import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
import { BroadcastPerformanceLogicProps, broadcastPerformanceLogic } from './broadcastPerformanceLogic'
import { BroadcastSendActivity } from './BroadcastSendActivity'
+import { BroadcastSendErrorAction, BroadcastSendErrorBanner } from './BroadcastSendErrorBanner'
const PUSH_DOCS_URL = 'https://posthog.com/docs/workflows/push-notifications'
+// Keyed by how many stats show, since the goal and the not sent stats only show when they apply.
+const STAT_GRID_COLUMNS: Record<number, string> = {
+ 4: '@xl:grid-cols-4',
+ 5: '@xl:grid-cols-5',
+ 6: '@xl:grid-cols-3 @4xl:grid-cols-6',
+}
+
function ofSent(part: number, sent: number): string {
return sent > 0 ? `${percentage(part / sent, 1)} of sent` : 'of sent'
}
@@ -44,10 +53,18 @@ function Stat({
/** A push send's numbers. Push providers confirm they accepted a notification, never that a phone showed it. */
export function BroadcastPushPerformance({
hasGoal = false,
+ fixAction,
+ resendAction,
+ content,
...props
-}: BroadcastPerformanceLogicProps & { hasGoal?: boolean }): JSX.Element {
+}: BroadcastPerformanceLogicProps & {
+ hasGoal?: boolean
+ fixAction?: BroadcastSendErrorAction
+ resendAction?: BroadcastSendErrorAction
+ content?: string
+}): JSX.Element {
const logic = broadcastPerformanceLogic(props)
- const { stats, totalsLoading, totalsFailed } = useValues(logic)
+ const { stats, sendCounts, totalsLoading, totalsFailed } = useValues(logic)
const { loadTotals } = useActions(logic)
if (totalsFailed && !totalsLoading) {
@@ -65,20 +82,20 @@ export function BroadcastPushPerformance({
}
const attempted = stats.sent + stats.skipped + stats.failed
+ const notSent = sendCounts?.notSent ?? 0
+ const statCount = 4 + (hasGoal ? 1 : 0) + (notSent > 0 ? 1 : 0)
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'
- }
- >
+ <BroadcastSendErrorBanner {...props} fixAction={fixAction} resendAction={resendAction} content={content} />
+ <div className={cn('grid grid-cols-2 gap-4', STAT_GRID_COLUMNS[statCount])}>
<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."
/>
+ {notSent > 0 ? <Stat label="Not sent" value={notSent} detail="people, stopped by an error" /> : null}
<Stat label="Opened" value={stats.opened} detail={ofSent(stats.opened, stats.sent)} />
<Stat
label="No device"
@@ -99,7 +116,7 @@ export function BroadcastPushPerformance({
</Link>
.
</span>
- <BroadcastSendActivity {...props} hideSingleBucket />
+ {stats.sent > 0 ? <BroadcastSendActivity {...props} hideSingleBucket /> : null}
</div>
)
}
diff --git a/products/workflows/frontend/Broadcasts/BroadcastSendErrorBanner.tsx b/products/workflows/frontend/Broadcasts/BroadcastSendErrorBanner.tsx
new file mode 100644
index 000000000000..c8062be3c38c
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/BroadcastSendErrorBanner.tsx
@@ -0,0 +1,163 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { BroadcastPerformanceLogicProps, broadcastPerformanceLogic } from './broadcastPerformanceLogic'
+import { BroadcastSendError, findMergeTag } from './broadcastSendError'
+
+export interface BroadcastSendErrorAction {
+ label: string
+ onClick: () => void
+}
+
+/** Sending again goes to the whole audience, so a sender has to know when that repeats the email for some people. */
+function sendAgainStep(sent: number, noun: string): string {
+ if (sent === 0) {
+ return 'Send it again to reach them.'
+ }
+ return `Sending it again goes to the whole audience, including the ${humanFriendlyNumber(sent)} ${
+ sent === 1 ? 'person' : 'people'
+ } who got this ${noun}.`
+}
+
+/** Every action here sends to the whole audience again, so the duplicate warning goes with fix instructions too. */
+function nextStepFor(sendError: BroadcastSendError | null, sent: number, noun: string): string {
+ if (!sendError || sendError.kind === 'unknown') {
+ return sendError?.nextStep ?? ''
+ }
+ if (!sendError.nextStep) {
+ return sendAgainStep(sent, noun)
+ }
+ return sent > 0 ? `${sendError.nextStep} ${sendAgainStep(sent, noun)}` : sendError.nextStep
+}
+
+function actionFor(
+ sendError: BroadcastSendError | null,
+ fixAction: BroadcastSendErrorAction | undefined,
+ resendAction: BroadcastSendErrorAction | undefined
+): BroadcastSendErrorAction | undefined {
+ if (sendError?.kind === 'content') {
+ return fixAction
+ }
+ if (sendError?.kind === 'our_side') {
+ return resendAction
+ }
+ return undefined
+}
+
+function SendErrorReason({
+ sendError,
+ tag,
+ nextStep,
+ onRetry,
+}: {
+ sendError: BroadcastSendError | null
+ tag: string | null
+ nextStep: string
+ onRetry: () => void
+}): JSX.Element {
+ if (!sendError) {
+ return (
+ <span>
+ Sending it hit an error, and its details didn't load.{' '}
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ noPadding
+ className="inline-flex"
+ onClick={onRetry}
+ data-attr="broadcast-send-error-retry"
+ >
+ Try again
+ </LemonButton>
+ </span>
+ )
+ }
+ return (
+ <span>
+ {tag ? (
+ <>
+ {`${sendError.reason}: `}
+ <code translate="no">{tag}</code>
+ {'. '}
+ </>
+ ) : (
+ `${sendError.reason}. `
+ )}
+ {nextStep}
+ </span>
+ )
+}
+
+function ErrorLogDetails({ log }: { log: string }): JSX.Element {
+ const [showDetails, setShowDetails] = useState(false)
+ return (
+ <>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ noPadding
+ sideIcon={showDetails ? <IconChevronDown /> : <IconChevronRight />}
+ onClick={() => setShowDetails(!showDetails)}
+ data-attr="broadcast-send-error-details"
+ >
+ {showDetails ? 'Hide details' : 'Show details'}
+ </LemonButton>
+ {showDetails ? (
+ <code className="block w-full whitespace-pre-wrap wrap-anywhere text-xs" translate="no">
+ {log}
+ </code>
+ ) : null}
+ </>
+ )
+}
+
+export function BroadcastSendErrorBanner({
+ fixAction,
+ resendAction,
+ content,
+ ...props
+}: BroadcastPerformanceLogicProps & {
+ fixAction?: BroadcastSendErrorAction
+ resendAction?: BroadcastSendErrorAction
+ /** The text the sender wrote, used to show a merge tag in full when the log cut it off. */
+ content?: string
+}): JSX.Element | null {
+ const { sendCounts, sendError, latestErrorLog } = useValues(broadcastPerformanceLogic(props))
+ const { loadLatestErrorLog } = useActions(broadcastPerformanceLogic(props))
+
+ const notSent = sendCounts?.notSent ?? 0
+ if (notSent === 0) {
+ return null
+ }
+ const noun = props.channel === 'push' ? 'notification' : 'email'
+ const tag = sendError?.tag && content ? findMergeTag(sendError.tag, content) : (sendError?.tag ?? null)
+ const nextStep = nextStepFor(sendError, sendCounts?.sent ?? 0, noun)
+ const action = actionFor(sendError, fixAction, resendAction)
+
+ return (
+ <LemonBanner
+ type="error"
+ alignItems="start"
+ action={
+ action
+ ? { children: action.label, onClick: action.onClick, 'data-attr': 'broadcast-send-error-action' }
+ : undefined
+ }
+ >
+ <div className="flex flex-col items-start gap-1" data-attr="broadcast-send-error">
+ <span className="wrap-anywhere">
+ <span className="font-semibold">{`${humanFriendlyNumber(notSent)} ${
+ notSent === 1 ? 'person' : 'people'
+ } didn't get this ${noun}.`}</span>{' '}
+ <SendErrorReason sendError={sendError} tag={tag} nextStep={nextStep} onRetry={loadLatestErrorLog} />
+ </span>
+ {latestErrorLog ? <ErrorLogDetails log={latestErrorLog} /> : null}
+ </div>
+ </LemonBanner>
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/BroadcastStatusTag.tsx b/products/workflows/frontend/Broadcasts/BroadcastStatusTag.tsx
index 03ea3022469d..34811889fa95 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastStatusTag.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastStatusTag.tsx
@@ -1,17 +1,22 @@
import { LemonTag, LemonTagType } from '@posthog/lemon-ui'
-import { BroadcastStatus } from './broadcastsLogic'
+import { BroadcastRunStatus, BroadcastStatus } from './broadcastsLogic'
-const STATUS_CONFIG: Record<Exclude<BroadcastStatus, 'unknown'>, { label: string; type: LemonTagType }> = {
+const STATUS_CONFIG: Record<
+ Exclude<BroadcastStatus | BroadcastRunStatus, 'unknown'>,
+ { label: string; type: LemonTagType }
+> = {
draft: { label: 'Draft', type: 'default' },
scheduled: { label: 'Scheduled', type: 'warning' },
sending: { label: 'Sending', type: 'completion' },
sent: { label: 'Sent', type: 'success' },
+ partially_failed: { label: 'Partly failed', type: 'warning' },
failed: { label: 'Failed', type: 'danger' },
+ cancelled: { label: 'Cancelled', type: 'muted' },
archived: { label: 'Archived', type: 'muted' },
}
-export function BroadcastStatusTag({ status }: { status: BroadcastStatus }): JSX.Element {
+export function BroadcastStatusTag({ status }: { status: BroadcastStatus | BroadcastRunStatus }): JSX.Element {
if (status === 'unknown') {
return <span className="text-muted">…</span>
}
diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
index bb2e00584219..9fa18ab9e88b 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
@@ -2,15 +2,7 @@ import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { useEffect } from 'react'
import { IconChevronDown, IconLetter } from '@posthog/icons'
-import {
- LemonBanner,
- LemonButton,
- LemonDialog,
- LemonDivider,
- LemonInput,
- LemonTag,
- LemonTagType,
-} from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonDialog, LemonDivider, LemonInput } from '@posthog/lemon-ui'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
import { TZLabel } from 'lib/components/TZLabel'
@@ -20,7 +12,6 @@ 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 { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -34,25 +25,19 @@ import { broadcastAudienceCohortsLogic } from './audience/broadcastAudienceCohor
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'
-const BATCH_JOB_STATUS_TAG: Record<string, LemonTagType> = {
- waiting: 'default',
- queued: 'warning',
- active: 'warning',
- completed: 'success',
- cancelled: 'muted',
- failed: 'danger',
-}
-
/**
* 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.
@@ -61,21 +46,34 @@ 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">
+ <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} />
+ <RunRecipientsTable workflowId={workflowId} runFinished={runFinished} sent={sendCounts?.sent ?? null} />
</BindLogic>
</div>
)
}
-function RunRecipientsTable({ workflowId }: { workflowId: string }): JSX.Element {
+function RunRecipientsTable({
+ workflowId,
+ runFinished,
+ sent,
+}: {
+ workflowId: string
+ runFinished: boolean
+ sent: number | null
+}): JSX.Element {
const {
sends,
sendsLoading,
@@ -94,7 +92,11 @@ function RunRecipientsTable({ workflowId }: { workflowId: string }): JSX.Element
const noSendsMessage = runPastRetention
? "Recipient details are kept for 30 days after sending, so this run's list is no longer available."
- : 'No sends recorded for this run yet.'
+ : !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> = [
{
@@ -221,11 +223,13 @@ function RunsTable({
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)
@@ -239,7 +243,13 @@ function RunsTable({
nouns={['run', 'runs']}
expandable={{
expandedRowRender: (job) => (
- <RunRecipients workflowId={workflowId} runId={job.id} runCreatedAt={job.created_at} />
+ <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
@@ -254,15 +264,22 @@ function RunsTable({
)
}
-const LATEST_RUN_LABEL: Record<string, string> = {
- completed: 'Sent',
- waiting: 'Sending, started',
- queued: 'Sending, started',
- active: 'Sending, started',
+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,
@@ -306,6 +323,16 @@ export function BroadcastSummary(): JSX.Element {
})
}
+ // 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
@@ -318,11 +345,7 @@ export function BroadcastSummary(): JSX.Element {
{
title: 'Status',
key: 'status',
- render: (_, job) => (
- <LemonTag type={BATCH_JOB_STATUS_TAG[job.status ?? 'waiting'] ?? 'default'}>
- {capitalizeFirstLetter(job.status ?? 'waiting')}
- </LemonTag>
- ),
+ render: (_, job) => <BroadcastStatusTag status={getRunStatus(job.status)} />,
},
{
title: 'Started by',
@@ -475,10 +498,7 @@ export function BroadcastSummary(): JSX.Element {
) : null}
</div>
) : latestBatchJob ? (
- <span>
- {LATEST_RUN_LABEL[latestBatchJob.status ?? 'waiting'] ?? 'Last run'}{' '}
- <TZLabel time={latestBatchJob.created_at} />
- </span>
+ <LatestRunLabel job={latestBatchJob} />
) : (
<span>{scheduleSummary}</span>
)}
@@ -504,12 +524,19 @@ export function BroadcastSummary(): JSX.Element {
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">
@@ -541,6 +568,7 @@ export function BroadcastSummary(): JSX.Element {
batchJobs={batchJobs}
batchJobsLoading={batchJobsLoading}
columns={batchJobColumns}
+ channel={channel}
/>
),
},
diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
index 73d1729a83bd..40afc2df7f97 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
@@ -83,7 +83,8 @@ export function BroadcastsTable(): JSX.Element {
title: 'Status',
width: 0,
render: (_, item) => {
- return <BroadcastStatusTag status={getBroadcastStatus(item, rowDetailsById[item.id])} />
+ const details = rowDetailsById[item.id]
+ return <BroadcastStatusTag status={getBroadcastStatus(item, details)} />
},
},
{
@@ -226,6 +227,7 @@ export function BroadcastsTable(): JSX.Element {
{ label: 'Scheduled', value: 'scheduled' },
{ label: 'Sending', value: 'sending' },
{ label: 'Sent', value: 'sent' },
+ { label: 'Partly failed', value: 'partially_failed' },
{ label: 'Failed', value: 'failed' },
{ label: 'Archived', value: 'archived' },
]}
diff --git a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.ts
index 72e37f193964..dfe229c27b8c 100644
--- a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.test.ts
@@ -67,6 +67,44 @@ describe('broadcastPerformanceLogic', () => {
expect(logic.values.stats?.sent).toEqual(49)
})
+ it.each(['email', 'push'] as const)(
+ 'counts %s sends that stopped at an error before reaching the provider, and says why',
+ async (channel) => {
+ // An aborting step records `failed` at step and run level, so the run-level row must not count twice.
+ const rows: [number, string, string][] = [
+ [0, 'email_sent', 'step_1'],
+ [0, 'push_sent', 'step_1'],
+ [245, 'failed', 'step_1'],
+ [245, 'failed', ''],
+ ]
+ const errorLog = '[Action:step_1] Errored: Error: invalid value expression: "person.name |", line:3, col:1'
+ jest.spyOn(api, 'queryHogQL').mockImplementation(
+ async (query) =>
+ ({
+ results: String(query).includes('log_entries')
+ ? [[errorLog]]
+ : rows.filter(([, name]) => String(query).includes(`'${name}'`)),
+ }) as HogQLQueryResponse
+ )
+ const logic = broadcastPerformanceLogic({
+ runId: `run-errored-${channel}`,
+ runStartedAt: '2026-10-19T22:28:56Z',
+ channel,
+ })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadTotalsSuccess', 'loadLatestErrorLogSuccess'])
+ expect(logic.values.stats).toMatchObject({ sent: 0, failed: 0 })
+ expect(logic.values.sendCounts).toEqual({ sent: 0, notSent: 245 })
+ expect(logic.values.sendError).toEqual({
+ kind: 'content',
+ reason: "A merge tag can't be read",
+ tag: '{{ person.name | }}',
+ nextStep: `Check the tag in the ${channel === 'push' ? 'notification' : 'email'} for typos.`,
+ })
+ }
+ )
+
it('does not report tracking off before anything was sent', async () => {
jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as unknown as HogQLQueryResponse)
const logic = broadcastPerformanceLogic({ runId: 'run-2', runStartedAt: '2026-10-19T22:28:56Z' })
diff --git a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts
index a2810911821e..1d6ae222d940 100644
--- a/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastPerformanceLogic.ts
@@ -1,13 +1,19 @@
-import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'
+import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import api from 'lib/api'
import { AppMetricsCommonParams, loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'
import { Dayjs, dayjs } from 'lib/dayjs'
+import { hogql } from 'lib/utils/hogql'
+import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
+import { ProductKey } from '~/queries/schema/schema-general'
+
import type { TeamPublicType, TeamType } from '../../../../frontend/src/types'
import { type EmailLinkRow, parseEmailLinkTotals } from '../Workflows/workflowMetricsSummaryLogic'
-import type { BroadcastChannel } from './broadcastsLogic'
+import { type BroadcastSendError, describeSendError } from './broadcastSendError'
+import { type BroadcastChannel, type BroadcastSendCounts, getSendCounts } 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. */
@@ -48,6 +54,8 @@ const TOTALS_METRICS = [
'push_opened',
'email_unsubscribed',
'conversion',
+ // Recorded when a step throws, so a send that never reached the provider has no email_failed or push_failed.
+ 'failed',
]
const SEND_ACTIVITY_METRICS: Record<BroadcastChannel, string[]> = {
@@ -80,8 +88,12 @@ export function sendActivityParams(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPerformanceLogicValues {
currentTeam: TeamPublicType | TeamType | null // teamLogic
+ latestErrorLog: string | null
+ latestErrorLogLoading: boolean
links: EmailLinkRow[]
linksLoading: boolean
+ sendCounts: BroadcastSendCounts | null
+ sendError: BroadcastSendError | null
stats: BroadcastPerformanceStats | null
totals: Record<string, number> | null
totalsFailed: boolean
@@ -91,6 +103,21 @@ export interface broadcastPerformanceLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPerformanceLogicActions {
+ loadLatestErrorLog: () => any
+ loadLatestErrorLogFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadLatestErrorLogSuccess: (
+ latestErrorLog: string,
+ payload?: any
+ ) => {
+ latestErrorLog: string
+ payload?: any
+ }
loadLinks: () => any
loadLinksFailure: (
error: string,
@@ -115,14 +142,10 @@ export interface broadcastPerformanceLogicActions {
errorObject?: any
}
loadTotalsSuccess: (
- totals: {
- [k: string]: number
- },
+ totals: Record<string, number>,
payload?: any
) => {
- totals: {
- [k: string]: number
- }
+ totals: Record<string, number>
payload?: any
}
}
@@ -135,6 +158,11 @@ export interface broadcastPerformanceLogicMeta {
totals: Record<string, number> | null,
arg: BroadcastChannel | undefined
) => BroadcastPerformanceStats | null
+ sendCounts: (
+ totals: Record<string, number> | null,
+ arg: BroadcastChannel | undefined
+ ) => BroadcastSendCounts | null
+ sendError: (latestErrorLog: string | null, arg: BroadcastChannel | undefined) => BroadcastSendError | null
trackingOff: (stats: BroadcastPerformanceStats | null) => boolean
}
}
@@ -168,14 +196,47 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([
appSource: 'hog_flow',
appSourceId: props.runId,
metricName: TOTALS_METRICS,
- breakdownBy: ['metric_name'],
+ breakdownBy: ['metric_name', 'instance_id'],
...window(),
},
values.currentTeam?.timezone ?? 'UTC'
)
- return Object.fromEntries(
- Object.values(response).map(({ total, breakdowns }) => [breakdowns[0], total])
+ const totals: Record<string, number> = {}
+ for (const { total, breakdowns } of Object.values(response)) {
+ const [metricName, instanceId] = breakdowns
+ // A step that aborts the run also records a run-level `failed`, which would count each
+ // person twice, so only step-level failures count people who weren't sent anything.
+ if (metricName === 'failed' && !instanceId) {
+ continue
+ }
+ totals[metricName] = (totals[metricName] ?? 0) + total
+ }
+ return totals
+ },
+ },
+ ],
+ latestErrorLog: [
+ null as string | null,
+ {
+ loadLatestErrorLog: async () => {
+ const response = await api.queryHogQL<[string]>(
+ hogql`
+ SELECT message
+ FROM log_entries
+ WHERE log_source = 'hog_flow'
+ AND log_source_id = ${props.runId}
+ AND lower(level) = 'error'
+ AND timestamp > {filters.dateRange.from}
+ ORDER BY startsWith(message, '[Action:') DESC, timestamp DESC
+ LIMIT 1`,
+ {
+ scene: Scene.Broadcast,
+ productKey: ProductKey.WORKFLOWS,
+ name: 'broadcast_run_latest_error',
+ },
+ { refresh: 'force_blocking', filtersOverride: { date_from: window().dateFrom } }
)
+ return response.results?.[0]?.[0] ?? null
},
},
],
@@ -257,12 +318,31 @@ export const broadcastPerformanceLogic = kea<broadcastPerformanceLogicType>([
}
},
],
+ sendCounts: [
+ (s) => [s.totals, (_, props: BroadcastPerformanceLogicProps) => props.channel],
+ (
+ totals: Record<string, number> | null,
+ channel: BroadcastChannel | undefined
+ ): BroadcastSendCounts | null => getSendCounts(totals, channel),
+ ],
+ sendError: [
+ (s) => [s.latestErrorLog, (_, props: BroadcastPerformanceLogicProps) => props.channel],
+ (latestErrorLog: string | null, channel: BroadcastChannel | undefined): BroadcastSendError | null =>
+ latestErrorLog ? describeSendError(latestErrorLog, channel) : null,
+ ],
// Every email went out with open and click tracking off, so no open or click can ever be counted.
trackingOff: [
(s) => [s.stats],
(stats: BroadcastPerformanceStats | null): boolean => !!stats && stats.sent > 0 && stats.trackedSends === 0,
],
}),
+ listeners(({ actions }) => ({
+ loadTotalsSuccess: ({ totals }) => {
+ if ((totals.failed ?? 0) > 0) {
+ actions.loadLatestErrorLog()
+ }
+ },
+ })),
afterMount(({ actions, props }) => {
actions.loadTotals()
if (props.channel !== 'push') {
diff --git a/products/workflows/frontend/Broadcasts/broadcastSendError.test.ts b/products/workflows/frontend/Broadcasts/broadcastSendError.test.ts
new file mode 100644
index 000000000000..3f6610ed71fc
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastSendError.test.ts
@@ -0,0 +1,80 @@
+import { describeSendError, findMergeTag } from './broadcastSendError'
+
+describe('broadcastSendError', () => {
+ it.each([
+ {
+ name: 'a merge tag inside a link',
+ log: '[Action:email_1] Errored: Error: invalid value expression: "%20person.properties.city%20|%20url_enco...", line:98, col:158',
+ expected: {
+ kind: 'content',
+ reason: 'A merge tag in a link is broken',
+ tag: 'person.properties.city | url_enco...',
+ nextStep: 'Edit the link and type the tag again.',
+ },
+ },
+ {
+ name: 'a merge tag outside a link',
+ log: '[Action:email_1] Errored: Error: invalid value expression: "person.properties.city |", line:3, col:9',
+ expected: {
+ kind: 'content',
+ reason: "A merge tag can't be read",
+ tag: '{{ person.properties.city | }}',
+ nextStep: 'Check the tag in the email for typos.',
+ },
+ },
+ {
+ name: 'a sender that no longer exists',
+ log: '[Action:email_1] Errored: Error: Email integration not found. The sender configured for this step no longer exists.',
+ expected: {
+ kind: 'content',
+ reason: "The sender for this email isn't set up",
+ tag: null,
+ nextStep: 'Check the sender in the email step and that its domain is verified, then send it again.',
+ },
+ },
+ {
+ name: 'an SES rejection for an unverified sender address',
+ log: '[Action:email_1] Errored: Error: Failed to send email via SES: Email address is not verified. The following identities failed the check: [email protected]',
+ expected: {
+ kind: 'content',
+ reason: "The sender for this email isn't set up",
+ tag: null,
+ nextStep: 'Check the sender in the email step and that its domain is verified, then send it again.',
+ },
+ },
+ {
+ name: 'a timeout on our side',
+ log: '[Action:email_1] Errored: Error: Request to the template service timed out after 10000ms',
+ expected: { kind: 'our_side', reason: 'A problem on our side stopped the send', tag: null, nextStep: null },
+ },
+ {
+ name: 'an error nothing recognizes',
+ log: '[Action:email_1] Errored: Error: Unexpected token in template',
+ expected: {
+ kind: 'unknown',
+ reason: 'Sending hit an error',
+ tag: null,
+ nextStep: 'Show details has the error from the send.',
+ },
+ },
+ ])('describes $name', ({ log, expected }) => {
+ expect(describeSendError(log, 'email')).toEqual(expected)
+ })
+
+ it.each([
+ {
+ name: 'recovers a truncated tag from URL-encoded link content',
+ tag: 'person.properties.city | url_enco...',
+ content: '<a href="https://example.com/?c={{%20person.properties.city%20|%20url_encode%20}}">Hi</a>',
+ expected: '{{ person.properties.city | url_encode }}',
+ },
+ {
+ name: 'keeps a truncated tag when no tag in the content matches',
+ tag: 'person.properties.city | url_enco...',
+ content: '<p>Hello {{ person.properties.first_name }}</p>',
+ expected: 'person.properties.city | url_enco...',
+ },
+ ])('$name', ({ tag, content, expected }) => {
+ expect(findMergeTag(tag, content)).toBe(expected)
+ })
+})
diff --git a/products/workflows/frontend/Broadcasts/broadcastSendError.ts b/products/workflows/frontend/Broadcasts/broadcastSendError.ts
new file mode 100644
index 000000000000..77a0a5aaae88
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastSendError.ts
@@ -0,0 +1,109 @@
+import type { BroadcastChannel } from './broadcastsLogic'
+
+/** Picks the banner's action: fix the content, send again, or nothing. */
+export type BroadcastSendErrorKind = 'content' | 'our_side' | 'unknown'
+
+export interface BroadcastSendError {
+ kind: BroadcastSendErrorKind
+ /** Why the sends errored, in plain language and without a trailing period. */
+ reason: string
+ tag: string | null
+ /** What the sender can do about it, as a full sentence. Null when it depends on how many people got the email. */
+ nextStep: string | null
+}
+
+// The hog flow executor logs `[Action:<step id>] Errored: <String(err)>`, and String(err) adds the error class.
+const LOG_PREFIX = /^(?:\[Action:[^\]]*\]\s*)?(?:Errored:\s*)?(?:[A-Za-z]*Error:\s*)*/
+// LiquidJS adds the position in the rendered template, which the sender can't map back to the editor.
+const TEMPLATE_POSITION = /,\s*line:\d+,\s*col:\d+\s*$/
+// Template text inside a link's URL is URL-encoded, so a tag there reaches Liquid as `%20person.name%20`.
+const URL_ENCODED = /%[0-9A-Fa-f]{2}/
+const TRUNCATION_MARKER = '...'
+const SENDER_NOT_SET_UP =
+ /^Email integration not found|is not an email channel|email integration is not configured correctly|not verified/i
+const PROVIDER_FAILED = /^Failed to send email via SES|^SES is not configured|^No messageId returned from SES/i
+const ON_OUR_SIDE =
+ /timed? ?out|ECONNRESET|ECONNREFUSED|ETIMEDOUT|socket hang up|rate limit|too many requests|\b5\d\d\b/i
+
+const EXPRESSION_ERROR = /^(?:invalid value expression:|unexpected character) "(.*)"$/
+
+function describeExpressionError(expression: string, noun: string, inLink: boolean): BroadcastSendError {
+ const tag = expression.endsWith(TRUNCATION_MARKER) ? expression : `{{ ${expression} }}`
+ if (inLink) {
+ return {
+ kind: 'content',
+ reason: 'A merge tag in a link is broken',
+ tag,
+ nextStep: 'Edit the link and type the tag again.',
+ }
+ }
+ return {
+ kind: 'content',
+ reason: "A merge tag can't be read",
+ tag,
+ nextStep: `Check the tag in the ${noun} for typos.`,
+ }
+}
+
+function decodeUrlEncoding(text: string): string {
+ try {
+ return decodeURIComponent(text)
+ } catch {
+ // A lone `%` makes the whole string invalid, so decode each escape on its own instead.
+ return text.replace(/%[0-9A-Fa-f]{2}/g, (escape) => {
+ try {
+ return decodeURIComponent(escape)
+ } catch {
+ return escape
+ }
+ })
+ }
+}
+
+export function describeSendError(logMessage: string, channel: BroadcastChannel = 'email'): BroadcastSendError {
+ const noun = channel === 'push' ? 'notification' : 'email'
+ const firstLine = logMessage.trim().split('\n')[0]
+ const rawMessage = firstLine.replace(LOG_PREFIX, '').replace(TEMPLATE_POSITION, '').trim()
+ const message = decodeUrlEncoding(rawMessage).trim()
+
+ const expression = EXPRESSION_ERROR.exec(message)?.[1].trim()
+ if (expression) {
+ return describeExpressionError(expression, noun, URL_ENCODED.test(rawMessage))
+ }
+ if (SENDER_NOT_SET_UP.test(message)) {
+ return {
+ kind: 'content',
+ reason: `The sender for this ${noun} isn't set up`,
+ tag: null,
+ nextStep: `Check the sender in the ${noun} step and that its domain is verified, then send it again.`,
+ }
+ }
+ if (PROVIDER_FAILED.test(message) || ON_OUR_SIDE.test(message)) {
+ return { kind: 'our_side', reason: 'A problem on our side stopped the send', tag: null, nextStep: null }
+ }
+ return {
+ kind: 'unknown',
+ reason: 'Sending hit an error',
+ tag: null,
+ nextStep: 'Show details has the error from the send.',
+ }
+}
+
+function normalizeExpression(expression: string): string {
+ return decodeUrlEncoding(expression).replace(/\s+/g, ' ').trim()
+}
+
+/** Liquid cuts long expressions in its error, so this finds the full tag in the content, or keeps the tag as is. */
+export function findMergeTag(tag: string, content: string): string {
+ if (!tag.endsWith(TRUNCATION_MARKER)) {
+ return tag
+ }
+ const prefix = normalizeExpression(tag.slice(0, -TRUNCATION_MARKER.length))
+ for (const [, inner] of decodeUrlEncoding(content).matchAll(/\{\{([\s\S]*?)\}\}/g)) {
+ const expression = normalizeExpression(inner)
+ if (prefix && expression.startsWith(prefix)) {
+ return `{{ ${expression} }}`
+ }
+ }
+ return tag
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts b/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts
index 368243a14eb6..56a71f987121 100644
--- a/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts
@@ -11,7 +11,7 @@ const withJob = (status: string): { latestBatchJob: HogFlowBatchJobApi; totals:
totals: {},
})
-describe('getBroadcastStatus', () => {
+describe('broadcast status', () => {
it.each([
['a draft, whatever its runs say', flow('draft'), withJob('completed'), 'draft'],
['an archived broadcast', flow('archived'), withJob('completed'), 'archived'],
@@ -49,6 +49,18 @@ describe('getBroadcastStatus', () => {
],
// Runs not loaded yet, or failed to load, used to read as "scheduled" for a broadcast that already sent.
['a live broadcast whose runs have not loaded', flow('active'), undefined, 'unknown'],
+ [
+ 'a run the server marks as partly failed',
+ flow('active'),
+ { ...withJob('partially_failed'), hasPendingSchedule: false },
+ 'partially_failed',
+ ],
+ [
+ 'a recurring broadcast whose last run partly failed',
+ flow('active'),
+ { ...withJob('partially_failed'), hasPendingSchedule: true },
+ 'scheduled',
+ ],
])('reads %s as %s', (_name, broadcast, details, expected) => {
expect(getBroadcastStatus(broadcast, details)).toBe(expected)
})
diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
index 75d2f208e46c..302398179372 100644
--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
@@ -35,7 +35,22 @@ import {
restoreBroadcast,
} from './broadcastLifecycle'
-export type BroadcastStatus = 'draft' | 'scheduled' | 'sending' | 'sent' | 'failed' | 'archived' | 'unknown'
+export type BroadcastStatus =
+ | 'draft'
+ | 'scheduled'
+ | 'sending'
+ | 'sent'
+ | 'partially_failed'
+ | 'failed'
+ | 'archived'
+ | 'unknown'
+
+export type BroadcastRunStatus = Exclude<BroadcastStatus, 'draft' | 'scheduled' | 'archived' | 'unknown'> | 'cancelled'
+
+export interface BroadcastSendCounts {
+ sent: number
+ notSent: number
+}
export interface BroadcastRowDetails {
latestBatchJob: HogFlowBatchJobApi | null
@@ -57,6 +72,7 @@ const BROADCASTS_STATUS_FILTERS: BroadcastsStatusFilter[] = [
'scheduled',
'sending',
'sent',
+ 'partially_failed',
'failed',
'archived',
]
@@ -157,6 +173,43 @@ export function canMoveToDraft(
)
}
+const RUN_STATUS: Record<string, BroadcastRunStatus> = {
+ waiting: 'sending',
+ queued: 'sending',
+ active: 'sending',
+ completed: 'sent',
+ partially_failed: 'partially_failed',
+ failed: 'failed',
+ cancelled: 'cancelled',
+}
+
+/** Unknown run statuses read as failed, so a new terminal status never reads as a send still going. */
+export function getRunStatus(jobStatus: string | null | undefined): BroadcastRunStatus {
+ return RUN_STATUS[jobStatus ?? 'waiting'] ?? 'failed'
+}
+
+/** Null until the run's totals load. Push counts notifications, so `sent` is only compared with zero. */
+export function getSendCounts(
+ totals: Record<string, number> | null | undefined,
+ channel: BroadcastChannel = 'email'
+): BroadcastSendCounts | null {
+ if (!totals) {
+ return null
+ }
+ return {
+ sent: totals[channel === 'push' ? 'push_sent' : 'email_sent'] ?? 0,
+ notSent: totals.failed ?? 0,
+ }
+}
+
+/** The server names a broadcast whose latest run partly failed `partially_sent`. */
+function toServerStatusFilter(status: BroadcastsStatusFilter): string | undefined {
+ if (status === 'all') {
+ return undefined
+ }
+ return status === 'partially_failed' ? 'partially_sent' : status
+}
+
export function getBroadcastStatus(
broadcast: { status?: string | null; origin_product?: string | null },
details: BroadcastRowDetails | undefined
@@ -172,15 +225,16 @@ export function getBroadcastStatus(
}
const latestJob = details.latestBatchJob
if (latestJob) {
- if (['waiting', 'queued', 'active'].includes(latestJob.status ?? '')) {
- return 'sending'
+ const runStatus = getRunStatus(latestJob.status)
+ if (runStatus === 'sending') {
+ return runStatus
}
- if (latestJob.status === 'completed') {
+ if (runStatus === 'sent' || runStatus === 'partially_failed') {
// A recurring broadcast between runs has more to send. A failed run still reads as failed.
if (details.hasPendingSchedule === undefined) {
return 'unknown'
}
- return details.hasPendingSchedule ? 'scheduled' : 'sent'
+ return details.hasPendingSchedule ? 'scheduled' : runStatus
}
// Without this a failed or cancelled run falls through to the no-run fallback below, which
// tells the sender another send is still pending when nothing is coming.
@@ -360,7 +414,7 @@ export const broadcastsLogic = kea<broadcastsLogicType>([
// Only broadcasts. A workflow shaped like one stays under workflows until someone moves it.
type: 'broadcast',
search: values.filters.search || undefined,
- broadcast_status: values.filters.status !== 'all' ? values.filters.status : undefined,
+ broadcast_status: toServerStatusFilter(values.filters.status),
created_by: values.filters.createdBy || undefined,
tags: values.filters.tags.length ? JSON.stringify(values.filters.tags) : undefined,
limit: BROADCASTS_PAGE_SIZE,