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): add the builder ui for the opt out of messages step (#121240)

Harley Alexanderf6b4e2b8bf22
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 5cb76c0cf2b2..090265ce8cd7 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -596,6 +596,7 @@ export const FEATURE_FLAGS = {
WORKFLOW_ADD_TO_STATIC_COHORT_ACTION: 'workflow-add-to-static-cohort-action', // owner: #team-workflows
WORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflows
WORKFLOW_CLASSIFY_ACTION: 'workflow-classify-action', // owner: #team-workflows
+ WORKFLOW_OPT_OUT_OF_MESSAGES_ACTION: 'workflow-opt-out-of-messages-action', // owner: #team-workflows
WORKFLOWS_AI_EMAIL_DRAFT: 'workflows-ai-email-draft', // owner: @dmarchuk #team-workflows, AI first draft for cross-product entry points
WORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflows
WORKFLOWS_BROADCAST_RECIPIENT_LISTS: 'workflows-broadcast-recipient-lists', // owner: @mayteio #team-workflows
diff --git a/products/workflows/frontend/OptOuts/optOutCategoriesLogic.ts b/products/workflows/frontend/OptOuts/optOutCategoriesLogic.ts
index 6f1f34825105..9e065131fe6f 100644
--- a/products/workflows/frontend/OptOuts/optOutCategoriesLogic.ts
+++ b/products/workflows/frontend/OptOuts/optOutCategoriesLogic.ts
@@ -65,8 +65,16 @@ export const optOutCategoriesLogic = kea<optOutCategoriesLogicType>([
categories: {
__default: [] as MessageCategory[],
loadCategories: async (): Promise<MessageCategory[]> => {
- const response = await messagingCategoriesList(String(ApiConfig.getCurrentTeamId()))
- return response.results
+ const projectId = String(ApiConfig.getCurrentTeamId())
+ const categories: MessageCategory[] = []
+ // The endpoint pages at 100, so a project with more categories needs every page.
+ for (let page = await messagingCategoriesList(projectId); ; ) {
+ categories.push(...page.results)
+ if (!page.next || page.results.length === 0) {
+ return categories
+ }
+ page = await messagingCategoriesList(projectId, { offset: categories.length })
+ }
},
},
}),
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index a88d6e541977..df51d07a4001 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -246,6 +246,7 @@ export type OutputMappingSuggestion = {
export type CreateActionType = Pick<HogFlowAction, 'type' | 'config' | 'name' | 'description'> & {
branchEdges?: number
output_variable?: HogFlowAction['output_variable']
+ on_error?: HogFlowAction['on_error']
getDefaultInputs?: () => Record<string, CyclotronInputType> | undefined
getOutputMappingSuggestions?: () => Promise<OutputMappingSuggestion[]>
}
@@ -2854,6 +2855,11 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
let config = partialNewAction.config
if (!isHogFlowActionNode) {
+ // pinned: analytics event name
+ posthog.capture('workflow step added', {
+ step_type: partialNewAction.type,
+ template_id: 'template_id' in config ? config.template_id : undefined,
+ })
const dynamicInputs = (partialNewAction as CreateActionType).getDefaultInputs?.()
if (dynamicInputs && 'inputs' in config) {
config = { ...config, inputs: { ...config.inputs, ...dynamicInputs } }
@@ -2913,6 +2919,9 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
...(!isHogFlowActionNode && (partialNewAction as CreateActionType).output_variable
? { output_variable: (partialNewAction as CreateActionType).output_variable }
: {}),
+ ...(!isHogFlowActionNode && (partialNewAction as CreateActionType).on_error
+ ? { on_error: (partialNewAction as CreateActionType).on_error }
+ : {}),
} as HogFlowAction
const step = getHogFlowStep(newAction, values.hogFunctionTemplatesById)
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
index 1ecb5f5b7fc3..49321f3fa801 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
@@ -4,6 +4,7 @@ import { workflowLogic } from '../../workflowLogic'
import { AddToStaticCohortConfiguration } from './components/AddToStaticCohortConfiguration'
import { AiTaskInstructionsCompare } from './components/AiTaskInstructionsCompare'
import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'
+import { OptOutOfMessagesConfiguration } from './components/OptOutOfMessagesConfiguration'
import { StepSchemaErrors } from './components/StepSchemaErrors'
import { StepFunctionNode } from './hogFunctionStepLogic'
@@ -20,6 +21,13 @@ export function StepFunctionConfiguration({ node }: { node: StepFunctionNode }):
<>
<StepSchemaErrors />
{templateId === 'template-posthog-create-task' && <AiTaskInstructionsCompare actionId={node.id} />}
+ {templateId === 'template-posthog-opt-out-of-messages' && (
+ <OptOutOfMessagesConfiguration
+ inputs={inputs}
+ setInputs={(inputs) => partialSetWorkflowActionConfig(node.id, { inputs })}
+ error={validationResult?.errors?.category_id}
+ />
+ )}
{templateId === 'template-posthog-add-to-static-cohort' ? (
<AddToStaticCohortConfiguration
inputs={inputs}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/OptOutOfMessagesConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/OptOutOfMessagesConfiguration.tsx
new file mode 100644
index 000000000000..9b2587502b4d
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/OptOutOfMessagesConfiguration.tsx
@@ -0,0 +1,51 @@
+import { useValues } from 'kea'
+
+import { LemonSelect } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { CyclotronJobInputType } from '~/types'
+
+import { optOutCategoriesLogic } from 'products/workflows/frontend/OptOuts/optOutCategoriesLogic'
+
+// Matches ALL_MARKETING_CATEGORY_ID in the workflows backend, which the messaging product reads as all marketing.
+const ALL_MARKETING_CATEGORY_ID = '$all'
+
+export function OptOutOfMessagesConfiguration({
+ inputs,
+ setInputs,
+ error,
+}: {
+ inputs: Record<string, CyclotronJobInputType>
+ setInputs: (inputs: Record<string, CyclotronJobInputType>) => void
+ error?: string
+}): JSX.Element {
+ const { categories, categoriesLoading } = useValues(optOutCategoriesLogic())
+ const value = typeof inputs.category_id?.value === 'string' ? inputs.category_id.value : null
+
+ // Transactional sends ignore opt-outs, so only marketing categories can take one.
+ const marketingOptions = categories
+ .filter((category) => category.category_type === 'marketing')
+ .map((category) => ({ label: category.name, value: category.id }))
+
+ return (
+ <LemonField.Pure
+ label="Message category"
+ info="Marketing email, SMS and push steps in this category skip anyone who opted out. Transactional messages still send."
+ error={error}
+ >
+ <LemonSelect<string | null>
+ fullWidth
+ value={value}
+ loading={categoriesLoading}
+ onChange={(categoryId) => setInputs({ ...inputs, category_id: { value: categoryId } })}
+ options={[
+ { options: [{ label: 'All marketing messages', value: ALL_MARKETING_CATEGORY_ID }] },
+ ...(marketingOptions.length > 0 ? [{ title: 'Marketing', options: marketingOptions }] : []),
+ ]}
+ placeholder="Choose a message category"
+ data-attr="workflow-opt-out-of-messages-category"
+ />
+ </LemonField.Pure>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
index bb7ad417e16f..73c31452285b 100644
--- a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
+++ b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
@@ -191,6 +191,15 @@ const ADD_TO_STATIC_COHORT_ACTION_NODE: CreateActionType = {
config: { template_id: 'template-posthog-add-to-static-cohort', inputs: {} },
}
+const OPT_OUT_OF_MESSAGES_ACTION_NODE: CreateActionType = {
+ type: 'function',
+ name: 'Opt out of messages',
+ description: 'Opt the recipient out of a message category, or of all marketing messages.',
+ config: { template_id: 'template-posthog-opt-out-of-messages', inputs: {} },
+ // The executor only stops on an explicit abort. A failed opt-out must not continue to a message step.
+ on_error: 'abort',
+}
+
export interface StepCatalogContext {
featureFlags: FeatureFlagsSet
currentTeam: Pick<TeamPublicType | TeamType, 'id' | 'project_id'> | null
@@ -231,6 +240,7 @@ function posthogSteps({ featureFlags }: StepCatalogContext): CreateActionType[]
return [
...POSTHOG_NODES_TO_SHOW,
...(featureFlags[FEATURE_FLAGS.WORKFLOW_ADD_TO_STATIC_COHORT_ACTION] ? [ADD_TO_STATIC_COHORT_ACTION_NODE] : []),
+ ...(featureFlags[FEATURE_FLAGS.WORKFLOW_OPT_OUT_OF_MESSAGES_ACTION] ? [OPT_OUT_OF_MESSAGES_ACTION_NODE] : []),
]
}
diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.md
index 6c981e95c9be..bebada398e82 100644
--- a/products/workflows/skills/building-workflows/references/graph-schema.md
+++ b/products/workflows/skills/building-workflows/references/graph-schema.md
@@ -198,6 +198,34 @@ A `function` node with `template_id: "template-posthog-replay-vision"` scans the
- **Daily caps.** Each workflow can start 100 scans a day, and the project 500, unless the project settings change `replay_vision_scan_rate_limit_per_day` and `replay_vision_scan_team_rate_limit_per_day`. Past a cap the step returns `state: "skipped"` and the workflow continues.
- **Access.** The token needs `session_recording:read` (or `:write`) and `replay_scanner:write`, and the user needs access to recordings and to the saved scanner. Without them, the save fails with a message that names what is missing.
+### Opt out of messages step
+
+A `function` node with `template_id: "template-posthog-opt-out-of-messages"` adds the run's recipient to the opt-out list for one message category, or for all marketing messages. Later email, SMS and push steps for that category skip the recipient. Use it whenever a workflow has to opt someone out. Don't build this with a `webhook` step that calls `messaging_preferences/add_opt_out/` with an API key: that call breaks when the key's owner leaves or the key rotates, and its failures only show as webhook errors.
+
+```json
+{
+ "id": "opt_out_1",
+ "name": "Opt out of product updates",
+ "type": "function",
+ "on_error": "abort",
+ "config": {
+ "template_id": "template-posthog-opt-out-of-messages",
+ "inputs": {
+ "category_id": { "value": "<message category id>" },
+ "identifier": { "value": "{person.properties.email}" }
+ }
+ }
+}
+```
+
+- **`category_id` is a literal, not a template.** Use a marketing message category's `id` (UUID), listed by `GET /api/projects/:project_id/messaging_categories/`, or `"$all"` for all marketing messages. If the user names a category you can't look up, ask them for it rather than guess. Never put `{...}` expressions in it. A save with a category the project doesn't have fails.
+- `identifier` is who to opt out. It defaults to `{person.properties.email}`. Use the same value as the recipient of the email step it should suppress, because opt-outs match the recipient exactly.
+- Only marketing categories work, because transactional messages ignore opt-outs. A save with a transactional category fails.
+- The step fails, and the workflow log says why, when `identifier` is empty or the category was deleted. It never passes silently.
+- Set `"on_error": "abort"` on the node. Without it, a failed opt-out continues to the next step, which may send the message the person asked to stop.
+- Running it again for someone who is already opted out succeeds and logs "Already opted out".
+- The step is behind the `workflow-opt-out-of-messages-action` feature flag. Without the flag, the save fails with "Template not found".
+
## Duration strings (`delay_duration`, `max_wait_duration`)
Must match `^\d*\.?\d+[dhms]$` — a number plus unit `s` | `m` | `h` | `d`. Examples: `30s`, `30m`, `2h`, `1d`, `1.5d` (=36h).