: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): add broadcasts prototype on top of workflows (#82343)
Daniel Marchuk6c3603f5a99f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b51024863327..8047b7c4682a 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2177,13 +2177,13 @@ snapshots:components-sample-data-state--wizard-installing--light:hash: v1.k794b7964.2052c49beff2e0a5c5c533ae05c73bacc2619a04053b4529acf93574160c3a66.sTXp62J02o4EVCFfSt9_QV7YwS6UN87FpVxkPGrmZ3ocomponents-search--default--dark:- hash: v1.k794b7964.4d547ac55501863b11034e51dfa0e6da46277ddb82d93dfff89bceb95ca3c457.xmcEpMR2kLjRqYgG8WhE7NMfZ4aq18g8E0y3UZTt_ek+ hash: v1.k794b7964.df826309ab6f79dd0e723266609072d8155ff6369f28981fd4f30aab3f3b33c5.QynuzGnFBVv5SVsZ0i1NmHz8sj1B6Sf141Ccpckxdxkcomponents-search--default--light:- hash: v1.k794b7964.4b12fa9beacbe7bd53eceed4c9506c4b72d3f965ef420371c90fc9ff2869d0e0.kwiTpTyd5He77Bw8P62p8IH4KgzmWQ0Ny1v7MsMtLpo+ hash: v1.k794b7964.8307816a710b634b4f755c0f584e7f778df593e71a7cb09ba78e62cf8bba5f57.hBPSJcqGMoi4cRbXv50OKANFPwec3pvdHyohoRI7uY4components-search--product-recents-and-starred--dark:- hash: v1.k794b7964.d4f3237e829a99a011fa463d061944dd2af82e010292656dde0c1052d893a2dc.dy_2uM10B_3hbRAPCMmt3tJlGObSqT5M27Tdk8BEaUw+ hash: v1.k794b7964.8ad383ffceb9b13eaa277b7a9f2669f664d3baf41e6de0c88c76d7270be14528.tRgtu-HnITjd9j5SOXmx14UfUqURzHUye2BpcOYIqp0components-search--product-recents-and-starred--light:- hash: v1.k794b7964.419cabcff30a22d68b283cf59562b74ca2d4910552fc4240e95b856303622508.0xCO-YA2i8xkqSjPXRWXjmLuVEiiP11XfIC6v9y77yU+ hash: v1.k794b7964.399cb172e81803597bf57053a5b00d30c286cb5ddf1d36b124a9ee8ba0556a3f.cFfdrCFp8jWHF-Ds9CDLZJg8ZlpohmTNgH70qM-OD5wcomponents-search--searching--dark:hash: v1.k794b7964.8640758c2d98a5f809ee318f61dc1e7669888757862a940b220e241742894ae2.3-TrMOHcLmJQNhFO0CuB3dEBeLcO-Cx-6lPP3jmfqzccomponents-search--searching--light:@@ -6001,9 +6001,9 @@ snapshots:products-data-modeling-model-downstream-summary--one-dependent-model--light:hash: v1.k794b7964.3781c6628ca1661df8c04dca9810e60e506339605cc7cf450c92f04d192e8e43.VSEp-9GtYN9N2rEpDX857fuikGwj_Te0u8y5aEqi_vsproducts-data-modeling-model-health-summary--completed--dark:- hash: v1.k794b7964.9ff59e8b73debe6a9a048c9acf2e2f75d3b2bee39333cf98a6076366332cedaa.8qsnlXL2fe2IKBQussZl00gQFvu16vlXlz0UXOWlEF4+ hash: v1.k794b7964.9cc469bbaef73328746c4ac6e81de0642d88ef96873576cfade18a4b6e9286e0.X8VeEn2p1rOdvI_CdJ1LAN_0-Qu_dtlRx1uQlE7t_Ocproducts-data-modeling-model-health-summary--completed--light:- hash: v1.k794b7964.ad2217f8103b0deaa5915468e4d87acbbde45729a4f571a2ce1a40ab01459675.g0WsEC9FhlErrHFFR6eyQ-JoAi5fvTrPSwasujUT7Hk+ hash: v1.k794b7964.4de53541f1249d0fb5beb418d582c65cda06eb36176807b4106bdf2bf3ed8a89.VyuxhEpCuUGzcKDXqjagV_YMAaeEkbXBIJEzOXHYGH4products-data-modeling-model-health-summary--failed--dark:hash: v1.k794b7964.c2997410c93e687b52914697b9701bd501a5ff2376a5d2092f2bdfbc33934db6.Zuvfn3zd5xYDRzSgMMEtt5nebN_9UWJEIcPSbZdVxWYproducts-data-modeling-model-health-summary--failed--light:@@ -6025,9 +6025,9 @@ snapshots:products-data-modeling-model-health-summary--narrow--light:hash: v1.k794b7964.e21979877fbe3c641b5fcf07731626126b51cb13b0feb652eae14c806850addf.qPtHjCRtiajbTPO_yDTncVlCGwwexFfGu-6k4ZR_F8sproducts-data-modeling-model-health-summary--running--dark:- hash: v1.k794b7964.2076c83ec1d36139c2ef392973619c3a97897c9ae5847c3d5085e4e3e8c46d1a.9FvGoMy8oGICwcBG2egoXfe2SWvW_q02FoTAYz3MAtE+ hash: v1.k794b7964.3d5813d589d6df8c849d1d0ecb3c4feadb34d7e48a190c6a7fed5ccb0b27848c.PBT6ffPfT9Cr_-ee_IJllSy3kmYQxuyCT_7pQCP2vDwproducts-data-modeling-model-health-summary--running--light:- hash: v1.k794b7964.62c724686b262a72d78e6fc0d59d1e5cdc39a0881c3024e67c527222594d563a._GhHEDolqGZzlvpgyglS22bjlhGG_UP7M9LNk9xS3eA+ hash: v1.k794b7964.467fc05c1d1434d678fabaa13455ddc7110d3c533afb867207ae6b1b05f64f4f.c7PSGKdTA0iHiz0VY_y8oZxDHeTfpCUSVohNEUubBhIproducts-data-modeling-model-health-summary--stale-history--dark:hash: v1.k794b7964.dd11f5b4fa0945c0a0956dc2fcc92bfcc11825b46786115540141039963d25d9.XAsL4Vbhk9so5SFnBNbtT3GIW8PfPqdrOR9v8qIO4k0products-data-modeling-model-health-summary--stale-history--light:@@ -10693,9 +10693,9 @@ snapshots:scenes-app-settings-user--settings-user-danger-zone--light:hash: v1.k794b7964.a18b0b851dcc99fc9c512c6809bcd9408d2d7710a1af1232600a330dfff18ac7.1Eo9vX2Xbpx00k_YhM-UEEsRXSEThzmS94cEEjcsfBsscenes-app-settings-user--settings-user-navigation--dark:- hash: v1.k794b7964.72b15c00b0ac4189aedbbece522c1b6549477de150ed88c907738f382d434619.e-MixdhMT5OmxKOCvKZ9ChOZO6zEtzv3qDssYH0yDwQ+ hash: v1.k794b7964.655266e72606c65c0922a40d98410f478eb0542a37d0bfa305c0e600af4d0147.EDoad7G4aG8TKsdZTvpfTL5vf40ENzKTExb2Z0vM5Pwscenes-app-settings-user--settings-user-navigation--light:- hash: v1.k794b7964.82cd75d315bdb6d00f3981ee6cd4212449a1a826cf7f5eb125c8596e7053a969.UkMkh-ocaZ9Zqjvvdx9WZQOWQ-5o6xQpUpttZfEs9Io+ hash: v1.k794b7964.51462652a0da70888f647c0bdbce33df42ab4cb60b1dac41a34185a075de3c21.MRiQE2Gd9oXVIzclsX7BkSvPuNgwS-0Mc1VUybzLgxkscenes-app-settings-user--settings-user-notifications--dark:hash: v1.k794b7964.71bacadb9ac5b0c487720425bf966d89a9c54f455faa1a892ff5ea907f6e329e.zXpXJ8VNwNQLHAZ2zdWcAv4Dlrp2aYxY6RxMaQt2SPUscenes-app-settings-user--settings-user-notifications--light:diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsxindex 8fb9708ee9e1..d27f5dc0021e 100644--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx@@ -32,6 +32,7 @@ import {IconLlmPromptManagement,IconMCP,IconMegaphone,+ IconSend,IconMessage,IconNotebook,IconNotification,@@ -216,6 +217,10 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Filicon: <IconDecisionTree />,iconColor: ['var(--color-product-workflows-light)', 'var(--color-product-workflows-dark)'],},+ broadcasts: {+ icon: <IconSend />,+ iconColor: ['var(--color-product-workflows-light)'],+ },notebook: {icon: <IconNotebook />,iconColor: ['var(--color-product-notebooks-light)', 'var(--color-product-notebooks-dark)'],diff --git a/frontend/src/layout/panel-layout/sidebarToolMeta.ts b/frontend/src/layout/panel-layout/sidebarToolMeta.tsindex 42f042ab971b..080e52648ba5 100644--- a/frontend/src/layout/panel-layout/sidebarToolMeta.ts+++ b/frontend/src/layout/panel-layout/sidebarToolMeta.ts@@ -9,6 +9,7 @@ import { FileSystemImport } from '~/queries/schema/schema-general'export const SIDEBAR_TOOLS_WITHOUT_DOCS = new Set<string>(['AI gateway','Apps',+ 'Broadcasts','Business knowledge','Engineering analytics','Identity matching',diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 37dea37b2191..5340727da028 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -486,6 +486,9 @@ export class ApiConfig {}}+/** A workflow's type: the surface that owns it, else what it does. */+export type HogFlowListType = 'messaging' | 'automation' | 'loop' | 'broadcast'+export class ApiRequest {private pathComponents: string[]private queryString: string | undefined@@ -6432,13 +6435,18 @@ const api = {search?: stringstatus?: HogFlow['status']created_by?: string- type?: 'messaging' | 'automation' | 'loop'+ type?: HogFlowListType[]/** JSON-encoded object the stored trigger must contain, e.g. `{"type":"batch"}`. */trigger?: stringlimit?: numberoffset?: number}): Promise<CountedPaginatedResponse<HogFlow>> {- return await new ApiRequest().hogFlows().withQueryString(params).get()+ // The API reads one comma-separated value; toParams would send a repeated key.+ const { type, ...rest } = params ?? {}+ return await new ApiRequest()+ .hogFlows()+ .withQueryString({ ...rest, ...(type?.length ? { type: type.join(',') } : {}) })+ .get()},async getHogFlow(hogFlowId: HogFlow['id']): Promise<HogFlow> {return await new ApiRequest().hogFlow(hogFlowId).get()diff --git a/frontend/src/lib/utils/liquid.test.ts b/frontend/src/lib/utils/liquid.test.tsnew file mode 100644index 000000000000..c53330cad2bb--- /dev/null+++ b/frontend/src/lib/utils/liquid.test.ts@@ -0,0 +1,26 @@+import { LiquidRenderer } from './liquid'++describe('LiquidRenderer', () => {+ const context = { person: { properties: { first_name: 'Ada', company: null } } }++ it('renders a template the editor has escaped', () => {+ // Unlayer stores `>` as `>`, so a renderer that skips the decode step compares the+ // literal entity and silently takes the wrong branch.+ const template =+ '{% if person.properties.first_name != "" %}Hi {{ person.properties.first_name }}{% endif %}'+ expect(LiquidRenderer.render(template, context)).toBe('Hi Ada')+ })++ it.each([+ ['person.properties.first_name', true],+ ['person.properties.company', false],+ ['person.properties.missing', false],+ ['person.properties.first_name | upcase', true],+ ])('resolves(%s) is %s', (expression, expected) => {+ expect(LiquidRenderer.resolves(expression, context)).toBe(expected)+ })++ it('treats an unparseable expression as unresolved rather than throwing', () => {+ expect(LiquidRenderer.resolves('person.properties[', context)).toBe(false)+ })+})diff --git a/frontend/src/lib/utils/liquid.ts b/frontend/src/lib/utils/liquid.tsindex 394f7ab022c6..984ed5ce8430 100644--- a/frontend/src/lib/utils/liquid.ts+++ b/frontend/src/lib/utils/liquid.ts@@ -1,5 +1,5 @@// Lazy load liquid library-import { Liquid, Template } from 'liquidjs'+import { Liquid, Output, Template } from 'liquidjs'const LIQUID_REGEX = /\{\{(.*?)\}\}|{%(.*?)%}/g@@ -11,23 +11,81 @@ export class LiquidRenderer {if (!this._liquid) {this._liquid = new Liquid({outputEscape: 'escape',+ // Render partials from an in-memory map only: this disables LiquidJS's filesystem-backed+ // partial loading, so user-controlled templates can't read local files via include/render/layout.+ templates: {},})}return this._liquid}+ private static decodeEntities(source: string): string {+ return source+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/&/g, '&') // NOTE: This should always be last+ }++ // TRICKY: Unlayer replaces all liquid's elements like > for example with >+ // We need to decode these but _only_ for the liquid elements i.e. content within {{ }} or {% %}+ private static decode(template: string): string {+ return template.replace(LIQUID_REGEX, (match) => this.decodeEntities(match))+ }+public static parse(template: string): Template[] {- // TRICKY: Unlayer replaces all liquid's elements like > for example with >- // We need to decode these but _only_ for the liquid elements i.e. content within {{ }} or {% %}- const decodedTemplate = template.replace(LIQUID_REGEX, (match) => {- return match- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"')- .replace(/'/g, "'")- .replace(/&/g, '&') // NOTE: This should always be last- })-- return this.liquid.parse(decodedTemplate)+ return this.liquid.parse(this.decode(template))+ }++ /** Mirrors what the worker renders at send time. Throws on an unparseable template. */+ public static render(template: string, context: Record<string, any>): string {+ return this.liquid.parseAndRenderSync(this.decode(template), context)+ }++ /**+ * Takes the expression as it appears in the template, so it decodes the editor's escaping first.+ */+ public static resolves(expression: string, context: Record<string, any>): boolean {+ return this.resolvesDecoded(this.decodeEntities(expression), context)+ }++ private static resolvesDecoded(expression: string, context: Record<string, any>): boolean {+ try {+ const value = this.liquid.evalValueSync(expression, context)+ return value !== undefined && value !== null+ } catch {+ return false+ }+ }++ /**+ * Render, but leave an output tag whose expression resolves to nothing as its own source text+ * instead of the empty string a plain render produces, so a reader sees which variables are+ * missing rather than a blank space.+ *+ * An expression carrying a filter renders normally, because the filter may be the fallback+ * (`| default:`), so an undefined value there is not necessarily a gap.+ *+ * Additive to the worker's copy of this class, which only ever renders the real thing.+ */+ public static renderKeepingUnresolved(template: string, context: Record<string, any>): string {+ const decoded = this.decode(template)+ let marked = ''+ let cursor = 0+ for (const node of this.liquid.parse(decoded)) {+ if (!(node instanceof Output)) {+ continue+ }+ const { begin, end, content } = node.token as unknown as { begin: number; end: number; content: string }+ const expression = content.trim()+ if (!expression || expression.includes('|') || this.resolvesDecoded(expression, context)) {+ continue+ }+ marked += `${decoded.slice(cursor, begin)}{% raw %}${decoded.slice(begin, end)}{% endraw %}`+ cursor = end+ }+ // `marked` is already decoded, so render it without a second pass.+ return this.liquid.parseAndRenderSync(marked + decoded.slice(cursor), context)}}diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 78bc598671d0..4dedddad0921 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -177,4 +177,5 @@ export const productScenes: Record<string, () => Promise<any>> = {Workflows: () => import('../../products/workflows/frontend/WorkflowsScene'),Workflow: () => import('../../products/workflows/frontend/Workflows/WorkflowScene'),WorkflowsLibraryTemplate: () => import('../../products/workflows/frontend/TemplateLibrary/MessageTemplate'),+ Broadcast: () => import('../../products/workflows/frontend/Broadcasts/BroadcastScene'),}diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex 3ace2865cc3b..301866121898 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -277,6 +277,13 @@"iconType": "workflows","type": "workflows","intents": ["workflows"]+ },+ {+ "path": "Broadcasts",+ "category": "Tools",+ "iconType": "broadcasts",+ "type": "broadcasts",+ "intents": ["workflows"]}],"games": [diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 0fd85c654bc2..37bec1e41e6f 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -285,6 +285,8 @@ export const productRoutes: Record<string, [string, string]> = {'/wizard/runs': ['WizardRuns', 'wizardRuns'],'/workflows': ['Workflows', 'workflows'],'/workflows/:tab': ['Workflows', 'workflows'],+ '/workflows/broadcasts/new': ['Broadcast', 'broadcast'],+ '/workflows/broadcasts/:id': ['Broadcast', 'broadcast'],'/workflows/:id/:tab': ['Workflow', 'workflowTab'],'/workflows/library/templates/:id': ['WorkflowsLibraryTemplate', 'workflowsLibraryTemplate'],'/workflows/library/templates/new': ['WorkflowsLibraryTemplate', 'workflowsLibraryTemplate'],@@ -1084,6 +1086,12 @@ export const productConfiguration: Record<string, any> = {},Workflow: { name: 'Workflows', iconType: 'workflows', projectBased: true },WorkflowsLibraryTemplate: { name: 'Workflows', iconType: 'workflows', projectBased: true },+ Broadcast: {+ name: 'Broadcast',+ iconType: 'workflows',+ projectBased: true,+ description: 'Send a one-time or scheduled email to a group of people',+ },}/** This const is auto-generated, as is the whole file */@@ -1647,6 +1655,9 @@ export const productUrls = {workflowsLibraryTemplate: (id?: string): string => `/workflows/library/templates/${id}`,workflowsLibraryTemplateNew: (): string => '/workflows/library/templates/new',workflowsLibraryTemplateFromMessage: (id?: string): string => `/workflows/library/templates/new?messageId=${id}`,+ broadcasts: (): string => '/workflows/broadcasts',+ broadcast: (id: string): string => `/workflows/broadcasts/${id}`,+ broadcastNew: (): string => '/workflows/broadcasts/new',}/** This const is auto-generated, as is the whole file */@@ -1973,6 +1984,7 @@ export const getTreeItemsNew = (): FileSystemImport[] => [export type ProductTreePath =| 'AI gateway'| 'Apps'+ | 'Broadcasts'| 'Business knowledge'| 'Clusters'| 'Code review'@@ -2052,6 +2064,17 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [sceneKey: 'StreamlitApps',sceneKeys: ['StreamlitApps', 'StreamlitApp', 'StreamlitAppEdit'],},+ {+ path: 'Broadcasts',+ intents: [ProductKey.WORKFLOWS],+ href: urls.broadcasts(),+ type: 'broadcasts',+ category: ProductItemCategory.TOOLS,+ iconType: 'broadcasts',+ iconColor: ['var(--color-product-workflows-light)'] as FileSystemIconColor,+ sceneKey: 'Broadcast',+ sceneKeys: ['Workflows', 'Workflow', 'WorkflowsLibraryTemplate', 'Broadcast'],+ },{path: 'Business knowledge',intents: [ProductKey.CONVERSATIONS],@@ -2787,7 +2810,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [iconType: 'workflows',iconColor: ['var(--color-product-workflows-light)'] as FileSystemIconColor,sceneKey: 'Workflows',- sceneKeys: ['Workflows', 'Workflow', 'WorkflowsLibraryTemplate'],+ sceneKeys: ['Workflows', 'Workflow', 'WorkflowsLibraryTemplate', 'Broadcast'],},]diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex ed5b35ebf803..36a6d3120cb9 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -26846,6 +26846,7 @@"tracing","metrics","workflows",+ "broadcasts","notebook","action","activity",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 5ade824cada0..159369a993af 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5314,6 +5314,7 @@ export type FileSystemIconType =| 'tracing'| 'metrics'| 'workflows'+ | 'broadcasts'| 'notebook'| 'action'| 'activity'diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 2fc25e4d0418..9a9196a8773a 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -209,6 +209,8 @@ export enum Scene {Endpoint = 'Endpoint',Workflow = 'Workflow',Workflows = 'Workflows',+ Broadcast = 'Broadcast',+ Wizard = 'Wizard',EarlyAccessFeature = 'EarlyAccessFeature',EndpointsScene = 'EndpointsScene',Game368Hedgehogs = 'Game368Hedgehogs',@@ -423,6 +425,7 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr// Workflows[Scene.Workflow]: AccessControlResourceType.Workflow,[Scene.Workflows]: AccessControlResourceType.Workflow,+ [Scene.Broadcast]: AccessControlResourceType.Workflow,// Product Tours[Scene.ProductTour]: AccessControlResourceType.ProductTour,diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 820e61a23728..3122a360b636 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -1382,6 +1382,7 @@ class FileSystemIconType(StrEnum):TRACING = "tracing"METRICS = "metrics"WORKFLOWS = "workflows"+ BROADCASTS = "broadcasts"NOTEBOOK = "notebook"ACTION = "action"ACTIVITY = "activity"diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 69237c49d5a7..6194566d1b6a 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -6,7 +6,7 @@ import dataclassesfrom copy import deepcopyfrom datetime import datetime, timedeltafrom time import monotonic-from typing import Any, NamedTuple, Optional, cast+from typing import Any, Final, NamedTuple, Optional, castfrom zoneinfo import ZoneInfo, ZoneInfoNotFoundErrorfrom django.conf import settings@@ -3784,12 +3784,39 @@ class CommaSeparatedListFilter(BaseInFilter, CharFilter):pass+# A workflow's type is what owns it, else what it does. `loop` and `broadcast` name the surfaces that+# have their own page, and the behavioural values exclude them: a flow those surfaces own is tagged+# by surface in the UI (see WorkflowTypeTag), so returning it under `messaging` would contradict the+# tag on the row. Accepting several lets a list say which surfaces it covers, which is how the+# workflows page asks for everything except the ones that moved out.+WORKFLOW_TYPES: Final[tuple[str, ...]] = ("messaging", "automation", "loop", "broadcast")+OWNED_WORKFLOW_TYPES: Final[dict[str, str]] = {+ "loop": HogFlow.OriginProduct.LOOPS,+ "broadcast": HogFlow.OriginProduct.BROADCASTS,+}+++def workflow_type_q(requested: set[str]) -> Q:+ owned = Q(origin_product__in=[OWNED_WORKFLOW_TYPES[t] for t in requested if t in OWNED_WORKFLOW_TYPES])+ behavioural = requested - set(OWNED_WORKFLOW_TYPES)+ if not behavioural:+ return owned++ messaging = Q()+ for action_type in MESSAGING_ACTION_TYPES:+ messaging |= Q(actions__contains=[{"type": action_type}])+ unowned = ~Q(origin_product__in=list(OWNED_WORKFLOW_TYPES.values()))+ if behavioural == {"messaging", "automation"}:+ return owned | unowned+ return owned | (unowned & (messaging if behavioural == {"messaging"} else ~messaging))++class HogFlowFilterSet(FilterSet):class Meta:model = HogFlow# `created_by` is filtered by uuid in safely_get_queryset (the list UI's member picker keys on# uuid, not pk), so it's deliberately not an exact-match field here.- fields = ["id", "created_at", "updated_at", "status"]+ fields = ["id", "created_at", "updated_at", "status", "origin_product"]class HogFlowPagination(LimitOffsetPagination):@@ -3915,8 +3942,7 @@ WRITABLE_DRAFT_CONTENT_FIELDS = frozenset(DRAFT_CONTENT_FIELDS) - frozenset(HogFOpenApiParameter("type",OpenApiTypes.STR,- enum=["messaging", "automation", "loop"],- description="Filter by workflow type. `loop` returns workflows owned by a Desktop loop; `messaging` returns the remaining workflows with an email, SMS, or push action; `automation` returns the rest.",+ description="Comma-separated workflow types. `loop` and `broadcast` return the workflows those surfaces own; `messaging` returns the remaining workflows with an email, SMS, or push action, and `automation` the rest.",),OpenApiParameter("origin_product",@@ -4061,22 +4087,17 @@ class HogFlowViewSet(workflow_type = self.request.GET.get("type")if workflow_type:- if workflow_type not in ("messaging", "automation", "loop"):- raise exceptions.ValidationError({"type": "Must be one of: messaging, automation, loop"})- if workflow_type == "loop":- queryset = queryset.filter(origin_product=HogFlow.OriginProduct.LOOPS)- else:- # A loop-origin workflow renders a "Loop" tag regardless of its actions (see- # WorkflowTypeTag), so it must not also match messaging/automation - otherwise- # picking one of those filters could return rows the UI still labels "Loop".- messaging_q = Q()- for action_type in MESSAGING_ACTION_TYPES:- messaging_q |= Q(actions__contains=[{"type": action_type}])- queryset = queryset.exclude(origin_product=HogFlow.OriginProduct.LOOPS)- queryset = (- queryset.filter(messaging_q) if workflow_type == "messaging" else queryset.exclude(messaging_q)- )-+ requested = {value for value in workflow_type.split(",") if value}+ unknown = sorted(requested - set(WORKFLOW_TYPES))+ # A value of only separators names no type. Filtering on nothing would answer with an+ # empty list, so it is rejected the way any other unusable value is.+ if unknown or not requested:+ named = f"Unknown: {', '.join(unknown)}. " if unknown else ""+ raise exceptions.ValidationError({"type": f"{named}Must be one of: {', '.join(WORKFLOW_TYPES)}"})+ queryset = queryset.filter(workflow_type_q(requested))++ # `?type=loop` and `?type=broadcast` return the same rows, but Desktop's Loops list sends+ # this param and ships on its own release cadence, so installed builds keep sending it.origin_product = self.request.GET.get("origin_product")if origin_product:if origin_product not in HogFlow.OriginProduct.values:diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 9db78fb3b7d0..13dccb392bb5 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -391,6 +391,16 @@ class TestHogFlowAPI(APIBaseTest):("messaging", "messaging", {"Email drip", "Push blast"}),("automation", "automation", {"Webhook sync"}),("loop", "loop", {"Loop with email action"}),+ ("broadcast", "broadcast", {"Announcement"}),+ # What the workflows page sends: everything except the surfaces with their own page.+ (+ "everything_but_broadcasts",+ "messaging,automation,loop",+ {"Email drip", "Push blast", "Webhook sync", "Loop with email action"},+ ),+ # A repeated value used to fall through to the negated branch and answer with the+ # automation rows, the exact opposite of what was asked for.+ ("repeated_value", "messaging,messaging", {"Email drip", "Push blast"}),])def test_list_filter_by_workflow_type(self, _name, workflow_type, expected_names):@@ -423,12 +433,30 @@ class TestHogFlowAPI(APIBaseTest):actions=[{"id": "a", "type": "function_email", "config": {}}],)+ # A broadcast carries an email action, so without the surface check it would also answer+ # `messaging` and contradict the tag its row shows.+ HogFlow.objects.create(+ team=self.team,+ name="Announcement",+ created_by=self.user,+ origin_product="broadcasts",+ actions=[{"id": "a", "type": "function_email", "config": {}}],+ )+response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?type={workflow_type}")assert response.status_code == 200, response.json()assert {flow["name"] for flow in response.json()["results"]} == expected_names- def test_list_filter_by_workflow_type_rejects_unknown_value(self):- response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?type=campaign")+ @parameterized.expand(+ [+ ("unknown_value", "campaign"),+ # Separators alone name no type. This used to pass validation and then filter on an empty+ # set, so the caller got an empty list rather than an error.+ ("separators_only", ",,"),+ ]+ )+ def test_list_filter_by_workflow_type_rejects(self, _name, workflow_type):+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?type={workflow_type}")assert response.status_code == 400def test_list_filter_by_origin_product(self):diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.pyindex 9c47602a2d48..dca3a042b0f1 100644--- a/products/workflows/backend/models/hog_flow/hog_flow.py+++ b/products/workflows/backend/models/hog_flow/hog_flow.py@@ -136,6 +136,7 @@ class HogFlow(UUIDTModel):class OriginProduct(models.TextChoices):LOOPS = "loops", "Loops"+ BROADCASTS = "broadcasts", "Broadcasts"name = models.CharField(max_length=400, null=True, blank=True)description = models.TextField(blank=True, default="")diff --git a/products/workflows/frontend/Broadcasts/BroadcastEmailPreview.tsx b/products/workflows/frontend/Broadcasts/BroadcastEmailPreview.tsxnew file mode 100644index 000000000000..6cff420d614a--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastEmailPreview.tsx@@ -0,0 +1,118 @@+import { useActions, useValues } from 'kea'++import { IconSend } from '@posthog/icons'+import { LemonButton, LemonSearchableSelect, Spinner } from '@posthog/lemon-ui'++import { broadcastPreviewLogic } from './broadcastPreviewLogic'+import { broadcastTestSendLogic } from './broadcastTestSendLogic'+import { broadcastWizardLogic } from './broadcastWizardLogic'+import { SendTestBroadcastModal } from './SendTestBroadcastModal'++function PreviewRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+ return (+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <span className="w-16 shrink-0 text-xs font-semibold uppercase tracking-wide text-muted">{label}</span>+ <div className="min-w-0 flex-1">{children}</div>+ </div>+ )+}++/**+ * Shows the email as one person in the audience will receive it, with their own property values+ * filled in. Anything the person has no value for stays on screen as `{{ ... }}` rather than+ * rendering blank, so a missing variable is visible before the send rather than after.+ */+export function BroadcastEmailPreview(): JSX.Element {+ const { email } = useValues(broadcastWizardLogic)+ const {+ persons,+ personsLoading,+ personsFailed,+ previewPerson,+ previewSubject,+ previewHtml,+ previewText,+ previewTo,+ } = useValues(broadcastPreviewLogic)+ const { selectPerson } = useActions(broadcastPreviewLogic)+ const { setModalOpen } = useActions(broadcastTestSendLogic)++ const hasContent = !!(email.html || email.text)++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-muted text-xs">Preview and test before this reaches the audience.</span>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSend />}+ onClick={() => setModalOpen(true)}+ data-attr="broadcast-open-test-email"+ >+ Send test email+ </LemonButton>+ </div>+ <SendTestBroadcastModal />++ <div className="flex flex-col gap-2 rounded border border-border bg-surface-secondary p-3">+ <PreviewRow label="To">+ {personsLoading ? (+ <Spinner />+ ) : persons.length > 0 ? (+ <div className="flex flex-wrap items-center gap-2">+ <LemonSearchableSelect+ value={previewPerson?.id}+ options={persons.map((person) => ({+ value: person.id,+ label: person.displayName,+ }))}+ onChange={(value) => selectPerson(value ?? null)}+ searchPlaceholder="Find a person..."+ size="small"+ data-attr="broadcast-preview-person"+ />+ {previewTo && previewTo !== previewPerson?.displayName && (+ <span className="text-muted text-xs">{previewTo}</span>+ )}+ </div>+ ) : personsFailed ? (+ <span className="text-warning">+ Couldn't load anyone to preview against, so variables stay unfilled below.+ </span>+ ) : (+ <span className="text-muted">+ No one matches this audience yet, so variables stay unfilled below.+ </span>+ )}+ </PreviewRow>++ <PreviewRow label="Subject">+ {previewSubject || <span className="text-muted">No subject</span>}+ </PreviewRow>+ </div>++ {hasContent ? (+ email.html ? (+ <iframe+ srcDoc={previewHtml}+ sandbox=""+ title="Email preview"+ className="h-96 w-full rounded border border-border bg-white"+ />+ ) : (+ <div className="text-muted max-h-96 overflow-y-auto whitespace-pre-wrap text-sm">{previewText}</div>+ )+ ) : (+ <span className="text-muted">No content yet</span>+ )}++ {previewPerson && (+ <span className="text-xs text-muted">+ Values come from {previewPerson.displayName}. Anything still shown as a variable is not set for+ them, and sends as blank text.+ </span>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastScene.tsx b/products/workflows/frontend/Broadcasts/BroadcastScene.tsxnew file mode 100644index 000000000000..39e763965ae5--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastScene.tsx@@ -0,0 +1,58 @@+import { BindLogic, useValues } from 'kea'++import { SpinnerOverlay } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { SceneExport } from 'scenes/sceneTypes'++import { ProductKey } from '~/queries/schema/schema-general'++import { broadcastPreviewLogic } from './broadcastPreviewLogic'+import { BroadcastSummary } from './BroadcastSummary'+import { broadcastTestSendLogic } from './broadcastTestSendLogic'+import { BroadcastWizard } from './BroadcastWizard'+import { BroadcastWizardLogicProps, broadcastWizardLogic } from './broadcastWizardLogic'++export const scene: SceneExport<BroadcastWizardLogicProps> = {+ component: BroadcastScene,+ logic: broadcastWizardLogic,+ paramsToProps: ({ params: { id } }): BroadcastWizardLogicProps => ({ id: id || 'new' }),+ productKey: ProductKey.WORKFLOWS,+}++export function BroadcastScene({ id }: BroadcastWizardLogicProps): JSX.Element {+ const logicProps: BroadcastWizardLogicProps = { id: id || 'new' }++ return (+ <BindLogic logic={broadcastWizardLogic} props={logicProps}>+ <BindLogic logic={broadcastPreviewLogic} props={logicProps}>+ <BindLogic logic={broadcastTestSendLogic} props={logicProps}>+ <BroadcastSceneContent id={logicProps.id} />+ </BindLogic>+ </BindLogic>+ </BindLogic>+ )+}++function BroadcastSceneContent({ id }: BroadcastWizardLogicProps): JSX.Element {+ const { broadcast, broadcastLoading } = useValues(broadcastWizardLogic)++ if (id !== 'new') {+ if (!broadcast && broadcastLoading) {+ return <SpinnerOverlay sceneLevel />+ }+ 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') {+ return <NotFound object="broadcast" />+ }+ if (broadcast.status !== 'draft') {+ return <BroadcastSummary />+ }+ }++ return <BroadcastWizard />+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsxnew file mode 100644index 000000000000..8a6252fe4696--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx@@ -0,0 +1,147 @@+import { useValues } from 'kea'++import { IconArrowLeft, IconExternal } from '@posthog/icons'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'+import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'+import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { capitalizeFirstLetter } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import type { HogFlowBatchJobApi } from 'products/workflows/frontend/generated/api.schemas'++import { EmailMetricsSummary } from '../Workflows/EmailMetricsSummary'+import { broadcastWizardLogic } from './broadcastWizardLogic'++const BATCH_JOB_STATUS_TAG: Record<string, 'success' | 'default' | 'warning' | 'danger' | 'muted'> = {+ waiting: 'default',+ queued: 'warning',+ active: 'warning',+ completed: 'success',+ cancelled: 'muted',+ failed: 'danger',+}++export function BroadcastSummary(): JSX.Element {+ const { broadcast, broadcastId, name, audienceProperties, email, scheduleSummary, batchJobs, batchJobsLoading } =+ useValues(broadcastWizardLogic)++ // Email metrics from a batch send are attributed to the batch job, not the flow (see+ // `parentRunId ?? functionId` in the plugin server's email service), so a flow-scoped query+ // returns zeros for every broadcast. Key the logic by the run so it remounts once runs load.+ const latestBatchJob = batchJobs[0]+ const latestBatchJobId = latestBatchJob?.id+ const metricsSourceId = latestBatchJobId ?? broadcastId+ const logicKey = `broadcast-${metricsSourceId}`+ // Mounting with force params here pins the metrics query to this run; EmailMetricsSummary+ // reads the same keyed logic below. The date window follows the run rather than a fixed+ // lookback, so a send older than 30 days still shows its counts.+ useValues(+ appMetricsLogic({+ logicKey,+ loadOnMount: true,+ loadOnChanges: true,+ forceParams: {+ appSource: 'hog_flow',+ appSourceId: metricsSourceId ?? undefined,+ breakdownBy: 'metric_name',+ dateFrom: latestBatchJob ? dayjs(latestBatchJob.created_at).subtract(1, 'hour').toISOString() : '-30d',+ dateTo: latestBatchJob ? dayjs().add(1, 'hour').toISOString() : undefined,+ interval: 'day',+ },+ })+ )++ const batchJobColumns: LemonTableColumns<HogFlowBatchJobApi> = [+ {+ title: 'Started',+ key: 'created_at',+ render: (_, job) => <TZLabel time={job.created_at} />,+ },+ {+ title: 'Status',+ key: 'status',+ render: (_, job) => (+ <LemonTag type={BATCH_JOB_STATUS_TAG[job.status ?? 'waiting'] ?? 'default'}>+ {capitalizeFirstLetter(job.status ?? 'waiting')}+ </LemonTag>+ ),+ },+ {+ title: 'Started by',+ key: 'created_by',+ render: (_, job) => <span>{job.created_by?.first_name || job.created_by?.email || 'Schedule'}</span>,+ },+ ]++ 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">+ <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">+ <h1 className="m-0 text-2xl font-semibold">{name}</h1>+ <LemonTag type={broadcast?.status === 'active' ? 'success' : 'default'}>+ {capitalizeFirstLetter(broadcast?.status ?? 'draft')}+ </LemonTag>+ </div>++ <div className="flex flex-col gap-3 rounded-lg border border-border bg-surface-primary p-4">+ <div className="flex flex-col gap-1">+ <span className="text-xs font-semibold uppercase tracking-wide text-muted">Audience</span>+ {audienceProperties.length > 0 ? (+ <PropertyFiltersDisplay filters={audienceProperties} />+ ) : (+ <span className="text-muted">Everyone</span>+ )}+ </div>+ <div className="flex flex-col gap-1">+ <span className="text-xs font-semibold uppercase tracking-wide text-muted">Schedule</span>+ <span>{scheduleSummary}</span>+ </div>+ <div className="flex flex-col gap-1">+ <span className="text-xs font-semibold uppercase tracking-wide text-muted">Email subject</span>+ <span>{email.subject || 'No subject'}</span>+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <h2 className="m-0 text-lg font-semibold">+ {latestBatchJobId ? 'Performance (latest send)' : 'Performance (last 30 days)'}+ </h2>+ <EmailMetricsSummary logicKey={logicKey} compact />+ </div>++ <div className="flex flex-col gap-2">+ <h2 className="m-0 text-lg font-semibold">Runs</h2>+ <LemonTable+ dataSource={batchJobs}+ loading={batchJobsLoading}+ rowKey="id"+ columns={batchJobColumns}+ nouns={['run', 'runs']}+ emptyState="No runs yet. Scheduled broadcasts appear here after they send."+ />+ </div>+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx b/products/workflows/frontend/Broadcasts/BroadcastWizard.tsxnew file mode 100644index 000000000000..080594a4c997--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastWizard.tsx@@ -0,0 +1,106 @@+import { useActions, useValues } from 'kea'++import { IconArrowLeft } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { EditableField } from 'lib/components/EditableField/EditableField'+import { urls } from 'scenes/urls'++import { broadcastWizardLogic } from './broadcastWizardLogic'+import { BroadcastWizardStepper } from './BroadcastWizardStepper'+import { BroadcastContentStep } from './steps/BroadcastContentStep'+import { BroadcastGoalStep } from './steps/BroadcastGoalStep'+import { BroadcastRecipientsStep } from './steps/BroadcastRecipientsStep'+import { BroadcastReviewStep } from './steps/BroadcastReviewStep'+import { BroadcastScheduleStep } from './steps/BroadcastScheduleStep'++export function BroadcastWizard(): JSX.Element {+ const { currentStep, name, stepValidationErrors, currentStepHasErrors, saving, launching, scheduleMode } =+ useValues(broadcastWizardLogic)+ const { setStep, prevStep, continueStep, launchBroadcast, setName } = useActions(broadcastWizardLogic)++ 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="space-y-3">+ <div className="flex items-center justify-between">+ <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.broadcasts()}>+ Broadcasts+ </LemonButton>+ </div>+ <div>+ <label htmlFor="broadcast-name" className="text-xs font-medium text-muted">+ Broadcast name+ </label>+ <EditableField+ name="broadcast-name"+ value={name}+ onSave={(value) => setName(value)}+ placeholder="Untitled broadcast"+ saveOnBlur+ clickToEdit+ compactIcon+ showEditIconOnHover+ className="text-xl font-semibold"+ editingIndication="underlined"+ />+ </div>+ <div className="flex justify-center">+ <BroadcastWizardStepper+ currentStep={currentStep}+ onStepClick={setStep}+ stepErrors={stepValidationErrors}+ />+ </div>+ </div>++ <div>+ {currentStep === 'recipients' && <BroadcastRecipientsStep />}+ {currentStep === 'goal' && <BroadcastGoalStep />}+ {currentStep === 'content' && <BroadcastContentStep />}+ {currentStep === 'schedule' && <BroadcastScheduleStep />}+ {currentStep === 'review' && <BroadcastReviewStep />}+ </div>++ <div className="flex items-center justify-between border-t border-border pt-4">+ <div>+ {currentStep !== 'recipients' && (+ <LemonButton type="secondary" onClick={prevStep} disabled={saving || launching}>+ Back+ </LemonButton>+ )}+ </div>+ <div className="flex items-center gap-2">+ {currentStep === 'review' ? (+ <LemonButton+ type="primary"+ loading={launching}+ disabled={saving}+ disabledReason={+ stepValidationErrors.review.length > 0+ ? 'Fix the issues above before sending'+ : undefined+ }+ onClick={launchBroadcast}+ data-attr="broadcast-wizard-launch"+ >+ {scheduleMode === 'now' ? 'Send now' : 'Schedule broadcast'}+ </LemonButton>+ ) : (+ <LemonButton+ type="primary"+ loading={saving}+ disabled={launching}+ disabledReason={currentStepHasErrors ? 'Fix errors before continuing' : undefined}+ onClick={continueStep}+ data-attr="broadcast-wizard-continue"+ >+ Continue+ </LemonButton>+ )}+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastWizardStepper.tsx b/products/workflows/frontend/Broadcasts/BroadcastWizardStepper.tsxnew file mode 100644index 000000000000..3cc1f6a85c1d--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastWizardStepper.tsx@@ -0,0 +1,112 @@+import { IconCheckCircle, IconWarning } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'++import { BROADCAST_WIZARD_STEPS, BroadcastWizardStep } from './broadcastWizardLogic'++const STEP_LABELS: Record<BroadcastWizardStep, string> = {+ recipients: 'Recipients',+ goal: 'Goal',+ content: 'Content',+ schedule: 'Schedule',+ review: 'Review',+}++interface BroadcastWizardStepperProps {+ currentStep: BroadcastWizardStep+ onStepClick: (step: BroadcastWizardStep) => void+ stepErrors?: Partial<Record<BroadcastWizardStep, string[]>>+}++export function BroadcastWizardStepper({+ currentStep,+ onStepClick,+ stepErrors = {},+}: BroadcastWizardStepperProps): JSX.Element {+ const currentOrder = BROADCAST_WIZARD_STEPS.indexOf(currentStep)+ const currentStepHasErrors = (stepErrors[currentStep]?.length ?? 0) > 0++ const handleStepClick = (step: BroadcastWizardStep): void => {+ const targetOrder = BROADCAST_WIZARD_STEPS.indexOf(step)+ if (currentStepHasErrors && targetOrder > currentOrder) {+ return+ }+ onStepClick(step)+ }++ return (+ <nav className="flex items-center" aria-label="Broadcast wizard progress">+ {BROADCAST_WIZARD_STEPS.map((step, index) => {+ const isCompleted = currentOrder > index+ const isCurrent = currentStep === step+ const hasErrors = (stepErrors[step]?.length ?? 0) > 0+ const isBlocked = currentStepHasErrors && index > currentOrder++ const button = (+ <button+ type="button"+ onClick={() => handleStepClick(step)}+ disabled={isBlocked}+ className={cn(+ 'group flex items-center gap-1.5 px-2 py-1 rounded',+ 'transition-all duration-150',+ 'focus:outline-none focus-visible:ring-1 focus-visible:ring-accent',+ isBlocked+ ? 'opacity-50 cursor-not-allowed'+ : 'hover:bg-fill-button-tertiary-hover active:scale-[0.98]'+ )}+ aria-current={isCurrent ? 'step' : undefined}+ data-attr={`broadcast-wizard-step-${step}`}+ >+ {hasErrors && isCurrent ? (+ <IconWarning className="size-5 text-warning" />+ ) : isCompleted ? (+ <IconCheckCircle className="size-5 text-success" />+ ) : (+ <span+ className={cn(+ 'flex items-center justify-center size-5 rounded-full text-xs font-semibold',+ 'transition-all duration-150',+ isCurrent && 'bg-accent text-primary-inverse ring-2 ring-accent/25',+ !isCurrent && 'bg-surface-secondary text-secondary border border-primary'+ )}+ >+ {index + 1}+ </span>+ )}++ <span+ className={cn(+ 'text-sm transition-colors duration-150',+ isCurrent && 'font-semibold text-primary',+ isCompleted && 'font-medium text-primary',+ !isCompleted && !isCurrent && 'text-secondary'+ )}+ >+ {STEP_LABELS[step]}+ </span>+ </button>+ )++ return (+ <div key={step} className="flex items-center">+ {index > 0 && (+ <div+ className={cn(+ 'w-6 h-px transition-colors duration-150',+ hasErrors && isCurrent+ ? 'bg-warning'+ : isCompleted || isCurrent+ ? 'bg-success'+ : 'bg-border-primary'+ )}+ />+ )}+ {isBlocked ? <Tooltip title="Fix errors before proceeding">{button}</Tooltip> : button}+ </div>+ )+ })}+ </nav>+ )+}diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsxnew file mode 100644index 000000000000..2224ef62fe43--- /dev/null+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx@@ -0,0 +1,103 @@+import { useValues } from 'kea'++import { LemonTag, LemonTagType } from '@posthog/lemon-ui'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import type { HogFlowMinimalApi } from 'products/workflows/frontend/generated/api.schemas'++import { BroadcastStatus, broadcastsLogic, getBroadcastStatus } from './broadcastsLogic'++const STATUS_CONFIG: Record<BroadcastStatus, { label: string; type: LemonTagType }> = {+ draft: { label: 'Draft', type: 'default' },+ scheduled: { label: 'Scheduled', type: 'warning' },+ sending: { label: 'Sending', type: 'completion' },+ sent: { label: 'Sent', type: 'success' },+ failed: { label: 'Failed', type: 'danger' },+ archived: { label: 'Archived', type: 'muted' },+}++const METRIC_COLUMNS: { title: string; metricName: string }[] = [+ { title: 'Sent', metricName: 'email_sent' },+ { title: 'Delivered', metricName: 'email_delivered' },+ { title: 'Opened', metricName: 'email_opened' },+ { title: 'Clicked', metricName: 'email_link_clicked' },+ { title: 'Converted', metricName: 'conversion' },+]++export function BroadcastsTable(): JSX.Element {+ const { broadcasts, broadcastsLoading, hasLoadedBroadcasts, rowDetailsById } = useValues(broadcastsLogic)++ const columns: LemonTableColumns<HogFlowMinimalApi> = [+ {+ title: 'Name',+ key: 'name',+ render: (_, item) => (+ <LemonTableLink+ to={urls.broadcast(item.id)}+ title={item.name || 'Untitled broadcast'}+ description={item.description}+ />+ ),+ },+ {+ title: 'Status',+ width: 0,+ render: (_, item) => {+ const config = STATUS_CONFIG[getBroadcastStatus(item, rowDetailsById[item.id])]+ return <LemonTag type={config.type}>{config.label}</LemonTag>+ },+ },+ ...METRIC_COLUMNS.map(({ title, metricName }) => ({+ title,+ width: 0,+ align: 'right' as const,+ render: (_: unknown, item: HogFlowMinimalApi) => {+ const details = rowDetailsById[item.id]+ if (item.status === 'draft') {+ return <span className="text-muted">-</span>+ }+ if (!details) {+ return <span className="text-muted">…</span>+ }+ return <span>{humanFriendlyNumber(details.totals[metricName] ?? 0)}</span>+ },+ })),+ createdByColumn() as LemonTableColumns<HogFlowMinimalApi>[number],+ createdAtColumn() as LemonTableColumns<HogFlowMinimalApi>[number],+ ]++ const isEmpty = hasLoadedBroadcasts && !broadcastsLoading && broadcasts.results.length === 0++ if (isEmpty) {+ return (+ <div+ className="flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border py-12"+ data-attr="broadcasts-empty-state"+ >+ <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">+ New broadcast+ </LemonButton>+ </div>+ )+ }++ return (+ <LemonTable+ dataSource={broadcasts.results}+ loading={broadcastsLoading}+ rowKey="id"+ columns={columns}+ nouns={['broadcast', 'broadcasts']}+ emptyState="No broadcasts"+ data-attr="broadcasts-table"+ />+ )+}diff --git a/products/workflows/frontend/Broadcasts/SendTestBroadcastModal.tsx b/products/workflows/frontend/Broadcasts/SendTestBroadcastModal.tsxnew file mode 100644index 000000000000..331af0ba38f6--- /dev/null+++ b/products/workflows/frontend/Broadcasts/SendTestBroadcastModal.tsx@@ -0,0 +1,77 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonInput, LemonLabel, LemonModal } from '@posthog/lemon-ui'++import { broadcastTestSendLogic } from './broadcastTestSendLogic'++export function SendTestBroadcastModal(): JSX.Element {+ const {+ isModalOpen,+ recipientEmail,+ previewPerson,+ sendDisabledReason,+ testSendResult,+ testSendSkipReason,+ testSendResultLoading,+ } = useValues(broadcastTestSendLogic)+ const { setModalOpen, setRecipientEmail, sendTestEmail } = useActions(broadcastTestSendLogic)++ return (+ <LemonModal+ isOpen={isModalOpen}+ onClose={() => setModalOpen(false)}+ title="Send a test email"+ description="Goes to this address only. Nobody in the audience receives it."+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setModalOpen(false)}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={sendTestEmail}+ loading={testSendResultLoading}+ disabledReason={sendDisabledReason}+ data-attr="broadcast-send-test-email"+ >+ Send test+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-3 max-w-160">+ <div className="flex flex-col gap-1">+ <LemonLabel>Send to</LemonLabel>+ <LemonInput+ type="email"+ value={recipientEmail}+ onChange={setRecipientEmail}+ placeholder="[email protected]"+ autoFocus+ data-attr="broadcast-test-email-recipient"+ />+ </div>++ <span className="text-muted text-xs">+ {previewPerson+ ? `Variables use ${previewPerson.displayName}'s values, matching the preview.`+ : 'No one matches this audience yet, so variables send as blank text.'}+ </span>++ {testSendSkipReason ? (+ <LemonBanner type="warning">{testSendSkipReason}</LemonBanner>+ ) : testSendResult?.status === 'skipped' ? (+ <LemonBanner type="warning">+ {testSendResult.logs?.map((log) => log.message).join(' ') ||+ 'The email step was skipped, so nothing was sent.'}+ </LemonBanner>+ ) : null}+ {testSendResult?.status === 'error' && (+ <LemonBanner type="error">+ {testSendResult.errors?.join(', ') || 'Could not send the test email.'}+ </LemonBanner>+ )}+ </div>+ </LemonModal>+ )+}diff --git a/products/workflows/frontend/Broadcasts/broadcastPreviewLogic.ts b/products/workflows/frontend/Broadcasts/broadcastPreviewLogic.tsnew file mode 100644index 000000000000..2b44163686f5--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastPreviewLogic.ts@@ -0,0 +1,205 @@+import { MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import api from 'lib/api'+import { Scene } from 'scenes/sceneTypes'++import { ActorsQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { AnyPersonScopeFilter, AnyPropertyFilter } from '~/types'++import { BroadcastEmailValue, BroadcastWizardLogicProps, broadcastWizardLogic } from './broadcastWizardLogic'+import { EmailPreviewPerson, renderEmailPreview } from './emailPreview'++const PREVIEW_PERSON_LIMIT = 25++export interface BroadcastPreviewPerson extends EmailPreviewPerson {+ displayName: string+}++// The properties column arrives as a JSON string over the query API, but tolerate an object in case+// a caller hands one over already parsed.+function parseProperties(raw: unknown): Record<string, any> {+ if (raw && typeof raw === 'object') {+ return raw as Record<string, any>+ }+ if (typeof raw === 'string') {+ try {+ return JSON.parse(raw)+ } catch {+ return {}+ }+ }+ return {}+}++function parsePerson(row: any[]): BroadcastPreviewPerson {+ const properties = parseProperties(row[2])+ return {+ id: String(row[0]),+ displayName: row[1]?.display_name || properties.email || String(row[0]),+ properties,+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastPreviewLogicValues {+ audienceProperties: AnyPropertyFilter[] // broadcastWizardLogic+ email: BroadcastEmailValue // broadcastWizardLogic+ persons: BroadcastPreviewPerson[]+ personsFailed: boolean+ personsLoading: boolean+ previewHtml: string+ previewPerson: BroadcastPreviewPerson | null+ previewSubject: string+ previewText: string+ previewTo: string+ selectedPersonId: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastPreviewLogicActions {+ loadPersons: () => any+ loadPersonsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPersonsSuccess: (+ persons: BroadcastPreviewPerson[],+ payload?: any+ ) => {+ persons: BroadcastPreviewPerson[]+ payload?: any+ }+ selectPerson: (personId: string | null) => {+ personId: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastPreviewLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ previewPerson: (+ persons: BroadcastPreviewPerson[],+ selectedPersonId: string | null+ ) => BroadcastPreviewPerson | null+ previewSubject: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string+ previewHtml: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string+ previewText: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string+ previewTo: (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null) => string+ }+}++export type broadcastPreviewLogicType = MakeLogicType<+ broadcastPreviewLogicValues,+ broadcastPreviewLogicActions,+ BroadcastWizardLogicProps,+ broadcastPreviewLogicMeta+>++export const broadcastPreviewLogic = kea<broadcastPreviewLogicType>([+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastPreviewLogic']),+ props({} as BroadcastWizardLogicProps),+ key((props) => props.id),++ connect((props: BroadcastWizardLogicProps) => ({+ values: [broadcastWizardLogic(props), ['audienceProperties', 'email']],+ })),++ actions({+ selectPerson: (personId: string | null) => ({ personId }),+ }),++ loaders(({ values }) => ({+ persons: [+ [] as BroadcastPreviewPerson[],+ {+ loadPersons: async () => {+ const query: ActorsQuery = {+ kind: NodeKind.ActorsQuery,+ // Attributes the query in the ClickHouse query log. Without it the backend+ // rejects the query outright when DEBUG is on, so the picker stays empty+ // for anyone running locally.+ tags: { productKey: ProductKey.WORKFLOWS, scene: Scene.Broadcast },+ // The recipients step only offers person-scoped filters, which is all an+ // actors query accepts.+ properties: values.audienceProperties as AnyPersonScopeFilter[],+ select: ['id', 'person_display_name -- Person', 'properties'],+ limit: PREVIEW_PERSON_LIMIT,+ }+ const response = await api.query<ActorsQuery>(query)+ return (response.results ?? []).map(parsePerson)+ },+ },+ ],+ })),++ reducers({+ selectedPersonId: [+ null as string | null,+ {+ selectPerson: (_, { personId }) => personId,+ // The audience decides who is on offer, so a reload invalidates the old pick.+ loadPersons: () => null,+ },+ ],+ // An empty list and a failed lookup both leave the picker empty, but they mean+ // different things to a sender, so keep them apart.+ personsFailed: [+ false,+ {+ loadPersons: () => false,+ loadPersonsSuccess: () => false,+ loadPersonsFailure: () => true,+ },+ ],+ }),++ selectors({+ previewPerson: [+ (s) => [s.persons, s.selectedPersonId],+ (persons: BroadcastPreviewPerson[], selectedPersonId: string | null): BroadcastPreviewPerson | null =>+ persons.find((person) => person.id === selectedPersonId) ??+ // Default to someone the broadcast can reach. An audience filter that does not mention+ // email can put a person with no email address first, and that person renders every+ // merge tag blank, so the preview reads as broken rather than as an empty value.+ persons.find((person) => !!person.properties.email) ??+ persons[0] ??+ null,+ ],+ previewSubject: [+ (s) => [s.email, s.previewPerson],+ (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>+ renderEmailPreview(email.subject, previewPerson),+ ],+ previewHtml: [+ (s) => [s.email, s.previewPerson],+ (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>+ renderEmailPreview(email.html, previewPerson),+ ],+ // The worker renders liquid in every string of the email input, `text` included, so a+ // text-only broadcast has to preview through the same renderer as the html one.+ previewText: [+ (s) => [s.email, s.previewPerson],+ (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>+ renderEmailPreview(email.text, previewPerson),+ ],+ previewTo: [+ (s) => [s.email, s.previewPerson],+ (email: BroadcastEmailValue, previewPerson: BroadcastPreviewPerson | null): string =>+ renderEmailPreview(email.to?.email ?? '', previewPerson),+ ],+ }),++ // Reload on the value rather than on the edit action, so resuming a saved draft loads against+ // the audience it hydrates with instead of the empty one the logic mounted on.+ subscriptions(({ actions }) => ({+ audienceProperties: () => {+ actions.loadPersons()+ },+ })),+])diff --git a/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts b/products/workflows/frontend/Broadcasts/broadcastStatus.test.tsnew file mode 100644index 000000000000..250fce272020--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastStatus.test.ts@@ -0,0 +1,25 @@+import type { HogFlowBatchJobApi, HogFlowMinimalApi } from 'products/workflows/frontend/generated/api.schemas'++import { getBroadcastStatus } from './broadcastsLogic'++const flow = (status: string): HogFlowMinimalApi => ({ status }) as unknown as HogFlowMinimalApi+const withJob = (status: string): { latestBatchJob: HogFlowBatchJobApi; totals: Record<string, number> } => ({+ latestBatchJob: { status } as HogFlowBatchJobApi,+ totals: {},+})++describe('getBroadcastStatus', () => {+ it.each([+ ['a draft, whatever its runs say', flow('draft'), withJob('completed'), 'draft'],+ ['an archived broadcast', flow('archived'), withJob('completed'), 'archived'],+ ['a run still going', flow('active'), withJob('active'), 'sending'],+ ['a run that finished', flow('active'), withJob('completed'), 'sent'],+ // A terminal run used to fall through to the no-run fallback and read as "scheduled",+ // telling the sender another send was pending when nothing was coming.+ ['a run that failed', flow('active'), withJob('failed'), 'failed'],+ ['a run that was cancelled', flow('active'), withJob('cancelled'), 'failed'],+ ['no run yet', flow('active'), undefined, 'scheduled'],+ ])('reads %s as %s', (_name, broadcast, details, expected) => {+ expect(getBroadcastStatus(broadcast, details)).toBe(expected)+ })+})diff --git a/products/workflows/frontend/Broadcasts/broadcastTestSend.test.ts b/products/workflows/frontend/Broadcasts/broadcastTestSend.test.tsnew file mode 100644index 000000000000..953830604fab--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastTestSend.test.ts@@ -0,0 +1,28 @@+import { HogflowTestResult } from '../Workflows/hogflows/steps/types'+import { findTestSendSkipReason } from './broadcastTestSendLogic'++const result = (partial: Partial<HogflowTestResult>): HogflowTestResult =>+ ({ status: 'success', nextActionId: null, ...partial }) as HogflowTestResult++const log = (message: string): any => ({ level: 'info', timestamp: '2026-01-01T00:00:00Z', message })++describe('findTestSendSkipReason', () => {+ it('finds the reason a declined send reports, even though the run says success', () => {+ // The worker declines the send but finishes the step, so status alone would read as sent.+ const reason =+ 'Skipping send: the domain "example.com" has no reachable mail servers, so this message would hard bounce.'+ expect(+ findTestSendSkipReason(+ result({ status: 'success', logs: [log('Executing action [Action:send_test_email]'), log(reason)] })+ )+ ).toBe(reason)+ })++ it.each([+ ['a delivered send', result({ status: 'success', logs: [log('Executing action [Action:send_test_email]')] })],+ ['a run with no logs', result({ status: 'success' })],+ ['no result at all', null],+ ])('reports no reason for %s', (_name, input) => {+ expect(findTestSendSkipReason(input)).toBeUndefined()+ })+})diff --git a/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts b/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.tsnew file mode 100644index 000000000000..e5322bc26185--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts@@ -0,0 +1,273 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { isEmail } from 'lib/utils/url'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { UserType } from '~/types'++import { HogflowTestResult } from '../Workflows/hogflows/steps/types'+import { createExampleEvent } from '../Workflows/hogflows/testEventFactory'+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../Workflows/hogflows/types'+import { EXIT_NODE_ID, NEW_WORKFLOW, TRIGGER_NODE_ID } from '../Workflows/workflowLogic'+import { BroadcastPreviewPerson, broadcastPreviewLogic } from './broadcastPreviewLogic'+import { BroadcastEmailValue, BroadcastWizardLogicProps, broadcastWizardLogic } from './broadcastWizardLogic'++// Fixed id for the single email action in the synthetic test flow. The edges below reference it,+// and it goes over as `current_action_id` so the worker runs just this node.+const TEST_EMAIL_ACTION_ID = 'send_test_email'++// Every reason the email worker declines a send is logged behind this prefix+// (nodejs/src/cdp/services/messaging/email-validation.service.ts).+const SKIP_LOG_PREFIX = 'Skipping send:'++/**+ * The reason the worker declined to send, if it did.+ *+ * A declined send still finishes the step cleanly, so the invocation comes back `success` and the+ * reason appears only in the logs. Reading the status alone reports a test as delivered when+ * nothing was sent, and the sender waits for mail that never arrives.+ */+export function findTestSendSkipReason(result: HogflowTestResult | null): string | undefined {+ return result?.logs?.find((log) => log.message?.includes(SKIP_LOG_PREFIX))?.message+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastTestSendLogicValues {+ previewPerson: BroadcastPreviewPerson | null // broadcastPreviewLogic+ email: BroadcastEmailValue // broadcastWizardLogic+ name: string // broadcastWizardLogic+ currentTeamId: number | null // teamLogic+ user: UserType | null // userLogic+ isModalOpen: boolean+ recipientEmail: string+ sendDisabledReason: string | undefined+ testSendResult: HogflowTestResult | null+ testSendResultLoading: boolean+ testSendSkipReason: string | undefined+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastTestSendLogicActions {+ clearTestSendResult: () => {+ value: true+ }+ clearTestSendResultFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ clearTestSendResultSuccess: (+ testSendResult: null,+ payload?: {+ value: true+ }+ ) => {+ testSendResult: null+ payload?: {+ value: true+ }+ }+ sendTestEmail: () => any+ sendTestEmailFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ sendTestEmailSuccess: (+ testSendResult: HogflowTestResult,+ payload?: any+ ) => {+ testSendResult: HogflowTestResult+ payload?: any+ }+ setModalOpen: (open: boolean) => {+ open: boolean+ }+ setRecipientEmail: (email: string) => {+ email: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastTestSendLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ testSendSkipReason: (testSendResult: HogflowTestResult | null) => string | undefined+ sendDisabledReason: (email: BroadcastEmailValue, recipientEmail: string) => string | undefined+ }+}++export type broadcastTestSendLogicType = MakeLogicType<+ broadcastTestSendLogicValues,+ broadcastTestSendLogicActions,+ BroadcastWizardLogicProps,+ broadcastTestSendLogicMeta+>++/**+ * Sends one real email to an address the user names, so they can read the broadcast in an inbox+ * before it reaches the audience. The send runs the same email step the broadcast will, through a+ * throwaway flow that exists only for this invocation.+ */+export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastTestSendLogic']),+ props({} as BroadcastWizardLogicProps),+ key((props) => props.id),++ connect((props: BroadcastWizardLogicProps) => ({+ values: [+ broadcastWizardLogic(props),+ ['email', 'name'],+ broadcastPreviewLogic(props),+ ['previewPerson'],+ teamLogic,+ ['currentTeamId'],+ userLogic,+ ['user'],+ ],+ })),++ actions({+ setModalOpen: (open: boolean) => ({ open }),+ setRecipientEmail: (email: string) => ({ email }),+ clearTestSendResult: true,+ }),++ reducers({+ isModalOpen: [false, { setModalOpen: (_, { open }) => open }],+ recipientEmail: ['', { setRecipientEmail: (_, { email }) => email }],+ }),++ loaders(({ values }) => ({+ testSendResult: [+ null as HogflowTestResult | null,+ {+ clearTestSendResult: () => null,+ sendTestEmail: async (): Promise<HogflowTestResult> => {+ const { email, name, previewPerson, recipientEmail, currentTeamId } = values++ const emailAction: HogFlowAction = {+ id: TEST_EMAIL_ACTION_ID,+ type: 'function_email',+ name: 'Send test email',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: {+ template_id: 'template-email',+ inputs: {+ email: {+ value: {+ ...email,+ // One visible recipient on a test, whatever the broadcast carries.+ cc: '',+ bcc: '',+ to: { email: recipientEmail, name: '' },+ },+ templating: 'liquid',+ },+ },+ },+ }++ const edges: HogFlowEdge[] = [+ { from: TRIGGER_NODE_ID, to: TEST_EMAIL_ACTION_ID, type: 'continue' },+ { from: TEST_EMAIL_ACTION_ID, to: EXIT_NODE_ID, type: 'continue' },+ ]++ const configuration: HogFlow = {+ ...NEW_WORKFLOW,+ team_id: currentTeamId ?? NEW_WORKFLOW.team_id,+ name: name || 'Test broadcast',+ actions: [NEW_WORKFLOW.actions[0], emailAction, NEW_WORKFLOW.actions[1]],+ edges,+ }++ const globals = createExampleEvent(+ currentTeamId ?? undefined,+ configuration.name,+ '$pageview',+ recipientEmail+ )+ if (previewPerson) {+ // Render against the person the preview is showing, so the test email that+ // lands is the one that person would have received.+ globals.person = {+ id: previewPerson.id,+ properties: previewPerson.properties,+ name: previewPerson.displayName,+ url: globals.person?.url ?? '',+ }+ }++ return await api.hogFlows.createTestInvocation('new', {+ configuration,+ globals,+ // A test send is a real send. Mocking it would defeat the point.+ mock_async_functions: false,+ current_action_id: TEST_EMAIL_ACTION_ID,+ })+ },+ },+ ],+ })),++ selectors({+ testSendSkipReason: [+ (s) => [s.testSendResult],+ (testSendResult: HogflowTestResult | null): string | undefined => findTestSendSkipReason(testSendResult),+ ],+ sendDisabledReason: [+ (s) => [s.email, s.recipientEmail],+ (email: BroadcastEmailValue, recipientEmail: string): string | undefined => {+ if (!email.from?.integrationId) {+ return 'Choose an email sender first'+ }+ if (!email.subject) {+ return 'Add a subject first'+ }+ if (!email.html && !email.text) {+ return 'Add email content first'+ }+ if (!recipientEmail || !isEmail(recipientEmail)) {+ return 'Enter a valid email address'+ }+ return undefined+ },+ ],+ }),++ listeners(({ actions, values }) => ({+ setModalOpen: ({ open }) => {+ // A stale result from a previous attempt must not greet the next one.+ actions.clearTestSendResult()+ if (open && !values.recipientEmail && values.user?.email) {+ actions.setRecipientEmail(values.user.email)+ }+ },+ sendTestEmailSuccess: ({ testSendResult }) => {+ // A declined send finishes the step cleanly, so check the reason before the status.+ if (values.testSendSkipReason) {+ lemonToast.warning('Nothing was sent, see why below')+ } else if (testSendResult?.status === 'success') {+ lemonToast.success(`Test email sent to ${values.recipientEmail}`)+ actions.setModalOpen(false)+ } else if (testSendResult?.status === 'skipped') {+ lemonToast.warning('The email step was skipped, so nothing was sent')+ } else {+ lemonToast.error('Could not send the test email')+ }+ },+ sendTestEmailFailure: () => {+ lemonToast.error('Could not send the test email')+ },+ })),+])diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.tsnew file mode 100644index 000000000000..491dd77752f5--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts@@ -0,0 +1,923 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { projectLogic } from 'scenes/projectLogic'+import { Scene } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { AnyPropertyFilter, Breadcrumb, TeamPublicType, TeamType } from '~/types'++import {+ hogFlowsBatchJobsCreate,+ hogFlowsBatchJobsList,+ hogFlowsCreate,+ hogFlowsPartialUpdate,+ hogFlowsRetrieve,+ hogFlowsSchedulesCreate,+ hogFlowsUserBlastRadiusCreate,+} from 'products/workflows/frontend/generated/api'+import type {+ BlastRadiusApi,+ HogFlowApi,+ HogFlowBatchJobApi,+ HogFlowConversionApi,+ HogFlowEmailSendingRateLimitApi,+ HogFlowScheduleApi,+} from 'products/workflows/frontend/generated/api.schemas'++import {+ DEFAULT_STATE,+ ONE_TIME_RRULE,+ ScheduleState,+ buildSummary,+ isOneTimeSchedule,+ parseRRuleToState,+ stateToRRule,+} from '../Workflows/hogflows/steps/components/rrule-helpers'++export type BroadcastWizardStep = 'recipients' | 'goal' | 'content' | 'schedule' | 'review'++export const BROADCAST_WIZARD_STEPS: BroadcastWizardStep[] = ['recipients', 'goal', 'content', 'schedule', 'review']++export type BroadcastScheduleMode = 'now' | 'later' | 'recurring'++// The value stored in the email action's `inputs.email.value`, mirroring the+// `template-email` hog function template's default input shape.+export interface BroadcastEmailValue {+ to: { email: string; name?: string }+ from: { integrationId?: number | null }+ replyTo?: string+ cc?: string+ bcc?: string+ subject: string+ preheader?: string+ text: string+ html: string+ design: Record<string, any> | null+}++export const DEFAULT_BROADCAST_EMAIL: BroadcastEmailValue = {+ to: { email: '{{ person.properties.email }}', name: '' },+ from: {},+ replyTo: '',+ cc: '',+ bcc: '',+ subject: '',+ preheader: '',+ text: '',+ html: '',+ design: null,+}++export const DEFAULT_BROADCAST_CONVERSION: HogFlowConversionApi = {+ events: [],+ filters: [],+ window: '7d',+}++// pinned: action node ids referenced by saved broadcasts — renaming breaks resume of existing drafts+const TRIGGER_ACTION_ID = 'trigger_node'+const EMAIL_ACTION_ID = 'email_node'+const EXIT_ACTION_ID = 'exit_node'++function findAction(broadcast: HogFlowApi, type: string): Record<string, any> | undefined {+ const flowActions = (broadcast.actions ?? []) as unknown as Record<string, any>[]+ return flowActions.find((action) => action.type === type)+}++export interface BroadcastWizardLogicProps {+ id: string // 'new' for new broadcasts, or a UUID for editing/viewing+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastWizardLogicValues {+ currentProjectId: number | null // projectLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ audienceProperties: AnyPropertyFilter[]+ batchJobs: HogFlowBatchJobApi[]+ batchJobsLoading: boolean+ blastRadius: BlastRadiusApi | null+ blastRadiusLoading: boolean+ breadcrumbs: Breadcrumb[]+ broadcast: HogFlowApi | null+ broadcastId: string | null+ broadcastLoading: boolean+ conversion: HogFlowConversionApi+ currentStep: BroadcastWizardStep+ currentStepHasErrors: boolean+ effectiveTimezone: string+ email: BroadcastEmailValue+ emailRateLimit: HogFlowEmailSendingRateLimitApi | null+ firstInvalidStep: BroadcastWizardStep | null+ goalEnabled: boolean+ hasHydrated: boolean+ isReadOnly: boolean+ launching: boolean+ name: string+ rateLimitedSendDuration: string+ recurringRepeating: boolean+ recurringStartsAt: string | null+ saving: boolean+ scheduleMode: BroadcastScheduleMode+ scheduleState: ScheduleState+ scheduleSummary: string+ scheduleTimezone: string | null+ sendAt: string | null+ stepValidationErrors: Record<BroadcastWizardStep, string[]>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastWizardLogicActions {+ continueStep: () => {+ value: true+ }+ hydrateFromBroadcast: (broadcast: HogFlowApi) => {+ broadcast: HogFlowApi+ }+ launchBroadcast: () => {+ value: true+ }+ launchBroadcastFinished: () => {+ value: true+ }+ loadBatchJobs: () => any+ loadBatchJobsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBatchJobsSuccess: (+ batchJobs: HogFlowBatchJobApi[],+ payload?: any+ ) => {+ batchJobs: HogFlowBatchJobApi[]+ payload?: any+ }+ loadBlastRadius: () => any+ loadBlastRadiusFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBlastRadiusSuccess: (+ blastRadius: BlastRadiusApi | null,+ payload?: any+ ) => {+ blastRadius: BlastRadiusApi | null+ payload?: any+ }+ loadBroadcast: () => any+ loadBroadcastFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBroadcastSuccess: (+ broadcast: HogFlowApi | null,+ payload?: any+ ) => {+ broadcast: HogFlowApi | null+ payload?: any+ }+ nextStep: () => {+ value: true+ }+ prevStep: () => {+ value: true+ }+ saveBroadcastFinished: (broadcast: HogFlowApi | null) => {+ broadcast: HogFlowApi | null+ }+ setAudienceProperties: (properties: AnyPropertyFilter[]) => {+ properties: AnyPropertyFilter[]+ }+ setConversion: (conversion: HogFlowConversionApi) => {+ conversion: HogFlowConversionApi+ }+ setEmail: (email: BroadcastEmailValue) => {+ email: BroadcastEmailValue+ }+ setEmailRateLimit: (emailRateLimit: HogFlowEmailSendingRateLimitApi | null) => {+ emailRateLimit: HogFlowEmailSendingRateLimitApi | null+ }+ setGoalEnabled: (enabled: boolean) => {+ enabled: boolean+ }+ setName: (name: string) => {+ name: string+ }+ setRecurringRepeating: (repeating: boolean) => {+ repeating: boolean+ }+ setRecurringStartsAt: (startsAt: string | null) => {+ startsAt: string | null+ }+ setRecurringStartsAtFromPicker: (pickerDate: string | null) => {+ pickerDate: string | null+ }+ setScheduleMode: (mode: BroadcastScheduleMode) => {+ mode: BroadcastScheduleMode+ }+ setScheduleState: (+ state: ScheduleState,+ source?: 'natural_language' | 'picker'+ ) => {+ source: 'natural_language' | 'picker'+ state: ScheduleState+ }+ setScheduleTimezone: (+ timezone: string,+ previousTimezone?: string+ ) => {+ previousTimezone: string | undefined+ timezone: string+ }+ setSendAt: (sendAt: string | null) => {+ sendAt: string | null+ }+ setSendAtFromPicker: (pickerDate: string | null) => {+ pickerDate: string | null+ }+ setStep: (step: BroadcastWizardStep) => {+ step: BroadcastWizardStep+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastWizardLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ broadcastId: (broadcast: HogFlowApi | null, id: string) => string | null+ isReadOnly: (broadcast: HogFlowApi | null) => boolean+ effectiveTimezone: (scheduleTimezone: string | null, currentTeam: TeamPublicType | TeamType | null) => string+ stepValidationErrors: (+ goalEnabled: boolean,+ conversion: HogFlowConversionApi,+ email: BroadcastEmailValue,+ scheduleMode: BroadcastScheduleMode,+ sendAt: string | null,+ recurringStartsAt: string | null+ ) => Record<BroadcastWizardStep, string[]>+ currentStepHasErrors: (+ stepValidationErrors: Record<BroadcastWizardStep, string[]>,+ currentStep: BroadcastWizardStep+ ) => boolean+ firstInvalidStep: (stepValidationErrors: Record<BroadcastWizardStep, string[]>) => BroadcastWizardStep | null+ scheduleSummary: (+ scheduleMode: BroadcastScheduleMode,+ sendAt: string | null,+ scheduleState: ScheduleState,+ recurringStartsAt: string | null,+ recurringRepeating: boolean,+ effectiveTimezone: string+ ) => string+ rateLimitedSendDuration: (+ emailRateLimit: HogFlowEmailSendingRateLimitApi | null,+ blastRadius: BlastRadiusApi | null+ ) => string+ breadcrumbs: (name: string) => Breadcrumb[]+ }+}++export type broadcastWizardLogicType = MakeLogicType<+ broadcastWizardLogicValues,+ broadcastWizardLogicActions,+ BroadcastWizardLogicProps,+ broadcastWizardLogicMeta+>++export const broadcastWizardLogic = kea<broadcastWizardLogicType>([+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastWizardLogic']),+ props({} as BroadcastWizardLogicProps),+ key((props) => props.id),++ connect(() => ({+ values: [projectLogic, ['currentProjectId'], teamLogic, ['currentTeam']],+ })),++ actions({+ setStep: (step: BroadcastWizardStep) => ({ step }),+ nextStep: true,+ prevStep: true,+ continueStep: true,+ setName: (name: string) => ({ name }),+ setAudienceProperties: (properties: AnyPropertyFilter[]) => ({ properties }),+ setGoalEnabled: (enabled: boolean) => ({ enabled }),+ setConversion: (conversion: HogFlowConversionApi) => ({ conversion }),+ setEmailRateLimit: (emailRateLimit: HogFlowEmailSendingRateLimitApi | null) => ({ emailRateLimit }),+ setEmail: (email: BroadcastEmailValue) => ({ email }),+ setScheduleMode: (mode: BroadcastScheduleMode) => ({ mode }),+ setSendAt: (sendAt: string | null) => ({ sendAt }),+ setSendAtFromPicker: (pickerDate: string | null) => ({ pickerDate }),+ setScheduleState: (state: ScheduleState, source: 'picker' | 'natural_language' = 'picker') => ({+ state,+ source,+ }),+ setRecurringStartsAt: (startsAt: string | null) => ({ startsAt }),+ setRecurringStartsAtFromPicker: (pickerDate: string | null) => ({ pickerDate }),+ setScheduleTimezone: (timezone: string, previousTimezone?: string) => ({ timezone, previousTimezone }),+ setRecurringRepeating: (repeating: boolean) => ({ repeating }),+ hydrateFromBroadcast: (broadcast: HogFlowApi) => ({ broadcast }),+ saveBroadcastFinished: (broadcast: HogFlowApi | null) => ({ broadcast }),+ launchBroadcast: true,+ launchBroadcastFinished: true,+ }),++ loaders(({ props, values }) => ({+ broadcast: [+ null as HogFlowApi | null,+ {+ loadBroadcast: async () => {+ if (props.id === 'new' || !values.currentProjectId) {+ return values.broadcast+ }+ return await hogFlowsRetrieve(String(values.currentProjectId), props.id)+ },+ },+ ],+ blastRadius: [+ null as BlastRadiusApi | null,+ {+ loadBlastRadius: async () => {+ if (!values.currentProjectId) {+ return null+ }+ return await hogFlowsUserBlastRadiusCreate(String(values.currentProjectId), {+ filters: { properties: values.audienceProperties },+ dedupe_key: 'email',+ })+ },+ },+ ],+ batchJobs: [+ [] as HogFlowBatchJobApi[],+ {+ loadBatchJobs: async () => {+ if (!values.broadcastId || !values.currentProjectId) {+ return []+ }+ return await hogFlowsBatchJobsList(String(values.currentProjectId), values.broadcastId)+ },+ },+ ],+ })),++ reducers(({ props }) => ({+ broadcast: {+ saveBroadcastFinished: (state: HogFlowApi | null, { broadcast }: { broadcast: HogFlowApi | null }) =>+ broadcast ?? state,+ },+ currentStep: [+ 'recipients' as BroadcastWizardStep,+ {+ setStep: (_, { step }) => step,+ nextStep: (state) => {+ const index = BROADCAST_WIZARD_STEPS.indexOf(state)+ return BROADCAST_WIZARD_STEPS[Math.min(index + 1, BROADCAST_WIZARD_STEPS.length - 1)]+ },+ prevStep: (state) => {+ const index = BROADCAST_WIZARD_STEPS.indexOf(state)+ return BROADCAST_WIZARD_STEPS[Math.max(index - 1, 0)]+ },+ },+ ],+ name: [+ 'New broadcast',+ {+ setName: (_, { name }) => name,+ hydrateFromBroadcast: (state, { broadcast }) => broadcast.name || state,+ },+ ],+ audienceProperties: [+ [] as AnyPropertyFilter[],+ {+ setAudienceProperties: (_, { properties }) => properties,+ hydrateFromBroadcast: (state, { broadcast }) => {+ const trigger = findAction(broadcast, 'trigger')+ return (trigger?.config?.filters?.properties as AnyPropertyFilter[]) ?? state+ },+ },+ ],+ goalEnabled: [+ false,+ {+ setGoalEnabled: (_, { enabled }) => enabled,+ hydrateFromBroadcast: (state, { broadcast }) => {+ const conversion = broadcast.conversion+ if (!conversion) {+ return state+ }+ return (conversion.events?.length ?? 0) > 0 || (conversion.filters?.length ?? 0) > 0+ },+ },+ ],+ conversion: [+ DEFAULT_BROADCAST_CONVERSION,+ {+ setConversion: (_, { conversion }) => conversion,+ hydrateFromBroadcast: (state, { broadcast }) =>+ broadcast.conversion ? { ...DEFAULT_BROADCAST_CONVERSION, ...broadcast.conversion } : state,+ },+ ],+ emailRateLimit: [+ null as HogFlowEmailSendingRateLimitApi | null,+ {+ setEmailRateLimit: (_, { emailRateLimit }) => emailRateLimit,+ hydrateFromBroadcast: (state, { broadcast }) => broadcast.email_sending_rate_limit ?? state,+ },+ ],+ email: [+ DEFAULT_BROADCAST_EMAIL,+ {+ setEmail: (_, { email }) => email,+ hydrateFromBroadcast: (state, { broadcast }) => {+ const emailAction = findAction(broadcast, 'function_email')+ const value = emailAction?.config?.inputs?.email?.value+ return value ? { ...DEFAULT_BROADCAST_EMAIL, ...value } : state+ },+ },+ ],+ scheduleMode: [+ 'now' as BroadcastScheduleMode,+ {+ setScheduleMode: (_, { mode }) => mode,+ hydrateFromBroadcast: (state, { broadcast }) => {+ const schedule = broadcast.schedules?.[0]+ if (!schedule) {+ return state+ }+ return isOneTimeSchedule(schedule.rrule) ? 'later' : 'recurring'+ },+ },+ ],+ sendAt: [+ null as string | null,+ {+ setSendAt: (_, { sendAt }) => sendAt,+ hydrateFromBroadcast: (state, { broadcast }) => {+ const schedule = broadcast.schedules?.[0]+ return schedule && isOneTimeSchedule(schedule.rrule) ? schedule.starts_at : state+ },+ },+ ],+ scheduleState: [+ DEFAULT_STATE,+ {+ setScheduleState: (_, { state }) => state,+ hydrateFromBroadcast: (state, { broadcast }) => {+ const schedule = broadcast.schedules?.[0]+ return schedule && !isOneTimeSchedule(schedule.rrule) ? parseRRuleToState(schedule.rrule) : state+ },+ },+ ],+ recurringStartsAt: [+ null as string | null,+ {+ setRecurringStartsAt: (_, { startsAt }) => startsAt,+ hydrateFromBroadcast: (state, { broadcast }) => {+ const schedule = broadcast.schedules?.[0]+ return schedule && !isOneTimeSchedule(schedule.rrule) ? schedule.starts_at : state+ },+ },+ ],+ recurringRepeating: [+ true,+ {+ setRecurringRepeating: (_, { repeating }) => repeating,+ },+ ],+ scheduleTimezone: [+ null as string | null,+ {+ setScheduleTimezone: (_, { timezone }) => timezone,+ hydrateFromBroadcast: (state, { broadcast }) => broadcast.schedules?.[0]?.timezone ?? state,+ },+ ],+ saving: [+ false,+ {+ continueStep: () => true,+ saveBroadcastFinished: () => false,+ },+ ],+ launching: [+ false,+ {+ launchBroadcast: () => true,+ launchBroadcastFinished: () => false,+ },+ ],+ // Set once the initial load of an existing draft has hydrated the reducers, so the wizard can+ // resume at the first incomplete step exactly once.+ hasHydrated: [+ props.id !== 'new' ? false : true,+ {+ hydrateFromBroadcast: () => true,+ },+ ],+ })),++ selectors({+ broadcastId: [+ (s, p) => [s.broadcast, p.id],+ (broadcast: HogFlowApi | null, id: string): string | null => broadcast?.id ?? (id !== 'new' ? id : null),+ ],+ isReadOnly: [+ (s) => [s.broadcast],+ (broadcast: HogFlowApi | null): boolean => !!broadcast && broadcast.status !== 'draft',+ ],+ effectiveTimezone: [+ (s) => [s.scheduleTimezone, s.currentTeam],+ (scheduleTimezone: string | null, currentTeam: TeamPublicType | TeamType | null): string =>+ scheduleTimezone ?? currentTeam?.timezone ?? dayjs.tz.guess(),+ ],+ stepValidationErrors: [+ (s) => [s.goalEnabled, s.conversion, s.email, s.scheduleMode, s.sendAt, s.recurringStartsAt],+ (+ goalEnabled: boolean,+ conversion: HogFlowConversionApi,+ email: BroadcastEmailValue,+ scheduleMode: BroadcastScheduleMode,+ sendAt: string | null,+ recurringStartsAt: string | null+ ): Record<BroadcastWizardStep, string[]> => {+ const errors: Record<BroadcastWizardStep, string[]> = {+ recipients: [],+ goal: [],+ content: [],+ schedule: [],+ review: [],+ }++ if (goalEnabled) {+ const hasEventGoal = (conversion.events?.[0]?.filters?.events?.length ?? 0) > 0+ const hasPropertyGoal = (conversion.filters?.length ?? 0) > 0+ if (!hasEventGoal && !hasPropertyGoal) {+ errors.goal.push('Add a conversion event or property, or choose no goal')+ }+ }++ if (!email.from?.integrationId) {+ errors.content.push('Choose an email sender')+ }+ if (!email.subject) {+ errors.content.push('Add a subject line')+ }+ if (!email.html && !email.text && !email.design) {+ errors.content.push('Add email content')+ }++ if (scheduleMode === 'later') {+ if (!sendAt) {+ errors.schedule.push('Pick a send date and time')+ } else if (dayjs(sendAt).isBefore(dayjs())) {+ errors.schedule.push('The send time must be in the future')+ }+ }+ if (scheduleMode === 'recurring' && !recurringStartsAt) {+ errors.schedule.push('Pick a start date and time')+ }++ errors.review = [...errors.recipients, ...errors.goal, ...errors.content, ...errors.schedule]++ return errors+ },+ ],+ currentStepHasErrors: [+ (s) => [s.stepValidationErrors, s.currentStep],+ (errors: Record<BroadcastWizardStep, string[]>, currentStep: BroadcastWizardStep): boolean =>+ errors[currentStep].length > 0,+ ],+ firstInvalidStep: [+ (s) => [s.stepValidationErrors],+ (errors: Record<BroadcastWizardStep, string[]>): BroadcastWizardStep | null =>+ BROADCAST_WIZARD_STEPS.find((step) => step !== 'review' && errors[step].length > 0) ?? null,+ ],+ scheduleSummary: [+ (s) => [+ s.scheduleMode,+ s.sendAt,+ s.scheduleState,+ s.recurringStartsAt,+ s.recurringRepeating,+ s.effectiveTimezone,+ ],+ (+ scheduleMode: BroadcastScheduleMode,+ sendAt: string | null,+ scheduleState: ScheduleState,+ recurringStartsAt: string | null,+ recurringRepeating: boolean,+ effectiveTimezone: string+ ): string => {+ if (scheduleMode === 'now') {+ return 'Sends immediately'+ }+ if (scheduleMode === 'later') {+ return sendAt+ ? `Sends once on ${dayjs(sendAt).tz(effectiveTimezone).format('MMMM D, YYYY h:mm A')} (${effectiveTimezone})`+ : 'No send time set'+ }+ if (!recurringStartsAt) {+ return 'No start time set'+ }+ if (!recurringRepeating) {+ return `Sends once on ${dayjs(recurringStartsAt).tz(effectiveTimezone).format('MMMM D, YYYY h:mm A')} (${effectiveTimezone})`+ }+ return buildSummary(scheduleState, recurringStartsAt)+ },+ ],+ rateLimitedSendDuration: [+ (s) => [s.emailRateLimit, s.blastRadius],+ (emailRateLimit: HogFlowEmailSendingRateLimitApi | null, blastRadius: BlastRadiusApi | null): string => {+ const recipients = blastRadius?.affected+ if (!emailRateLimit || !recipients) {+ return ''+ }+ // An estimate: the worker holds sends under the limit by rescheduling them, and it+ // retries on a jittered delay, so the real send runs a little longer than this.+ const perSecond = emailRateLimit.count / (emailRateLimit.period === 'hour' ? 3600 : 60)+ return humanFriendlyDuration(Math.ceil(recipients / perSecond), { maxUnits: 2 })+ },+ ],+ breadcrumbs: [+ (s) => [s.name],+ (name: string): Breadcrumb[] => [+ {+ key: Scene.Workflows,+ name: 'Broadcasts',+ path: urls.broadcasts(),+ iconType: 'workflows',+ },+ {+ key: [Scene.Broadcast, name],+ name,+ iconType: 'workflows',+ },+ ],+ ],+ }),++ listeners(({ actions, values }) => ({+ setAudienceProperties: async (_, breakpoint) => {+ // Debounce so each filter keystroke doesn't fire a preview query.+ await breakpoint(500)+ actions.loadBlastRadius()+ },+ setStep: ({ step }) => {+ if (step === 'review') {+ // A fresh preview mints the confirm token launch needs and shows an up-to-date count.+ actions.loadBlastRadius()+ }+ },+ nextStep: () => {+ // Listeners run after reducers, so this sees the step just navigated to.+ if (values.currentStep === 'review') {+ actions.loadBlastRadius()+ }+ },+ setSendAtFromPicker: ({ pickerDate }) => {+ if (!pickerDate) {+ actions.setSendAt(null)+ return+ }+ // The picker returns browser-local time; reinterpret it in the schedule timezone.+ const wallClock = dayjs(pickerDate).startOf('minute').format('YYYY-MM-DDTHH:mm:ss')+ actions.setSendAt(dayjs.tz(wallClock, values.effectiveTimezone).toISOString())+ },+ setRecurringStartsAtFromPicker: ({ pickerDate }) => {+ if (!pickerDate) {+ actions.setRecurringStartsAt(null)+ return+ }+ const wallClock = dayjs(pickerDate).startOf('minute').format('YYYY-MM-DDTHH:mm:ss')+ actions.setRecurringStartsAt(dayjs.tz(wallClock, values.effectiveTimezone).toISOString())+ },+ setScheduleTimezone: ({ timezone, previousTimezone }) => {+ // Keep the wall-clock time when the timezone changes, matching the workflow editor.+ const oldTz = previousTimezone ?? dayjs.tz.guess()+ if (values.sendAt) {+ const wallClock = dayjs(values.sendAt).tz(oldTz).format('YYYY-MM-DDTHH:mm:ss')+ actions.setSendAt(dayjs.tz(wallClock, timezone).toISOString())+ }+ if (values.recurringStartsAt) {+ const wallClock = dayjs(values.recurringStartsAt).tz(oldTz).format('YYYY-MM-DDTHH:mm:ss')+ actions.setRecurringStartsAt(dayjs.tz(wallClock, timezone).toISOString())+ }+ },+ continueStep: async () => {+ if (values.currentStepHasErrors || !values.currentProjectId) {+ actions.saveBroadcastFinished(null)+ return+ }+ const projectId = String(values.currentProjectId)+ try {+ let saved: HogFlowApi+ if (!values.broadcastId) {+ saved = await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)+ } else {+ saved = await hogFlowsPartialUpdate(+ projectId,+ values.broadcastId,+ buildBroadcastPayload(values) as any+ )+ }+ actions.saveBroadcastFinished(saved)+ actions.nextStep()+ } catch (error: any) {+ actions.saveBroadcastFinished(null)+ lemonToast.error(`Couldn't save the broadcast: ${error?.detail || error?.message || 'unknown error'}`)+ }+ },+ launchBroadcast: async () => {+ if (!values.currentProjectId) {+ actions.launchBroadcastFinished()+ return+ }+ if (values.firstInvalidStep) {+ actions.launchBroadcastFinished()+ actions.setStep(values.firstInvalidStep)+ return+ }+ const projectId = String(values.currentProjectId)+ let broadcastId = values.broadcastId+ let activated: HogFlowApi | null = null+ try {+ // Save the latest edits (creating the draft if the user skipped ahead).+ if (!broadcastId) {+ const created = await hogFlowsCreate(projectId, buildBroadcastPayload(values) as any)+ broadcastId = created.id+ actions.saveBroadcastFinished(created)+ } else {+ const saved = await hogFlowsPartialUpdate(+ projectId,+ broadcastId,+ buildBroadcastPayload(values) as any+ )+ actions.saveBroadcastFinished(saved)+ }++ // A fresh audience preview mints the confirm token the batch dispatch expects.+ const blastRadius = await hogFlowsUserBlastRadiusCreate(projectId, {+ filters: { properties: values.audienceProperties },+ dedupe_key: 'email',+ })++ // The resolver silently caps the batch at this limit, so dispatching an audience over+ // it would confirm N recipients and deliver to the first slice. Stop at the step that+ // can fix it. Mirrors the guard on the workflow editor's manual trigger.+ if (blastRadius.limit != null && blastRadius.affected > blastRadius.limit) {+ actions.launchBroadcastFinished()+ actions.setStep('recipients')+ lemonToast.error(+ `This audience is above the project's batch limit of ${humanFriendlyNumber(+ blastRadius.limit+ )}. Add filters to narrow it, then launch again.`+ )+ return+ }++ activated = await hogFlowsPartialUpdate(projectId, broadcastId, { status: 'active' })++ if (values.scheduleMode === 'now') {+ await hogFlowsBatchJobsCreate(projectId, broadcastId, {+ hog_flow: broadcastId,+ variables: {},+ confirm_token: blastRadius.confirm_token,+ } 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,+ }+ 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+ // no-op there. Store the activated broadcast so the scene swaps to the read-only summary+ // instead of leaving a live send button on a broadcast that already went out.+ actions.saveBroadcastFinished(activated)+ actions.loadBatchJobs()+ actions.launchBroadcastFinished()+ router.actions.push(urls.broadcast(broadcastId))+ } catch (error: any) {+ if (activated && broadcastId) {+ // Activation landed but the send did not. An active broadcast with no job and no+ // schedule is read-only, so leaving it there would strand it with no way to retry.+ try {+ await hogFlowsPartialUpdate(projectId, broadcastId, { status: 'draft' })+ } catch {+ lemonToast.error('The broadcast is still active but has nothing scheduled. Reload the page.')+ }+ }+ actions.launchBroadcastFinished()+ lemonToast.error(`Couldn't launch the broadcast: ${error?.detail || error?.message || 'unknown error'}`)+ }+ },+ loadBroadcastSuccess: ({ broadcast }) => {+ if (!broadcast || values.hasHydrated) {+ return+ }+ actions.hydrateFromBroadcast(broadcast)+ if (broadcast.status !== 'draft') {+ actions.loadBatchJobs()+ }+ },+ hydrateFromBroadcast: () => {+ // Resume a draft at the first incomplete step; complete drafts land on review.+ if (values.broadcast?.status === 'draft') {+ actions.setStep(values.firstInvalidStep ?? 'review')+ }+ },+ loadBroadcastFailure: () => {+ lemonToast.error("Couldn't load the broadcast. Refresh the page to try again.")+ },+ })),++ afterMount(({ actions, props }) => {+ if (props.id !== 'new') {+ actions.loadBroadcast()+ } else {+ actions.loadBlastRadius()+ }+ }),+])++// 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: {+ name: string+ audienceProperties: AnyPropertyFilter[]+ goalEnabled: boolean+ conversion: HogFlowConversionApi+ email: BroadcastEmailValue+ emailRateLimit: HogFlowEmailSendingRateLimitApi | null+}): Record<string, any> {+ return {+ origin_product: 'broadcasts',+ status: 'draft',+ name: values.name,+ exit_condition: 'exit_only_at_end',+ conversion: values.goalEnabled ? values.conversion : null,+ email_sending_rate_limit: values.emailRateLimit,+ actions: [+ {+ id: TRIGGER_ACTION_ID,+ type: 'trigger',+ name: 'Audience',+ description: 'People this broadcast is sent to.',+ created_at: 0,+ updated_at: 0,+ config: {+ type: 'batch',+ filters: { properties: values.audienceProperties },+ },+ },+ {+ id: EMAIL_ACTION_ID,+ type: 'function_email',+ name: 'Send email',+ description: 'The broadcast email.',+ created_at: 0,+ updated_at: 0,+ config: {+ template_id: 'template-email',+ inputs: {+ email: { value: values.email },+ },+ },+ },+ {+ id: EXIT_ACTION_ID,+ type: 'exit',+ name: 'Exit',+ description: 'Broadcast sent.',+ created_at: 0,+ updated_at: 0,+ config: { reason: 'Broadcast sent' },+ },+ ],+ edges: [+ { from: TRIGGER_ACTION_ID, to: EMAIL_ACTION_ID, type: 'continue' },+ { from: EMAIL_ACTION_ID, to: EXIT_ACTION_ID, type: 'continue' },+ ],+ }+}diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.tsnew file mode 100644index 000000000000..7ab8d7625a60--- /dev/null+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts@@ -0,0 +1,188 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from '@posthog/lemon-ui'++import { loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'+import { dayjs } from 'lib/dayjs'+import { projectLogic } from 'scenes/projectLogic'+import { teamLogic } from 'scenes/teamLogic'++import { TeamPublicType, TeamType } from '~/types'++import { hogFlowsBatchJobsList, hogFlowsList } from 'products/workflows/frontend/generated/api'+import type {+ HogFlowBatchJobApi,+ HogFlowMinimalApi,+ PaginatedHogFlowMinimalListApi,+} from 'products/workflows/frontend/generated/api.schemas'++export type BroadcastStatus = 'draft' | 'scheduled' | 'sending' | 'sent' | 'failed' | 'archived'++export interface BroadcastRowDetails {+ latestBatchJob: HogFlowBatchJobApi | null+ totals: Record<string, number>+}++export function getBroadcastStatus(+ broadcast: HogFlowMinimalApi,+ details: BroadcastRowDetails | undefined+): BroadcastStatus {+ if (broadcast.status === 'draft') {+ return 'draft'+ }+ if (broadcast.status === 'archived') {+ return 'archived'+ }+ const latestJob = details?.latestBatchJob+ if (latestJob) {+ if (['waiting', 'queued', 'active'].includes(latestJob.status ?? '')) {+ return 'sending'+ }+ if (latestJob.status === 'completed') {+ return 'sent'+ }+ // Without this a failed or cancelled run falls through to the no-run fallback below, which+ // tells the sender another send is still pending when nothing is coming.+ return 'failed'+ }+ // Active with no batch job yet: it's waiting on its schedule (or a manual send).+ return 'scheduled'+}++// A batch send's email metrics are recorded against the batch job, not the flow, so the row counts+// come from the latest run rather than the flow-scoped totals endpoint.+async function loadRunMetricTotals(job: HogFlowBatchJobApi, timezone: string): Promise<Record<string, number>> {+ const created = dayjs(job.created_at)+ const response = await loadAppMetricsTotals(+ {+ appSource: 'hog_flow',+ appSourceId: job.id,+ breakdownBy: ['metric_name'],+ dateFrom: created.subtract(1, 'hour').toISOString(),+ dateTo: dayjs().add(1, 'hour').toISOString(),+ },+ timezone+ )+ return Object.fromEntries(Object.entries(response).map(([metricName, { total }]) => [metricName, total]))+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastsLogicValues {+ currentProjectId: number | null // projectLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ broadcasts: PaginatedHogFlowMinimalListApi+ broadcastsLoading: boolean+ hasLoadedBroadcasts: boolean+ rowDetailsById: Record<string, BroadcastRowDetails>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface broadcastsLogicActions {+ loadBroadcasts: () => {+ value: true+ }+ loadBroadcastsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBroadcastsSuccess: (+ broadcasts: PaginatedHogFlowMinimalListApi,+ payload?: {+ value: true+ }+ ) => {+ broadcasts: PaginatedHogFlowMinimalListApi+ payload?: {+ value: true+ }+ }+ setRowDetails: (+ id: string,+ details: BroadcastRowDetails+ ) => {+ details: BroadcastRowDetails+ id: string+ }+}++export type broadcastsLogicType = MakeLogicType<broadcastsLogicValues, broadcastsLogicActions>++export const broadcastsLogic = kea<broadcastsLogicType>([+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastsLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId'], teamLogic, ['currentTeam']],+ })),+ actions({+ loadBroadcasts: true,+ setRowDetails: (id: string, details: BroadcastRowDetails) => ({ id, details }),+ }),+ loaders(({ values }) => ({+ broadcasts: [+ { results: [], count: 0 } as PaginatedHogFlowMinimalListApi,+ {+ loadBroadcasts: async () => {+ if (!values.currentProjectId) {+ return values.broadcasts+ }+ return await hogFlowsList(String(values.currentProjectId), {+ type: 'broadcast',+ limit: 100,+ })+ },+ },+ ],+ })),+ reducers({+ rowDetailsById: [+ {} as Record<string, BroadcastRowDetails>,+ {+ setRowDetails: (state, { id, details }) => ({ ...state, [id]: details }),+ },+ ],+ hasLoadedBroadcasts: [+ false as boolean,+ {+ loadBroadcastsSuccess: () => true,+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ loadBroadcastsSuccess: ({ broadcasts }) => {+ const projectId = values.currentProjectId+ if (!projectId) {+ return+ }+ // Best-effort per-row enrichment: batch jobs decide the status chip, metric totals fill+ // the engagement counts. Rows without details just show their fallbacks.+ for (const broadcast of broadcasts.results ?? []) {+ void (async () => {+ try {+ const batchJobs =+ broadcast.status === 'draft'+ ? ([] as HogFlowBatchJobApi[])+ : await hogFlowsBatchJobsList(String(projectId), broadcast.id)+ const latestBatchJob = batchJobs[0] ?? null+ actions.setRowDetails(broadcast.id, {+ latestBatchJob,+ totals: latestBatchJob+ ? await loadRunMetricTotals(latestBatchJob, values.currentTeam?.timezone ?? 'UTC')+ : {},+ })+ } catch {+ // Leave the row on its fallbacks; the list itself already loaded.+ }+ })()+ }+ },+ loadBroadcastsFailure: () => {+ lemonToast.error("Couldn't load broadcasts. Refresh the page to try again.")+ },+ })),+ afterMount(({ actions }) => {+ actions.loadBroadcasts()+ }),+])diff --git a/products/workflows/frontend/Broadcasts/emailPreview.test.ts b/products/workflows/frontend/Broadcasts/emailPreview.test.tsnew file mode 100644index 000000000000..38b63f39cc6e--- /dev/null+++ b/products/workflows/frontend/Broadcasts/emailPreview.test.ts@@ -0,0 +1,60 @@+import { renderEmailPreview } from './emailPreview'++describe('renderEmailPreview', () => {+ const person = {+ id: 'person-1',+ properties: { email: '[email protected]', first_name: 'Sam' },+ }++ it.each([+ ['substitutes a property the person has', 'Hi {{ person.properties.first_name }}', 'Hi Sam'],+ [+ 'keeps a property the person lacks visible instead of blanking it',+ 'Hi {{ person.properties.nickname }}',+ 'Hi {{ person.properties.nickname }}',+ ],+ ['keeps an unknown root visible', 'Your plan: {{ customer.plan_name }}', 'Your plan: {{ customer.plan_name }}'],+ [+ 'leaves a filter to supply its own fallback',+ "Hi {{ person.properties.nickname | default: 'there' }}",+ 'Hi there',+ ],+ [+ 'keeps a missing property visible when its tag spans lines',+ 'Hi {{\n person.properties.nickname \n}}',+ 'Hi {{\n person.properties.nickname \n}}',+ ],+ [+ 'leaves a tag the template already marked raw alone',+ 'Hi {% raw %}{{ person.properties.nickname }}{% endraw %}',+ 'Hi {{ person.properties.nickname }}',+ ],+ [+ 'reads a filter argument containing the closing braces as part of the expression',+ 'Hi {{ person.properties.nickname | default: "}}" }}',+ 'Hi }}',+ ],+ ])('%s', (_name, template, expected) => {+ expect(renderEmailPreview(template, person)).toBe(expected)+ })++ it('decodes liquid tags the email editor escaped', () => {+ // Unlayer escapes the whole document, so a comparison arrives as > and must still evaluate.+ expect(+ renderEmailPreview('{% if person.properties.age > 20 %}adult{% endif %}', {+ id: 'person-2',+ properties: { age: 30 },+ })+ ).toBe('adult')+ })++ it('returns the template untouched when there is no person to render against', () => {+ expect(renderEmailPreview('Hi {{ person.properties.first_name }}', null)).toBe(+ 'Hi {{ person.properties.first_name }}'+ )+ })++ it('falls back to the template rather than throwing on a broken tag', () => {+ expect(renderEmailPreview('{% for %}', person)).toBe('{% for %}')+ })+})diff --git a/products/workflows/frontend/Broadcasts/emailPreview.ts b/products/workflows/frontend/Broadcasts/emailPreview.tsnew file mode 100644index 000000000000..7e15b7a1de02--- /dev/null+++ b/products/workflows/frontend/Broadcasts/emailPreview.ts@@ -0,0 +1,34 @@+import { LiquidRenderer } from 'lib/utils/liquid'++/** The person values a preview renders against, shaped like the worker's `person` global. */+export interface EmailPreviewPerson {+ id: string+ properties: Record<string, any>+}++/**+ * Render one templated email field against a person, the way the send will.+ *+ * Returns the template unchanged when it can't be parsed, because a preview must never be the+ * thing that breaks the review step.+ */+export function renderEmailPreview(template: string, person: EmailPreviewPerson | null): string {+ if (!template || !person) {+ return template+ }+ const context = {+ person: {+ id: person.id,+ properties: person.properties,+ },+ // Injected by the email service per recipient. Stand it in so a preview doesn't report the+ // unsubscribe link every marketing email carries as a missing variable.+ unsubscribe_url: '#unsubscribe',+ now: new Date(),+ }+ try {+ return LiquidRenderer.renderKeepingUnresolved(template, context)+ } catch {+ return template+ }+}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsxnew file mode 100644index 000000000000..ddf0b05818ce--- /dev/null+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx@@ -0,0 +1,53 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { EmailTemplater, TemplatePickerModal } from 'scenes/hog-functions/email-templater/EmailTemplater'+import type { EmailFieldErrors, EmailTemplate } from 'scenes/hog-functions/email-templater/types'++import { buildSampleGlobals } from '../../Workflows/hogflows/steps/components/HogFlowFunctionConfiguration'+import { BroadcastEmailValue, DEFAULT_BROADCAST_EMAIL, broadcastWizardLogic } from '../broadcastWizardLogic'++export function BroadcastContentStep(): JSX.Element {+ const { email, stepValidationErrors } = useValues(broadcastWizardLogic)+ const { setEmail } = useActions(broadcastWizardLogic)+ const [templatePickerOpen, setTemplatePickerOpen] = useState(false)++ const errors = stepValidationErrors.content+ const fieldErrors: EmailFieldErrors = {+ from: errors.find((error) => error.includes('sender')),+ subject: errors.find((error) => error.includes('subject')),+ body: errors.find((error) => error.includes('content')),+ }++ return (+ <div className="flex flex-col gap-2 min-h-[36rem]">+ <div className="flex items-start justify-between gap-2">+ <div>+ <h2 className="m-0 text-xl font-semibold">Write your email</h2>+ <p className="m-0 text-secondary">Pick a sender, add a subject, and design the email.</p>+ </div>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setTemplatePickerOpen(true)}+ data-attr="broadcast-wizard-template-picker"+ >+ Start from template+ </LemonButton>+ </div>+ <TemplatePickerModal isOpen={templatePickerOpen} onClose={() => setTemplatePickerOpen(false)} />+ <EmailTemplater+ type="native_email"+ templating="liquid"+ liveChanges+ value={email as unknown as EmailTemplate}+ defaultValue={DEFAULT_BROADCAST_EMAIL as unknown as EmailTemplate}+ onChange={(value) => setEmail(value as unknown as BroadcastEmailValue)}+ variables={buildSampleGlobals({ type: 'batch' }, null)}+ fieldErrors={fieldErrors}+ />+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastGoalStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastGoalStep.tsxnew file mode 100644index 000000000000..209a9703794e--- /dev/null+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastGoalStep.tsx@@ -0,0 +1,57 @@+import { useActions, useValues } from 'kea'++import { LemonRadio } from 'lib/lemon-ui/LemonRadio'++import type { HogFlowConversionApi } from 'products/workflows/frontend/generated/api.schemas'++import { ConversionGoalEditor } from '../../Workflows/hogflows/steps/components/ConversionGoalEditor'+import { DEFAULT_BROADCAST_CONVERSION, broadcastWizardLogic } from '../broadcastWizardLogic'++export function BroadcastGoalStep(): JSX.Element {+ const { goalEnabled, conversion, stepValidationErrors } = useValues(broadcastWizardLogic)+ const { setGoalEnabled, setConversion } = useActions(broadcastWizardLogic)++ return (+ <div className="flex flex-col gap-4">+ <div>+ <h2 className="m-0 text-xl font-semibold">Do you want to measure a conversion goal?</h2>+ <p className="m-0 text-secondary">+ A goal counts recipients who do something after receiving the email, like signing up or making a+ purchase.+ </p>+ </div>++ <LemonRadio+ value={goalEnabled ? 'goal' : 'none'}+ onChange={(value) => setGoalEnabled(value === 'goal')}+ options={[+ { value: 'none', label: 'No goal' },+ { value: 'goal', label: 'Set a conversion goal' },+ ]}+ />++ {goalEnabled && (+ <div className="flex flex-col gap-2">+ <ConversionGoalEditor+ conversion={conversion}+ onChange={(newConversion) =>+ setConversion({+ ...DEFAULT_BROADCAST_CONVERSION,+ ...newConversion,+ } as HogFlowConversionApi)+ }+ pageKey="broadcast-wizard-goal"+ />+ <p className="m-0 text-xs text-muted">+ Conversions are counted within 7 days of a person receiving the broadcast.+ </p>+ {stepValidationErrors.goal.map((error) => (+ <div key={error} className="text-danger text-xs">+ {error}+ </div>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsxnew file mode 100644index 000000000000..69aec3020cb5--- /dev/null+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx@@ -0,0 +1,91 @@+import { useActions, useValues } from 'kea'++import { IconWarning } from '@posthog/icons'+import { Spinner } from '@posthog/lemon-ui'++import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'++import { PropertyFilterType } from '~/types'++import { WORKFLOW_OPERATOR_ALLOWLIST } from '../../Workflows/hogflows/filters/HogFlowFilters'+import { broadcastWizardLogic } from '../broadcastWizardLogic'++function AudienceSizePreview(): JSX.Element | null {+ const { blastRadius, blastRadiusLoading } = useValues(broadcastWizardLogic)++ if (blastRadiusLoading) {+ return <Spinner className="mt-1" />+ }++ if (!blastRadius) {+ return (+ <div className="text-warning text-xs flex items-center gap-1 mt-1">+ <IconWarning className="text-base shrink-0" />+ <span>Couldn't estimate the audience size. Check your filters and try again.</span>+ </div>+ )+ }++ const { affected, total, limit } = blastRadius+ const exceeded = limit != null && affected > limit++ return (+ <div className="text-muted">+ <span className={exceeded ? 'text-danger font-semibold' : undefined}>+ approximately {humanFriendlyNumber(affected)} of {humanFriendlyNumber(total)} people.+ </span>+ {exceeded && (+ <div className="text-danger text-xs">+ The audience exceeds the limit of {humanFriendlyNumber(limit)} people. Add filters to narrow it+ down.+ </div>+ )}+ </div>+ )+}++export function BroadcastRecipientsStep(): JSX.Element {+ const { audienceProperties } = useValues(broadcastWizardLogic)+ const { setAudienceProperties } = useActions(broadcastWizardLogic)++ return (+ <div className="flex flex-col gap-2">+ <div>+ <h2 className="m-0 text-xl font-semibold">Who should receive this email?</h2>+ <p className="m-0 text-secondary">+ Filter by person properties or static cohorts. Without filters, the broadcast goes to everyone.+ </p>+ </div>+ <div>+ <span className="font-semibold">This broadcast will reach</span> <AudienceSizePreview />+ </div>+ <PropertyFilters+ pageKey="broadcast-wizard-recipients"+ propertyFilters={audienceProperties}+ addText="Add condition"+ orFiltering+ sendAllKeyUpdates+ allowRelativeDateOptions+ {...COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS}+ hideBehavioralCohorts+ logicalRowDivider+ onChange={(properties) => setAudienceProperties(properties)}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.Cohorts,+ TaxonomicFilterGroupType.Metadata,+ ]}+ taxonomicFilterOptionsFromProp={{+ [TaxonomicFilterGroupType.Metadata]: [+ { name: 'distinct_id', propertyFilterType: PropertyFilterType.Person },+ ],+ }}+ hasRowOperator={false}+ operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}+ />+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsxnew file mode 100644index 000000000000..baee495135e9--- /dev/null+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx@@ -0,0 +1,102 @@+import { useValues } from 'kea'++import { Spinner } from '@posthog/lemon-ui'++import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import { BroadcastEmailPreview } from '../BroadcastEmailPreview'+import { broadcastWizardLogic } from '../broadcastWizardLogic'++function ReviewRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+ return (+ <div className="flex flex-col gap-1 border-b border-border pb-3 last:border-b-0">+ <span className="text-xs font-semibold uppercase tracking-wide text-muted">{label}</span>+ <div>{children}</div>+ </div>+ )+}++export function BroadcastReviewStep(): JSX.Element {+ const {+ audienceProperties,+ blastRadius,+ blastRadiusLoading,+ goalEnabled,+ conversion,+ scheduleSummary,+ emailRateLimit,+ rateLimitedSendDuration,+ stepValidationErrors,+ } = useValues(broadcastWizardLogic)++ const goalEventNames: string[] = goalEnabled+ ? (conversion.events?.[0]?.filters?.events ?? []).map(+ (event: { name?: string; id?: string }) => event.name || String(event.id)+ )+ : []++ return (+ <div className="flex flex-col gap-4">+ <div>+ <h2 className="m-0 text-xl font-semibold">Review and confirm</h2>+ <p className="m-0 text-secondary">Check everything before sending. Emails can't be unsent.</p>+ </div>++ <div className="flex flex-col gap-3 rounded-lg border border-border bg-surface-primary p-4">+ <ReviewRow label="Recipients">+ {blastRadiusLoading ? (+ <Spinner />+ ) : blastRadius ? (+ <span>+ Approximately {humanFriendlyNumber(blastRadius.affected)} of{' '}+ {humanFriendlyNumber(blastRadius.total)} people+ </span>+ ) : (+ <span className="text-warning">Couldn't estimate the audience size</span>+ )}+ {audienceProperties.length > 0 ? (+ <PropertyFiltersDisplay filters={audienceProperties} />+ ) : (+ <div className="text-muted text-xs">No filters. This broadcast goes to everyone.</div>+ )}+ </ReviewRow>++ <ReviewRow label="Goal">+ {goalEnabled ? (+ goalEventNames.length > 0 ? (+ <span>Conversion when a person performs: {goalEventNames.join(', ')}</span>+ ) : (+ <span>Conversion goal based on property changes</span>+ )+ ) : (+ <span className="text-muted">No goal</span>+ )}+ </ReviewRow>++ <ReviewRow label="Email">+ <BroadcastEmailPreview />+ </ReviewRow>++ <ReviewRow label="Schedule">{scheduleSummary}</ReviewRow>++ {emailRateLimit && (+ <ReviewRow label="Sending rate">+ At most {humanFriendlyNumber(emailRateLimit.count)} emails per {emailRateLimit.period}+ {rateLimitedSendDuration ? `, so about ${rateLimitedSendDuration} to reach everyone` : ''}+ </ReviewRow>+ )}+ </div>++ {stepValidationErrors.review.length > 0 && (+ <div className="flex flex-col gap-1">+ {stepValidationErrors.review.map((error) => (+ <div key={error} className="text-danger text-xs">+ {error}+ </div>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsxnew file mode 100644index 000000000000..c4d8bee1cf15--- /dev/null+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx@@ -0,0 +1,133 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { LemonCalendarSelectInput, LemonSearchableSelect } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonRadio } from 'lib/lemon-ui/LemonRadio'+import { timeZoneLabel } from 'lib/utils/timezones'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'++import { EmailSendingRateLimitPicker } from '../../Workflows/hogflows/steps/components/EmailSendingRateLimitPicker'+import { RecurringSchedulePicker } from '../../Workflows/hogflows/steps/components/RecurringSchedulePicker'+import { broadcastWizardLogic } from '../broadcastWizardLogic'++function SendingRateLimit(): JSX.Element {+ const { emailRateLimit } = useValues(broadcastWizardLogic)+ const { setEmailRateLimit } = useActions(broadcastWizardLogic)++ return (+ <div className="max-w-160">+ <EmailSendingRateLimitPicker value={emailRateLimit} onChange={setEmailRateLimit} />+ </div>+ )+}++function TimezonePicker({ value, onChange }: { value: string; onChange: (timezone: string) => void }): JSX.Element {+ const { preflight } = useValues(preflightLogic)+ const options = useMemo(+ () =>+ Object.entries(preflight?.available_timezones || {}).map(([tz, offset]) => ({+ value: tz,+ label: timeZoneLabel(tz, offset),+ })),+ [preflight?.available_timezones]+ )++ return (+ <LemonSearchableSelect+ value={value}+ options={options}+ onChange={(val) => val && onChange(val)}+ searchPlaceholder="Search timezones..."+ fullWidth+ />+ )+}++export function BroadcastScheduleStep(): JSX.Element {+ const {+ scheduleMode,+ sendAt,+ scheduleState,+ recurringStartsAt,+ recurringRepeating,+ effectiveTimezone,+ stepValidationErrors,+ } = useValues(broadcastWizardLogic)+ const {+ setScheduleMode,+ setSendAtFromPicker,+ setScheduleState,+ setRecurringStartsAtFromPicker,+ setRecurringRepeating,+ setScheduleTimezone,+ } = useActions(broadcastWizardLogic)++ return (+ <div className="flex flex-col gap-4">+ <div>+ <h2 className="m-0 text-xl font-semibold">When should this email go out?</h2>+ <p className="m-0 text-secondary">Send it right away, pick a time, or set up a repeating schedule.</p>+ </div>++ <LemonRadio+ value={scheduleMode}+ onChange={setScheduleMode}+ options={[+ { value: 'now', label: 'Send now' },+ { value: 'later', label: 'Send later' },+ { value: 'recurring', label: 'Recurring' },+ ]}+ />++ {scheduleMode === 'later' && (+ <div className="flex flex-col gap-2 max-w-160">+ <LemonCalendarSelectInput+ buttonProps={{ fullWidth: true }}+ format="MMMM D, YYYY h:mm A"+ clearable+ value={sendAt ? dayjs(sendAt).tz(effectiveTimezone).tz(dayjs.tz.guess(), true) : null}+ onChange={(date) => setSendAtFromPicker(date ? date.toISOString() : null)}+ granularity="minute"+ selectionPeriod="upcoming"+ showTimeToggle={false}+ />+ <TimezonePicker+ value={effectiveTimezone}+ onChange={(timezone) => setScheduleTimezone(timezone, effectiveTimezone)}+ />+ {effectiveTimezone !== dayjs.tz.guess() && sendAt && (+ <span className="text-xs text-muted">+ Sends at {dayjs(sendAt).tz(effectiveTimezone).format('h:mm A')} {effectiveTimezone} · Your+ time: {dayjs(sendAt).format('h:mm A')} {dayjs.tz.guess()}+ </span>+ )}+ </div>+ )}++ {scheduleMode === 'recurring' && (+ <div className="max-w-160">+ <RecurringSchedulePicker+ state={scheduleState}+ startsAt={recurringStartsAt}+ timezone={effectiveTimezone}+ repeating={recurringRepeating}+ onStateChange={setScheduleState}+ onStartsAtChange={setRecurringStartsAtFromPicker}+ onTimezoneChange={setScheduleTimezone}+ onRepeatingChange={setRecurringRepeating}+ />+ </div>+ )}++ <SendingRateLimit />++ {stepValidationErrors.schedule.map((error) => (+ <div key={error} className="text-danger text-xs">+ {error}+ </div>+ ))}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsxindex e5de8943b807..9ea6c5576796 100644--- a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx+++ b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx@@ -26,9 +26,11 @@ function sumTimeSeries(timeSeries: AppMetricsTimeSeriesResponse | null): numberexport function EmailMetricsSummary({logicKey,onMetricClick,+ compact,}: {logicKey: stringonMetricClick?: (metricKey: EmailMetric) => void+ compact?: boolean}): JSX.Element {const { appMetricsTrendsLoading, appMetricsTrends, getSingleTrendSeries } = useValues(appMetricsLogic({ logicKey }))@@ -75,6 +77,7 @@ export function EmailMetricsSummary({onClick={canDrillDown ? () => onMetricClick(key) : undefined}onClickTooltip={`View invocations with a ${metric.name.toLowerCase()} log entry in this timeframe`}footer={shareOfSent ? <span>{shareOfSent} of sent</span> : null}+ compact={compact}/>)})}diff --git a/products/workflows/frontend/Workflows/WorkflowMetricCard.tsx b/products/workflows/frontend/Workflows/WorkflowMetricCard.tsxindex 583c3135081a..6ca5da2d52f7 100644--- a/products/workflows/frontend/Workflows/WorkflowMetricCard.tsx+++ b/products/workflows/frontend/Workflows/WorkflowMetricCard.tsx@@ -76,6 +76,8 @@ export interface WorkflowMetricCardProps {onClick?: () => voidonClickTooltip?: stringfooter?: ReactNode+ /** Shorter card, so a page with tables below it does not push them off screen. */+ compact?: boolean}// Collapse a response into the numbers the tile reads (per-index sums plus the grand total). A@@ -105,6 +107,7 @@ export function WorkflowMetricCard({onClick,onClickTooltip,footer,+ compact,}: WorkflowMetricCardProps): JSX.Element {const theme = useChartTheme()@@ -171,7 +174,7 @@ export function WorkflowMetricCard({<div className="flex flex-col px-3"><Skeleton className="h-4 w-24" /><Skeleton className="mt-3 h-9 w-32" />- <Skeleton className="mt-4 h-40 w-full" />+ <Skeleton className={compact ? 'mt-3 h-16 w-full' : 'mt-4 h-40 w-full'} /></div></div>)@@ -230,8 +233,8 @@ export function WorkflowMetricCard({</MetricTitle><MetricDelta /></MetricHeader>- <MetricValue className="mt-2" />- <MetricSparkline className="-mx-3 mt-4" />+ <MetricValue className={compact ? 'mt-1' : 'mt-2'} />+ <MetricSparkline className={compact ? '-mx-3 mt-2 h-16' : '-mx-3 mt-4'} /></Metric>{footer && (// Stop clicks here from firing the tile's drill — the footer carries its own link.diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 1f504f396480..99d32ea252c6 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -1,6 +1,6 @@import { Node } from '@xyflow/react'import { useActions, useValues } from 'kea'-import { useEffect, useMemo, useState } from 'react'+import { useMemo, useState } from 'react'import {IconBolt,@@ -16,7 +16,6 @@ import {import {LemonBanner,LemonButton,- LemonCheckbox,LemonCollapse,LemonDivider,LemonDropdown,@@ -60,7 +59,8 @@ import { TriggerFrequencyOption, getRegisteredTriggerTypes } from '../registry/timport { HogFlowAction } from '../types'import { createAccountAssignmentFilterUpdate, parseAccountAssignmentFilter } from './accountAssignmentFilter'import { batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './batchTriggerLogic'-import { HogFlowDuration, MAX_CONVERSION_WINDOW_FOR_DURATION_UNIT } from './components/HogFlowDuration'+import { ConversionGoalEditor } from './components/ConversionGoalEditor'+import { EmailSendingRateLimitPicker } from './components/EmailSendingRateLimitPicker'import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'import { RecurringSchedulePicker } from './components/RecurringSchedulePicker'import { ScheduleStatusBadge } from './components/ScheduleStatusBadge'@@ -379,7 +379,7 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }users, use a batch trigger instead.</p><LemonField.Pure error={validationResult?.errors?.schedule}>- <RecurringSchedulePicker />+ <WorkflowRecurringSchedulePicker /></LemonField.Pure></div>) : node.data.config.type === 'batch' ? (@@ -550,6 +550,25 @@ function StepTriggerConfigurationManual(): JSX.Element {)}+function WorkflowRecurringSchedulePicker(): JSX.Element {+ const { scheduleState, scheduleStartsAt, scheduleTimezone, isScheduleRepeating } = useValues(workflowLogic)+ const { setScheduleState, setScheduleStartsAtFromPicker, setScheduleTimezone, setScheduleRepeating } =+ useActions(workflowLogic)++ return (+ <RecurringSchedulePicker+ state={scheduleState}+ startsAt={scheduleStartsAt}+ timezone={scheduleTimezone}+ repeating={isScheduleRepeating}+ onStateChange={setScheduleState}+ onStartsAtChange={setScheduleStartsAtFromPicker}+ onTimezoneChange={setScheduleTimezone}+ onRepeatingChange={setScheduleRepeating}+ />+ )+}+function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; filters: any }): JSX.Element | null {const { workflow } = useValues(workflowLogic)const isAccountAudience = filters?.audience_type === 'accounts'@@ -615,7 +634,7 @@ function BatchScheduleSection(): JSX.Element {<><LemonDivider /><LemonLabel showOptional>Schedule</LemonLabel>- <RecurringSchedulePicker />+ <WorkflowRecurringSchedulePicker /></>)}@@ -947,32 +966,10 @@ function FrequencySection({)}-const DEFAULT_CONVERSION_WINDOW = '90d'-// The worker measures a legacy window_minutes at most this long, so a longer stored value is shown-// as what it actually measures rather than as a number the API would now reject.-const LEGACY_CONVERSION_WINDOW_CEILING_MINUTES = 90 * 24 * 60--function conversionWindowFromMinutes(minutes: number): string {- const capped = Math.min(minutes, LEGACY_CONVERSION_WINDOW_CEILING_MINUTES)- if (capped % (24 * 60) === 0) {- return `${capped / (24 * 60)}d`- }- if (capped % 60 === 0) {- return `${capped / 60}h`- }- return `${capped}m`-}-function ConversionGoalSection(): JSX.Element {const { setWorkflowValue } = useActions(workflowLogic)const { workflow } = useValues(workflowLogic)- const conversionEventFilters = workflow.conversion?.events?.[0]?.filters ?? {}- const legacyWindowMinutes = workflow.conversion?.window_minutes- const conversionWindow =- workflow.conversion?.window ??- (legacyWindowMinutes ? conversionWindowFromMinutes(legacyWindowMinutes) : DEFAULT_CONVERSION_WINDOW)-return (<div className="flex flex-col py-2 w-full"><span className="flex gap-1 items-center">@@ -987,64 +984,11 @@ function ConversionGoalSection(): JSX.Element {considered converted.</p>- <div className="flex flex-col gap-4">- <div className="flex flex-col gap-1 items-start">- <LemonLabel>Detect conversion from property changes</LemonLabel>- <PropertyFilters- buttonText="Add property conversion"- buttonClassName="grow-0"- propertyFilters={workflow.conversion?.filters ?? []}- taxonomicGroupTypes={[- TaxonomicFilterGroupType.PersonProperties,- TaxonomicFilterGroupType.HogQLExpression,- ]}- onChange={(filters) => setWorkflowValue('conversion', { ...workflow.conversion, filters })}- pageKey="workflow-conversion-properties"- hideBehavioralCohorts- operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}- logicalRowDivider- />- </div>-- <div className="flex flex-col gap-1 items-start w-full">- <LemonLabel>Detect conversion from events</LemonLabel>- <HogFlowEventFilters- filtersKey="workflow-conversion-events"- filters={conversionEventFilters}- setFilters={(newFilters) =>- setWorkflowValue('conversion', {- ...workflow.conversion,- events: newFilters ? [{ filters: newFilters }] : undefined,- })- }- typeKey="workflow-conversion-event"- buttonCopy="Add event"- />- </div>-- <div className="flex flex-col gap-1 items-start">- <span className="flex gap-1 items-center">- <LemonLabel>Conversion window</LemonLabel>- <Tooltip title="A person who meets the goal after this window is not counted as converted. The window runs from the moment they enter the workflow.">- <IconInfo className="text-secondary" />- </Tooltip>- </span>- <HogFlowDuration- value={conversionWindow}- onChange={(next) => {- // Dropping window_minutes keeps the two forms from arriving together, which- // the API rejects. A cleared amount arrives as a bare unit such as "d", so- // omitting window restores the default instead of failing the save.- const { window_minutes, window, ...conversion } = workflow.conversion ?? {}- setWorkflowValue(- 'conversion',- /\d/.test(next) ? { ...conversion, window: next } : conversion- )- }}- maxValueForUnit={MAX_CONVERSION_WINDOW_FOR_DURATION_UNIT}- />- </div>- </div>+ <ConversionGoalEditor+ conversion={workflow.conversion}+ onChange={(conversion) => setWorkflowValue('conversion', conversion)}+ pageKey="workflow-conversion"+ /></div>)}@@ -1054,12 +998,6 @@ function SendingRateLimitSection(): JSX.Element | null {const { workflow } = useValues(workflowLogic)const rateLimit = workflow.email_sending_rate_limit ?? null- // Mirror the count locally so clearing the field doesn't snap back to the committed value- // mid-edit; reconcile when the stored value changes externally (toggle, another editor).- const [displayCount, setDisplayCount] = useState<number | undefined>(rateLimit?.count)- useEffect(() => {- setDisplayCount(rateLimit?.count)- }, [rateLimit?.count])const hasEmailAction = workflow.actions.some((action) => action.type === 'function_email')// Stay visible while a limit is set even without an email step, so it can still be removed.@@ -1070,72 +1008,10 @@ function SendingRateLimitSection(): JSX.Element | null {return (<><LemonDivider />- <div className="flex flex-col w-full py-2 gap-2">- <span className="flex gap-1 items-center">- <IconClock className="text-lg" />- <span className="text-md font-semibold">Email sending rate limit (optional)</span>- <Tooltip title="Sending a large volume too quickly can hurt deliverability. Emails over the limit are delayed until capacity frees up, not dropped.">- <IconInfo className="text-secondary" />- </Tooltip>- </span>- <p className="mb-0">Spread this workflow's emails out over time instead of sending all at once.</p>- <LemonCheckbox- checked={!!rateLimit}- onChange={(checked) =>- setWorkflowValue('email_sending_rate_limit', checked ? { count: 100, period: 'minute' } : null)- }- label="Limit sending rate"- data-attr="workflow-email-rate-limit-toggle"- />- {rateLimit ? (- <div className="flex items-center gap-2">- <span>Send at most</span>- <LemonInput- type="number"- size="small"- className="w-24"- min={1}- // Mirror the API's accepted range (min_value=1, max_value=1_000_000) so an- // out-of-range entry is clamped here instead of failing the workflow save.- max={1_000_000}- aria-label="Maximum emails per period"- value={displayCount ?? NaN}- onChange={(count) => {- if (count == null || !Number.isFinite(count)) {- setDisplayCount(undefined)- return- }- const next = Math.min(1_000_000, Math.max(1, Math.floor(count)))- setDisplayCount(next)- setWorkflowValue('email_sending_rate_limit', { ...rateLimit, count: next })- }}- onBlur={() =>- displayCount === undefined- ? setDisplayCount(rateLimit.count)- : setWorkflowValue('email_sending_rate_limit', {- ...rateLimit,- count: displayCount,- })- }- data-attr="workflow-email-rate-limit-count"- />- <span>emails per</span>- <LemonSelect- size="small"- aria-label="Rate limit period"- value={rateLimit.period}- options={[- { value: 'minute' as const, label: 'minute' },- { value: 'hour' as const, label: 'hour' },- ]}- onChange={(period) =>- setWorkflowValue('email_sending_rate_limit', { ...rateLimit, period })- }- data-attr="workflow-email-rate-limit-period"- />- </div>- ) : null}- </div>+ <EmailSendingRateLimitPicker+ value={rateLimit}+ onChange={(value) => setWorkflowValue('email_sending_rate_limit', value)}+ /></>)}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/ConversionGoalEditor.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/ConversionGoalEditor.tsxnew file mode 100644index 000000000000..c5c3e4937c8f--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/ConversionGoalEditor.tsx@@ -0,0 +1,108 @@+import { IconInfo } from '@posthog/icons'+import { LemonLabel, Tooltip } from '@posthog/lemon-ui'++import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'++import { HogFlowEventFilters, WORKFLOW_OPERATOR_ALLOWLIST } from '../../filters/HogFlowFilters'+import { HogFlowDuration, MAX_CONVERSION_WINDOW_FOR_DURATION_UNIT } from './HogFlowDuration'++// Structural shape of a workflow conversion goal, compatible with both the frontend HogFlow+// type and the generated HogFlowConversionApi type.+export interface ConversionGoalValue {+ window?: string | null+ window_minutes?: number | null+ filters?: any+ events?: { filters?: any; name?: string }[]+ bytecode?: unknown+}++export interface ConversionGoalEditorProps {+ conversion: ConversionGoalValue | null | undefined+ onChange: (conversion: ConversionGoalValue) => void+ /** Unique key for the filter pickers, so multiple editors on one page don't share state. */+ pageKey: string+}++const DEFAULT_CONVERSION_WINDOW = '90d'+// The worker measures a legacy window_minutes at most this long, so a longer stored value is shown+// as what it actually measures rather than as a number the API would now reject.+const LEGACY_CONVERSION_WINDOW_CEILING_MINUTES = 90 * 24 * 60++function conversionWindowFromMinutes(minutes: number): string {+ const capped = Math.min(minutes, LEGACY_CONVERSION_WINDOW_CEILING_MINUTES)+ if (capped % (24 * 60) === 0) {+ return `${capped / (24 * 60)}d`+ }+ if (capped % 60 === 0) {+ return `${capped / 60}h`+ }+ return `${capped}m`+}++export function ConversionGoalEditor({ conversion, onChange, pageKey }: ConversionGoalEditorProps): JSX.Element {+ const conversionEventFilters = conversion?.events?.[0]?.filters ?? {}+ const legacyWindowMinutes = conversion?.window_minutes+ const conversionWindow =+ conversion?.window ??+ (legacyWindowMinutes ? conversionWindowFromMinutes(legacyWindowMinutes) : DEFAULT_CONVERSION_WINDOW)++ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1 items-start">+ <LemonLabel>Detect conversion from property changes</LemonLabel>+ <PropertyFilters+ buttonText="Add property conversion"+ buttonClassName="grow-0"+ propertyFilters={conversion?.filters ?? []}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.HogQLExpression,+ ]}+ onChange={(filters) => onChange({ ...conversion, filters })}+ pageKey={`${pageKey}-properties`}+ hideBehavioralCohorts+ operatorAllowlist={WORKFLOW_OPERATOR_ALLOWLIST}+ logicalRowDivider+ />+ </div>++ <div className="flex flex-col gap-1 items-start w-full">+ <LemonLabel>Detect conversion from events</LemonLabel>+ <HogFlowEventFilters+ filtersKey={`${pageKey}-events`}+ filters={conversionEventFilters}+ setFilters={(newFilters) =>+ onChange({+ filters: [],+ ...conversion,+ events: newFilters ? [{ filters: newFilters }] : undefined,+ })+ }+ typeKey={`${pageKey}-event`}+ buttonCopy="Add event"+ />+ </div>++ <div className="flex flex-col gap-1 items-start">+ <span className="flex gap-1 items-center">+ <LemonLabel>Conversion window</LemonLabel>+ <Tooltip title="A person who meets the goal after this window is not counted as converted. The window runs from the moment they enter the workflow.">+ <IconInfo className="text-secondary" />+ </Tooltip>+ </span>+ <HogFlowDuration+ value={conversionWindow}+ onChange={(next) => {+ // Dropping window_minutes keeps the two forms from arriving together, which+ // the API rejects. A cleared amount arrives as a bare unit such as "d", so+ // omitting window restores the default instead of failing the save.+ const { window_minutes, window, ...rest } = conversion ?? {}+ onChange(/\d/.test(next) ? { ...rest, window: next } : rest)+ }}+ maxValueForUnit={MAX_CONVERSION_WINDOW_FOR_DURATION_UNIT}+ />+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/EmailSendingRateLimitPicker.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/EmailSendingRateLimitPicker.tsxnew file mode 100644index 000000000000..86cdcf86a57b--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/EmailSendingRateLimitPicker.tsx@@ -0,0 +1,89 @@+import { useEffect, useState } from 'react'++import { IconClock, IconInfo } from '@posthog/icons'+import { LemonCheckbox, LemonInput, LemonSelect, Tooltip } from '@posthog/lemon-ui'++import type { HogFlowEmailSendingRateLimitApi } from 'products/workflows/frontend/generated/api.schemas'++const DEFAULT_RATE_LIMIT: HogFlowEmailSendingRateLimitApi = { count: 100, period: 'minute' }++export interface EmailSendingRateLimitPickerProps {+ value: HogFlowEmailSendingRateLimitApi | null+ onChange: (value: HogFlowEmailSendingRateLimitApi | null) => void+}++/**+ * Editor for a flow's email pacing, shared by the workflow trigger panel and the broadcast wizard.+ * Callers decide when to show it, because the conditions differ: a workflow needs an email step+ * before pacing means anything, while a broadcast always has one.+ */+export function EmailSendingRateLimitPicker({ value, onChange }: EmailSendingRateLimitPickerProps): JSX.Element {+ // Mirror the count locally so clearing the field doesn't snap back to the committed value+ // mid-edit; reconcile when the stored value changes externally (toggle, another editor).+ const [displayCount, setDisplayCount] = useState<number | undefined>(value?.count)+ useEffect(() => {+ setDisplayCount(value?.count)+ }, [value?.count])++ return (+ <div className="flex flex-col w-full py-2 gap-2">+ <span className="flex gap-1 items-center">+ <IconClock className="text-lg" />+ <span className="text-md font-semibold">Email sending rate limit (optional)</span>+ <Tooltip title="Sending a large volume too quickly can hurt deliverability. Emails over the limit are delayed until capacity frees up, not dropped.">+ <IconInfo className="text-secondary" />+ </Tooltip>+ </span>+ <p className="mb-0">Spread the emails out over time instead of sending all at once.</p>+ <LemonCheckbox+ checked={!!value}+ onChange={(checked) => onChange(checked ? DEFAULT_RATE_LIMIT : null)}+ label="Limit sending rate"+ data-attr="workflow-email-rate-limit-toggle"+ />+ {value ? (+ <div className="flex items-center gap-2">+ <span>Send at most</span>+ <LemonInput+ type="number"+ size="small"+ className="w-24"+ min={1}+ // Mirror the API's accepted range (min_value=1, max_value=1_000_000) so an+ // out-of-range entry is clamped here instead of failing the save.+ max={1_000_000}+ aria-label="Maximum emails per period"+ value={displayCount ?? NaN}+ onChange={(count) => {+ if (count == null || !Number.isFinite(count)) {+ setDisplayCount(undefined)+ return+ }+ const next = Math.min(1_000_000, Math.max(1, Math.floor(count)))+ setDisplayCount(next)+ onChange({ ...value, count: next })+ }}+ onBlur={() =>+ displayCount === undefined+ ? setDisplayCount(value.count)+ : onChange({ ...value, count: displayCount })+ }+ data-attr="workflow-email-rate-limit-count"+ />+ <span>emails per</span>+ <LemonSelect+ size="small"+ aria-label="Rate limit period"+ value={value.period}+ options={[+ { value: 'minute' as const, label: 'minute' },+ { value: 'hour' as const, label: 'hour' },+ ]}+ onChange={(period) => onChange({ ...value, period })}+ data-attr="workflow-email-rate-limit-period"+ />+ </div>+ ) : null}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsxindex 6a9bdb95c139..97c9e1ed4e6d 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/RecurringSchedulePicker.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useValues } from 'kea'import { useCallback, useMemo, useState } from 'react'import { IconCalendar } from '@posthog/icons'@@ -15,7 +15,6 @@ import { dayjs } from 'lib/dayjs'import { timeZoneLabel } from 'lib/utils/timezones'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'-import { workflowLogic } from '../../../workflowLogic'import { OccurrencesList } from './OccurrencesList'import {buildSummary,@@ -320,11 +319,28 @@ function NaturalLanguageScheduleInput({)}-export function RecurringSchedulePicker(): JSX.Element {- const { scheduleState, scheduleStartsAt, scheduleTimezone, isScheduleRepeating } = useValues(workflowLogic)- const { setScheduleState, setScheduleStartsAtFromPicker, setScheduleTimezone, setScheduleRepeating } =- useActions(workflowLogic)+export interface RecurringSchedulePickerProps {+ state: ScheduleState+ startsAt: string | null+ timezone: string+ repeating: boolean+ onStateChange: (state: ScheduleState, source?: 'picker' | 'natural_language') => void+ /** Receives the picker's browser-local ISO datetime (or null when cleared). */+ onStartsAtChange: (pickerDate: string | null) => void+ onTimezoneChange: (timezone: string, previousTimezone: string) => void+ onRepeatingChange: (repeating: boolean) => void+}+export function RecurringSchedulePicker({+ state: scheduleState,+ startsAt: scheduleStartsAt,+ timezone: scheduleTimezone,+ repeating: isScheduleRepeating,+ onStateChange: setScheduleState,+ onStartsAtChange: setScheduleStartsAtFromPicker,+ onTimezoneChange: setScheduleTimezone,+ onRepeatingChange: setScheduleRepeating,+}: RecurringSchedulePickerProps): JSX.Element {const previewOccurrences = useMemo(() => {if (!isScheduleRepeating || !scheduleStartsAt) {return []diff --git a/products/workflows/frontend/Workflows/hogflows/types.ts b/products/workflows/frontend/Workflows/hogflows/types.tsindex 37d8c151cb71..53e62ee6ff93 100644--- a/products/workflows/frontend/Workflows/hogflows/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/types.ts@@ -91,6 +91,8 @@ export const HogFlowBatchJobSchema = z.object({// NOTE: these are purposefully exported as interfaces to support kea typegenexport interface HogFlow extends z.infer<typeof HogFlowSchema> {created_by?: UserBasicType | null+ // UX discriminator set by purpose-built surfaces; 'broadcast' rows are managed via the+ // broadcasts UI and hidden from the ordinary workflows list.// Product surface that owns this workflow (e.g. `loops` for Desktop loops). Null when built directly in the workflows UI.origin_product?: HogFlowOriginProductEnumApi | null// Effective access level of the current user for this workflow (resource access control).diff --git a/products/workflows/frontend/Workflows/workflowsLogic.ts b/products/workflows/frontend/Workflows/workflowsLogic.tsindex 69c29c61ad96..a4399ebe1faa 100644--- a/products/workflows/frontend/Workflows/workflowsLogic.ts+++ b/products/workflows/frontend/Workflows/workflowsLogic.ts@@ -4,7 +4,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { LemonDialog, PaginationManual, lemonToast } from '@posthog/lemon-ui'-import api, { CountedPaginatedResponse } from 'lib/api'+import api, { CountedPaginatedResponse, HogFlowListType } from 'lib/api'import { objectsEqual } from 'lib/utils/objects'import { urls } from 'scenes/urls'@@ -19,6 +19,10 @@ const WORKFLOW_STATUS_FILTERS: WorkflowStatusFilter[] = ['all', 'active', 'draftexport type WorkflowTypeFilter = 'all' | 'messaging' | 'automation' | 'loop'+// What this page covers. A surface that grows its own page drops out of this list, rather than every+// other list learning to exclude it.+const WORKFLOWS_PAGE_TYPES: HogFlowListType[] = ['messaging', 'automation', 'loop']+const WORKFLOW_TYPE_FILTERS: WorkflowTypeFilter[] = ['all', 'messaging', 'automation', 'loop']export type WorkflowTriggerTypeFilter = 'all' | (NonNullable<HogFlow['trigger']> extends { type: infer T } ? T : never)@@ -65,7 +69,7 @@ interface WorkflowsListParams {search?: stringstatus?: HogFlow['status']created_by?: string- type?: Exclude<WorkflowTypeFilter, 'all'>+ type?: HogFlowListType[]trigger?: stringlimit: numberoffset: number@@ -417,7 +421,10 @@ export const workflowsLogic = kea<workflowsLogicType>([search: filters.search || undefined,status: filters.status !== 'all' ? filters.status : undefined,created_by: filters.createdBy || undefined,- type: filters.type !== 'all' ? filters.type : undefined,+ // Name the types this page covers rather than the one it hides, so a surface that+ // grows its own page drops out here instead of every list learning to exclude it.+ // Server-side keeps `count` honest, which dropping rows from the page did not.+ type: filters.type !== 'all' ? [filters.type] : WORKFLOWS_PAGE_TYPES,// The API filters triggers by JSON containment, so the type goes over as a JSON object.trigger: filters.triggerType !== 'all' ? JSON.stringify({ type: filters.triggerType }) : undefined,limit: WORKFLOWS_PER_PAGE,diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsxindex bcbce31c2ffb..5da96a4f481a 100644--- a/products/workflows/frontend/WorkflowsScene.tsx+++ b/products/workflows/frontend/WorkflowsScene.tsx@@ -24,6 +24,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'+import { BroadcastsTable } from './Broadcasts/BroadcastsTable'import { MessageChannels } from './Channels/MessageChannels'import { workflowsEmptyState } from './emptyState/workflowsEmptyState'import { optOutCategoriesLogic } from './OptOuts/optOutCategoriesLogic'@@ -36,7 +37,15 @@ import { WorkflowsReputation } from './Workflows/Reputation/WorkflowsReputation'import { WorkflowsTable } from './Workflows/WorkflowsTable'import { workflowsEmailSuspensionLogic } from './workflowsEmailSuspensionLogic'-const WORKFLOW_SCENE_TABS = ['workflows', 'library', 'channels', 'opt-outs', 'suppression', 'reputation'] as const+const WORKFLOW_SCENE_TABS = [+ 'workflows',+ 'broadcasts',+ 'library',+ 'channels',+ 'opt-outs',+ 'suppression',+ 'reputation',+] as constexport type WorkflowsSceneTab = (typeof WORKFLOW_SCENE_TABS)[number]export type WorkflowsSceneProps = {@@ -53,7 +62,7 @@ export interface workflowsSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsSceneLogicActions {setCurrentTab: (tab: WorkflowsSceneTab) => {- tab: 'channels' | 'library' | 'opt-outs' | 'reputation' | 'suppression' | 'workflows'+ tab: 'broadcasts' | 'channels' | 'library' | 'opt-outs' | 'reputation' | 'suppression' | 'workflows'}}@@ -62,7 +71,7 @@ export interface workflowsSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {logicProps: (arg: any) => anybreadcrumbs: (- currentTab: 'channels' | 'library' | 'opt-outs' | 'reputation' | 'suppression' | 'workflows'+ currentTab: 'broadcasts' | 'channels' | 'library' | 'opt-outs' | 'reputation' | 'suppression' | 'workflows') => Breadcrumb[]}}@@ -204,6 +213,12 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {content: <WorkflowsTable />,link: urls.workflows(),},+ {+ label: 'Broadcasts',+ key: 'broadcasts',+ content: <BroadcastsTable />,+ link: urls.workflows('broadcasts'),+ },{label: 'Library',key: 'library',@@ -278,6 +293,21 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {</LemonButton></AccessControlAction>)}+ {currentTab === 'broadcasts' && (+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ data-attr="new-broadcast"+ to={urls.broadcastNew()}+ type="primary"+ size="small"+ >+ New broadcast+ </LemonButton>+ </AccessControlAction>+ )}{currentTab === 'library' && (<AccessControlActionresourceType={AccessControlResourceType.Workflow}diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 2cda1a13e844..b92ae8a6bff7 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -238,11 +238,13 @@ export const HogFlowStateEnumApi = {/*** * `loops` - Loops+ * * `broadcasts` - Broadcasts*/export type HogFlowOriginProductEnumApi = (typeof HogFlowOriginProductEnumApi)[keyof typeof HogFlowOriginProductEnumApi]export const HogFlowOriginProductEnumApi = {Loops: 'loops',+ Broadcasts: 'broadcasts',} as const/**@@ -595,7 +597,8 @@ export interface HogFlowApi {status?: HogFlowStateEnumApi/** Product surface that owns this workflow (e.g. `loops` for Desktop loops). Set only when creating a workflow. Filter the list with `?origin_product=`.*- * * `loops` - Loops */+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts */origin_product?: HogFlowOriginProductEnumApi | nullreadonly created_at: stringreadonly created_by: UserBasicApi@@ -693,7 +696,8 @@ export interface HogFlowUpdateApi {status?: HogFlowStateEnumApi/** Product surface that owns this workflow. This value cannot change after creation.*- * * `loops` - Loops */+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts */readonly origin_product: HogFlowOriginProductEnumApi | nullreadonly created_at: stringreadonly created_by: UserBasicApi@@ -791,7 +795,8 @@ export interface PatchedHogFlowUpdateApi {status?: HogFlowStateEnumApi/** Product surface that owns this workflow. This value cannot change after creation.*- * * `loops` - Loops */+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts */readonly origin_product?: HogFlowOriginProductEnumApi | nullreadonly created_at?: stringreadonly created_by?: UserBasicApi@@ -1808,15 +1813,16 @@ export type HogFlowsListParams = {*/trigger?: string/**- * Filter by workflow type. `loop` returns workflows owned by a Desktop loop; `messaging` returns the remaining workflows with an email, SMS, or push action; `automation` returns the rest.+ * Comma-separated workflow types. `loop` and `broadcast` return the workflows those surfaces own; `messaging` returns the remaining workflows with an email, SMS, or push action, and `automation` the rest.*/- type?: HogFlowsListType+ type?: stringupdated_at?: string}export type HogFlowsListOriginProduct = (typeof HogFlowsListOriginProduct)[keyof typeof HogFlowsListOriginProduct]export const HogFlowsListOriginProduct = {+ Broadcasts: 'broadcasts',Loops: 'loops',} as const@@ -1828,14 +1834,6 @@ export const HogFlowsListStatus = {Draft: 'draft',} as const-export type HogFlowsListType = (typeof HogFlowsListType)[keyof typeof HogFlowsListType]--export const HogFlowsListType = {- Automation: 'automation',- Loop: 'loop',- Messaging: 'messaging',-} as const-export type HogFlowsAssetsRetrieveParams = {/*** Only return assets sent by this email step (action node id) — used to drill in from a step's metric.diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex b184baafa0fd..75642f473da6 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -433,10 +433,13 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod'draft (no execution), active (live), archived (disabled).\n\n\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'),origin_product: zod- .union([zod.enum(['loops']).describe('\* `loops` - Loops'), zod.null()])+ .union([+ zod.enum(['loops', 'broadcasts']).describe('\* `loops` - Loops\n\* `broadcasts` - Broadcasts'),+ zod.null(),+ ]).optional().describe(- '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'+ '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'),trigger_masking: zod.union([@@ -1844,10 +1847,13 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({'draft (no execution), active (live), archived (disabled).\n\n\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'),origin_product: zod- .union([zod.enum(['loops']).describe('\* `loops` - Loops'), zod.null()])+ .union([+ zod.enum(['loops', 'broadcasts']).describe('\* `loops` - Loops\n\* `broadcasts` - Broadcasts'),+ zod.null(),+ ]).optional().describe(- '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'+ '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'),created_at: zod.iso.datetime({ offset: true }),created_by: zod.object({@@ -2622,10 +2628,13 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod'draft (no execution), active (live), archived (disabled).\n\n\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'),origin_product: zod- .union([zod.enum(['loops']).describe('\* `loops` - Loops'), zod.null()])+ .union([+ zod.enum(['loops', 'broadcasts']).describe('\* `loops` - Loops\n\* `broadcasts` - Broadcasts'),+ zod.null(),+ ]).optional().describe(- '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'+ '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'),trigger_masking: zod.union([diff --git a/products/workflows/manifest.tsx b/products/workflows/manifest.tsxindex 3ef66bf221c4..b98c3591042b 100644--- a/products/workflows/manifest.tsx+++ b/products/workflows/manifest.tsx@@ -28,11 +28,22 @@ export const manifest: ProductManifest = {iconType: 'workflows',projectBased: true,},+ Broadcast: {+ import: () => import('./frontend/Broadcasts/BroadcastScene'),+ name: 'Broadcast',+ iconType: 'workflows',+ projectBased: true,+ description: 'Send a one-time or scheduled email to a group of people',+ },},routes: {// URL: [Scene, SceneKey]'/workflows': ['Workflows', 'workflows'],'/workflows/:tab': ['Workflows', 'workflows'],+ // Broadcast routes must precede '/workflows/:id/:tab': kea-router matches routes in+ // declaration order, so the literal 'broadcasts' segment only wins if it's listed first.+ '/workflows/broadcasts/new': ['Broadcast', 'broadcast'],+ '/workflows/broadcasts/:id': ['Broadcast', 'broadcast'],'/workflows/:id/:tab': ['Workflow', 'workflowTab'],'/workflows/library/templates/:id': ['WorkflowsLibraryTemplate', 'workflowsLibraryTemplate'],'/workflows/library/templates/new': ['WorkflowsLibraryTemplate', 'workflowsLibraryTemplate'],@@ -50,6 +61,9 @@ export const manifest: ProductManifest = {workflowsLibraryTemplateNew: (): string => '/workflows/library/templates/new',workflowsLibraryTemplateFromMessage: (id?: string): string =>`/workflows/library/templates/new?messageId=${id}`,+ broadcasts: (): string => '/workflows/broadcasts',+ broadcast: (id: string): string => `/workflows/broadcasts/${id}`,+ broadcastNew: (): string => '/workflows/broadcasts/new',},fileSystemTypes: {workflows: {@@ -71,5 +85,15 @@ export const manifest: ProductManifest = {iconColor: ['var(--color-product-workflows-light)'] as FileSystemIconColor,sceneKey: 'Workflows',},+ {+ path: 'Broadcasts',+ intents: [ProductKey.WORKFLOWS],+ href: urls.broadcasts(),+ type: 'broadcasts',+ category: ProductItemCategory.TOOLS,+ iconType: 'broadcasts',+ iconColor: ['var(--color-product-workflows-light)'] as FileSystemIconColor,+ sceneKey: 'Broadcast',+ },],}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5e1aac663bdd..466ff1a3ee04 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47488,12 +47488,14 @@ export namespace Schemas {/*** * `loops` - Loops+ * * `broadcasts` - Broadcasts*/export type HogFlowOriginProductEnum = typeof HogFlowOriginProductEnum[keyof typeof HogFlowOriginProductEnum];export const HogFlowOriginProductEnum = {Loops: 'loops',+ Broadcasts: 'broadcasts',} as const;export interface HogFlowMasking {@@ -47805,7 +47807,8 @@ export namespace Schemas {status?: HogFlowStateEnum;/** Product surface that owns this workflow (e.g. `loops` for Desktop loops). Set only when creating a workflow. Filter the list with `?origin_product=`.*- * * `loops` - Loops */+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts */origin_product?: HogFlowOriginProductEnum | null;readonly created_at: string;readonly created_by: UserBasic;@@ -48273,7 +48276,8 @@ export namespace Schemas {status?: HogFlowStateEnum;/** Product surface that owns this workflow. This value cannot change after creation.*- * * `loops` - Loops */+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts */readonly origin_product: HogFlowOriginProductEnum | null;readonly created_at: string;readonly created_by: UserBasic;@@ -71114,7 +71118,8 @@ export namespace Schemas {status?: HogFlowStateEnum;/** Product surface that owns this workflow. This value cannot change after creation.*- * * `loops` - Loops */+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts */readonly origin_product?: HogFlowOriginProductEnum | null;readonly created_at?: string;readonly created_by?: UserBasic;@@ -107085,9 +107090,9 @@ export namespace Schemas {*/trigger?: string;/**- * Filter by workflow type. `loop` returns workflows owned by a Desktop loop; `messaging` returns the remaining workflows with an email, SMS, or push action; `automation` returns the rest.+ * Comma-separated workflow types. `loop` and `broadcast` return the workflows those surfaces own; `messaging` returns the remaining workflows with an email, SMS, or push action, and `automation` the rest.*/- type?: HogFlowsListType;+ type?: string;updated_at?: string;};@@ -107095,6 +107100,7 @@ export namespace Schemas {export const HogFlowsListOriginProduct = {+ Broadcasts: 'broadcasts',Loops: 'loops',} as const;@@ -107107,15 +107113,6 @@ export namespace Schemas {Draft: 'draft',} as const;- export type HogFlowsListType = typeof HogFlowsListType[keyof typeof HogFlowsListType];--- export const HogFlowsListType = {- Automation: 'automation',- Loop: 'loop',- Messaging: 'messaging',- } as const;-export type HogFlowsAssetsRetrieveParams = {/*** Only return assets sent by this email step (action node id) — used to drill in from a step's metric.diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex e54503eb2406..5efedf1f22d3 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -23,7 +23,7 @@ export const HogFlowsListQueryParams = () => zod.object({limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),origin_product: zod- .enum(['loops'])+ .enum(['broadcasts', 'loops']).optional().describe('Filter to workflows owned by a product surface, e.g. `loops` for Desktop loops.'),search: zod@@ -43,10 +43,10 @@ export const HogFlowsListQueryParams = () => zod.object({'Filter by trigger config as a JSON object. Returns workflows whose trigger contains the given object, e.g. {\"type\": \"event\"}.'),type: zod- .enum(['automation', 'loop', 'messaging'])+ .string().optional().describe(- 'Filter by workflow type. `loop` returns workflows owned by a Desktop loop; `messaging` returns the remaining workflows with an email, SMS, or push action; `automation` returns the rest.'+ 'Comma-separated workflow types. `loop` and `broadcast` return the workflows those surfaces own; `messaging` returns the remaining workflows with an email, SMS, or push action, and `automation` the rest.'),updated_at: zod.iso.datetime({ offset: true }).optional(),})@@ -92,10 +92,13 @@ export const HogFlowsCreateBody = () => zod'draft (no execution), active (live), archived (disabled).\n\n\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'),origin_product: zod- .union([zod.enum(['loops']).describe('\* `loops` - Loops'), zod.null()])+ .union([+ zod.enum(['loops', 'broadcasts']).describe('\* `loops` - Loops\n\* `broadcasts` - Broadcasts'),+ zod.null(),+ ]).optional().describe(- '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'+ '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'),trigger_masking: zod.union([diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 3b31b7df573f..5d2924f87781 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -254,6 +254,21 @@"params": [],"scope": "project"},+ "broadcast": {+ "template": "/workflows/broadcasts/{id}",+ "params": ["id"],+ "scope": "project"+ },+ "broadcastNew": {+ "template": "/workflows/broadcasts/new",+ "params": [],+ "scope": "project"+ },+ "broadcasts": {+ "template": "/workflows/broadcasts",+ "params": [],+ "scope": "project"+ },"businessKnowledge": {"template": "/business-knowledge","params": [],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex 456f1d0d00e2..28c107f69745 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/broadcasts\n/workflows/broadcasts/new\n/workflows/broadcasts/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.jsonindex 4c23c0528475..7eebd3dba52d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json@@ -543,15 +543,15 @@"origin_product": {"anyOf": [{- "description": "* `loops` - Loops",- "enum": ["loops"],+ "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"+ "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",diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.jsonindex 7f80f146ac74..ba6dbb483743 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json@@ -23,7 +23,7 @@},"origin_product": {"description": "Filter to workflows owned by a product surface, e.g. `loops` for Desktop loops.",- "enum": ["loops"],+ "enum": ["broadcasts", "loops"],"type": "string"},"search": {@@ -40,8 +40,7 @@"type": "string"},"type": {- "description": "Filter by workflow type. `loop` returns workflows owned by a Desktop loop; `messaging` returns the remaining workflows with an email, SMS, or push action; `automation` returns the rest.",- "enum": ["automation", "loop", "messaging"],+ "description": "Comma-separated workflow types. `loop` and `broadcast` return the workflows those surfaces own; `messaging` returns the remaining workflows with an email, SMS, or push action, and `automation` the rest.","type": "string"},"updated_at": {