: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): list broadcast-shaped workflows on the broadcasts page (#105785)
Daniel Marchukfece620f5b10
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 6de68ac13d7e..2a4e215d7c44 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -3837,6 +3837,50 @@ def workflow_type_q(requested: set[str]) -> Q:return owned | (unowned & (messaging if behavioural == {"messaging"} else ~messaging))+BROADCAST_TRIGGER_TYPE = "batch"+BROADCAST_ALLOWED_ACTION_TYPES = frozenset({"trigger", "function_email", "exit"})+++def _json_path(path: str) -> models.Func:+ # A jsonpath bind parameter. Postgres types a plain parameter as text and the jsonb_path_*+ # functions take jsonpath, so the cast has to be spelled out.+ return models.Func(models.Value(path), template="%(expressions)s::jsonpath", output_field=models.TextField())+++def _jsonb_path_exists(path: str) -> models.Func:+ return models.Func(+ models.F("actions"),+ _json_path(path),+ function="jsonb_path_exists",+ output_field=models.BooleanField(),+ )+++def annotate_broadcast_shape(queryset: QuerySet) -> QuerySet:+ # Whether a workflow has the shape the broadcasts UI renders: a batch trigger and one email step,+ # evaluated in Postgres so a list can filter on the graph without loading every row's actions.+ # The trigger comes from the trigger action, where mask_trigger_config reads it: the `trigger`+ # column is a legacy copy and rows exist where the two disagree. jsonpath runs in lax mode, so a+ # row whose `actions` is not an array yields no matches rather than an error.+ other_step = " && ".join(f'@.type != "{action_type}"' for action_type in sorted(BROADCAST_ALLOWED_ACTION_TYPES))+ return queryset.annotate(+ _has_batch_trigger=_jsonb_path_exists(+ f'$[*] ? (@.type == "trigger" && @.config.type == "{BROADCAST_TRIGGER_TYPE}")'+ ),+ _email_step_count=models.Func(+ models.Func(+ models.F("actions"),+ _json_path('$[*] ? (@.type == "function_email")'),+ function="jsonb_path_query_array",+ output_field=models.JSONField(),+ ),+ function="jsonb_array_length",+ output_field=models.IntegerField(),+ ),+ _has_other_step=_jsonb_path_exists(f"$[*] ? ({other_step})"),+ )++class HogFlowFilterSet(FilterSet):class Meta:model = HogFlow@@ -3981,6 +4025,11 @@ WRITABLE_DRAFT_CONTENT_FIELDS = frozenset(DRAFT_CONTENT_FIELDS) - frozenset(HogFOpenApiTypes.STR,description='Filter by trigger config as a JSON object. Returns workflows whose trigger contains the given object, e.g. {"type": "event"}.',),+ OpenApiParameter(+ "broadcast_eligible",+ OpenApiTypes.BOOL,+ description="Pass `true` to return broadcasts plus the ordinary workflows the broadcasts UI can render: a batch trigger and a single email step.",+ ),]))@@ -4122,6 +4171,17 @@ class HogFlowViewSet(raise exceptions.ValidationError({"type": f"{named}Must be one of: {', '.join(WORKFLOW_TYPES)}"})queryset = queryset.filter(workflow_type_q(requested))+ if self.request.GET.get("broadcast_eligible") == "true":+ queryset = annotate_broadcast_shape(queryset).filter(+ Q(origin_product=HogFlow.OriginProduct.BROADCASTS)+ | Q(+ origin_product__isnull=True,+ _has_batch_trigger=True,+ _email_step_count=1,+ _has_other_step=False,+ )+ )+# `?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")diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex ecc3cba9950f..6234a01be5a4 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -470,6 +470,35 @@ class TestHogFlowAPI(APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?origin_product=spreadsheets")assert response.status_code == 400+ def test_list_filter_by_broadcast_eligible(self):+ email_action = {"id": "email_node", "type": "function_email", "config": {}}+ exit_action = {"id": "exit_node", "type": "exit", "config": {}}++ def trigger_action(trigger_type: str) -> dict:+ return {"id": "trigger_node", "type": "trigger", "config": {"type": trigger_type}}++ def create(name: str, actions: list[dict], **kwargs) -> None:+ HogFlow.objects.create(+ team=self.team, name=name, created_by=self.user, trigger={"type": "batch"}, actions=actions, **kwargs+ )++ broadcast_shape = [trigger_action("batch"), email_action, exit_action]+ create("Broadcast", broadcast_shape, origin_product="broadcasts")+ create("Eligible", broadcast_shape)+ create("Loop with the same shape", broadcast_shape, origin_product="loops")+ create("Two emails", [trigger_action("batch"), email_action, dict(email_action, id="email_2"), exit_action])+ create(+ "Has a delay",+ [trigger_action("batch"), {"id": "wait", "type": "delay", "config": {}}, email_action, exit_action],+ )+ # The `trigger` column is a legacy copy of the trigger action's config and rows exist where the+ # two disagree. The API reads the action, so the filter must read it too.+ create("Event trigger action", [trigger_action("event"), email_action, exit_action])++ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?broadcast_eligible=true")+ assert response.status_code == 200, response.json()+ assert {flow["name"] for flow in response.json()["results"]} == {"Broadcast", "Eligible"}+def test_origin_product_is_set_on_create_and_immutable(self):hog_flow, _ = self._create_hog_flow_with_action({"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}diff --git a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsxindex 2224ef62fe43..820807194be3 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx@@ -1,4 +1,4 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { LemonTag, LemonTagType } from '@posthog/lemon-ui'@@ -11,7 +11,13 @@ import { urls } from 'scenes/urls'import type { HogFlowMinimalApi } from 'products/workflows/frontend/generated/api.schemas'-import { BroadcastStatus, broadcastsLogic, getBroadcastStatus } from './broadcastsLogic'+import {+ BROADCASTS_PAGE_SIZE,+ BroadcastStatus,+ broadcastsLogic,+ getBroadcastStatus,+ isEligibleWorkflow,+} from './broadcastsLogic'const STATUS_CONFIG: Record<BroadcastStatus, { label: string; type: LemonTagType }> = {draft: { label: 'Draft', type: 'default' },@@ -31,18 +37,30 @@ const METRIC_COLUMNS: { title: string; metricName: string }[] = []export function BroadcastsTable(): JSX.Element {- const { broadcasts, broadcastsLoading, hasLoadedBroadcasts, rowDetailsById } = useValues(broadcastsLogic)+ const { broadcasts, broadcastsLoading, hasLoadedBroadcasts, rowDetailsById, page } = useValues(broadcastsLogic)+ const { setPage } = useActions(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}- />+ <div className="flex items-center gap-2">+ <LemonTableLink+ to={isEligibleWorkflow(item) ? urls.workflow(item.id, 'workflow') : urls.broadcast(item.id)}+ title={item.name || 'Untitled broadcast'}+ description={item.description}+ />+ {isEligibleWorkflow(item) && (+ <LemonTag+ type="muted"+ data-attr="broadcast-workflow-tag"+ title="A workflow with a batch trigger and one email. It opens in the workflow editor."+ >+ Workflow+ </LemonTag>+ )}+ </div>),},{@@ -92,6 +110,14 @@ export function BroadcastsTable(): JSX.Element {return (<LemonTabledataSource={broadcasts.results}+ pagination={{+ controlled: true,+ pageSize: BROADCASTS_PAGE_SIZE,+ currentPage: page,+ entryCount: broadcasts.count,+ onForward: broadcasts.next ? () => setPage(page + 1) : undefined,+ onBackward: page > 1 ? () => setPage(page - 1) : undefined,+ }}loading={broadcastsLoading}rowKey="id"columns={columns}diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.tsindex 7ab8d7625a60..2860771fb9e7 100644--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts@@ -24,6 +24,14 @@ export interface BroadcastRowDetails {totals: Record<string, number>}+/** An ordinary workflow shaped like a broadcast. It opens in the workflow editor, since the wizard would rewrite its graph. */+/** Rows per page. Each row loads its latest run and metrics, so a page stays small enough to enrich. */+export const BROADCASTS_PAGE_SIZE = 100++export function isEligibleWorkflow(flow: Pick<HogFlowMinimalApi, 'origin_product'>): boolean {+ return flow.origin_product !== 'broadcasts'+}+export function getBroadcastStatus(broadcast: HogFlowMinimalApi,details: BroadcastRowDetails | undefined@@ -74,6 +82,7 @@ export interface broadcastsLogicValues {broadcasts: PaginatedHogFlowMinimalListApibroadcastsLoading: booleanhasLoadedBroadcasts: boolean+ page: numberrowDetailsById: Record<string, BroadcastRowDetails>}@@ -100,6 +109,9 @@ export interface broadcastsLogicActions {value: true}}+ setPage: (page: number) => {+ page: number+ }setRowDetails: (id: string,details: BroadcastRowDetails@@ -118,6 +130,7 @@ export const broadcastsLogic = kea<broadcastsLogicType>([})),actions({loadBroadcasts: true,+ setPage: (page: number) => ({ page }),setRowDetails: (id: string, details: BroadcastRowDetails) => ({ id, details }),}),loaders(({ values }) => ({@@ -129,8 +142,11 @@ export const broadcastsLogic = kea<broadcastsLogicType>([return values.broadcasts}return await hogFlowsList(String(values.currentProjectId), {- type: 'broadcast',- limit: 100,+ // Broadcasts plus the ordinary workflows already shaped like one (a batch+ // trigger and a single email), so existing sends show up here too.+ broadcast_eligible: true,+ limit: BROADCASTS_PAGE_SIZE,+ offset: (values.page - 1) * BROADCASTS_PAGE_SIZE,})},},@@ -149,6 +165,12 @@ export const broadcastsLogic = kea<broadcastsLogicType>([loadBroadcastsSuccess: () => true,},],+ page: [+ 1,+ {+ setPage: (_, { page }) => page,+ },+ ],}),listeners(({ actions, values }) => ({loadBroadcastsSuccess: ({ broadcasts }) => {@@ -178,6 +200,9 @@ export const broadcastsLogic = kea<broadcastsLogicType>([})()}},+ setPage: () => {+ actions.loadBroadcasts()+ },loadBroadcastsFailure: () => {lemonToast.error("Couldn't load broadcasts. Refresh the page to try again.")},diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 385088027ee6..a4bf5cc3a238 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -1781,6 +1781,10 @@ export type HogFlowTemplatesLogsRetrieveParams = {}export type HogFlowsListParams = {+ /**+ * Pass `true` to return broadcasts plus the ordinary workflows the broadcasts UI can render: a batch trigger and a single email step.+ */+ broadcast_eligible?: booleancreated_at?: string/*** Filter to workflows created by the user with this uuid.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3b5214e50277..bbdc95c83055 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -110169,6 +110169,10 @@ export namespace Schemas {};export type HogFlowsListParams = {+ /**+ * Pass `true` to return broadcasts plus the ordinary workflows the broadcasts UI can render: a batch trigger and a single email step.+ */+ broadcast_eligible?: boolean;created_at?: string;/*** Filter to workflows created by the user with this uuid.diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex 7b64f2328f48..e03a95b34651 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -17,6 +17,12 @@ export const HogFlowsListParams = () => zod.object({})export const HogFlowsListQueryParams = () => zod.object({+ broadcast_eligible: zod+ .boolean()+ .optional()+ .describe(+ 'Pass `true` to return broadcasts plus the ordinary workflows the broadcasts UI can render: a batch trigger and a single email step.'+ ),created_at: zod.iso.datetime({ offset: true }).optional(),created_by: zod.string().optional().describe('Filter to workflows created by the user with this uuid.'),id: zod.string().optional(),diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex a54deace5225..8d5bddfb9b5e 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -182,6 +182,7 @@ const workflowsList = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/`,query: {+ broadcast_eligible: params.broadcast_eligible,created_at: params.created_at,created_by: params.created_by,id: params.id,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.jsonindex ba6dbb483743..851de03e0f31 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json@@ -1,6 +1,10 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "broadcast_eligible": {+ "description": "Pass `true` to return broadcasts plus the ordinary workflows the broadcasts UI can render: a batch trigger and a single email step.",+ "type": "boolean"+ },"created_at": {"format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",