: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): papercut - gate programmatic batch dispatch on an audience confirm token (#73225)
Harley Alexanderc4561f04476c
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 5d99a0353ff8..f7a5231e30f6 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -965,6 +965,36 @@ describe('CDP API', () => {}})+ it('resolves the audience from the posted snapshot, not the live trigger filters', async () => {+ // The snapshot was validated at confirm time - re-reading the trigger here would let an+ // edit racing the dispatch widen the send past what was previewed.+ const snapshotProperties = [{ key: 'email', type: 'person', value: 'a', operator: 'icontains' }]++ const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')+ api['batchResolverProducer'] = {+ createJob: createJobMock,+ countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),+ rescheduleParkedJobs: jest.fn(),+ disconnect: jest.fn().mockResolvedValue(undefined),+ }++ try {+ const res = await supertest(app)+ .post(+ `/api/projects/${batchHogFlow.team_id}/hog_flows/${batchHogFlow.id}/batch_invocations/job-791`+ )+ .send({ filters: { properties: snapshotProperties } })++ expect(res.status).toEqual(200)+ const arg = createJobMock.mock.calls[0][0]+ const state = parseJSON((arg.state as Buffer).toString('utf-8')) as Record<string, any>+ expect(state.filters.properties).toEqual(snapshotProperties)+ expect(state.filters.properties).not.toEqual((batchHogFlow as any).trigger.filters.properties)+ } finally {+ api['batchResolverProducer'] = null+ }+ })+it('sets email dedupe on the resolver state when the flow sends email to the default {{person.properties.email}}', async () => {const emailHogFlow = await insertHogFlow({id: new UUIDT().toString(),diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 3707f3517c74..a32ad8a2f33d 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -983,8 +983,13 @@ export class CdpApi {teamId: team.id,hogFlowId: hogFlow.id,filters: {- properties: hogFlow.trigger.filters.properties || [],- filter_test_accounts: req.body.filters?.filter_test_accounts || false,+ // Prefer the audience snapshot validated at dispatch time - re-reading the live+ // trigger here would let an edit landing after the confirm check widen the send.+ // Fallback covers callers that predate the snapshot.+ properties: req.body.filters?.properties ?? (hogFlow.trigger.filters.properties || []),+ filter_test_accounts:+ req.body.filters?.filter_test_accounts ??+ (hogFlow.trigger.filters.filter_test_accounts || false),},variables: req.body.variables ?? {},groupTypeIndex: typeof req.body.group_type_index === 'number' ? req.body.group_type_index : undefined,diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex 7e96591cd958..9d480df6a22b 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -66,6 +66,7 @@ const HogFlowTriggerSchema = z.discriminatedUnion('type', [type: z.literal('batch'),filters: z.object({properties: z.array(z.any()),+ filter_test_accounts: z.boolean().optional(),}),}),z.object({diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 9f5297d43399..2d9d4ae49ff1 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -207,11 +207,15 @@ def get_hog_function_templates() -> requests.Response:def create_batch_hog_flow_job_invocation(- team_id: int, hog_flow_id: UUIDT, batch_job_id: UUIDT, max_audience_size: int | None = None+ team_id: int,+ hog_flow_id: UUIDT,+ batch_job_id: UUIDT,+ max_audience_size: int | None = None,+ filters: dict | None = None,) -> requests.Response:return internal_requests.post(CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/batch_invocations/{batch_job_id}",- json={"max_audience_size": max_audience_size},+ json={"max_audience_size": max_audience_size, "filters": filters},headers=get_internal_api_headers(),)diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex c863784bab86..a7330ab5f8c2 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -1,6 +1,7 @@import reimport jsonimport uuid as uuid_mod+import hashlibimport dataclassesfrom datetime import timedeltafrom typing import Any, Optional, cast@@ -281,6 +282,12 @@ class BlastRadiusSerializer(serializers.Serializer):allow_null=True,help_text="The dedupe key that was actually applied to 'affected'. 'email' means it counts unique email addresses; null means it counts persons.",)+ confirm_token = serializers.CharField(+ help_text=(+ "Proof this audience was previewed: pass it to the batch dispatch (confirm_token) after "+ "echoing 'affected' to the user. Signs these exact filters; expires in 15 minutes."+ ),+ )class WorkflowGlobalStatsRequestSerializer(serializers.Serializer):@@ -1650,6 +1657,31 @@ def mint_publish_confirm_token(hog_flow: HogFlow) -> str:return TimestampSigner(salt=_PUBLISH_CONFIRM_SALT).sign(_publish_confirm_value(hog_flow))+# Same structural-unskippability pattern for batch dispatch: only the blast-radius preview mints+# this token, and it signs the exact audience filters it sized - so a valid token proves the+# caller saw the recipient count for the filters being dispatched. Short max-age keeps it fresh.+AUDIENCE_CONFIRM_TOKEN_MAX_AGE = timedelta(minutes=15)+_AUDIENCE_CONFIRM_SALT = "hogflow-batch-audience"+++def _audience_confirm_value(+ team_id: int, filters: dict, group_type_index: Optional[int] = None, dedupe_key: Optional[str] = None+) -> str:+ # group_type_index and dedupe_key change the previewed count, so they're part of what the+ # caller confirmed. Dispatch always runs person-scope without a caller-chosen dedupe, so+ # tokens minted under other semantics must not authorize it.+ canonical = json.dumps(filters, sort_keys=True, separators=(",", ":"))+ return f"{team_id}:{group_type_index}:{dedupe_key}:{hashlib.sha256(canonical.encode()).hexdigest()[:32]}"+++def mint_audience_confirm_token(+ team_id: int, filters: dict, group_type_index: Optional[int] = None, dedupe_key: Optional[str] = None+) -> str:+ return TimestampSigner(salt=_AUDIENCE_CONFIRM_SALT).sign(+ _audience_confirm_value(team_id, filters, group_type_index, dedupe_key)+ )++@extend_schema(extensions={"x-product": "workflows"})class HogFlowViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, LogEntryMixin, AppMetricsMixin, viewsets.ModelViewSet@@ -2185,6 +2217,45 @@ class HogFlowViewSet(lambda: reschedule_hog_flow_timing.delay(team_id=team_id, hog_flow_id=hog_flow_id, action_ids=action_ids))+ def _require_audience_confirm_token(self, request: Request, hog_flow: HogFlow) -> None:+ confirm_token = request.data.get("confirm_token")+ if not confirm_token:+ raise exceptions.ValidationError(+ {+ "confirm_token": (+ "Required: preview the audience with workflows-blast-radius first - its response "+ "carries the recipient count to confirm with the user and the confirm_token for "+ "this dispatch."+ )+ }+ )+ try:+ previewed = TimestampSigner(salt=_AUDIENCE_CONFIRM_SALT).unsign(+ confirm_token, max_age=AUDIENCE_CONFIRM_TOKEN_MAX_AGE+ )+ except SignatureExpired:+ raise exceptions.ValidationError(+ {"confirm_token": "Expired - preview the audience again with workflows-blast-radius."}+ )+ except BadSignature:+ raise exceptions.ValidationError(+ {"confirm_token": "Invalid - get one from a workflows-blast-radius preview."}+ )+ # The dispatch always fans out to the flow's stored trigger audience (the resolver reads the+ # trigger's filters; request filters are never forwarded), so the token must sign exactly+ # that - a token minted for other filters, or for an audience edited since the preview,+ # forces a re-preview of the real recipient set.+ filters = (hog_flow.trigger or {}).get("filters") or {}+ if previewed != _audience_confirm_value(self.team_id, filters):+ raise exceptions.ValidationError(+ {+ "confirm_token": (+ "The audience changed since the preview - run workflows-blast-radius again with "+ "the current filters and confirm the new count with the user."+ )+ }+ )+def _get_in_flight_counts(self, hog_flow: HogFlow) -> Optional[dict]:# Best-effort: publish must not fail because the counting service is unreachable — the counts# are advisory ("N runs in flight will follow the new config"), not a gate. by_action and@@ -2508,6 +2579,9 @@ class HogFlowViewSet("total": total,"limit": get_hogflow_batch_trigger_limit(self.team_id),"dedupe_key": applied_dedupe_key,+ "confirm_token": mint_audience_confirm_token(+ self.team_id, filters, group_type_index, applied_dedupe_key+ ),}).data)@@ -2850,13 +2924,22 @@ class HogFlowViewSet(if hog_flow.status != HogFlow.State.ACTIVE:raise exceptions.ValidationError("Workflow must be active to run a batch. Enable it first.")+ # A batch run is an irreversible mass send: programmatic callers must prove they previewed+ # the audience, because only the blast-radius preview mints this token and it signs the+ # exact filters being dispatched. The web builder has its own confirmation UI and stays+ # token-free.+ if get_event_source(request) != EventSource.WEB:+ self._require_audience_confirm_token(request, hog_flow)+serializer = HogFlowBatchJobSerializer(data={**request.data, "hog_flow": hog_flow.id}, context={**self.get_serializer_context()})if not serializer.is_valid():return Response(serializer.errors, status=400)- batch_job = serializer.save()+ # The consumer fans out to the trigger's stored filters, so snapshot those on the job -+ # caller-supplied filters are never what actually runs.+ batch_job = serializer.save(filters=(hog_flow.trigger or {}).get("filters") or {})self._report_workflow_action("hog_flow_batch_job_created", hog_flow, {"batch_job_id": str(batch_job.id)})return Response(HogFlowBatchJobSerializer(batch_job).data)else:@@ -2873,6 +2956,21 @@ class HogFlowViewSet(hog_flow = self.get_object()if request.method == "POST":+ # A schedule is a recurring batch dispatch - without this, a programmatic caller could+ # sidestep the batch_jobs token gate by scheduling the send instead. Same rules: the+ # web builder keeps its own confirm UI and stays token-free.+ if get_event_source(request) != EventSource.WEB:+ # A draft's trigger can still be edited after the audience was sized, so a schedule+ # staged on a draft could fire on a broadened audience once enabled. Same rule the+ # MCP tool enforces, applied at the API boundary.+ if hog_flow.status != HogFlow.State.ACTIVE:+ raise exceptions.ValidationError(+ "Workflow must be active before scheduling - a draft's audience can still be "+ "edited after previewing. Enable it with workflows-enable, then preview and "+ "schedule."+ )+ self._require_audience_confirm_token(request, hog_flow)+serializer = HogFlowScheduleSerializer(data=request.data, context=self.get_serializer_context())serializer.is_valid(raise_exception=True)schedule = serializer.save(team=self.team, hog_flow=hog_flow)diff --git a/products/workflows/backend/api/hog_flow_batch_job.py b/products/workflows/backend/api/hog_flow_batch_job.pyindex 34f10ca25970..2887531ddb28 100644--- a/products/workflows/backend/api/hog_flow_batch_job.py+++ b/products/workflows/backend/api/hog_flow_batch_job.py@@ -25,6 +25,7 @@ class HogFlowBatchJobSerializer(serializers.ModelSerializer):]read_only_fields = ["id",+ "filters","created_at","created_by","updated_at",diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 36e97c9d3f6f..bc3188964c2f 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -21,7 +21,7 @@ from posthog.test.fixtures import create_app_metric2from products.actions.backend.models.action import Actionfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESfrom products.cohorts.backend.models.cohort import Cohort-from products.workflows.backend.api.hog_flow import _should_validate_strictly+from products.workflows.backend.api.hog_flow import _should_validate_strictly, mint_audience_confirm_tokenfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import HogFlowBatchJob@@ -2692,6 +2692,108 @@ class TestHogFlowAPI(APIBaseTest):mock_create_invocation.assert_called_once()assert mock_create_invocation.call_args.kwargs["max_audience_size"] == 50000+ @patch(+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"+ )+ def test_programmatic_batch_dispatch_requires_audience_confirm_token(self, mock_create_invocation):+ # A batch run is an irreversible mass send. Programmatic callers must hold a token only the+ # blast-radius preview mints, signed over the workflow's stored trigger filters - the audience+ # the dispatch actually fans out to. A token minted for other (e.g. narrower) filters is+ # rejected, so an agent can't size one audience and send to another, and an edited trigger+ # invalidates earlier previews. The web builder (session auth) keeps its own confirm UI and+ # stays token-free (covered by the existing batch job tests, which run as WEB).+ flow_id = self._create_active_hog_flow()+ trigger_filters = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}").json()["trigger"][+ "filters"+ ]++ no_token = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",+ {},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert no_token.status_code == 400, no_token.json()+ assert "workflows-blast-radius" in no_token.json()["detail"]+ mock_create_invocation.assert_not_called()++ narrow_preview = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",+ {"filters": {"properties": [{"key": "email", "type": "person", "value": "x", "operator": "icontains"}]}},+ )+ assert narrow_preview.status_code == 200, narrow_preview.json()+ narrow_token = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",+ {"confirm_token": narrow_preview.json()["confirm_token"]},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert narrow_token.status_code == 400, narrow_token.json()+ assert "audience changed" in narrow_token.json()["detail"]+ mock_create_invocation.assert_not_called()++ # A token minted under group or dedupe semantics sized a different count than the+ # person-scope send the dispatch runs - it must not authorize it.+ group_semantics_token = mint_audience_confirm_token(self.team.id, trigger_filters, group_type_index=0)+ group_semantics = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",+ {"confirm_token": group_semantics_token},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert group_semantics.status_code == 400, group_semantics.json()+ assert "audience changed" in group_semantics.json()["detail"]+ mock_create_invocation.assert_not_called()++ preview = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius", {"filters": trigger_filters}+ )+ assert preview.status_code == 200, preview.json()+ token = preview.json()["confirm_token"]++ dispatched = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/batch_jobs",+ # Caller-supplied filters are ignored: the job snapshots the trigger filters it fans out to.+ {"filters": {"properties": []}, "confirm_token": token},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert dispatched.status_code == 200, dispatched.json()+ assert dispatched.json()["filters"] == trigger_filters+ mock_create_invocation.assert_called_once()+ # The resolver dispatches from this snapshot rather than re-reading the live trigger, so a+ # trigger edit racing the dispatch can't widen the confirmed audience.+ assert mock_create_invocation.call_args.kwargs["filters"] == trigger_filters++ # Scheduling is a recurring dispatch - the same gate applies, or the batch_jobs token+ # check could be sidestepped by scheduling the send instead.+ schedule_body = {"rrule": "FREQ=DAILY;INTERVAL=1", "starts_at": "2026-08-01T00:00:00Z"}+ no_token_schedule = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/schedules",+ schedule_body,+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert no_token_schedule.status_code == 400, no_token_schedule.json()+ assert "workflows-blast-radius" in no_token_schedule.json()["detail"]++ scheduled = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/schedules",+ {**schedule_body, "confirm_token": token},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert scheduled.status_code == 201, scheduled.json()++ # A draft's trigger can still be edited after previewing, so a schedule staged on a draft+ # could fire on a broadened audience once enabled - programmatic scheduling requires active.+ draft_flow, _ = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}+ )+ draft_create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", draft_flow)+ assert draft_create.status_code == 201, draft_create.json()+ draft_schedule = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{draft_create.json()['id']}/schedules",+ {**schedule_body, "confirm_token": token},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert draft_schedule.status_code == 400, draft_schedule.json()+ assert "active" in draft_schedule.json()["detail"].lower()+def test_post_hog_flow_batch_jobs_endpoint_rejects_non_active_workflow(self):# A batch run is gated on an enabled workflow — a draft (or archived) one can't start a broadcast.hog_flow, _ = self._create_hog_flow_with_action(diff --git a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.pyindex 31d521d7f6c1..0543e0edbabb 100644--- a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py+++ b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py@@ -53,6 +53,9 @@ def handle_hog_flow_batch_job_created(sender, instance, created, **kwargs):hog_flow_id=instance.hog_flow.id,batch_job_id=instance.id,max_audience_size=get_hogflow_batch_trigger_limit(instance.team.id),+ # The audience snapshot the confirm check validated - the resolver dispatches from+ # this, not the live trigger, so a trigger edit racing the dispatch can't widen it.+ filters=instance.filters,)except Exception as e:logger.exception(diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 06eb65143923..c57ea1c11f35 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -686,7 +686,7 @@ export interface HogFlowBatchJobApi {/** ID of the workflow this batch run belongs to. */hog_flow: string/** Audience snapshot the run fanned out to, taken from the workflow's batch trigger filters. */- filters?: unknown+ readonly filters: unknown/** Variable value overrides applied to this run. */variables?: unknownreadonly created_at: string@@ -1175,6 +1175,8 @@ export interface BlastRadiusApi {** * `email` - email */dedupe_key: DedupeKeyEnumApi | null+ /** Proof this audience was previewed: pass it to the batch dispatch (confirm_token) after echoing 'affected' to the user. Signs these exact filters; expires in 15 minutes. */+ confirm_token: string}export type HogFlowTemplatesListParams = {diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex a23941c931a8..1ecc817d29c2 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -1395,10 +1395,6 @@ export const HogFlowsBatchJobsCreateBody = /* @__PURE__ */ zod.object({'Not currently tracked — stays at its initial value. Use the workflow logs\/metrics endpoints for run outcome.\n\n\* `waiting` - Waiting\n\* `queued` - Queued\n\* `active` - Active\n\* `completed` - Completed\n\* `cancelled` - Cancelled\n\* `failed` - Failed'),hog_flow: zod.uuid().describe('ID of the workflow this batch run belongs to.'),- filters: zod- .unknown()- .optional()- .describe("Audience snapshot the run fanned out to, taken from the workflow's batch trigger filters."),variables: zod.unknown().optional().describe('Variable value overrides applied to this run.'),})diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex a60cd1648c49..c4acbf09a58b 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -11035,7 +11035,7 @@}},"workflows-blast-radius": {- "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes.",+ "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.","category": "Workflows","feature": "workflows","summary": "Size workflow audience",@@ -11315,7 +11315,7 @@}},"workflows-run-batch": {- "description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count from workflows-blast-radius; rejects on drift or over the cap.",+ "description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count AND the confirm_token from that same workflows-blast-radius preview; the API rejects dispatch without the token, on audience drift, over the cap, or after 15 minutes.","category": "Workflows","feature": "workflows","summary": "Run batch workflow",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex d07c95ff6ca6..fbbda7c51a6f 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -719,7 +719,7 @@}},"workflows-blast-radius": {- "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes.",+ "description": "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.","category": "Workflows","feature": "workflows","summary": "Size workflow audience",@@ -733,7 +733,7 @@}},"workflows-run-batch": {- "description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count from workflows-blast-radius; rejects on drift or over the cap.",+ "description": "Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count AND the confirm_token from that same workflows-blast-radius preview; the API rejects dispatch without the token, on audience drift, over the cap, or after 15 minutes.","category": "Workflows","feature": "workflows","summary": "Run batch workflow",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5803cb97c46a..6e565ad5e208 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12572,6 +12572,8 @@ export namespace Schemas {** * `email` - email */dedupe_key: DedupeKeyEnum | null;+ /** Proof this audience was previewed: pass it to the batch dispatch (confirm_token) after echoing 'affected' to the user. Signs these exact filters; expires in 15 minutes. */+ confirm_token: string;}/**@@ -32535,7 +32537,7 @@ export namespace Schemas {/** ID of the workflow this batch run belongs to. */hog_flow: string;/** Audience snapshot the run fanned out to, taken from the workflow's batch trigger filters. */- filters?: unknown;+ readonly filters: unknown;/** Variable value overrides applied to this run. */variables?: unknown;readonly created_at: string;diff --git a/services/mcp/src/tools/workflows/batch.ts b/services/mcp/src/tools/workflows/batch.tsindex 8e9f56738d9b..2d9e9c7c5d7a 100644--- a/services/mcp/src/tools/workflows/batch.ts+++ b/services/mcp/src/tools/workflows/batch.ts@@ -2,7 +2,7 @@ import { z } from 'zod'import type { Context, ToolBase } from '@/tools/types'-type BlastRadius = { affected: number; total: number; limit: number }+type BlastRadius = { affected: number; total: number; limit: number; confirm_token: string }type WorkflowTrigger = { type?: string; filters?: unknown }@@ -75,6 +75,13 @@ const RunBatchSchema = z.object({'confirmed before you called this — never size and fire in one step. Rejected if it no longer ' +'matches the current audience, forcing a re-check.'),+ confirm_token: z+ .string()+ .describe(+ 'The confirm_token from the same workflows-blast-radius preview whose count the user confirmed. ' ++ 'The API rejects dispatch without it, and it goes stale when the audience filters change or ' ++ 'after 15 minutes — re-preview to refresh.'+ ),variables: z.record(z.string(), z.unknown()).optional()@@ -109,7 +116,11 @@ export const workflowsRunBatch = (): ToolBase<typeof RunBatchSchema, unknown> =>return await context.api.request({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.workflow_id))}/batch_jobs/`,- body: { filters, ...(params.variables !== undefined ? { variables: params.variables } : {}) },+ body: {+ filters,+ confirm_token: params.confirm_token,+ ...(params.variables !== undefined ? { variables: params.variables } : {}),+ },})},})@@ -129,6 +140,13 @@ const ScheduleCreateSchema = z.object({'confirmed before scheduling. Each firing re-broadcasts to the audience at that time; rejected if it ' +'no longer matches.'),+ confirm_token: z+ .string()+ .describe(+ 'The confirm_token from the same workflows-blast-radius preview whose count the user confirmed. ' ++ 'The API rejects schedule creation without it, and it goes stale when the audience filters change ' ++ 'or after 15 minutes - re-preview to refresh.'+ ),variables: z.record(z.string(), z.unknown()).optional()@@ -169,6 +187,7 @@ export const workflowsScheduleCreate = (): ToolBase<typeof ScheduleCreateSchema,body: {rrule: params.rrule,starts_at: params.starts_at,+ confirm_token: params.confirm_token,...(params.timezone !== undefined ? { timezone: params.timezone } : {}),...(params.variables !== undefined ? { variables: params.variables } : {}),},diff --git a/services/mcp/tests/tools/workflows.integration.test.ts b/services/mcp/tests/tools/workflows.integration.test.tsindex 43003a656a94..f37ce43a3b6c 100644--- a/services/mcp/tests/tools/workflows.integration.test.ts+++ b/services/mcp/tests/tools/workflows.integration.test.ts@@ -513,10 +513,16 @@ describe('Workflows', { concurrent: false }, () => {// Must be active or the run-batch active-guard fires before the echo-back check.await enableTool.handler(context, { id: created.id })- const { affected } = parseToolResponse(await blastRadiusTool.handler(context, { workflow_id: created.id }))+ const { affected, confirm_token } = parseToolResponse(+ await blastRadiusTool.handler(context, { workflow_id: created.id })+ )await expect(- runBatchTool.handler(context, { workflow_id: created.id, acknowledged_affected_count: affected + 1 })+ runBatchTool.handler(context, {+ workflow_id: created.id,+ acknowledged_affected_count: affected + 1,+ confirm_token,+ })).rejects.toThrow(String(affected))})@@ -526,7 +532,12 @@ describe('Workflows', { concurrent: false }, () => {createdWorkflowIds.push(created.id)await expect(- runBatchTool.handler(context, { workflow_id: created.id, acknowledged_affected_count: 0 })+ // Trigger-type guard fires before the token is ever used, so any value works here.+ runBatchTool.handler(context, {+ workflow_id: created.id,+ acknowledged_affected_count: 0,+ confirm_token: 'unused',+ })).rejects.toThrow(/batch/)})@@ -542,7 +553,9 @@ describe('Workflows', { concurrent: false }, () => {createdWorkflowIds.push(created.id)await enableTool.handler(context, { id: created.id })- const { affected } = parseToolResponse(await blastRadiusTool.handler(context, { workflow_id: created.id }))+ const { affected, confirm_token } = parseToolResponse(+ await blastRadiusTool.handler(context, { workflow_id: created.id })+ )const schedule = parseToolResponse(await scheduleCreateTool.handler(context, {@@ -551,6 +564,7 @@ describe('Workflows', { concurrent: false }, () => {starts_at: new Date().toISOString(),timezone: 'UTC',acknowledged_affected_count: affected,+ confirm_token,}))expect(schedule.id).toBeTypeOf('string')@@ -579,11 +593,13 @@ describe('Workflows', { concurrent: false }, () => {const { affected } = parseToolResponse(await blastRadiusTool.handler(context, { workflow_id: created.id }))await expect(+ // Echo-back guard fires before the token is used, so any value works here.scheduleCreateTool.handler(context, {workflow_id: created.id,rrule: 'FREQ=DAILY;INTERVAL=1',starts_at: new Date().toISOString(),acknowledged_affected_count: affected + 1,+ confirm_token: 'unused',})).rejects.toThrow(String(affected))})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run-batch.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run-batch.jsonindex a1f4ab6eda0b..b9e800d84195 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run-batch.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-run-batch.json@@ -7,6 +7,10 @@"minimum": -9007199254740991,"type": "integer"},+ "confirm_token": {+ "description": "The confirm_token from the same workflows-blast-radius preview whose count the user confirmed. The API rejects dispatch without it, and it goes stale when the audience filters change or after 15 minutes — re-preview to refresh.",+ "type": "string"+ },"variables": {"additionalProperties": {},"description": "Optional {key: value} variable overrides for this run; defaults to the workflow definition.",@@ -20,6 +24,6 @@"type": "string"}},- "required": ["workflow_id", "acknowledged_affected_count"],+ "required": ["workflow_id", "acknowledged_affected_count", "confirm_token"],"type": "object"}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.jsonindex 78c8278f7ad2..97d739b964c3 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-schedule-create.json@@ -7,6 +7,10 @@"minimum": -9007199254740991,"type": "integer"},+ "confirm_token": {+ "description": "The confirm_token from the same workflows-blast-radius preview whose count the user confirmed. The API rejects schedule creation without it, and it goes stale when the audience filters change or after 15 minutes - re-preview to refresh.",+ "type": "string"+ },"rrule": {"description": "iCalendar RRULE (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour.","type": "string"@@ -32,6 +36,6 @@"type": "string"}},- "required": ["workflow_id", "rrule", "starts_at", "acknowledged_affected_count"],+ "required": ["workflow_id", "rrule", "starts_at", "acknowledged_affected_count", "confirm_token"],"type": "object"}diff --git a/services/mcp/tests/unit/workflows-batch-handlers.test.ts b/services/mcp/tests/unit/workflows-batch-handlers.test.tsindex e843149a5ab9..68f7dee153c7 100644--- a/services/mcp/tests/unit/workflows-batch-handlers.test.ts+++ b/services/mcp/tests/unit/workflows-batch-handlers.test.ts@@ -30,7 +30,7 @@ function createMockContext(opts: {return { id: 'wf-1', status: opts.status ?? 'active', trigger: opts.trigger }}if (method === 'POST' && path.endsWith('/user_blast_radius/')) {- return { limit: DEFAULT_LIMIT, ...opts.blastRadius }+ return { limit: DEFAULT_LIMIT, confirm_token: 'tok-preview', ...opts.blastRadius }}if (method === 'POST' && path.endsWith('/batch_jobs/')) {return { id: 'batch-1', status: 'queued' }@@ -78,7 +78,8 @@ describe('workflows batch handlers', () => {path: '/api/projects/1/hog_flows/user_blast_radius/',body: { filters: BATCH_FILTERS },})- expect(result).toEqual({ affected: 42, total: 100, limit: DEFAULT_LIMIT })+ // confirm_token must surface to the agent: it is a required workflows-run-batch input.+ expect(result).toEqual({ affected: 42, total: 100, limit: DEFAULT_LIMIT, confirm_token: 'tok-preview' })})})@@ -92,6 +93,7 @@ describe('workflows batch handlers', () => {const result = await runBatchTool.handler(context, {workflow_id: 'wf-1',acknowledged_affected_count: 10,+ confirm_token: 'tok-123',variables: { plan: 'pro' },})@@ -99,7 +101,7 @@ describe('workflows batch handlers', () => {expect(batchCall).toMatchObject({method: 'POST',path: '/api/projects/1/hog_flows/wf-1/batch_jobs/',- body: { filters: BATCH_FILTERS, variables: { plan: 'pro' } },+ body: { filters: BATCH_FILTERS, confirm_token: 'tok-123', variables: { plan: 'pro' } },})expect(result).toMatchObject({ id: 'batch-1' })})@@ -110,10 +112,14 @@ describe('workflows batch handlers', () => {blastRadius: { affected: 10, total: 100 },})- await runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })+ await runBatchTool.handler(context, {+ workflow_id: 'wf-1',+ acknowledged_affected_count: 10,+ confirm_token: 'tok-123',+ })const batchCall = calls(request).find((c) => c.path.endsWith('/batch_jobs/'))- expect(batchCall!.body).toEqual({ filters: BATCH_FILTERS })+ expect(batchCall!.body).toEqual({ filters: BATCH_FILTERS, confirm_token: 'tok-123' })})it('rejects and does not fire when the acknowledged count is stale, surfacing the fresh count', async () => {@@ -123,7 +129,11 @@ describe('workflows batch handlers', () => {})await expect(- runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })+ runBatchTool.handler(context, {+ workflow_id: 'wf-1',+ acknowledged_affected_count: 10,+ confirm_token: 'tok-123',+ })).rejects.toThrow(/25/)expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)})@@ -138,6 +148,7 @@ describe('workflows batch handlers', () => {runBatchTool.handler(context, {workflow_id: 'wf-1',acknowledged_affected_count: 5001,+ confirm_token: 'tok-123',})).rejects.toThrow(/5000/)expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)@@ -152,6 +163,7 @@ describe('workflows batch handlers', () => {const result = await runBatchTool.handler(context, {workflow_id: 'wf-1',acknowledged_affected_count: 40_000,+ confirm_token: 'tok-123',})expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(true)@@ -165,7 +177,11 @@ describe('workflows batch handlers', () => {})await expect(- runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })+ runBatchTool.handler(context, {+ workflow_id: 'wf-1',+ acknowledged_affected_count: 10,+ confirm_token: 'tok-123',+ })).rejects.toThrow(/batch/)expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)})@@ -178,7 +194,11 @@ describe('workflows batch handlers', () => {})await expect(- runBatchTool.handler(context, { workflow_id: 'wf-1', acknowledged_affected_count: 10 })+ runBatchTool.handler(context, {+ workflow_id: 'wf-1',+ acknowledged_affected_count: 10,+ confirm_token: 'tok-123',+ })).rejects.toThrow(/enable/i)expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)})@@ -197,6 +217,7 @@ describe('workflows batch handlers', () => {starts_at: '2026-06-01T00:00:00Z',timezone: 'UTC',acknowledged_affected_count: 3,+ confirm_token: 'tok-preview',variables: { plan: 'pro' },})@@ -208,6 +229,7 @@ describe('workflows batch handlers', () => {rrule: 'FREQ=DAILY;INTERVAL=1',starts_at: '2026-06-01T00:00:00Z',timezone: 'UTC',+ confirm_token: 'tok-preview',variables: { plan: 'pro' },},})@@ -226,6 +248,7 @@ describe('workflows batch handlers', () => {rrule: 'FREQ=DAILY;INTERVAL=1',starts_at: '2026-06-01T00:00:00Z',acknowledged_affected_count: 3,+ confirm_token: 'unused',})).rejects.toThrow(/50/)expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)@@ -244,6 +267,7 @@ describe('workflows batch handlers', () => {rrule: 'FREQ=DAILY;INTERVAL=1',starts_at: '2026-06-01T00:00:00Z',acknowledged_affected_count: 3,+ confirm_token: 'unused',})).rejects.toThrow(/active/i)expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)@@ -261,6 +285,7 @@ describe('workflows batch handlers', () => {rrule: 'FREQ=DAILY;INTERVAL=1',starts_at: '2026-06-01T00:00:00Z',acknowledged_affected_count: 1,+ confirm_token: 'unused',})).rejects.toThrow(/batch/)expect(calls(request).some((c) => c.path.endsWith('/schedules/'))).toBe(false)