: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): open broadcast-shaped workflows as broadcasts (#106363)
Daniel Marchuk113265dc4d6a
diff --git a/products/workflows/frontend/Broadcasts/BroadcastScene.tsx b/products/workflows/frontend/Broadcasts/BroadcastScene.tsxindex 39e763965ae5..30a3d31639c1 100644--- a/products/workflows/frontend/Broadcasts/BroadcastScene.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastScene.tsx@@ -8,6 +8,7 @@ import { SceneExport } from 'scenes/sceneTypes'import { ProductKey } from '~/queries/schema/schema-general'import { broadcastPreviewLogic } from './broadcastPreviewLogic'+import { canEditInWizard, isBroadcastShaped } from './broadcastsLogic'import { BroadcastSummary } from './BroadcastSummary'import { broadcastTestSendLogic } from './broadcastTestSendLogic'import { BroadcastWizard } from './BroadcastWizard'@@ -44,12 +45,16 @@ function BroadcastSceneContent({ id }: BroadcastWizardLogicProps): JSX.Element {if (!broadcast) {return <NotFound object="broadcast" />}- // Any workflow id resolves on this route, and the wizard would rewrite whatever graph it- // opened into a broadcast's trigger/email/exit on the next save. Only open real broadcasts.- if (broadcast.origin_product !== 'broadcasts') {+ // Any workflow id resolves on this route. An unowned workflow shaped like a broadcast opens here+ // like one, matching the list; a workflow another product owns, or any other shape, does not.+ const isBroadcast = broadcast.origin_product === 'broadcasts'+ if (!isBroadcast && (broadcast.origin_product || !isBroadcastShaped(broadcast.actions as any))) {return <NotFound object="broadcast" />}- if (broadcast.status !== 'draft') {+ if (+ broadcast.status !== 'draft' ||+ (!isBroadcast && !canEditInWizard(broadcast.actions as any, broadcast.edges as any))+ ) {return <BroadcastSummary />}}diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsxindex 8a6252fe4696..32d4fbee301e 100644--- a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx@@ -1,6 +1,6 @@import { useValues } from 'kea'-import { IconArrowLeft, IconExternal } from '@posthog/icons'+import { IconArrowLeft } from '@posthog/icons'import { LemonButton, LemonTag } from '@posthog/lemon-ui'import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'@@ -80,21 +80,10 @@ export function BroadcastSummary(): JSX.Element {return (<div className="min-h-full w-full shrink-0 bg-bg-light"><div className="mx-auto max-w-4xl space-y-5 px-6 py-6">- <div className="flex items-center justify-between">+ <div className="flex items-center"><LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.broadcasts()}>Broadcasts</LemonButton>- {broadcastId && (- <LemonButton- type="tertiary"- size="small"- sideIcon={<IconExternal />}- to={urls.workflow(broadcastId, 'workflow')}- data-attr="broadcast-open-in-workflow-editor"- >- Open in workflow editor- </LemonButton>- )}</div><div className="flex items-center gap-2">diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsxindex 820807194be3..30936cb70451 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx@@ -47,7 +47,7 @@ export function BroadcastsTable(): JSX.Element {render: (_, item) => (<div className="flex items-center gap-2"><LemonTableLink- to={isEligibleWorkflow(item) ? urls.workflow(item.id, 'workflow') : urls.broadcast(item.id)}+ to={urls.broadcast(item.id)}title={item.name || 'Untitled broadcast'}description={item.description}/>@@ -55,7 +55,7 @@ export function BroadcastsTable(): JSX.Element {<LemonTagtype="muted"data-attr="broadcast-workflow-tag"- title="A workflow with a batch trigger and one email. It opens in the workflow editor."+ title="A workflow with a batch trigger and one email, shown here as a broadcast.">Workflow</LemonTag>diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.tsindex 491dd77752f5..e3bf64c51ea4 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts@@ -21,6 +21,7 @@ import {hogFlowsPartialUpdate,hogFlowsRetrieve,hogFlowsSchedulesCreate,+ hogFlowsSchedulesPartialUpdate,hogFlowsUserBlastRadiusCreate,} from 'products/workflows/frontend/generated/api'import type {@@ -808,7 +809,18 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([starts_at: (values.scheduleMode === 'recurring' ? values.recurringStartsAt : values.sendAt)!,timezone: values.effectiveTimezone,}- await hogFlowsSchedulesCreate(projectId, broadcastId, schedule as any)+ // A workflow shown as a broadcast can already carry a schedule. A second one would+ // fire alongside it and send twice. Saving new audience filters pauses it, and launch+ // has just previewed the audience, so it resumes here.+ const existingScheduleId = values.broadcast?.schedules?.[0]?.id+ if (existingScheduleId) {+ await hogFlowsSchedulesPartialUpdate(projectId, broadcastId, existingScheduleId, {+ ...schedule,+ status: 'active',+ } as any)+ } else {+ await hogFlowsSchedulesCreate(projectId, broadcastId, schedule as any)+ }lemonToast.success('Broadcast scheduled')}// Resuming a draft launches from the broadcast's own URL, so the router push below is a@@ -863,14 +875,48 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([// Serializes the wizard state into the HogFlow the broadcast is stored as: a batch trigger// (the audience), one email action, and an exit node.-function buildBroadcastPayload(values: {+export function buildBroadcastPayload(values: {name: stringaudienceProperties: AnyPropertyFilter[]goalEnabled: booleanconversion: HogFlowConversionApiemail: BroadcastEmailValueemailRateLimit: HogFlowEmailSendingRateLimitApi | null+ broadcast?: HogFlowApi | null}): Record<string, any> {+ const existing = values.broadcast+ if (existing && existing.origin_product !== 'broadcasts') {+ // A workflow shaped like a broadcast keeps its own steps: its ids, names and any setting the+ // wizard does not manage survive, and origin_product stays as it was created.+ return {+ name: values.name,+ conversion: values.goalEnabled ? values.conversion : null,+ email_sending_rate_limit: values.emailRateLimit,+ actions: (existing.actions as Record<string, any>[]).map((action) =>+ action.type === 'trigger'+ ? {+ ...action,+ config: {+ ...action.config,+ filters: { ...action.config?.filters, properties: values.audienceProperties },+ },+ }+ : action.type === 'function_email'+ ? {+ ...action,+ config: {+ ...action.config,+ inputs: {+ ...action.config?.inputs,+ email: { ...action.config?.inputs?.email, value: values.email },+ },+ },+ }+ : action+ ),+ edges: existing.edges,+ }+ }return {origin_product: 'broadcasts',status: 'draft',diff --git a/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.tsnew file mode 100644index 000000000000..c0fa4c6d887c--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts@@ -0,0 +1,79 @@+import type { HogFlowApi } from 'products/workflows/frontend/generated/api.schemas'++import { canEditInWizard } from './broadcastsLogic'+import { DEFAULT_BROADCAST_CONVERSION, DEFAULT_BROADCAST_EMAIL, buildBroadcastPayload } from './broadcastWizardLogic'++const trigger = (filters: Record<string, any> = { properties: [] }): Record<string, any> => ({+ id: 'trigger_node',+ type: 'trigger',+ name: 'Audience',+ config: { type: 'batch', filters },+})+const email = (to = '{{ person.properties.email }}'): Record<string, any> => ({+ id: 'email_1',+ type: 'function_email',+ name: 'Email',+ on_error: 'continue',+ config: { template_id: 'template-email', inputs: { email: { value: { to: { email: to } } }, extra: { value: 1 } } },+})+const exit = { id: 'exit_node', type: 'exit', name: 'Exit', config: {} }+const edges = [+ { from: 'trigger_node', to: 'email_1', type: 'continue' },+ { from: 'email_1', to: 'exit_node', type: 'continue' },+]++describe('broadcast edits to broadcast-shaped workflows', () => {+ it.each([+ ['a person audience sent to each person', [trigger(), email(), exit], edges, true],+ ['an account audience', [trigger({ audience_type: 'accounts', properties: [] }), email(), exit], edges, false],+ ['a custom recipient expression', [trigger(), email('{{ inputs.owner_email }}'), exit], edges, false],+ [+ 'a trigger that skips the email',+ [trigger(), email(), exit],+ [{ from: 'trigger_node', to: 'exit_node' }],+ false,+ ],+ ['a second, disconnected exit', [trigger(), email(), exit, { ...exit, id: 'exit_2' }], edges, false],+ [+ 'an extra path around the email',+ [trigger(), email(), exit],+ [...edges, { from: 'trigger_node', to: 'exit_node', type: 'continue' }],+ false,+ ],+ ])('opens %s in the wizard: %s', (_, actions, flowEdges, expected) => {+ expect(canEditInWizard(actions, flowEdges)).toBe(expected)+ })++ it('saves the audience and email into the existing steps without replacing them', () => {+ const existing = {+ origin_product: null,+ actions: [trigger({ properties: [], cohort_hint: 'kept' }), email(), exit],+ edges,+ } as unknown as HogFlowApi++ const payload = buildBroadcastPayload({+ name: 'Renamed',+ audienceProperties: [{ key: 'plan', value: 'pro', operator: 'exact', type: 'person' }] as any,+ goalEnabled: false,+ conversion: DEFAULT_BROADCAST_CONVERSION,+ email: { ...DEFAULT_BROADCAST_EMAIL, subject: 'New subject' },+ emailRateLimit: null,+ broadcast: existing,+ })++ expect(payload).not.toHaveProperty('origin_product')+ expect(payload.edges).toEqual(edges)+ expect(payload.actions.map((action: any) => [action.id, action.name])).toEqual([+ ['trigger_node', 'Audience'],+ ['email_1', 'Email'],+ ['exit_node', 'Exit'],+ ])+ expect(payload.actions[0].config.filters).toEqual({+ properties: [{ key: 'plan', value: 'pro', operator: 'exact', type: 'person' }],+ cohort_hint: 'kept',+ })+ expect(payload.actions[1].on_error).toBe('continue')+ expect(payload.actions[1].config.inputs.extra).toEqual({ value: 1 })+ expect(payload.actions[1].config.inputs.email.value.subject).toBe('New subject')+ })+})diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.tsindex 2860771fb9e7..88eff4467ff7 100644--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts@@ -28,6 +28,50 @@ export interface BroadcastRowDetails {/** Rows per page. Each row loads its latest run and metrics, so a page stays small enough to enrich. */export const BROADCASTS_PAGE_SIZE = 100+/** Mirrors the list API's broadcast_eligible filter: a batch trigger, one email step, nothing else. */+export function isBroadcastShaped(+ actions: { type?: string; config?: { type?: string } }[] | null | undefined+): boolean {+ const steps = actions ?? []+ return (+ steps.some((step) => step.type === 'trigger' && step.config?.type === 'batch') &&+ steps.filter((step) => step.type === 'function_email').length === 1 &&+ steps.every((step) => ['trigger', 'function_email', 'exit'].includes(step.type ?? ''))+ )+}++const DEFAULT_RECIPIENT = '{{ person.properties.email }}'++type FlowStep = { id?: string; type?: string; config?: Record<string, any> }+type FlowEdge = { from?: string; to?: string }++/**+ * Whether the broadcast wizard can edit a broadcast-shaped workflow without misdescribing it. The+ * wizard only models a person audience sent to each person's own email along trigger, email, exit;+ * anything else opens as the read-only summary instead.+ */+export function canEditInWizard(actions: FlowStep[] | null | undefined, edges: FlowEdge[] | null | undefined): boolean {+ const steps = actions ?? []+ const [trigger, email, exit] = ['trigger', 'function_email', 'exit'].map((type) =>+ steps.filter((step) => step.type === type)+ )+ // One of each and nothing else, so the steps the wizard edits are the only ones there are.+ if (steps.length !== 3 || trigger.length !== 1 || email.length !== 1 || exit.length !== 1) {+ return false+ }+ const recipient = email[0].config?.inputs?.email?.value?.to?.email+ // Exactly trigger -> email -> exit: any other edge is a path the wizard cannot show, such as one+ // that skips the email.+ const paths = new Set((edges ?? []).map((edge) => `${edge.from}->${edge.to}`))+ return (+ trigger[0].config?.filters?.audience_type !== 'accounts' &&+ (!recipient || recipient === DEFAULT_RECIPIENT) &&+ paths.size === 2 &&+ paths.has(`${trigger[0].id}->${email[0].id}`) &&+ paths.has(`${email[0].id}->${exit[0].id}`)+ )+}+export function isEligibleWorkflow(flow: Pick<HogFlowMinimalApi, 'origin_product'>): boolean {return flow.origin_product !== 'broadcasts'}