: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
feat(workflows): start a new broadcast from a description with PostHog AI (#107782)
Daniel Marchuk96a5aec2f345
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex df13e29cc061..57fb1bd0c457 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -269,6 +269,7 @@ export const FEATURE_FLAGS = {BACKFILL_WORKFLOWS_DESTINATION: 'backfill-workflows-destination', // owner: #team-batch-exportsBILLING_ALERTS: 'billing-alerts', // owner: #team-billing, gates the Billing > Alerts tabBILLING_REAL_TIME_USAGE: 'billing-real-time-usage', // owner: #team-billing, gates the Real-time usage scene+ BROADCASTS_AI_FIRST_NEW: 'broadcasts-ai-first-new', // owner: @dmarchuk #team-workflowsCDP_DWH_TABLE_SOURCE: 'cdp-dwh-table-source', // owner: #team-workflows-cdpCDP_DWH_VIEW_SOURCE: 'cdp-dwh-view-source', // owner: #team-workflows-cdpCDP_HOG_SOURCES: 'cdp-hog-sources', // owner #team-workflows-cdpdiff --git a/products/workflows/frontend/Broadcasts/BroadcastScene.tsx b/products/workflows/frontend/Broadcasts/BroadcastScene.tsxindex 30a3d31639c1..3e8ca9f74531 100644--- a/products/workflows/frontend/Broadcasts/BroadcastScene.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastScene.tsx@@ -3,16 +3,26 @@ import { BindLogic, useValues } from 'kea'import { SpinnerOverlay } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'+import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'import { SceneExport } from 'scenes/sceneTypes'import { ProductKey } from '~/queries/schema/schema-general'+import {+ NEW_BROADCAST_AGENT_HEADLINES,+ NEW_BROADCAST_COMPOSER_OVERRIDE,+ buildNewBroadcastComposerContext,+} from './broadcastAgentContext'import { broadcastPreviewLogic } from './broadcastPreviewLogic'import { canEditInWizard, isBroadcastShaped } from './broadcastsLogic'import { BroadcastSummary } from './BroadcastSummary'import { broadcastTestSendLogic } from './broadcastTestSendLogic'import { BroadcastWizard } from './BroadcastWizard'import { BroadcastWizardLogicProps, broadcastWizardLogic } from './broadcastWizardLogic'+import { NewBroadcastAgent } from './NewBroadcastAgent'+import { newBroadcastAgentLogic } from './newBroadcastAgentLogic'++const NEW_BROADCAST_COMPOSER_CONTEXT = buildNewBroadcastComposerContext()export const scene: SceneExport<BroadcastWizardLogicProps> = {component: BroadcastScene,@@ -37,6 +47,22 @@ export function BroadcastScene({ id }: BroadcastWizardLogicProps): JSX.Element {function BroadcastSceneContent({ id }: BroadcastWizardLogicProps): JSX.Element {const { broadcast, broadcastLoading } = useValues(broadcastWizardLogic)+ const { aiComposerAvailable } = useValues(newBroadcastAgentLogic)+ // The escape hatch lands on the wizard instead (see `aiComposerAvailable`).+ const showAiComposer = id === 'new' && aiComposerAvailable+ useSceneAgentPanel({+ sceneKey: 'broadcast-new',+ contextItems: showAiComposer ? NEW_BROADCAST_COMPOSER_CONTEXT : null,+ headlines: NEW_BROADCAST_AGENT_HEADLINES,+ composer: NEW_BROADCAST_COMPOSER_OVERRIDE,+ active: showAiComposer,+ // The composer is the page while drafting; the panel opens itself once the broadcast exists.+ autoOpen: false,+ })++ if (showAiComposer) {+ return <NewBroadcastAgent />+ }if (id !== 'new') {if (!broadcast && broadcastLoading) {@@ -51,10 +77,9 @@ function BroadcastSceneContent({ id }: BroadcastWizardLogicProps): JSX.Element {if (!isBroadcast && (broadcast.origin_product || !isBroadcastShaped(broadcast.actions as any))) {return <NotFound object="broadcast" />}- if (- broadcast.status !== 'draft' ||- (!isBroadcast && !canEditInWizard(broadcast.actions as any, broadcast.edges as any))- ) {+ // The wizard saves a broadcast back as its three-step graph, so any other graph (an edit made in the+ // workflow editor, or an agent-created one) stays read-only here rather than losing its extra steps.+ if (broadcast.status !== 'draft' || !canEditInWizard(broadcast.actions as any, broadcast.edges as any)) {return <BroadcastSummary />}}diff --git a/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx b/products/workflows/frontend/Broadcasts/BroadcastWizard.tsxindex 1064c38d1ec6..023289e35152 100644--- a/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx@@ -16,12 +16,14 @@ import { BroadcastGoalStep } from './steps/BroadcastGoalStep'import { BroadcastRecipientsStep } from './steps/BroadcastRecipientsStep'import { BroadcastReviewStep } from './steps/BroadcastReviewStep'import { BroadcastScheduleStep } from './steps/BroadcastScheduleStep'+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 { broadcastId, broadcast } = useValues(broadcastWizardLogic)+ useBroadcastAgentPanel()return (<SceneContent className="min-h-full w-full shrink-0" data-attr="broadcast-wizard">diff --git a/products/workflows/frontend/Broadcasts/BroadcastsScene.tsx b/products/workflows/frontend/Broadcasts/BroadcastsScene.tsxindex 65cc17c8e09d..bfdca806835a 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsScene.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsScene.tsx@@ -1,4 +1,4 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { LemonButton } from '@posthog/lemon-ui'@@ -18,6 +18,7 @@ import { MessagingTabActions } from '../MessagingTabActions'import { MESSAGING_NAV_TAB_KEYS, MessagingNavTabKey, messagingNavTabs } from '../messagingTabs'import { BroadcastsFeaturePreview } from './BroadcastsFeaturePreview'import { BroadcastsTable } from './BroadcastsTable'+import { newBroadcastAgentLogic } from './newBroadcastAgentLogic'export const scene: SceneExport = {component: BroadcastsScene,@@ -26,6 +27,7 @@ export const scene: SceneExport = {export function BroadcastsScene(): JSX.Element {const { location } = useValues(router)+ const { startNewBroadcast } = useActions(newBroadcastAgentLogic)// The tab routes are literal paths, so the tab is the last path segment rather than a route param.const lastSegment = location.pathname.split('/').pop() as MessagingNavTabKeyconst currentTab: MessagingNavTabKey | 'broadcasts' = MESSAGING_NAV_TAB_KEYS.includes(lastSegment)@@ -44,7 +46,12 @@ export function BroadcastsScene(): JSX.Element {resourceType={AccessControlResourceType.Workflow}minAccessLevel={AccessControlLevel.Editor}>- <LemonButton data-attr="new-broadcast" to={urls.broadcastNew()} type="primary" size="small">+ <LemonButton+ data-attr="new-broadcast"+ onClick={startNewBroadcast}+ type="primary"+ size="small"+ >New broadcast</LemonButton></AccessControlAction>diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsxindex 02d781a309f0..031922432f27 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx@@ -22,6 +22,7 @@ import {isEligibleWorkflow,} from './broadcastsLogic'import { BroadcastStatusTag } from './BroadcastStatusTag'+import { newBroadcastAgentLogic } from './newBroadcastAgentLogic'const METRIC_COLUMNS: { title: string; metricName: string }[] = [{ title: 'Sent', metricName: 'email_sent' },@@ -37,6 +38,7 @@ export function BroadcastsTable(): JSX.Element {// Rows from other filters stay behind the loading state, and are dropped once the load for these fails.const hideRows = loadFailed && filtersPendingconst { setFilters, archiveBroadcast, restoreBroadcast, deleteBroadcast } = useActions(broadcastsLogic)+ const { startNewBroadcast } = useActions(newBroadcastAgentLogic)const { page } = filtersconst isFiltered = !!filters.search || filters.status !== 'all' || !!filters.createdBy@@ -152,7 +154,7 @@ export function BroadcastsTable(): JSX.Element {><h3 className="m-0 text-lg font-semibold">No broadcasts yet</h3><p className="m-0 text-secondary">Send a one-time or scheduled email to an audience of your users.</p>- <LemonButton type="primary" to={urls.broadcastNew()} data-attr="broadcasts-empty-new">+ <LemonButton type="primary" onClick={startNewBroadcast} data-attr="broadcasts-empty-new">New broadcast</LemonButton></div>diff --git a/products/workflows/frontend/Broadcasts/NewBroadcastAgent.tsx b/products/workflows/frontend/Broadcasts/NewBroadcastAgent.tsxnew file mode 100644index 000000000000..664d230fcd28--- /dev/null+++ b/products/workflows/frontend/Broadcasts/NewBroadcastAgent.tsx@@ -0,0 +1,26 @@+import { useActions } from 'kea'++import { AiFirstCreateScene } from 'scenes/max/aiFirstCreate/AiFirstCreateScene'++import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'++import { NEW_BROADCAST_SUGGESTIONS } from './broadcastAgentContext'+import { newBroadcastAgentLogic } from './newBroadcastAgentLogic'+import { NEW_BROADCAST_HANDOFF } from './newBroadcastHandoff'++/** The AI-first "New broadcast" screen: the composer first, with the step-by-step wizard behind the escape hatch. */+export function NewBroadcastAgent(): JSX.Element {+ const { openWizardFromAiComposer } = useActions(newBroadcastAgentLogic)++ return (+ <AiFirstCreateScene+ handoff={NEW_BROADCAST_HANDOFF}+ banner="We're trialling writing broadcasts with PostHog AI. Describe what you want to send and to whom, and it drafts the broadcast for you to review before it goes out."+ escapeHatchLabel="Set it up step by step instead"+ onEscapeHatch={openWizardFromAiComposer}+ suggestions={NEW_BROADCAST_SUGGESTIONS}+ suggestionIcon={iconForType('broadcasts')}+ dataAttr="new-broadcast-agent"+ />+ )+}diff --git a/products/workflows/frontend/Broadcasts/broadcastAgentContext.ts b/products/workflows/frontend/Broadcasts/broadcastAgentContext.tsnew file mode 100644index 000000000000..eae9bf1a92ca--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastAgentContext.ts@@ -0,0 +1,68 @@+import type { AiFirstSuggestion } from 'scenes/max/aiFirstCreate/AiFirstCreateScene'+import { AI_FIRST_COMPOSER_OVERRIDE } from 'scenes/max/aiFirstCreate/aiFirstMode'++import type { ComposerOverride } from 'products/posthog_ai/frontend/api/logics'+import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'++// Own dismiss group: a dismissal is global and never resets, so a chip closed elsewhere must not strip this page.+const NEW_BROADCAST_DISMISS_GROUP = 'new-broadcast-composer'++const BUILDING_WORKFLOWS_SKILL = 'building-workflows'++export const NEW_BROADCAST_AGENT_HEADLINES: string[] = ['What would you like to send?']++export const NEW_BROADCAST_COMPOSER_OVERRIDE: ComposerOverride = {+ ...AI_FIRST_COMPOSER_OVERRIDE,+ subheadline: 'Describe the email and who should get it.',+ placeholder: 'For example, announce our new pricing to all active users…',+}++export const NEW_BROADCAST_SUGGESTIONS: AiFirstSuggestion[] = [+ {+ title: 'Announce a feature',+ description: 'Tell your users about something new',+ prompt: 'Announce our newest feature to all our users',+ },+ {+ title: 'Monthly product update',+ description: 'A roundup of what changed this month',+ prompt: 'Write a monthly product update email for all users',+ },+ {+ title: 'Invite to an event',+ description: 'Ask people to join a webinar or meetup',+ prompt: 'Invite our users to an upcoming webinar and ask them to register',+ },+ {+ title: 'Planned maintenance',+ description: 'Let people know about downtime ahead of time',+ prompt: 'Tell all users about planned maintenance and when it will happen',+ },+]++// Static text, so it is safe as a trusted instruction. Launching belongs to the wizard's review step.+const DRAFT_FIRST_CONTEXT_ITEM: AttachedContextItem = {+ type: 'instructions',+ hidden: true,+ dismissGroup: NEW_BROADCAST_DISMISS_GROUP,+ value:+ `The user is starting a new broadcast from a description. Load the ${BUILDING_WORKFLOWS_SKILL} skill, ` ++ 'then make broadcasts-create your first workflows tool call and do not ask clarifying questions first: ' ++ 'a name, the audience, and a first draft of the email. The broadcast wizard opens the draft the moment it ' ++ 'exists, so refine the email afterwards with workflows-patch-action-email. Do not add steps, do not enable ' ++ 'or publish it, and do not attach a schedule or start a run. The user picks the timing and launches it ' ++ 'from the wizard.',+}++const SKILL_CHIP_CONTEXT_ITEM: AttachedContextItem = {+ type: 'skill',+ key: BUILDING_WORKFLOWS_SKILL,+ label: 'Building workflows skill',+ dismissGroup: NEW_BROADCAST_DISMISS_GROUP,+ // Not dismissible: the page only advances once the broadcast exists.+ dismissible: false,+}++export function buildNewBroadcastComposerContext(): AttachedContextItem[] {+ return [SKILL_CHIP_CONTEXT_ITEM, DRAFT_FIRST_CONTEXT_ITEM]+}diff --git a/products/workflows/frontend/Broadcasts/newBroadcastAgentLogic.test.ts b/products/workflows/frontend/Broadcasts/newBroadcastAgentLogic.test.tsnew file mode 100644index 000000000000..59fb32d483d8--- /dev/null+++ b/products/workflows/frontend/Broadcasts/newBroadcastAgentLogic.test.ts@@ -0,0 +1,87 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { maxMocks } from 'scenes/max/testUtils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { newBroadcastAgentLogic } from './newBroadcastAgentLogic'++const AI_FIRST_FLAGS = [+ FEATURE_FLAGS.BROADCASTS_AI_FIRST_NEW,+ FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN,+ FEATURE_FLAGS.PHAI_SANDBOX_MODE,+]++describe('newBroadcastAgentLogic', () => {+ let logic: ReturnType<typeof newBroadcastAgentLogic.build>++ const setFlags = (flags: string[]): void => {+ featureFlagLogic.actions.setFeatureFlags(flags, Object.fromEntries(flags.map((flag) => [flag, true])))+ }++ beforeEach(() => {+ useMocks(maxMocks)+ initKeaTests()+ logic = newBroadcastAgentLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ // The flag-off path must stay on the wizard, and exposure is recorded only for a click the composer could answer.+ it.each([+ { name: 'flag on', flags: AI_FIRST_FLAGS, mode: { mode: 'ai' }, exposed: true, composer: true },+ {+ name: 'flag off',+ flags: [FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN, FEATURE_FLAGS.PHAI_SANDBOX_MODE],+ mode: {},+ exposed: true,+ composer: false,+ },+ {+ name: 'scene integration off',+ flags: [FEATURE_FLAGS.BROADCASTS_AI_FIRST_NEW],+ mode: {},+ exposed: false,+ composer: false,+ },+ ])('startNewBroadcast opens the composer only with $name', async ({ flags, mode, exposed, composer }) => {+ setFlags(flags)+ const recordExposure = jest.spyOn(posthog, 'getFeatureFlag').mockReturnValue(undefined)+ router.actions.push('/broadcasts')++ await expectLogic(logic, () => {+ logic.actions.startNewBroadcast()+ }).toFinishAllListeners()++ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe('/broadcasts/new')+ expect(router.values.searchParams).toEqual(mode)+ expect(logic.values.aiComposerAvailable).toBe(composer)+ if (exposed) {+ expect(recordExposure).toHaveBeenCalledWith(FEATURE_FLAGS.BROADCASTS_AI_FIRST_NEW)+ } else {+ expect(recordExposure).not.toHaveBeenCalled()+ }+ })++ it('the escape hatch opens the wizard and keeps the composer away', async () => {+ setFlags(AI_FIRST_FLAGS)+ router.actions.push('/broadcasts/new', { mode: 'ai' })+ expect(logic.values.aiComposerAvailable).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.openWizardFromAiComposer()+ }).toFinishAllListeners()++ expect(router.values.searchParams).toEqual({ mode: 'editor' })+ expect(logic.values.aiComposerAvailable).toBe(false)+ })+})diff --git a/products/workflows/frontend/Broadcasts/newBroadcastAgentLogic.ts b/products/workflows/frontend/Broadcasts/newBroadcastAgentLogic.tsnew file mode 100644index 000000000000..247292c23957--- /dev/null+++ b/products/workflows/frontend/Broadcasts/newBroadcastAgentLogic.ts@@ -0,0 +1,127 @@+import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import {+ AI_COMPOSER_MODE_VALUE,+ EDITOR_MODE_PARAM,+ EDITOR_MODE_VALUE,+ aiComposerAvailable,+ isAiFirstVariant,+} from 'scenes/max/aiFirstCreate/aiFirstMode'+import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'+import { urls } from 'scenes/urls'++function isNewBroadcastRoute(pathname: string): boolean {+ return removeProjectIdIfPresent(pathname) === urls.broadcastNew()+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newBroadcastAgentLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ location: {+ pathname: string+ search: string+ hash: string+ } // router+ searchParams: Record<string, any> // router+ sceneIntegrationEnabled: boolean // sceneAgentPanelLogic+ aiComposerAvailable: boolean+ aiFirstNewEnabled: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newBroadcastAgentLogicActions {+ openWizardFromAiComposer: () => {+ value: true+ }+ startNewBroadcast: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface newBroadcastAgentLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ aiFirstNewEnabled: (featureFlags: FeatureFlagsSet, sceneIntegrationEnabled: boolean) => boolean+ aiComposerAvailable: (+ featureFlags: FeatureFlagsSet,+ sceneIntegrationEnabled: boolean,+ searchParams: Record<string, any>,+ location: {+ hash: string+ pathname: string+ search: string+ }+ ) => boolean+ }+}++export type newBroadcastAgentLogicType = MakeLogicType<+ newBroadcastAgentLogicValues,+ newBroadcastAgentLogicActions,+ Record<string, any>,+ newBroadcastAgentLogicMeta+>++/** Entry and mode for the AI-first "New broadcast" page. */+export const newBroadcastAgentLogic = kea<newBroadcastAgentLogicType>([+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'newBroadcastAgentLogic']),+ connect(() => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ sceneAgentPanelLogic,+ ['sceneIntegrationEnabled'],+ router,+ ['searchParams', 'location'],+ ],+ })),+ actions({+ startNewBroadcast: true,+ openWizardFromAiComposer: true,+ }),+ selectors({+ // Same gate as the scene integration. Only the `test` variant, or a plain boolean rollout, qualifies.+ aiFirstNewEnabled: [+ (s) => [s.featureFlags, s.sceneIntegrationEnabled],+ (featureFlags: FeatureFlagsSet, sceneIntegrationEnabled: boolean): boolean =>+ sceneIntegrationEnabled && isAiFirstVariant(FEATURE_FLAGS.BROADCASTS_AI_FIRST_NEW, featureFlags),+ ],+ aiComposerAvailable: [+ (s) => [s.featureFlags, s.sceneIntegrationEnabled, s.searchParams, s.location],+ (+ featureFlags: FeatureFlagsSet,+ sceneIntegrationEnabled: boolean,+ searchParams: Record<string, any>,+ location: { pathname: string }+ ): boolean =>+ aiComposerAvailable(+ FEATURE_FLAGS.BROADCASTS_AI_FIRST_NEW,+ featureFlags,+ sceneIntegrationEnabled,+ searchParams,+ isNewBroadcastRoute(location.pathname)+ ),+ ],+ }),+ listeners(({ values }) => ({+ startNewBroadcast: () => {+ // Exposure is recorded at the click, and only when the composer could answer it.+ if (values.sceneIntegrationEnabled) {+ posthog.getFeatureFlag(FEATURE_FLAGS.BROADCASTS_AI_FIRST_NEW)+ }+ router.actions.push(+ urls.broadcastNew(),+ values.aiFirstNewEnabled ? { [EDITOR_MODE_PARAM]: AI_COMPOSER_MODE_VALUE } : {}+ )+ },+ // The editor URL keeps the composer from rendering again, so the wizard mounts in its place.+ openWizardFromAiComposer: () => {+ router.actions.push(urls.broadcastNew(), { [EDITOR_MODE_PARAM]: EDITOR_MODE_VALUE })+ },+ })),+])diff --git a/products/workflows/frontend/Broadcasts/newBroadcastHandoff.test.ts b/products/workflows/frontend/Broadcasts/newBroadcastHandoff.test.tsnew file mode 100644index 000000000000..9f40e50b595e--- /dev/null+++ b/products/workflows/frontend/Broadcasts/newBroadcastHandoff.test.ts@@ -0,0 +1,43 @@+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { findCreatedBroadcastId } from './newBroadcastHandoff'++const BROADCAST_ID = '2f1e9c3a-5b7d-4e8f-9a0b-1c2d3e4f5a6b'+const NAME = 'Spring sale'++describe('findCreatedBroadcastId', () => {+ let requestedTypes: string | null++ beforeEach(() => {+ requestedTypes = null+ useMocks({+ get: {+ '/api/projects/:team_id/hog_flows/': ({ request }) => {+ requestedTypes = new URL(request.url).searchParams.get('origin_product')+ return [+ 200,+ {+ results: [+ { id: 'older', name: NAME, created_at: '2026-09-01T00:00:00Z' },+ { id: BROADCAST_ID, name: NAME, created_at: '2026-09-15T00:00:00Z' },+ { id: 'other', name: `${NAME} v2`, created_at: '2026-09-16T00:00:00Z' },+ ],+ count: 3,+ },+ ]+ },+ },+ })+ initKeaTests()+ })++ // A workflow can share the name, so the lookup must only consider broadcasts.+ it.each([+ { name: 'the newest exact match among broadcasts', input: NAME, expected: BROADCAST_ID, types: 'broadcasts' },+ { name: 'null for a blank name', input: ' ', expected: null, types: null },+ ])('returns $name', async ({ input, expected, types }) => {+ await expect(findCreatedBroadcastId(input)).resolves.toBe(expected)+ expect(requestedTypes).toBe(types)+ })+})diff --git a/products/workflows/frontend/Broadcasts/newBroadcastHandoff.ts b/products/workflows/frontend/Broadcasts/newBroadcastHandoff.tsnew file mode 100644index 000000000000..c082fb93dc73--- /dev/null+++ b/products/workflows/frontend/Broadcasts/newBroadcastHandoff.ts@@ -0,0 +1,40 @@+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'++// pinned: MCP tool name from products/workflows/mcp/tools.yaml+const CREATE_BROADCAST_TOOL = 'broadcasts-create'++/**+ * Fallback for a completed create whose output carries no record: the draft is found by exact name among+ * broadcasts only, newest `created_at` first, so a workflow of the same name is never opened as one.+ */+export async function findCreatedBroadcastId(name: unknown): Promise<string | null> {+ const search = typeof name === 'string' && name.trim() ? name.trim() : undefined+ if (!search) {+ return null+ }+ const { results } = await hogFlowsList(String(ApiConfig.getCurrentTeamId()), {+ search,+ origin_product: 'broadcasts',+ limit: 5,+ })+ const match = results+ .filter((broadcast) => broadcast.name === search)+ .sort((a, b) => b.created_at.localeCompare(a.created_at))[0]+ return match?.id ?? null+}++/** A completed `broadcasts-create` opens the panel and routes to the draft in the broadcast wizard. */+export const NEW_BROADCAST_HANDOFF: AiFirstHandoffLogicProps = {+ toolName: CREATE_BROADCAST_TOOL,+ findCreatedId: (innerInput) => findCreatedBroadcastId(innerInput?.name),+ urlFor: (id) => urls.broadcast(id),+ 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',+ createdEvent: 'broadcast ai composer created broadcast',+ createdIdProperty: 'broadcast_id',+}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsxindex 43f255c773b8..a9c457c40cac 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx@@ -1,55 +1,20 @@import { useActions, useValues } from 'kea'-import { useMemo, useState } from 'react'+import { 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 { HogFunctionTemplateType, IntegrationType } from '~/types'--import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { IntegrationType } from '~/types'import { EmailSetupModal } from '../../Channels/EmailSetup/EmailSetupModal'import { buildSampleGlobals } from '../../Workflows/hogflows/steps/components/HogFlowFunctionConfiguration'-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.',-}+import { BroadcastEmailValue, DEFAULT_BROADCAST_EMAIL, broadcastWizardLogic } from '../broadcastWizardLogic'export function BroadcastContentStep(): JSX.Element {- const { email, stepValidationErrors, selectedSender, broadcastAsWorkflow, broadcastId } =- useValues(broadcastWizardLogic)+ const { email, stepValidationErrors, selectedSender } = useValues(broadcastWizardLogic)const { setEmail } = useActions(broadcastWizardLogic)const { integrations, integrationsLoading } = useValues(integrationsLogic)const { loadIntegrations } = useActions(integrationsLogic)@@ -69,33 +34,6 @@ 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.contentconst fieldErrors: EmailFieldErrors = {from: errors.find((error) => error.includes('sender')),diff --git a/products/workflows/frontend/Broadcasts/useBroadcastAgentPanel.ts b/products/workflows/frontend/Broadcasts/useBroadcastAgentPanel.tsnew file mode 100644index 000000000000..2a62d9b1a44f--- /dev/null+++ b/products/workflows/frontend/Broadcasts/useBroadcastAgentPanel.ts@@ -0,0 +1,71 @@+import { useValues } from 'kea'+import { useMemo } from 'react'++import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'+import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'+import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'++import { HogFunctionTemplateType } from '~/types'++import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'++import type { HogFlow } from '../Workflows/hogflows/types'+import { EMAIL_EDITOR_AGENT_HEADLINES, buildWorkflowAgentContext } from '../Workflows/workflowAgentContext'+import { 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.',+}++/**+ * Attaches the saved broadcast to PostHog AI on every wizard step, so a run that lands on review still+ * knows the email it is refining. The panel only opens itself on the content step.+ */+export function useBroadcastAgentPanel(): void {+ const { broadcastAsWorkflow, broadcastId, currentStep } = useValues(broadcastWizardLogic)+ 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,+ autoOpen: currentStep === 'content',+ })+}diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex d5d1b78812ed..8786d91b2ed1 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -15,6 +15,30 @@ ui_apps:type: listdetail_tool: workflows-gettools:+ broadcasts-create:+ operation: hog_flows_create+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create broadcast+ description: >+ Create a broadcast: a one-time or scheduled email to an audience, which the user reviews and launches from+ the broadcast wizard. It is created as a draft and never sends from this tool; do not enable it, run it or+ attach a schedule. The actions array must be exactly three nodes connected in order by two 'continue' edges:+ a trigger with id 'trigger_node' and config {type:'batch', filters:{properties:[...]}} holding the audience+ as person-property conditions and/or cohort references (empty properties means everyone), then a+ function_email with id 'email_1', config.template_id 'template-email' and config.inputs.email.value+ {to:{email:'{{ person.properties.email }}', name:''}, from:{email, name, integrationId}, subject, preheader,+ html, text}, then an exit with id 'exit_node'. Any other shape does not open in the wizard. Put a verified+ email sender in from when the project has one; otherwise leave from empty and the user picks one in the+ wizard. Write the email as html plus a plain-text fallback, and refine it afterwards with+ workflows-patch-action-email.+ inject_body:+ origin_product: broadcastshog-flow-templates-create:operation: hog_flow_templates_createenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 5fd335a63ac1..279e378538a7 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1711,6 +1711,20 @@},"feature_flag": "organization-billing-api"},+ "broadcasts-create": {+ "description": "Create a broadcast: a one-time or scheduled email to an audience, which the user reviews and launches from the broadcast wizard. It is created as a draft and never sends from this tool; do not enable it, run it or attach a schedule. The actions array must be exactly three nodes connected in order by two 'continue' edges: a trigger with id 'trigger_node' and config {type:'batch', filters:{properties:[...]}} holding the audience as person-property conditions and/or cohort references (empty properties means everyone), then a function_email with id 'email_1', config.template_id 'template-email' and config.inputs.email.value {to:{email:'{{ person.properties.email }}', name:''}, from:{email, name, integrationId}, subject, preheader, html, text}, then an exit with id 'exit_node'. Any other shape does not open in the wizard. Put a verified email sender in from when the project has one; otherwise leave from empty and the user picks one in the wizard. Write the email as html plus a plain-text fallback, and refine it afterwards with workflows-patch-action-email.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Create broadcast",+ "title": "Create broadcast",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"business-knowledge-document-window-retrieve": {"description": "Returns a window of content chunks from a business knowledge document, centered around a specific ordinal. Use after searching knowledge to get more surrounding context for a specific result.","category": "Business knowledge",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 13821b82a84e..89c0b3ccc57a 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1726,6 +1726,20 @@},"feature_flag": "organization-billing-api"},+ "broadcasts-create": {+ "description": "Create a broadcast: a one-time or scheduled email to an audience, which the user reviews and launches from the broadcast wizard. It is created as a draft and never sends from this tool; do not enable it, run it or attach a schedule. The actions array must be exactly three nodes connected in order by two 'continue' edges: a trigger with id 'trigger_node' and config {type:'batch', filters:{properties:[...]}} holding the audience as person-property conditions and/or cohort references (empty properties means everyone), then a function_email with id 'email_1', config.template_id 'template-email' and config.inputs.email.value {to:{email:'{{ person.properties.email }}', name:''}, from:{email, name, integrationId}, subject, preheader, html, text}, then an exit with id 'exit_node'. Any other shape does not open in the wizard. Put a verified email sender in from when the project has one; otherwise leave from empty and the user picks one in the wizard. Write the email as html plus a plain-text fallback, and refine it afterwards with workflows-patch-action-email.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Create broadcast",+ "title": "Create broadcast",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"business-knowledge-document-window-retrieve": {"description": "Returns a window of content chunks from a business knowledge document, centered around a specific ordinal. Use after searching knowledge to get more surrounding context for a specific result.","category": "Business knowledge",diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex f4810fa3c4d9..39c01ab3dfa1 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -8,6 +8,60 @@ import { WorkflowActionEmailPatchSchema, WorkflowGraphPatchSchema } from '@/scheimport { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const BroadcastsCreateSchema = () => {+ const HogFlowsCreateBody = orvalSchemas.HogFlowsCreateBody()+ return HogFlowsCreateBody+}++const broadcastsCreate = (): ToolBase<ReturnType<typeof BroadcastsCreateSchema>, Schemas.HogFlow> => ({+ name: 'broadcasts-create',+ schema: BroadcastsCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof BroadcastsCreateSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }+ if (params.status !== undefined) {+ body['status'] = params.status+ }+ if (params.origin_product !== undefined) {+ body['origin_product'] = params.origin_product+ }+ if (params.trigger_masking !== undefined) {+ body['trigger_masking'] = params.trigger_masking+ }+ if (params.conversion !== undefined) {+ body['conversion'] = params.conversion+ }+ if (params.exit_condition !== undefined) {+ body['exit_condition'] = params.exit_condition+ }+ if (params.email_sending_rate_limit !== undefined) {+ body['email_sending_rate_limit'] = params.email_sending_rate_limit+ }+ if (params.edges !== undefined) {+ body['edges'] = params.edges+ }+ if (params.actions !== undefined) {+ body['actions'] = params.actions+ }+ if (params.variables !== undefined) {+ body['variables'] = params.variables+ }+ body['origin_product'] = 'broadcasts'+ const result = await context.api.request<Schemas.HogFlow>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/`,+ body,+ })+ return result+ },+})+const WorkflowsCreateSchema = () => {const HogFlowsCreateBody = orvalSchemas.HogFlowsCreateBody()return HogFlowsCreateBody@@ -614,6 +668,7 @@ const workflowsUpdateSchedule = (): ToolBase<})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'broadcasts-create': broadcastsCreate,'workflows-create': workflowsCreate,'workflows-discard-draft': workflowsDiscardDraft,'workflows-get': workflowsGet,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.jsonnew file mode 100644index 000000000000..e6f682ac2fd9--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json@@ -0,0 +1,624 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "description": "Mixin for serializers to add user access control fields",+ "properties": {+ "actions": {+ "description": "Ordered action nodes. Exactly one type='trigger' required. Typically one type='exit' too.",+ "items": {+ "properties": {+ "config": {+ "anyOf": [+ {+ "additionalProperties": {},+ "description": "Config for every action type except wait_until_condition — see the field description for per-type shapes.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ {+ "description": "Config for type='wait_until_condition'. Provide 'condition' and/or 'events' — an events-only wait (no condition) is valid.",+ "properties": {+ "condition": {+ "description": "Property-based wait condition; continues when the person matches. A condition with no property filters is ignored — the wait then relies on 'events' and the max_wait_duration timeout.",+ "properties": {+ "filters": {+ "anyOf": [+ {+ "properties": {+ "actions": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "bytecode": {},+ "bytecode_contract": {+ "type": "string"+ },+ "bytecode_error": {+ "type": "string"+ },+ "data_warehouse": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "events": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "filter_test_accounts": {+ "type": "boolean"+ },+ "properties": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "source": {+ "default": "events",+ "description": "* `events` - events\n* `internal-events` - internal-events\n* `person-updates` - person-updates\n* `data-warehouse-table` - data-warehouse-table\n* `data-warehouse-view` - data-warehouse-view",+ "enum": [+ "events",+ "internal-events",+ "person-updates",+ "data-warehouse-table",+ "data-warehouse-view"+ ],+ "type": "string"+ },+ "transpiled": {}+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Property conditions, e.g. {properties: [{key, value, operator, type}]}."+ },+ "name": {+ "description": "Optional display name.",+ "type": "string"+ }+ },+ "type": "object"+ },+ "events": {+ "description": "Events to wait for: continues when ANY entry fires (OR'd with 'condition'). Each entry: {filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}.",+ "items": {+ "properties": {+ "filters": {+ "anyOf": [+ {+ "properties": {+ "actions": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "bytecode": {},+ "bytecode_contract": {+ "type": "string"+ },+ "bytecode_error": {+ "type": "string"+ },+ "data_warehouse": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "events": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "filter_test_accounts": {+ "type": "boolean"+ },+ "properties": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "source": {+ "default": "events",+ "description": "* `events` - events\n* `internal-events` - internal-events\n* `person-updates` - person-updates\n* `data-warehouse-table` - data-warehouse-table\n* `data-warehouse-view` - data-warehouse-view",+ "enum": [+ "events",+ "internal-events",+ "person-updates",+ "data-warehouse-table",+ "data-warehouse-view"+ ],+ "type": "string"+ },+ "transpiled": {}+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Event/action filters; the workflow wakes when a matching event fires. Must target at least one event or action (entries targeting neither are dropped)."+ },+ "name": {+ "description": "Optional display name.",+ "type": "string"+ }+ },+ "type": "object"+ },+ "type": "array"+ },+ "max_wait_duration": {+ "description": "'<number><unit>' with unit s|m|h|d, e.g. '30m' (same rules as delay).",+ "type": "string"+ }+ },+ "required": ["max_wait_duration"],+ "type": "object"+ }+ ],+ "description": "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel|internal-event, filters?}. An active event trigger must name at least one event, action or property filter; with filters.source 'person-updates' that means at least one property filter. internal-event requires filters.events naming one or more allowed event ids, and runs once for each matching event on the internal-events stream. Runs are person-less, so person-dependent steps are rejected. $slack_message_received takes filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply), and requires an exact-match channel filter; without one it runs on every message in every connected channel. $github_event_received takes filters: {properties: [<cond>]} over the delivery properties (repository, event_type, action, sender, bot_sender, own_app, author_association, actor_access, title, body, review_state, branch, repository_visibility), and requires exact-match repository and event_type filters; without them it runs on every delivery from every connected repository. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assignment_status: 'all'|'assigned'|'unassigned', and assigned_to_user_ids: [<int>] when assignment_status is 'assigned'. all_roles_unassigned remains accepted for workflows saved before assignment_status was added. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: waits a fixed span or until a per-person/-event date — set EXACTLY ONE of delay_duration or delay_until. {delay_duration: '<number><unit>'} where unit is s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ },+ "created_at": {+ "description": "Created at (epoch ms). Frontend-managed.",+ "type": "number"+ },+ "description": {+ "default": "",+ "description": "Optional description.",+ "type": "string"+ },+ "filters": {+ "anyOf": [+ {+ "properties": {+ "actions": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "bytecode": {},+ "bytecode_contract": {+ "type": "string"+ },+ "bytecode_error": {+ "type": "string"+ },+ "data_warehouse": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "events": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "filter_test_accounts": {+ "type": "boolean"+ },+ "properties": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "source": {+ "default": "events",+ "description": "* `events` - events\n* `internal-events` - internal-events\n* `person-updates` - person-updates\n* `data-warehouse-table` - data-warehouse-table\n* `data-warehouse-view` - data-warehouse-view",+ "enum": [+ "events",+ "internal-events",+ "person-updates",+ "data-warehouse-table",+ "data-warehouse-view"+ ],+ "type": "string"+ },+ "transpiled": {}+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Property filters gating this action."+ },+ "id": {+ "description": "Unique node ID within the workflow.",+ "maxLength": 200,+ "type": "string"+ },+ "name": {+ "description": "Display name.",+ "maxLength": 400,+ "type": "string"+ },+ "on_error": {+ "anyOf": [+ {+ "description": "* `continue` - continue\n* `abort` - abort",+ "enum": ["continue", "abort"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "On failure: continue (skip the action and proceed) or abort (stop the run).\n\n* `continue` - continue\n* `abort` - abort"+ },+ "output_variable": {+ "description": "Output variable for downstream actions: {key, result_path?, spread?, label?} or a list of those."+ },+ "type": {+ "description": "One of: trigger | function | function_email | function_sms | function_push | delay | wait_until_condition | wait_until_time_window | conditional_branch | random_cohort_branch | exit.\n\n* `trigger` - trigger\n* `function` - function\n* `function_email` - function_email\n* `function_sms` - function_sms\n* `function_push` - function_push\n* `delay` - delay\n* `wait_until_condition` - wait_until_condition\n* `wait_until_time_window` - wait_until_time_window\n* `conditional_branch` - conditional_branch\n* `random_cohort_branch` - random_cohort_branch\n* `exit` - exit",+ "enum": [+ "trigger",+ "function",+ "function_email",+ "function_sms",+ "function_push",+ "delay",+ "wait_until_condition",+ "wait_until_time_window",+ "conditional_branch",+ "random_cohort_branch",+ "exit"+ ],+ "type": "string"+ },+ "updated_at": {+ "description": "Updated at (epoch ms). Frontend-managed.",+ "type": "number"+ }+ },+ "required": ["id", "name", "type", "config"],+ "type": "object"+ },+ "type": "array"+ },+ "conversion": {+ "anyOf": [+ {+ "properties": {+ "bytecode": {+ "description": "Compiled server-side from 'filters'. Do not set; ignored if sent."+ },+ "events": {+ "description": "Event-based conversion goals: [{filters: {events: [{id, name, type: 'events'}], ...}}].",+ "items": {+ "properties": {+ "filters": {+ "description": "Event/action filters for this conversion event, same shape as trigger filters: {events: [{id, name, type: 'events', properties?: [<cond>]}], actions?: [...], properties?: [<cond>]}. bytecode is compiled server-side.",+ "properties": {+ "actions": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "bytecode": {},+ "bytecode_contract": {+ "type": "string"+ },+ "bytecode_error": {+ "type": "string"+ },+ "data_warehouse": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "events": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "filter_test_accounts": {+ "type": "boolean"+ },+ "properties": {+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "source": {+ "default": "events",+ "description": "* `events` - events\n* `internal-events` - internal-events\n* `person-updates` - person-updates\n* `data-warehouse-table` - data-warehouse-table\n* `data-warehouse-view` - data-warehouse-view",+ "enum": [+ "events",+ "internal-events",+ "person-updates",+ "data-warehouse-table",+ "data-warehouse-view"+ ],+ "type": "string"+ },+ "transpiled": {}+ },+ "type": "object"+ }+ },+ "required": ["filters"],+ "type": "object"+ },+ "type": "array"+ },+ "filters": {+ "description": "Property-based conversion conditions, as an ARRAY of property filters: [{key, value, operator, type: event|person|group}, ...]. Event-based goals do NOT go here — put them in 'events'. Empty array = any event within the window converts.",+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },+ "window": {+ "anyOf": [+ {+ "maxLength": 32,+ "pattern": "^(?:[0-9]+(?:\\.[0-9]+)?|\\.[0-9]+)[dhms]$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "How long after entering the workflow a conversion still counts, as a duration string: '7d', '12h', '30m', '45s'. Same form the delay steps use. Must be longer than zero, and at most '365d'. Omit it to use the default of 90 days."+ }+ },+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Conversion goal. filters: ARRAY of property conditions [{key, value, operator, type: event|person|group}]; events: event-based goals [{filters: {events: [...]}}]; window: how long after entry a conversion counts, as a duration string such as '7d' or '12h', maximum '365d'. Required for exit_on_conversion / exit_on_trigger_not_matched_or_conversion. bytecode compiled server-side."+ },+ "description": {+ "default": "",+ "description": "Optional description.",+ "type": "string"+ },+ "edges": {+ "description": "Graph edges: [{from, to, type: 'continue'|'branch', index?}]. 'continue' = fall-through (sequential, or no-match path of conditional_branch). 'branch' requires 'index': matches config.conditions[index] on conditional_branch / wait_until_condition. Every non-exit action needs a reachable next action ('No next action found' otherwise).",+ "items": {+ "properties": {+ "from": {+ "description": "Source action id.",+ "type": "string"+ },+ "index": {+ "description": "Required for type='branch'. conditional_branch: index into config.conditions[index]. random_cohort_branch: index into config.cohorts[index]. wait_until_condition: use index:0 — it advances via the index:0 branch edge when it resolves (a condition match or an events entry firing).",+ "type": "number"+ },+ "to": {+ "description": "Target action id.",+ "type": "string"+ },+ "type": {+ "description": "continue: fall-through (sequential or the no-match path of conditional_branch). branch: requires 'index' matching config.conditions[index].\n\n* `continue` - continue\n* `branch` - branch",+ "enum": ["continue", "branch"],+ "type": "string"+ }+ },+ "required": ["to", "type", "from"],+ "type": "object"+ },+ "type": "array"+ },+ "email_sending_rate_limit": {+ "anyOf": [+ {+ "properties": {+ "count": {+ "description": "Maximum number of emails this workflow sends per period.",+ "maximum": 1000000,+ "minimum": 1,+ "type": "number"+ },+ "period": {+ "description": "Window the count applies to. Sends over the limit are delayed until capacity frees up, not dropped.\n\n* `minute` - minute\n* `hour` - hour",+ "enum": ["minute", "hour"],+ "type": "string"+ }+ },+ "required": ["count", "period"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional email pacing for deliverability: {count, period: 'minute' | 'hour'}. The email worker spreads this workflow's sends to stay under the limit; over-limit sends wait for capacity instead of failing. Null disables pacing."+ },+ "exit_condition": {+ "description": "exit_only_at_end: only at exit node (default). exit_on_conversion: also on conversion (needs 'conversion'; silent no-op otherwise). exit_on_trigger_not_matched: also when trigger filter stops matching. exit_on_trigger_not_matched_or_conversion: both (needs 'conversion').\n\n* `exit_on_conversion` - Conversion\n* `exit_on_trigger_not_matched` - Trigger Not Matched\n* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n* `exit_only_at_end` - Only At End",+ "enum": [+ "exit_on_conversion",+ "exit_on_trigger_not_matched",+ "exit_on_trigger_not_matched_or_conversion",+ "exit_only_at_end"+ ],+ "type": "string"+ },+ "name": {+ "anyOf": [+ {+ "maxLength": 400,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Workflow name."+ },+ "origin_product": {+ "anyOf": [+ {+ "description": "* `loops` - Loops\n* `broadcasts` - Broadcasts",+ "enum": ["loops", "broadcasts"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Product surface that owns this workflow (e.g. `loops` for Desktop loops). Set only when creating a workflow. Filter the list with `?origin_product=`.\n\n* `loops` - Loops\n* `broadcasts` - Broadcasts"+ },+ "status": {+ "description": "draft (no execution), active (live), archived (disabled).\n\n* `draft` - Draft\n* `active` - Active\n* `archived` - Archived",+ "enum": ["draft", "active", "archived"],+ "type": "string"+ },+ "trigger_masking": {+ "anyOf": [+ {+ "properties": {+ "bytecode": {+ "description": "Auto-compiled from hash. Do not set."+ },+ "hash": {+ "description": "HogQL template defining the dedup/grouping key, e.g. '{person.id}' (once per person) within ttl.",+ "type": "string"+ },+ "threshold": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Fire once per N matches of the same hash within ttl — a sampler: N=3 fires on the 1st, 4th, 7th… match. Omit to fire on the first match, then suppress repeats within ttl."+ },+ "ttl": {+ "anyOf": [+ {+ "maximum": 94608000,+ "minimum": 60,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Seconds (60 to ~94M / 3y) to suppress repeat firings of the same hash."+ }+ },+ "required": ["hash"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional dedup/throttle on an already-matched trigger: {hash: <HogQL template>, ttl: <seconds, 60-94608000>, threshold?: <int>}. Without threshold: fire once per hash, then suppress repeats within ttl (hash '{person.id}' = once per person per ttl). With threshold N: fire once per N matches of the same hash — a sampler, the 1st then every Nth. Throttles an already-qualifying trigger; it doesn't decide who enters. Server compiles bytecode from hash; omit to disable."+ },+ "variables": {+ "description": "Workflow vars (key, type, default). Total <5KB.",+ "items": {+ "additionalProperties": {+ "type": "string"+ },+ "description": "Variable: {key, type: string|number|boolean, default}.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["actions"],+ "type": "object"+}