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): move a new broadcast onto its own URL once its draft is saved (#107557)

Daniel Marchuke1fcc285a1f9
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index 4174a251bf7f..6bfb51668b01 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -1,3 +1,4 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
@@ -6,7 +7,7 @@ import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types
import type { HogFlowApi } from 'products/workflows/frontend/generated/api.schemas'
-import { broadcastWizardLogic } from './broadcastWizardLogic'
+import { DEFAULT_BROADCAST_EMAIL, broadcastWizardLogic } from './broadcastWizardLogic'
const LOCAL_AUDIENCE: AnyPropertyFilter[] = [
{ key: 'plan', value: ['pro'], operator: PropertyOperator.Exact, type: PropertyFilterType.Person },
@@ -56,14 +57,47 @@ function savedBroadcast(overrides: { name: string; subject: string; updatedAt: s
describe('broadcastWizardLogic', () => {
let logic: ReturnType<typeof broadcastWizardLogic.build>
let latest: HogFlowApi
+ let releaseCreate: () => void
+ let patchedSubjects: string[]
+ let holdPatch: Promise<void> | null
+ let onPatchStarted: (() => void) | null
+ let failPatches: number
beforeEach(() => {
+ patchedSubjects = []
+ holdPatch = null
+ onPatchStarted = null
+ failPatches = 0
+ const created = new Promise<void>((resolve) => {
+ releaseCreate = resolve
+ })
useMocks({
get: {
'/api/projects/:team_id/hog_flows/:id/': () => [200, latest],
},
post: {
'/api/projects/:team_id/hog_flows/user_blast_radius/': () => [200, { affected: 0, total: 0 }],
+ '/api/projects/:team_id/hog_flows/': async () => {
+ await created
+ return [201, savedBroadcast({ name: '', subject: '', updatedAt: '2026-09-24T10:00:00Z' })]
+ },
+ },
+ patch: {
+ '/api/projects/:team_id/hog_flows/:id/': async ({ request }) => {
+ const body = (await request.json()) as { actions: any[] }
+ const subject = body.actions.find((action) => action.type === 'function_email').config.inputs.email
+ .value.subject
+ if (failPatches > 0) {
+ failPatches -= 1
+ return [500, { detail: 'Simulated outage' }]
+ }
+ patchedSubjects.push(subject)
+ onPatchStarted?.()
+ if (holdPatch) {
+ await holdPatch
+ }
+ return [200, savedBroadcast({ name: '', subject, updatedAt: '2026-09-24T10:00:05Z' })]
+ },
},
})
initKeaTests()
@@ -110,4 +144,157 @@ describe('broadcastWizardLogic', () => {
})
}
)
+
+ it('moves a new broadcast onto its draft URL once the draft is created', async () => {
+ router.actions.push('/broadcasts/new')
+ await expectLogic(logic, () => {
+ logic.actions.setStep('content')
+ releaseCreate()
+ }).toDispatchActions(['draftAutosaved', 'showSavedDraftUrl'])
+
+ expect(router.values.location.pathname).toContain('/broadcasts/broadcast-1')
+ expect(router.values.searchParams).toEqual({ step: 'content' })
+ })
+
+ it('saves an email edit made while the draft is created before leaving /broadcasts/new', async () => {
+ router.actions.push('/broadcasts/new')
+ logic.actions.setStep('content')
+ logic.actions.setEmail({ ...DEFAULT_BROADCAST_EMAIL, subject: 'Typed during the create' })
+ releaseCreate()
+
+ await expectLogic(logic).toDispatchActions(['draftAutosaved', 'draftAutosaved'])
+ await expectLogic(logic).toDispatchActions(['showSavedDraftUrl']).toFinishAllListeners()
+
+ expect(patchedSubjects).toEqual(['Typed during the create'])
+ expect(router.values.location.pathname).toContain('/broadcasts/broadcast-1')
+ })
+
+ it('retries a failed email autosave and moves to the draft URL once it saves', async () => {
+ router.actions.push('/broadcasts/new')
+ logic.actions.setStep('content')
+ releaseCreate()
+ await expectLogic(logic).toDispatchActions(['draftAutosaved', 'showSavedDraftUrl'])
+ router.actions.push('/broadcasts/new')
+ failPatches = 1
+
+ logic.actions.setEmail({ ...DEFAULT_BROADCAST_EMAIL, subject: 'Saved on the retry' })
+
+ await expectLogic(logic)
+ .toDispatchActions(['setEmail', 'draftAutosaved', 'showSavedDraftUrl'])
+ .toFinishAllListeners()
+ expect(patchedSubjects).toEqual(['Saved on the retry'])
+ expect(router.values.location.pathname).toContain('/broadcasts/broadcast-1')
+ })
+
+ it('moves to the draft URL when Continue saves an email edit still waiting on its autosave', async () => {
+ router.actions.push('/broadcasts/new')
+ logic.actions.setStep('content')
+ releaseCreate()
+ await expectLogic(logic).toDispatchActions(['draftAutosaved', 'showSavedDraftUrl'])
+ router.actions.push('/broadcasts/new')
+
+ logic.actions.setEmail({
+ ...DEFAULT_BROADCAST_EMAIL,
+ from: { ...DEFAULT_BROADCAST_EMAIL.from, integrationId: 1 },
+ subject: 'Typed before Continue',
+ html: '<p>Hi</p>',
+ })
+ await expectLogic(logic, () => {
+ logic.actions.continueStep()
+ }).toDispatchActions(['nextStep', 'showSavedDraftUrl'])
+
+ expect(patchedSubjects).toEqual(['Typed before Continue'])
+ expect(router.values.location.pathname).toContain('/broadcasts/broadcast-1')
+ })
+
+ it('keeps an email edit made while Continue is saving and moves to the draft URL after it saves', async () => {
+ const validEmail = {
+ ...DEFAULT_BROADCAST_EMAIL,
+ from: { ...DEFAULT_BROADCAST_EMAIL.from, integrationId: 1 },
+ html: '<p>Hi</p>',
+ }
+ router.actions.push('/broadcasts/new')
+ logic.actions.setStep('content')
+ releaseCreate()
+ await expectLogic(logic).toDispatchActions(['draftAutosaved'])
+ logic.actions.setEmail({ ...validEmail, subject: 'Saved by Continue' })
+ await expectLogic(logic).toDispatchActions(['draftAutosaved', 'showSavedDraftUrl'])
+ router.actions.push('/broadcasts/new')
+ patchedSubjects = []
+
+ let releasePatch: () => void = () => {}
+ holdPatch = new Promise((resolve) => {
+ releasePatch = resolve
+ })
+ const patchStarted = new Promise<void>((resolve) => {
+ onPatchStarted = resolve
+ })
+ logic.actions.continueStep()
+ await patchStarted
+ holdPatch = null
+ logic.actions.setEmail({ ...validEmail, subject: 'Typed during Continue' })
+ releasePatch()
+
+ await expectLogic(logic).toDispatchActions(['nextStep', 'draftAutosaved', 'showSavedDraftUrl'])
+ expect(patchedSubjects).toEqual(['Saved by Continue', 'Typed during Continue'])
+ expect(router.values.location.pathname).toContain('/broadcasts/broadcast-1')
+ })
+
+ it.each([
+ { stop: 'the audience is over the batch limit', affected: 60000, editedElsewhere: false, step: 'recipients' },
+ { stop: 'the draft was edited elsewhere', affected: 10, editedElsewhere: true, step: 'review' },
+ ])(
+ 'moves to the draft URL when a launch from /broadcasts/new stops because $stop',
+ async ({ affected, editedElsewhere, step }) => {
+ latest = savedBroadcast({
+ name: '',
+ subject: 'Edited by the assistant',
+ updatedAt: editedElsewhere ? '2026-09-24T10:00:09Z' : '2026-09-24T10:00:00Z',
+ })
+ useMocks({
+ get: {
+ '/api/projects/:team_id/integrations/': {
+ results: [{ id: 1, kind: 'email', config: { verified: true } }],
+ count: 1,
+ },
+ },
+ post: {
+ '/api/projects/:team_id/hog_flows/user_blast_radius/': () => [
+ 200,
+ { affected, total: affected, limit: 50000, dedupe_key: 'email', confirm_token: 'token' },
+ ],
+ },
+ })
+ router.actions.push('/broadcasts/new')
+ logic.actions.setEmail({
+ ...DEFAULT_BROADCAST_EMAIL,
+ from: { ...DEFAULT_BROADCAST_EMAIL.from, integrationId: 1 },
+ subject: 'Launch over the limit',
+ html: '<p>Hi</p>',
+ })
+ releaseCreate()
+
+ logic.actions.setStep('review')
+ await expectLogic(logic, () => {
+ logic.actions.launchBroadcast()
+ }).toDispatchActions(['saveBroadcastFinished', 'launchBroadcastFinished', 'showSavedDraftUrl'])
+
+ expect(router.values.location.pathname).toContain('/broadcasts/broadcast-1')
+ expect(router.values.searchParams).toEqual({ step })
+ }
+ )
+
+ it('resumes a saved draft on the step in its URL and drops the step from the URL', async () => {
+ latest = savedBroadcast({ name: 'Spring sale', subject: '', updatedAt: '2026-09-24T10:00:00Z' })
+ router.actions.push('/broadcasts/broadcast-1', { step: 'content', other: 'kept' })
+ const draftLogic = broadcastWizardLogic({ id: 'broadcast-1' })
+
+ await expectLogic(draftLogic, () => {
+ draftLogic.mount()
+ })
+ .toDispatchActions(['hydrateFromBroadcast', 'setStep'])
+ .toMatchValues({ currentStep: 'content' })
+ expect(router.values.searchParams).toEqual({ other: 'kept' })
+ draftLogic.unmount()
+ })
})
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index dce1f61641d2..08be6cbf6f15 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -57,6 +57,9 @@ import {
export type BroadcastWizardStep = 'recipients' | 'goal' | 'content' | 'schedule' | 'review'
+const EMAIL_AUTOSAVE_RETRIES = 3
+const EMAIL_AUTOSAVE_RETRY_MS = 2000
+
export const BROADCAST_WIZARD_STEPS: BroadcastWizardStep[] = ['recipients', 'goal', 'content', 'schedule', 'review']
export type BroadcastScheduleMode = 'now' | 'later' | 'recurring'
@@ -337,6 +340,9 @@ export interface broadcastWizardLogicActions {
setSummaryTab: (tab: BroadcastSummaryTab) => {
tab: BroadcastSummaryTab
}
+ showSavedDraftUrl: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -448,6 +454,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
hydrateFromBroadcast: (broadcast: HogFlowApi) => ({ broadcast }),
saveBroadcastFinished: (broadcast: HogFlowApi | null) => ({ broadcast }),
ensureDraft: true,
+ showSavedDraftUrl: true,
draftAutosaved: (broadcast: HogFlowApi) => ({ broadcast }),
applyExternalEdit: (broadcast: HogFlowApi, base: HogFlowApi | null) => ({ broadcast, base }),
replayDeferredEdit: true,
@@ -994,21 +1001,30 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
await saves.run(async () => {
actions.draftAutosaved(await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any))
})
+ actions.showSavedDraftUrl()
} catch (error: any) {
lemonToast.error(`Couldn't save the broadcast: ${error?.detail || error?.message || 'unknown error'}`)
}
},
+ showSavedDraftUrl: () => {
+ // On /broadcasts/new a reload starts over and orphans the saved draft. The new URL remounts the
+ // wizard from the saved copy, so an unsaved email edit moves it only once its autosave lands.
+ if (
+ props.id === 'new' &&
+ !cache.emailEditPending &&
+ values.broadcastId &&
+ values.broadcast?.status === 'draft'
+ ) {
+ router.actions.replace(urls.broadcast(values.broadcastId), { step: values.currentStep })
+ }
+ },
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.
// The editor is live while the draft is still being created, so wait for it before the
// draft check. Otherwise edits made during the create never reach the saved draft.
- const saves = getSaveQueue(cache, values)
- await saves.whenIdle()
- if (values.currentStep !== 'content' || values.broadcast?.status !== 'draft') {
- return
- }
- // Overlapping autosaves share the pending flag, so only the latest edit may clear it.
+ // Overlapping autosaves share the pending flag, so only the latest edit may clear it. It is set
+ // before the wait, so a draft created meanwhile does not leave /broadcasts/new without this edit.
const generation = (cache.emailEditGeneration = (cache.emailEditGeneration ?? 0) + 1)
const clearPending = (): void => {
if (cache.emailEditGeneration === generation) {
@@ -1016,14 +1032,17 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}
}
cache.emailEditPending = true
+ // Read before the wait: a Continue in flight moves the step on, but its save may not carry this edit.
+ const editedOnContent = values.currentStep === 'content'
+ const saves = getSaveQueue(cache, values)
+ await saves.whenIdle()
+ if (!editedOnContent || values.broadcast?.status !== 'draft') {
+ clearPending()
+ return
+ }
await breakpoint(1000)
- if (
- !values.broadcastId ||
- !values.currentProjectId ||
- values.currentStep !== 'content' ||
- values.broadcast?.status !== 'draft'
- ) {
- // Continue or Launch saves this edit instead.
+ if (!values.broadcastId || !values.currentProjectId || values.broadcast?.status !== 'draft') {
+ // Launch saves this edit instead.
clearPending()
return
}
@@ -1035,14 +1054,23 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.draftAutosaved(await saveWithoutClobbering(projectId, values.broadcastId!, values))
clearPending()
})
+ cache.emailAutosaveRetries = 0
+ actions.showSavedDraftUrl()
} catch (error: any) {
if (error instanceof EditedElsewhereError) {
clearPending()
cache.autosaveConflict = true
actions.applyExternalEdit(error.latest, values.broadcast)
lemonToast.info(EDITED_ELSEWHERE_MESSAGE)
+ } else if ((cache.emailAutosaveRetries ?? 0) < EMAIL_AUTOSAVE_RETRIES) {
+ // The edit stays pending, which keeps a new draft on /broadcasts/new until it saves, so retry
+ // a failed save rather than wait for Continue. Continue saves it and reports a lasting failure.
+ cache.emailAutosaveRetries = (cache.emailAutosaveRetries ?? 0) + 1
+ actions.replayDeferredEdit()
+ await breakpoint(EMAIL_AUTOSAVE_RETRY_MS)
+ actions.setEmail(values.email)
+ return
}
- // Otherwise Continue saves the same state and reports the failure there.
}
actions.replayDeferredEdit()
},
@@ -1132,14 +1160,21 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
return
}
const projectId = String(values.currentProjectId)
+ let savedEditGeneration: number | undefined
try {
- const saved = await saves.run(() =>
- values.broadcastId
+ const saved = await saves.run(() => {
+ savedEditGeneration = cache.emailEditGeneration
+ return values.broadcastId
? saveWithoutClobbering(projectId, values.broadcastId, values)
: hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)
- )
+ })
actions.saveBroadcastFinished(saved)
+ // This save carried the email edits made before it started. A later one keeps its own autosave.
+ if (cache.emailEditGeneration === savedEditGeneration) {
+ cache.emailEditPending = false
+ }
actions.nextStep()
+ actions.showSavedDraftUrl()
} catch (error: any) {
actions.saveBroadcastFinished(null)
if (error instanceof EditedElsewhereError) {
@@ -1196,6 +1231,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
if (blastRadius.limit != null && blastRadius.affected > blastRadius.limit) {
actions.launchBroadcastFinished()
actions.setStep('recipients')
+ actions.showSavedDraftUrl()
lemonToast.error(
`This audience is above the project's batch limit of ${humanFriendlyNumber(
blastRadius.limit
@@ -1267,6 +1303,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
lemonToast.info(
'This email changed while you were editing it. Review the latest version, then launch.'
)
+ actions.showSavedDraftUrl()
return
}
if (activated && broadcastId) {
@@ -1280,6 +1317,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}
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.
+ actions.showSavedDraftUrl()
}
},
moveToDraft: async () => {
@@ -1353,8 +1392,16 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}
},
hydrateFromBroadcast: () => {
- // Resume a draft at the first incomplete step; complete drafts land on review.
- if (values.broadcast?.status === 'draft') {
+ 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
+ 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')
}
},