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): expose email sending allowance to mcp agents (#122577)

Luke Belton97e143bfdf28
diff --git a/docs/internal/workflows-email-sending-tiers.md b/docs/internal/workflows-email-sending-tiers.md
index 03ea64a7289d..b511cea77ec8 100644
--- a/docs/internal/workflows-email-sending-tiers.md
+++ b/docs/internal/workflows-email-sending-tiers.md
@@ -14,9 +14,12 @@ Only workflows that send email are subject to the tiers; SMS, push, and webhook
- Staff controls: the team's Django admin page (view state, set/pin a tier, recompute now).
- Audit trail: every tier or pin change writes an `email_sending_tier_changed` row to the team's activity log, with the before and after values and the decision reason (`staff_set` for a tier staff set by hand). Staff rows name the acting user. Sweep and backfill rows carry a trigger with the job type and a per-run id. The rows are staff-only in the activity log (`products/workflows/backend/services/email_sending_tier_audit.py`).
- Customer surface: the Reputation tab's sending allowance card, shown only while the team is enforced.
+- Agent surface: the `workflows-reputation-get` MCP tool returns the same allowance (`sending_allowance` on `GET hog_flows/reputation`), behind the same `workflows-sending-tier-requests` flag.
- Raise requests: the card's "Request a higher allowance" link opens a support ticket whose hidden context starts with `Email sending tier increase request`, followed by the project ID, tier, usage, and 30-day rates.
Search tickets for that line to find these requests.
The `workflows-sending-tier-requests` feature flag gates the link.
+ With the flag on, when the tier sets an email batch's cap, the MCP batch tool's over-cap error points agents at the same link, so they can tell the user how to ask for more.
+ Agents cannot file a request themselves.
The link shows only to accounts that can file a support ticket: a paid or custom plan, an active support trial, or an organization in its first 3 months.
## Configuration
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 6dceecf50a4a..856ede87d870 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -3010,7 +3010,8 @@ class TeamEmailReputationResponseSerializer(serializers.Serializer):
read_only=True,
help_text=(
"The project's sending tier, what it allows, and how much of it has been used; null when the "
- "caller lacks project-wide workflow access."
+ "caller lacks project-wide workflow access. Tiers grow on their own as the project builds a clean "
+ "sending record."
),
)
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 671545388657..fdf9163bec64 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -2208,7 +2208,7 @@ export interface TeamEmailReputationResponseApi {
readonly email_sending_suspended_at: string | null
/** Staff-authored reason shown to customers alongside the suspension notice; empty when not suspended. */
readonly email_sending_suspension_reason: string
- /** The project's sending tier, what it allows, and how much of it has been used; null when the caller lacks project-wide workflow access. */
+ /** The project's sending tier, what it allows, and how much of it has been used; null when the caller lacks project-wide workflow access. Tiers grow on their own as the project builds a clean sending record. */
readonly sending_allowance: EmailSendingAllowanceApi | null
}
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index a6f109b01c61..dba121885021 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -467,6 +467,35 @@ tools:
delays apply to parked runs via a spread sweep: runs already waking soon keep their original time, and wakes
moved earlier by the sweep trickle in from a few minutes after publish rather than all at once - so runs
still parked shortly after publishing are normal, not a sign of a failed publish.
+ workflows-reputation-get:
+ operation: hog_flows_reputation_retrieve
+ enabled: true
+ title: Get email reputation and sending allowance
+ description: >
+ The project's workflow email health over the last 30 days and its sending allowance: tier, hourly and daily
+ email caps, largest batch audience, and usage. Call it before planning a batch send or broadcast, and tell
+ the user when the audience or volume would go over a cap. The caps apply only while
+ sending_allowance.enforced is true; while it is false they are measured but not applied. Pass
+ fields=['sending_allowance'] when that is all you need. Tiers rise on their own with a clean sending record.
+ To get more sooner, the user can request a higher allowance in Workflows > Messaging > Reputation; the link
+ shows while the caps are enforced, to accounts that can open a support ticket. Also returns bounce and
+ complaint rates (project-wide and per workflow, worst first), the AWS SES verdict, per-mailbox-provider
+ health, and any suspension. sending_allowance, aws and reputation are null for a user without project-wide
+ workflow access.
+ feature_flag: workflows-sending-tier-requests
+ response:
+ include:
+ - sending_allowance
+ - reputation
+ - workflows
+ - aws
+ - isps
+ - isp_shared_domains
+ - isp_withheld_domains
+ - email_sending_suspended
+ - email_sending_suspended_at
+ - email_sending_suspension_reason
+ selectable: true
workflows-restore-revision:
operation: hog_flows_revisions_restore_create
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 945f3d35dc19..9f8718ac154b 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -16903,6 +16903,22 @@
"readOnlyHint": false
}
},
+ "workflows-reputation-get": {
+ "description": "The project's workflow email health over the last 30 days and its sending allowance: tier, hourly and daily email caps, largest batch audience, and usage. Call it before planning a batch send or broadcast, and tell the user when the audience or volume would go over a cap. The caps apply only while sending_allowance.enforced is true; while it is false they are measured but not applied. Pass fields=['sending_allowance'] when that is all you need. Tiers rise on their own with a clean sending record. To get more sooner, the user can request a higher allowance in Workflows > Messaging > Reputation; the link shows while the caps are enforced, to accounts that can open a support ticket. Also returns bounce and complaint rates (project-wide and per workflow, worst first), the AWS SES verdict, per-mailbox-provider health, and any suspension. sending_allowance, aws and reputation are null for a user without project-wide workflow access.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get email reputation and sending allowance",
+ "title": "Get email reputation and sending allowance",
+ "required_scopes": ["hog_flow:read"],
+ "api_operations": ["GET /api/projects/{project_id}/hog_flows/reputation/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "workflows-sending-tier-requests"
+ },
"workflows-restore-revision": {
"description": "Roll a workflow back (or forward) by copying a revision's content into its staged draft — the live config is untouched until you publish. Then run the normal cycle: test with workflows-test-run (use_draft=true), preview with workflows-publish, confirm. The preview shows exactly what the rollback does to people in-flight. A 409 means a draft is already open — publish or discard it, or pass overwrite=true to replace it. Note what a rollback can't undo: runs that already moved on while the newer version was live keep their positions.",
"category": "Workflows",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 63f86560ea4e..e5843fda136e 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -17708,6 +17708,22 @@
"readOnlyHint": false
}
},
+ "workflows-reputation-get": {
+ "description": "The project's workflow email health over the last 30 days and its sending allowance: tier, hourly and daily email caps, largest batch audience, and usage. Call it before planning a batch send or broadcast, and tell the user when the audience or volume would go over a cap. The caps apply only while sending_allowance.enforced is true; while it is false they are measured but not applied. Pass fields=['sending_allowance'] when that is all you need. Tiers rise on their own with a clean sending record. To get more sooner, the user can request a higher allowance in Workflows > Messaging > Reputation; the link shows while the caps are enforced, to accounts that can open a support ticket. Also returns bounce and complaint rates (project-wide and per workflow, worst first), the AWS SES verdict, per-mailbox-provider health, and any suspension. sending_allowance, aws and reputation are null for a user without project-wide workflow access.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get email reputation and sending allowance",
+ "title": "Get email reputation and sending allowance",
+ "required_scopes": ["hog_flow:read"],
+ "api_operations": ["GET /api/projects/{project_id}/hog_flows/reputation/"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "workflows-sending-tier-requests"
+ },
"workflows-restore-revision": {
"description": "Roll a workflow back (or forward) by copying a revision's content into its staged draft — the live config is untouched until you publish. Then run the normal cycle: test with workflows-test-run (use_draft=true), preview with workflows-publish, confirm. The preview shows exactly what the rollback does to people in-flight. A 409 means a draft is already open — publish or discard it, or pass overwrite=true to replace it. Note what a rollback can't undo: runs that already moved on while the newer version was live keep their positions.",
"category": "Workflows",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 78a95291c5b9..35ace8d52cb5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -119558,7 +119558,7 @@ export namespace Schemas {
readonly email_sending_suspended_at: string | null;
/** Staff-authored reason shown to customers alongside the suspension notice; empty when not suspended. */
readonly email_sending_suspension_reason: string;
- /** The project's sending tier, what it allows, and how much of it has been used; null when the caller lacks project-wide workflow access. */
+ /** The project's sending tier, what it allows, and how much of it has been used; null when the caller lacks project-wide workflow access. Tiers grow on their own as the project builds a clean sending record. */
readonly sending_allowance: EmailSendingAllowance | null;
}
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index da4c35722ec3..75f8c6a8d5b3 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 29 enabled ops
+ * PostHog API - MCP 30 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1355,6 +1355,29 @@ export const HogFlowsMetricsGlobalRetrieveQueryParams = () => zod.object({
before: zod.string().min(1).optional().describe("End of the window. Same format as 'after'. Defaults to now."),
})
+/**
+ * Bounce/complaint rates for this project's workflow email over the last 30 days, computed on
+ * the fly from app metrics (a project-wide aggregate plus per-workflow rows, worst first,
+ * capped), together with the authoritative AWS SES tenant verdict — sending status and open
+ * reputation findings. Our rates are the per-workflow diagnosis; AWS judges and enforces.
+ */
+export const HogFlowsReputationRetrieveParams = () => zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const HogFlowsReputationRetrieveQueryParams = () => zod.object({
+ search: zod
+ .string()
+ .optional()
+ .describe(
+ 'Case-insensitive workflow name filter. Applied before the worst-50 cap, so it finds workflows the unfiltered response cuts off.'
+ ),
+})
+
/**
* Workflow ideas written by AI from the project's own events. Both calls are free for the customer.
*/
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index fc1f0f2e86fb..0c7525aa56a4 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -633,6 +633,68 @@ const workflowsPublish = (): ToolBase<ReturnType<typeof WorkflowsPublishSchema>,
},
})
+const WorkflowsReputationGetSchema = () => {
+ const HogFlowsReputationRetrieveQueryParams = orvalSchemas.HogFlowsReputationRetrieveQueryParams()
+ return HogFlowsReputationRetrieveQueryParams.extend({
+ fields: z
+ .array(
+ z.enum([
+ 'sending_allowance',
+ 'reputation',
+ 'workflows',
+ 'aws',
+ 'isps',
+ 'isp_shared_domains',
+ 'isp_withheld_domains',
+ 'email_sending_suspended',
+ 'email_sending_suspended_at',
+ 'email_sending_suspension_reason',
+ ])
+ )
+ .min(1)
+ .optional()
+ .describe(
+ 'Optional subset of response fields to return, each a dot-path from the allowlist. Omit to return all fields. Request only the fields your task needs to keep responses small.'
+ ),
+ })
+}
+
+const workflowsReputationGet = (): ToolBase<
+ ReturnType<typeof WorkflowsReputationGetSchema>,
+ Schemas.TeamEmailReputationResponse
+> => ({
+ name: 'workflows-reputation-get',
+ schema: WorkflowsReputationGetSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsReputationGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.TeamEmailReputationResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/reputation/`,
+ query: {
+ search: params.search,
+ },
+ })
+ const filtered = pickResponseFields(
+ result,
+ params.fields?.length
+ ? params.fields
+ : [
+ 'sending_allowance',
+ 'reputation',
+ 'workflows',
+ 'aws',
+ 'isps',
+ 'isp_shared_domains',
+ 'isp_withheld_domains',
+ 'email_sending_suspended',
+ 'email_sending_suspended_at',
+ 'email_sending_suspension_reason',
+ ]
+ ) as typeof result
+ return filtered
+ },
+})
+
const WorkflowsRestoreRevisionSchema = () => {
const HogFlowsRevisionsRestoreCreateBody = orvalSchemas.HogFlowsRevisionsRestoreCreateBody()
const HogFlowsRevisionsRestoreCreateParams = orvalSchemas.HogFlowsRevisionsRestoreCreateParams()
@@ -982,6 +1044,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'workflows-patch-action-email': workflowsPatchActionEmail,
'workflows-patch-graph': workflowsPatchGraph,
'workflows-publish': workflowsPublish,
+ 'workflows-reputation-get': workflowsReputationGet,
'workflows-restore-revision': workflowsRestoreRevision,
'workflows-sending-rules-get': workflowsSendingRulesGet,
'workflows-sending-rules-update': workflowsSendingRulesUpdate,
diff --git a/services/mcp/src/tools/workflows/batch.ts b/services/mcp/src/tools/workflows/batch.ts
index a4a31e1ec48e..c38742536473 100644
--- a/services/mcp/src/tools/workflows/batch.ts
+++ b/services/mcp/src/tools/workflows/batch.ts
@@ -1,5 +1,7 @@
import { z } from 'zod'
+import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'
+import { isFeatureFlagEnabled } from '@/lib/posthog/flags'
import type { Context, ToolBase } from '@/tools/types'
type BlastRadius = { affected: number; total: number; limit: number; confirm_token: string }
@@ -8,6 +10,8 @@ type WorkflowTrigger = { type?: string; filters?: unknown }
type WorkflowAction = { type?: string; config?: { template_id?: string } }
+const SENDING_TIER_REQUESTS_FLAG = 'workflows-sending-tier-requests'
+
async function fetchWorkflow(
context: Context,
projectId: string,
@@ -48,13 +52,30 @@ async function sizeAudience(
})
}
+// Evaluate with the same workspace groups tool discovery uses, so a flag that targets projects or
+// organizations agrees with whether workflows-reputation-get is listed.
+async function sendingTierRequestsEnabled(context: Context): Promise<boolean> {
+ const analyticsContext = await context.stateManager.getAnalyticsContext().catch(() => undefined)
+ return await isFeatureFlagEnabled(
+ SENDING_TIER_REQUESTS_FLAG,
+ await context.getDistinctId(),
+ analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : undefined
+ )
+}
+
/**
* Echo-back guard: the caller must have sized the audience with workflows-blast-radius and surfaced the
* number to the user. We recompute it here and reject on drift or over-cap before any fan-out. The cap is
* the per-team `limit` the blast-radius endpoint returns (HOGFLOW_BATCH_TRIGGER_LIMIT), which the batch
* consumer also enforces — so the run is rejected here rather than silently truncated downstream.
*/
-function assertAcknowledged(affected: number, acknowledged: number, limit: number): void {
+async function assertAcknowledged(
+ context: Context,
+ affected: number,
+ acknowledged: number,
+ limit: number,
+ sendsEmail: boolean
+): Promise<void> {
if (affected !== acknowledged) {
throw new Error(
`Audience size is now ${affected} users (you acknowledged ${acknowledged}). Re-check with ` +
@@ -62,9 +83,17 @@ function assertAcknowledged(affected: number, acknowledged: number, limit: numbe
)
}
if (affected > limit) {
+ // The flag is read only here, so runs within the cap never wait on flag evaluation.
+ const pointAtTier = sendsEmail && (await sendingTierRequestsEnabled(context))
throw new Error(
`Audience of ${affected} users exceeds the ${limit}-user cap for this project. Narrow the ` +
- `workflow's batch trigger filters to reduce the audience, then try again.`
+ `workflow's batch trigger filters to reduce the audience, then try again.` +
+ (pointAtTier
+ ? ` If workflows-reputation-get shows sending_allowance.enforced with this max_batch_audience, ` +
+ `the cap comes from the project's email sending tier, which grows with a clean sending ` +
+ `record. If the user needs a higher cap, tell them they can request one from Workflows > ` +
+ `Messaging > Reputation with "Request a higher allowance".`
+ : '')
)
}
}
@@ -129,7 +158,7 @@ export const workflowsRunBatch = (): ToolBase<typeof RunBatchSchema, unknown> =>
const filters = triggerFilters(trigger)
const { affected, limit } = await sizeAudience(context, projectId, filters, sendsEmail)
- assertAcknowledged(affected, params.acknowledged_affected_count, limit)
+ await assertAcknowledged(context, affected, params.acknowledged_affected_count, limit, sendsEmail)
return await context.api.request({
method: 'POST',
@@ -210,7 +239,7 @@ export const workflowsScheduleCreate = (): ToolBase<typeof ScheduleCreateSchema,
)
}
const { affected, limit } = await sizeAudience(context, projectId, triggerFilters(trigger), sendsEmail)
- assertAcknowledged(affected, params.acknowledged_affected_count, limit)
+ await assertAcknowledged(context, affected, params.acknowledged_affected_count, limit, sendsEmail)
confirmToken = params.confirm_token
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-reputation-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-reputation-get.json
new file mode 100644
index 000000000000..9acc6faad2c0
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-reputation-get.json
@@ -0,0 +1,30 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "fields": {
+ "description": "Optional subset of response fields to return, each a dot-path from the allowlist. Omit to return all fields. Request only the fields your task needs to keep responses small.",
+ "items": {
+ "enum": [
+ "sending_allowance",
+ "reputation",
+ "workflows",
+ "aws",
+ "isps",
+ "isp_shared_domains",
+ "isp_withheld_domains",
+ "email_sending_suspended",
+ "email_sending_suspended_at",
+ "email_sending_suspension_reason"
+ ],
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ },
+ "search": {
+ "description": "Case-insensitive workflow name filter. Applied before the worst-50 cap, so it finds workflows the unfiltered response cuts off.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 0ef8e9e3a530..0d4c976dc00f 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -1103,6 +1103,7 @@ describe('Tool Filtering - Feature Flags', () => {
'cross-project-dashboards',
'warehouse-suggestions',
'scouts-tool-access',
+ 'workflows-sending-tier-requests',
'replay-vision-scanner-dashboard',
'metrics-dashboard-import',
'managed-warehouse-trino-query',
diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
index a72d646986ea..e320bd38f4da 100644
--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts
+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts
@@ -107,6 +107,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {
'subscription-source-summaries': true,
'marketing-analytics-conversion-setup-ai': true,
'workflows-mcp-onboarding': true,
+ 'workflows-sending-tier-requests': true,
'insight-data-checks': true,
'workflows-transactional-email-api': true,
'activity-summary': true,
diff --git a/services/mcp/tests/unit/workflows-batch-handlers.test.ts b/services/mcp/tests/unit/workflows-batch-handlers.test.ts
index 84c3ea3bf905..dd106f7bdddc 100644
--- a/services/mcp/tests/unit/workflows-batch-handlers.test.ts
+++ b/services/mcp/tests/unit/workflows-batch-handlers.test.ts
@@ -1,8 +1,13 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { isFeatureFlagEnabled } from '@/lib/posthog/flags'
import type { Context } from '@/tools/types'
import { workflowsBlastRadius, workflowsRunBatch, workflowsScheduleCreate } from '@/tools/workflows/batch'
+vi.mock('@/lib/posthog/flags', () => ({
+ isFeatureFlagEnabled: vi.fn().mockResolvedValue(false),
+}))
+
// Default per-team audience cap the mocked blast-radius endpoint returns unless a test overrides it.
const DEFAULT_LIMIT = 50_000
@@ -44,7 +49,11 @@ function createMockContext(opts: {
const context = {
api: { request },
- stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },
+ stateManager: {
+ getProjectId: vi.fn().mockResolvedValue('1'),
+ getAnalyticsContext: vi.fn().mockResolvedValue({ organizationId: 'org-1', projectUuid: 'project-uuid-1' }),
+ },
+ getDistinctId: vi.fn().mockResolvedValue('user-1'),
} as unknown as Context
return { context, request }
@@ -61,6 +70,7 @@ const scheduleCreateTool = workflowsScheduleCreate()
describe('workflows batch handlers', () => {
beforeEach(() => {
vi.clearAllMocks()
+ vi.mocked(isFeatureFlagEnabled).mockResolvedValue(false)
})
describe('workflows-blast-radius', () => {
@@ -144,21 +154,45 @@ describe('workflows batch handlers', () => {
expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
})
- it('rejects and does not fire when the audience exceeds the per-team cap', async () => {
- const { context, request } = createMockContext({
- trigger: { type: 'batch', filters: BATCH_FILTERS },
- blastRadius: { affected: 5001, total: 1_000_000, limit: 5000 },
- })
-
- await expect(
- runBatchTool.handler(context, {
- workflow_id: 'wf-1',
- acknowledged_affected_count: 5001,
- confirm_token: 'tok-123',
+ it.each([
+ {
+ name: 'an email workflow with the flag on for its project',
+ actions: [{ type: 'function_email' }],
+ flagOn: true,
+ pointsAtTier: true,
+ },
+ {
+ name: 'an email workflow with the flag off',
+ actions: [{ type: 'function_email' }],
+ flagOn: false,
+ pointsAtTier: false,
+ },
+ { name: 'a non-email workflow', actions: [], flagOn: true, pointsAtTier: false },
+ ])(
+ 'rejects and does not fire when the audience exceeds the per-team cap for $name',
+ async ({ actions, flagOn, pointsAtTier }) => {
+ // The flag targets the workspace, so it reads as on only when the project group is passed.
+ vi.mocked(isFeatureFlagEnabled).mockImplementation(
+ async (_key, _distinctId, groups) => flagOn && groups?.project === 'project-uuid-1'
+ )
+ const { context, request } = createMockContext({
+ trigger: { type: 'batch', filters: BATCH_FILTERS },
+ blastRadius: { affected: 5001, total: 1_000_000, limit: 5000 },
+ actions,
})
- ).rejects.toThrow(/5000/)
- expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
- })
+
+ const error = await runBatchTool
+ .handler(context, {
+ workflow_id: 'wf-1',
+ acknowledged_affected_count: 5001,
+ confirm_token: 'tok-123',
+ })
+ .catch((e: Error) => e)
+ expect(String(error)).toMatch(/5000/)
+ expect(String(error).includes('workflows-reputation-get')).toBe(pointsAtTier)
+ expect(calls(request).some((c) => c.path.endsWith('/batch_jobs/'))).toBe(false)
+ }
+ )
it('fires for a large audience that is within an elevated per-team cap', async () => {
const { context, request } = createMockContext({