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): link broadcasts and the workflow editor both ways (#114184)

Daniel Marchuk73c5ebd0b58f
diff --git a/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx b/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx
index 023289e35152..2e7e0f100a1b 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx
@@ -21,7 +21,8 @@ import { useBroadcastAgentPanel } from './useBroadcastAgentPanel'
export function BroadcastWizard(): JSX.Element {
const { currentStep, stepValidationErrors, currentStepHasErrors, saving, launching, scheduleMode } =
useValues(broadcastWizardLogic)
- const { setStep, prevStep, continueStep, launchBroadcast, archiveBroadcast } = useActions(broadcastWizardLogic)
+ const { setStep, prevStep, continueStep, launchBroadcast, archiveBroadcast, openInWorkflowEditor } =
+ useActions(broadcastWizardLogic)
const { broadcastId, broadcast } = useValues(broadcastWizardLogic)
useBroadcastAgentPanel()
@@ -34,6 +35,13 @@ export function BroadcastWizard(): JSX.Element {
broadcastId ? (
<LemonMenu
items={[
+ {
+ label: 'Open in workflow editor',
+ onClick: openInWorkflowEditor,
+ disabledReason:
+ saving || launching ? 'Wait for the broadcast to finish saving' : undefined,
+ 'data-attr': 'broadcast-open-in-workflow-editor',
+ },
{
label: 'Archive',
status: 'danger',
diff --git a/products/workflows/frontend/Broadcasts/broadcastLifecycle.ts b/products/workflows/frontend/Broadcasts/broadcastLifecycle.ts
index 51ffb7865e04..4abc11a649de 100644
--- a/products/workflows/frontend/Broadcasts/broadcastLifecycle.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastLifecycle.ts
@@ -117,3 +117,19 @@ export function confirmDeleteBroadcast(projectId: string, broadcast: ManagedBroa
secondaryButton: { children: 'Cancel' },
})
}
+
+export function confirmOpenInWorkflowEditor(onConfirm: () => void): void {
+ LemonDialog.open({
+ width: 500,
+ title: 'Open in the workflow editor?',
+ description:
+ 'Add delays, follow-up emails, branches or other steps there. After you add steps, the broadcast shows here read-only and you keep editing it in the workflow editor.',
+ primaryButton: {
+ children: 'Open workflow editor',
+ type: 'primary',
+ 'data-attr': 'broadcast-open-in-workflow-editor-confirm',
+ onClick: onConfirm,
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index 8579b22be8e5..32807b0d6230 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -1,7 +1,9 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -421,6 +423,81 @@ describe('broadcastWizardLogic', () => {
expect(router.values.location.pathname).toContain('/broadcasts/broadcast-1')
})
+ it('saves an email edit still waiting on its autosave before opening the workflow editor', async () => {
+ router.actions.push('/broadcasts/new')
+ logic.actions.setStep('content')
+ releaseCreate()
+ await expectLogic(logic).toDispatchActions(['draftAutosaved', 'showSavedDraftUrl'])
+
+ logic.actions.setEmail({ ...DEFAULT_BROADCAST_EMAIL, subject: 'Typed before the handoff' })
+ const capture = jest.spyOn(posthog, 'capture')
+ await expectLogic(logic, () => {
+ logic.actions.openInWorkflowEditorConfirmed()
+ })
+ .toDispatchActions(['saveBroadcastFinished'])
+ .toFinishAllListeners()
+
+ expect(patchedSubjects.at(-1)).toEqual('Typed before the handoff')
+ expect(router.values.location.pathname).toContain('/workflows/broadcast-1/workflow')
+ expect(capture).toHaveBeenCalledWith('broadcast opened in workflow editor', {
+ broadcast_id: 'broadcast-1',
+ step: 'content',
+ })
+ })
+
+ it('saves an email edit made while the workflow editor handoff is saving before it opens the editor', async () => {
+ router.actions.push('/broadcasts/new')
+ logic.actions.setStep('content')
+ releaseCreate()
+ await expectLogic(logic).toDispatchActions(['draftAutosaved', 'showSavedDraftUrl'])
+ logic.actions.setEmail({ ...DEFAULT_BROADCAST_EMAIL, subject: 'Saved by the handoff' })
+
+ let releasePatch: () => void = () => {}
+ holdPatch = new Promise((resolve) => {
+ releasePatch = resolve
+ })
+ const patchStarted = new Promise<void>((resolve) => {
+ onPatchStarted = resolve
+ })
+ logic.actions.openInWorkflowEditorConfirmed()
+ await patchStarted
+ holdPatch = null
+ logic.actions.setEmail({ ...DEFAULT_BROADCAST_EMAIL, subject: 'Typed during the handoff' })
+ releasePatch()
+
+ await expectLogic(logic).toDispatchActions(['saveBroadcastFinished']).toFinishAllListeners()
+ expect(patchedSubjects.at(-1)).toEqual('Typed during the handoff')
+ expect(router.values.location.pathname).toContain('/workflows/broadcast-1/workflow')
+ })
+
+ it('creates the draft and stores its send time when the workflow editor opens before any Continue', async () => {
+ const createdSchedules: Record<string, any>[] = []
+ useMocks({
+ post: {
+ '/api/projects/:team_id/hog_flows/:id/schedules/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ createdSchedules.push(body)
+ return [201, { id: 'schedule-1', ...body }]
+ },
+ },
+ })
+ const sendAt = dayjs().add(1, 'day').startOf('minute').toISOString()
+ router.actions.push('/broadcasts/new')
+ logic.actions.setScheduleMode('later')
+ logic.actions.setSendAt(sendAt)
+ logic.actions.setStep('review')
+ releaseCreate()
+
+ await expectLogic(logic, () => {
+ logic.actions.openInWorkflowEditorConfirmed()
+ })
+ .toDispatchActions(['saveBroadcastFinished'])
+ .toFinishAllListeners()
+
+ expect(createdSchedules).toEqual([expect.objectContaining({ starts_at: sendAt, rrule: expect.any(String) })])
+ expect(router.values.location.pathname).toContain('/workflows/broadcast-1/workflow')
+ })
+
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,
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 3bfc4eb5898d..2d5702f06705 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -89,7 +89,12 @@ import {
parseBroadcastAudiencePrefill,
SOURCE_PREFILL_PARAM,
} from './broadcastAudiencePrefill'
-import { confirmArchiveBroadcast, confirmDeleteBroadcast, restoreBroadcast } from './broadcastLifecycle'
+import {
+ confirmArchiveBroadcast,
+ confirmDeleteBroadcast,
+ confirmOpenInWorkflowEditor,
+ restoreBroadcast,
+} from './broadcastLifecycle'
import {
BroadcastStatus,
StoppableBroadcast,
@@ -449,6 +454,12 @@ export interface broadcastWizardLogicActions {
nextStep: () => {
value: true
}
+ openInWorkflowEditor: () => {
+ value: true
+ }
+ openInWorkflowEditorConfirmed: () => {
+ value: true
+ }
prefillFromLink: (prefill: BroadcastPrefill) => {
prefill: BroadcastPrefill
}
@@ -699,6 +710,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
moveToDraftFinished: true,
duplicateBroadcast: true,
archiveBroadcast: true,
+ openInWorkflowEditor: true,
+ openInWorkflowEditorConfirmed: true,
restoreBroadcast: true,
deleteBroadcast: true,
duplicateBroadcastFinished: true,
@@ -1003,6 +1016,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
false,
{
continueStep: () => true,
+ openInWorkflowEditorConfirmed: () => true,
saveBroadcastFinished: () => false,
},
],
@@ -1512,6 +1526,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
// wizard from the saved copy, so an unsaved email edit moves it only once its autosave lands.
if (
props.id === 'new' &&
+ !cache.handedOffToWorkflowEditor &&
!cache.emailEditPending &&
values.broadcastId &&
values.broadcast?.status === 'draft'
@@ -1549,8 +1564,13 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
return
}
await breakpoint(1000)
- if (!values.broadcastId || !values.currentProjectId || values.broadcast?.status !== 'draft') {
- // Launch saves this edit instead.
+ if (
+ cache.handedOffToWorkflowEditor ||
+ !values.broadcastId ||
+ !values.currentProjectId ||
+ values.broadcast?.status !== 'draft'
+ ) {
+ // Launch, or the save before the workflow editor opens, saves this edit instead.
clearPending()
return
}
@@ -1839,19 +1859,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
} as any)
lemonToast.success('Broadcast is sending')
} else {
- const schedule: Partial<HogFlowScheduleApi> = {
- rrule:
- values.scheduleMode === 'recurring' && values.recurringRepeating
- ? stateToRRule(values.scheduleState, values.recurringStartsAt)
- : ONE_TIME_RRULE,
- starts_at: (values.scheduleMode === 'recurring' ? values.recurringStartsAt : values.sendAt)!,
- timezone: values.effectiveTimezone,
- // The wizard has no variables step, so keep any overrides the old schedule carried.
- ...(values.broadcast?.schedules?.[0]?.variables
- ? { variables: values.broadcast.schedules[0].variables }
- : {}),
- }
- await hogFlowsSchedulesCreate(projectId, broadcastId, schedule as any)
+ await hogFlowsSchedulesCreate(projectId, broadcastId, wizardSchedule(values) as any)
for (const id of oldScheduleIds) {
await hogFlowsSchedulesDestroy(projectId, broadcastId, id)
}
@@ -1962,6 +1970,66 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}
actions.moveToDraftFinished()
},
+ openInWorkflowEditor: () => {
+ confirmOpenInWorkflowEditor(actions.openInWorkflowEditorConfirmed)
+ },
+ openInWorkflowEditorConfirmed: async (_, breakpoint) => {
+ if ((!values.broadcastId && props.id !== 'new') || !values.currentProjectId) {
+ actions.saveBroadcastFinished(null)
+ return
+ }
+ // The editor loads the saved workflow, so the latest edits must land first, as on Continue.
+ cache.autosaveConflict = false
+ const saves = getSaveQueue(cache, values)
+ await saves.whenIdle()
+ breakpoint()
+ if (cache.autosaveConflict) {
+ actions.saveBroadcastFinished(null)
+ return
+ }
+ const projectId = String(values.currentProjectId)
+ let broadcastId = values.broadcastId
+ try {
+ // The email stays editable while the save runs, so save again until a save carries the latest edit.
+ let savedEditGeneration: number | undefined
+ do {
+ const saved = await saves.run(() => {
+ savedEditGeneration = cache.emailEditGeneration
+ // The stepper can reach Review before any Continue created the draft.
+ return broadcastId
+ ? saveWithoutClobbering(projectId, broadcastId, values)
+ : createDraft(projectId, values)
+ })
+ if (!broadcastId && values.entrySource) {
+ saveEntrySource(saved.id, values.entrySource)
+ }
+ broadcastId = saved.id
+ actions.draftAutosaved(saved)
+ } while (cache.emailEditGeneration !== savedEditGeneration)
+ cache.emailEditPending = false
+ await saveDraftSchedule(projectId, broadcastId, values)
+ actions.saveBroadcastFinished(values.broadcast)
+ } catch (error: any) {
+ actions.saveBroadcastFinished(null)
+ if (error instanceof EditedElsewhereError) {
+ actions.applyExternalEdit(error.latest, values.broadcast)
+ lemonToast.info(
+ 'This broadcast changed while you were editing it. Review the latest version first.'
+ )
+ return
+ }
+ lemonToast.error(`Couldn't save the broadcast: ${error?.detail || error?.message || 'unknown error'}`)
+ return
+ }
+ // An autosave still waiting would save again and move the page back to the broadcast.
+ cache.handedOffToWorkflowEditor = true
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('broadcast opened in workflow editor', {
+ broadcast_id: broadcastId,
+ step: values.currentStep,
+ })
+ router.actions.push(urls.workflow(broadcastId, 'workflow'))
+ },
archiveBroadcast: () => {
if (values.currentProjectId && values.broadcast) {
confirmArchiveBroadcast(String(values.currentProjectId), values.broadcast, actions.loadBroadcast)
@@ -2104,6 +2172,47 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}),
])
+function wizardSchedule(values: broadcastWizardLogicType['values']): Partial<HogFlowScheduleApi> {
+ return {
+ rrule:
+ values.scheduleMode === 'recurring' && values.recurringRepeating
+ ? stateToRRule(values.scheduleState, values.recurringStartsAt)
+ : ONE_TIME_RRULE,
+ starts_at: (values.scheduleMode === 'recurring' ? values.recurringStartsAt : values.sendAt)!,
+ timezone: values.effectiveTimezone,
+ // The wizard has no variables step, so keep any overrides the old schedule carried.
+ ...(values.broadcast?.schedules?.[0]?.variables ? { variables: values.broadcast.schedules[0].variables } : {}),
+ }
+}
+
+/** Stores the timing picked in the wizard on the draft, so the workflow editor opens with it. The scheduler skips drafts. */
+async function saveDraftSchedule(
+ projectId: string,
+ broadcastId: string,
+ values: broadcastWizardLogicType['values']
+): Promise<void> {
+ if (values.stepValidationErrors.schedule.length > 0) {
+ return
+ }
+ const existing = values.broadcast?.schedules ?? []
+ const wanted = values.scheduleMode === 'now' ? null : wizardSchedule(values)
+ const unchanged = wanted
+ ? existing.length === 1 &&
+ existing[0].rrule === wanted.rrule &&
+ dayjs(existing[0].starts_at).isSame(dayjs(wanted.starts_at)) &&
+ existing[0].timezone === wanted.timezone
+ : existing.length === 0
+ if (unchanged) {
+ return
+ }
+ if (wanted) {
+ await hogFlowsSchedulesCreate(projectId, broadcastId, wanted as any)
+ }
+ for (const schedule of existing) {
+ await hogFlowsSchedulesDestroy(projectId, broadcastId, schedule.id)
+ }
+}
+
async function createDraft(projectId: string, values: broadcastWizardLogicType['values']): Promise<HogFlowApi> {
const created = await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)
// pinned: analytics event name
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
index bf3879215511..135a0f942084 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
@@ -5,6 +5,7 @@ import { LemonButton, Spinner } from '@posthog/lemon-ui'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { Link } from 'lib/lemon-ui/Link'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { AiEmailDraftStatus } from '../../MessageAudience/AiEmailDraftStatus'
@@ -78,6 +79,7 @@ export function BroadcastReviewStep(): JSX.Element {
const { categories } = useValues(optOutCategoriesLogic())
const category = categories.find((item) => item.id === emailSettings.messageCategoryId)
const { props } = useMountedLogic(broadcastWizardLogic)
+ const { openInWorkflowEditor } = useActions(broadcastWizardLogic)
const { nonCohortAudience } = useValues(broadcastAudienceCohortsLogic(props))
const { integrationsLoading } = useValues(integrationsLogic)
const { loadIntegrations } = useActions(integrationsLogic)
@@ -170,6 +172,14 @@ export function BroadcastReviewStep(): JSX.Element {
)}
</div>
+ <div className="text-xs text-secondary">
+ Need delays, follow-up emails or branches?{' '}
+ <Link onClick={openInWorkflowEditor} data-attr="broadcast-review-open-in-workflow-editor">
+ Continue in the workflow editor
+ </Link>
+ .
+ </div>
+
{reviewOnlyErrors.length > 0 && (
<div className="flex flex-col gap-1">
{reviewOnlyErrors.map((error) => (
diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
index d9bcfc97317a..996e16593161 100644
--- a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
@@ -208,6 +208,12 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El
onDescriptionChange={(description) => setWorkflowValue('description', description)}
isLoading={workflowLoading && !workflow}
renameDebounceMs={200}
+ // A broadcast isn't in the workflows list, so going back from here returns to the broadcast.
+ forceBackTo={
+ workflow?.origin_product === 'broadcasts' && props.id && props.id !== 'new'
+ ? { key: 'broadcast', name: workflow.name || 'the broadcast', path: urls.broadcast(props.id) }
+ : undefined
+ }
actions={
<>
{isManualWorkflow && <HogFlowManualTriggerButton {...props} />}
diff --git a/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsx b/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsx
index 1cdf6784d112..370169cad22a 100644
--- a/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsx
+++ b/products/workflows/frontend/setupGuide/wizard/WorkflowsOnboardingWizard.tsx
@@ -1,8 +1,11 @@
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
import { LemonBanner, LemonButton, LemonTag } from '@posthog/lemon-ui'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
import { CustomerIOImportModal } from '../../OptOuts/CustomerIOImportModal'
import { OptOutCategories } from '../../OptOuts/OptOutCategories'
@@ -99,6 +102,22 @@ export function WorkflowsOnboardingWizard(): JSX.Element {
<div>
<h2 className="mb-1 text-xl font-bold">{copy.title}</h2>
<p className="mb-0 text-secondary">{suggestionsFirst ? SUGGESTIONS_DESCRIPTION : copy.description}</p>
+ {currentStep === 'journey' && (
+ <div className="mt-1 text-secondary">
+ Sending one email to a list of people?{' '}
+ <Link
+ to={urls.broadcastNew()}
+ onClick={() => {
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('workflows onboarding wizard broadcast clicked')
+ }}
+ data-attr="workflows-onboarding-wizard-broadcast"
+ >
+ Create a broadcast instead
+ </Link>
+ .
+ </div>
+ )}
</div>
<LemonCard hoverEffect={false} className="p-6">
{currentStep === 'channel' && <WizardChannelStep />}