Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): filter broadcasts by the status the list shows (#107592)

Daniel Marchukebe00b8c6fb4
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 4a3a5f663a96..d00b6e3e770c 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -15,7 +15,7 @@ from django.core.cache import cache
from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.db import IntegrityError, models, transaction
-from django.db.models import Q, QuerySet
+from django.db.models import Exists, OuterRef, Q, QuerySet, Subquery
from django.db.models.expressions import RawSQL
from django.http import Http404, HttpResponse
from django.utils import timezone
@@ -4402,6 +4402,55 @@ def annotate_broadcast_shape(queryset: QuerySet) -> QuerySet:
)
+BROADCAST_STATUSES = ("draft", "scheduled", "sending", "sent", "failed", "archived")
+
+
+def filter_by_broadcast_status(queryset: QuerySet, statuses: set[str]) -> QuerySet:
+ # The status a sender sees on a broadcast, derived the way the broadcasts UI derives it: from the
+ # latest run and whether a schedule still has sends to come.
+ latest_run_status = (
+ HogFlowBatchJob.objects.filter(team_id=OuterRef("team_id"), hog_flow_id=OuterRef("pk"))
+ .order_by("-created_at")
+ .values("status")[:1]
+ )
+ queryset = queryset.annotate(
+ _latest_run_status=Subquery(latest_run_status),
+ _has_pending_schedule=Exists(
+ HogFlowSchedule.objects.filter(
+ team_id=OuterRef("team_id"), hog_flow_id=OuterRef("pk"), status=HogFlowSchedule.Status.ACTIVE
+ )
+ ),
+ )
+ live = Q(status=HogFlow.State.ACTIVE)
+ # Only a wizard launch always leaves a schedule or a run. An opened workflow can wait for an API send.
+ nothing_to_come = Q(_latest_run_status__isnull=True, _has_pending_schedule=False)
+ unfinished_launch = nothing_to_come & Q(origin_product="broadcasts")
+ running = [HogFlowBatchJob.State.WAITING, HogFlowBatchJob.State.QUEUED, HogFlowBatchJob.State.ACTIVE]
+ conditions = {
+ "draft": Q(status=HogFlow.State.DRAFT),
+ "archived": Q(status=HogFlow.State.ARCHIVED),
+ "sending": live & Q(_latest_run_status__in=running),
+ "sent": live & Q(_latest_run_status=HogFlowBatchJob.State.COMPLETED, _has_pending_schedule=False),
+ "scheduled": live
+ & (
+ (
+ Q(_has_pending_schedule=True)
+ & (Q(_latest_run_status__isnull=True) | Q(_latest_run_status=HogFlowBatchJob.State.COMPLETED))
+ )
+ | (nothing_to_come & ~Q(origin_product="broadcasts"))
+ ),
+ "failed": live
+ & (
+ Q(_latest_run_status__in=[HogFlowBatchJob.State.FAILED, HogFlowBatchJob.State.CANCELLED])
+ | unfinished_launch
+ ),
+ }
+ combined = Q()
+ for broadcast_status in statuses:
+ combined |= conditions[broadcast_status]
+ return queryset.filter(combined)
+
+
class HogFlowFilterSet(FilterSet):
class Meta:
model = HogFlow
@@ -4551,6 +4600,15 @@ WRITABLE_DRAFT_CONTENT_FIELDS = frozenset(DRAFT_CONTENT_FIELDS) - frozenset(HogF
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.",
),
+ OpenApiParameter(
+ "broadcast_status",
+ OpenApiTypes.STR,
+ description=(
+ "Comma-separated broadcast statuses as the broadcasts UI shows them: draft, scheduled, sending, "
+ "sent, failed, archived. Scheduled, sending, sent and failed come from the latest run and "
+ "whether a schedule still has sends to come."
+ ),
+ ),
]
)
)
@@ -4712,6 +4770,16 @@ class HogFlowViewSet(
)
)
+ broadcast_status = self.request.GET.get("broadcast_status")
+ if broadcast_status:
+ requested_statuses = {value for value in broadcast_status.split(",") if value}
+ unknown_statuses = sorted(requested_statuses - set(BROADCAST_STATUSES))
+ if unknown_statuses or not requested_statuses:
+ raise exceptions.ValidationError(
+ {"broadcast_status": f"Must be one or more of: {', '.join(BROADCAST_STATUSES)}"}
+ )
+ queryset = filter_by_broadcast_status(queryset, requested_statuses)
+
# `?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.py
index cb430e23cc30..b8703ecd4fc5 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -11,6 +11,7 @@ from unittest.mock import ANY, MagicMock, PropertyMock, patch
from django.core.management import call_command
from django.db import connection
from django.test import override_settings
+from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
@@ -500,6 +501,66 @@ class TestHogFlowAPI(APIBaseTest):
assert response.status_code == 200, response.json()
assert {flow["name"] for flow in response.json()["results"]} == {"Broadcast", "Eligible"}
+ @parameterized.expand(
+ [
+ ("draft", {"Draft"}),
+ ("scheduled", {"Scheduled", "Recurring between runs", "Workflow waiting for an API send"}),
+ ("sending", {"Sending"}),
+ ("sent", {"Sent", "Sent after a failed run"}),
+ ("failed", {"Run failed", "Launch never finished"}),
+ ("archived", {"Archived"}),
+ ("sent,failed", {"Sent", "Sent after a failed run", "Run failed", "Launch never finished"}),
+ ]
+ )
+ @patch(
+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"
+ )
+ def test_list_filter_by_broadcast_status(self, statuses, expected_names, _mock_dispatch):
+ def create(
+ name: str,
+ status: str = "active",
+ runs: tuple[str, ...] = (),
+ schedule: str | None = None,
+ origin_product: str | None = "broadcasts",
+ ) -> None:
+ flow = HogFlow.objects.create(
+ team=self.team, name=name, created_by=self.user, origin_product=origin_product, status=status
+ )
+ for minutes_ago, run in enumerate(reversed(runs)):
+ job = HogFlowBatchJob.objects.create(
+ team=self.team, hog_flow=flow, status=run, filters={}, variables={}
+ )
+ HogFlowBatchJob.objects.filter(pk=job.pk).update(
+ created_at=timezone.now() - timedelta(minutes=minutes_ago)
+ )
+ if schedule:
+ HogFlowSchedule.objects.create(
+ team=self.team,
+ hog_flow=flow,
+ rrule="FREQ=WEEKLY;BYDAY=MO",
+ starts_at=datetime(2026, 1, 5, 9, tzinfo=UTC),
+ status=schedule,
+ )
+
+ create("Draft", status="draft")
+ create("Archived", status="archived")
+ create("Scheduled", schedule="active")
+ create("Recurring between runs", runs=("completed",), schedule="active")
+ create("Sending", runs=("active",))
+ create("Sent", runs=("completed",))
+ create("Sent after a failed run", runs=("failed", "completed"))
+ create("Run failed", runs=("failed",), schedule="active")
+ create("Launch never finished")
+ create("Workflow waiting for an API send", origin_product=None)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?broadcast_status={statuses}")
+ assert response.status_code == 200, response.json()
+ assert {flow["name"] for flow in response.json()["results"]} == expected_names
+
+ def test_list_filter_by_broadcast_status_rejects_unknown_values(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?broadcast_status=paused")
+ assert response.status_code == 400
+
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.tsx
index 784586811134..02d781a309f0 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastsTable.tsx
@@ -179,8 +179,11 @@ export function BroadcastsTable(): JSX.Element {
onChange={(status) => setFilters({ status: status as BroadcastsStatusFilter })}
options={[
{ label: 'All', value: 'all' },
- { label: 'Active', value: 'active' },
{ label: 'Draft', value: 'draft' },
+ { label: 'Scheduled', value: 'scheduled' },
+ { label: 'Sending', value: 'sending' },
+ { label: 'Sent', value: 'sent' },
+ { label: 'Failed', value: 'failed' },
{ label: 'Archived', value: 'archived' },
]}
value={filters.status}
diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
index 7457eeea3b89..f79bb8276ed5 100644
--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
@@ -44,8 +44,16 @@ export interface BroadcastRowDetails {
/** Rows per page. Each row loads its latest run and metrics, so a page stays small enough to enrich. */
export const BROADCASTS_PAGE_SIZE = 30
-export type BroadcastsStatusFilter = 'all' | 'draft' | 'active' | 'archived'
-const BROADCASTS_STATUS_FILTERS: BroadcastsStatusFilter[] = ['all', 'draft', 'active', 'archived']
+export type BroadcastsStatusFilter = 'all' | Exclude<BroadcastStatus, 'unknown'>
+const BROADCASTS_STATUS_FILTERS: BroadcastsStatusFilter[] = [
+ 'all',
+ 'draft',
+ 'scheduled',
+ 'sending',
+ 'sent',
+ 'failed',
+ 'archived',
+]
export interface BroadcastsFilters {
search: string
@@ -299,7 +307,7 @@ export const broadcastsLogic = kea<broadcastsLogicType>([
// trigger and a single email), so existing sends show up here too.
broadcast_eligible: true,
search: values.filters.search || undefined,
- status: values.filters.status !== 'all' ? values.filters.status : undefined,
+ broadcast_status: values.filters.status !== 'all' ? values.filters.status : undefined,
created_by: values.filters.createdBy || undefined,
limit: BROADCASTS_PAGE_SIZE,
offset: (values.filters.page - 1) * BROADCASTS_PAGE_SIZE,
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 1036597b7257..1034f9594b16 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1936,6 +1936,10 @@ 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
+ /**
+ * Comma-separated broadcast statuses as the broadcasts UI shows them: draft, scheduled, sending, sent, failed, archived. Scheduled, sending, sent and failed come from the latest run and whether a schedule still has sends to come.
+ */
+ broadcast_status?: string
created_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.ts
index c8f7f3bd7944..054fcf09c3fc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -113564,6 +113564,10 @@ export namespace Schemas {
* 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;
+ /**
+ * Comma-separated broadcast statuses as the broadcasts UI shows them: draft, scheduled, sending, sent, failed, archived. Scheduled, sending, sent and failed come from the latest run and whether a schedule still has sends to come.
+ */
+ broadcast_status?: string;
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.ts
index af14460ede3e..d03190fb3c85 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -23,6 +23,12 @@ export const HogFlowsListQueryParams = () => zod.object({
.describe(
'Pass `true` to return broadcasts plus the ordinary workflows the broadcasts UI can render: a batch trigger and a single email step.'
),
+ broadcast_status: zod
+ .string()
+ .optional()
+ .describe(
+ 'Comma-separated broadcast statuses as the broadcasts UI shows them: draft, scheduled, sending, sent, failed, archived. Scheduled, sending, sent and failed come from the latest run and whether a schedule still has sends to come.'
+ ),
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.ts
index 8d5bddfb9b5e..84f489306a49 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -183,6 +183,7 @@ const workflowsList = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/`,
query: {
broadcast_eligible: params.broadcast_eligible,
+ broadcast_status: params.broadcast_status,
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.json
index 851de03e0f31..1e089f0ac4db 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
@@ -5,6 +5,10 @@
"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"
},
+ "broadcast_status": {
+ "description": "Comma-separated broadcast statuses as the broadcasts UI shows them: draft, scheduled, sending, sent, failed, archived. Scheduled, sending, sent and failed come from the latest run and whether a schedule still has sends to come.",
+ "type": "string"
+ },
"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)))$",