Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): let PostHog AI write a broadcast's email on the content step (#105625)

Daniel Marchukb0a709bb6e91
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
new file mode 100644
index 000000000000..4174a251bf7f
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -0,0 +1,113 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import type { HogFlowApi } from 'products/workflows/frontend/generated/api.schemas'
+
+import { broadcastWizardLogic } from './broadcastWizardLogic'
+
+const LOCAL_AUDIENCE: AnyPropertyFilter[] = [
+ { key: 'plan', value: ['pro'], operator: PropertyOperator.Exact, type: PropertyFilterType.Person },
+]
+
+function savedBroadcast(overrides: { name: string; subject: string; updatedAt: string }): HogFlowApi {
+ return {
+ id: 'broadcast-1',
+ name: overrides.name,
+ version: 1,
+ status: 'draft',
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: { id: 1, uuid: 'user-1', email: '[email protected]', hedgehog_config: null },
+ updated_at: overrides.updatedAt,
+ trigger: { type: 'batch', filters: { properties: [] } },
+ conversion: null,
+ email_sending_rate_limit: null,
+ actions: [
+ {
+ id: 'trigger_node',
+ name: 'Trigger',
+ type: 'trigger',
+ config: { type: 'batch', filters: { properties: [] } },
+ },
+ {
+ id: 'email_node',
+ name: 'Email',
+ type: 'function_email',
+ config: { inputs: { email: { value: { subject: overrides.subject } } } },
+ },
+ ],
+ abort_action: null,
+ billable_action_types: [],
+ schedules: [],
+ user_access_level: 'editor',
+ draft: null,
+ draft_updated_at: null,
+ action_redirects: null,
+ email_sending_paused_at: null,
+ email_sending_paused_reason: '',
+ email_sending_paused_by: '',
+ email_sending_pause_requires_support: false,
+ email_sending_resumed_at: null,
+ }
+}
+
+describe('broadcastWizardLogic', () => {
+ let logic: ReturnType<typeof broadcastWizardLogic.build>
+ let latest: HogFlowApi
+
+ beforeEach(() => {
+ 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 }],
+ },
+ })
+ initKeaTests()
+ logic = broadcastWizardLogic({ id: 'new' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ test.each([
+ { edited: 'only the email', latestName: 'Spring sale', expectedName: 'Spring sale, final' },
+ { edited: 'the name too', latestName: 'Spring promo', expectedName: 'Spring promo' },
+ ])(
+ 'an edit saved elsewhere that changed $edited keeps the unsaved local fields it did not change',
+ async ({ latestName, expectedName }) => {
+ const base = savedBroadcast({ name: 'Spring sale', subject: '', updatedAt: '2026-09-24T10:00:00Z' })
+ latest = savedBroadcast({
+ name: latestName,
+ subject: 'Our spring sale starts today',
+ updatedAt: '2026-09-24T10:00:05Z',
+ })
+ logic.actions.draftAutosaved(base)
+ logic.actions.setName('Spring sale, final')
+ logic.actions.setAudienceProperties(LOCAL_AUDIENCE)
+
+ await expectLogic(logic, () => {
+ logic.actions.resourceEdited({
+ notification_type: 'resource_edited',
+ team_id: 1,
+ resource_type: 'HogFlow',
+ resource_id: base.id,
+ updated_at: latest.updated_at,
+ actor_user_id: null,
+ })
+ })
+ .toDispatchActions(['applyExternalEdit'])
+ .toMatchValues({
+ broadcast: latest,
+ name: expectedName,
+ audienceProperties: LOCAL_AUDIENCE,
+ email: expect.objectContaining({ subject: 'Our spring sale starts today' }),
+ })
+ }
+ )
+})
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index af7c6be7618e..dce1f61641d2 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -8,13 +8,15 @@ import { dayjs } from 'lib/dayjs'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { AnyPropertyFilter, Breadcrumb, IntegrationType, TeamPublicType, TeamType } from '~/types'
+import { AnyPropertyFilter, Breadcrumb, IntegrationType, ResourceEditedEvent, TeamPublicType, TeamType } from '~/types'
+import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'
import {
hogFlowsBatchJobsCancelCreate,
hogFlowsBatchJobsCreate,
@@ -44,6 +46,7 @@ import {
parseRRuleToState,
stateToRRule,
} from '../Workflows/hogflows/steps/components/rrule-helpers'
+import { ResourceSaveQueue } from '../Workflows/resourceSaveQueue'
import {
BroadcastStatus,
StoppableBroadcast,
@@ -94,7 +97,7 @@ export const DEFAULT_BROADCAST_CONVERSION: HogFlowConversionApi = {
// pinned: action node ids referenced by saved broadcasts — renaming breaks resume of existing drafts
const TRIGGER_ACTION_ID = 'trigger_node'
-const EMAIL_ACTION_ID = 'email_node'
+export const EMAIL_ACTION_ID = 'email_node'
const EXIT_ACTION_ID = 'exit_node'
function findAction(broadcast: HogFlowApi, type: string): Record<string, any> | undefined {
@@ -102,6 +105,18 @@ function findAction(broadcast: HogFlowApi, type: string): Record<string, any> |
return flowActions.find((action) => action.type === type)
}
+function readAudience(broadcast: HogFlowApi): AnyPropertyFilter[] | undefined {
+ return findAction(broadcast, 'trigger')?.config?.filters?.properties as AnyPropertyFilter[] | undefined
+}
+
+// Compares two server copies, so derived keys the server adds (such as bytecode) match on both sides.
+// A field the other edit changed must follow the saved copy, or the next save sends the stale value back
+// under a fresh base and overwrites that edit without a conflict. A field it did not change keeps the
+// local value, so an unsaved local edit (a rename, an audience change) is not lost.
+function changedElsewhere<T>(latest: HogFlowApi, base: HogFlowApi | null, read: (broadcast: HogFlowApi) => T): boolean {
+ return !base || !objectsEqual(read(latest), read(base))
+}
+
export type BroadcastSummaryTab = 'overview' | 'content' | 'runs'
export interface BroadcastWizardLogicProps {
@@ -121,6 +136,7 @@ export interface broadcastWizardLogicValues {
blastRadiusLoading: boolean
breadcrumbs: Breadcrumb[]
broadcast: HogFlowApi | null
+ broadcastAsWorkflow: HogFlowApi | null
broadcastId: string | null
broadcastLoading: boolean
canEditContent: boolean
@@ -159,18 +175,34 @@ export interface broadcastWizardLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastWizardLogicActions {
+ resourceEdited: (event: ResourceEditedEvent) => {
+ event: ResourceEditedEvent
+ } // resourceEditedLogic
+ applyExternalEdit: (
+ broadcast: HogFlowApi,
+ base: HogFlowApi | null
+ ) => {
+ base: HogFlowApi | null
+ broadcast: HogFlowApi
+ }
collapseRun: (runId: string) => {
runId: string
}
continueStep: () => {
value: true
}
+ draftAutosaved: (broadcast: HogFlowApi) => {
+ broadcast: HogFlowApi
+ }
duplicateBroadcast: () => {
value: true
}
duplicateBroadcastFinished: () => {
value: true
}
+ ensureDraft: () => {
+ value: true
+ }
expandRun: (runId: string) => {
runId: string
}
@@ -240,6 +272,9 @@ export interface broadcastWizardLogicActions {
prevStep: () => {
value: true
}
+ replayDeferredEdit: () => {
+ value: true
+ }
saveBroadcastFinished: (broadcast: HogFlowApi | null) => {
broadcast: HogFlowApi | null
}
@@ -308,6 +343,15 @@ export interface broadcastWizardLogicActions {
export interface broadcastWizardLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ broadcastAsWorkflow: (
+ broadcast: HogFlowApi | null,
+ name: string,
+ audienceProperties: AnyPropertyFilter[],
+ goalEnabled: boolean,
+ conversion: HogFlowConversionApi,
+ email: BroadcastEmailValue,
+ emailRateLimit: HogFlowEmailSendingRateLimitApi | null
+ ) => HogFlowApi | null
broadcastId: (broadcast: HogFlowApi | null, id: string) => string | null
expandedRunIds: (expandedRunOverride: string[] | null, batchJobs: HogFlowBatchJobApi[]) => string[]
canMoveToDraft: (
@@ -376,6 +420,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
integrationsLogic,
['integrations', 'integrationsLoading'],
],
+ actions: [resourceEditedLogic, ['resourceEdited']],
})),
actions({
@@ -402,6 +447,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
setRecurringRepeating: (repeating: boolean) => ({ repeating }),
hydrateFromBroadcast: (broadcast: HogFlowApi) => ({ broadcast }),
saveBroadcastFinished: (broadcast: HogFlowApi | null) => ({ broadcast }),
+ ensureDraft: true,
+ draftAutosaved: (broadcast: HogFlowApi) => ({ broadcast }),
+ applyExternalEdit: (broadcast: HogFlowApi, base: HogFlowApi | null) => ({ broadcast, base }),
+ replayDeferredEdit: true,
expandRun: (runId: string) => ({ runId }),
collapseRun: (runId: string) => ({ runId }),
setExpandedRunOverride: (runIds: string[]) => ({ runIds }),
@@ -457,6 +506,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
broadcast: {
saveBroadcastFinished: (state: HogFlowApi | null, { broadcast }: { broadcast: HogFlowApi | null }) =>
broadcast ?? state,
+ draftAutosaved: (_, { broadcast }) => broadcast,
+ applyExternalEdit: (_, { broadcast }) => broadcast,
},
// Null until the sender expands or collapses a run; until then the latest run shows open.
summaryTab: [
@@ -490,6 +541,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
{
setName: (_, { name }) => name,
hydrateFromBroadcast: (state, { broadcast }) => broadcast.name || state,
+ applyExternalEdit: (state, { broadcast, base }) =>
+ changedElsewhere(broadcast, base, (b) => b.name) ? broadcast.name || state : state,
},
],
audienceProperties: [
@@ -500,6 +553,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
const trigger = findAction(broadcast, 'trigger')
return (trigger?.config?.filters?.properties as AnyPropertyFilter[]) ?? state
},
+ applyExternalEdit: (state, { broadcast, base }) =>
+ changedElsewhere(broadcast, base, readAudience) ? (readAudience(broadcast) ?? state) : state,
},
],
goalEnabled: [
@@ -513,6 +568,11 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}
return (conversion.events?.length ?? 0) > 0 || (conversion.filters?.length ?? 0) > 0
},
+ applyExternalEdit: (state, { broadcast, base }) =>
+ changedElsewhere(broadcast, base, (b) => b.conversion)
+ ? (broadcast.conversion?.events?.length ?? 0) > 0 ||
+ (broadcast.conversion?.filters?.length ?? 0) > 0
+ : state,
},
],
conversion: [
@@ -521,6 +581,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
setConversion: (_, { conversion }) => conversion,
hydrateFromBroadcast: (state, { broadcast }) =>
broadcast.conversion ? { ...DEFAULT_BROADCAST_CONVERSION, ...broadcast.conversion } : state,
+ applyExternalEdit: (state, { broadcast, base }) =>
+ changedElsewhere(broadcast, base, (b) => b.conversion) && broadcast.conversion
+ ? { ...DEFAULT_BROADCAST_CONVERSION, ...broadcast.conversion }
+ : state,
},
],
emailRateLimit: [
@@ -528,12 +592,20 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
{
setEmailRateLimit: (_, { emailRateLimit }) => emailRateLimit,
hydrateFromBroadcast: (state, { broadcast }) => broadcast.email_sending_rate_limit ?? state,
+ applyExternalEdit: (state, { broadcast, base }) =>
+ changedElsewhere(broadcast, base, (b) => b.email_sending_rate_limit)
+ ? (broadcast.email_sending_rate_limit ?? null)
+ : state,
},
],
email: [
DEFAULT_BROADCAST_EMAIL,
{
setEmail: (_, { email }) => email,
+ applyExternalEdit: (state, { broadcast }) => {
+ const value = findAction(broadcast, 'function_email')?.config?.inputs?.email?.value
+ return value ? { ...DEFAULT_BROADCAST_EMAIL, ...value } : state
+ },
hydrateFromBroadcast: (state, { broadcast }) => {
const emailAction = findAction(broadcast, 'function_email')
const value = emailAction?.config?.inputs?.email?.value
@@ -643,6 +715,35 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
})),
selectors({
+ // The saved broadcast overlaid with the editor's unsaved state, in the shape the AI assistant reads.
+ broadcastAsWorkflow: [
+ (s) => [s.broadcast, s.name, s.audienceProperties, s.goalEnabled, s.conversion, s.email, s.emailRateLimit],
+ (
+ broadcast: HogFlowApi | null,
+ name: string,
+ audienceProperties: AnyPropertyFilter[],
+ goalEnabled: boolean,
+ conversion: HogFlowConversionApi,
+ email: BroadcastEmailValue,
+ emailRateLimit: HogFlowEmailSendingRateLimitApi | null
+ ): HogFlowApi | null =>
+ broadcast
+ ? ({
+ ...broadcast,
+ ...buildBroadcastPayload({
+ name,
+ audienceProperties,
+ goalEnabled,
+ conversion,
+ email,
+ emailRateLimit,
+ // A workflow shaped like a broadcast keeps its own step ids in the agent's view.
+ broadcast,
+ }),
+ status: broadcast.status,
+ } as HogFlowApi)
+ : null,
+ ],
broadcastId: [
(s, p) => [s.broadcast, p.id],
(broadcast: HogFlowApi | null, id: string): string | null => broadcast?.id ?? (id !== 'new' ? id : null),
@@ -843,7 +944,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, props, cache }) => ({
expandRun: ({ runId }) => {
actions.setExpandedRunOverride([...values.expandedRunIds.filter((id) => id !== runId), runId])
},
@@ -860,12 +961,130 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
// A fresh preview mints the confirm token launch needs and shows an up-to-date count.
actions.loadBlastRadius()
}
+ if (step === 'content') {
+ actions.ensureDraft()
+ }
},
nextStep: () => {
// Listeners run after reducers, so this sees the step just navigated to.
if (values.currentStep === 'review') {
actions.loadBlastRadius()
}
+ if (values.currentStep === 'content') {
+ actions.ensureDraft()
+ }
+ },
+ ensureDraft: async () => {
+ // The AI assistant edits the saved broadcast, so the content step needs one to exist even
+ // when the stepper skipped past the Continue that would have created it. A Continue or launch
+ // save still in flight creates the draft itself, so a create here would make a second one.
+ const saves = getSaveQueue(cache, values)
+ if (
+ values.broadcastId ||
+ saves.inFlight > 0 ||
+ values.saving ||
+ values.launching ||
+ props.id !== 'new' ||
+ !values.currentProjectId
+ ) {
+ return
+ }
+ const projectId = String(values.currentProjectId)
+ try {
+ await saves.run(async () => {
+ actions.draftAutosaved(await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any))
+ })
+ } catch (error: any) {
+ lemonToast.error(`Couldn't save the broadcast: ${error?.detail || error?.message || 'unknown error'}`)
+ }
+ },
+ 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.
+ const generation = (cache.emailEditGeneration = (cache.emailEditGeneration ?? 0) + 1)
+ const clearPending = (): void => {
+ if (cache.emailEditGeneration === generation) {
+ cache.emailEditPending = false
+ }
+ }
+ cache.emailEditPending = true
+ await breakpoint(1000)
+ if (
+ !values.broadcastId ||
+ !values.currentProjectId ||
+ values.currentStep !== 'content' ||
+ values.broadcast?.status !== 'draft'
+ ) {
+ // Continue or Launch saves this edit instead.
+ clearPending()
+ return
+ }
+ const projectId = String(values.currentProjectId)
+ try {
+ // Queued behind any save still in flight, and fenced on the copy that save wrote, so the
+ // assistant's edit between two keystrokes comes back as a conflict instead of being lost.
+ await saves.run(async () => {
+ actions.draftAutosaved(await saveWithoutClobbering(projectId, values.broadcastId!, values))
+ clearPending()
+ })
+ } catch (error: any) {
+ if (error instanceof EditedElsewhereError) {
+ clearPending()
+ cache.autosaveConflict = true
+ actions.applyExternalEdit(error.latest, values.broadcast)
+ lemonToast.info(EDITED_ELSEWHERE_MESSAGE)
+ }
+ // Otherwise Continue saves the same state and reports the failure there.
+ }
+ actions.replayDeferredEdit()
+ },
+ saveBroadcastFinished: () => {
+ actions.replayDeferredEdit()
+ },
+ launchBroadcastFinished: () => {
+ actions.replayDeferredEdit()
+ },
+ replayDeferredEdit: () => {
+ const deferred = getSaveQueue(cache, values).takeDeferred()
+ if (deferred) {
+ actions.resourceEdited(deferred)
+ }
+ },
+ resourceEdited: async ({ event }, breakpoint) => {
+ const broadcast = values.broadcast
+ if (
+ !broadcast ||
+ broadcast.status !== 'draft' ||
+ !values.currentProjectId ||
+ getSaveQueue(cache, values).classify(event) !== 'external'
+ ) {
+ return
+ }
+ await breakpoint(200)
+ const fresh = await hogFlowsRetrieve(String(values.currentProjectId), broadcast.id).catch(() => null)
+ breakpoint()
+ if (!fresh) {
+ lemonToast.error("Couldn't load the latest version of the broadcast. Reload the page to see it.")
+ return
+ }
+ // A save can land while the fetch runs. Do not replace that newer state with an older copy.
+ if (values.broadcast && !dayjs(fresh.updated_at).isAfter(dayjs(values.broadcast.updated_at))) {
+ return
+ }
+ if (cache.emailEditPending) {
+ // The saved version wins, as in the workflow editor, but not without saying so.
+ cache.emailEditPending = false
+ lemonToast.info(EDITED_ELSEWHERE_MESSAGE)
+ }
+ actions.applyExternalEdit(fresh, values.broadcast)
},
setSendAtFromPicker: ({ pickerDate }) => {
if (!pickerDate) {
@@ -896,31 +1115,44 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.setRecurringStartsAt(dayjs.tz(wallClock, timezone).toISOString())
}
},
- continueStep: async () => {
+ continueStep: async (_, breakpoint) => {
if (values.currentStepHasErrors || !values.currentProjectId) {
actions.saveBroadcastFinished(null)
return
}
+ // A draft create or autosave still in flight must land first: the create so this doesn't make
+ // a second draft, the autosave so a conflict it found stops this save.
+ cache.autosaveConflict = false
+ const saves = getSaveQueue(cache, values)
+ await saves.whenIdle()
+ breakpoint()
+ if (cache.autosaveConflict) {
+ // That autosave loaded an edit made elsewhere and said so. Let the user review it first.
+ actions.saveBroadcastFinished(null)
+ return
+ }
const projectId = String(values.currentProjectId)
try {
- let saved: HogFlowApi
- if (!values.broadcastId) {
- saved = await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)
- } else {
- saved = await hogFlowsPartialUpdate(
- projectId,
- values.broadcastId,
- buildBroadcastPayload(values) as any
- )
- }
+ const saved = await saves.run(() =>
+ values.broadcastId
+ ? saveWithoutClobbering(projectId, values.broadcastId, values)
+ : hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)
+ )
actions.saveBroadcastFinished(saved)
actions.nextStep()
} catch (error: any) {
actions.saveBroadcastFinished(null)
+ if (error instanceof EditedElsewhereError) {
+ actions.applyExternalEdit(error.latest, values.broadcast)
+ lemonToast.info(
+ 'This email changed while you were editing it. Review the latest version, then continue.'
+ )
+ return
+ }
lemonToast.error(`Couldn't save the broadcast: ${error?.detail || error?.message || 'unknown error'}`)
}
},
- launchBroadcast: async () => {
+ launchBroadcast: async (_, breakpoint) => {
if (!values.currentProjectId) {
actions.launchBroadcastFinished()
return
@@ -931,22 +1163,26 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
return
}
const projectId = String(values.currentProjectId)
+ // Same ordering as Continue: a save that trails the content step must land first.
+ cache.autosaveConflict = false
+ const saves = getSaveQueue(cache, values)
+ await saves.whenIdle()
+ breakpoint()
+ if (cache.autosaveConflict) {
+ actions.launchBroadcastFinished()
+ return
+ }
let broadcastId = values.broadcastId
let activated: HogFlowApi | null = null
try {
// Save the latest edits (creating the draft if the user skipped ahead).
- if (!broadcastId) {
- const created = await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)
- broadcastId = created.id
- actions.saveBroadcastFinished(created)
- } else {
- const saved = await hogFlowsPartialUpdate(
- projectId,
- broadcastId,
- buildBroadcastPayload(values) as any
- )
- actions.saveBroadcastFinished(saved)
- }
+ const saved = await saves.run(() =>
+ broadcastId
+ ? saveWithoutClobbering(projectId, broadcastId, values)
+ : hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)
+ )
+ broadcastId = saved.id
+ actions.saveBroadcastFinished(saved)
// A fresh audience preview mints the confirm token the batch dispatch expects.
const blastRadius = await hogFlowsUserBlastRadiusCreate(projectId, {
@@ -968,15 +1204,29 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
return
}
+ // The assistant can edit the draft during the audience request. Activate only the saved
+ // version, so the send never goes out with an email the user did not see. Schedule
+ // changes don't bump the flow's updated_at, so the base stays valid across the swap.
+ const toActivate = broadcastId
+ const activate = (): Promise<HogFlowApi> =>
+ saves.run(() =>
+ patchWithoutClobbering(projectId, toActivate, { status: 'active' }, saved.updated_at)
+ )
// An old schedule would fire alongside the new one, and a paused one can't be resumed, so
// launch replaces them. The flow stays a draft until the swap is done, and the scheduler
// skips drafts, so a failure part way never leaves two live schedules or none.
const oldScheduleIds = (values.broadcast?.schedules ?? []).map((existing) => existing.id)
+ // Stop before touching schedules if the assistant saved meanwhile. Otherwise the guarded
+ // activation below would 409 after the old schedule is already gone.
+ const current = await hogFlowsRetrieve(projectId, toActivate)
+ if (current.updated_at !== saved.updated_at) {
+ throw new EditedElsewhereError(current)
+ }
if (values.scheduleMode === 'now') {
for (const id of oldScheduleIds) {
await hogFlowsSchedulesDestroy(projectId, broadcastId, id)
}
- activated = await hogFlowsPartialUpdate(projectId, broadcastId, { status: 'active' })
+ activated = await activate()
await hogFlowsBatchJobsCreate(projectId, broadcastId, {
hog_flow: broadcastId,
variables: {},
@@ -1000,7 +1250,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
for (const id of oldScheduleIds) {
await hogFlowsSchedulesDestroy(projectId, broadcastId, id)
}
- activated = await hogFlowsPartialUpdate(projectId, broadcastId, { status: 'active' })
+ activated = await activate()
lemonToast.success('Broadcast scheduled')
}
// Resuming a draft launches from the broadcast's own URL, so the router push below is a
@@ -1011,6 +1261,14 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.launchBroadcastFinished()
router.actions.push(urls.broadcast(broadcastId))
} catch (error: any) {
+ if (error instanceof EditedElsewhereError) {
+ actions.applyExternalEdit(error.latest, values.broadcast)
+ actions.launchBroadcastFinished()
+ lemonToast.info(
+ 'This email changed while you were editing it. Review the latest version, then launch.'
+ )
+ return
+ }
if (activated && broadcastId) {
// Activation landed but the send did not. An active broadcast with no job and no
// schedule is read-only, so leaving it there would strand it with no way to retry.
@@ -1114,6 +1372,58 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}),
])
+function getSaveQueue(cache: Record<string, any>, values: broadcastWizardLogicType['values']): ResourceSaveQueue {
+ return (cache.saveQueue ??= new ResourceSaveQueue({
+ resourceType: 'HogFlow',
+ getResourceId: () => values.broadcast?.id,
+ getLoadedStamp: () => values.broadcast?.updated_at,
+ // Continue and launch save outside an autosave, and their echo can arrive before they finish.
+ isBusy: () => values.saving || values.launching,
+ }))
+}
+
+const EDITED_ELSEWHERE_MESSAGE = 'This email changed elsewhere, so your last few seconds of edits were replaced.'
+
+class EditedElsewhereError extends Error {
+ constructor(public latest: HogFlowApi) {
+ super('The broadcast was edited elsewhere')
+ }
+}
+
+// Saves with the updated_at last loaded, so an edit saved elsewhere since (e.g. by PostHog AI) comes
+// back as a conflict instead of being overwritten by an editor that has not shown it yet.
+async function saveWithoutClobbering(
+ projectId: string,
+ broadcastId: string,
+ values: Parameters<typeof buildBroadcastPayload>[0] & { broadcast: HogFlowApi | null }
+): Promise<HogFlowApi> {
+ return await patchWithoutClobbering(
+ projectId,
+ broadcastId,
+ buildBroadcastPayload(values),
+ values.broadcast?.updated_at
+ )
+}
+
+async function patchWithoutClobbering(
+ projectId: string,
+ broadcastId: string,
+ payload: Record<string, any>,
+ baseUpdatedAt: string | undefined
+): Promise<HogFlowApi> {
+ try {
+ return await hogFlowsPartialUpdate(projectId, broadcastId, {
+ ...payload,
+ base_updated_at: baseUpdatedAt,
+ } as any)
+ } catch (error: any) {
+ if (error?.status === 409) {
+ throw new EditedElsewhereError(await hogFlowsRetrieve(projectId, broadcastId))
+ }
+ throw error
+ }
+}
+
export const SENDERS_LOAD_FAILED_ERROR = "Couldn't load your email senders. Reload them to launch."
/**
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
index a9c457c40cac..43f255c773b8 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
@@ -1,20 +1,55 @@
import { useActions, useValues } from 'kea'
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { EmailTemplater, TemplatePickerModal } from 'scenes/hog-functions/email-templater/EmailTemplater'
import type { EmailFieldErrors, EmailTemplate } from 'scenes/hog-functions/email-templater/types'
+import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'
+import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'
-import { IntegrationType } from '~/types'
+import { HogFunctionTemplateType, IntegrationType } from '~/types'
+
+import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
import { EmailSetupModal } from '../../Channels/EmailSetup/EmailSetupModal'
import { buildSampleGlobals } from '../../Workflows/hogflows/steps/components/HogFlowFunctionConfiguration'
-import { BroadcastEmailValue, DEFAULT_BROADCAST_EMAIL, broadcastWizardLogic } from '../broadcastWizardLogic'
+import type { HogFlow } from '../../Workflows/hogflows/types'
+import { EMAIL_EDITOR_AGENT_HEADLINES, buildWorkflowAgentContext } from '../../Workflows/workflowAgentContext'
+import {
+ BroadcastEmailValue,
+ DEFAULT_BROADCAST_EMAIL,
+ EMAIL_ACTION_ID,
+ broadcastWizardLogic,
+} from '../broadcastWizardLogic'
+
+// The context builder redacts every input of a step whose template it cannot find. The broadcast's only
+// function step uses template-email, whose single input is the email itself and holds no secret.
+const BROADCAST_TEMPLATES: Record<string, HogFunctionTemplateType> = {
+ 'template-email': {
+ id: 'template-email',
+ inputs_schema: [{ key: 'email', type: 'email' }],
+ } as unknown as HogFunctionTemplateType,
+}
+
+// Static text, so it is safe as a trusted instruction. The wizard rewrites the graph on every save,
+// so graph edits would be lost, and launching belongs to the wizard's review step.
+const BROADCAST_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: 'broadcast-content',
+ value:
+ 'This workflow is a broadcast: a batch trigger, one email step and an exit. Change only the email step ' +
+ '(its content, subject and preheader). Do not add, remove or reorder steps, and do not enable or ' +
+ 'publish it. The user launches it from the broadcast wizard. An email edit only saves once the step has ' +
+ 'a sender, so if from.integrationId is empty, ask the user to pick one in the From field first.',
+}
export function BroadcastContentStep(): JSX.Element {
- const { email, stepValidationErrors, selectedSender } = useValues(broadcastWizardLogic)
+ const { email, stepValidationErrors, selectedSender, broadcastAsWorkflow, broadcastId } =
+ useValues(broadcastWizardLogic)
const { setEmail } = useActions(broadcastWizardLogic)
const { integrations, integrationsLoading } = useValues(integrationsLogic)
const { loadIntegrations } = useActions(integrationsLogic)
@@ -34,6 +69,33 @@ export function BroadcastContentStep(): JSX.Element {
}
}
+ const { sceneIntegrationEnabled } = useValues(sceneAgentPanelLogic)
+ // Debounced so each keystroke does not re-serialize the email into the agent context.
+ const debouncedWorkflow = useDebouncedValue(broadcastAsWorkflow, 500)
+ const agentContextItems = useMemo(
+ () =>
+ sceneIntegrationEnabled && debouncedWorkflow && broadcastId
+ ? [
+ ...buildWorkflowAgentContext(
+ debouncedWorkflow as unknown as HogFlow,
+ broadcastId,
+ BROADCAST_TEMPLATES,
+ // A workflow shaped like a broadcast keeps its own step ids.
+ debouncedWorkflow.actions?.find((action) => action.type === 'function_email')?.id ??
+ EMAIL_ACTION_ID
+ ),
+ BROADCAST_CONTEXT_ITEM,
+ ]
+ : null,
+ [sceneIntegrationEnabled, debouncedWorkflow, broadcastId]
+ )
+ useSceneAgentPanel({
+ sceneKey: 'broadcast',
+ contextItems: agentContextItems,
+ headlines: EMAIL_EDITOR_AGENT_HEADLINES,
+ active: !!broadcastId,
+ })
+
const errors = stepValidationErrors.content
const fieldErrors: EmailFieldErrors = {
from: errors.find((error) => error.includes('sender')),