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): track how broadcasts are launched and why they stop (#108443)

Daniel Marchukdd82ad1b8ef6
diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
index 11c127b6d62d..6e3f20babecd 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
@@ -32,7 +32,9 @@ import { BroadcastPerformance } from './BroadcastPerformance'
import { BroadcastSceneHeader } from './BroadcastSceneHeader'
import { broadcastSentLogic } from './broadcastSentLogic'
import { BroadcastStatusTag } from './BroadcastStatusTag'
+import { broadcastPath } from './broadcastUsage'
import { broadcastWizardLogic } from './broadcastWizardLogic'
+import { ComposerDraftFeedback } from './ComposerDraftFeedback'
const BATCH_JOB_STATUS_TAG: Record<string, LemonTagType> = {
waiting: 'default',
@@ -371,6 +373,7 @@ export function BroadcastSummary(): JSX.Element {
<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}
{summaryStatus === 'failed' && !latestBatchJob && !batchJobsLoading ? (
<LemonBanner
type="warning"
diff --git a/products/workflows/frontend/Broadcasts/BroadcastsFeaturePreview.tsx b/products/workflows/frontend/Broadcasts/BroadcastsFeaturePreview.tsx
index 327f1b7d1667..ac21380b6329 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastsFeaturePreview.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastsFeaturePreview.tsx
@@ -1,15 +1,16 @@
import { FeaturePreviewFeedbackBanner } from '../FeaturePreviewFeedbackBanner'
-
-const SURVEY_ID = '01a0ce6c-f291-0000-092b-8677d994599c'
-const RATING_QUESTION_ID = 'a5e6e02a-174b-41a7-8da6-7fa1595ac763'
-const FEEDBACK_QUESTION_ID = '1e3e0368-135f-485c-bf46-ddaac558e879'
+import {
+ BROADCASTS_FEEDBACK_RATING_QUESTION_ID,
+ BROADCASTS_FEEDBACK_SURVEY_ID,
+ BROADCASTS_FEEDBACK_TEXT_QUESTION_ID,
+} from './broadcastsFeedbackSurvey'
export function BroadcastsFeaturePreview(): JSX.Element {
return (
<FeaturePreviewFeedbackBanner
- surveyId={SURVEY_ID}
- ratingQuestionId={RATING_QUESTION_ID}
- feedbackQuestionId={FEEDBACK_QUESTION_ID}
+ surveyId={BROADCASTS_FEEDBACK_SURVEY_ID}
+ ratingQuestionId={BROADCASTS_FEEDBACK_RATING_QUESTION_ID}
+ feedbackQuestionId={BROADCASTS_FEEDBACK_TEXT_QUESTION_ID}
surface="broadcasts"
dismissKey="broadcasts-feature-preview"
prompt="Broadcasts is new. Is it doing what you need?"
diff --git a/products/workflows/frontend/Broadcasts/ComposerDraftFeedback.tsx b/products/workflows/frontend/Broadcasts/ComposerDraftFeedback.tsx
new file mode 100644
index 000000000000..50ef13ad5964
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/ComposerDraftFeedback.tsx
@@ -0,0 +1,25 @@
+import { FeaturePreviewFeedbackBanner } from '../FeaturePreviewFeedbackBanner'
+import {
+ BROADCASTS_FEEDBACK_RATING_QUESTION_ID,
+ BROADCASTS_FEEDBACK_SURVEY_ID,
+ BROADCASTS_FEEDBACK_TEXT_QUESTION_ID,
+} from './broadcastsFeedbackSurvey'
+
+/** Asked on a sent or scheduled broadcast that PostHog AI drafted. */
+export function ComposerDraftFeedback(): JSX.Element {
+ return (
+ <FeaturePreviewFeedbackBanner
+ surveyId={BROADCASTS_FEEDBACK_SURVEY_ID}
+ ratingQuestionId={BROADCASTS_FEEDBACK_RATING_QUESTION_ID}
+ feedbackQuestionId={BROADCASTS_FEEDBACK_TEXT_QUESTION_ID}
+ // pinned: feedback_surface value, filtered on in the broadcasts dashboard
+ surface="broadcasts-composer-draft"
+ dismissKey="broadcasts-composer-draft-feedback"
+ prompt="Did PostHog AI get this broadcast right?"
+ modalTitle="Help us improve AI drafts"
+ feedbackPlaceholder="What did you have to change, or what did it get wrong?"
+ className="m-0"
+ data-attr="broadcasts-composer-draft-feedback"
+ />
+ )
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastUsage.test.ts b/products/workflows/frontend/Broadcasts/broadcastUsage.test.ts
new file mode 100644
index 000000000000..10d1b1566813
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastUsage.test.ts
@@ -0,0 +1,63 @@
+import { advanceAgentDraft, broadcastPath, editedFields, saveComposerDraft, snapshotBroadcast } from './broadcastUsage'
+
+function flow(overrides: { name?: string; subject?: string; html?: string; audience?: unknown[] }): any {
+ return {
+ name: overrides.name ?? 'Spring sale',
+ conversion: null,
+ actions: [
+ { type: 'trigger', config: { filters: { properties: overrides.audience ?? [] } } },
+ {
+ type: 'function_email',
+ config: {
+ inputs: {
+ email: {
+ value: {
+ from: { integrationId: 1 },
+ subject: overrides.subject ?? 'Our spring sale',
+ html: overrides.html ?? '<p>Hi</p>',
+ },
+ },
+ },
+ },
+ },
+ ],
+ }
+}
+
+describe('broadcastUsage', () => {
+ it.each([
+ {
+ case: 'nothing changed',
+ launched: flow({}),
+ expected: [],
+ },
+ {
+ case: 'the subject and audience changed',
+ launched: flow({ subject: 'Our spring sale ends Friday', audience: [{ key: 'plan', value: 'pro' }] }),
+ expected: ['audience', 'subject'],
+ },
+ ])('reports the edited fields when $case', ({ launched, expected }) => {
+ expect(editedFields(snapshotBroadcast(flow({})), snapshotBroadcast(launched))).toEqual(expected)
+ })
+
+ it('keeps a saved edit of the person counted when the agent then edits another field', () => {
+ const agentDraft = snapshotBroadcast(flow({}))
+ // The person saved a new subject, then the agent rewrote the body. The copy the agent saved carries both.
+ const base = snapshotBroadcast(flow({ subject: 'Last days of the sale' }))
+ const latest = snapshotBroadcast(flow({ subject: 'Last days of the sale', html: '<p>Hi again</p>' }))
+
+ const advanced = advanceAgentDraft(agentDraft, latest, base)
+
+ expect(editedFields(advanced, latest)).toEqual(['subject'])
+ })
+
+ it('reports the composer path only for a draft the composer marked', () => {
+ saveComposerDraft('broadcast-1', { agentDraft: snapshotBroadcast(flow({})), agentEdits: 0 })
+
+ expect([broadcastPath('broadcast-1'), broadcastPath('broadcast-2'), broadcastPath(null)]).toEqual([
+ 'composer',
+ 'manual',
+ 'manual',
+ ])
+ })
+})
diff --git a/products/workflows/frontend/Broadcasts/broadcastUsage.ts b/products/workflows/frontend/Broadcasts/broadcastUsage.ts
new file mode 100644
index 000000000000..32b5a45cf775
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastUsage.ts
@@ -0,0 +1,103 @@
+import { objectsEqual } from 'lib/utils/objects'
+import { hashCodeForString } from 'lib/utils/strings'
+
+// pinned: URL search param the composer handoff adds to the draft URL, so the wizard knows where the draft came from
+export const COMPOSER_DRAFT_PARAM = 'from'
+export const COMPOSER_DRAFT_VALUE = 'ai_composer'
+
+const COMPOSER_DRAFTS_STORAGE_KEY = 'broadcasts-ai-composer-drafts'
+
+export type BroadcastPath = 'composer' | 'manual'
+
+export type BroadcastField = 'name' | 'audience' | 'goal' | 'sender' | 'subject' | 'body'
+
+export type BroadcastFieldSnapshot = Record<BroadcastField, unknown>
+
+/** What the agent last saved for a composer draft, and how many of its edits reached the wizard. */
+export interface ComposerDraftState {
+ agentDraft: BroadcastFieldSnapshot
+ agentEdits: number
+}
+
+const BROADCAST_FIELDS: BroadcastField[] = ['name', 'audience', 'goal', 'sender', 'subject', 'body']
+
+function readComposerDrafts(): Record<string, ComposerDraftState> {
+ try {
+ const stored = JSON.parse(sessionStorage.getItem(COMPOSER_DRAFTS_STORAGE_KEY) || '{}')
+ return stored && typeof stored === 'object' && !Array.isArray(stored) ? stored : {}
+ } catch {
+ return {}
+ }
+}
+
+/**
+ * Kept for the tab in session storage, so a reload still reports the composer path and still compares the
+ * launch with what the agent drafted rather than with a copy that already holds the person's saved edits.
+ */
+export function saveComposerDraft(broadcastId: string, state: ComposerDraftState): void {
+ try {
+ sessionStorage.setItem(
+ COMPOSER_DRAFTS_STORAGE_KEY,
+ JSON.stringify({ ...readComposerDrafts(), [broadcastId]: state })
+ )
+ } catch {
+ // Storage can be blocked. The draft then reports the manual path, which only undercounts the composer.
+ }
+}
+
+export function loadComposerDraft(broadcastId: string | null | undefined): ComposerDraftState | null {
+ return broadcastId ? (readComposerDrafts()[broadcastId] ?? null) : null
+}
+
+export function broadcastPath(broadcastId: string | null | undefined): BroadcastPath {
+ return loadComposerDraft(broadcastId) ? 'composer' : 'manual'
+}
+
+/**
+ * The fields a person can change in the wizard, read from a saved broadcast or from the payload the
+ * wizard would save, so both sides of a comparison come out in the same shape. The body is hashed to
+ * keep the stored copy small.
+ */
+export function snapshotBroadcast(flow: {
+ name?: string | null
+ conversion?: { events?: unknown[] | null; filters?: unknown[] | null; window?: unknown } | null
+ actions?: unknown
+}): BroadcastFieldSnapshot {
+ const actions = (Array.isArray(flow.actions) ? flow.actions : []) as Record<string, any>[]
+ const trigger = actions.find((action) => action.type === 'trigger')
+ const email = actions.find((action) => action.type === 'function_email')?.config?.inputs?.email?.value
+ const conversion = flow.conversion
+ const hasGoal = !!conversion && ((conversion.events?.length ?? 0) > 0 || (conversion.filters?.length ?? 0) > 0)
+ return {
+ name: flow.name ?? '',
+ audience: trigger?.config?.filters?.properties ?? [],
+ goal: hasGoal
+ ? { events: conversion.events ?? [], filters: conversion.filters ?? [], window: conversion.window }
+ : null,
+ sender: email?.from?.integrationId ?? null,
+ subject: email?.subject ?? '',
+ body: hashCodeForString(email?.html ?? ''),
+ }
+}
+
+/**
+ * Moves the agent's draft forward by an edit saved elsewhere. Only the fields that edit changed are taken,
+ * because the saved copy also carries the person's own saved edits, which must still count as theirs.
+ */
+export function advanceAgentDraft(
+ agentDraft: BroadcastFieldSnapshot,
+ latest: BroadcastFieldSnapshot,
+ base: BroadcastFieldSnapshot | null
+): BroadcastFieldSnapshot {
+ const next = { ...agentDraft }
+ for (const field of BROADCAST_FIELDS) {
+ if (!base || !objectsEqual(latest[field], base[field])) {
+ next[field] = latest[field]
+ }
+ }
+ return next
+}
+
+export function editedFields(agentDraft: BroadcastFieldSnapshot, current: BroadcastFieldSnapshot): BroadcastField[] {
+ return BROADCAST_FIELDS.filter((field) => !objectsEqual(agentDraft[field], current[field]))
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 44fb8820deb0..ee99d109b086 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -1,6 +1,7 @@
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -55,6 +56,16 @@ import {
canMoveToDraft,
getBroadcastStatus,
} from './broadcastsLogic'
+import {
+ COMPOSER_DRAFT_PARAM,
+ COMPOSER_DRAFT_VALUE,
+ advanceAgentDraft,
+ broadcastPath,
+ editedFields,
+ loadComposerDraft,
+ saveComposerDraft,
+ snapshotBroadcast,
+} from './broadcastUsage'
export type BroadcastWizardStep = 'recipients' | 'goal' | 'content' | 'schedule' | 'review'
@@ -285,6 +296,9 @@ export interface broadcastWizardLogicActions {
replayDeferredEdit: () => {
value: true
}
+ reportReviewVisit: () => {
+ value: true
+ }
restoreBroadcast: () => {
value: true
}
@@ -447,6 +461,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
nextStep: true,
prevStep: true,
continueStep: true,
+ reportReviewVisit: true,
setName: (name: string) => ({ name }),
saveName: true,
setAudienceProperties: (properties: AnyPropertyFilter[]) => ({ properties }),
@@ -988,6 +1003,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
if (step === 'content') {
actions.ensureDraft()
}
+ actions.reportReviewVisit()
},
nextStep: () => {
// Listeners run after reducers, so this sees the step just navigated to.
@@ -997,6 +1013,46 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
if (values.currentStep === 'content') {
actions.ensureDraft()
}
+ actions.reportReviewVisit()
+ },
+ prevStep: () => {
+ actions.reportReviewVisit()
+ },
+ reportReviewVisit: async (_, breakpoint) => {
+ if (values.currentStep !== 'review') {
+ cache.reviewBlockReported = false
+ return
+ }
+ if (cache.reviewBlockReported) {
+ return
+ }
+ // Senders load after the step renders, so let the blocking issues settle before reading them.
+ await breakpoint(2000)
+ const issues = values.stepValidationErrors.review
+ if (values.currentStep !== 'review' || issues.length === 0 || values.integrationsLoading) {
+ return
+ }
+ cache.reviewBlockReported = true
+ // pinned: analytics event name
+ posthog.capture('broadcast launch blocked', {
+ broadcast_id: values.broadcastId,
+ path: broadcastPath(values.broadcastId),
+ blocking_issues: issues,
+ })
+ },
+ applyExternalEdit: ({ broadcast, base }) => {
+ const composerDraft = loadComposerDraft(broadcast.id)
+ if (!composerDraft) {
+ return
+ }
+ saveComposerDraft(broadcast.id, {
+ agentDraft: advanceAgentDraft(
+ composerDraft.agentDraft,
+ snapshotBroadcast(broadcast),
+ base ? snapshotBroadcast(base) : null
+ ),
+ agentEdits: composerDraft.agentEdits + 1,
+ })
},
ensureDraft: async () => {
// The AI assistant edits the saved broadcast, so the content step needs one to exist even
@@ -1258,6 +1314,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
await saves.whenIdle()
breakpoint()
if (cache.autosaveConflict) {
+ captureLaunchFailed(values.broadcastId, 'edited_elsewhere')
actions.launchBroadcastFinished()
return
}
@@ -1283,6 +1340,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
// it would confirm N recipients and deliver to the first slice. Stop at the step that
// can fix it. Mirrors the guard on the workflow editor's manual trigger.
if (blastRadius.limit != null && blastRadius.affected > blastRadius.limit) {
+ captureLaunchFailed(broadcastId, 'audience_over_limit')
actions.launchBroadcastFinished()
actions.setStep('recipients')
actions.showSavedDraftUrl()
@@ -1347,11 +1405,33 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
// no-op there. Store the activated broadcast so the scene swaps to the read-only summary
// instead of leaving a live send button on a broadcast that already went out.
actions.saveBroadcastFinished(activated)
+ const composerDraft = loadComposerDraft(broadcastId)
+ // pinned: analytics event name
+ posthog.capture('broadcast launched', {
+ broadcast_id: broadcastId,
+ path: broadcastPath(broadcastId),
+ schedule_mode: values.scheduleMode,
+ audience_filter_count: values.audienceProperties.length,
+ has_goal: values.goalEnabled,
+ seconds_since_created: activated
+ ? Math.round((Date.now() - new Date(activated.created_at).getTime()) / 1000)
+ : null,
+ ...(composerDraft
+ ? {
+ edited_fields: editedFields(
+ composerDraft.agentDraft,
+ snapshotBroadcast(buildBroadcastPayload(values))
+ ),
+ agent_edits_after_draft: composerDraft.agentEdits,
+ }
+ : {}),
+ })
actions.loadBatchJobs()
actions.launchBroadcastFinished()
router.actions.push(urls.broadcast(broadcastId))
} catch (error: any) {
if (error instanceof EditedElsewhereError) {
+ captureLaunchFailed(broadcastId, 'edited_elsewhere')
actions.applyExternalEdit(error.latest, values.broadcast)
actions.launchBroadcastFinished()
lemonToast.info(
@@ -1369,6 +1449,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
lemonToast.error('The broadcast is still active but has nothing scheduled. Reload the page.')
}
}
+ captureLaunchFailed(broadcastId, 'error')
actions.launchBroadcastFinished()
lemonToast.error(`Couldn't launch the broadcast: ${error?.detail || error?.message || 'unknown error'}`)
// The launch saved the draft first, so a reload of /broadcasts/new would orphan it.
@@ -1462,19 +1543,25 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.loadBatchJobs()
}
},
- hydrateFromBroadcast: () => {
+ hydrateFromBroadcast: ({ broadcast }) => {
if (values.broadcast?.status !== 'draft') {
return
}
- // A draft just saved from /broadcasts/new carries the step it was on. Otherwise resume at the
- // first incomplete step; complete drafts land on review.
- const { step, ...searchParams } = router.values.searchParams
+ // A draft just saved from /broadcasts/new carries the step it was on, and a composer draft says so.
+ // Otherwise resume at the first incomplete step; complete drafts land on review.
+ const { step, [COMPOSER_DRAFT_PARAM]: from, ...searchParams } = router.values.searchParams
+ if (from === COMPOSER_DRAFT_VALUE && !loadComposerDraft(broadcast.id)) {
+ // What the agent drafted, so the launch can report which fields the person changed.
+ saveComposerDraft(broadcast.id, { agentDraft: snapshotBroadcast(broadcast), agentEdits: 0 })
+ }
if (BROADCAST_WIZARD_STEPS.includes(step)) {
actions.setStep(step)
- router.actions.replace(router.values.location.pathname, searchParams, router.values.hashParams)
} else {
actions.setStep(values.firstInvalidStep ?? 'review')
}
+ if (step !== undefined || from !== undefined) {
+ router.actions.replace(router.values.location.pathname, searchParams, router.values.hashParams)
+ }
},
loadBroadcastFailure: () => {
lemonToast.error("Couldn't load the broadcast. Refresh the page to try again.")
@@ -1490,6 +1577,14 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}),
])
+function captureLaunchFailed(
+ broadcastId: string | null | undefined,
+ reason: 'audience_over_limit' | 'edited_elsewhere' | 'error'
+): void {
+ // pinned: analytics event name
+ posthog.capture('broadcast launch failed', { broadcast_id: broadcastId, path: broadcastPath(broadcastId), reason })
+}
+
function getSaveQueue(cache: Record<string, any>, values: broadcastWizardLogicType['values']): ResourceSaveQueue {
return (cache.saveQueue ??= new ResourceSaveQueue({
resourceType: 'HogFlow',
diff --git a/products/workflows/frontend/Broadcasts/broadcastsFeedbackSurvey.ts b/products/workflows/frontend/Broadcasts/broadcastsFeedbackSurvey.ts
new file mode 100644
index 000000000000..7babac657443
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastsFeedbackSurvey.ts
@@ -0,0 +1,4 @@
+// The api-type survey every broadcasts feedback banner reports to. `feedback_surface` tells the banners apart.
+export const BROADCASTS_FEEDBACK_SURVEY_ID = '01a0ce6c-f291-0000-092b-8677d994599c'
+export const BROADCASTS_FEEDBACK_RATING_QUESTION_ID = 'a5e6e02a-174b-41a7-8da6-7fa1595ac763'
+export const BROADCASTS_FEEDBACK_TEXT_QUESTION_ID = '1e3e0368-135f-485c-bf46-ddaac558e879'
diff --git a/products/workflows/frontend/Broadcasts/newBroadcastHandoff.ts b/products/workflows/frontend/Broadcasts/newBroadcastHandoff.ts
index c082fb93dc73..868dc607d2d7 100644
--- a/products/workflows/frontend/Broadcasts/newBroadcastHandoff.ts
+++ b/products/workflows/frontend/Broadcasts/newBroadcastHandoff.ts
@@ -1,9 +1,13 @@
+import { combineUrl } from 'kea-router'
+
import { ApiConfig } from 'lib/api'
import type { AiFirstHandoffLogicProps } from 'scenes/max/aiFirstCreate/aiFirstHandoffLogic'
import { urls } from 'scenes/urls'
import { hogFlowsList } from 'products/workflows/frontend/generated/api'
+import { COMPOSER_DRAFT_PARAM, COMPOSER_DRAFT_VALUE } from './broadcastUsage'
+
// pinned: MCP tool name from products/workflows/mcp/tools.yaml
const CREATE_BROADCAST_TOOL = 'broadcasts-create'
@@ -31,7 +35,7 @@ export async function findCreatedBroadcastId(name: unknown): Promise<string | nu
export const NEW_BROADCAST_HANDOFF: AiFirstHandoffLogicProps = {
toolName: CREATE_BROADCAST_TOOL,
findCreatedId: (innerInput) => findCreatedBroadcastId(innerInput?.name),
- urlFor: (id) => urls.broadcast(id),
+ urlFor: (id) => combineUrl(urls.broadcast(id), { [COMPOSER_DRAFT_PARAM]: COMPOSER_DRAFT_VALUE }).url,
notOpenedMessage: 'Your broadcast was created, but it could not be opened. Find it in the broadcasts list.',
// pinned: analytics event names
eventPrefix: 'broadcast ai composer',