: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): email tracking consent and per-send tracking gate for CNIL compliance (#73506)
Harley Alexandera22595d75d61
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 14caaa09a019..8841446e04e5 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -982,9 +982,29 @@ export interface TeamCustomerAnalyticsConfigApi {account_group_type_index?: number | null}+/**+ * * `off` - Off+ * * `opt_out` - Opt Out+ * * `opt_in` - Opt In+ */+export type EmailTrackingConsentModeEnumApi =+ (typeof EmailTrackingConsentModeEnumApi)[keyof typeof EmailTrackingConsentModeEnumApi]++export const EmailTrackingConsentModeEnumApi = {+ Off: 'off',+ OptOut: 'opt_out',+ OptIn: 'opt_in',+} as const+export interface TeamWorkflowsConfigApi {/** When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_*) alongside the existing workflow metrics. */capture_workflows_engagement_events?: boolean+ /** Recipient-consent enforcement for open/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.+ *+ * * `off` - Off+ * * `opt_out` - Opt Out+ * * `opt_in` - Opt In */+ email_tracking_consent_mode?: EmailTrackingConsentModeEnumApi}/**diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 4b4561282eee..5b5cb2fe36b7 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -721,6 +721,13 @@ export const OrganizationsProjectsCreateBody = /* @__PURE__ */ zod.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -1321,6 +1328,13 @@ export const OrganizationsProjectsUpdateBody = /* @__PURE__ */ zod.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -1923,6 +1937,13 @@ export const OrganizationsProjectsPartialUpdateBody = /* @__PURE__ */ zod.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -2539,6 +2560,13 @@ export const OrganizationsProjectsAddProductIntentPartialUpdateBody = /* @__PURE.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -3147,6 +3175,13 @@ export const OrganizationsProjectsChangeOrganizationCreateBody = /* @__PURE__ */.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -3775,6 +3810,13 @@ export const OrganizationsProjectsCompleteProductOnboardingPartialUpdateBody = /.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -4391,6 +4433,13 @@ export const OrganizationsProjectsDefaultEvaluationContextsCreateBody = /* @__PU.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -5007,6 +5056,13 @@ export const OrganizationsProjectsDefaultReleaseConditionsUpdateBody = /* @__PUR.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -5631,6 +5687,13 @@ export const OrganizationsProjectsDeleteSecretTokenBackupPartialUpdateBody = /*.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -6247,6 +6310,13 @@ export const OrganizationsProjectsExperimentsConfigPartialUpdateBody = /* @__PUR.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -6875,6 +6945,13 @@ export const OrganizationsProjectsGenerateConversationsPublicTokenCreateBody = /.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -7482,6 +7559,13 @@ export const OrganizationsProjectsLogsConfigPartialUpdateBody = /* @__PURE__ */.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -8086,6 +8170,13 @@ export const OrganizationsProjectsResetTokenPartialUpdateBody = /* @__PURE__ */.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zod@@ -8702,6 +8793,13 @@ export const OrganizationsProjectsRotateSecretTokenPartialUpdateBody = /* @__PUR.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zoddiff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 86b4e656fe2e..e036629f8485 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -59,6 +59,7 @@ import { LogsAlertingSection } from 'products/logs/frontend/components/LogsAlertimport { LogsMetricRulesSection } from 'products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection'import { LogsSamplingSection } from 'products/logs/frontend/components/LogsSampling/LogsSamplingSection'import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'+import { WorkflowsEmailTrackingConsentSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEmailTrackingConsentSettings'import { WorkflowsEngagementEventsSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEngagementEventsSettings'import { IntegrationsList } from '../../lib/integrations/IntegrationsList'@@ -1356,7 +1357,7 @@ export const SETTINGS_MAP: SettingSection[] = [id: 'workflows-engagement-events',title: 'Engagement events',description:- 'When enabled, email engagement activity (sent, delivered, opened, link clicked, bounced, blocked, failed) is captured as standard PostHog events alongside the existing workflow metrics. This lets you build insights, funnels, and dashboards from workflows data. These events count toward your event usage and are billed like any other event.',+ 'When enabled, email engagement activity (sent, delivered, opened, link clicked, bounced, blocked, failed) is captured as standard PostHog events alongside the existing workflow metrics. This lets you build insights, funnels, and dashboards from workflows data. These events count toward your event usage and are billed like any other event. This setting only controls event capture: it does not disable open and click tracking itself. To stop tracking opens and clicks for an email, turn off "Track opens and link clicks" on that email step.',docsUrl: 'https://posthog.com/docs/workflows/engagement-events',component: <WorkflowsEngagementEventsSettings />,keywords: [@@ -1375,6 +1376,25 @@ export const SETTINGS_MAP: SettingSection[] = ['failed',],},+ {+ id: 'workflows-email-tracking-consent',+ title: 'Email tracking consent',+ description:+ 'Controls whether open and click tracking on marketing workflow emails requires recipient consent. Untracked emails contain no tracking pixel and no rewritten links, and never record opens or clicks. Transactional emails are exempt. Delivery, bounce, and unsubscribe events are always recorded.',+ component: <WorkflowsEmailTrackingConsentSettings />,+ keywords: [+ 'workflows',+ 'email',+ 'tracking',+ 'consent',+ 'pixel',+ 'cnil',+ 'gdpr',+ 'privacy',+ 'opt-in',+ 'opt-out',+ ],+ },],},{diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 963836a7a499..93e6ea830267 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -258,6 +258,7 @@ export type SettingId =| 'web-analytics-pre-aggregated-tables'| 'web-revenue-events'| 'web-vitals-autocapture'+ | 'workflows-email-tracking-consent'| 'workflows-engagement-events'type FeatureFlagKey = keyof typeof FEATURE_FLAGSdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex a0ba967111c4..6508cec7625a 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -897,6 +897,8 @@ export interface TeamType extends TeamBasicType {export interface WorkflowsConfig {capture_workflows_engagement_events: boolean+ // Optional so cached team objects from before this field shipped still typecheck.+ email_tracking_consent_mode?: 'off' | 'opt_out' | 'opt_in'}export interface ProductIntentType {diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 238b04a6dd77..8594b75117d1 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -146,6 +146,8 @@ export type CdpCoreServicesConfig = Pick<| 'SES_SECRET_ACCESS_KEY'| 'SES_REGION'| 'SES_ENDPOINT'+ | 'SES_TRACKED_CONFIGURATION_SET'+ | 'SES_UNTRACKED_CONFIGURATION_SET'| 'EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD'| 'CDP_GOOGLE_ADWORDS_DEVELOPER_TOKEN'| 'CDP_FETCH_RETRIES'@@ -401,12 +403,15 @@ export function createCdpCoreServices(const emailSuppressionService = new EmailSuppressionService(deps.postgres, {transientBounceThreshold: config.EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD,})+ const recipientsManager = new RecipientsManagerService(deps.postgres)const emailService = new EmailService({sesAccessKeyId: config.SES_ACCESS_KEY_ID,sesSecretAccessKey: config.SES_SECRET_ACCESS_KEY,sesRegion: config.SES_REGION,sesEndpoint: config.SES_ENDPOINT,+ sesTrackedConfigurationSet: config.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: config.SES_UNTRACKED_CONFIGURATION_SET,},deps.integrationManager,teamWorkflowsConfigService,@@ -414,6 +419,7 @@ export function createCdpCoreServices(config.SITE_URL,trackingCodeSigner,emailSuppressionService,+ recipientsManager,messageAssetsService)const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)@@ -453,7 +459,6 @@ export function createCdpCoreServices(hogExecutor)- const recipientsManager = new RecipientsManagerService(deps.postgres)const recipientPreferencesService = new RecipientPreferencesService(recipientsManager, emailSuppressionService)// MX verdicts live on the dedicated SES Valkey (same instance as the SES rate// limiter, separate pool). The pool is created by the server only on podsdiff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 913b503df0bd..30716427c6a1 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -132,6 +132,11 @@ export type CdpConfig = ClickhouseConfig & {SES_ACCESS_KEY_ID: stringSES_SECRET_ACCESS_KEY: stringSES_REGION: string+ // Configuration set with ESP-level open/click tracking enabled, used for sends with engagement tracking on.+ SES_TRACKED_CONFIGURATION_SET: string+ // Configuration set without open/click tracking (same delivery/bounce/complaint event destination).+ // Empty means not provisioned: tracking-off sends fall back to the tracked set with a warning.+ SES_UNTRACKED_CONFIGURATION_SET: string// Comma-separated allowlist of SNS Topic ARNs the SES webhook accepts events from. Empty string// means no restriction (dev/test); production should set this to the workflow SES topic ARN(s).SES_ALLOWED_SNS_TOPIC_ARNS: string@@ -310,6 +315,8 @@ export function getDefaultCdpConfig(): CdpConfig {SES_ACCESS_KEY_ID: isTestEnv() || isDevEnv() ? 'test' : '',SES_SECRET_ACCESS_KEY: isTestEnv() || isDevEnv() ? 'test' : '',SES_REGION: isTestEnv() || isDevEnv() ? 'us-east-1' : '',+ SES_TRACKED_CONFIGURATION_SET: 'posthog-messaging',+ SES_UNTRACKED_CONFIGURATION_SET: '',SES_ALLOWED_SNS_TOPIC_ARNS: '',EMAIL_SUPPRESSION_TRANSIENT_BOUNCE_THRESHOLD: 5,diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.tsindex 33a9f44f9405..bd5167f375ad 100644--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts@@ -20,6 +20,7 @@ import { HogInputsService } from '../services/hog-inputs.service'import { LegacyPluginExecutorService } from '../services/legacy-plugin-executor.service'import { HogFunctionManagerService } from '../services/managers/hog-function-manager.service'import { IntegrationManagerService } from '../services/managers/integration-manager.service'+import { RecipientsManagerService } from '../services/managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../services/managers/team-workflows-config.service'import { EmailSuppressionService } from '../services/messaging/email-suppression.service'import { EmailService } from '../services/messaging/email.service'@@ -519,13 +520,16 @@ export function createHogTransformerService(sesSecretAccessKey: config.SES_SECRET_ACCESS_KEY,sesRegion: config.SES_REGION,sesEndpoint: config.SES_ENDPOINT,+ sesTrackedConfigurationSet: config.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: config.SES_UNTRACKED_CONFIGURATION_SET,},deps.integrationManager,teamWorkflowsConfigService,config.ENCRYPTION_SALT_KEYS,config.SITE_URL,trackingCodeSigner,- emailSuppressionService+ emailSuppressionService,+ new RecipientsManagerService(deps.postgres))const pushNotificationService = new PushNotificationService(deps.integrationManager,diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex 9d480df6a22b..33f8cd6f3572 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -177,6 +177,9 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [config: z.object({message_category_id: z.string().optional(),message_category_type: z.enum(['marketing', 'transactional']).optional(),+ // When false, no open pixel is injected, links are not rewritten, and the send uses the+ // untracked SES configuration set. Absent/true means tracked (existing behavior).+ tracking_enabled: z.boolean().optional(),template_uuid: z.string().optional(), // May be used later to specify a specific template versiontemplate_id: z.literal('template-email'),inputs: z.record(z.string(), CyclotronInputSchema),diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex ed1259f186d3..29703fca6fc7 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -8,6 +8,7 @@ import { logger } from '~/common/utils/logger'import { HogExecutorService } from '../../../src/cdp/services/hog-executor.service'import { HogInputsService } from '../../../src/cdp/services/hog-inputs.service'+import { RecipientsManagerService } from '../../../src/cdp/services/managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../../../src/cdp/services/managers/team-workflows-config.service'import { EmailService } from '../../../src/cdp/services/messaging/email.service'import {@@ -68,13 +69,16 @@ describe('Hog Executor', () => {sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,sesRegion: hub.SES_REGION,sesEndpoint: hub.SES_ENDPOINT,+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),- new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),+ new RecipientsManagerService(hub.postgres))const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)executor = new HogExecutorService(diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex e882acad8a5c..fa0756f7bb20 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -15,6 +15,7 @@ import { CyclotronJobInvocationHogFlow, DBHogFunctionTemplate } from '../../../timport { HogExecutorService } from '../../hog-executor.service'import { HogInputsService } from '../../hog-inputs.service'import { HogFunctionTemplateManagerService } from '../../managers/hog-function-template-manager.service'+import { RecipientsManagerService } from '../../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../../managers/team-workflows-config.service'import { EmailSuppressionService, emailSuppressionConfigFromEnv } from '../../messaging/email-suppression.service'import { EmailValidationService } from '../../messaging/email-validation.service'@@ -57,13 +58,16 @@ describe('HogFunctionHandler', () => {sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,sesRegion: hub.SES_REGION,sesEndpoint: hub.SES_ENDPOINT,+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),- new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),+ new RecipientsManagerService(hub.postgres))mockHogFunctionExecutor = new HogExecutorService({diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 43c471ed7840..57ccb3c027fd 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -76,13 +76,16 @@ describe('Hogflow Executor', () => {sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,sesRegion: hub.SES_REGION,sesEndpoint: hub.SES_ENDPOINT,+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),- emailSuppressionService+ emailSuppressionService,+ new RecipientsManagerService(hub.postgres))const recipientTokensService = new RecipientTokensService(hub.ENCRYPTION_SALT_KEYS, hub.SITE_URL)const hogExecutor = new HogExecutorService(diff --git a/nodejs/src/cdp/services/managers/recipients-manager.service.ts b/nodejs/src/cdp/services/managers/recipients-manager.service.tsindex 3b45b864c5f1..1b3520babcf7 100644--- a/nodejs/src/cdp/services/managers/recipients-manager.service.ts+++ b/nodejs/src/cdp/services/managers/recipients-manager.service.ts@@ -16,6 +16,11 @@ const fromKey = (key: string): RecipientGetArgs => {export type PreferenceStatus = 'OPTED_IN' | 'OPTED_OUT' | 'NO_PREFERENCE'+// Reserved key in the preferences JSON for open/click tracking consent, alongside the '$all'+// unsubscribe key. Mirrors EMAIL_TRACKING_PREFERENCE_ID in+// products/messaging/backend/models/message_preferences.py.+export const EMAIL_TRACKING_PREFERENCE_ID = '$email_tracking'+// Type for the query result from the databasetype MessageRecipientPreferenceRow = {id: string@@ -71,6 +76,12 @@ export class RecipientsManagerService {return recipient.preferences['$all'] ?? 'NO_PREFERENCE'}+ // Consent for open/click tracking, distinct from messaging opt-out: a recipient can keep+ // receiving emails while refusing to have their opens/clicks tracked.+ public getEmailTrackingPreference(recipient: RecipientManagerRecipient): PreferenceStatus {+ return recipient.preferences[EMAIL_TRACKING_PREFERENCE_ID] ?? 'NO_PREFERENCE'+ }+/*** Opt out one or more recipients from all marketing messaging by upserting the $all preference to OPTED_OUT.*/diff --git a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts b/nodejs/src/cdp/services/managers/team-workflows-config.service.tsindex 063ea8bc35a4..687d951a113d 100644--- a/nodejs/src/cdp/services/managers/team-workflows-config.service.ts+++ b/nodejs/src/cdp/services/managers/team-workflows-config.service.ts@@ -1,12 +1,17 @@import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { LazyLoader } from '~/common/utils/lazy-loader'+// Mirrors EmailTrackingConsentMode in products/workflows/backend/models/team_workflows_config.py+export type EmailTrackingConsentMode = 'off' | 'opt_out' | 'opt_in'+export type TeamWorkflowsConfig = {capture_workflows_engagement_events: boolean+ email_tracking_consent_mode: EmailTrackingConsentMode}const DEFAULT_CONFIG: TeamWorkflowsConfig = {capture_workflows_engagement_events: false,+ email_tracking_consent_mode: 'off',}/**@@ -35,10 +40,19 @@ export class TeamWorkflowsConfigService {return config.capture_workflows_engagement_events}+ public async getEmailTrackingConsentMode(teamId: number): Promise<EmailTrackingConsentMode> {+ const config = await this.get(teamId)+ return config.email_tracking_consent_mode+ }+private async fetchConfigs(teamIds: string[]): Promise<Record<string, TeamWorkflowsConfig>> {- const result = await this.postgres.query<{ team_id: number; capture_workflows_engagement_events: boolean }>(+ const result = await this.postgres.query<{+ team_id: number+ capture_workflows_engagement_events: boolean+ email_tracking_consent_mode: EmailTrackingConsentMode+ }>(PostgresUse.COMMON_READ,- `SELECT team_id, capture_workflows_engagement_events+ `SELECT team_id, capture_workflows_engagement_events, email_tracking_consent_modeFROM workflows_teamworkflowsconfigWHERE team_id = ANY($1)`,[teamIds.map(Number)],@@ -52,6 +66,7 @@ export class TeamWorkflowsConfigService {for (const row of result.rows) {configs[String(row.team_id)] = {capture_workflows_engagement_events: row.capture_workflows_engagement_events,+ email_tracking_consent_mode: row.email_tracking_consent_mode ?? 'off',}}return configsdiff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex d6c93349be15..c00e32cd1787 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -10,6 +10,7 @@ import { waitForExpect } from '~/tests/helpers/expectations'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { Hub, Team } from '../../../types'+import { RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-suppression.service'import { EmailService, parseAddressList, sanitizeEmailSubject } from './email.service'@@ -90,13 +91,16 @@ describe('EmailService', () => {sesSecretAccessKey: hub.SES_SECRET_ACCESS_KEY,sesRegion: hub.SES_REGION,sesEndpoint: hub.SES_ENDPOINT,+ sesTrackedConfigurationSet: hub.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: hub.SES_UNTRACKED_CONFIGURATION_SET,},hub.integrationManager,new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),- new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),+ new RecipientsManagerService(hub.postgres))mockFetch.mockClear()})@@ -106,13 +110,21 @@ describe('EmailService', () => {describe('when SES is not configured', () => {it('should not crash on construction and should fail explicitly on send', async () => {const serviceWithoutSES = new EmailService(- { sesAccessKeyId: '', sesSecretAccessKey: '', sesRegion: '', sesEndpoint: '' },+ {+ sesAccessKeyId: '',+ sesSecretAccessKey: '',+ sesRegion: '',+ sesEndpoint: '',+ sesTrackedConfigurationSet: 'posthog-messaging',+ sesUntrackedConfigurationSet: '',+ },hub.integrationManager,new TeamWorkflowsConfigService(hub.postgres),hub.ENCRYPTION_SALT_KEYS,hub.SITE_URL,new EmailTrackingCodeSigner(hub.ENCRYPTION_SALT_KEYS, hub.CDP_EMAIL_TRACKING_URL),- new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv())+ new EmailSuppressionService(hub.postgres, emailSuppressionConfigFromEnv()),+ new RecipientsManagerService(hub.postgres))expect(serviceWithoutSES.sesV2Client).toBeNull()@@ -673,6 +685,176 @@ describe('EmailService', () => {expect(sentCommand.input.EmailTags[0].Value).not.toEqual(trackingHeader.Value)})+ describe('per-send tracking gate (tracking_enabled)', () => {+ // Would be tracked if the gate regressed: has an anchor to rewrite and a </body> to pixel.+ const trackableHtml = '<body>Hi! <a href="https://example.com">Click me</a></body>'++ beforeEach(() => {+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ invocation.queueParameters = createEmailParams({ from: { integrationId: 1 }, html: trackableHtml })+ invocation.hogFunction.metadata = { tracking_enabled: false }+ })++ it('skips pixel and link rewriting and uses the untracked configuration set when tracking is off', async () => {+ service['sesConfig'].sesUntrackedConfigurationSet = 'posthog-messaging-untracked'+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }+ expect(sentCommand.input.ConfigurationSetName).toEqual('posthog-messaging-untracked')+ expect(sentCommand.input.Content.Simple.Body.Html.Data).toEqual(trackableHtml)+ // Delivery/bounce attribution must survive tracking-off: the untracked configuration+ // set still emits delivery events, and the webhook needs this header to attribute them.+ const headerNames = sentCommand.input.Content.Simple.Headers.map((h: { Name: string }) => h.Name)+ expect(headerNames).toContain('X-PostHog-Tracking-Code')+ })++ it('falls back to the tracked configuration set when no untracked set is configured, still untracked HTML', async () => {+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }+ expect(sentCommand.input.ConfigurationSetName).toEqual('posthog-messaging')+ expect(sentCommand.input.Content.Simple.Body.Html.Data).toEqual(trackableHtml)+ })++ it('records an email_untracked app metric for untracked sends but not for test sends', async () => {+ const normal = await service.executeSendEmail(invocation)+ expect(normal.metrics.map((m) => m.metric_name)).toEqual(+ expect.arrayContaining(['email_sent', 'email_untracked'])+ )++ const testSend = await service.executeSendEmail(invocation, true)+ expect(testSend.metrics).toEqual([])+ })+ })++ describe('recipient tracking consent', () => {+ const trackableHtml = '<body>Hi! <a href="https://example.com">Click me</a></body>'++ const setConsentState = (+ mode: 'off' | 'opt_out' | 'opt_in',+ storedConsent: 'OPTED_IN' | 'OPTED_OUT' | null+ ): void => {+ jest.spyOn(+ (service as any).teamWorkflowsConfigService,+ 'getEmailTrackingConsentMode'+ ).mockResolvedValue(mode)+ jest.spyOn((service as any).recipientsManager, 'get').mockResolvedValue(+ storedConsent+ ? {+ id: 'pref-1',+ team_id: team.id,+ identifier: '[email protected]',+ preferences: { $email_tracking: storedConsent },+ created_at: '',+ updated_at: '',+ }+ : null+ )+ }++ beforeEach(() => {+ sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })+ invocation.queueParameters = createEmailParams({ from: { integrationId: 1 }, html: trackableHtml })+ invocation.hogFunction.metadata = { message_category_type: 'marketing' }+ })++ it.each([+ ['off mode ignores consent entirely', 'off', null, true],+ ['opt_out mode tracks recipients with no stored preference', 'opt_out', null, true],+ ['opt_out mode does not track recipients who opted out', 'opt_out', 'OPTED_OUT', false],+ ['opt_in mode does not track recipients with no stored preference', 'opt_in', null, false],+ ['opt_in mode tracks recipients who opted in', 'opt_in', 'OPTED_IN', true],+ ] as [string, 'off' | 'opt_out' | 'opt_in', 'OPTED_IN' | 'OPTED_OUT' | null, boolean][])(+ '%s',+ async (_name, mode, storedConsent, expectTracked) => {+ setConsentState(mode, storedConsent)+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html+ .Data+ if (expectTracked) {+ expect(sentHtml).toContain('/redirect?ph_id=')+ } else {+ expect(sentHtml).toEqual(trackableHtml)+ }+ }+ )++ it('transactional emails are exempt from consent enforcement', async () => {+ invocation.hogFunction.metadata = { message_category_type: 'transactional' }+ setConsentState('opt_in', null)+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html.Data+ expect(sentHtml).toContain('/redirect?ph_id=')+ })++ it('the step-level toggle wins over consent: tracking_enabled false is untracked even for opted-in recipients', async () => {+ invocation.hogFunction.metadata = { message_category_type: 'marketing', tracking_enabled: false }+ setConsentState('opt_in', 'OPTED_IN')+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html.Data+ expect(sentHtml).toEqual(trackableHtml)+ })++ it('sends untracked when the consent lookup fails (fail closed)', async () => {+ jest.spyOn(+ (service as any).teamWorkflowsConfigService,+ 'getEmailTrackingConsentMode'+ ).mockResolvedValue('opt_out')+ jest.spyOn((service as any).recipientsManager, 'get').mockRejectedValue(new Error('db down'))+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html.Data+ expect(sentHtml).toEqual(trackableHtml)+ })++ it('sends untracked when the consent-mode lookup fails (fail closed)', async () => {+ jest.spyOn(+ (service as any).teamWorkflowsConfigService,+ 'getEmailTrackingConsentMode'+ ).mockRejectedValue(new Error('db down'))+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html.Data+ expect(sentHtml).toEqual(trackableHtml)+ })++ it('honors a cc recipient tracking opt-out for the whole send', async () => {+ invocation.queueParameters = createEmailParams({+ from: { integrationId: 1 },+ html: trackableHtml,+ cc: '[email protected]',+ })+ jest.spyOn(+ (service as any).teamWorkflowsConfigService,+ 'getEmailTrackingConsentMode'+ ).mockResolvedValue('opt_out')+ jest.spyOn((service as any).recipientsManager, 'get').mockImplementation(+ (options: unknown): Promise<any> => {+ const { identifier } = options as { identifier: string }+ return Promise.resolve(+ identifier === '[email protected]'+ ? {+ id: 'pref-1',+ team_id: team.id,+ identifier,+ preferences: { $email_tracking: 'OPTED_OUT' },+ created_at: '',+ updated_at: '',+ }+ : null+ )+ }+ )+ const result = await service.executeSendEmail(invocation)+ expect(result.error).toBeUndefined()+ const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html.Data+ expect(sentHtml).toEqual(trackableHtml)+ })+ })+it('should report a missing message id', async () => {sendEmailSpy.mockResolvedValue({})const result = await service.executeSendEmail(invocation)diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex dc3fcfb513bd..0dc2a64a43d6 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -12,9 +12,10 @@ import {} from '~/cdp/types'import { createAddLogFunction, logEntry } from '~/cdp/utils'import { createInvocationResult } from '~/cdp/utils/invocation-utils'+import { logger } from '~/common/utils/logger'import { IntegrationManagerService } from '../managers/integration-manager.service'-import { RecipientManagerRecipient } from '../managers/recipients-manager.service'+import { RecipientManagerRecipient, RecipientsManagerService } from '../managers/recipients-manager.service'import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { EmailSuppressionService } from './email-suppression.service'import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-tracking.service'@@ -80,6 +81,11 @@ export interface EmailServiceConfig {sesSecretAccessKey: stringsesRegion: stringsesEndpoint: string+ // Configuration set with ESP-level open/click tracking enabled.+ sesTrackedConfigurationSet: string+ // Configuration set without open/click tracking. Empty means not provisioned: tracking-off+ // sends fall back to the tracked set (with a warning) rather than failing.+ sesUntrackedConfigurationSet: string}/**@@ -125,6 +131,7 @@ export class EmailService {sesV2Client: SESv2Client | nullprivate recipientTokensService: RecipientTokensService+ private untrackedConfigSetWarningLogged = falseconstructor(private sesConfig: EmailServiceConfig,@@ -134,6 +141,7 @@ export class EmailService {siteUrl: string,private trackingCodeSigner: EmailTrackingCodeSigner,private emailSuppressionService: EmailSuppressionService,+ private recipientsManager: RecipientsManagerService,private messageAssetsService?: MessageAssetsService) {this.sesV2Client = this.sesConfig.sesRegion@@ -170,6 +178,7 @@ export class EmailService {let success: boolean = falselet throttled: boolean = falselet assetRow: MessageAssetRow | null = null+ let trackingEnabled = truetry {// Wrong-team references deliberately read as not-found so an ID's existence on another team can't be probed@@ -207,12 +216,16 @@ export class EmailService {return result}+ // Like suppression, the tracking decision lives at this choke point so every send path+ // (workflow action or email destination hog function) resolves it the same way.+ trackingEnabled = await this.resolveTrackingEnabled(result.invocation, params)+switch (integration.config.provider ?? 'ses') {case 'maildev':- await this.sendEmailWithMaildev(result, params, from, isTest)+ await this.sendEmailWithMaildev(result, params, from, trackingEnabled, isTest)breakcase 'ses':- await this.sendEmailWithSES(result, params, from, isTest)+ await this.sendEmailWithSES(result, params, from, trackingEnabled, isTest)breakcase 'unsupported':@@ -270,6 +283,19 @@ export class EmailService {count: 1,})+ // Untracked sends can never produce opens/clicks, so record them separately: open/click+ // rates are computed against (delivered - untracked) to avoid deflation.+ if (success && !trackingEnabled) {+ result.metrics.push({+ team_id: invocation.teamId,+ app_source_id: invocation.parentRunId ?? invocation.functionId,+ instance_id: invocation.state.actionId || invocation.id,+ metric_kind: 'email',+ metric_name: 'email_untracked',+ count: 1,+ })+ }+if (success && assetRow) {result.emailAssets.push(assetRow)}@@ -330,6 +356,86 @@ export class EmailService {return `Skipping send: recipient(s) on the suppression list — ${suppressed.join(', ')}`}+ // Per-send tracking decision, combining two independent controls:+ // 1. Message-level: `tracking_enabled` on the email step's config (via `hogFunction.metadata`,+ // same as `message_category_type`). False is a hard off regardless of consent. Absent means+ // tracked, so email destination hog functions (which have no such config) keep tracking.+ // 2. Recipient-level consent (marketing only; transactional exempt per CNIL): the team's+ // consent mode combined with the recipient's stored $email_tracking preference.+ // Consent lookup failures resolve to untracked (fail closed): tracking without verifiable+ // consent is a compliance risk, while an untracked send only costs metrics.+ private async resolveTrackingEnabled(+ invocation: CyclotronJobInvocationHogFunction,+ params: CyclotronInvocationQueueParametersEmailType+ ): Promise<boolean> {+ if (invocation.hogFunction?.metadata?.tracking_enabled === false) {+ return false+ }+ if (invocation.hogFunction?.metadata?.message_category_type === 'transactional') {+ return true+ }++ try {+ const consentMode = await this.teamWorkflowsConfigService.getEmailTrackingConsentMode(invocation.teamId)+ if (consentMode === 'off') {+ return true+ }++ // The pixel and rewritten links are whole-message artifacts delivered to every list,+ // so consent must hold for every recipient (same reasoning as the suppression check).+ const recipients: string[] = []+ if (params.to?.email && params.to.email.trim()) {+ recipients.push(params.to.email.trim())+ }+ recipients.push(...extractEmailsFromAddressList(params.cc))+ recipients.push(...extractEmailsFromAddressList(params.bcc))++ const consents = await Promise.all(+ recipients.map(async (email) => {+ const recipient = await this.recipientsManager.get({+ teamId: invocation.teamId,+ identifier: email,+ })+ return recipient ? this.recipientsManager.getEmailTrackingPreference(recipient) : 'NO_PREFERENCE'+ })+ )+ return consents.every((consent) =>+ consentMode === 'opt_in' ? consent === 'OPTED_IN' : consent !== 'OPTED_OUT'+ )+ } catch (error) {+ logger.warn('Email tracking consent lookup failed - sending untracked', {+ teamId: invocation.teamId,+ functionId: invocation.functionId,+ error: error instanceof Error ? error.message : String(error),+ })+ return false+ }+ }++ // The tracked and untracked configuration sets share the same delivery/bounce/complaint event+ // destination (suppression and the Metrics tab depend on those events); they differ only in+ // ESP-level open/click tracking.+ private resolveConfigurationSetName(+ trackingEnabled: boolean,+ invocation: CyclotronJobInvocationHogFunction+ ): string {+ if (trackingEnabled) {+ return this.sesConfig.sesTrackedConfigurationSet+ }+ if (this.sesConfig.sesUntrackedConfigurationSet) {+ return this.sesConfig.sesUntrackedConfigurationSet+ }+ // The missing set is static per process - one warning is signal, one per send is noise.+ if (!this.untrackedConfigSetWarningLogged) {+ this.untrackedConfigSetWarningLogged = true+ logger.warn(+ 'Email tracking disabled for send but no untracked SES configuration set is configured - falling back to the tracked set, ESP-level open/click tracking may still apply',+ { teamId: invocation.teamId, functionId: invocation.functionId }+ )+ }+ return this.sesConfig.sesTrackedConfigurationSet+ }+private resolveFromSender(integration: IntegrationType): { email: string; name: string } {if (!integration.config.verified) {throw new Error('The selected email integration domain is not verified')@@ -347,6 +453,7 @@ export class EmailService {result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,params: CyclotronInvocationQueueParametersEmailType,from: { email: string; name: string },+ trackingEnabled: boolean,isTest = false): Promise<void> {// This can timeout but there is no native timeout so we do our own one@@ -356,7 +463,11 @@ export class EmailService {subject: sanitizeEmailSubject(params.subject),text: params.text,...(params.html- ? { html: addTrackingToEmail(params.html, result.invocation, this.trackingCodeSigner, isTest) }+ ? {+ html: trackingEnabled+ ? addTrackingToEmail(params.html, result.invocation, this.trackingCodeSigner, isTest)+ : params.html,+ }: {}),}@@ -383,6 +494,7 @@ export class EmailService {result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>,params: CyclotronInvocationQueueParametersEmailType,from: { email: string; name: string },+ trackingEnabled: boolean,isTest = false): Promise<void> {if (!this.sesV2Client) {@@ -399,7 +511,9 @@ export class EmailService {? {Html: {Data: maybeAddPreheaderToEmail(- addTrackingToEmail(params.html, result.invocation, this.trackingCodeSigner, isTest),+ trackingEnabled+ ? addTrackingToEmail(params.html, result.invocation, this.trackingCodeSigner, isTest)+ : params.html,params.preheader),Charset: 'UTF-8',@@ -427,7 +541,7 @@ export class EmailService {},},},- ConfigurationSetName: 'posthog-messaging',+ ConfigurationSetName: this.resolveConfigurationSetName(trackingEnabled, result.invocation),// Short unsigned tag kept as a backwards-compat carrier for in-flight messages and// environments where the configuration set isn't yet emitting original headers.EmailTags: [{ Name: 'ph_id', Value: shortTrackingCode }],diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex bdfabeb674eb..bc9f3ea255a1 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -202,12 +202,15 @@ export class TemplateTester {sesSecretAccessKey: config.SES_SECRET_ACCESS_KEY,sesRegion: config.SES_REGION,sesEndpoint: config.SES_ENDPOINT,+ sesTrackedConfigurationSet: config.SES_TRACKED_CONFIGURATION_SET,+ sesUntrackedConfigurationSet: config.SES_UNTRACKED_CONFIGURATION_SET,},undefined as any,undefined as any,config.ENCRYPTION_SALT_KEYS,config.SITE_URL,new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL),+ undefined as any,undefined as any)return new HogExecutorService(diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 6c4bea0f0c49..a2fcef7b0d1b 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -244,6 +244,7 @@ export type MinimalAppMetric = {| 'email_blocked'| 'email_spam'| 'email_unsubscribed'+ | 'email_untracked'| 'push_sent'| 'push_failed'| 'push_skipped'diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 6916d23962b8..00e757585dbc 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -98,7 +98,7 @@ from products.feature_flags.backend.models.evaluation_context import ()from products.logs.backend.models import TeamLogsConfigfrom products.signals.backend.models import SignalSourceConfig-from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode, TeamWorkflowsConfigtracer = trace.get_tracer(__name__)@@ -613,10 +613,21 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr"alongside the existing workflow metrics."),)+ email_tracking_consent_mode = serializers.ChoiceField(+ choices=EmailTrackingConsentMode.choices,+ required=False,+ help_text=(+ "Recipient-consent enforcement for open/click tracking on marketing workflow emails. "+ "'off': no enforcement, tracking follows each email step's own setting. "+ "'opt_out': track by default but not recipients who have opted out. "+ "'opt_in': only track recipients who have explicitly opted in. "+ "Transactional emails are exempt from consent enforcement."+ ),+ )class Meta:model = TeamWorkflowsConfig- fields = ["capture_workflows_engagement_events"]+ fields = ["capture_workflows_engagement_events", "email_tracking_consent_mode"]class TeamCustomerAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):diff --git a/posthog/templates/message_preferences/preferences.html b/posthog/templates/message_preferences/preferences.htmlindex 7966b8f06ae6..9e29562818de 100644--- a/posthog/templates/message_preferences/preferences.html+++ b/posthog/templates/message_preferences/preferences.html@@ -50,6 +50,38 @@</div>{% endfor %}+ {% if email_tracking_consent_enabled %}+ <hr class="border-gray-200" />+ <div class="bg-gray-50 rounded-lg p-6 transition-all duration-200 hover:shadow-md">+ <div class="flex items-start justify-between gap-4">+ <div class="flex-1 min-w-0">+ <h3 class="text-lg font-medium text-gray-900">Open and click tracking</h3>+ <p class="text-sm text-gray-500 mt-1">We use an invisible image and measured links to see whether marketing emails are opened and clicked. This never affects which emails you receive.</p>+ </div>+ <div class="flex flex-col items-end flex-shrink-0 w-40">+ <div class="relative inline-block w-12 select-none">+ <input+ type="checkbox"+ name="$email_tracking"+ id="email-tracking-toggle"+ data-on-label="Tracking allowed"+ data-off-label="Tracking off"+ {% if email_tracking_allowed %}checked{% endif %}+ class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer transition-transform duration-200 ease-in-out checked:translate-x-full checked:bg-blue-500"+ />+ <label+ for="email-tracking-toggle"+ class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer"+ ></label>+ </div>+ <span class="text-xs font-medium mt-1 text-right {% if email_tracking_allowed %}text-green-700{% else %}text-gray-500{% endif %}" data-status-for="$email_tracking">+ {% if email_tracking_allowed %}Tracking allowed{% else %}Tracking off{% endif %}+ </span>+ </div>+ </div>+ </div>+ {% endif %}+</form></div>@@ -67,6 +99,13 @@statusLabel.className = 'text-xs font-medium mt-1 text-right ' + colorClass}+ // The tracking-consent toggle labels differ from the subscription ones+ function statusLabelText(toggle) {+ return toggle.checked+ ? (toggle.dataset.onLabel || 'Subscribed')+ : (toggle.dataset.offLabel || 'Not subscribed')+ }+function showToast(message, isError) {const toast = document.createElement('div')toast.className =@@ -90,6 +129,12 @@const formData = new FormData()formData.append('token', document.querySelector('input[name="token"]').value)toggles.forEach((toggle) => {+ // Only submit the tracking answer when that toggle is the one that changed:+ // its rendered default must never be persisted as an explicit consent choice.+ // The backend preserves a stored answer when the key is absent.+ if (toggle.name === '$email_tracking' && toggle !== changedToggle) {+ return+ }formData.append('preferences[]', `${toggle.name}:${toggle.checked}`)})@@ -108,12 +153,12 @@}toggles.forEach(t => { t.defaultChecked = t.checked })- updateStatusLabel(changedToggle, changedToggle.checked ? 'Subscribed' : 'Not subscribed', changedToggle.checked ? 'text-green-700' : 'text-gray-500')+ updateStatusLabel(changedToggle, statusLabelText(changedToggle), changedToggle.checked ? 'text-green-700' : 'text-gray-500')showToast('Preferences updated successfully', false)} catch (error) {// Revert the toggle on failurechangedToggle.checked = !changedToggle.checked- updateStatusLabel(changedToggle, changedToggle.checked ? 'Subscribed' : 'Not subscribed', changedToggle.checked ? 'text-green-700' : 'text-gray-500')+ updateStatusLabel(changedToggle, statusLabelText(changedToggle), changedToggle.checked ? 'text-green-700' : 'text-gray-500')showToast(error.message || 'Failed to update preferences', true)}}diff --git a/posthog/views.py b/posthog/views.pyindex b86f609aabd5..e4ae85bfbdbe 100644--- a/posthog/views.py+++ b/posthog/views.py@@ -64,10 +64,12 @@ from posthog.utils import (from products.messaging.backend.models.message_category import MessageCategoryfrom products.messaging.backend.models.message_preferences import (ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ EMAIL_TRACKING_PREFERENCE_ID,MessageRecipientPreference,PreferenceStatus,)from products.messaging.backend.services.customerio_sync_service import sync_preferences_to_customerio+from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentModelogger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)@@ -574,6 +576,34 @@ def report_workflows_email_unsubscribed(team_id: int, identifier: str, category_capture_exception(e)+def report_workflows_email_tracking_consent_updated(team_id: int, identifier: str, status: str) -> None:+ """+ Emit a $workflows_email_tracking_consent_updated engagement event when a recipient+ changes their open/click tracking consent on the preferences page. Gated on the same+ capture_workflows_engagement_events flag as the other $workflows_email_* events.+ Best-effort — never fails the preferences flow.+ """+ try:+ team = Team.objects.get(id=team_id)+ if not team.workflows_config.capture_workflows_engagement_events:+ return+ result = capture_internal(+ token=team.api_token,+ event_name="$workflows_email_tracking_consent_updated",+ event_source="workflows_preferences",+ distinct_id=identifier,+ properties={"$email": identifier, "status": status, "source": "preferences_page"},+ )+ if not result.succeeded():+ logger.error(+ "workflows_email_tracking_consent_capture_failed",+ team_id=team_id,+ error=result.error,+ )+ except Exception as e:+ capture_exception(e)++@csrf_exempt@require_http_methods(["GET", "POST"])def preferences_page(request: HttpRequest, token: str) -> HttpResponse:@@ -607,6 +637,12 @@ def preferences_page(request: HttpRequest, token: str) -> HttpResponse:# Also set the "$all" preferencepreferences_dict[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value+ # Unsubscribing is about which emails arrive, not how they're measured — a stored+ # tracking-consent answer must survive the wholesale rebuild+ tracking_pref = (recipient.preferences or {}).get(EMAIL_TRACKING_PREFERENCE_ID)+ if tracking_pref is not None:+ preferences_dict[EMAIL_TRACKING_PREFERENCE_ID] = tracking_pref+recipient.preferences = preferences_dictrecipient.save(update_fields=["preferences"])@@ -632,6 +668,11 @@ def preferences_page(request: HttpRequest, token: str) -> HttpResponse:for cat in categories]+ # Only surface the tracking-consent toggle when the team actually enforces consent —+ # in "off" mode a stored preference would have no effect on sends+ tracking_consent_mode = Team.objects.get(id=team_id).workflows_config.email_tracking_consent_mode+ tracking_status = preferences.get(EMAIL_TRACKING_PREFERENCE_ID, PreferenceStatus.NO_PREFERENCE)+context = {"recipient": recipient,"categories": [@@ -644,6 +685,13 @@ def preferences_page(request: HttpRequest, token: str) -> HttpResponse:},],"token": token,+ "email_tracking_consent_enabled": tracking_consent_mode != EmailTrackingConsentMode.OFF,+ # No stored answer falls back to the mode's default: tracked under opt-out, untracked under opt-in+ "email_tracking_allowed": (+ tracking_status == PreferenceStatus.OPTED_IN+ if tracking_consent_mode == EmailTrackingConsentMode.OPT_IN+ else tracking_status != PreferenceStatus.OPTED_OUT+ ),}return render(@@ -688,7 +736,6 @@ def update_preferences(request: HttpRequest) -> JsonResponse:preferences = request.POST.getlist("preferences[]")# Convert to dict of category_id: statuspreferences_dict = {}- all_opted_out = Truefor pref in preferences:category_id, opted_in = pref.split(":")@@ -699,13 +746,24 @@ def update_preferences(request: HttpRequest) -> JsonResponse:status = PreferenceStatus.OPTED_IN if opted_in == "true" else PreferenceStatus.OPTED_OUTpreferences_dict[category_id] = status.value- if status == PreferenceStatus.OPTED_IN:- all_opted_out = False+ # $email_tracking is a measurement consent, not a subscription — it must neither+ # block nor trigger the "unsubscribed from everything" $all computation+ subscription_prefs = {k: v for k, v in preferences_dict.items() if k != EMAIL_TRACKING_PREFERENCE_ID}# If all preferences are opted out, add the "$all" preference- if all_opted_out and preferences_dict:+ if subscription_prefs and all(v == PreferenceStatus.OPTED_OUT.value for v in subscription_prefs.values()):preferences_dict[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value+ # A save that doesn't include the tracking toggle (e.g. consent mode is off) must+ # not erase a stored consent answer in the wholesale rebuild+ if EMAIL_TRACKING_PREFERENCE_ID not in preferences_dict and EMAIL_TRACKING_PREFERENCE_ID in prior_preferences:+ preferences_dict[EMAIL_TRACKING_PREFERENCE_ID] = prior_preferences[EMAIL_TRACKING_PREFERENCE_ID]++ # A tracking-only save (no category toggles rendered, e.g. a team without marketing+ # categories) must not rebuild subscription state - it would drop a stored $all opt-out+ if not subscription_prefs:+ preferences_dict = {**prior_preferences, **preferences_dict}+# Update all preferences with a single DB writerecipient.preferences = preferences_dictrecipient.save()@@ -716,12 +774,19 @@ def update_preferences(request: HttpRequest) -> JsonResponse:newly_opted_out = [category_idfor category_id, status in preferences_dict.items()- if status == PreferenceStatus.OPTED_OUT.value+ if category_id != EMAIL_TRACKING_PREFERENCE_ID+ and status == PreferenceStatus.OPTED_OUT.valueand prior_preferences.get(category_id) != PreferenceStatus.OPTED_OUT.value]if newly_opted_out:report_workflows_email_unsubscribed(team_id, identifier, newly_opted_out, "preferences_page")+ new_tracking_consent = preferences_dict.get(EMAIL_TRACKING_PREFERENCE_ID)+ if new_tracking_consent is not None and new_tracking_consent != prior_preferences.get(+ EMAIL_TRACKING_PREFERENCE_ID+ ):+ report_workflows_email_tracking_consent_updated(team_id, identifier, new_tracking_consent)+return JsonResponse({"success": True})except Exception as e:diff --git a/products/messaging/backend/api/test/test_message_preferences.py b/products/messaging/backend/api/test/test_message_preferences.pyindex 4d8ae4e6e9b3..9738d160069f 100644--- a/products/messaging/backend/api/test/test_message_preferences.py+++ b/products/messaging/backend/api/test/test_message_preferences.py@@ -14,6 +14,7 @@ import posthog.plugins.plugin_server_api as plugin_server_apifrom products.messaging.backend.models.message_category import MessageCategoryfrom products.messaging.backend.models.message_preferences import (ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ EMAIL_TRACKING_PREFERENCE_ID,MessageRecipientPreference,PreferenceStatus,)@@ -291,6 +292,165 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(response.status_code, 200)mock_capture_internal.assert_not_called()+ def _set_tracking_consent_mode(self, mode: str):+ config = self.team.workflows_config+ config.email_tracking_consent_mode = mode+ config.save()++ @parameterized.expand(+ [+ # (consent mode, stored preference, section shown, toggle checked)+ ("off", None, False, None),+ ("opt_out", None, True, True),+ ("opt_out", PreferenceStatus.OPTED_OUT, True, False),+ ("opt_in", None, True, False),+ ("opt_in", PreferenceStatus.OPTED_IN, True, True),+ ]+ )+ @patch("posthog.views.validate_messaging_preferences_token")+ def test_preferences_page_tracking_section_per_mode(+ self, mode, stored_preference, section_shown, toggle_checked, mock_validate_messaging_preferences_token+ ):+ self._set_tracking_consent_mode(mode)+ if stored_preference is not None:+ self.recipient.preferences = {EMAIL_TRACKING_PREFERENCE_ID: stored_preference.value}+ self.recipient.save()+ mock_validate_messaging_preferences_token.return_value = mock_response(+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ )++ response = self.client.get(reverse("message_preferences", kwargs={"token": self.token}))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.context["email_tracking_consent_enabled"], section_shown)+ if section_shown:+ self.assertEqual(response.context["email_tracking_allowed"], toggle_checked)+ self.assertContains(response, "Open and click tracking")+ else:+ self.assertNotContains(response, "Open and click tracking")++ @patch("posthog.views.validate_messaging_preferences_token")+ def test_tracking_opt_out_alone_does_not_unsubscribe(self, mock_validate_messaging_preferences_token):+ mock_validate_messaging_preferences_token.return_value = mock_response(+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ )++ response = self.client.post(+ reverse("message_preferences_update"),+ {"token": self.token, "preferences[]": [f"{EMAIL_TRACKING_PREFERENCE_ID}:false"]},+ )++ self.assertEqual(response.status_code, 200)+ self.recipient.refresh_from_db()+ prefs = self.recipient.get_all_preferences()+ self.assertEqual(prefs[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_OUT)+ self.assertNotIn(ALL_MESSAGE_PREFERENCE_CATEGORY_ID, prefs)++ @patch("posthog.views.validate_messaging_preferences_token")+ def test_tracking_only_save_preserves_stored_all_opt_out(self, mock_validate_messaging_preferences_token):+ # A tracking-only payload (no category toggles rendered) must not rebuild+ # subscription state and silently resubscribe a one-click-unsubscribed recipient+ self.recipient.preferences = {ALL_MESSAGE_PREFERENCE_CATEGORY_ID: PreferenceStatus.OPTED_OUT.value}+ self.recipient.save()+ mock_validate_messaging_preferences_token.return_value = mock_response(+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ )++ response = self.client.post(+ reverse("message_preferences_update"),+ {"token": self.token, "preferences[]": [f"{EMAIL_TRACKING_PREFERENCE_ID}:false"]},+ )++ self.assertEqual(response.status_code, 200)+ self.recipient.refresh_from_db()+ prefs = self.recipient.get_all_preferences()+ self.assertEqual(prefs[ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_OUT)+ self.assertEqual(prefs[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_OUT)++ @patch("posthog.views.validate_messaging_preferences_token")+ def test_tracking_opt_in_does_not_block_all_unsubscribe(self, mock_validate_messaging_preferences_token):+ mock_validate_messaging_preferences_token.return_value = mock_response(+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ )++ response = self.client.post(+ reverse("message_preferences_update"),+ {+ "token": self.token,+ "preferences[]": [+ f"{self.category.id}:false",+ f"{self.category2.id}:false",+ f"{EMAIL_TRACKING_PREFERENCE_ID}:true",+ ],+ },+ )++ self.assertEqual(response.status_code, 200)+ self.recipient.refresh_from_db()+ prefs = self.recipient.get_all_preferences()+ self.assertEqual(prefs[ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_OUT)+ self.assertEqual(prefs[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_IN)++ @parameterized.expand(["one_click", "preferences_form"])+ @patch("posthog.views.validate_messaging_preferences_token")+ def test_stored_tracking_consent_survives_writes_that_omit_it(+ self, code_path, mock_validate_messaging_preferences_token+ ):+ # Both write paths rebuild the preferences dict wholesale — a stored tracking-consent+ # answer must not be erased by an unsubscribe or a category-only save+ self.recipient.preferences = {EMAIL_TRACKING_PREFERENCE_ID: PreferenceStatus.OPTED_OUT.value}+ self.recipient.save()+ mock_validate_messaging_preferences_token.return_value = mock_response(+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ )++ if code_path == "one_click":+ response = self.client.get(+ reverse("message_preferences", kwargs={"token": self.token}),+ {"one_click_unsubscribe": "1"},+ )+ else:+ response = self.client.post(+ reverse("message_preferences_update"),+ {"token": self.token, "preferences[]": [f"{self.category.id}:true"]},+ )++ self.assertEqual(response.status_code, 200)+ self.recipient.refresh_from_db()+ self.assertEqual(self.recipient.get_all_preferences()[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_OUT)++ @patch("posthog.views.capture_internal")+ @patch("posthog.views.validate_messaging_preferences_token")+ def test_tracking_consent_change_emits_event_only_on_transition(+ self, mock_validate_messaging_preferences_token, mock_capture_internal+ ):+ self._enable_engagement_events()+ mock_validate_messaging_preferences_token.return_value = mock_response(+ 200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}+ )+ data = {"token": self.token, "preferences[]": [f"{EMAIL_TRACKING_PREFERENCE_ID}:false"]}++ response = self.client.post(reverse("message_preferences_update"), data)++ self.assertEqual(response.status_code, 200)+ mock_capture_internal.assert_called_once_with(+ token=self.team.api_token,+ event_name="$workflows_email_tracking_consent_updated",+ event_source="workflows_preferences",+ distinct_id=self.recipient.identifier,+ properties={+ "$email": self.recipient.identifier,+ "status": PreferenceStatus.OPTED_OUT.value,+ "source": "preferences_page",+ },+ )++ # A repeated save with the same value is not a transition and must not emit again+ mock_capture_internal.reset_mock()+ response = self.client.post(reverse("message_preferences_update"), data)+ self.assertEqual(response.status_code, 200)+ mock_capture_internal.assert_not_called()+class TestMessagePreferencesAPIViewSet(APIBaseTest):def setUp(self):diff --git a/products/messaging/backend/models/message_preferences.py b/products/messaging/backend/models/message_preferences.pyindex ef5162e06898..9a19cb6238d7 100644--- a/products/messaging/backend/models/message_preferences.py+++ b/products/messaging/backend/models/message_preferences.py@@ -6,6 +6,11 @@ from posthog.models.utils import UUIDTModelALL_MESSAGE_PREFERENCE_CATEGORY_ID = "$all"+# Reserved preference key for open/click tracking consent (CNIL/ePrivacy). Distinct from the+# '$all' unsubscribe: a recipient can keep receiving emails while refusing open/click tracking.+# Mirrored in nodejs/src/cdp/services/managers/recipients-manager.service.ts.+EMAIL_TRACKING_PREFERENCE_ID = "$email_tracking"+class PreferenceStatus(models.TextChoices):OPTED_IN = "OPTED_IN"diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 0ba344d07f64..3e36dfc7f3c9 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -455,6 +455,9 @@ class HogFlowActionSerializer(serializers.Serializer):"type: event|person|group}. ""function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable ""hog templating ({person.x}, {event.x}); flat strings won't interpolate. "+ "function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open "+ "pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, "+ "so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). ""Dictionary input values are template strings too — write booleans/numbers as single-expression ""templates ('{true}', '{42}'), which evaluate to the typed value. ""delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; "diff --git a/products/workflows/backend/test/test_team_workflows_config.py b/products/workflows/backend/test/test_team_workflows_config.pyindex 3c2245afbf4a..7da156b71c15 100644--- a/products/workflows/backend/test/test_team_workflows_config.py+++ b/products/workflows/backend/test/test_team_workflows_config.py@@ -24,7 +24,10 @@ class TestTeamWorkflowsConfig(APIBaseTest):def test_defaults_to_capture_disabled_when_no_extension_row_exists(self) -> None:response = self.client.get(self.url)assert response.status_code == status.HTTP_200_OK- assert response.json()["workflows_config"] == {"capture_workflows_engagement_events": False}+ assert response.json()["workflows_config"] == {+ "capture_workflows_engagement_events": False,+ "email_tracking_consent_mode": "off",+ }def test_patch_enables_capture(self) -> None:# APIBaseTest.setUp may trigger the workflows_config cached_property (which calls@@ -32,7 +35,7 @@ class TestTeamWorkflowsConfig(APIBaseTest):# value. Either way, the patch must end with the row present and capture enabled.response = self.client.patch(self.url, {"workflows_config": {"capture_workflows_engagement_events": True}})assert response.status_code == status.HTTP_200_OK- assert response.json()["workflows_config"] == {"capture_workflows_engagement_events": True}+ assert response.json()["workflows_config"]["capture_workflows_engagement_events"] is Truerow = TeamWorkflowsConfig.objects.get(team=self.team)assert row.capture_workflows_engagement_events is True@@ -42,7 +45,7 @@ class TestTeamWorkflowsConfig(APIBaseTest):response = self.client.patch(self.url, {"workflows_config": {"capture_workflows_engagement_events": False}})assert response.status_code == status.HTTP_200_OK- assert response.json()["workflows_config"] == {"capture_workflows_engagement_events": False}+ assert response.json()["workflows_config"]["capture_workflows_engagement_events"] is Falseassert TeamWorkflowsConfig.objects.get(team=self.team).capture_workflows_engagement_events is Falsedef test_patch_with_other_team_fields_does_not_disturb_workflows_config(self) -> None:@@ -50,9 +53,20 @@ class TestTeamWorkflowsConfig(APIBaseTest):response = self.client.patch(self.url, {"name": "renamed team"})assert response.status_code == status.HTTP_200_OK- assert response.json()["workflows_config"] == {"capture_workflows_engagement_events": True}+ assert response.json()["workflows_config"]["capture_workflows_engagement_events"] is Trueassert TeamWorkflowsConfig.objects.get(team=self.team).capture_workflows_engagement_events is True+ def test_patch_sets_email_tracking_consent_mode(self) -> None:+ response = self.client.patch(self.url, {"workflows_config": {"email_tracking_consent_mode": "opt_in"}})+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["workflows_config"]["email_tracking_consent_mode"] == "opt_in"+ assert TeamWorkflowsConfig.objects.get(team=self.team).email_tracking_consent_mode == "opt_in"++ def test_patch_rejects_unknown_email_tracking_consent_mode(self) -> None:+ response = self.client.patch(self.url, {"workflows_config": {"email_tracking_consent_mode": "sometimes"}})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "workflows_config__email_tracking_consent_mode"+def test_patch_rejects_non_boolean_capture_workflows_engagement_events(self) -> None:response = self.client.patch(self.url, {"workflows_config": {"capture_workflows_engagement_events": "yes please"}}@@ -69,4 +83,7 @@ class TestTeamWorkflowsConfig(APIBaseTest):self.url, {"workflows_config": {"capture_workflows_engagement_events": True, "future_flag": "ignored"}})assert response.status_code == status.HTTP_200_OK- assert response.json()["workflows_config"] == {"capture_workflows_engagement_events": True}+ assert response.json()["workflows_config"] == {+ "capture_workflows_engagement_events": True,+ "email_tracking_consent_mode": "off",+ }diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsxindex 0a3edb98ac12..3529691ea625 100644--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx@@ -80,8 +80,40 @@ export function WorkflowMetricsSummary({align: 'right',render: (_, row) => row.delivered.toLocaleString(),},- { title: 'Opened', key: 'opened', align: 'right', render: (_, row) => row.opened.toLocaleString() },- { title: 'Clicked', key: 'clicked', align: 'right', render: (_, row) => row.linkClicked.toLocaleString() },+ {+ title: 'Opened',+ key: 'opened',+ align: 'right',+ tooltip:+ 'Untracked sends can never record opens or clicks, so opens are shown against tracked deliveries (delivered minus untracked).',+ render: (_, row) => (+ <span>+ {row.opened.toLocaleString()}+ {row.untracked > 0 && row.delivered - row.untracked > 0 && (+ <span className="text-muted">+ {' '}+ of {(row.delivered - row.untracked).toLocaleString()} tracked+ </span>+ )}+ </span>+ ),+ },+ {+ title: 'Clicked',+ key: 'clicked',+ align: 'right',+ render: (_, row) => (+ <span>+ {row.linkClicked.toLocaleString()}+ {row.untracked > 0 && row.delivered - row.untracked > 0 && (+ <span className="text-muted">+ {' '}+ of {(row.delivered - row.untracked).toLocaleString()} tracked+ </span>+ )}+ </span>+ ),+ },{title: 'Issues',key: 'issues',diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsxindex 04635917b02f..38af2a6fab7a 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx@@ -578,7 +578,7 @@ export interface hogFlowEditorLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}created_at?: number | undefined@@ -609,7 +609,7 @@ export interface hogFlowEditorLogicActions {}[]| null| undefined- type: 'function_email'+ type: 'function_push'updated_at?: number | undefined}| {@@ -626,7 +626,7 @@ export interface hogFlowEditorLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}created_at?: number | undefined@@ -657,7 +657,7 @@ export interface hogFlowEditorLogicActions {}[]| null| undefined- type: 'function_push'+ type: 'function_sms'updated_at?: number | undefined}| {@@ -674,8 +674,9 @@ export interface hogFlowEditorLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}created_at?: number | undefineddescription: string@@ -705,7 +706,7 @@ export interface hogFlowEditorLogicActions {}[]| null| undefined- type: 'function_sms'+ type: 'function_email'updated_at?: number | undefined}| {@@ -1363,7 +1364,7 @@ export interface hogFlowEditorLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}created_at?: number | undefined@@ -1394,7 +1395,7 @@ export interface hogFlowEditorLogicActions {}[]| null| undefined- type: 'function_email'+ type: 'function_push'updated_at?: number | undefined}| {@@ -1411,7 +1412,7 @@ export interface hogFlowEditorLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}created_at?: number | undefined@@ -1442,7 +1443,7 @@ export interface hogFlowEditorLogicActions {}[]| null| undefined- type: 'function_push'+ type: 'function_sms'updated_at?: number | undefined}| {@@ -1459,8 +1460,9 @@ export interface hogFlowEditorLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}created_at?: number | undefineddescription: string@@ -1490,7 +1492,7 @@ export interface hogFlowEditorLogicActions {}[]| null| undefined- type: 'function_sms'+ type: 'function_email'updated_at?: number | undefined}| {diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsxindex 0cb8450b77cc..342e14d37322 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx@@ -11,6 +11,7 @@ import {LemonInput,LemonLabel,LemonSelect,+ LemonSwitch,} from '@posthog/lemon-ui'import { EditableField } from 'lib/components/EditableField/EditableField'@@ -26,7 +27,7 @@ import { workflowLogic } from '../../workflowLogic'import { HogFlowPropertyFilters } from '../filters/HogFlowFilters'import { hogFlowEditorLogic } from '../hogFlowEditorLogic'import { useHogFlowStep } from '../steps/HogFlowSteps'-import { isOptOutEligibleAction, isScheduleTrigger } from '../steps/types'+import { isEmailAction, isOptOutEligibleAction, isScheduleTrigger } from '../steps/types'import type { HogFlowAction } from '../types'import { hogFlowOutputMappingLogic } from './hogFlowOutputMappingLogic'import { OutputTestResultTree } from './OutputTestResultTree'@@ -161,6 +162,26 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {</>)}+ {isEmailAction(action) && (+ <>+ <LemonDivider className="my-0" />+ <div className="flex gap-2 justify-between items-center px-2 py-1">+ <LemonLabel info="Turn this off for emails that should never be tracked, such as transactional messages. When off, no tracking pixel is added and links are not rewritten, so opens and clicks won't appear in the workflow's metrics. Delivery, bounce, and unsubscribe events are still recorded. Marketing emails may additionally be sent untracked based on the email tracking consent setting in your environment settings.">+ Track opens and link clicks+ </LemonLabel>+ <LemonSwitch+ checked={action.config.tracking_enabled !== false}+ onChange={(checked) => {+ setWorkflowAction(action.id, {+ ...action,+ config: { ...action.config, tracking_enabled: checked },+ })+ }}+ />+ </div>+ </>+ )}+{!['trigger', 'exit'].includes(action.type) && (<><LemonDivider className="my-0" />diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.tsindex 5c79e9592b97..12bf0ca8e50e 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts@@ -258,7 +258,7 @@ export interface stepDelayLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}| {@@ -274,9 +274,20 @@ export interface stepDelayLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}+ | {+ day:+ | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]+ | 'any'+ | 'weekday'+ | 'weekend'+ fallback_timezone?: string | null | undefined+ time: [string, string] | 'any'+ timezone: string | null+ use_person_timezone?: boolean | undefined+ }| {inputs: Record<string,@@ -290,19 +301,9 @@ export interface stepDelayLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined- }- | {- day:- | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]- | 'any'- | 'weekday'- | 'weekend'- fallback_timezone?: string | null | undefined- time: [string, string] | 'any'- timezone: string | null- use_person_timezone?: boolean | undefined+ tracking_enabled?: boolean | undefined}) => {actionId: string@@ -527,7 +528,7 @@ export interface stepDelayLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}| {@@ -543,7 +544,7 @@ export interface stepDelayLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}| {@@ -559,8 +560,9 @@ export interface stepDelayLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}} // workflowLogicsetDelayWorkflowActionConfig: (diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.tsindex 3e30c9ef4db5..21b5bc995942 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts@@ -306,7 +306,7 @@ export interface stepWaitUntilTimeWindowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}| {@@ -322,9 +322,20 @@ export interface stepWaitUntilTimeWindowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}+ | {+ day:+ | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]+ | 'any'+ | 'weekday'+ | 'weekend'+ fallback_timezone?: string | null | undefined+ time: [string, string] | 'any'+ timezone: string | null+ use_person_timezone?: boolean | undefined+ }| {inputs: Record<string,@@ -338,19 +349,9 @@ export interface stepWaitUntilTimeWindowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined- }- | {- day:- | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]- | 'any'- | 'weekday'- | 'weekend'- fallback_timezone?: string | null | undefined- time: [string, string] | 'any'- timezone: string | null- use_person_timezone?: boolean | undefined+ tracking_enabled?: boolean | undefined}>) => {@@ -576,7 +577,7 @@ export interface stepWaitUntilTimeWindowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}| {@@ -592,7 +593,7 @@ export interface stepWaitUntilTimeWindowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}| {@@ -608,8 +609,9 @@ export interface stepWaitUntilTimeWindowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}>} // workflowLogicdiff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.tsindex 6dc270a0fa39..09c8e5f47f7d 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts@@ -280,6 +280,10 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [config: z.object({message_category_id: z.string().optional(),message_category_type: z.enum(['marketing', 'transactional']).optional(),+ // When false, no open pixel is injected, links are not rewritten, and the send uses the+ // untracked SES configuration set. Absent/true means tracked. Keep in sync with+ // nodejs/src/cdp/schema/hogflow.ts.+ tracking_enabled: z.boolean().optional(),template_uuid: z.string().optional(), // May be used later to specify a specific template versiontemplate_id: z.literal('template-email'),inputs: z.record(z.string(), CyclotronInputSchema),diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 6136f687e407..69c95e116789 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -485,6 +485,7 @@ export interface workflowLogicActions {message_category_type?: 'marketing' | 'transactional' | undefinedtemplate_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}created_at?: number | undefineddescription: string@@ -1270,6 +1271,7 @@ export interface workflowLogicActions {message_category_type?: 'marketing' | 'transactional' | undefinedtemplate_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}created_at?: number | undefineddescription: string@@ -2032,7 +2034,7 @@ export interface workflowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}| {@@ -2048,9 +2050,20 @@ export interface workflowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}+ | {+ day:+ | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]+ | 'any'+ | 'weekday'+ | 'weekend'+ fallback_timezone?: string | null | undefined+ time: [string, string] | 'any'+ timezone: string | null+ use_person_timezone?: boolean | undefined+ }| {inputs: Record<string,@@ -2064,19 +2077,9 @@ export interface workflowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined- }- | {- day:- | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]- | 'any'- | 'weekday'- | 'weekend'- fallback_timezone?: string | null | undefined- time: [string, string] | 'any'- timezone: string | null- use_person_timezone?: boolean | undefined+ tracking_enabled?: boolean | undefined}>}@@ -2361,7 +2364,7 @@ export interface workflowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-email'+ template_id: 'template-native-push'template_uuid?: string | undefined}| {@@ -2377,9 +2380,20 @@ export interface workflowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-native-push'+ template_id: 'template-twilio'template_uuid?: string | undefined}+ | {+ day:+ | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]+ | 'any'+ | 'weekday'+ | 'weekend'+ fallback_timezone?: string | null | undefined+ time: [string, string] | 'any'+ timezone: string | null+ use_person_timezone?: boolean | undefined+ }| {inputs: Record<string,@@ -2393,19 +2407,9 @@ export interface workflowLogicActions {>message_category_id?: string | undefinedmessage_category_type?: 'marketing' | 'transactional' | undefined- template_id: 'template-twilio'+ template_id: 'template-email'template_uuid?: string | undefined- }- | {- day:- | ('friday' | 'monday' | 'saturday' | 'sunday' | 'thursday' | 'tuesday' | 'wednesday')[]- | 'any'- | 'weekday'- | 'weekend'- fallback_timezone?: string | null | undefined- time: [string, string] | 'any'- timezone: string | null- use_person_timezone?: boolean | undefined+ tracking_enabled?: boolean | undefined}}setWorkflowActionEdges: (diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.tsindex 5de8597cf5c8..ae2686082a0a 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts@@ -162,6 +162,7 @@ describe('buildEmailMetricRows', () => {email_bounced: 6,email_bounce_prevented: 2,email_blocked: 4,+ email_untracked: 7,},})expect(rows).toEqual([@@ -175,6 +176,7 @@ describe('buildEmailMetricRows', () => {bounced: 6,bouncePrevented: 2,blocked: 4,+ untracked: 7,},])})diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.tsindex 40e0a557e483..3cefeb4464f5 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts@@ -46,6 +46,7 @@ export type EmailMetric =| 'email_bounce_prevented'| 'email_blocked'| 'email_spam'+ | 'email_untracked'export type PushMetric = 'push_sent' | 'push_skipped' | 'push_failed'@@ -67,6 +68,9 @@ export type EmailMetricRow = {bounced: numberbouncePrevented: numberblocked: number+ // Sends without open/click tracking (step toggle off or no recipient consent). These can never+ // record opens/clicks, so engagement reads against (delivered - untracked).+ untracked: number}// Single source of truth for metric colors across the workflow metric views. Keyed by the metric's@@ -99,6 +103,7 @@ export const METRIC_COLORS: Record<string, string> = {'Bounce prevented': getColorVar('data-color-7'),Blocked: getColorVar('data-color-8'),'Marked as spam': getColorVar('data-color-9'),+ Untracked: getColorVar('data-color-10'),Skipped: getColorVar('data-color-2'),// Workflow run + batch-job metricsSuccess: getColorVar('success'),@@ -176,7 +181,8 @@ export const WORKFLOW_EMAIL_METRICS: Record<},email_opened: {name: 'Opened',- description: 'Total number of emails opened',+ description:+ 'Total number of emails opened. Untracked sends can never record an open, so compare opens against delivered minus untracked.',color: METRIC_COLORS['Opened'],metricNames: ['email_opened'],},@@ -211,6 +217,13 @@ export const WORKFLOW_EMAIL_METRICS: Record<color: METRIC_COLORS['Marked as spam'],metricNames: ['email_spam'],},+ email_untracked: {+ name: 'Untracked',+ description:+ 'Total number of emails sent without open/click tracking, because tracking was turned off on the step or the recipient has not consented. These sends can never record opens or clicks, so exclude them when judging engagement.',+ color: METRIC_COLORS['Untracked'],+ metricNames: ['email_untracked'],+ },}// Push has no delivery-receipt channel like email's SES webhook (FCM/APNs respond synchronously), so@@ -293,6 +306,7 @@ const EMAIL_METRICS: EmailMetric[] = ['email_bounce_prevented','email_blocked','email_spam',+ 'email_untracked',]const PUSH_METRICS: PushMetric[] = ['push_sent', 'push_skipped', 'push_failed']@@ -342,6 +356,7 @@ export interface workflowMetricsSummaryLogicValues {message_category_type?: 'marketing' | 'transactional' | undefinedtemplate_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}created_at?: number | undefineddescription: string@@ -549,6 +564,7 @@ export interface workflowMetricsSummaryLogicMeta {message_category_type?: 'marketing' | 'transactional' | undefinedtemplate_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}created_at?: number | undefineddescription: string@@ -647,7 +663,7 @@ export interface workflowMetricsSummaryLogicMeta {dateFrom: DayjsdateTo: DayjsdiffMs: number- }, // appMetricsLogic+ },arg: string) => stringworkflowSummaryTrends: (@@ -657,7 +673,7 @@ export interface workflowMetricsSummaryLogicMeta {getCompletedSingleTrendSeries: (name: string,previousPeriod?: boolean- ) => AppMetricsTimeSeriesResponse | null, // appMetricsLogic+ ) => AppMetricsTimeSeriesResponse | null,messagingChannels: {hasEmail: booleanhasPush: boolean@@ -681,6 +697,7 @@ export interface workflowMetricsSummaryLogicMeta {message_category_type?: 'marketing' | 'transactional' | undefinedtemplate_id: 'template-email'template_uuid?: string | undefined+ tracking_enabled?: boolean | undefined}created_at?: number | undefineddescription: string@@ -1320,6 +1337,7 @@ export function buildEmailMetricRows(bounced,bouncePrevented: totals.email_bounce_prevented ?? 0,blocked,+ untracked: totals.email_untracked ?? 0,}})}diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex a6cefe774431..9ebb92f14d38 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -384,7 +384,7 @@ export interface HogFlowEdgeApi {}/**- * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.+ * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.*/export type HogFlowActionApiConfig =| { [key: string]: unknown }@@ -436,7 +436,7 @@ export interface HogFlowActionApi {* @maxLength 100*/type: string- /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */+ /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */config: HogFlowActionApiConfig/** Output variable for downstream actions: {key, result_path?, spread?, label?} or a list of those. */output_variable?: unknowndiff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 7a86b92c8eec..68e72907a406 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -692,7 +692,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -1024,7 +1024,7 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -1361,7 +1361,7 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -1878,7 +1878,7 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()@@ -2436,7 +2436,7 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()diff --git a/products/workflows/frontend/scenes/settings/WorkflowsEmailTrackingConsentSettings.tsx b/products/workflows/frontend/scenes/settings/WorkflowsEmailTrackingConsentSettings.tsxnew file mode 100644index 000000000000..5aa0a7fc2927--- /dev/null+++ b/products/workflows/frontend/scenes/settings/WorkflowsEmailTrackingConsentSettings.tsx@@ -0,0 +1,51 @@+import { useActions, useValues } from 'kea'++import { LemonRadio } from 'lib/lemon-ui/LemonRadio'+import { teamLogic } from 'scenes/teamLogic'++import type { WorkflowsConfig } from '~/types'++type ConsentMode = NonNullable<WorkflowsConfig['email_tracking_consent_mode']>++export function WorkflowsEmailTrackingConsentSettings(): JSX.Element {+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)+ const { updateCurrentTeam } = useActions(teamLogic)++ const mode: ConsentMode = currentTeam?.workflows_config?.email_tracking_consent_mode ?? 'off'++ return (+ <LemonRadio+ value={mode}+ onChange={(value: ConsentMode) => {+ updateCurrentTeam({+ workflows_config: {+ capture_workflows_engagement_events:+ currentTeam?.workflows_config?.capture_workflows_engagement_events ?? false,+ email_tracking_consent_mode: value,+ },+ })+ }}+ options={[+ {+ value: 'off',+ label: 'No consent enforcement',+ description:+ 'Opens and clicks are tracked according to each email step\'s "Track opens and link clicks" setting.',+ },+ {+ value: 'opt_out',+ label: 'Opt-out',+ description:+ 'Track by default, but not for recipients who have objected to tracking. Marketing emails only; transactional emails are exempt.',+ },+ {+ value: 'opt_in',+ label: 'Opt-in',+ description:+ 'Only track recipients who have explicitly consented. Recipients without a stored consent are sent untracked emails. Marketing emails only; transactional emails are exempt.',+ },+ ]}+ className={currentTeamLoading ? 'opacity-50 pointer-events-none' : undefined}+ />+ )+}diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdindex 6c95e2a32519..484521c76d17 100644--- a/products/workflows/skills/building-workflows/references/graph-schema.md+++ b/products/workflows/skills/building-workflows/references/graph-schema.md@@ -38,19 +38,19 @@ Every action object has these common fields plus a type-specific `config`:Use **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor's parse for the entire graph.-| `type` | `config` |-| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |-| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |-| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |-| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages should sum to 100 — a shortfall leaves an unrouted remainder, an excess makes later cohorts unreachable. |-| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |-| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |-| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don't guess the id or its inputs — discover them live (see below). |-| `function_email` | `{ "template_id": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-email` — reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id`. |-| `function_sms` | `{ "template_id": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`. |-| `function_push` | `{ "template_id": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email's — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project's push integration ids for `channels`. |-| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |+| `type` | `config` |+| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |+| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |+| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |+| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages should sum to 100 — a shortfall leaves an unrouted remainder, an excess makes later cohorts unreachable. |+| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |+| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |+| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don't guess the id or its inputs — discover them live (see below). |+| `function_email` | `{ "template_id": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email` — reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id`. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |+| `function_sms` | `{ "template_id": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`. |+| `function_push` | `{ "template_id": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email's — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project's push integration ids for `channels`. |+| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |### Branch and wait condition filters (the `filters` wrapper is mandatory)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 80bb7c79fb78..838d116a7b59 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22814,6 +22814,20 @@ export namespace Schemas {design?: EmailTemplateDesign;}+ /**+ * * `off` - Off+ * * `opt_out` - Opt Out+ * * `opt_in` - Opt In+ */+ export type EmailTrackingConsentModeEnum = typeof EmailTrackingConsentModeEnum[keyof typeof EmailTrackingConsentModeEnum];+++ export const EmailTrackingConsentModeEnum = {+ Off: 'off',+ OptOut: 'opt_out',+ OptIn: 'opt_in',+ } as const;+export type EmbeddingStatusEnum = typeof EmbeddingStatusEnum[keyof typeof EmbeddingStatusEnum];@@ -32563,7 +32577,7 @@ export namespace Schemas {} as const;/**- * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.+ * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}.*/export type HogFlowActionConfig = { [key: string]: unknown } | {/** Property-based wait condition; continues when the person matches. A condition with no property filters is ignored — the wait then relies on 'events' and the max_wait_duration timeout. */@@ -32613,7 +32627,7 @@ export namespace Schemas {* @maxLength 100*/type: string;- /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */+ /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}. */config: HogFlowActionConfig;/** Output variable for downstream actions: {key, result_path?, spread?, label?} or a list of those. */output_variable?: unknown;@@ -50455,6 +50469,12 @@ export namespace Schemas {export interface TeamWorkflowsConfig {/** When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_*) alongside the existing workflow metrics. */capture_workflows_engagement_events?: boolean;+ /** Recipient-consent enforcement for open/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.+ *+ * * `off` - Off+ * * `opt_out` - Opt Out+ * * `opt_in` - Opt In */+ email_tracking_consent_mode?: EmailTrackingConsentModeEnum;}/**diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex ea89d8b7edf0..8c894cd76506 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -451,6 +451,13 @@ export const OrganizationsProjectsPartialUpdateBody = /* @__PURE__ */ zod.describe('When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_\*) alongside the existing workflow metrics.'),+ email_tracking_consent_mode: zod+ .enum(['off', 'opt_out', 'opt_in'])+ .describe('\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In')+ .optional()+ .describe(+ "Recipient-consent enforcement for open\/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n\* `off` - Off\n\* `opt_out` - Opt Out\n\* `opt_in` - Opt In"+ ),}).optional(),base_currency: zoddiff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex e90ad82b8615..3d21c6340ed0 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -347,7 +347,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function\*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open\/click tracking, so opens and clicks are not recorded for that step (delivery\/bounce\/unsubscribe still are). Dictionary input values are template strings too — write booleans\/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."),output_variable: zod.unknown()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.jsonindex 14495560db1c..e6f0e02f6134 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json@@ -899,6 +899,11 @@"capture_workflows_engagement_events": {"description": "When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_*) alongside the existing workflow metrics.","type": "boolean"+ },+ "email_tracking_consent_mode": {+ "description": "Recipient-consent enforcement for open/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n* `off` - Off\n* `opt_out` - Opt Out\n* `opt_in` - Opt In",+ "enum": ["off", "opt_out", "opt_in"],+ "type": "string"}},"type": "object"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.jsonindex dd72cd039d46..8f909fc64782 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json@@ -193,7 +193,7 @@"type": "object"}],- "description": "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."+ "description": "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}. function*: {template_id, inputs: {<key>: {value: <str>}}}. Wrap values in {value:...} to enable hog templating ({person.x}, {event.x}); flat strings won't interpolate. function_email also accepts tracking_enabled?: <bool> (default true) - when false, no open pixel is injected, links are not rewritten, and the send skips ESP-level open/click tracking, so opens and clicks are not recorded for that step (delivery/bounce/unsubscribe still are). Dictionary input values are template strings too — write booleans/numbers as single-expression templates ('{true}', '{42}'), which evaluate to the typed value. delay: {delay_duration: '<number><unit>'} where unit is m|h|d. Fractions OK ('0.5m'=30s; seconds unsupported). Per-unit max m<=60, h<=24, d<=30; values above are SILENTLY CLAMPED. Max 30d. conditional_branch: {conditions: [{filters}, ...]}. Index N matches the 'branch' edge with index:N. random_cohort_branch: {cohorts: [{percentage: <number>, name?}, ...]}. Index N matches the 'branch' edge with index:N; percentages should sum to 100 (an unallocated remainder routes to the last cohort). wait_until_condition: {condition: {filters}, events?: [{filters: {events: [{id, name, type: 'events'}], actions?: [...]}, name?}], max_wait_duration: <duration>} (same rules as delay). Continues when condition.filters match OR any events entry fires; each events entry must target at least one event or action. On resolution (a condition match or any events entry firing) it advances via the 'branch' edge with index:0; the max_wait_duration timeout falls through the 'continue' edge. exit: {reason}."},"created_at": {"description": "Created at (epoch ms). Frontend-managed.",