: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): trigger a workflow from a Slack channel message (#83765)
Ben White07e7141f4611
diff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 8577b3fd72fe..da9fc2220b1d 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -165,6 +165,12 @@ procs:tech: Frontend# no capability: always_required via intent-map.yaml+ ngrok:+ shell: 'bin/start-local-ngrok'+ groups:+ layer: Application+ tech: Network+typegen:sandbox: trueshell: 'cd frontend && pnpm run typegen:watch'diff --git a/bin/start-local-ngrok b/bin/start-local-ngroknew file mode 100755index 000000000000..72ec16ea04f9--- /dev/null+++ b/bin/start-local-ngrok@@ -0,0 +1,45 @@+#!/usr/bin/env bash++set -euo pipefail++check_only=false+if [[ "${1:-}" == "--check" ]]; then+ check_only=true+elif [[ $# -gt 0 ]]; then+ echo "Usage: $0 [--check]" >&2+ exit 1+fi++site_url="${SITE_URL:-}"+if [[ ! "$site_url" =~ ^https://[A-Za-z0-9-]+\.ngrok(-free)?\.dev/?$ ]]; then+ echo "ngrok tunnel disabled: SITE_URL is not an ngrok URL"+ exit 0+fi++ngrok_config="$(ngrok config check --log=stdout 2>&1 | sed -n 's/.*Valid configuration file at //p' | tail -n 1)"+if [[ -z "$ngrok_config" ]]; then+ echo "Configure ngrok first with: ngrok config add-authtoken <token>" >&2+ exit 1+fi++domain="${site_url#https://}"+domain="${domain%/}"+tunnel_config="$(mktemp "${TMPDIR:-/tmp}/posthog-ngrok.XXXXXX")"+trap 'rm -f "$tunnel_config"' EXIT++cat >"$tunnel_config" <<EOF+version: '3'+tunnels:+ posthog:+ proto: http+ addr: 8010+ domain: $domain+ host_header: localhost+EOF++if [[ "$check_only" == true ]]; then+ ngrok config check --config "$ngrok_config" --config "$tunnel_config"+ exit 0+fi++ngrok start posthog --config "$ngrok_config" --config "$tunnel_config"diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yamlindex f276e3a0ffc2..28f1eeff247b 100644--- a/devenv/intent-map.yaml+++ b/devenv/intent-map.yaml@@ -211,6 +211,11 @@ capabilities:requires: [core_infra]docker_profiles: [dev_tools]+ webhook_tester:+ description: 'Local HTTP sink for webhook steps and destinations (localhost:2080)'+ requires: [core_infra]+ docker_profiles: [webhook_tester]+mcp_server:description: 'MCP server for AI assistant integration'requires: [core_infra]@@ -392,6 +397,7 @@ intents:temporal_workflows,nodejs_cdp_workflows,cyclotron,+ webhook_tester,]tracing:@@ -437,6 +443,7 @@ intents:always_required:- backend- frontend+ - ngrok- typegen- docker-compose# Migrations (DBs created by postgres init scripts, run for everyone)diff --git a/docker-compose.profiles.yml b/docker-compose.profiles.ymlindex 095383d24494..2581ef4be901 100644--- a/docker-compose.profiles.yml+++ b/docker-compose.profiles.yml@@ -41,8 +41,10 @@ services:profiles: [dev_tools]maildev:profiles: [dev_tools]+ # Also carries its own profile: a workflow's webhook step needs somewhere to point, and+ # that shouldn't cost you Kafka UI, Flower and maildev as well.webhook-tester:- profiles: [dev_tools]+ profiles: [dev_tools, webhook_tester]# Session-recording storage (replay).seaweedfs:diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.mdindex e285d2cbd3a8..b7905b8df4eb 100644--- a/docs/internal/slack-local-setup-guide.md+++ b/docs/internal/slack-local-setup-guide.md@@ -46,26 +46,20 @@ Cloudflare Tunnel (`cloudflared`) is a fine free alternative; whatever you pick,**8010** (Caddy) and make it rewrite the upstream `Host` header to `localhost` (see "How requestsflow" for why).-ngrok config — point the tunnel at **8010** and set `host_header: localhost`:+Reserve an ngrok domain, then authenticate once:-```yaml-# ~/Library/Application Support/ngrok/ngrok.yml (macOS)-# ~/.config/ngrok/ngrok.yml (Linux)-version: '3'-tunnels:- app:- proto: http- addr: 8010- domain: <you>-posthog.ngrok.dev # a domain you've reserved in the ngrok dashboard- host_header: localhost # REQUIRED — see "How requests flow" above-agent:- authtoken: <your-ngrok-authtoken>+```bash+ngrok config add-authtoken <your-ngrok-authtoken>```+Set the reserved URL in `.env.local`:+```bash-ngrok start --all+SITE_URL=https://<you>-posthog.ngrok.dev```+`hogli start` detects an ngrok `SITE_URL` and starts the tunnel for you. It creates a temporary ngrok configuration that forwards to **8010** and rewrites the upstream Host header to `localhost`.+Verify the tunnel reaches Django through Caddy:```bash@@ -168,16 +162,8 @@ curl -sS https://<you>-posthog.ngrok.dev/_preflight | jq '.slack_service'````SITE_URL` must point at your tunnel for the OAuth step (Step 5), or the redirect goes to-`https://localhost:8010/...` and the browser fails with an SSL error. It only matters during-OAuth, so you don't have to commit it to `.env` — a plain `export` in the shell that runs the-stack is enough, and the connected integration keeps working afterwards (until you re-auth) even-if you drop it:--```bash-export SITE_URL=https://<you>-posthog.ngrok.dev # then (re)start the stack from this shell-```--Put it in `.env` instead if you want it to survive restarts from a fresh shell.+`https://localhost:8010/...` and the browser fails with an SSL error. Put it in `.env.local` so+it is available every time you run `hogli start`.> There's also an `NGROK_URL` env var that `redirect_uri()` checks before `SITE_URL` in DEBUG —> it would override just the OAuth redirect and leave `SITE_URL` alone. We used `SITE_URL` anddiff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c38a561667ed..f6a73af52bbe 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -286,8 +286,8 @@ export const FEATURE_FLAGS = {CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analyticsCUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analyticsDASHBOARD_AUTO_PREVIEW_LIMIT: 'dashboard-auto-preview-limit', // owner: @pauldambra #team-product-analytics- DASHBOARD_EXPORT_NUDGE: 'dashboard-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported a dashboard toward a recurring subscriptionDASHBOARD_CUSTOMIZATION: 'dashboard-customization', // owner: @MattPua #team-analytics-platform+ DASHBOARD_EXPORT_NUDGE: 'dashboard-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported a dashboard toward a recurring subscriptionDASHBOARD_INLINE_TILE_INSERTION: 'dashboard-inline-tile-insertion', // owner: @MattPua #team-analytics-platformDASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platformDASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,new@@ -497,6 +497,7 @@ export const FEATURE_FLAGS = {SHOW_REPLAY_FILTERS_FEEDBACK_BUTTON: 'show-replay-filters-feedback-button', // owner: @ksvat #team-replaySIGNUP_AA_TEST_4_WAY: 'signup-aa-test-4-way', // owner: @andehen #team-experiments multivariate=control,test-1,test-2,test-3SLACK_DWH: 'slack-dwh', // owner: @MarconLP #team-warehouse-sources+ SLACK_WORKFLOW_TRIGGERS: 'slack-workflow-triggers', // owner: #team-workflows-cdpSQL_EDITOR_BI_MODE: 'sql-editor-bi-mode', // owner: @mariusandra #team-data-toolsSQL_EDITOR_LAZY_SCHEMA: 'sql-editor-lazy-schema', // owner: @mariusandra #team-data-toolsSQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeusdiff --git a/hogli.yaml b/hogli.yamlindex 3a44087f9038..1c60b05b6304 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -17,6 +17,7 @@ config:# name, not bin_script:, so exclude it from auto-discovery to stop the manifest# regenerating a stub entry on every hogli run.- phrocs+ - start-local-ngrokenv:files:- .env.developmentdiff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.tsindex 3c795c884dea..e79990c73c8f 100644--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts@@ -10,6 +10,7 @@ import { captureException } from '~/common/utils/posthog'import { HealthCheckResult, PluginsServerConfig } from '../../types'import { isManagedAlertInternalEvent } from '../managed-alert-events'import { CdpInternalEventSchema } from '../schema'+import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'@@ -17,17 +18,29 @@ import { convertInternalEventToHogFunctionInvocationGlobals } from '../utils'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'+const SLACK_MESSAGE_RECEIVED_EVENT = '$slack_message_received'++// The event that starts each trigger type. Type alone would match every other signal on this topic.+const INTERNAL_EVENT_TRIGGER_EVENTS = new Map([['slack-message', SLACK_MESSAGE_RECEIVED_EVENT]])+export class CdpInternalEventsConsumer extends CdpConsumerBase {protected name = 'CdpInternalEventsConsumer'protected hogTypes: HogFunctionTypeType[] = ['internal_destination']protected hogQueue: JobQueue+ protected hogflowQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFunctionPipeline: HogFunctionInvocationPipeline+ private hogFlowPipeline: HogFlowInvocationPipeline- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, hogQueue: JobQueue) {+ constructor(+ config: PluginsServerConfig,+ deps: CdpConsumerBaseDeps,+ jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue }+ ) {super(config, deps)- this.hogQueue = hogQueue+ this.hogQueue = jobQueues.hogQueue+ this.hogflowQueue = jobQueues.hogflowQueuethis.kafkaConsumer = createKafkaConsumer({groupId: 'cdp-internal-events-consumer',topic: KAFKA_CDP_INTERNAL_EVENTS,@@ -43,6 +56,17 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {redis: this.redis,valkeyShadow: this.valkeyShadow,})+ this.hogFlowPipeline = new HogFlowInvocationPipeline(config, {+ hogFlowManager: this.hogFlowManager,+ hogFlowExecutor: this.hogFlowExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })}public async processBatch(@@ -54,32 +78,53 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {await this.groupsManager.addGroupsToGlobalsList(invocationGlobals)- const invocationsToBeQueued = await this.hogFunctionPipeline.buildInvocations(invocationGlobals, {- hogTypes: this.hogTypes,- filterFn: () => true,- invocationFilterFn: (fn, globals) => {- if (!isManagedAlertInternalEvent(globals.event.event)) {- return true- }- const alertId = globals.event.properties?.alert_id- return Boolean(- typeof alertId === 'string' &&- fn.filters?.events?.some((event) => event.id === globals.event.event) &&- fn.filters?.properties?.some(- (property) =>- property.type === 'event' &&- property.key === 'alert_id' &&- property.operator === 'exact' &&- property.value === alertId- )- )- },- })+ const ownSlackMessages = await this.findOwnSlackMessages(invocationGlobals)++ const [hogInvocations, hogflowInvocations] = await Promise.all([+ this.hogFunctionPipeline.buildInvocations(invocationGlobals, {+ hogTypes: this.hogTypes,+ filterFn: () => true,+ invocationFilterFn: (fn, globals) => {+ if (!isManagedAlertInternalEvent(globals.event.event)) {+ return true+ }+ const alertId = globals.event.properties?.alert_id+ return Boolean(+ typeof alertId === 'string' &&+ fn.filters?.events?.some((event) => event.id === globals.event.event) &&+ fn.filters?.properties?.some(+ (property) =>+ property.type === 'event' &&+ property.key === 'alert_id' &&+ property.operator === 'exact' &&+ property.value === alertId+ )+ )+ },+ }),+ this.hogFlowPipeline.buildInvocations(invocationGlobals, {+ eligibilityFn: (flow, globals) =>+ INTERNAL_EVENT_TRIGGER_EVENTS.get(flow.trigger.type) === globals.event.event &&+ !ownSlackMessages.has(globals),+ }),+ ])++ const invocationsToBeQueued = [...hogInvocations, ...hogflowInvocations]++ // Emit a `running` lifecycle row per freshly-created invocation so the runs UI shows these as+ // in-flight, matching the event and warehouse consumers. The terminal row is queued later by+ // the cyclotron worker; both collapse under the same `invocation_id` via ReplacingMergeTree.+ for (const invocation of hogflowInvocations) {+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')+ }return {backgroundTask: Promise.all([instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>- this.hogQueue.queueInvocations(invocationsToBeQueued)+ this.hogQueue.queueInvocations(hogInvocations)+ ),+ instrumentFn({ key: 'cdp.background_task.queue_hogflow_invocations', sendException: false }, () =>+ this.hogflowQueue.queueInvocations(hogflowInvocations)),instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {try {@@ -89,11 +134,49 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {logger.error('🔴', 'Error producing queued messages for monitoring', { err })}}),+ instrumentFn({ key: 'cdp.background_task.lifecycle_running_flush', sendException: false }, () =>+ this.invocationResultsService.invocationResultsRowsService.flush()+ ),]),invocations: invocationsToBeQueued,}}+ /**+ * Slack messages PostHog's own app posted, resolved through the integration the emit stamped+ * on the event.+ *+ * A workflow that replies in Slack sees its own reply arrive back on this topic, so without+ * this it retriggers itself forever. This is part of eligibility rather than a trigger's stored+ * filters, which a workflow created through the API or MCP would not carry.+ */+ private async findOwnSlackMessages(+ invocationGlobals: HogFunctionInvocationGlobals[]+ ): Promise<Set<HogFunctionInvocationGlobals>> {+ const candidates = invocationGlobals.filter(+ (globals) =>+ globals.event.event === SLACK_MESSAGE_RECEIVED_EVENT &&+ typeof globals.event.properties.app_id === 'string' &&+ typeof globals.event.properties.integration_id === 'number'+ )++ if (!candidates.length) {+ return new Set()+ }++ const integrations = await this.deps.integrationManager.getMany([+ ...new Set(candidates.map((globals) => globals.event.properties.integration_id as number)),+ ])++ return new Set(+ candidates.filter(+ (globals) =>+ integrations[globals.event.properties.integration_id as number]?.config?.app_id ===+ globals.event.properties.app_id+ )+ )+ }+@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const events: HogFunctionInvocationGlobals[] = []@@ -103,12 +186,13 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {const kafkaEvent = parseJSON(message.value!.toString()) as unknownconst event = CdpInternalEventSchema.parse(kafkaEvent)- const [teamHogFunctions, team] = await Promise.all([+ const [teamHogFunctions, teamHogFlows, team] = await Promise.all([this.hogFunctionManager.getHogFunctionsForTeam(event.team_id, this.hogTypes),+ this.hogFlowManager.getHogFlowsForTeam(event.team_id),this.deps.teamManager.getTeam(event.team_id),])- if (!teamHogFunctions.length || !team) {+ if ((!teamHogFunctions.length && !teamHogFlows.length) || !team) {return}@@ -125,7 +209,7 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {public override async start(): Promise<void> {await super.start()- await this.hogQueue.startAsProducer()+ await Promise.all([this.hogQueue.startAsProducer(), this.hogflowQueue.startAsProducer()])await this.kafkaConsumer.connect(async (messages) => {logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })return await instrumentFn('cdpConsumer.handleEachBatch', async () => {@@ -139,7 +223,7 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {public override async stop(): Promise<void> {logger.info('💤', 'Stopping consumer...')await this.kafkaConsumer.disconnect()- await this.hogQueue.stopProducer()+ await Promise.all([this.hogQueue.stopProducer(), this.hogflowQueue.stopProducer()])await super.stop()}diff --git a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.tsindex 5b32f5c56fc4..b6e64e241543 100644--- a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts@@ -1,13 +1,21 @@import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'import '../../../tests/helpers/mocks/producer.mock'+import { HogFlow } from '~/cdp/schema/hogflow'import { closeHub, createHub } from '~/common/utils/db/hub'import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'import { createOrganization, createTeam, getFirstTeam, getTeam, resetTestDatabase } from '../../../tests/helpers/sql'import { Hub, Team } from '../../types'+import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'-import { insertHogFunction as _insertHogFunction, createInternalEvent, createKafkaMessage } from '../_tests/fixtures'+import {+ insertHogFunction as _insertHogFunction,+ createInternalEvent,+ createKafkaMessage,+ insertIntegration,+} from '../_tests/fixtures'+import { insertHogFlow as _insertHogFlow } from '../_tests/fixtures-hogflows'import { HogWatcherState } from '../services/monitoring/hog-watcher.service'import { HogFunctionType } from '../types'import { CdpInternalEventsConsumer } from './cdp-internal-event.consumer'@@ -44,7 +52,10 @@ describe('CDP Internal Events Consumer', () => {jest.spyOn(hub.quotaLimiting, 'isTeamQuotaLimited').mockResolvedValue(false)const mockJobQueue = createMockJobQueue()- processor = new CdpInternalEventsConsumer(hub, createCdpConsumerDeps(hub), mockJobQueue)+ processor = new CdpInternalEventsConsumer(hub, createCdpConsumerDeps(hub), {+ hogQueue: mockJobQueue,+ hogflowQueue: mockJobQueue,+ })// Don't actually connect Kafka — test the core logic onlyprocessor['kafkaConsumer'] = {@@ -289,4 +300,104 @@ describe('CDP Internal Events Consumer', () => {expect(invocations.map((invocation) => invocation.functionId)).toEqual([fn.id])})})++ describe('hog flow invocations', () => {+ const buildHogFlow = (teamId: number, trigger: any): HogFlow =>+ new FixtureHogFlowBuilder()+ .withTeamId(teamId)+ // Always-true bytecode (return true), so the test is about eligibility, not filters+ .withSimpleWorkflow({ trigger: { ...trigger, filters: { properties: [], bytecode: ['_h', 29] } } })+ .build()++ const slackMessage = (teamId: number, properties: Record<string, any> = {}) =>+ createInternalEvent(teamId, {+ event: {+ timestamp: '2026-08-17T12:00:00.000Z',+ uuid: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',+ event: '$slack_message_received',+ distinct_id: 'U123',+ properties: { channel: 'C0ALERTS', text: 'database is on fire', ...properties },+ },+ })++ it('should start a workflow whose trigger is a slack message', async () => {+ const hogFlow = await _insertHogFlow(hub.postgres, buildHogFlow(team.id, { type: 'slack-message' }))++ const globals = await processor._parseKafkaBatch([createKafkaMessage(slackMessage(team.id))])+ expect(globals).toHaveLength(1)++ const { invocations } = await processor.processBatch(globals)+ const hogFlowInvocations = invocations.filter((i: any) => i.hogFlow)+ expect(hogFlowInvocations).toHaveLength(1)+ expect(hogFlowInvocations[0].functionId).toBe(hogFlow.id)+ })++ it('should not start a slack workflow from another signal on this topic', async () => {+ // Eligibility has to match the event as well as the trigger type. Error tracking, alerts+ // and activity logs all arrive here, and a workflow whose stored filters are empty (which+ // the API accepts) matches whatever it is handed — so trigger type alone fires on all of+ // them, with no channel or ts for a reply step to use.+ await _insertHogFlow(hub.postgres, buildHogFlow(team.id, { type: 'slack-message' }))++ const globals = await processor._parseKafkaBatch([+ createKafkaMessage(+ createInternalEvent(team.id, {+ event: {+ timestamp: '2026-08-17T12:00:00.000Z',+ uuid: 'aaaaaaaa-bbbb-cccc-dddd-ffffffffffff',+ event: '$insight_alert_firing',+ distinct_id: 'U123',+ properties: { alert_id: 'abc' },+ },+ })+ ),+ ])+ const { invocations } = await processor.processBatch(globals)++ expect(invocations.filter((i: any) => i.hogFlow)).toHaveLength(0)+ })++ it('should not start an event-triggered workflow', async () => {+ // Internal events share this topic with error tracking and activity log signals. An+ // event-triggered workflow expects those from analytics capture, so widening eligibility+ // to 'event' would fire every one of them.+ await _insertHogFlow(hub.postgres, buildHogFlow(team.id, { type: 'event' }))++ const globals = await processor._parseKafkaBatch([createKafkaMessage(slackMessage(team.id))])+ const { invocations } = await processor.processBatch(globals)++ expect(invocations.filter((i: any) => i.hogFlow)).toHaveLength(0)+ })++ it.each([+ ['PostHog posted the message', 'A0POSTHOG', 0],+ ['another app posted the message', 'A0OTHER', 1],+ ])('starts a workflow only when it did not post the message: %s', async (_name, appId, expected) => {+ // A workflow that replies in Slack sees its own reply arrive back on this topic. The+ // guard is part of eligibility, not the trigger's stored filters, so a workflow created+ // through the API or MCP still has it.+ const integration = await insertIntegration(hub.postgres, team.id, {+ kind: 'slack',+ config: { app_id: 'A0POSTHOG' },+ })+ await _insertHogFlow(hub.postgres, buildHogFlow(team.id, { type: 'slack-message' }))++ const globals = await processor._parseKafkaBatch([+ createKafkaMessage(slackMessage(team.id, { app_id: appId, integration_id: integration.id })),+ ])+ const { invocations } = await processor.processBatch(globals)++ expect(invocations.filter((i: any) => i.hogFlow)).toHaveLength(expected)+ })++ it('should parse a message for a team that has a hog flow but no hog functions', async () => {+ // The parse step used to drop any team with no internal_destination functions, which+ // would discard the event before the flow pipeline ever saw it.+ await _insertHogFlow(hub.postgres, buildHogFlow(team.id, { type: 'slack-message' }))++ const globals = await processor._parseKafkaBatch([createKafkaMessage(slackMessage(team.id))])++ expect(globals).toHaveLength(1)+ })+ })})diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex 4b3d25e5cec4..e1e6f1a4f99a 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -86,6 +86,14 @@ const HogFlowTriggerSchema = z.discriminatedUnion('type', [// Optional row column used as the masking / dedup key in place of distinct_idkey_property: z.string().optional(),}),+ z.object({+ type: z.literal('slack-message'),+ filters: z.object({+ // Message-property filters only. Channel is one of these rather than a field of its own,+ // so it composes with poster and text conditions instead of being matched separately.+ properties: z.array(z.any()).optional(),+ }),+ }),])export const HogFlowActionSchema = z.discriminatedUnion('type', [diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 3d0707bd1a68..2d64613d2518 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -177,7 +177,11 @@ export class HogFlowExecutorService {const trigger = hogFlow.trigger// Defensive: only the trigger types that carry `filters` make it through eligibility.- if (trigger.type !== 'event' && trigger.type !== 'data-warehouse-table') {+ if (+ trigger.type !== 'event' &&+ trigger.type !== 'data-warehouse-table' &&+ trigger.type !== 'slack-message'+ ) {continue}diff --git a/nodejs/src/cdp/templates/_destinations/slack/slack.template.test.ts b/nodejs/src/cdp/templates/_destinations/slack/slack.template.test.tsnew file mode 100644index 000000000000..f5aac99299f4--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/slack/slack.template.test.ts@@ -0,0 +1,97 @@+import { parseJSON } from '~/common/utils/json-parse'++import { TemplateTester } from '../../test/test-helpers'+import { template } from './slack.template'++describe('slack template', () => {+ const tester = new TemplateTester(template)++ const commonInputs = {+ slack_workspace: { access_token: 'xoxb-1234' },+ icon_emoji: ':hedgehog:',+ username: 'PostHog',+ channel: 'channel',+ blocks: [],+ text: 'hello',+ }++ // What the thread_ts input's description tells people to paste.+ const THREAD_TS_EXPRESSION = '{event.properties.thread_ts ?? event.properties.ts}'++ const slackMessage = (properties: Record<string, any> = {}): any => ({+ event: {+ event: '$slack_message_received',+ properties: { channel: 'C0ALERTS', ts: '1700000000.000100', thread_ts: null, ...properties },+ },+ })++ const bodyOf = (queueParameters: any): any => parseJSON(queueParameters.body)++ beforeEach(async () => {+ await tester.beforeEach()+ })++ it('should post a message', async () => {+ const response = await tester.invoke(commonInputs)++ expect(response.error).toBeUndefined()+ expect(response.invocation.queueParameters).toMatchObject({+ url: 'https://slack.com/api/chat.postMessage',+ method: 'POST',+ headers: {+ Authorization: 'Bearer xoxb-1234',+ 'Content-Type': 'application/json',+ },+ })+ expect(bodyOf(response.invocation.queueParameters)).toEqual({+ channel: 'channel',+ icon_emoji: ':hedgehog:',+ username: 'PostHog',+ blocks: [],+ text: 'hello',+ })++ const fetchResponse = await tester.invokeFetchResponse(response.invocation, {+ status: 200,+ body: { ok: true },+ })+ expect(fetchResponse.finished).toBe(true)+ expect(fetchResponse.error).toBeUndefined()+ })++ it.each([+ ['a top-level post, reply under that post', {}, '1700000000.000100'],+ ['a thread reply, reply in the same thread', { thread_ts: '1699999999.000000' }, '1699999999.000000'],+ ])('given %s', async (_name, properties, expected) => {+ const response = await tester.invoke(+ { ...commonInputs, thread_ts: THREAD_TS_EXPRESSION },+ slackMessage(properties)+ )++ expect(response.error).toBeUndefined()+ expect(bodyOf(response.invocation.queueParameters).thread_ts).toEqual(expected)+ })++ it.each([+ ['the input is unset', undefined],+ ['the input is empty', ''],+ // An event with no Slack timestamps resolves the expression to null, which must not be sent+ // either: Slack answers invalid_arguments instead of posting to the channel.+ ['the expression resolves to nothing', THREAD_TS_EXPRESSION],+ ])('should omit thread_ts when %s', async (_name, thread_ts) => {+ const response = await tester.invoke({ ...commonInputs, thread_ts })++ expect(response.error).toBeUndefined()+ expect(bodyOf(response.invocation.queueParameters)).not.toHaveProperty('thread_ts')+ })++ it.each([+ ['a non-200 status', { status: 400, body: { ok: true } }, "Failed to post message to Slack: 400: {'ok': true}"],+ ['ok: false', { status: 200, body: { ok: false } }, "Failed to post message to Slack: 200: {'ok': false}"],+ ])('should throw on %s', async (_name, fetchResponse, expectedError) => {+ let response = await tester.invoke(commonInputs)+ response = await tester.invokeFetchResponse(response.invocation, fetchResponse)++ expect(response.error).toEqual(expectedError)+ })+})diff --git a/nodejs/src/cdp/templates/_destinations/slack/slack.template.ts b/nodejs/src/cdp/templates/_destinations/slack/slack.template.tsnew file mode 100644index 000000000000..96c7e413f1f1--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/slack/slack.template.ts@@ -0,0 +1,135 @@+import { HogFunctionTemplate } from '~/cdp/types'++export const template: HogFunctionTemplate = {+ status: 'stable',+ free: true,+ type: 'destination',+ id: 'template-slack',+ name: 'Slack',+ description: 'Sends a message to a Slack channel',+ icon_url: '/static/services/slack.png',+ category: ['Customer Success'],+ code_language: 'hog',+ code: `+let body := {+ 'channel': inputs.channel,+ 'icon_emoji': inputs.icon_emoji,+ 'username': inputs.username,+ 'blocks': inputs.blocks,+ 'text': inputs.text+};++// Slack rejects an empty thread_ts, so only send it when there is one to reply under.+if (not empty(inputs.thread_ts)) {+ body['thread_ts'] := inputs.thread_ts;+}++let res := fetch('https://slack.com/api/chat.postMessage', {+ 'body': body,+ 'method': 'POST',+ 'headers': {+ 'Authorization': f'Bearer {inputs.slack_workspace.access_token}',+ 'Content-Type': 'application/json'+ }+});++if (res.status != 200 or res.body.ok == false) {+ throw Error(f'Failed to post message to Slack: {res.status}: {res.body}');+}+`.trim(),+ inputs_schema: [+ {+ key: 'slack_workspace',+ type: 'integration',+ integration: 'slack',+ label: 'Slack workspace',+ requiredScopes: 'channels:read groups:read chat:write chat:write.customize',+ secret: false,+ hidden: false,+ required: true,+ },+ {+ key: 'channel',+ type: 'integration_field',+ integration_key: 'slack_workspace',+ integration_field: 'slack_channel',+ label: 'Channel to post to',+ description:+ 'Select the channel to post to. Channel IDs (e.g. C0123ABC, returned by integrations-channels-retrieve) are preferred; #channel-name (e.g. #general) is also accepted. The PostHog app must be installed in the workspace. For private channels, the PostHog app must be a member of the channel.',+ secret: false,+ hidden: false,+ required: true,+ },+ {+ key: 'icon_emoji',+ type: 'string',+ label: 'Emoji icon',+ default: ':hedgehog:',+ required: false,+ secret: false,+ hidden: false,+ },+ {+ key: 'username',+ type: 'string',+ label: 'Bot name',+ default: 'PostHog',+ required: false,+ secret: false,+ hidden: false,+ },+ {+ key: 'blocks',+ type: 'json',+ label: 'Blocks',+ description: '(see https://api.slack.com/block-kit/building)',+ default: [+ {+ text: {+ text: "*{person.name}* triggered event: '{event.event}'",+ type: 'mrkdwn',+ },+ type: 'section',+ },+ {+ type: 'actions',+ elements: [+ {+ url: '{person.url}',+ text: { text: 'View Person in PostHog', type: 'plain_text' },+ type: 'button',+ },+ {+ url: '{source.url}',+ text: { text: 'Message source', type: 'plain_text' },+ type: 'button',+ },+ ],+ },+ ],+ secret: false,+ required: false,+ hidden: false,+ },+ {+ key: 'text',+ type: 'string',+ label: 'Plain text message',+ description: 'Optional fallback message if blocks are not provided or supported',+ default: "*{person.name}* triggered event: '{event.event}'",+ secret: false,+ required: false,+ hidden: false,+ },+ {+ key: 'thread_ts',+ type: 'string',+ label: 'Reply in thread',+ description:+ 'Timestamp of the message to reply under. Leave this empty to post a new message. In a workflow triggered by a Slack message, use {event.properties.thread_ts ?? event.properties.ts} to reply under the message that started the run.',+ secret: false,+ required: false,+ hidden: false,+ },+ ],+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex 1f2bcbfc29c0..28ee0ddcb2f0 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -35,6 +35,7 @@ import { template as posthogSetHogflowVariableTemplate } from './_destinations/pimport { template as pushTemplate } from './_destinations/push/push.template'import { template as redditAdsTemplate } from './_destinations/reddit_ads/reddit.template'import { template as retainTemplate } from './_destinations/retain/retain.template'+import { template as slackTemplate } from './_destinations/slack/slack.template'import { template as snapchatAdsTemplate } from './_destinations/snapchat_ads/snapchat.template'import { template as tiktokAdsTemplate } from './_destinations/tiktok_ads/tiktok.template'import { template as twilioTemplate } from './_destinations/twilio/twilio.template'@@ -64,6 +65,7 @@ import { template as logRedactAttributesTemplate } from './_transformations_log/export const HOG_FUNCTION_TEMPLATES_COMING_SOON: HogFunctionTemplate[] = allComingSoonTemplatesexport const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [+ slackTemplate,webhookTemplate,tiktokAdsTemplate,snapchatAdsTemplate,diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 8465fb97abbf..b2e614d3c240 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -192,7 +192,10 @@ export class PluginServer implements NodeServer {if (capabilities.cdpInternalEvents) {serviceLoaders.push(async () => {- const consumer = new CdpInternalEventsConsumer(this.config, cdpDeps!, kafkaQueue)+ const consumer = new CdpInternalEventsConsumer(this.config, cdpDeps!, {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })await consumer.start()return consumer.service})diff --git a/posthog/cdp/templates/__init__.py b/posthog/cdp/templates/__init__.pyindex c6c2c857ca77..a752cf7de149 100644--- a/posthog/cdp/templates/__init__.py+++ b/posthog/cdp/templates/__init__.py@@ -81,7 +81,6 @@ from .sendgrid.template_sendgrid import (TemplateSendGridMigrator,template as sendgrid,)-from .slack.template_slack import template as slackfrom .snapchat_ads.template_pixel import template_snapchat_pixel as snapchat_pixelfrom .tiktok_ads.template_tiktok_pixel import template_tiktok_pixel as tiktok_pixelfrom .userlist.template_userlist import template as userlist@@ -91,7 +90,6 @@ from .zendesk.template_zendesk import template as zendeskHOG_FUNCTION_TEMPLATES = [blank_site_destination,blank_site_app,- slack,activecampaign,airtable,attio,diff --git a/posthog/cdp/templates/slack/template_slack.py b/posthog/cdp/templates/fixtures.pysimilarity index 51%rename from posthog/cdp/templates/slack/template_slack.pyrename to posthog/cdp/templates/fixtures.pyindex 06b600eb648b..93d4fc08d973 100644--- a/posthog/cdp/templates/slack/template_slack.py+++ b/posthog/cdp/templates/fixtures.py@@ -1,6 +1,9 @@from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC-template: HogFunctionTemplateDC = HogFunctionTemplateDC(+# The Slack destination itself lives in nodejs (nodejs/src/cdp/templates/_destinations/slack). Tests+# that need a real destination template in the database sync this stand-in instead of reaching out to+# the plugin server. It does not have to track the nodejs template field for field.+template_slack = HogFunctionTemplateDC(status="stable",free=True,type="destination",@@ -14,8 +17,6 @@ template: HogFunctionTemplateDC = HogFunctionTemplateDC(let res := fetch('https://slack.com/api/chat.postMessage', {'body': {'channel': inputs.channel,- 'icon_emoji': inputs.icon_emoji,- 'username': inputs.username,'blocks': inputs.blocks,'text': inputs.text},@@ -47,58 +48,14 @@ if (res.status != 200 or res.body.ok == false) {"integration_key": "slack_workspace","integration_field": "slack_channel","label": "Channel to post to",- "description": "Select the channel to post to. Channel IDs (e.g. C0123ABC, returned by integrations-channels-retrieve) are preferred; #channel-name (e.g. #general) is also accepted. The PostHog app must be installed in the workspace. For private channels, the PostHog app must be a member of the channel.","secret": False,"hidden": False,"required": True,},- {- "key": "icon_emoji",- "type": "string",- "label": "Emoji icon",- "default": ":hedgehog:",- "required": False,- "secret": False,- "hidden": False,- },- {- "key": "username",- "type": "string",- "label": "Bot name",- "default": "PostHog",- "required": False,- "secret": False,- "hidden": False,- },{"key": "blocks","type": "json","label": "Blocks",- "description": "(see https://api.slack.com/block-kit/building)",- "default": [- {- "text": {- "text": "*{person.name}* triggered event: '{event.event}'",- "type": "mrkdwn",- },- "type": "section",- },- {- "type": "actions",- "elements": [- {- "url": "{person.url}",- "text": {"text": "View Person in PostHog", "type": "plain_text"},- "type": "button",- },- {- "url": "{source.url}",- "text": {"text": "Message source", "type": "plain_text"},- "type": "button",- },- ],- },- ],"secret": False,"required": False,"hidden": False,@@ -107,8 +64,14 @@ if (res.status != 200 or res.body.ok == false) {"key": "text","type": "string","label": "Plain text message",- "description": "Optional fallback message if blocks are not provided or supported",- "default": "*{person.name}* triggered event: '{event.event}'",+ "secret": False,+ "required": False,+ "hidden": False,+ },+ {+ "key": "thread_ts",+ "type": "string",+ "label": "Reply in thread","secret": False,"required": False,"hidden": False,diff --git a/posthog/cdp/templates/slack/test_template_slack.py b/posthog/cdp/templates/slack/test_template_slack.pydeleted file mode 100644index 08f9d2e82362..000000000000--- a/posthog/cdp/templates/slack/test_template_slack.py+++ /dev/null@@ -1,62 +0,0 @@-import pytest--from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest-from posthog.cdp.templates.slack.template_slack import template as template_slack--from common.hogvm.python.utils import UncaughtHogVMException---class TestTemplateSlack(BaseHogFunctionTemplateTest):- template = template_slack-- def _inputs(self, **kwargs):- inputs = {- "slack_workspace": {- "access_token": "xoxb-1234",- },- "icon_emoji": ":hedgehog:",- "username": "PostHog",- "channel": "channel",- "blocks": [],- }- inputs.update(kwargs)- return inputs-- def test_function_works(self):- self.mock_fetch_response = lambda *args: {"status": 200, "body": {"ok": True}} # type: ignore- res = self.run_function(self._inputs())-- assert res.result is None-- assert self.get_mock_fetch_calls()[0] == (- "https://slack.com/api/chat.postMessage",- {- "body": {- "channel": "channel",- "icon_emoji": ":hedgehog:",- "username": "PostHog",- "blocks": [],- "text": None,- },- "method": "POST",- "headers": {- "Authorization": "Bearer xoxb-1234",- "Content-Type": "application/json",- },- },- )-- assert self.get_mock_print_calls() == []-- def test_function_prints_warning_on_bad_status(self):- self.mock_fetch_response = lambda *args: {"status": 400, "body": {"ok": True}} # type: ignore- with pytest.raises(UncaughtHogVMException) as e:- self.run_function(self._inputs())-- assert e.value.message == "Failed to post message to Slack: 400: {'ok': true}"-- def test_function_prints_warning_on_bad_body(self):- self.mock_fetch_response = lambda *args: {"status": 200, "body": {"ok": False}} # type: ignore- with pytest.raises(UncaughtHogVMException) as e:- self.run_function(self._inputs())- assert e.value.message == "Failed to post message to Slack: 200: {'ok': false}"diff --git a/posthog/management/commands/sync_hog_function_templates.py b/posthog/management/commands/sync_hog_function_templates.pyindex 90fd83d877a4..8a3f3299cba4 100644--- a/posthog/management/commands/sync_hog_function_templates.py+++ b/posthog/management/commands/sync_hog_function_templates.py@@ -24,7 +24,6 @@ TYPES_WITH_JAVASCRIPT_SOURCE = (HogFunctionType.SITE_DESTINATION, HogFunctionTyp# Templates to include in test modeTEST_INCLUDE_PYTHON_TEMPLATE_IDS = [- "template-slack","template-warehouse-source-stripe","template-warehouse-source-customer-io","template-warehouse-source-slack",@@ -32,6 +31,7 @@ TEST_INCLUDE_PYTHON_TEMPLATE_IDS = ["template-warehouse-source-default",]TEST_INCLUDE_NODEJS_TEMPLATE_IDS = [+ "template-slack","template-webhook","template-geoip","plugin-posthog-plugin-geoip",diff --git a/posthog/management/commands/test/test_sync_hog_function_templates.py b/posthog/management/commands/test/test_sync_hog_function_templates.pyindex c8cbe8d787f4..8a981fb54053 100644--- a/posthog/management/commands/test/test_sync_hog_function_templates.py+++ b/posthog/management/commands/test/test_sync_hog_function_templates.py@@ -159,28 +159,21 @@ class TestSyncHogFunctionTemplates:call_command("sync_hog_function_templates")- # Find the slack template in HOG_FUNCTION_TEMPLATES- slack_template = next((t for t in HOG_FUNCTION_TEMPLATES if t.id == TEST_INCLUDE_PYTHON_TEMPLATE_IDS[0]), None)- assert slack_template is not None, (- f"Template {TEST_INCLUDE_PYTHON_TEMPLATE_IDS[0]} not found in HOG_FUNCTION_TEMPLATES"- )+ python_template = next(t for t in HOG_FUNCTION_TEMPLATES if t.type in TYPES_WITH_JAVASCRIPT_SOURCE)# Check that the template was stored correctly- db_template = HogFunctionTemplate.objects.get(template_id=slack_template.id)+ db_template = HogFunctionTemplate.objects.get(template_id=python_template.id)# Verify core template fields- assert db_template.name == slack_template.name- assert db_template.code == slack_template.code- assert db_template.type == slack_template.type+ assert db_template.template_id == python_template.id+ assert db_template.name == python_template.name+ assert db_template.code == python_template.code+ assert db_template.type == python_template.type# Only check bytecode if it's not a JavaScript templateif db_template.type not in TYPES_WITH_JAVASCRIPT_SOURCE:assert db_template.bytecode is not None- assert db_template.template_id == slack_template.id- assert db_template.name == slack_template.name- assert db_template.code == slack_template.code-@patch("posthog.plugins.plugin_server_api.get_hog_function_templates")def test_template_version_behavior(self, mock_get_hog_function_templates):"""Test that template versioning behaves correctly"""diff --git a/posthog/models/test/test_hog_function_template.py b/posthog/models/test/test_hog_function_template.pyindex e92a60b1f724..9c5a39495a24 100644--- a/posthog/models/test/test_hog_function_template.py+++ b/posthog/models/test/test_hog_function_template.py@@ -1,7 +1,7 @@from django.test import TestCase+from posthog.cdp.templates.fixtures import template_slack as slack_templatefrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as slack_templatefrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatediff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.pyindex 4a5170638b10..a4132cf96275 100644--- a/posthog/settings/__init__.py+++ b/posthog/settings/__init__.py@@ -81,6 +81,11 @@ INSTANCE_TAG: str = os.getenv("INSTANCE_TAG", "none")# empty to use the real Slack email while keeping DEBUG on. Ignored outside DEBUG.SLACK_APP_LOCAL_DEV_EMAIL: str = os.getenv("SLACK_APP_LOCAL_DEV_EMAIL", "[email protected]")+# Forward every Slack channel message onto the internal events topic, where a workflow with a Slack+# trigger can pick it up. Off by default: this is the only thing admitting the full channel+# firehose, so it doubles as the kill switch.+SLACK_WORKFLOW_TRIGGERS_ENABLED: bool = get_from_env("SLACK_WORKFLOW_TRIGGERS_ENABLED", False, type_cast=str_to_bool)+# Vapi voice-AI integration (used by user_interviews to host public interview pages).VAPI_PUBLIC_KEY: str = os.getenv("VAPI_PUBLIC_KEY", "")VAPI_ASSISTANT_ID: str = os.getenv("VAPI_ASSISTANT_ID", "")diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 547e86ed8637..1a5c632232f2 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -484,6 +484,10 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"label": "Conversation ticket priority changed","description": "Fires when the priority of a support conversation ticket changes.",},+ "$slack_message_received": {+ "label": "Slack message received",+ "description": "Fires when a message is posted in a Slack channel PostHog is connected to.",+ },},"elements": {"tag_name": {diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex ab3e7edae150..25173b7b5bd9 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -10,9 +10,9 @@ from django.db import connectionfrom parameterized import parameterizedfrom rest_framework import status+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.helpers import mock_transpilefrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom products.actions.backend.models.action import Actionfrom products.cdp.backend.api.hog_function import (diff --git a/products/cdp/backend/api/test/test_hog_function_templates.py b/products/cdp/backend/api/test/test_hog_function_templates.pyindex 5576f08bddf2..c12b3b6e43c0 100644--- a/products/cdp/backend/api/test/test_hog_function_templates.py+++ b/products/cdp/backend/api/test/test_hog_function_templates.py@@ -6,8 +6,8 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTesfrom parameterized import parameterizedfrom rest_framework import status+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuediff --git a/products/customer_analytics/backend/test/test_event_stream.py b/products/customer_analytics/backend/test/test_event_stream.pyindex c935b60274ed..132001e31ff1 100644--- a/products/customer_analytics/backend/test/test_event_stream.py+++ b/products/customer_analytics/backend/test/test_event_stream.py@@ -6,8 +6,8 @@ from django.core.cache import cachefrom rest_framework import statusfrom slack_sdk.errors import SlackApiError+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.constants import AvailableFeaturefrom posthog.models import Integration, Organization, OrganizationMembership, Teamdiff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 2d35e38fea6c..aa90e9cea864 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -11,9 +11,9 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.cdp.templates.microsoft_teams.template_microsoft_teams import template as template_microsoft_teams-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.clickhouse.client import sync_executefrom posthog.models.team.team import Teamfrom posthog.models.user import Userdiff --git a/products/replay_vision/backend/tests/test_vision_action_delivery.py b/products/replay_vision/backend/tests/test_vision_action_delivery.pyindex 7332c0e7ab3d..72349275ea4c 100644--- a/products/replay_vision/backend/tests/test_vision_action_delivery.py+++ b/products/replay_vision/backend/tests/test_vision_action_delivery.py@@ -5,8 +5,8 @@ from unittest.mock import patchfrom parameterized import parameterized+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.models import Teamfrom posthog.models.integration import Integrationdiff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.pyindex 76a243e476af..627e95507c2f 100644--- a/products/replay_vision/backend/tests/test_vision_actions_api.py+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py@@ -7,8 +7,8 @@ from django.test import SimpleTestCasefrom parameterized import parameterized+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.models import Organization, Teamfrom posthog.models.integration import Integrationdiff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 7ad8e1349e52..49ae470277a4 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -105,6 +105,7 @@ from products.slack_app.backend.slack_link_unfurl import (link_url_region,parse_posthog_resource_link,)+from products.slack_app.backend.slack_workflow_events import emit_slack_message_eventlogger = structlog.get_logger(__name__)@@ -2016,6 +2017,22 @@ def route_posthog_code_event_to_relevant_region()if event_type in ("app_mention", "message"):+ # Above every drop below, because a workflow trigger watches a whole channel: the top-level+ # posts the follow-up pipeline discards are the ones it exists for. Emitting here rather+ # than inside that pipeline keeps the two independent.+ if event_type == "message":+ should_try_other_region = emit_slack_message_event(+ event,+ slack_team_id,+ event_id=event_id,+ is_ext_shared_channel=is_ext_shared_channel,+ )+ # The emit sees only this region's connections, and the drops below end a top-level post+ # before the pipeline's region gate could forward it. No US-precedence probe: for a+ # channel trigger, whichever region holds the connection should run the workflow.+ if should_try_other_region and not proxied and cross_region_routing_enabled():+ return _proxy_event_and_return_route(request, other_domain)+if event_type == "app_mention":ignore_reason = _app_mention_ignore_reason(event)if ignore_reason:@@ -2045,7 +2062,7 @@ def route_posthog_code_event_to_relevant_region(message_ts=event.get("ts"),)return ROUTE_HANDLED_LOCALLY- # Top-level channel posts dominate the wire volume; drop before any DB hit.+ # Top-level channel posts dominate the wire volume; drop before the pipeline's DB hits.top_level_thread_ts = event.get("thread_ts")if not isinstance(top_level_thread_ts, str) or top_level_thread_ts == event.get("ts"):return ROUTE_HANDLED_LOCALLYdiff --git a/products/slack_app/backend/slack_workflow_events.py b/products/slack_app/backend/slack_workflow_events.pynew file mode 100644index 000000000000..ddff96a7c8b8--- /dev/null+++ b/products/slack_app/backend/slack_workflow_events.py@@ -0,0 +1,126 @@+"""Forward Slack channel messages onto the internal events topic.++Deliberately dumb: check Slack is telling us about a new post, resolve the PostHog projects behind+the Slack workspace, then write the message out as-is. A workflow's trigger config decides what it+wants, and the CDP consumer evaluates that, so nothing here needs to know a trigger exists.+"""++import uuid+from typing import Any++from django.conf import settings++import structlog++from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event+from posthog.models.integration import Integration++logger = structlog.get_logger(__name__)++SLACK_MESSAGE_RECEIVED_EVENT = "$slack_message_received"++# Slack labels edits, deletions and joins `message` too, and those retrigger a workflow's own reply.+# `bot_message` stays in: "apps and bots only" is a trigger mode.+_TRIGGERING_SUBTYPES: frozenset[str | None] = frozenset(+ {None, "bot_message", "file_share", "me_message", "thread_broadcast"}+)++# Fixed namespace so the event uuid is a pure function of (team, Slack event id). Slack redelivers+# on any non-2xx, and the handler's retry guard only covers the copies that carry the retry header.+_SLACK_EVENT_NAMESPACE = uuid.UUID("6f1a4b3c-0d2e-4f6a-9b5c-8e7d1a2f3b4c")+++def _event_properties(+ event: dict[str, Any], slack_team_id: str, *, integration_id: int, is_ext_shared_channel: bool+) -> dict[str, Any]:+ thread_ts = event.get("thread_ts")+ return {+ # The PostHog Slack connection this copy belongs to. The CDP consumer reads its stored+ # app id from here to recognize, and ignore, a message PostHog itself posted.+ "integration_id": integration_id,+ "channel": event.get("channel"),+ "channel_type": event.get("channel_type"),+ "slack_team_id": slack_team_id,+ "user": event.get("user"),+ "bot_id": event.get("bot_id"),+ "app_id": event.get("app_id"),+ "subtype": event.get("subtype"),+ "text": event.get("text"),+ "ts": event.get("ts"),+ "thread_ts": thread_ts,+ # Property filters compare a property against a constant, never against another property,+ # so "is this a reply" is unexpressible from thread_ts and ts alone.+ "is_thread_reply": isinstance(thread_ts, str) and thread_ts != event.get("ts"),+ "is_ext_shared_channel": is_ext_shared_channel,+ # Anything a step wants that the flat fields above don't cover, blocks and attachments most+ # of all: an alerting app posts Block Kit, so its text is often empty.+ "slack_event": event,+ }+++def emit_slack_message_event(+ event: dict[str, Any],+ slack_team_id: str,+ *,+ event_id: str | None,+ is_ext_shared_channel: bool,+) -> bool:+ """Write one internal event per PostHog project connected to this Slack workspace.++ Returns whether the event still needs a home: True only when a workflow could have triggered on+ it and no connection in this region holds the workspace. The caller turns that into a+ cross-region hand-off. Every other outcome is False, including the cases where there was nothing+ to emit at all, so a disabled setting or an edit never costs a hop.++ Never raises. This runs inside the Slack event webhook, which owes Slack an ack within three+ seconds and shares the handler with mention routing, so a failure here has to cost neither.+ """+ if not settings.SLACK_WORKFLOW_TRIGGERS_ENABLED:+ return False++ if event.get("subtype") not in _TRIGGERING_SUBTYPES:+ return False++ try:+ # A Slack workspace can be connected to several projects (the unique constraint on+ # Integration is per team), and each configures its own workflows, so every one gets a copy.+ # Projects with nothing listening are discarded by the CDP consumer, which is cheaper than+ # asking Postgres here.+ integrations = list(+ Integration.objects.filter(kind="slack", integration_id=slack_team_id).values_list("team_id", "id")+ )+ except Exception:+ # Stay put on a lookup failure: handing the workspace over would turn a local database blip+ # into a cross-region hop for every message in every channel.+ logger.exception("slack_workflow_event_integration_lookup_failed", slack_team_id=slack_team_id)+ return False++ distinct_id = str(event.get("user") or event.get("bot_id") or event.get("channel") or slack_team_id)++ for team_id, integration_id in integrations:+ try:+ produce_internal_event(+ team_id,+ InternalEventEvent(+ event=SLACK_MESSAGE_RECEIVED_EVENT,+ distinct_id=distinct_id,+ properties=_event_properties(+ event,+ slack_team_id,+ integration_id=integration_id,+ is_ext_shared_channel=is_ext_shared_channel,+ ),+ uuid=str(uuid.uuid5(_SLACK_EVENT_NAMESPACE, f"{team_id}:{event_id or ''}")),+ ),+ )+ except Exception:+ # Deliberately not flushed or waited on — the delivery callback runs in the background,+ # and blocking here would spend the Slack ack budget on Kafka.+ logger.exception(+ "slack_workflow_event_produce_failed",+ slack_team_id=slack_team_id,+ team_id=team_id,+ event_id=event_id,+ )++ return not integrationsdiff --git a/products/slack_app/backend/tests/test_slack_workflow_events.py b/products/slack_app/backend/tests/test_slack_workflow_events.pynew file mode 100644index 000000000000..b5d0929327d6--- /dev/null+++ b/products/slack_app/backend/tests/test_slack_workflow_events.py@@ -0,0 +1,115 @@+import pytest+from unittest.mock import patch++from posthog.models.integration import Integration+from posthog.models.team.team import Team++from products.slack_app.backend.slack_workflow_events import emit_slack_message_event++# Matches the workspace_integration fixture in conftest.+SLACK_TEAM_ID = "T12345"++MESSAGE_EVENT = {+ "type": "message",+ "channel": "C0ALERTS",+ "channel_type": "channel",+ "user": "U123",+ "text": "database is on fire",+ "ts": "1700000000.000100",+}+++def produce():+ with patch("products.slack_app.backend.slack_workflow_events.produce_internal_event") as mock:+ yield mock++[email protected]("enabled", [True, False])+def test_setting_gates_the_emit(produce, workspace_integration, enabled) -> None:+ with patch("django.conf.settings.SLACK_WORKFLOW_TRIGGERS_ENABLED", enabled):+ emit_slack_message_event(MESSAGE_EVENT, SLACK_TEAM_ID, event_id="Ev1", is_ext_shared_channel=False)++ assert produce.call_count == (1 if enabled else 0)+++def test_emits_once_per_connected_project(produce, org_team_user, workspace_integration) -> None:+ org, first_team, _ = org_team_user+ second_team = Team.objects.create(organization=org, name="Second")+ second_integration = Integration.objects.create(+ team=second_team,+ kind="slack",+ integration_id=SLACK_TEAM_ID,+ sensitive_config={"access_token": "xoxb-test"},+ )++ with patch("django.conf.settings.SLACK_WORKFLOW_TRIGGERS_ENABLED", True):+ emit_slack_message_event(MESSAGE_EVENT, SLACK_TEAM_ID, event_id="Ev1", is_ext_shared_channel=False)++ assert {call.args[0] for call in produce.call_args_list} == {first_team.pk, second_team.pk}+ # Same Slack event, different projects: the uuids have to differ or the second project's run+ # would be discarded as a duplicate of the first.+ assert len({call.args[1].uuid for call in produce.call_args_list}) == 2+ # The consumer resolves this back to a stored app id to recognize a message PostHog posted, and+ # each project has its own connection.+ assert {call.args[1].properties["integration_id"] for call in produce.call_args_list} == {+ workspace_integration.pk,+ second_integration.pk,+ }+++ "subtype,emitted",+ [+ (None, True),+ ("bot_message", True),+ ("file_share", True),+ ("message_changed", False),+ ("message_deleted", False),+ ("channel_join", False),+ ],+)+def test_only_a_new_post_is_emitted(produce, workspace_integration, subtype, emitted) -> None:+ event = MESSAGE_EVENT if subtype is None else {**MESSAGE_EVENT, "subtype": subtype}++ with patch("django.conf.settings.SLACK_WORKFLOW_TRIGGERS_ENABLED", True):+ emit_slack_message_event(event, SLACK_TEAM_ID, event_id="Ev1", is_ext_shared_channel=False)++ assert produce.call_count == (1 if emitted else 0)+++def test_emits_nothing_for_an_unconnected_workspace(produce, workspace_integration) -> None:+ with patch("django.conf.settings.SLACK_WORKFLOW_TRIGGERS_ENABLED", True):+ emit_slack_message_event(MESSAGE_EVENT, "T-OTHER-REGION", event_id="Ev1", is_ext_shared_channel=False)++ produce.assert_not_called()+++def test_properties_carry_what_a_filter_needs(produce, workspace_integration) -> None:+ event = {**MESSAGE_EVENT, "thread_ts": "1699999999.000000", "bot_id": "B42"}++ with patch("django.conf.settings.SLACK_WORKFLOW_TRIGGERS_ENABLED", True):+ emit_slack_message_event(event, SLACK_TEAM_ID, event_id="Ev1", is_ext_shared_channel=True)++ properties = produce.call_args.args[1].properties+ assert properties["channel"] == "C0ALERTS"+ assert properties["bot_id"] == "B42"+ assert properties["is_ext_shared_channel"] is True+ assert properties["is_thread_reply"] is True+ assert properties["slack_event"] == event+++def test_a_top_level_post_is_not_a_thread_reply(produce, workspace_integration) -> None:+ event = {**MESSAGE_EVENT, "thread_ts": MESSAGE_EVENT["ts"]}++ with patch("django.conf.settings.SLACK_WORKFLOW_TRIGGERS_ENABLED", True):+ emit_slack_message_event(event, SLACK_TEAM_ID, event_id="Ev1", is_ext_shared_channel=False)++ assert produce.call_args.args[1].properties["is_thread_reply"] is False+++def test_a_kafka_failure_does_not_reach_the_webhook(produce, workspace_integration) -> None:+ produce.side_effect = RuntimeError("kafka is down")++ with patch("django.conf.settings.SLACK_WORKFLOW_TRIGGERS_ENABLED", True):+ emit_slack_message_event(MESSAGE_EVENT, SLACK_TEAM_ID, event_id="Ev1", is_ext_shared_channel=False)diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.pyindex 189c0bd9ba33..15f409bbba5f 100644--- a/products/slack_app/backend/tests/test_thread_message_routing.py+++ b/products/slack_app/backend/tests/test_thread_message_routing.py@@ -128,11 +128,11 @@ class TestRouteThreadMessage(TestCase):defaults.update(overrides)return defaults- def _route(self, event: dict) -> str:+ def _route(self, event: dict, slack_team_id: str = "T_SLACK") -> str:from products.slack_app.backend.api import route_posthog_code_event_to_relevant_regionrequest = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")- return route_posthog_code_event_to_relevant_region(request, event, "T_SLACK")+ return route_posthog_code_event_to_relevant_region(request, event, slack_team_id)# --- Cheap pre-DB gates ------------------------------------------------@@ -179,6 +179,34 @@ class TestRouteThreadMessage(TestCase):assert result == ROUTE_HANDLED_LOCALLYmock_start.assert_not_called()+ # --- Workflow trigger region hand-off ----------------------------------++ @parameterized.expand(+ [+ ("owned here", "T_SLACK", None, False),+ ("owned by the other region", "T_OTHER_REGION", None, True),+ # Nothing to trigger on, so no reason to spend a hop looking for a region that wants it.+ ("an edit, owned by the other region", "T_OTHER_REGION", "message_changed", False),+ ]+ )+ @override_settings(SLACK_WORKFLOW_TRIGGERS_ENABLED=True)+ def test_top_level_post_reaches_the_region_owning_the_workspace(self, _name, slack_team_id, subtype, expect_proxy):+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, ROUTE_PROXIED++ # thread_ts == ts, so a top-level post+ event = self._make_event(thread_ts="1001.0000")+ if isinstance(subtype, str):+ event["subtype"] = subtype+ with (+ patch("products.slack_app.backend.api.cross_region_routing_enabled", return_value=True),+ patch("products.slack_app.backend.api._proxy_event_to_region") as mock_proxy,+ patch("products.slack_app.backend.slack_workflow_events.produce_internal_event"),+ ):+ result = self._route(event, slack_team_id=slack_team_id)++ assert result == (ROUTE_PROXIED if expect_proxy else ROUTE_HANDLED_LOCALLY)+ assert mock_proxy.called is expect_proxy+# --- Mapping + FF gate -------------------------------------------------def test_thread_without_mapping_dropped(self):diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 3b212b60c0b0..d6f207928ebb 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -112,6 +112,7 @@ from products.workflows.backend.api.publish_impact import build_publish_impactfrom products.workflows.backend.models.hog_flow.hog_flow import (BILLABLE_ACTION_TYPES,PERSON_DEPENDENT_ACTION_TYPES,+ ROW_SCOPED_TRIGGER_TYPES,SUPPORTED_ACTION_TYPES,TRIGGER_TYPES,HogFlow,@@ -740,6 +741,26 @@ def _should_validate_strictly(context: dict, is_draft: Optional[bool]) -> bool:return source is not None and source != EventSource.WEB+def _normalize_slack_channel_filters(filters: dict) -> None:+ """Reduce a `channel` filter value to the bare Slack channel id, in place.++ The channel picker identifies a channel as ``C123|#name``, but the event carries ``C123``, so+ storing the picker's value verbatim compiles a filter that can never match. The frontend strips+ it too; this is here because the same dead filter is one API or MCP call away otherwise.+ """+ properties = filters.get("properties")+ if not isinstance(properties, list):+ return+ for prop in properties:+ if not isinstance(prop, dict) or prop.get("key") != "channel":+ continue+ value = prop.get("value")+ if isinstance(value, str):+ prop["value"] = value.split("|")[0]+ elif isinstance(value, list):+ prop["value"] = [item.split("|")[0] if isinstance(item, str) else item for item in value]++def _existing_email_from_by_action(instance: "HogFlow") -> dict[str, list[dict]]:"""Stored email sender overrides keyed by action id, live and draft variants both kept.@@ -1016,7 +1037,11 @@ class HogFlowActionSerializer(serializers.Serializer):config = HogFlowActionConfigField(help_text=("Type-specific config keyed by action type. "- "trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and "+ "trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel|slack-message, filters?}. "+ "slack-message runs once per message posted in a connected Slack channel, and takes only "+ "filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, "+ "subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. "+ "webhook and ""manual triggers also require template_id: 'template-source-webhook', and tracking_pixel ""requires template_id: 'template-source-webhook-pixel'. ""filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], "@@ -1234,6 +1259,25 @@ class HogFlowActionSerializer(serializers.Serializer):else:serializer.is_valid(raise_exception=True)data["config"]["filters"] = serializer.validated_data+ elif data.get("config", {}).get("type") == "slack-message":+ # Everything the trigger selects on — channel, poster, text, thread — is a property+ # of the Slack message, so there is no config beyond the filters. The event name is+ # fixed, which is what makes an events/actions entry here meaningless.+ filters = data.get("config", {}).get("filters", {}) or {}+ if not isinstance(filters, dict):+ raise serializers.ValidationError({"filters": "Filters must be a dictionary."})+ filters.pop("events", None)+ filters.pop("actions", None)+ _normalize_slack_channel_filters(filters)+ # Left on the default "events" source: the internal event is event-shaped, so+ # property filters compile against event.properties.* with no special casing.+ serializer = HogFunctionFiltersSerializer(data=filters, context=self.context)+ if is_draft:+ if serializer.is_valid():+ data["config"]["filters"] = serializer.validated_data+ else:+ serializer.is_valid(raise_exception=True)+ data["config"]["filters"] = serializer.validated_dataelse:if strict:raise serializers.ValidationError({"config": "Invalid trigger type"})@@ -2124,12 +2168,13 @@ class HogFlowSerializer(HogFlowMinimalSerializer):data["trigger"] = trigger_actions[0]["config"]- # Warehouse-triggered workflows are person-less ("row-scoped"): one run per synced row with no- # associated person. Person-dependent steps and person-aware exit conditions would silently- # assume person data, so we block them here — the serializer is the source of truth, so the API,- # MCP, and frontend can't bypass it. We force exit_only_at_end since the other exit conditions- # re-evaluate trigger/conversion filters that may reference person properties.- if data["trigger"].get("type") == "data-warehouse-table":+ # Some triggers are person-less ("row-scoped"): a synced warehouse row and a Slack poster are+ # both things no PostHog person is attached to. Person-dependent steps and person-aware exit+ # conditions would silently assume person data, so we block them here — the serializer is the+ # source of truth, so the API, MCP, and frontend can't bypass it. We force exit_only_at_end+ # since the other exit conditions re-evaluate trigger/conversion filters that may reference+ # person properties.+ if data["trigger"].get("type") in ROW_SCOPED_TRIGGER_TYPES:data["exit_condition"] = HogFlow.ExitCondition.ONLY_AT_ENDif not is_draft:offending_types = sorted(@@ -2143,8 +2188,9 @@ class HogFlowSerializer(HogFlowMinimalSerializer):raise serializers.ValidationError({"actions": (- "These step types rely on person data, which is unavailable for data warehouse "- f"table triggers: {', '.join(offending_types)}"+ "These step types rely on person data, which a "+ f"{data['trigger'].get('type')} trigger has none of: "+ f"{', '.join(offending_types)}")})diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 51fd561def4a..6accb83e1ac4 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -13,8 +13,8 @@ from django.test import override_settingsfrom parameterized import parameterizedfrom rest_framework import status+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.constants import AvailableFeaturefrom posthog.event_usage import EventSourcefrom posthog.models import Organization, OrganizationMembership, Team, User@@ -2324,6 +2324,35 @@ class TestHogFlowAPI(APIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)assert response.status_code == 201, response.json()+ def test_hog_flow_slack_trigger_stores_the_bare_channel_id(self):+ # The channel picker identifies a channel as `C123|#name`, but the event carries `C123`, so+ # storing the composite compiles a filter that never matches and the workflow never runs.+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "slack-message",+ "filters": {+ "properties": [+ {+ "key": "channel",+ "value": ["C0ALERTS|#alerts"],+ "operator": "exact",+ "type": "event",+ }+ ]+ },+ },+ }++ hog_flow = {"name": "Test Slack Flow", "status": "active", "actions": [trigger_action]}++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()+ stored = response.json()["trigger"]["filters"]["properties"][0]["value"]+ assert stored == ["C0ALERTS"]+def test_hog_flow_data_warehouse_table_trigger_forces_exit_only_at_end(self):# Other exit conditions re-evaluate trigger/conversion filters that may reference person# data, so warehouse-triggered flows are coerced to exit_only_at_end regardless of input.diff --git a/products/workflows/backend/api/test/test_hog_flow_template.py b/products/workflows/backend/api/test/test_hog_flow_template.pyindex 73c7f0b90fcb..81ffb1cc0667 100644--- a/products/workflows/backend/api/test/test_hog_flow_template.py+++ b/products/workflows/backend/api/test/test_hog_flow_template.py@@ -4,8 +4,8 @@ from posthog.test.base import APIBaseTestfrom rest_framework import status+from posthog.cdp.templates.fixtures import template_slackfrom posthog.cdp.templates.hog_function_template import sync_template_to_db-from posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.models import Organization, Team, Userfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESdiff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.pyindex ae98beaa5d90..ab5ba395b5e9 100644--- a/products/workflows/backend/models/hog_flow/hog_flow.py+++ b/products/workflows/backend/models/hog_flow/hog_flow.py@@ -42,7 +42,9 @@ SUPPORTED_ACTION_TYPES: Final[list[str]] = [# Callers confuse the two (a stored workflow had an action of type "webhook", which is a trigger# kind), so the rejection message can say which mistake was made. Mirrors HogFlowTriggerSchema in# nodejs/src/cdp/schema/hogflow.ts.-TRIGGER_TYPES: Final[frozenset[str]] = frozenset({"event", "schedule", "manual", "batch", "tracking_pixel", "webhook"})+TRIGGER_TYPES: Final[frozenset[str]] = frozenset(+ {"event", "schedule", "manual", "batch", "tracking_pixel", "webhook", "data-warehouse-table", "slack-message"}+)# Billable action types that are subject to rate limiting and quota tracking# These action types incur costs and are counted against customer quotas@@ -61,6 +63,14 @@ PERSON_DEPENDENT_ACTION_TYPES: Final[set[str]] = {"random_cohort_branch",}+# Trigger types that start a run with no person attached: a synced warehouse row and a Slack message+# are both authored by something PostHog has no person record for. Keep in sync with the frontend's+# ROW_SCOPED_TRIGGER_TYPES.+ROW_SCOPED_TRIGGER_TYPES: Final[set[str]] = {+ "data-warehouse-table",+ "slack-message",+}+class HogFlow(UUIDTModel):"""diff --git a/products/workflows/backend/test/test_slack_trigger_filters.py b/products/workflows/backend/test/test_slack_trigger_filters.pynew file mode 100644index 000000000000..3a8a4ddfee05--- /dev/null+++ b/products/workflows/backend/test/test_slack_trigger_filters.py@@ -0,0 +1,111 @@+import json+from typing import Any++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from parameterized import parameterized++from posthog.hogql.compiler.bytecode import create_bytecode++from posthog.cdp.filters import hog_function_filters_to_expr++from common.hogvm.python.execute import execute_bytecode++SLACK_MESSAGE_GLOBALS: dict[str, Any] = {+ "event": "$slack_message_received",+ "properties": {+ "channel": "C0ALERTS",+ "channel_type": "channel",+ "slack_team_id": "T123",+ "user": "U123",+ "bot_id": None,+ "app_id": None,+ "subtype": None,+ "text": "the database is on fire",+ "ts": "1700000000.000100",+ "thread_ts": None,+ "is_thread_reply": False,+ "is_ext_shared_channel": False,+ },+}+++def _event(**overrides):+ return {**SLACK_MESSAGE_GLOBALS, "properties": {**SLACK_MESSAGE_GLOBALS["properties"], **overrides}}+++def _prop(key, value, operator):+ return {"key": key, "value": value, "operator": operator, "type": "event"}+++class TestSlackTriggerFilters(ClickhouseTestMixin, APIBaseTest):+ """The trigger editor writes property filters, the engine runs their bytecode. These check the+ two actually agree, which is what the editor's own round-trip tests can't see."""++ def _matches(self, properties: list[dict], globals: dict | None = None) -> bool:+ expr = hog_function_filters_to_expr(filters={"properties": properties}, team=self.team, actions={})+ bytecode = json.loads(json.dumps(create_bytecode(expr).bytecode))+ return execute_bytecode(bytecode, globals or SLACK_MESSAGE_GLOBALS).result is True++ def test_channel_filter_matches_the_bare_id(self):+ assert self._matches([_prop("channel", ["C0ALERTS"], "exact")])++ def test_channel_filter_does_not_match_the_picker_composite(self):+ # The picker identifies a channel as `C123|#name`; storing that verbatim compiled a filter+ # that could never match, and the editor's round-trip tests were blind to it.+ assert not self._matches([_prop("channel", ["C0ALERTS|#alerts"], "exact")])++ @parameterized.expand(+ [+ ("a person posted", {}, True),+ ("an app posted", {"bot_id": "B42"}, False),+ ]+ )+ def test_people_only_excludes_apps(self, _name, overrides, expected):+ assert self._matches([_prop("bot_id", "is_not_set", "is_not_set")], _event(**overrides)) is expected++ @parameterized.expand(+ [+ ("an app posted", {"bot_id": "B42"}, True),+ ("a person posted", {}, False),+ ]+ )+ def test_apps_only_excludes_people(self, _name, overrides, expected):+ assert self._matches([_prop("bot_id", "is_set", "is_set")], _event(**overrides)) is expected++ @parameterized.expand(+ [+ ("a listed user", {"user": "U123"}, True),+ ("someone else", {"user": "U999"}, False),+ ]+ )+ def test_specific_people(self, _name, overrides, expected):+ assert self._matches([_prop("user", ["U123", "U456"], "exact")], _event(**overrides)) is expected++ @parameterized.expand(+ [+ ("a top-level post", {"thread_ts": None}, True),+ ("a thread reply", {"thread_ts": "1699999999.000000"}, False),+ ]+ )+ def test_ignoring_thread_replies_keys_off_thread_ts(self, _name, overrides, expected):+ # Matching on the is_thread_reply boolean instead would compare a bool against a string and+ # never fire, so the editor deliberately writes this one against thread_ts.+ assert self._matches([_prop("thread_ts", "is_not_set", "is_not_set")], _event(**overrides)) is expected++ @parameterized.expand(+ [+ ("matching text", {"text": "the database is on fire"}, True),+ ("other text", {"text": "deploy finished"}, False),+ ]+ )+ def test_message_text_contains(self, _name, overrides, expected):+ assert self._matches([_prop("text", ["fire"], "icontains")], _event(**overrides)) is expected++ def test_filters_combine_with_and(self):+ properties = [+ _prop("channel", ["C0ALERTS"], "exact"),+ _prop("bot_id", "is_not_set", "is_not_set"),+ ]+ assert self._matches(properties)+ assert not self._matches(properties, _event(bot_id="B42"))diff --git a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsxindex 8b99ad44c8d4..c6435a5c6f32 100644--- a/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx+++ b/products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters.tsx@@ -57,6 +57,8 @@ export type HogFlowFiltersProps = {taxonomicGroupTypes?: TaxonomicFilterGroupType[]propertyAllowList?: AllowedPropertiespropertyDefinitionsOverride?: PropertyDefinition[]+ /** Extra options to offer in the taxonomic filter, for events whose properties aren't stored. */+ taxonomicFilterOptionsFromProp?: Record<string, { name: string }[]>staticValueOptions?: (propertyKey: string) => PropValue[] | nullinline?: booleanallowNew?: boolean@@ -138,6 +140,7 @@ export function HogFlowPropertyFilters({taxonomicGroupTypes,propertyAllowList,propertyDefinitionsOverride,+ taxonomicFilterOptionsFromProp: taxonomicFilterOptionsFromPropOverride,staticValueOptions,buttonCopy,inline,@@ -156,6 +159,7 @@ export function HogFlowPropertyFilters({[TaxonomicFilterGroupType.WorkflowVariables]: (workflow?.variables ?? []).map((variable) => ({name: variable.key,})),+ ...taxonomicFilterOptionsFromPropOverride,}const isDataWarehouse = !!dataWarehouseTableNamereturn (diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsxindex 867887b8dccf..5efecc103ffc 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx@@ -715,6 +715,12 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {actions?: any[] | undefined@@ -857,6 +863,12 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {actions?: any[] | undefined@@ -1509,6 +1521,12 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {actions?: any[] | undefined@@ -1651,6 +1669,12 @@ export interface hogFlowEditorLogicActions {| {type: 'schedule'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {actions?: any[] | undefineddiff --git a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.tsindex e80981f1ec09..3caf6c2ec630 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/panel/testing/hogFlowEditorTestLogic.ts@@ -375,6 +375,12 @@ export interface hogFlowEditorTestLogicMeta {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {properties?: any[] | undefined@@ -491,6 +497,12 @@ export interface hogFlowEditorTestLogicMeta {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {properties?: any[] | undefineddiff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.tsindex f41587592d85..80be7034364f 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts@@ -1,4 +1,5 @@import './conversations'import './customer_analytics'import './data_warehouse_table'+import './slack'import './surveys'diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.test.tsnew file mode 100644index 000000000000..3ae2aca40992--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.test.ts@@ -0,0 +1,125 @@+import './slack'++import { PropertyOperator } from '~/types'++import { SlackPosterMode, decodeSlackFilters, encodeSlackFilters } from './slackTriggerFilters'+import { getRegisteredTriggerTypes } from './triggerTypeRegistry'++describe('slack message trigger', () => {+ const getTriggerType = (): ReturnType<typeof getRegisteredTriggerTypes>[number] => {+ const triggerType = getRegisteredTriggerTypes().find((t) => t.value === 'slack-message')+ if (!triggerType) {+ throw new Error('Slack message trigger type not registered')+ }+ return triggerType+ }++ describe('filters round-trip', () => {+ it.each<{ name: string; mode: SlackPosterMode; ids: string[] }>([+ { name: 'anyone', mode: 'anyone', ids: [] },+ { name: 'people only', mode: 'people', ids: [] },+ { name: 'apps and bots only', mode: 'apps', ids: [] },+ { name: 'specific people', mode: 'specific_people', ids: ['U01ABCDEF'] },+ { name: 'specific apps', mode: 'specific_apps', ids: ['A01ABCDEF'] },+ ])('survives a save and reload for $name', ({ mode, ids }) => {+ // The editor reads its controls back out of the stored filters, so a mode that encodes+ // to something decode can't recognize silently resets the control on reopen.+ const filters = {+ channel: 'C0ALERTS',+ posterMode: mode,+ posterIds: ids,+ topLevelOnly: true,+ additional: [],+ }+ expect(decodeSlackFilters(encodeSlackFilters(filters))).toEqual(filters)+ })++ it('keeps filters the native controls do not own', () => {+ const custom = { key: 'text', value: ['fire'], operator: PropertyOperator.IContains, type: 'event' }+ const encoded = encodeSlackFilters({+ channel: 'C0ALERTS',+ posterMode: 'people',+ posterIds: [],+ topLevelOnly: false,+ additional: [custom],+ })++ expect(encoded).toContainEqual(custom)+ expect(decodeSlackFilters(encoded).additional).toEqual([custom])+ })++ it('reduces the picker composite to a channel id', () => {+ // The picker round-trips `C123|#name`; the event carries `C123`, so storing the+ // composite compiles a filter that matches nothing.+ const encoded = encodeSlackFilters({+ channel: 'C0ALERTS|#alerts',+ posterMode: 'anyone',+ posterIds: [],+ topLevelOnly: false,+ additional: [],+ })+ expect(decodeSlackFilters(encoded).channel).toBe('C0ALERTS')+ })++ it('separates top-level posts on thread_ts, not the boolean', () => {+ // is_thread_reply is a real boolean on the event, and comparing it against a string+ // would never match. Absence of thread_ts is what marks a top-level post.+ const encoded = encodeSlackFilters({+ channel: null,+ posterMode: 'anyone',+ posterIds: [],+ topLevelOnly: true,+ additional: [],+ })+ expect(encoded).toContainEqual(+ expect.objectContaining({ key: 'thread_ts', operator: PropertyOperator.IsNotSet })+ )+ })++ it.each<SlackPosterMode>(['specific_people', 'specific_apps'])(+ 'keeps %s selected before any id is typed',+ (mode) => {+ // The control re-derives from the stored filters on every render, so a mode that+ // encodes to nothing snaps straight back to "anyone" the moment you pick it.+ const encoded = encodeSlackFilters({+ channel: null,+ posterMode: mode,+ posterIds: [],+ topLevelOnly: false,+ additional: [],+ })+ expect(decodeSlackFilters(encoded).posterMode).toBe(mode)+ }+ )+ })++ describe('registry entry', () => {+ it.each([+ { name: 'no channel filter', properties: [], valid: false },+ { name: 'channel filter present', properties: [{ key: 'channel', value: ['C0ALERTS'] }], valid: true },+ { name: 'other filters alone', properties: [{ key: 'text', value: ['fire'] }], valid: false },+ ])('validate returns valid=$valid for $name', ({ properties, valid }) => {+ const result = getTriggerType().validate!({ type: 'slack-message', filters: { properties } } as any)+ expect(result?.valid).toBe(valid)+ })++ it('validate returns null for a non slack-message config', () => {+ expect(getTriggerType().validate!({ type: 'event', filters: {} } as any)).toBeNull()+ })++ it('is gated behind the slack-workflow-triggers feature flag', () => {+ expect(getTriggerType().featureFlag).toBe('slack-workflow-triggers')+ })++ it('buildConfig produces a config recognized by matchConfig', () => {+ const triggerType = getTriggerType()+ const config = triggerType.buildConfig()+ expect(config.type).toBe('slack-message')+ expect(triggerType.matchConfig!(config)).toBe(true)+ })++ it('defaults to people only so a workflow cannot retrigger on its own message', () => {+ expect(decodeSlackFilters(getTriggerType().buildConfig().filters.properties).posterMode).toBe('people')+ })+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.tsxnew file mode 100644index 000000000000..6305233652fd--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slack.tsx@@ -0,0 +1,225 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonInputSelect, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'++import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'+import { IconSlack } from 'lib/lemon-ui/icons'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { Link } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import { PropertyDefinition, PropertyDefinitionType, PropertyType } from '~/types'++import { HogFlowPropertyFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters'+import { registerTriggerType } from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry'+import { workflowLogic } from 'products/workflows/frontend/Workflows/workflowLogic'++import { HogFlowAction } from '../../types'+import {+ SLACK_POSTER_MODE_OPTIONS,+ SlackPosterMode,+ decodeSlackFilters,+ encodeSlackFilters,+} from './slackTriggerFilters'++export type SlackMessageTriggerConfig = {+ type: 'slack-message'+ filters: {+ properties?: any[]+ }+}++export function isSlackMessageTriggerConfig(+ config: Extract<HogFlowAction, { type: 'trigger' }>['config']+): config is SlackMessageTriggerConfig {+ return config.type === 'slack-message'+}++// Slack messages never reach ClickHouse, so the advanced list has no stored values to+// autocomplete from and the properties have to be declared.+const ADVANCED_PROPERTIES: { key: string; type: PropertyType }[] = [+ { key: 'text', type: PropertyType.String },+ { key: 'subtype', type: PropertyType.String },+ { key: 'channel_type', type: PropertyType.String },+ { key: 'is_thread_reply', type: PropertyType.Boolean },+ { key: 'is_ext_shared_channel', type: PropertyType.Boolean },+]++const ADVANCED_PROPERTY_DEFINITIONS: PropertyDefinition[] = ADVANCED_PROPERTIES.map(({ key, type }) => ({+ id: `slack-message-${key}`,+ name: key,+ type: PropertyDefinitionType.Event,+ property_type: type,+}))++const POSTER_ID_PLACEHOLDER: Record<SlackPosterMode, string> = {+ anyone: '',+ people: '',+ apps: '',+ specific_people: 'Slack user IDs, e.g. U01ABCDEF',+ specific_apps: 'Slack app IDs, e.g. A01ABCDEF',+}++function StepTriggerConfigurationSlackMessage({ node }: { node: any }): JSX.Element {+ const { setWorkflowActionConfig } = useActions(workflowLogic)+ const { actionValidationErrorsById } = useValues(workflowLogic)+ const { slackIntegrations, integrationsLoading } = useValues(integrationsLogic)++ const config = node.data.config as SlackMessageTriggerConfig+ const filters = decodeSlackFilters(config.filters?.properties)+ const validationResult = actionValidationErrorsById[node.data.id]+ const integrations = slackIntegrations ?? []+ const wantsIds = filters.posterMode === 'specific_people' || filters.posterMode === 'specific_apps'++ const update = (changes: Partial<typeof filters>): void => {+ setWorkflowActionConfig(node.data.id, {+ type: 'slack-message',+ filters: { properties: encodeSlackFilters({ ...filters, ...changes }) },+ })+ }++ if (integrationsLoading) {+ return <p className="mb-0 text-sm text-muted-alt">Loading Slack connections…</p>+ }++ if (integrations.length === 0) {+ return (+ <LemonBanner type="warning" className="w-full">+ <p className="mb-0">+ This trigger needs a Slack connection, and this project doesn't have one yet. Connect Slack, invite+ the bot to a channel, then come back and pick it.{' '}+ <Link to={urls.settings('project-integrations')} className="font-semibold">+ Connect Slack+ </Link>+ </p>+ </LemonBanner>+ )+ }++ return (+ <div className="flex flex-col gap-2 w-full">+ <p className="mb-0 text-sm text-muted-alt">+ This workflow runs once for each message posted in the channel you pick. Runs have no associated person,+ so person-dependent steps are unavailable.+ </p>++ <LemonField.Pure+ label="Channel"+ error={validationResult?.errors?.channel}+ info="PostHog only receives messages from channels the Slack bot has been invited to."+ >+ <SlackChannelPicker+ integration={integrations[0]}+ value={filters.channel ?? undefined}+ onChange={(value) => update({ channel: value })}+ />+ </LemonField.Pure>++ <LemonField.Pure+ label="Who can start a run"+ info="Messages posted by PostHog never start a run, so a workflow can reply in Slack without triggering itself."+ >+ <LemonSelect<SlackPosterMode>+ value={filters.posterMode}+ options={SLACK_POSTER_MODE_OPTIONS.map(({ value, label, description }) => ({+ value,+ label,+ labelInMenu: (+ <div className="flex flex-col py-1">+ <span>{label}</span>+ <span className="text-xs text-muted-alt">{description}</span>+ </div>+ ),+ }))}+ onChange={(posterMode) => update({ posterMode, posterIds: [] })}+ data-attr="slack-trigger-poster-mode"+ />+ </LemonField.Pure>++ {wantsIds && (+ <LemonField.Pure+ label={filters.posterMode === 'specific_people' ? 'Slack user IDs' : 'Slack app IDs'}+ error={validationResult?.errors?.posterIds}+ info="Find an ID from the member or app profile in Slack, under 'Copy member ID' or the app's About tab."+ >+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={filters.posterIds}+ options={filters.posterIds.map((id) => ({ key: id, label: id }))}+ placeholder={POSTER_ID_PLACEHOLDER[filters.posterMode]}+ onChange={(posterIds) => update({ posterIds })}+ data-attr="slack-trigger-poster-ids"+ />+ </LemonField.Pure>+ )}++ <LemonSwitch+ checked={filters.topLevelOnly}+ onChange={(topLevelOnly) => update({ topLevelOnly })}+ label="Ignore replies inside threads"+ bordered+ data-attr="slack-trigger-top-level-only"+ />++ <LemonField.Pure label="Additional filters" info="Match on the message text, subtype, or other fields.">+ <HogFlowPropertyFilters+ filtersKey={`slack-message-trigger-${node.data.id}`}+ filters={{ properties: filters.additional }}+ setFilters={(next) => update({ additional: next?.properties ?? [] })}+ taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}+ propertyAllowList={{+ [TaxonomicFilterGroupType.EventProperties]: ADVANCED_PROPERTIES.map((p) => p.key),+ }}+ propertyDefinitionsOverride={ADVANCED_PROPERTY_DEFINITIONS}+ taxonomicFilterOptionsFromProp={{+ [TaxonomicFilterGroupType.EventProperties]: ADVANCED_PROPERTIES.map((p) => ({ name: p.key })),+ }}+ inline+ />+ </LemonField.Pure>+ </div>+ )+}++registerTriggerType({+ value: 'slack-message',+ label: 'Slack message posted',+ icon: <IconSlack />,+ description: 'Trigger when someone posts in a Slack channel',+ group: 'Slack',+ featureFlag: 'slack-workflow-triggers',+ matchConfig: (config) => isSlackMessageTriggerConfig(config),+ buildConfig: () => ({+ type: 'slack-message',+ filters: {+ properties: encodeSlackFilters({+ channel: null,+ posterMode: 'people',+ posterIds: [],+ topLevelOnly: true,+ additional: [],+ }),+ },+ }),+ validate: (config): { valid: boolean; errors: Record<string, string> } | null => {+ if (config.type !== 'slack-message') {+ return null+ }+ const filters = decodeSlackFilters(config.filters?.properties)+ if (!filters.channel) {+ return { valid: false, errors: { channel: 'Please pick a Slack channel' } }+ }+ const wantsIds = filters.posterMode === 'specific_people' || filters.posterMode === 'specific_apps'+ if (wantsIds && !filters.posterIds.length) {+ return {+ valid: false,+ errors: { posterIds: 'Add at least one Slack ID, or the trigger will never fire' },+ }+ }+ return { valid: true, errors: {} }+ },+ ConfigComponent: StepTriggerConfigurationSlackMessage,+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/slackTriggerFilters.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slackTriggerFilters.tsnew file mode 100644index 000000000000..87b1de2be41a--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/slackTriggerFilters.ts@@ -0,0 +1,138 @@+import { PropertyFilterType, PropertyOperator } from '~/types'++/** Who is allowed to start a run. Each mode compiles to exactly one property filter. */+export type SlackPosterMode = 'anyone' | 'people' | 'specific_people' | 'apps' | 'specific_apps'++export const SLACK_POSTER_MODE_OPTIONS: { value: SlackPosterMode; label: string; description: string }[] = [+ {+ value: 'people',+ label: 'People only',+ description: 'Skips anything posted by an app or bot.',+ },+ {+ value: 'specific_people',+ label: 'Specific people',+ description: 'Only messages from the Slack users you list.',+ },+ {+ value: 'apps',+ label: 'Apps and bots only',+ description: 'For alerts posted by another tool rather than typed by a person.',+ },+ {+ value: 'specific_apps',+ label: 'Specific apps',+ description: 'Only messages from the Slack apps you list.',+ },+ {+ value: 'anyone',+ label: 'Anyone',+ description: 'Every message in the channel, from people and from other apps.',+ },+]++/**+ * Property keys the native controls own. Anything else a person adds survives untouched in the+ * advanced list, so the two editors never fight over the same entry.+ */+const OWNED_KEYS = new Set(['channel', 'user', 'bot_id', 'app_id', 'thread_ts'])++export interface SlackTriggerFilters {+ channel: string | null+ posterMode: SlackPosterMode+ posterIds: string[]+ topLevelOnly: boolean+ additional: Record<string, any>[]+}++/** The picker round-trips a channel as `C123|#name`, but the event carries the bare id. */+export function channelId(value: string): string {+ return value.split('|')[0]+}++function find(properties: Record<string, any>[], key: string): Record<string, any> | undefined {+ return properties.find((property) => property?.key === key)+}++function values(entry: Record<string, any> | undefined): string[] {+ if (!entry) {+ return []+ }+ const value = Array.isArray(entry.value) ? entry.value : [entry.value]+ return value.filter((item: unknown): item is string => typeof item === 'string' && item !== '')+}++function exact(key: string, value: string[]): Record<string, any> {+ return { key, value, operator: PropertyOperator.Exact, type: PropertyFilterType.Event }+}++function presence(key: string, operator: PropertyOperator): Record<string, any> {+ return { key, value: operator, operator, type: PropertyFilterType.Event }+}++export function decodeSlackFilters(properties: Record<string, any>[] | undefined): SlackTriggerFilters {+ const list = Array.isArray(properties) ? properties : []+ const channelEntry = find(list, 'channel')+ const user = find(list, 'user')+ const appId = find(list, 'app_id')+ const botId = find(list, 'bot_id')+ const threadTs = find(list, 'thread_ts')++ let posterMode: SlackPosterMode = 'anyone'+ let posterIds: string[] = []+ // Keyed on the entry existing, not on it having values: the mode is chosen before any id is+ // typed, and reading the values would snap the control back to "anyone" while you fill it in.+ if (user) {+ posterMode = 'specific_people'+ posterIds = values(user)+ } else if (appId) {+ posterMode = 'specific_apps'+ posterIds = values(appId)+ } else if (botId?.operator === PropertyOperator.IsSet) {+ posterMode = 'apps'+ } else if (botId?.operator === PropertyOperator.IsNotSet) {+ posterMode = 'people'+ }++ return {+ channel: values(channelEntry).length ? channelId(values(channelEntry)[0]) : null,+ posterMode,+ posterIds,+ topLevelOnly: threadTs?.operator === PropertyOperator.IsNotSet,+ additional: list.filter((property) => !OWNED_KEYS.has(property?.key)),+ }+}++export function encodeSlackFilters(filters: SlackTriggerFilters): Record<string, any>[] {+ const properties: Record<string, any>[] = []++ if (filters.channel) {+ properties.push(exact('channel', [channelId(filters.channel)]))+ }++ switch (filters.posterMode) {+ case 'people':+ properties.push(presence('bot_id', PropertyOperator.IsNotSet))+ break+ case 'apps':+ properties.push(presence('bot_id', PropertyOperator.IsSet))+ break+ case 'specific_people':+ properties.push(exact('user', filters.posterIds))+ break+ case 'specific_apps':+ properties.push(exact('app_id', filters.posterIds))+ break+ case 'anyone':+ break+ }++ if (filters.topLevelOnly) {+ // A top-level post carries no thread_ts, so absence is what separates it from a reply.+ // Avoids comparing against the boolean is_thread_reply, where a string/bool mismatch+ // would silently never match.+ properties.push(presence('thread_ts', PropertyOperator.IsNotSet))+ }++ return [...properties, ...filters.additional]+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.tsindex 86992185791f..63b708014cca 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts@@ -103,6 +103,12 @@ export interface stepDelayLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {condition: {filters?:@@ -347,6 +353,12 @@ export interface stepDelayLogicActions {}[]delay_duration?: string | undefined}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {actions?: any[] | undefineddiff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.tsindex dcc6a45e824b..e62d41765d80 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts@@ -144,6 +144,12 @@ export interface stepWaitUntilTimeWindowLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {condition: {filters?:@@ -389,6 +395,12 @@ export interface stepWaitUntilTimeWindowLogicActions {}[]delay_duration?: string | undefined}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {actions?: any[] | undefineddiff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.tsindex 95d1b8dfa5e9..570e81ae954b 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts@@ -179,6 +179,13 @@ export const HogFlowTriggerSchema = z.discriminatedUnion('type', [}),key_property: z.string().optional(),}),+ z.object({+ type: z.literal('slack-message'),+ filters: z.object({+ // Message properties only, channel included — see the trigger registry entry+ properties: z.array(z.any()).optional(),+ }),+ }),])/** Trigger types that use HogFlowSchedule for recurring execution */diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 3c4cc3bc95ac..6e51b31e3bd8 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -112,6 +112,10 @@ export const NEW_WORKFLOW: HogFlow = {// data-warehouse-table triggers. Module-scoped to avoid reallocating on every selector recompute.export const PERSON_DEPENDENT_ACTION_TYPES = new Set(['wait_until_condition', 'random_cohort_branch'])+// Trigger types whose runs have no person attached. Keep in sync with the backend's+// ROW_SCOPED_TRIGGER_TYPES, which is the authoritative check.+export const ROW_SCOPED_TRIGGER_TYPES = new Set(['data-warehouse-table', 'slack-message'])+function getTemplatingError(value: string, templating?: 'liquid' | 'hog'): string | undefined {if (templating === 'liquid' && typeof value === 'string') {try {@@ -740,6 +744,12 @@ export interface workflowLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {properties?: any[] | undefined@@ -992,6 +1002,12 @@ export interface workflowLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {properties?: any[] | undefined@@ -1534,6 +1550,12 @@ export interface workflowLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {properties?: any[] | undefined@@ -1786,6 +1808,12 @@ export interface workflowLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {properties?: any[] | undefined@@ -1953,6 +1981,12 @@ export interface workflowLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {condition: {filters?:@@ -2299,6 +2333,12 @@ export interface workflowLogicActions {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {condition: {filters?:@@ -2658,6 +2698,12 @@ export interface workflowLogicMeta {}type: 'event'}+ | {+ filters: {+ properties?: any[] | undefined+ }+ type: 'slack-message'+ }| {filters: {properties?: any[] | undefined@@ -3255,11 +3301,12 @@ export const workflowLogic = kea<workflowLogicType>([scheduleStartsAt: string | null,saveAttemptedActionIds: string[] | null): Record<string, HogFlowActionValidationResult | null> => {- // Warehouse-triggered workflows are person-less ("row-scoped"). Person-dependent- // step types make no sense without a person, so we block them at save time.+ // Warehouse- and Slack-triggered workflows are person-less ("row-scoped").+ // Person-dependent step types make no sense without a person, so we block them at+ // save time.const triggerAction = workflow.actions.find((a) => a.type === 'trigger')const isRowScopedTrigger =- triggerAction?.type === 'trigger' && triggerAction.config?.type === 'data-warehouse-table'+ triggerAction?.type === 'trigger' && ROW_SCOPED_TRIGGER_TYPES.has(triggerAction.config?.type)return workflow.actions.reduce((acc, action) => {@@ -3448,7 +3495,8 @@ export const workflowLogic = kea<workflowLogicType>([// for the authoritative enforcement).isRowScopedTrigger: [(s) => [s.triggerAction],- (triggerAction: TriggerAction | null): boolean => triggerAction?.config?.type === 'data-warehouse-table',+ (triggerAction: TriggerAction | null): boolean =>+ ROW_SCOPED_TRIGGER_TYPES.has(triggerAction?.config?.type as string),],workflowSanitized: [diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex bc7142f28c3e..bd9c9c4b18b2 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -415,7 +415,7 @@ export const HogFlowActionTypeEnumApi = {} as const/**- * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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 }@@ -476,7 +476,7 @@ export interface HogFlowActionApi {* * `random_cohort_branch` - random_cohort_branch* * `exit` - exit */type: HogFlowActionTypeEnumApi- /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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 0d9fa0b522cc..c6e8448990c3 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -704,7 +704,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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()@@ -1048,7 +1048,7 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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()@@ -1397,7 +1397,7 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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()@@ -2001,7 +2001,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?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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()@@ -2617,7 +2617,7 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a50d8c3482b9..1a34b534f637 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -39673,7 +39673,7 @@ export namespace Schemas {} as const;/**- * Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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. */@@ -39732,7 +39732,7 @@ export namespace Schemas {* * `random_cohort_branch` - random_cohort_branch* * `exit` - exit */type: HogFlowActionTypeEnum;- /** Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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;diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex 778431970b00..654051a85b29 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -360,7 +360,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod),]).describe(- "Type-specific config keyed by action type. trigger: {type: event|webhook|manual|batch|schedule|tracking_pixel, filters?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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/workflows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.jsonindex 03a32fa7d08a..7c7fe060ab12 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?}. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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|slack-message, filters?}. slack-message runs once per message posted in a connected Slack channel, and takes only filters: {properties: [<cond>]} over the message properties (channel, user, bot_id, text, subtype, is_thread_reply). Runs are person-less, so person-dependent steps are rejected. webhook and manual triggers also require template_id: 'template-source-webhook', and tracking_pixel requires template_id: 'template-source-webhook-pixel'. filters shape: {events: [{id, name, type:'events', properties:[<cond>]}], properties:[<cond>], actions:[...], filter_test_accounts:<bool>}. <cond>: {key, value, operator, type: event|person|group}, or {key: 'id', type: 'cohort', value: <cohort_id>, operator: 'in'} to reference a cohort. batch triggers may set filters.audience_type: 'persons' (default) or 'accounts'. An accounts audience fans out one run per customer analytics account and takes account filters instead: properties entries of type 'account_custom_property' (key = definition id), plus tag_names: [<str>], assigned_to_user_ids: [<int>], all_roles_unassigned: <bool>. 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 s|m|h|d. Fractions OK ('1.5d'=36h). Per-unit max s<=60, 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 are relative weights, so they should sum to 100 but a total above or below that still splits traffic in the given proportions. 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.",