Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): let a delay wait until a date carried by the person or event (#82920)

Daniel Marchuk085c3d34e4c5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 747877ecf3bc..fa4b8dfb9619 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5332,6 +5332,18 @@ snapshots:
hash: v1.k794b7964.d553cecf3e544087316e1687404c8e2b3a6c19f618a05e09880e60e656054f23.hNkLLb04XLyd-PQJa59WwPhgRAxMbW5fSDzCnowJKBs
products-workflows-customerioimportmodal--step-4-track-not-configured--light:
hash: v1.k794b7964.0954891b73cdc0b1bce1275fa11a5fa4af2055b83b518bce82f3fde886097659.mgEq2W8sZg7x-vt8z2EpwEHPBGRzPI1GWtn-9tu-46o
+ products-workflows-steps-delay--date-not-chosen-yet--dark:
+ hash: v1.k794b7964.ec9c913ba6edb54c2b521e3b1913e45fe914dcd4fc5b45febacd543038865cd0.khqeV0deGQR_Ows3heRrRyvzw8fUBJ6KUNQbhb1asas
+ products-workflows-steps-delay--date-not-chosen-yet--light:
+ hash: v1.k794b7964.dc158b1016438cce345c29d6286ded7e04c3425d8af7db8ceb8afedecb8fd2d3.kI3pKbOwmZIvyBcmr2W9FanENuzvek1DTD0L8x9LxgU
+ products-workflows-steps-delay--date-on-the-person--dark:
+ hash: v1.k794b7964.8833fd60d4b54c0751a7d18be9646611e7946c01182fda9ca2a90069a6462ac9.aZ7c7m-BBK3s1bidL57E4cLDR-CW36j527cyvA7Vgkw
+ products-workflows-steps-delay--date-on-the-person--light:
+ hash: v1.k794b7964.957751579f78f83fb2300b18ea372c50283e9b4caab2d2bd86b2246c5038204a.HH3ABZUVOmlM6GjJzheIbs3KYeZtbREPrlqkdFkt5G4
+ products-workflows-steps-delay--fixed-duration--dark:
+ hash: v1.k794b7964.9e7a12c3094416ddf703121095bc7eba5189420cab88d6967618bf43139069fe.UZSvEld_DwpzTPi6QpbRfxOtDYP7S_gR0F03DJcFMpM
+ products-workflows-steps-delay--fixed-duration--light:
+ hash: v1.k794b7964.f394f1e00c55c84136a291d5acb646dc12e0b27951a99e493137f7bad05a2082.zj4h9BHlkIR9RBHiB6nkO0QjDgPC1UKa08uSHemhjSQ
queries-webvitals--web-vitals--dark:
hash: v1.k794b7964.2ae778a0c5fdba3c69dfcbd3e9589c3c3d9cc2f0fef2eefd304c565be7e9a7c9.hH71byl33sIAdRCgaPk1lDOev0qooW1xhv0AL_yrIvg
queries-webvitals--web-vitals--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 50601b8401b6..6e5d9357d7bf 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -558,6 +558,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics
WORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflows
+ WORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflows
WORKFLOWS_EMAIL_REPUTATION: 'workflows-email-reputation', // owner: #team-workflows
WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflows
WORKFLOWS_INCIDENT_REPLAY: 'workflows-incident-replay', // owner: #team-workflows
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.ts
index 8ea308bb5ae6..f09af3f9ab00 100644
--- a/nodejs/src/cdp/schema/hogflow.ts
+++ b/nodejs/src/cdp/schema/hogflow.ts
@@ -146,8 +146,31 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
z.object({
..._commonActionFields,
type: z.literal('delay'),
+ // Two ways to say when to continue, exactly one of which is set. `delay_duration` waits a fixed
+ // span from when the step starts. `delay_until` waits for an instant carried by the person or the
+ // event, which a fixed duration cannot express (e.g. a per-person trial expiry).
config: z.object({
- delay_duration: z.string(),
+ delay_duration: z.string().optional(),
+ delay_until: z
+ .object({
+ // HogQL evaluating to a datetime: an ISO string, a HogDateTime, or unix seconds.
+ expression: z.string(),
+ // Signed offset applied to that instant, e.g. '-1d' for "one day before". Kept separate
+ // from the expression so the builder can offer a property picker instead of arithmetic.
+ offset: z.string().optional(),
+ // Which zone a date with no offset of its own is read in, the same three fields
+ // wait_until_time_window uses. A stored '2026-03-01' means midnight where the customer
+ // lives, not midnight UTC.
+ timezone: z.string().nullish(),
+ use_person_timezone: z.boolean().optional(),
+ fallback_timezone: z.string().nullish(),
+ bytecode: z.any().optional(),
+ bytecode_error: z.string().optional(),
+ })
+ .optional(),
+ // How long past the step's start the wait may run, so a far-future or malformed instant cannot
+ // park a run indefinitely. Applies to delay_until only.
+ max_delay_duration: z.string().optional(),
}),
}),
z.object({
diff --git a/nodejs/src/cdp/services/hogflows/actions/delay.test.ts b/nodejs/src/cdp/services/hogflows/actions/delay.test.ts
index b43c1ae4a59c..98bd29a25d45 100644
--- a/nodejs/src/cdp/services/hogflows/actions/delay.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/delay.test.ts
@@ -1,6 +1,11 @@
import { DateTime } from 'luxon'
-import { calculatedScheduledAt } from './delay'
+import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'
+import { createExampleHogFlowInvocation } from '~/cdp/_tests/fixtures-hogflows'
+
+import { findActionByType } from '../hogflow-utils'
+import { ActionHandlerResult } from './action.interface'
+import { DelayHandler, calculatedScheduledAt } from './delay'
describe('calculatedScheduledAt', () => {
let startedAtTimestamp: number
@@ -88,3 +93,302 @@ describe('calculatedScheduledAt', () => {
})
})
})
+
+describe('DelayHandler with delay_until', () => {
+ // Compiled by the HogQL compiler from `person.properties.trial_expiration_at`.
+ const EXPIRY_BYTECODE = ['_H', 1, 32, 'trial_expiration_at', 32, 'properties', 32, 'person', 1, 3]
+ const NOW = '2025-01-01T00:00:00.000Z'
+
+ const buildDelay = (
+ config: Record<string, any>,
+ personProperties: Record<string, any> = {}
+ ): { invocation: ReturnType<typeof createExampleHogFlowInvocation>; action: any } => {
+ const hogFlow = new FixtureHogFlowBuilder()
+ .withWorkflow({
+ actions: {
+ delay: { type: 'delay', config: config as any },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [{ from: 'delay', to: 'exit', type: 'continue' }],
+ })
+ .build()
+ const action = findActionByType(hogFlow, 'delay')!
+ const invocation = createExampleHogFlowInvocation(hogFlow, {}, { properties: personProperties })
+ invocation.state.currentAction = {
+ id: action.id,
+ startedAtTimestamp: DateTime.fromISO(NOW).toMillis(),
+ }
+ return { invocation, action }
+ }
+
+ const runDelay = async (
+ config: Record<string, any>,
+ personProperties: Record<string, any> = {}
+ ): Promise<ActionHandlerResult> => {
+ const { invocation, action } = buildDelay(config, personProperties)
+ return await new DelayHandler().execute({ invocation, action, result: {} as any })
+ }
+
+ const delayUntil = (overrides: Record<string, any> = {}): Record<string, any> => ({
+ delay_until: {
+ expression: 'person.properties.trial_expiration_at',
+ bytecode: EXPIRY_BYTECODE,
+ ...overrides,
+ },
+ })
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ jest.setSystemTime(new Date(NOW))
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ // A stored date reaches the VM in whichever shape the customer set it, and all of these have to park to
+ // the same instant — the step exists to follow their data rather than dictate a format.
+ it.each([
+ ['ISO string', '2025-01-08T00:00:00.000Z'],
+ ['ISO string with no offset, read as UTC', '2025-01-08T00:00:00'],
+ ['unix seconds', DateTime.fromISO('2025-01-08T00:00:00.000Z').toSeconds()],
+ [
+ 'HogDateTime',
+ { __hogDateTime__: true, dt: DateTime.fromISO('2025-01-08T00:00:00.000Z').toSeconds(), zone: 'UTC' },
+ ],
+ ])('parks until a date given as %s', async (_label, value) => {
+ const result = await runDelay(delayUntil(), { trial_expiration_at: value })
+
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO('2025-01-08T00:00:00.000Z').toUTC().toISO())
+ // Parking must not advance the step, or the matcher could wake the run and collapse the wait.
+ expect(result.nextAction).toBeUndefined()
+ })
+
+ // Why a bare property picker is not enough: the reminder has to fire before the stored date.
+ it.each([
+ ['a day before', '-1d', '2025-01-07T00:00:00.000Z'],
+ ['three days before', '-3d', '2025-01-05T00:00:00.000Z'],
+ ['two hours after', '2h', '2025-01-08T02:00:00.000Z'],
+ ])('applies an offset of %s', async (_label, offset, expected) => {
+ const result = await runDelay(delayUntil({ offset }), { trial_expiration_at: '2025-01-08T00:00:00.000Z' })
+
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO(expected).toUTC().toISO())
+ })
+
+ it('continues immediately when the date has already passed', async () => {
+ const result = await runDelay(delayUntil(), { trial_expiration_at: '2024-12-01T00:00:00.000Z' })
+
+ expect(result.scheduledAt).toBeUndefined()
+ expect(result.nextAction?.type).toBe('exit')
+ })
+
+ it('continues when the offset pulls the date into the past', async () => {
+ // "Three days before" a date only one day out, so the reminder moment has already gone.
+ const result = await runDelay(delayUntil({ offset: '-3d' }), {
+ trial_expiration_at: '2025-01-02T00:00:00.000Z',
+ })
+
+ expect(result.nextAction?.type).toBe('exit')
+ })
+
+ // A fixed delay caps each unit ('45d' means 30 days). Carrying that into the offset would send a "45
+ // days before" reminder 15 days late, and silently, so the offset keeps its full magnitude. The wait
+ // stays bounded by max_delay_duration instead.
+ it('keeps an offset larger than a fixed delay allows', async () => {
+ const result = await runDelay(delayUntil({ offset: '-45d' }), {
+ trial_expiration_at: '2025-03-02T00:00:00.000Z',
+ })
+
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-16T00:00:00.000Z').toUTC().toISO())
+ })
+
+ // A ceiling nothing can parse must not read as zero: that puts the cap at the step's own start, so every
+ // date resolves as already past and the next step runs at once.
+ it('falls back to the default maximum when the configured one is unreadable', async () => {
+ const result = await runDelay(
+ { ...delayUntil(), max_delay_duration: 'whenever' },
+ { trial_expiration_at: '2025-01-08T00:00:00.000Z' }
+ )
+
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-08T00:00:00.000Z').toUTC().toISO())
+ expect(result.nextAction).toBeUndefined()
+ })
+
+ it('clamps a far-future date to the default maximum', async () => {
+ const result = await runDelay(delayUntil(), { trial_expiration_at: '2030-01-01T00:00:00.000Z' })
+
+ // 30 days past the step's start, not five years: an unbounded park would strand the run.
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO(NOW).toUTC().plus({ days: 30 }).toISO())
+ })
+
+ // An offset whose magnitude overflows luxon's date range makes an invalid target: without a guard it
+ // slips past the cap and hands the queue an unschedulable instant. It must clamp like '45d' or a
+ // far-future date instead.
+ it('clamps an offset too large to represent to the default maximum', async () => {
+ const result = await runDelay(delayUntil({ offset: '100000000000000000000d' }), {
+ trial_expiration_at: '2025-01-08T00:00:00.000Z',
+ })
+
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO(NOW).toUTC().plus({ days: 30 }).toISO())
+ expect(result.nextAction).toBeUndefined()
+ })
+
+ it('honours a configured maximum', async () => {
+ const result = await runDelay(
+ { ...delayUntil(), max_delay_duration: '2d' },
+ { trial_expiration_at: '2025-01-08T00:00:00.000Z' }
+ )
+
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO(NOW).toUTC().plus({ days: 2 }).toISO())
+ })
+
+ // Failing is deliberate. Continuing would run the next step at once, which for a "before X" reminder
+ // sends the wrong message rather than none; erroring leaves the choice to the step's error handling.
+ it.each([
+ ['the property is missing', {}],
+ ['the property is not a date', { trial_expiration_at: 'whenever' }],
+ // A millisecond timestamp read as seconds lands in the year 58970; rejecting it stops the clamp from
+ // silently turning it into a 30-day wait.
+ ['the property is a unix millisecond timestamp', { trial_expiration_at: 1798761600000 }],
+ ])('fails when %s', async (_label, personProperties) => {
+ await expect(runDelay(delayUntil(), personProperties)).rejects.toThrow(
+ 'The date to wait for did not evaluate to a date'
+ )
+ })
+
+ it('fails when the expression was never compiled', async () => {
+ await expect(
+ runDelay({ delay_until: { expression: 'person.properties.x', bytecode_error: 'boom' } })
+ ).rejects.toThrow('Could not read the date to wait for: boom')
+ })
+
+ // A resume can rebuild globals without the person the expression reads, so the read raises rather than
+ // returning null. The instant stored on the first park must still carry the run, not strand it.
+ it('falls back to the saved instant when the expression errors on a resume', async () => {
+ const { invocation, action } = buildDelay(delayUntil())
+ invocation.state.currentAction!.delayUntilAt = '2025-01-08T00:00:00.000Z'
+ delete (invocation.filterGlobals as any).person
+
+ const result = await new DelayHandler().execute({ invocation, action, result: {} as any })
+
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO('2025-01-08T00:00:00.000Z').toUTC().toISO())
+ expect(invocation.state.currentAction!.delayUntilUnresolved).toBeUndefined()
+ })
+
+ // With no saved instant to fall back on, the wait cannot resolve at all. It must mark itself unresolved
+ // so the run aborts — otherwise on_error's default of continuing sends the message with nothing to be
+ // before.
+ it('marks the wait unresolved when the expression errors and no instant was saved', async () => {
+ const { invocation, action } = buildDelay(delayUntil())
+ delete (invocation.filterGlobals as any).person
+
+ await expect(new DelayHandler().execute({ invocation, action, result: {} as any })).rejects.toThrow(
+ 'Could not read the date to wait for'
+ )
+ expect(invocation.state.currentAction!.delayUntilUnresolved).toBe(true)
+ })
+
+ // A date stored without a zone ('2025-01-08', or a local datetime) means midnight where the customer
+ // is, not midnight UTC. Reading it in UTC sends a "day before" reminder on the wrong local day for
+ // most of the world.
+ it.each([
+ ['UTC by default', {}, '2025-01-08T00:00:00.000Z'],
+ ['a configured zone', { timezone: 'Asia/Tokyo' }, '2025-01-07T15:00:00.000Z'],
+ ['a zone behind UTC', { timezone: 'America/New_York' }, '2025-01-08T05:00:00.000Z'],
+ ])('reads a date with no offset of its own in %s', async (_label, zoneConfig, expected) => {
+ const result = await runDelay(delayUntil(zoneConfig), { trial_expiration_at: '2025-01-08' })
+
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO(expected).toUTC().toISO())
+ })
+
+ // The zone only fills in what the value leaves out, so anything absolute must come out unchanged -
+ // otherwise setting a zone would quietly move dates that were already exact.
+ it.each([
+ ['an offset-bearing string', '2025-01-08T00:00:00+00:00'],
+ ['unix seconds', DateTime.fromISO('2025-01-08T00:00:00.000Z').toSeconds()],
+ ])('leaves %s alone whatever the zone says', async (_label, value) => {
+ const result = await runDelay(delayUntil({ timezone: 'Asia/Tokyo' }), { trial_expiration_at: value })
+
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-08T00:00:00.000Z').toUTC().toISO())
+ })
+
+ it("reads the date in the person's own timezone", async () => {
+ const result = await runDelay(delayUntil({ use_person_timezone: true, fallback_timezone: 'Europe/Berlin' }), {
+ trial_expiration_at: '2025-01-08',
+ $geoip_time_zone: 'Asia/Tokyo',
+ })
+
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-07T15:00:00.000Z').toUTC().toISO())
+ })
+
+ // Someone who travels, or whose GeoIP zone is corrected, must not be woken on their old local day. The
+ // wait is read again when it ends, so the zone the person has then is the one that decides.
+ it("follows the person's timezone when it changes while the run is parked", async () => {
+ const { invocation, action } = buildDelay(delayUntil({ use_person_timezone: true, fallback_timezone: 'UTC' }), {
+ trial_expiration_at: '2025-01-08',
+ $geoip_time_zone: 'Asia/Tokyo',
+ })
+
+ const parked = await new DelayHandler().execute({ invocation, action, result: {} as any })
+ expect(parked.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-07T15:00:00.000Z').toUTC().toISO())
+
+ invocation.person!.properties.$geoip_time_zone = 'America/New_York'
+ const onWake = await new DelayHandler().execute({ invocation, action, result: {} as any })
+
+ expect(onWake.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-08T05:00:00.000Z').toUTC().toISO())
+ })
+
+ // Clocks go back in Berlin on 26 October 2025, so 02:30 that morning happens twice and the stored value
+ // names two instants. Luxon takes the first. Locking that down stops a library change from moving such a
+ // send by an hour unnoticed. The step's own clock moves to the day before, or the 30-day cap would
+ // swallow a date ten months out.
+ it('reads a local time inside a repeated hour as the first of the two', async () => {
+ const dayBefore = '2025-10-25T00:00:00.000Z'
+ jest.setSystemTime(new Date(dayBefore))
+ const { invocation, action } = buildDelay(delayUntil({ timezone: 'Europe/Berlin' }), {
+ trial_expiration_at: '2025-10-26T02:30:00',
+ })
+ invocation.state.currentAction!.startedAtTimestamp = DateTime.fromISO(dayBefore).toMillis()
+
+ const result = await new DelayHandler().execute({ invocation, action, result: {} as any })
+
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-10-26T00:30:00.000Z').toUTC().toISO())
+ })
+
+ it('falls back when the person has no timezone', async () => {
+ const result = await runDelay(delayUntil({ use_person_timezone: true, fallback_timezone: 'Europe/Berlin' }), {
+ trial_expiration_at: '2025-01-08',
+ })
+
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-07T23:00:00.000Z').toUTC().toISO())
+ })
+
+ // A rerun of a failed run carries the marker in its stored state. Leaving it set would turn any later
+ // failure of this step into an abort, whatever the step's error handling says.
+ it('clears the unresolved marker once the wait resolves', async () => {
+ const { invocation, action } = buildDelay(delayUntil(), { trial_expiration_at: '2025-01-08T00:00:00.000Z' })
+ invocation.state.currentAction!.delayUntilUnresolved = true
+
+ await new DelayHandler().execute({ invocation, action, result: {} as any })
+
+ expect(invocation.state.currentAction!.delayUntilUnresolved).toBeUndefined()
+ })
+
+ // HogQL returns a HogDateTime holding whatever it parsed, so toDateTime('not a date') arrives as NaN
+ // seconds. Without a check that becomes an instant the queue cannot schedule, rather than a wait that
+ // could not work out its date.
+ it.each([
+ ['NaN', NaN],
+ ['Infinity', Infinity],
+ ])('fails on a HogDateTime holding %s', async (_label, seconds) => {
+ await expect(
+ runDelay(delayUntil(), { trial_expiration_at: { __hogDateTime__: true, dt: seconds, zone: 'UTC' } })
+ ).rejects.toThrow('The date to wait for did not evaluate to a date')
+ })
+
+ it('still delays by a fixed duration when that is what is configured', async () => {
+ const result = await runDelay({ delay_duration: '2h' })
+
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO(NOW).toUTC().plus({ hours: 2 }).toISO())
+ })
+})
diff --git a/nodejs/src/cdp/services/hogflows/actions/delay.ts b/nodejs/src/cdp/services/hogflows/actions/delay.ts
index 505f10e106f4..255761e0272b 100644
--- a/nodejs/src/cdp/services/hogflows/actions/delay.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/delay.ts
@@ -1,19 +1,24 @@
import { DateTime, DurationLike } from 'luxon'
import { HogFlowAction } from '~/cdp/schema/hogflow'
+import { CyclotronJobInvocationHogFlow } from '~/cdp/types'
+import { execHog } from '~/cdp/utils/hog-exec'
import { findContinueAction } from '../hogflow-utils'
import { ActionHandler, ActionHandlerOptions, ActionHandlerResult } from './action.interface'
+import { resolveTimezone } from './timezone'
export class DelayHandler implements ActionHandler {
- execute({
+ async execute({
invocation,
action,
- }: ActionHandlerOptions<Extract<HogFlowAction, { type: 'delay' }>>): ActionHandlerResult {
- const nextScheduledAt = calculatedScheduledAt(
- action.config.delay_duration,
- invocation.state.currentAction?.startedAtTimestamp
- )
+ }: ActionHandlerOptions<Extract<HogFlowAction, { type: 'delay' }>>): Promise<ActionHandlerResult> {
+ const nextScheduledAt = action.config.delay_until
+ ? await scheduledAtFromInstant(action, invocation)
+ : calculatedScheduledAt(
+ action.config.delay_duration ?? '',
+ invocation.state.currentAction?.startedAtTimestamp
+ )
// While the delay is still pending, park WITHOUT advancing currentAction. Advancing eagerly
// (returning nextAction alongside scheduledAt) made the job look like it was already at the
@@ -32,6 +37,162 @@ export class DelayHandler implements ActionHandler {
const DURATION_REGEX = /^(\d*\.?\d+)([dhms])$/
+// Same shape as a duration, with an optional leading sign so an offset can point before the instant.
+const OFFSET_REGEX = /^(-?)(\d*\.?\d+)([dhms])$/
+
+const DEFAULT_MAX_DELAY_UNTIL = '30d'
+
+// The last second luxon (and JS Date) can represent as a real date, end of year 9999. A numeric value larger
+// than this is a millisecond timestamp mislabelled as seconds, not a plausible date to wait for.
+const MAX_UNIX_SECONDS = 253402300799
+
+const SECONDS_PER_DURATION_UNIT: Record<string, number> = { d: 86400, h: 3600, m: 60, s: 1 }
+
+/**
+ * Seconds for a signed offset, at its full magnitude.
+ *
+ * Deliberately not held to the per-unit ceilings a fixed delay uses. Those exist to bound how long a run
+ * waits, which `max_delay_duration` already does here, and applying them to an offset would turn "45 days
+ * before" into "30 days before" without saying so: for a date two months out that fires the message 15 days
+ * late rather than not at all.
+ */
+function offsetSeconds(value: string): number | null {
+ const match = OFFSET_REGEX.exec(value)
+ if (!match) {
+ return null
+ }
+ const [, sign, amountString, unit] = match
+ return (sign === '-' ? -1 : 1) * parseFloat(amountString) * SECONDS_PER_DURATION_UNIT[unit]
+}
+
+/** Seconds for the wait's ceiling, using the same units and per-unit ceilings as a fixed delay. */
+function maxDelaySeconds(value: string): number | null {
+ const match = DURATION_REGEX.exec(value)
+ if (!match) {
+ return null
+ }
+ const [, amountString, unit] = match
+ return Math.min(MAX_VALUE_FOR_DURATION_UNIT[unit], parseFloat(amountString)) * SECONDS_PER_DURATION_UNIT[unit]
+}
+
+/**
+ * The instant a `delay_until` expression evaluates to, or null when it yields nothing usable.
+ *
+ * `zone` only decides how a value that carries no offset of its own is read — a bare date or a local
+ * datetime string. Luxon keeps the offset a value already states, and unix seconds and HogDateTime are
+ * absolute, so those are unaffected by the zone.
+ */
+function instantFromHogValue(value: unknown, zone: string): DateTime | null {
+ if (value && typeof value === 'object' && '__hogDateTime__' in (value as Record<string, unknown>)) {
+ const seconds = (value as { dt?: unknown }).dt
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds)) {
+ // HogQL hands back a HogDateTime holding whatever it managed to parse, so toDateTime('not a date')
+ // arrives here as NaN seconds. Left alone that becomes an instant the queue cannot schedule.
+ return null
+ }
+ const asHogDateTime = DateTime.fromSeconds(seconds, { zone: 'UTC' })
+ return asHogDateTime.isValid ? asHogDateTime : null
+ }
+ if (typeof value === 'number') {
+ // Unix seconds, matching toUnixTimestamp(). A millisecond timestamp — what Date.now() and most SDKs
+ // produce — is ~1000x too large and lands tens of thousands of years out, where the max-delay clamp
+ // would swallow it silently. luxon still calls that instant valid, so reject anything past the last
+ // representable second rather than guess the unit.
+ if (value > MAX_UNIX_SECONDS) {
+ return null
+ }
+ const asSeconds = DateTime.fromSeconds(value, { zone: 'UTC' })
+ return asSeconds.isValid ? asSeconds : null
+ }
+ if (typeof value === 'string') {
+ const parsed = DateTime.fromISO(value, { zone })
+ return parsed.isValid ? parsed : null
+ }
+ return null
+}
+
+/**
+ * When to continue for a `delay_until` step: the instant its expression evaluates to, plus any offset,
+ * clamped to `max_delay_duration` past the step's start. Returns null once that instant has passed.
+ *
+ * Re-evaluated on every wake rather than only on entry, so a stored date that moves *later* while the run
+ * is parked is honoured: the job wakes at the old, earlier instant and re-parks to the new one. A date
+ * that moves *earlier* is only noticed once the old instant passes, because the only wake for a parked
+ * delay is that stored instant — the subscription matcher never pulls a delay forward. Waking early is
+ * free; the step simply re-parks to the new instant.
+ */
+async function scheduledAtFromInstant(
+ action: Extract<HogFlowAction, { type: 'delay' }>,
+ invocation: CyclotronJobInvocationHogFlow
+): Promise<DateTime | null> {
+ const config = action.config.delay_until!
+ const startedAtTimestamp = invocation.state.currentAction?.startedAtTimestamp
+ if (!startedAtTimestamp) {
+ throw new Error("'startedAtTimestamp' is not set or is invalid")
+ }
+
+ if (!Array.isArray(config.bytecode) || config.bytecode.length === 0) {
+ throw new Error(`Could not read the date to wait for: ${config.bytecode_error ?? 'no compiled expression'}`)
+ }
+
+ const globals = { ...invocation.filterGlobals, variables: invocation.state.variables }
+ const { execResult, error } = await execHog(config.bytecode, { globals })
+ const evaluationError = error ?? execResult?.error
+ const zone = resolveTimezone(config, invocation.person)
+
+ // A resumed invocation rebuilds its globals from stored state, which can arrive without the event or
+ // person properties the expression reads — so evaluation can error (a missing global raises) or yield a
+ // non-date on wake even though it resolved on entry. Re-evaluating is still worth attempting every wake,
+ // because it is what lets a stored date that moved while parked be honoured — but it must not strand a
+ // run that already resolved once, so an unusable evaluation falls back to the instant recorded on the
+ // first park before giving up.
+ const previous = invocation.state.currentAction?.delayUntilAt
+ const instant =
+ (evaluationError ? null : instantFromHogValue(execResult?.result, zone)) ??
+ (previous ? DateTime.fromISO(previous, { zone: 'UTC' }) : null)
+ if (!instant) {
+ // Marked so the run aborts rather than falling through to the next step. on_error defaults to
+ // 'continue', which for a "N days before X" message means sending it with nothing to be before.
+ if (invocation.state.currentAction) {
+ invocation.state.currentAction.delayUntilUnresolved = true
+ }
+ throw new Error(
+ evaluationError
+ ? `Could not read the date to wait for: ${String(evaluationError)}`
+ : 'The date to wait for did not evaluate to a date'
+ )
+ }
+ if (invocation.state.currentAction) {
+ invocation.state.currentAction.delayUntilAt = instant.toISO() ?? undefined
+ // The wait resolved, so a marker left by an earlier attempt must not outlive it and turn some later
+ // failure of this step into an abort the author never asked for.
+ delete invocation.state.currentAction.delayUntilUnresolved
+ }
+
+ const offset = config.offset ? offsetSeconds(config.offset) : 0
+ if (offset === null) {
+ throw new Error(`Invalid offset: ${config.offset}`)
+ }
+
+ const target = instant.plus({ seconds: offset })
+ // A ceiling that cannot be read falls back to the default rather than to nothing: zero would put the cap
+ // at the step's own start, which continues the run immediately - the outcome the wait exists to prevent.
+ const maxSeconds =
+ maxDelaySeconds(action.config.max_delay_duration ?? DEFAULT_MAX_DELAY_UNTIL) ??
+ maxDelaySeconds(DEFAULT_MAX_DELAY_UNTIL)!
+ const cap = DateTime.fromMillis(startedAtTimestamp).toUTC().plus({ seconds: maxSeconds })
+ // An offset large enough to push the date past luxon's representable range makes the target invalid, and
+ // an invalid DateTime compares false against everything — so it would slip past the cap below and hand the
+ // queue an unschedulable instant. Treat it like any out-of-range target: a future overflow is bounded by
+ // the cap, a past one has already elapsed.
+ if (!target.isValid) {
+ return offset > 0 && DateTime.utc() < cap ? cap : null
+ }
+ const scheduledAt = target > cap ? cap : target
+
+ return DateTime.utc() >= scheduledAt ? null : scheduledAt
+}
+
const MAX_VALUE_FOR_DURATION_UNIT: Record<string, number> = {
d: 30,
h: 24,
diff --git a/nodejs/src/cdp/services/hogflows/actions/timezone.ts b/nodejs/src/cdp/services/hogflows/actions/timezone.ts
new file mode 100644
index 000000000000..5715d10e51c6
--- /dev/null
+++ b/nodejs/src/cdp/services/hogflows/actions/timezone.ts
@@ -0,0 +1,35 @@
+import { DateTime } from 'luxon'
+
+import { CyclotronPerson } from '~/cdp/types'
+
+const GEOIP_TIMEZONE_PROPERTY = '$geoip_time_zone'
+
+/** The timezone fields carried by every step that reasons about local time. */
+export interface TimezoneConfig {
+ timezone?: string | null
+ use_person_timezone?: boolean
+ fallback_timezone?: string | null
+}
+
+function isValidTimezone(timezone: string): boolean {
+ // Luxon returns an invalid DateTime if the timezone is not recognized
+ return DateTime.utc().setZone(timezone).isValid
+}
+
+/** The zone a step reads local time in: the person's own when asked for and usable, else the configured one. */
+export function resolveTimezone(config: TimezoneConfig, person?: CyclotronPerson): string {
+ const fallback = config.fallback_timezone || config.timezone || 'UTC'
+
+ if (config.use_person_timezone) {
+ if (person?.properties) {
+ const personTimezone = person.properties[GEOIP_TIMEZONE_PROPERTY]
+ if (personTimezone && typeof personTimezone === 'string' && isValidTimezone(personTimezone)) {
+ return personTimezone
+ }
+ }
+ // Fall back if person doesn't exist, doesn't have a timezone, or timezone is invalid
+ return fallback
+ }
+ // Use the configured timezone or default to UTC
+ return config.timezone || 'UTC'
+}
diff --git a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts
index be35b0d1b06d..4e2fbe01e520 100644
--- a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts
@@ -5,7 +5,8 @@ import { HogFlowAction } from '~/cdp/schema/hogflow'
import { CyclotronPerson } from '~/cdp/types'
import { findActionByType } from '../hogflow-utils'
-import { getWaitUntilTime, resolveTimezone } from './wait_until_time_window'
+import { resolveTimezone } from './timezone'
+import { getWaitUntilTime } from './wait_until_time_window'
describe('HogFlowActionRunnerWaitUntilTimeWindow', () => {
let action: Extract<HogFlowAction, { type: 'wait_until_time_window' }>
diff --git a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts
index 0b5907633f9d..db70e78e55d1 100644
--- a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts
@@ -5,11 +5,11 @@ import { CyclotronPerson } from '~/cdp/types'
import { findContinueAction } from '../hogflow-utils'
import { ActionHandler, ActionHandlerOptions, ActionHandlerResult } from './action.interface'
+import { resolveTimezone } from './timezone'
type Action = Extract<HogFlowAction, { type: 'wait_until_time_window' }>
const DAY_NAMES = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] as const
-const GEOIP_TIMEZONE_PROPERTY = '$geoip_time_zone'
export class WaitUntilTimeWindowHandler implements ActionHandler {
execute({
@@ -59,28 +59,6 @@ function getNextValidDay(now: DateTime, dateConfig: Action['config']['day']): Da
return nextDay
}
-function isValidTimezone(timezone: string): boolean {
- // Luxon returns an invalid DateTime if the timezone is not recognized
- return DateTime.utc().setZone(timezone).isValid
-}
-
-export function resolveTimezone(config: Action['config'], person?: CyclotronPerson): string {
- const fallback = config.fallback_timezone || config.timezone || 'UTC'
-
- if (config.use_person_timezone) {
- if (person?.properties) {
- const personTimezone = person.properties[GEOIP_TIMEZONE_PROPERTY]
- if (personTimezone && typeof personTimezone === 'string' && isValidTimezone(personTimezone)) {
- return personTimezone
- }
- }
- // Fall back if person doesn't exist, doesn't have a timezone, or timezone is invalid
- return fallback
- }
- // Use the configured timezone or default to UTC
- return config.timezone || 'UTC'
-}
-
export const getWaitUntilTime = (
action: Extract<HogFlowAction, { type: 'wait_until_time_window' }>,
person?: CyclotronPerson
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index bda4106e22f7..ad81e83d2bf7 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -1683,6 +1683,76 @@ describe('Hogflow Executor', () => {
)
loggerErrorSpy.mockRestore()
})
+
+ // A delay that cannot work out when to continue is the one error on_error must not be
+ // allowed to carry past: continuing runs the next step immediately, which for a "N days
+ // before X" reminder sends it with nothing to be before. The handler marks the wait
+ // unresolved and the executor has to honour that over on_error: 'continue'.
+ it('does NOT continue past a delay whose date cannot be worked out, despite on_error continue', async () => {
+ const flow = new FixtureHogFlowBuilder()
+ .withWorkflow({
+ actions: {
+ trigger: {
+ type: 'trigger',
+ config: {
+ type: 'event',
+ filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {},
+ },
+ },
+ // Compiled by the HogQL compiler from `person.properties.expires_at`,
+ // which evaluates to null for a person without that property.
+ delay_1: {
+ type: 'delay',
+ config: {
+ delay_until: {
+ expression: 'person.properties.expires_at',
+ bytecode: [
+ '_H',
+ 1,
+ 32,
+ 'expires_at',
+ 32,
+ 'properties',
+ 32,
+ 'person',
+ 1,
+ 3,
+ ],
+ },
+ } as any,
+ },
+ exit: { type: 'exit', config: {} },
+ },
+ edges: [
+ { from: 'trigger', to: 'delay_1', type: 'continue' },
+ { from: 'delay_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ .build()
+ expect(flow.actions.find((a) => a.id === 'delay_1')!.on_error).toBe('continue')
+
+ const invocation = createExampleHogFlowInvocation(flow)
+ invocation.state.currentAction = {
+ id: 'delay_1',
+ startedAtTimestamp: DateTime.now().toMillis(),
+ }
+
+ const result = await executor.execute(invocation)
+
+ expect(result.error).toContain('The date to wait for did not evaluate to a date')
+ expect(result.finished).toBe(true)
+ expect(result.invocation.state.currentAction?.id).toBe('delay_1')
+ expect(result.logs.map((l) => l.message)).not.toEqual(
+ expect.arrayContaining([expect.stringContaining('Workflow moved to action')])
+ )
+ expect(result.logs.map((l) => l.message)).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining(
+ 'Workflow is aborting because [Action:delay_1] could not work out the date to wait for'
+ ),
+ ])
+ )
+ })
})
})
})
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index 1e9ef4022f4c..99fd715cd313 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -302,6 +302,18 @@ export class HogFlowExecutorService {
timestamp: DateTime.now(),
message: `Workflow is aborting due to ${actionIdForLogging(lastExecutedAction)} error handling setting being set to abort on error`,
})
+ } else if (result.invocation.state.currentAction?.delayUntilUnresolved) {
+ // A delay that cannot work out when to continue overrides on_error's default of carrying
+ // on: the next step would run immediately, which is the one outcome the wait exists to
+ // prevent. See delayUntilUnresolved.
+ shouldAbortAfterError = true
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: `Workflow is aborting because ${
+ lastExecutedAction ? actionIdForLogging(lastExecutedAction) : lastExecutedActionId
+ } could not work out the date to wait for`,
+ })
}
}
@@ -708,6 +720,13 @@ export class HogFlowExecutorService {
): void {
try {
const { invocation } = result
+ // A delay that could not work out when to continue must never fall through, whatever on_error
+ // says: the next step would run immediately, which is what the wait exists to prevent. Bailing
+ // here also keeps the flag readable by shouldEndHogFlowExecution, since goToNextAction would
+ // replace currentAction with a fresh entry and drop it.
+ if (invocation.state.currentAction?.delayUntilUnresolved) {
+ return
+ }
// If current action's on_error is set to 'continue', we move to the next action instead of failing the flow
const currentAction = ensureCurrentAction(invocation)
if (currentAction?.on_error === 'continue') {
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 9a4993028a7a..eda18f37ce73 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -398,6 +398,14 @@ export type HogFlowInvocationContext = {
currentAction?: {
id: string
startedAtTimestamp: number
+ // The instant a delay_until step resolved to when it first parked, as an ISO string. A resumed
+ // invocation rebuilds its filter globals from stored state, which can arrive without the event
+ // properties the expression reads, so re-evaluating on wake is allowed to fail back to this.
+ delayUntilAt?: string
+ // Set when a delay_until step could not work out when to continue. The run aborts on it whatever
+ // on_error says, because "no date" is not an ambiguous failure to carry on from: continuing would
+ // run the next step immediately, which for a "N days before X" message is worse than not sending.
+ delayUntilUnresolved?: boolean
hogFunctionState?: CyclotronJobInvocationHogFunctionContext
// Set by the subscription matcher consumer when it wakes a wait_until_condition
// job because a matching event arrived (as opposed to a scheduled timeout firing).
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 05da2a84d8df..fcb5f64a8cd8 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -356,6 +356,19 @@ describe('Workflows E2E (postgres-v2)', () => {
config: { delay_duration: duration },
})
+ // Waits for a date carried by the event rather than a fixed span. Bytecode is what the HogQL compiler
+ // emits for `properties.expires_at`, which is what HogFlowSerializer stores for this expression.
+ const delayUntilAction = (offset?: string) => ({
+ type: 'delay' as const,
+ config: {
+ delay_until: {
+ expression: 'properties.expires_at',
+ bytecode: ['_H', 1, 32, 'expires_at', 32, 'properties', 1, 2],
+ ...(offset ? { offset } : {}),
+ },
+ },
+ })
+
const exitAction = () => ({ type: 'exit' as const, config: {} })
// Mirrors what HogFlowSerializer compiles for {events: [{id: <name>}]}: a single
@@ -505,6 +518,89 @@ describe('Workflows E2E (postgres-v2)', () => {
})
})
+ describe('delay until a date carried by the data', () => {
+ const workflowWaitingUntil = async (offset?: string): Promise<void> => {
+ await createWorkflow({
+ actions: {
+ trigger: trigger(),
+ delay_1: delayUntilAction(offset),
+ function_1: fetchAction('https://example.com/reminder'),
+ exit: exitAction(),
+ },
+ edges: [
+ { from: 'trigger', to: 'delay_1', type: 'continue' },
+ { from: 'delay_1', to: 'function_1', type: 'continue' },
+ { from: 'function_1', to: 'exit', type: 'continue' },
+ ],
+ })
+ }
+
+ it('parks until the date on the event, then continues', async () => {
+ // A fixed duration cannot express this: the instant comes from the payload, so two runs of the
+ // same workflow park to different times.
+ const expiresAt = DateTime.utc().plus({ seconds: 3 })
+ await workflowWaitingUntil()
+ await triggerWorkflow(createGlobals({ properties: { expires_at: expiresAt.toISO() } } as any))
+ await waitForExpect(async () => {
+ const parked = (await queryCyclotronJobs()).filter(
+ (j: any) => j[statusColumn] === 'available' && new Date(j.scheduled) > new Date()
+ )
+ expect(parked).toHaveLength(1)
+ // Parked to the instant from the data, not to some default span.
+ const scheduled = DateTime.fromJSDate(new Date(parked[0].scheduled)).toUTC()
+ expect(Math.abs(scheduled.diff(expiresAt).as('seconds'))).toBeLessThan(2)
+ }, 5000)
+
+ expect(mockFetch).not.toHaveBeenCalled()
+
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 15000)
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/reminder', expect.anything())
+ })
+
+ it('continues straight away when the date has already passed', async () => {
+ // The guard against a reminder for something that already happened firing days late.
+ await workflowWaitingUntil()
+ await triggerWorkflow(
+ createGlobals({ properties: { expires_at: DateTime.utc().minus({ days: 5 }).toISO() } } as any)
+ )
+
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ })
+
+ it('fires before the date when an offset asks for it', async () => {
+ // The shape a "remind me N days before" workflow needs, and the reason an offset exists rather
+ // than only a bare date: here the date is 1 hour out and the offset pulls the wait to now.
+ await workflowWaitingUntil('-1h')
+ await triggerWorkflow(
+ createGlobals({ properties: { expires_at: DateTime.utc().plus({ hours: 1 }).toISO() } } as any)
+ )
+
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ })
+
+ it('aborts instead of sending when the date cannot be worked out', async () => {
+ // The outcome that matters: a "before it expires" message must not go out for someone with no
+ // expiry. on_error defaults to 'continue', which would do exactly that, so an unresolvable date
+ // aborts the run regardless of that setting.
+ await workflowWaitingUntil()
+ await triggerWorkflow(createGlobals({ properties: {} } as any))
+
+ // Waiting for a terminal state, not merely "not available": a job being worked on is also not
+ // available, so the looser check can pass in the window before the run would have sent.
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ expect(jobs.filter((j: any) => j[statusColumn] === 'failed')).toHaveLength(1)
+ }, 10000)
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
+ })
+
describe('conditional branch workflow', () => {
beforeEach(async () => {
await createWorkflow({
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 451de810b629..8fd7d7813fcc 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -7,6 +7,7 @@ from copy import deepcopy
from datetime import timedelta
from time import monotonic
from typing import Any, NamedTuple, Optional, cast
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from django.conf import settings
from django.core.cache import cache
@@ -32,6 +33,10 @@ from rest_framework.serializers import BaseSerializer
from posthog.schema import ProductKey
+from posthog.hogql.compiler.bytecode import create_bytecode
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.parser import parse_expr
+
from posthog.api.app_metrics2 import AppMetricsMixin, fetch_app_metric_totals_by_source
from posthog.api.documentation import _FallbackSerializer
from posthog.api.hog_invocation_cancel import (
@@ -156,6 +161,9 @@ logger = structlog.get_logger(__name__)
# is held to the same format.
DELAY_DURATION_REGEX = re.compile(r"^\d*\.?\d+[dhms]$")
+# A delay_until offset is the same shape, signed, so it can point before the date it is offsetting.
+DELAY_OFFSET_REGEX = re.compile(r"^-?\d*\.?\d+[dhms]$")
+
def _is_valid_duration(value: Any) -> bool:
return isinstance(value, str) and bool(DELAY_DURATION_REGEX.match(value))
@@ -1064,9 +1072,21 @@ class HogFlowActionSerializer(serializers.Serializer):
"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. "
+ "delay: waits a fixed span or until a per-person/-event date — set EXACTLY ONE of "
+ "delay_duration or delay_until. {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. "
+ "delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date "
+ "expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the "
+ "same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours "
+ "after). expression is compiled server-side, so any bytecode sent with it is discarded. "
+ "A person property is person.properties.<key>; an event property is properties.<key>, as the "
+ "'event.' prefix resolves to nothing and aborts the run. "
+ "Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and "
+ "fallback_timezone decide which zone a date with no offset of its own is read in; a date that "
+ "states an offset, and unix seconds, ignore them. Default UTC. "
+ "Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how "
+ "far past the step's start the wait may run. "
"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 "
@@ -1471,11 +1491,83 @@ class HogFlowActionSerializer(serializers.Serializer):
raise serializers.ValidationError({"config": _duration_error("max_wait_duration")})
if data.get("type") == "delay":
- if strict and not _is_valid_duration(data.get("config", {}).get("delay_duration")):
- raise serializers.ValidationError({"config": _duration_error("delay_duration")})
+ self._validate_delay(data, strict)
return data
+ def _validate_delay(self, data: dict, strict: bool) -> None:
+ """A delay waits either a fixed span or until a date carried by the person or event, never both."""
+ config = data.get("config") or {}
+ delay_until = config.get("delay_until")
+
+ if delay_until is None:
+ if strict and not _is_valid_duration(config.get("delay_duration")):
+ raise serializers.ValidationError({"config": _duration_error("delay_duration")})
+ return
+
+ if config.get("delay_duration"):
+ raise serializers.ValidationError(
+ {"config": "A delay takes either delay_duration or delay_until, not both."}
+ )
+ if not isinstance(delay_until, dict):
+ raise serializers.ValidationError({"config": "delay_until must be an object with an 'expression'."})
+
+ # Client bytecode is dropped on every path, strict or not, as the executor runs whatever it finds.
+ stored = {k: v for k, v in delay_until.items() if k not in ("bytecode", "bytecode_error")}
+ data["config"]["delay_until"] = stored
+
+ expression = delay_until.get("expression")
+ if not isinstance(expression, str) or not expression.strip():
+ if strict:
+ raise serializers.ValidationError({"config": "delay_until.expression is required and must be SQL."})
+ # The builder writes the mode before the date is picked, so a draft can legitimately be
+ # half-configured. Nothing further is checkable without an expression.
+ return
+
+ offset = delay_until.get("offset")
+ if strict and offset is not None and not (isinstance(offset, str) and DELAY_OFFSET_REGEX.match(offset)):
+ raise serializers.ValidationError(
+ {
+ "config": (
+ "delay_until.offset must be a string matching ^-?\\d*\\.?\\d+[dhms]$ "
+ "(e.g. '-1d' for a day before the date, '2h' for two hours after)."
+ )
+ }
+ )
+
+ max_delay_duration = config.get("max_delay_duration")
+ if strict and max_delay_duration is not None and not _is_valid_duration(max_delay_duration):
+ raise serializers.ValidationError({"config": _duration_error("max_delay_duration")})
+
+ use_person_timezone = delay_until.get("use_person_timezone")
+ if strict and use_person_timezone is not None and not isinstance(use_person_timezone, bool):
+ # The executor only checks whether this is truthy, so a string like "no" would switch the
+ # person's timezone on rather than off.
+ raise serializers.ValidationError({"config": "delay_until.use_person_timezone must be true or false."})
+
+ # An unknown zone would silently fall back to UTC in the executor, which is the wrong local day
+ # for most of the world - the mistake this setting exists to prevent.
+ for field in ("timezone", "fallback_timezone"):
+ value = delay_until.get(field)
+ if not strict or value is None:
+ continue
+ try:
+ ZoneInfo(value)
+ except (ZoneInfoNotFoundError, ValueError, TypeError):
+ raise serializers.ValidationError(
+ {"config": f"delay_until.{field} must be an IANA timezone name, e.g. 'Europe/Berlin'."}
+ )
+
+ # Compiled here rather than trusted from the client. Compiling also surfaces a broken expression
+ # at save time instead of at the first run that reaches it.
+ try:
+ stored["bytecode"] = create_bytecode(
+ parse_expr(expression), context=HogQLContext(team_id=self.context["get_team"]().id)
+ ).bytecode
+ except Exception as e:
+ if strict:
+ raise serializers.ValidationError({"config": f"delay_until.expression could not be read as SQL: {e}"})
+
class HogFlowVariableSerializer(serializers.ListSerializer):
child = serializers.DictField(
diff --git a/products/workflows/backend/api/test/test_hog_flow_delay_until.py b/products/workflows/backend/api/test/test_hog_flow_delay_until.py
new file mode 100644
index 000000000000..c1a549714a99
--- /dev/null
+++ b/products/workflows/backend/api/test/test_hog_flow_delay_until.py
@@ -0,0 +1,150 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+TRIGGER = {
+ "id": "trigger_node",
+ "name": "trigger",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+}
+
+EXIT = {"id": "exit_node", "name": "exit", "type": "exit", "config": {}}
+
+
+def delay(config: dict) -> dict:
+ return {"id": "delay_1", "name": "Delay", "type": "delay", "config": config}
+
+
+class TestDelayUntil(APIBaseTest):
+ def _post(self, delay_config: dict, status: str = "active") -> tuple[int, dict]:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {
+ "name": "Test Flow",
+ "status": status,
+ "actions": [TRIGGER, delay(delay_config), EXIT],
+ "edges": [
+ {"from": "trigger_node", "to": "delay_1", "type": "continue"},
+ {"from": "delay_1", "to": "exit_node", "type": "continue"},
+ ],
+ },
+ )
+ return response.status_code, response.json()
+
+ def test_compiles_the_expression_and_stores_only_server_bytecode(self):
+ # The executor runs whatever bytecode it finds on the action, so a client-supplied value must never
+ # survive. Compiling at save time also surfaces a broken expression before any run reaches it.
+ status, body = self._post(
+ {
+ "delay_until": {
+ "expression": "person.properties.trial_expiration_at",
+ "offset": "-1d",
+ "bytecode": ["_H", 1, 32, "malicious"],
+ }
+ }
+ )
+
+ assert status == 201, body
+ stored = next(a for a in body["actions"] if a["id"] == "delay_1")["config"]["delay_until"]
+ assert stored["bytecode"] != ["_H", 1, 32, "malicious"]
+ assert "trial_expiration_at" in stored["bytecode"]
+ assert stored["offset"] == "-1d"
+
+ def test_accepts_a_fixed_duration_as_before(self):
+ status, body = self._post({"delay_duration": "2h"})
+
+ assert status == 201, body
+
+ @parameterized.expand(
+ [
+ ("both_modes", {"delay_duration": "2h", "delay_until": {"expression": "person.properties.x"}}),
+ ("neither_mode", {}),
+ ("expression_missing", {"delay_until": {"offset": "-1d"}}),
+ ("expression_blank", {"delay_until": {"expression": " "}}),
+ ("delay_until_not_an_object", {"delay_until": "person.properties.x"}),
+ ("offset_unsigned_garbage", {"delay_until": {"expression": "person.properties.x", "offset": "soon"}}),
+ ("offset_missing_unit", {"delay_until": {"expression": "person.properties.x", "offset": "-1"}}),
+ (
+ "max_delay_duration_invalid",
+ {"delay_until": {"expression": "person.properties.x"}, "max_delay_duration": "forever"},
+ ),
+ ("expression_not_sql", {"delay_until": {"expression": "this is not sql ("}}),
+ # An unknown zone reaches the executor and silently reads dates in UTC, which is the wrong
+ # local day for most of the world - the mistake the setting exists to prevent.
+ ("timezone_unknown", {"delay_until": {"expression": "person.properties.x", "timezone": "Mars/Olympus"}}),
+ # The executor only checks truthiness, so a string would switch the person's timezone on.
+ (
+ "use_person_timezone_not_a_bool",
+ {"delay_until": {"expression": "person.properties.x", "use_person_timezone": "yes"}},
+ ),
+ (
+ "fallback_timezone_unknown",
+ {
+ "delay_until": {
+ "expression": "person.properties.x",
+ "use_person_timezone": True,
+ "fallback_timezone": "Europe/Atlantis",
+ }
+ },
+ ),
+ ]
+ )
+ def test_rejects_an_unusable_delay(self, _name: str, config: dict):
+ status, body = self._post(config)
+
+ assert status == 400, body
+
+ @parameterized.expand(
+ [
+ ("day_before", "-1d"),
+ ("hours_after", "2h"),
+ ("fractional", "1.5h"),
+ ("seconds", "30s"),
+ ]
+ )
+ def test_accepts_offset_shape(self, _name: str, offset: str):
+ status, body = self._post({"delay_until": {"expression": "person.properties.expires_at", "offset": offset}})
+
+ assert status == 201, body
+
+ def test_keeps_the_timezone_settings_it_was_given(self):
+ status, body = self._post(
+ {
+ "delay_until": {
+ "expression": "person.properties.expires_at",
+ "timezone": "Europe/Berlin",
+ "use_person_timezone": True,
+ "fallback_timezone": "America/New_York",
+ }
+ }
+ )
+
+ assert status == 201, body
+ stored = next(a for a in body["actions"] if a["id"] == "delay_1")["config"]["delay_until"]
+ assert stored["timezone"] == "Europe/Berlin"
+ assert stored["use_person_timezone"] is True
+ assert stored["fallback_timezone"] == "America/New_York"
+
+ def test_a_draft_saves_the_date_mode_before_a_date_is_picked(self):
+ # The builder writes the mode as soon as it is chosen, so the editor autosaves this exact state
+ # every time someone starts a date delay. Client bytecode is still dropped on this path.
+ status, body = self._post(
+ {"delay_until": {"expression": "", "bytecode": ["_H", 1, 32, "malicious"]}}, status="draft"
+ )
+
+ assert status == 201, body
+ stored = next(a for a in body["actions"] if a["id"] == "delay_1")["config"]["delay_until"]
+ assert stored == {"expression": ""}
+
+ def test_a_draft_can_be_saved_without_a_usable_delay(self):
+ # Drafts from the builder stay lenient so a half-built graph saves; the checks apply on activation.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {"name": "Test Flow", "status": "draft", "actions": [TRIGGER, delay({}), EXIT]},
+ )
+
+ assert response.status_code == 201, response.json()
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index 2406ccfbc3c4..e32f4994923b 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -235,41 +235,6 @@ export interface hogFlowEditorLogicActions {
type: 'random_cohort_branch'
updated_at?: number | undefined
}
- | {
- config: {
- delay_duration: string
- }
- created_at?: number | undefined
- description: string
- filters?:
- | {
- actions?: any[] | undefined
- events?: any[] | undefined
- properties?: any[] | undefined
- }
- | null
- | undefined
- id: string
- name: string
- on_error?: 'abort' | 'continue' | null | undefined
- output_variable?:
- | {
- key: string
- label?: string | null | undefined
- result_path?: string | null | undefined
- spread?: boolean | null | undefined
- }
- | {
- key: string
- label?: string | null | undefined
- result_path?: string | null | undefined
- spread?: boolean | null | undefined
- }[]
- | null
- | undefined
- type: 'delay'
- updated_at?: number | undefined
- }
| {
config: {
reason?: string | undefined
@@ -407,6 +372,53 @@ export interface hogFlowEditorLogicActions {
type: 'wait_until_condition'
updated_at?: number | undefined
}
+ | {
+ config: {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
+ created_at?: number | undefined
+ description: string
+ filters?:
+ | {
+ actions?: any[] | undefined
+ events?: any[] | undefined
+ properties?: any[] | undefined
+ }
+ | null
+ | undefined
+ id: string
+ name: string
+ on_error?: 'abort' | 'continue' | null | undefined
+ output_variable?:
+ | {
+ key: string
+ label?: string | null | undefined
+ result_path?: string | null | undefined
+ spread?: boolean | null | undefined
+ }
+ | {
+ key: string
+ label?: string | null | undefined
+ result_path?: string | null | undefined
+ spread?: boolean | null | undefined
+ }[]
+ | null
+ | undefined
+ type: 'delay'
+ updated_at?: number | undefined
+ }
| {
config: {
inputs: Record<
@@ -1063,41 +1075,6 @@ export interface hogFlowEditorLogicActions {
type: 'random_cohort_branch'
updated_at?: number | undefined
}
- | {
- config: {
- delay_duration: string
- }
- created_at?: number | undefined
- description: string
- filters?:
- | {
- actions?: any[] | undefined
- events?: any[] | undefined
- properties?: any[] | undefined
- }
- | null
- | undefined
- id: string
- name: string
- on_error?: 'abort' | 'continue' | null | undefined
- output_variable?:
- | {
- key: string
- label?: string | null | undefined
- result_path?: string | null | undefined
- spread?: boolean | null | undefined
- }
- | {
- key: string
- label?: string | null | undefined
- result_path?: string | null | undefined
- spread?: boolean | null | undefined
- }[]
- | null
- | undefined
- type: 'delay'
- updated_at?: number | undefined
- }
| {
config: {
reason?: string | undefined
@@ -1235,6 +1212,53 @@ export interface hogFlowEditorLogicActions {
type: 'wait_until_condition'
updated_at?: number | undefined
}
+ | {
+ config: {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
+ created_at?: number | undefined
+ description: string
+ filters?:
+ | {
+ actions?: any[] | undefined
+ events?: any[] | undefined
+ properties?: any[] | undefined
+ }
+ | null
+ | undefined
+ id: string
+ name: string
+ on_error?: 'abort' | 'continue' | null | undefined
+ output_variable?:
+ | {
+ key: string
+ label?: string | null | undefined
+ result_path?: string | null | undefined
+ spread?: boolean | null | undefined
+ }
+ | {
+ key: string
+ label?: string | null | undefined
+ result_path?: string | null | undefined
+ spread?: boolean | null | undefined
+ }[]
+ | null
+ | undefined
+ type: 'delay'
+ updated_at?: number | undefined
+ }
| {
config: {
inputs: Record<
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
index 6bb22fbc5be1..523d1e354246 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
@@ -19,7 +19,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { PERSON_DEPENDENT_ACTION_TYPES, workflowLogic } from '../../workflowLogic'
import { getRegisteredActionNodeCategories } from '../registry/actions/actionNodeRegistry'
import { useHogFlowStep } from '../steps/HogFlowSteps'
-import { getDelayDescription } from '../steps/stepDelayLogic'
+import { DEFAULT_DELAY_DURATION, getDelayDescription } from '../steps/stepDelayLogic'
import { HogFlowAction } from '../types'
export const ACTION_NODES_TO_SHOW: CreateActionType[] = [
@@ -76,13 +76,12 @@ const AI_TASK_ACTION_NODE: CreateActionType = {
output_variable: { key: 'task', result_path: null, label: 'Task' },
}
-const DEFAULT_DELAY = '10m'
export const DELAY_NODES_TO_SHOW: CreateActionType[] = [
{
type: 'delay',
name: 'Delay',
- description: getDelayDescription(DEFAULT_DELAY),
- config: { delay_duration: DEFAULT_DELAY },
+ description: getDelayDescription({ delay_duration: DEFAULT_DELAY_DURATION }),
+ config: { delay_duration: DEFAULT_DELAY_DURATION },
},
{
type: 'wait_until_time_window',
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepDelay.stories.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepDelay.stories.tsx
new file mode 100644
index 000000000000..80a3459ab5ba
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepDelay.stories.tsx
@@ -0,0 +1,69 @@
+import { Meta, StoryFn } from '@storybook/react'
+import { Node } from '@xyflow/react'
+import { BindLogic, useActions } from 'kea'
+import { useEffect } from 'react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { WorkflowLogicProps, workflowLogic } from '../../workflowLogic'
+import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { HogFlowAction } from '../types'
+import { StepDelayConfiguration } from './StepDelay'
+
+type DelayAction = Extract<HogFlowAction, { type: 'delay' }>
+
+const LOGIC_PROPS: WorkflowLogicProps = { id: 'new' }
+
+const meta: Meta<typeof StepDelayConfiguration> = {
+ title: 'Products/Workflows/Steps/Delay',
+ component: StepDelayConfiguration,
+ parameters: {
+ // The stories show the panel an author sees once the date mode is rolled out
+ featureFlags: [FEATURE_FLAGS.WORKFLOWS_DELAY_UNTIL_DATE],
+ },
+}
+export default meta
+
+function delayAction(config: DelayAction['config'], description: string): DelayAction {
+ return {
+ id: 'delay_1',
+ type: 'delay',
+ name: 'Delay',
+ description,
+ config,
+ } as DelayAction
+}
+
+const Template: StoryFn<{ action: DelayAction }> = ({ action }) => {
+ const { setWorkflowInfo } = useActions(workflowLogic(LOGIC_PROPS))
+
+ useEffect(() => {
+ setWorkflowInfo({ actions: [action] })
+ }, [action, setWorkflowInfo])
+
+ return (
+ <BindLogic logic={workflowLogic} props={LOGIC_PROPS}>
+ <BindLogic logic={hogFlowEditorLogic} props={LOGIC_PROPS}>
+ <div className="w-[420px] p-4 flex flex-col gap-2">
+ <StepDelayConfiguration node={{ data: action } as Node<DelayAction>} />
+ </div>
+ </BindLogic>
+ </BindLogic>
+ )
+}
+
+export const FixedDuration: StoryFn<{ action: DelayAction }> = Template.bind({})
+FixedDuration.args = { action: delayAction({ delay_duration: '10m' }, 'Wait for 10 minutes.') }
+
+export const DateOnThePerson: StoryFn<{ action: DelayAction }> = Template.bind({})
+DateOnThePerson.args = {
+ action: delayAction(
+ { delay_until: { expression: 'person.properties.trial_expires_at', offset: '-1d' } },
+ 'Wait until 1 day before trial_expires_at.'
+ ),
+}
+
+export const DateNotChosenYet: StoryFn<{ action: DelayAction }> = Template.bind({})
+DateNotChosenYet.args = {
+ action: delayAction({ delay_until: { expression: '' } }, 'Wait until a date on the person or event.'),
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepDelay.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepDelay.tsx
index 3a6bd12214b2..b5f3e73110e1 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepDelay.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepDelay.tsx
@@ -1,11 +1,32 @@
import { Node } from '@xyflow/react'
import { useActions, useValues } from 'kea'
+import { LemonInputSelect, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
+
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { timeZoneLabel } from 'lib/utils/timezones'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
import { workflowLogic } from '../../workflowLogic'
import { HogFlowAction } from '../types'
import { HogFlowDuration } from './components/HogFlowDuration'
import { StepSchemaErrors } from './components/StepSchemaErrors'
-import { stepDelayLogic } from './stepDelayLogic'
+import {
+ DEFAULT_DELAY_TIMEZONE,
+ DEFAULT_MAX_DELAY_DURATION,
+ DelayTimezone,
+ getDelayMode,
+ getDurationText,
+ parseDelayExpression,
+ parseDelayOffset,
+ stepDelayLogic,
+} from './stepDelayLogic'
+
+const PROPERTY_GROUP_TYPES = [TaxonomicFilterGroupType.PersonProperties, TaxonomicFilterGroupType.EventProperties]
export function StepDelayConfiguration({
node,
@@ -13,22 +34,195 @@ export function StepDelayConfiguration({
node: Node<Extract<HogFlowAction, { type: 'delay' }>>
}): JSX.Element {
const action = node.data
- const { delay_duration } = action.config
+ const config = action.config
const { logicProps } = useValues(workflowLogic)
- const { setDelayWorkflowActionConfig } = useActions(stepDelayLogic({ workflowLogicProps: logicProps }))
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { setDelayWorkflowActionConfig, setDelayMode, setDelayProperty, setDelayOffset, setDelayTimezone } =
+ useActions(stepDelayLogic({ workflowLogicProps: logicProps }))
+
+ // A step already configured for a date keeps its controls even without the flag, so the panel
+ // can't quietly turn a date wait into a fixed duration.
+ const dateModeAvailable = !!featureFlags[FEATURE_FLAGS.WORKFLOWS_DELAY_UNTIL_DATE] || !!config.delay_until
+
+ const mode = getDelayMode(config)
+ const expression = config.delay_until?.expression ?? ''
+ const property = parseDelayExpression(expression)
+ const offset = parseDelayOffset(config.delay_until?.offset)
+ // An expression saved through the API can be any SQL, so it may not read back as a property pick.
+ const customExpression = expression.trim() && !property ? expression : null
+ const maxDelayText = getDurationText(config.max_delay_duration ?? '') ?? getDurationText(DEFAULT_MAX_DELAY_DURATION)
+
+ if (!dateModeAvailable) {
+ return (
+ <>
+ <StepSchemaErrors />
+
+ <p className="mb-0">Wait for a specified duration.</p>
+ <HogFlowDuration
+ value={config.delay_duration ?? ''}
+ onChange={(value) => setDelayWorkflowActionConfig(action.id, { delay_duration: value })}
+ />
+ </>
+ )
+ }
return (
<>
<StepSchemaErrors />
- <p className="mb-0">Wait for a specified duration.</p>
- <HogFlowDuration
- value={delay_duration}
- onChange={(value) => {
- setDelayWorkflowActionConfig(action.id, { delay_duration: value })
- }}
- />
+ {/* Owns its own vertical rhythm: the panel does not space these siblings apart, so without this
+ the sentence row and the inputs beneath it sit flush together. */}
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span>Wait for</span>
+ <LemonSelect
+ size="small"
+ value={mode}
+ onChange={(value) => setDelayMode(action.id, value)}
+ options={[
+ { label: 'a specified duration', value: 'duration' as const },
+ { label: 'a date on the person or event', value: 'until' as const },
+ ]}
+ data-attr="workflow-delay-mode"
+ />
+ </div>
+
+ {mode === 'duration' ? (
+ <HogFlowDuration
+ value={config.delay_duration ?? ''}
+ onChange={(value) => setDelayWorkflowActionConfig(action.id, { delay_duration: value })}
+ />
+ ) : (
+ <>
+ <div className="flex flex-wrap items-center gap-2">
+ {offset.direction !== 'on' ? (
+ // Narrower than the duration mode's own input: this one is part of a sentence
+ // that has to fit next to the direction and the property.
+ <div className="w-44">
+ <HogFlowDuration
+ value={offset.duration}
+ onChange={(duration) => setDelayOffset(action.id, { ...offset, duration })}
+ // The offset can be any size; the wait itself is capped by max_delay_duration.
+ allowUnbounded
+ />
+ </div>
+ ) : null}
+ <LemonSelect
+ size="small"
+ value={offset.direction}
+ onChange={(value) => setDelayOffset(action.id, { ...offset, direction: value })}
+ options={[
+ { label: 'on', value: 'on' as const },
+ { label: 'before', value: 'before' as const },
+ { label: 'after', value: 'after' as const },
+ ]}
+ data-attr="workflow-delay-offset-direction"
+ />
+ <TaxonomicStringPopover
+ size="small"
+ // Reopen on the category the saved expression came from, so an event
+ // property does not read back as, and get silently repointed to, a person one.
+ groupType={
+ property?.source === 'event'
+ ? TaxonomicFilterGroupType.EventProperties
+ : TaxonomicFilterGroupType.PersonProperties
+ }
+ groupTypes={PROPERTY_GROUP_TYPES}
+ value={property?.key}
+ placeholder="Choose a date property"
+ onChange={(key, groupType) =>
+ setDelayProperty(action.id, {
+ source:
+ groupType === TaxonomicFilterGroupType.EventProperties ? 'event' : 'person',
+ key,
+ })
+ }
+ data-attr="workflow-delay-property"
+ />
+ </div>
+
+ {customExpression ? (
+ <p className="mb-0 mt-1 text-xs text-muted">
+ This step waits for <code>{customExpression}</code>, which was set through the API.
+ Choose a property to replace it.
+ </p>
+ ) : null}
+
+ <DelayTimezoneConfiguration
+ timezone={config.delay_until?.timezone}
+ usePersonTimezone={config.delay_until?.use_person_timezone}
+ fallbackTimezone={config.delay_until?.fallback_timezone}
+ onChange={(timezone) => setDelayTimezone(action.id, timezone)}
+ />
+
+ <p className="mb-0 mt-1 text-xs text-muted">
+ If the date moves further out, the wait follows it. If it moves closer, the wait still ends
+ on the original date, so the next step runs late. A run never waits more than {maxDelayText}{' '}
+ past this step.
+ </p>
+ </>
+ )}
+ </div>
</>
)
}
+
+/**
+ * A date stored without a zone ('2026-03-01', or '2026-03-01T09:00:00') is read in the zone chosen here.
+ * A date that carries its own offset already names an instant and ignores this.
+ */
+function DelayTimezoneConfiguration({
+ timezone,
+ usePersonTimezone,
+ fallbackTimezone,
+ onChange,
+}: {
+ timezone?: string | null
+ usePersonTimezone?: boolean
+ fallbackTimezone?: string | null
+ onChange: (timezone: DelayTimezone) => void
+}): JSX.Element {
+ const { preflight } = useValues(preflightLogic)
+
+ const timezoneOptions = Object.entries(preflight?.available_timezones || {}).map(([tz, offset]) => ({
+ key: tz,
+ label: timeZoneLabel(tz, offset),
+ }))
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSwitch
+ size="small"
+ checked={usePersonTimezone ?? false}
+ onChange={(checked) => onChange({ use_person_timezone: checked })}
+ label="Use the person's timezone"
+ bordered
+ tooltip="Requires the GeoIP transformation to be enabled in Data pipelines → Transformations."
+ data-attr="workflow-delay-use-person-timezone"
+ />
+
+ <LemonField.Pure
+ label={usePersonTimezone ? 'Fallback timezone' : 'Timezone'}
+ help={
+ usePersonTimezone
+ ? 'Used when the person has no timezone set.'
+ : 'A date with no timezone of its own is read in this timezone.'
+ }
+ >
+ <LemonInputSelect
+ mode="single"
+ size="small"
+ placeholder="Select a timezone"
+ value={[(usePersonTimezone ? fallbackTimezone || timezone : timezone) || DEFAULT_DELAY_TIMEZONE]}
+ popoverClassName="z-[1000]"
+ onChange={([selected]) =>
+ onChange(usePersonTimezone ? { fallback_timezone: selected } : { timezone: selected })
+ }
+ options={timezoneOptions}
+ data-attr="workflow-delay-timezone"
+ />
+ </LemonField.Pure>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.test.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.test.tsx
index 4bf7f3aade23..169d600ef789 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.test.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.test.tsx
@@ -71,6 +71,18 @@ describe('HogFlowDuration', () => {
expect(screen.getByText('Second(s)')).toBeInTheDocument()
})
+ it.each([
+ ['holds a day amount to the 30-day ceiling on blur by default', false, '30d'],
+ ['keeps a day amount past the ceiling on blur when unbounded', true, '45d'],
+ ])('%s', (_name, allowUnbounded, expected) => {
+ const onChange = jest.fn()
+ render(<HogFlowDuration value="45d" onChange={onChange} allowUnbounded={allowUnbounded as boolean} />)
+
+ fireEvent.blur(screen.getByRole('spinbutton'))
+
+ expect(onChange).toHaveBeenCalledWith(expected)
+ })
+
it('clears the field immediately on change even before the parent commits the new value', () => {
render(<HogFlowDuration value="2h" onChange={jest.fn()} />)
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx
index e2c3552b753c..7c4844e04d5b 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx
@@ -26,9 +26,13 @@ const EXPONENT_THRESHOLD = 1e21
export function HogFlowDuration({
value,
onChange,
+ allowUnbounded = false,
}: {
value: string
onChange: (value: string) => void
+ // The per-unit ceilings bound how long a fixed delay waits. A date offset is bounded by the
+ // step's max_delay_duration instead, so it opts out and keeps its full magnitude ("45 days before").
+ allowUnbounded?: boolean
}): JSX.Element {
const inputRef = useRef<HTMLInputElement>(null)
const parts = value.match(DURATION_REGEX)
@@ -48,9 +52,13 @@ export function HogFlowDuration({
setDisplayNumber(numberValue)
}, [numberValue])
+ // Holds an amount to the unit's ceiling, unless the field opts out (a date offset).
+ const capToUnit = (n: number, u: string): number =>
+ allowUnbounded ? n : Math.min(n, MAX_VALUE_FOR_DURATION_UNIT[u])
+
// Fractions are allowed, so the only lower bound is "greater than zero". Anything at or below it
// would save a delay that never waits, so snap those back up to one whole unit.
- const clamp = (n: number): number => (n > 0 ? Math.min(n, MAX_VALUE_FOR_DURATION_UNIT[unit]) : 1)
+ const clamp = (n: number): number => (n > 0 ? capToUnit(n, unit) : 1)
const normalizeAmount = (n: number): number =>
n >= EXPONENT_THRESHOLD ? MAX_VALUE_FOR_DURATION_UNIT[unit] : Number(n.toFixed(MAX_FRACTION_DIGITS))
@@ -62,7 +70,7 @@ export function HogFlowDuration({
inputRef={inputRef}
value={displayNumber ?? NaN}
min={0}
- max={MAX_VALUE_FOR_DURATION_UNIT[unit]}
+ max={allowUnbounded ? undefined : MAX_VALUE_FOR_DURATION_UNIT[unit]}
step="any"
onKeyDown={(e) => {
if (BLOCKED_NUMBER_INPUT_KEYS.has(e.key)) {
@@ -97,11 +105,7 @@ export function HogFlowDuration({
{ label: 'Day(s)', value: 'd' },
]}
value={unit}
- onChange={(v) =>
- onChange(
- `${displayNumber === undefined ? '' : Math.min(displayNumber, MAX_VALUE_FOR_DURATION_UNIT[v])}${v}`
- )
- }
+ onChange={(v) => onChange(`${displayNumber === undefined ? '' : capToUnit(displayNumber, v)}${v}`)}
/>
</div>
)
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
index d7e67f59719e..99cb2d6953d6 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.test.ts
@@ -7,7 +7,18 @@ import { initKeaTests } from '~/test/init'
import { workflowLogic } from '../../workflowLogic'
import { HogFlowAction } from '../types'
-import { getDelayDescription, stepDelayLogic } from './stepDelayLogic'
+import {
+ DelayActionConfig,
+ DelayOffset,
+ DelayProperty,
+ buildDelayExpression,
+ buildDelayOffset,
+ getDelayDescription,
+ parseDelayExpression,
+ parseDelayOffset,
+ shouldAutoUpdateDescription,
+ stepDelayLogic,
+} from './stepDelayLogic'
describe('stepDelayLogic', () => {
let sdLogic: ReturnType<typeof stepDelayLogic.build>
@@ -27,13 +38,16 @@ describe('stepDelayLogic', () => {
sdLogic.mount()
})
- const setupInitialDelayAction = async (initialDescription: string): Promise<HogFlowAction> => {
+ const setupInitialDelayAction = async (
+ initialDescription: string,
+ config: DelayActionConfig = { delay_duration: '10m' }
+ ): Promise<HogFlowAction> => {
const delayAction = {
id: `delay_action_${uuid()}`,
type: 'delay',
name: 'Delay',
description: initialDescription,
- config: { delay_duration: '10m' },
+ config,
created_at: Date.now(),
updated_at: Date.now(),
} as HogFlowAction
@@ -53,8 +67,14 @@ describe('stepDelayLogic', () => {
return delayAction
}
+ const configOf = (actionId: string): DelayActionConfig =>
+ wfLogic.values.workflow.actions.find((a) => a.id === actionId)?.config as DelayActionConfig
+
+ const descriptionOf = (actionId: string): string =>
+ wfLogic.values.workflow.actions.find((a) => a.id === actionId)?.description ?? ''
+
it('should update the description when the duration is changed', async () => {
- const delayAction = await setupInitialDelayAction(getDelayDescription('10m'))
+ const delayAction = await setupInitialDelayAction(getDelayDescription({ delay_duration: '10m' }))
await expectLogic(sdLogic, () => {
sdLogic.actions.setDelayWorkflowActionConfig(delayAction.id, { delay_duration: '5m' })
@@ -86,6 +106,156 @@ describe('stepDelayLogic', () => {
})
})
+ // A key the builder cannot read back leaves the picker blank on reload, so the user's choice looks
+ // lost and re-picking silently overwrites it. Property keys carry $, spaces and quotes in practice.
+ // An event property is `properties.x`, not `event.properties.x`: the expression is evaluated against
+ // the same globals as a filter, where `event` is the event's name. Getting this wrong resolves to
+ // nothing at run time and aborts the run instead of waiting.
+ it.each([
+ [{ source: 'person', key: 'expires_at' } as DelayProperty, 'person.properties.expires_at'],
+ [{ source: 'event', key: 'scheduled_at' } as DelayProperty, 'properties.scheduled_at'],
+ [{ source: 'person', key: '$trial_ends' } as DelayProperty, "person.properties['$trial_ends']"],
+ [{ source: 'person', key: 'renews on' } as DelayProperty, "person.properties['renews on']"],
+ [{ source: 'event', key: "o'clock" } as DelayProperty, "properties['o\\'clock']"],
+ ])('%o round trips through %p', (property, expression) => {
+ expect(buildDelayExpression(property)).toBe(expression)
+ expect(parseDelayExpression(expression)).toEqual(property)
+ })
+
+ // Shown as a hand-written expression rather than a picked property, which is what invites the user to
+ // re-pick it. Reading it back as a property would present an unrunnable step as configured.
+ it.each([
+ ['a composed expression', 'toDateTime(person.properties.a) + toIntervalDay(1)'],
+ ['an event property written with the event prefix', 'event.properties.expires_at'],
+ ])('reads back no property for %s', (_label, expression) => {
+ expect(parseDelayExpression(expression)).toBeNull()
+ })
+
+ // The sign carries the direction. Losing it turns "a day before their trial ends" into a message
+ // sent a day late, which reads as working right up until someone checks the send times.
+ it.each([
+ [{ duration: '1d', direction: 'before' } as DelayOffset, '-1d'],
+ [{ duration: '2h', direction: 'after' } as DelayOffset, '2h'],
+ [{ duration: '1.5d', direction: 'before' } as DelayOffset, '-1.5d'],
+ [{ duration: '30s', direction: 'after' } as DelayOffset, '30s'],
+ ])('%o round trips through %p', (offset, serialized) => {
+ expect(buildDelayOffset(offset)).toBe(serialized)
+ expect(parseDelayOffset(serialized)).toEqual(offset)
+ })
+
+ // 'on' has to save nothing rather than '0d', and a cleared duration input emits just its unit.
+ it.each([
+ [{ duration: '1d', direction: 'on' } as DelayOffset],
+ [{ duration: 'd', direction: 'before' } as DelayOffset],
+ [{ duration: '', direction: 'after' } as DelayOffset],
+ ])('saves no offset for %o', (offset) => {
+ expect(buildDelayOffset(offset)).toBeUndefined()
+ })
+
+ it('starts a fresh date delay on the date itself', () => {
+ expect(parseDelayOffset(undefined).direction).toBe('on')
+ })
+
+ // Agent-created actions can omit description entirely, and editing such a delay must not throw.
+ it('treats an action with no description as auto-written', () => {
+ expect(shouldAutoUpdateDescription(undefined)).toBe(true)
+ })
+
+ // The API rejects a config carrying both modes, so a merge here would 400 every save. The value the
+ // author set has to come back on a switch across and back all the same, which is why '5h' is not the
+ // default: a default-valued fixture cannot tell a restored duration from a fresh one.
+ it('drops the duration when switching to a date, and restores it when switching back', async () => {
+ const delayAction = await setupInitialDelayAction(getDelayDescription({ delay_duration: '5h' }), {
+ delay_duration: '5h',
+ max_delay_duration: '7d',
+ })
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayMode(delayAction.id, 'until')
+ }).toFinishListeners()
+
+ expect(configOf(delayAction.id)).toEqual({
+ delay_until: { expression: '' },
+ max_delay_duration: '7d',
+ })
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayMode(delayAction.id, 'duration')
+ }).toFinishListeners()
+
+ expect(configOf(delayAction.id)).toEqual({ delay_duration: '5h' })
+ })
+
+ // A misclick on the mode select must not throw away the date, its offset and its timezone.
+ it('restores a configured date when switching to a duration and back', async () => {
+ const configured = {
+ delay_until: {
+ expression: 'person.properties.expires_at',
+ offset: '-2d',
+ timezone: 'Europe/Berlin',
+ },
+ }
+ const delayAction = await setupInitialDelayAction(getDelayDescription(configured), configured)
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayMode(delayAction.id, 'duration')
+ }).toFinishListeners()
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayMode(delayAction.id, 'until')
+ }).toFinishListeners()
+
+ expect(configOf(delayAction.id)).toEqual(configured)
+ })
+
+ it('composes the expression and offset onto delay_until', async () => {
+ const delayAction = await setupInitialDelayAction('', { delay_until: { expression: '' } })
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayProperty(delayAction.id, { source: 'person', key: 'expires_at' })
+ }).toFinishListeners()
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayOffset(delayAction.id, { duration: '1d', direction: 'before' })
+ }).toFinishListeners()
+
+ expect(configOf(delayAction.id)).toEqual({
+ delay_until: { expression: 'person.properties.expires_at', offset: '-1d' },
+ })
+ expect(descriptionOf(delayAction.id)).toBe('Wait until 1 day before expires_at.')
+ })
+
+ // Clearing the amount emits a unit-only 'd', which serializes to no offset and reads back as
+ // direction 'on', unmounting the amount field mid-edit. Keep the last offset so the author can
+ // type a replacement; only picking 'on' actually drops it.
+ it.each([
+ ['keeps the last offset when the amount is cleared mid-edit', { duration: 'd', direction: 'before' }, '-2d'],
+ ['drops the offset when the direction becomes on', { duration: '2d', direction: 'on' }, undefined],
+ ])('%s', async (_label, offset, expected) => {
+ const configured = { delay_until: { expression: 'person.properties.expires_at', offset: '-2d' } }
+ const delayAction = await setupInitialDelayAction(getDelayDescription(configured), configured)
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayOffset(delayAction.id, offset as DelayOffset)
+ }).toFinishListeners()
+
+ expect(configOf(delayAction.id).delay_until?.offset).toBe(expected)
+ })
+
+ it('keeps a customized description when the mode changes', async () => {
+ const customDescription = 'Nudge them before renewal'
+ const delayAction = await setupInitialDelayAction(customDescription)
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayMode(delayAction.id, 'until')
+ }).toFinishListeners()
+
+ await expectLogic(sdLogic, () => {
+ sdLogic.actions.setDelayProperty(delayAction.id, { source: 'person', key: 'expires_at' })
+ }).toFinishListeners()
+
+ expect(descriptionOf(delayAction.id)).toBe(customDescription)
+ })
+
it('should auto-update the description when the action has no description', async () => {
// Agent-created actions can arrive without a description key; editing one must not throw on .trim().
const delayAction = {
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
index 2208cbd2b3c1..bc546d5aa700 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
@@ -4,8 +4,19 @@ import { WorkflowLogicProps, workflowLogic } from '../../workflowLogic'
import type { HogFlow, HogFlowAction } from '../types'
const DURATION_REGEX = /^(\d*\.?\d*)([dhms])$/
+const OFFSET_REGEX = /^(-?)(\d*\.?\d+)([dhms])$/
const AUTO_DESCRIPTION_REGEX = /^Wait for \d*\.?\d+ (second|minute|hour|day)s?\.$/
const LEGACY_DEFAULT_DESCRIPTION = 'Wait for a specified duration.'
+const UNCONFIGURED_UNTIL_DESCRIPTION = 'Wait until a date on the person or event.'
+
+// A property key only reads back as `person.properties.foo` when it is a bare identifier. Anything
+// else (spaces, a leading $, punctuation) has to go through brackets to survive the round trip.
+const BARE_IDENTIFIER_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/
+// An event's own properties are `properties.foo`, with no prefix: the expression runs against the same
+// globals as a filter, where `event` is the event's name rather than an object. `event.properties.foo`
+// reads a field off that string, resolves to nothing, and aborts every run of the step.
+const DOTTED_EXPRESSION_REGEX = /^(?:(person)\.)?properties\.([A-Za-z_][A-Za-z0-9_]*)$/
+const BRACKETED_EXPRESSION_REGEX = /^(?:(person)\.)?properties\['((?:[^'\\]|\\.)*)'\]$/
const UNIT_LABELS: Record<string, string> = {
s: 'second',
@@ -14,29 +25,134 @@ const UNIT_LABELS: Record<string, string> = {
d: 'day',
}
-export function getDelayDescription(duration: string): string {
+export type DelayActionConfig = Extract<HogFlowAction, { type: 'delay' }>['config']
+
+export type DelayMode = 'duration' | 'until'
+/** 'on' means no offset at all: wait for the date itself. */
+export type DelayOffsetDirection = 'on' | 'before' | 'after'
+export type DelayPropertySource = 'person' | 'event'
+
+export interface DelayProperty {
+ source: DelayPropertySource
+ key: string
+}
+
+export interface DelayOffset {
+ /** An unsigned duration string, the same shape HogFlowDuration edits. */
+ duration: string
+ direction: DelayOffsetDirection
+}
+
+/** Only the fields the timezone controls change, merged onto whatever else delay_until holds. */
+export interface DelayTimezone {
+ timezone?: string | null
+ use_person_timezone?: boolean
+ fallback_timezone?: string | null
+}
+
+/** Matches the executor's default when no zone is configured. */
+export const DEFAULT_DELAY_TIMEZONE = 'UTC'
+
+export const DEFAULT_DELAY_DURATION = '10m'
+// Mirrors the executor's cap in nodejs/src/cdp/services/hogflows/actions/delay.ts.
+export const DEFAULT_MAX_DELAY_DURATION = '30d'
+
+export function getDelayMode(config: DelayActionConfig): DelayMode {
+ return config.delay_until ? 'until' : 'duration'
+}
+
+export function buildDelayExpression({ source, key }: DelayProperty): string {
+ const prefix = source === 'person' ? 'person.properties' : 'properties'
+ if (BARE_IDENTIFIER_REGEX.test(key)) {
+ return `${prefix}.${key}`
+ }
+ return `${prefix}['${key.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}']`
+}
+
+/** Null for an expression the builder did not compose, e.g. hand-written SQL saved through the API. */
+export function parseDelayExpression(expression: string): DelayProperty | null {
+ const dotted = expression.match(DOTTED_EXPRESSION_REGEX)
+ if (dotted) {
+ return { source: dotted[1] === 'person' ? 'person' : 'event', key: dotted[2] }
+ }
+ const bracketed = expression.match(BRACKETED_EXPRESSION_REGEX)
+ if (bracketed) {
+ return { source: bracketed[1] === 'person' ? 'person' : 'event', key: bracketed[2].replace(/\\(.)/g, '$1') }
+ }
+ return null
+}
+
+/** Undefined for direction 'on', so "wait for the date itself" saves no offset at all. */
+export function buildDelayOffset({ duration, direction }: DelayOffset): string | undefined {
+ if (direction === 'on' || !DURATION_REGEX.test(duration) || !Number.isFinite(parseFloat(duration))) {
+ return undefined
+ }
+ return `${direction === 'before' ? '-' : ''}${duration}`
+}
+
+export function parseDelayOffset(offset: string | undefined): DelayOffset {
+ const parts = offset?.match(OFFSET_REGEX)
+ if (!parts) {
+ // A day is the offset almost every reminder uses, so it is the amount to start from once
+ // someone switches off 'on'.
+ return { duration: '1d', direction: 'on' }
+ }
+ return { duration: `${parts[2]}${parts[3]}`, direction: parts[1] === '-' ? 'before' : 'after' }
+}
+
+/** "2 days" for '2d'. Null when there is no number to read, e.g. a cleared duration input. */
+export function getDurationText(duration: string): string | null {
const parts = duration.match(DURATION_REGEX)
const number = parseFloat(parts?.[1] ?? '')
- const unit = parts?.[2] ?? 'm'
- // No valid number yet (e.g. the input was cleared) - keep a neutral description
if (!Number.isFinite(number)) {
- return LEGACY_DEFAULT_DESCRIPTION
+ return null
+ }
+ const unitLabel = UNIT_LABELS[parts?.[2] ?? 'm'] ?? 'minute'
+ return `${number} ${unitLabel}${number !== 1 ? 's' : ''}`
+}
+
+export function getDelayDescription(config: DelayActionConfig): string {
+ if (config.delay_until) {
+ const expression = config.delay_until.expression
+ if (!expression.trim()) {
+ return UNCONFIGURED_UNTIL_DESCRIPTION
+ }
+ // The property name alone reads better than the expression it was composed from, but an
+ // expression the builder cannot read back has nothing shorter to show.
+ const dateText = parseDelayExpression(expression)?.key ?? expression
+ const offsetText = getDurationText(config.delay_until.offset?.replace('-', '') ?? '')
+ if (!offsetText || !config.delay_until.offset) {
+ return `Wait until ${dateText}.`
+ }
+ const direction = config.delay_until.offset.startsWith('-') ? 'before' : 'after'
+ return `Wait until ${offsetText} ${direction} ${dateText}.`
}
- const unitLabel = UNIT_LABELS[unit] ?? 'minute'
- const durationText = `${number} ${unitLabel}${number !== 1 ? 's' : ''}`
- return `Wait for ${durationText}.`
+
+ // No valid number yet (e.g. the input was cleared) - keep a neutral description
+ const durationText = getDurationText(config.delay_duration ?? '')
+ return durationText ? `Wait for ${durationText}.` : LEGACY_DEFAULT_DESCRIPTION
}
-export function shouldAutoUpdateDescription(description: string | undefined): boolean {
- // Agent-created actions can arrive without a description at all; treat an absent one like empty.
+export function shouldAutoUpdateDescription(description: string | undefined, config?: DelayActionConfig): boolean {
return (
+ // Agent-created actions can arrive with no description at all, so treat an absent one like an empty one.
!description ||
description.trim() === '' ||
AUTO_DESCRIPTION_REGEX.test(description) ||
- description === LEGACY_DEFAULT_DESCRIPTION
+ description === LEGACY_DEFAULT_DESCRIPTION ||
+ description === UNCONFIGURED_UNTIL_DESCRIPTION ||
+ // An until-mode description ends in a property name, which no regex can tell apart from a
+ // description someone typed. Comparing against what the step's current config generates
+ // identifies the auto-written one exactly.
+ (config !== undefined && description === getDelayDescription(config))
)
}
+function findDelayAction(workflow: HogFlow, actionId: string): Extract<HogFlowAction, { type: 'delay' }> | undefined {
+ const action = workflow.actions.find((a) => a.id === actionId)
+ return action?.type === 'delay' ? (action as Extract<HogFlowAction, { type: 'delay' }>) : undefined
+}
+
export type StepDelayLogicProps = {
workflowLogicProps: WorkflowLogicProps
}
@@ -64,9 +180,6 @@ export interface stepDelayLogicActions {
percentage: number
}[]
}
- | {
- delay_duration: string
- }
| {
reason?: string | undefined
}
@@ -136,6 +249,21 @@ export interface stepDelayLogicActions {
| undefined
max_wait_duration: string
}
+ | {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
| {
inputs: Record<
string,
@@ -344,9 +472,6 @@ export interface stepDelayLogicActions {
percentage: number
}[]
}
- | {
- delay_duration: string
- }
| {
reason?: string | undefined
}
@@ -416,6 +541,21 @@ export interface stepDelayLogicActions {
| undefined
max_wait_duration: string
}
+ | {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
| {
filters: {
properties?: any[] | undefined
@@ -616,15 +756,53 @@ export interface stepDelayLogicActions {
tracking_enabled?: boolean | undefined
}
} // workflowLogic
+ setDelayMode: (
+ actionId: string,
+ mode: DelayMode
+ ) => {
+ actionId: string
+ mode: DelayMode
+ }
+ setDelayOffset: (
+ actionId: string,
+ offset: DelayOffset
+ ) => {
+ actionId: string
+ offset: DelayOffset
+ }
+ setDelayProperty: (
+ actionId: string,
+ property: DelayProperty
+ ) => {
+ actionId: string
+ property: DelayProperty
+ }
+ setDelayTimezone: (
+ actionId: string,
+ timezone: DelayTimezone
+ ) => {
+ actionId: string
+ timezone: DelayTimezone
+ }
setDelayWorkflowActionConfig: (
actionId: string,
- config: {
- delay_duration: string
- }
+ config: DelayActionConfig
) => {
actionId: string
config: {
- delay_duration: string
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
}
}
}
@@ -650,24 +828,102 @@ export const stepDelayLogic = kea<stepDelayLogicType>([
actions: [workflowLogic(workflowLogicProps), ['setWorkflowActionConfig', 'setWorkflowAction']],
})),
actions({
- setDelayWorkflowActionConfig: (actionId: string, config: { delay_duration: string }) => ({ actionId, config }),
+ setDelayWorkflowActionConfig: (actionId: string, config: DelayActionConfig) => ({ actionId, config }),
+ setDelayMode: (actionId: string, mode: DelayMode) => ({ actionId, mode }),
+ setDelayProperty: (actionId: string, property: DelayProperty) => ({ actionId, property }),
+ setDelayOffset: (actionId: string, offset: DelayOffset) => ({ actionId, offset }),
+ setDelayTimezone: (actionId: string, timezone: DelayTimezone) => ({ actionId, timezone }),
}),
- listeners(({ values, actions }) => ({
+ listeners(({ values, actions, cache }) => ({
setDelayWorkflowActionConfig: ({ actionId, config }) => {
+ // Read before the write: whether the description was auto-written is a question about the
+ // config it was generated from, which the dispatch below replaces.
+ const previous = findDelayAction(values.workflow, actionId)
+
actions.setWorkflowActionConfig(actionId, config)
- const action = values.workflow.actions.find((a) => a.id === actionId)
- if (!action || action.type !== 'delay') {
+ if (!previous || !shouldAutoUpdateDescription(previous.description, previous.config)) {
return
}
+ const action = findDelayAction(values.workflow, actionId)
+ if (action) {
+ actions.setWorkflowAction(actionId, { ...action, description: getDelayDescription(config) })
+ }
+ },
- const delayConfig = config as { delay_duration: string }
- if (shouldAutoUpdateDescription(action.description)) {
- actions.setWorkflowAction(actionId, {
- ...action,
- description: getDelayDescription(delayConfig.delay_duration),
+ setDelayMode: ({ actionId, mode }) => {
+ const action = findDelayAction(values.workflow, actionId)
+ const leaving = action ? getDelayMode(action.config) : undefined
+ if (!action || leaving === mode) {
+ return
+ }
+ // The config is replaced rather than merged, because the backend accepts exactly one of the
+ // two modes and rejects a config carrying both. So the mode being left is remembered here for
+ // as long as the editor is open: switching across and back otherwise resets a configured
+ // duration to the default, and drops the chosen date, its offset and its timezone.
+ const remembered: Record<string, DelayActionConfig> = (cache.configByMode ??= {})
+ const restored = remembered[`${actionId}:${mode}`]
+ remembered[`${actionId}:${leaving}`] = action.config
+
+ if (mode === 'duration') {
+ actions.setDelayWorkflowActionConfig(actionId, {
+ delay_duration: restored?.delay_duration ?? DEFAULT_DELAY_DURATION,
})
+ return
+ }
+ // max_delay_duration is only meaningful alongside delay_until, so it comes across from
+ // whichever side of the switch still carries it, and never stays on a duration delay.
+ const maxDelayDuration = action.config.max_delay_duration ?? restored?.max_delay_duration
+ actions.setDelayWorkflowActionConfig(actionId, {
+ delay_until: restored?.delay_until ?? { expression: '' },
+ ...(maxDelayDuration ? { max_delay_duration: maxDelayDuration } : {}),
+ })
+ },
+
+ setDelayProperty: ({ actionId, property }) => {
+ const action = findDelayAction(values.workflow, actionId)
+ if (!action?.config.delay_until) {
+ return
+ }
+ actions.setDelayWorkflowActionConfig(actionId, {
+ ...action.config,
+ delay_until: {
+ ...action.config.delay_until,
+ expression: buildDelayExpression(property),
+ },
+ })
+ },
+
+ setDelayOffset: ({ actionId, offset }) => {
+ const action = findDelayAction(values.workflow, actionId)
+ if (!action?.config.delay_until) {
+ return
+ }
+ const serialized = buildDelayOffset(offset)
+ // Only direction 'on' truly means "no offset". A cleared amount also serializes to undefined,
+ // but writing it reads back as 'on' and unmounts the amount field mid-edit. Keep the last
+ // stored offset in that case, so the author can type a replacement into the field they cleared.
+ if (serialized === undefined && offset.direction !== 'on') {
+ return
+ }
+ actions.setDelayWorkflowActionConfig(actionId, {
+ ...action.config,
+ delay_until: {
+ ...action.config.delay_until,
+ offset: serialized,
+ },
+ })
+ },
+
+ setDelayTimezone: ({ actionId, timezone }) => {
+ const action = findDelayAction(values.workflow, actionId)
+ if (!action?.config.delay_until) {
+ return
}
+ actions.setDelayWorkflowActionConfig(actionId, {
+ ...action.config,
+ delay_until: { ...action.config.delay_until, ...timezone },
+ })
},
})),
])
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
index 89054803e393..bb8605494cef 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
@@ -105,9 +105,6 @@ export interface stepWaitUntilTimeWindowLogicActions {
percentage: number
}[]
}
- | {
- delay_duration: string
- }
| {
reason?: string | undefined
}
@@ -177,6 +174,21 @@ export interface stepWaitUntilTimeWindowLogicActions {
| undefined
max_wait_duration: string
}
+ | {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
| {
inputs: Record<
string,
@@ -386,9 +398,6 @@ export interface stepWaitUntilTimeWindowLogicActions {
percentage: number
}[]
}
- | {
- delay_duration: string
- }
| {
reason?: string | undefined
}
@@ -458,6 +467,21 @@ export interface stepWaitUntilTimeWindowLogicActions {
| undefined
max_wait_duration: string
}
+ | {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
| {
filters: {
properties?: any[] | undefined
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.test.ts
index 20e7228f52e9..9969051b41db 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/types.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.test.ts
@@ -86,6 +86,30 @@ describe('HogFlowActionSchema', () => {
expect(HogFlowActionSchema.safeParse(delayAction(duration)).success).toBe(valid)
})
+ // The API takes exactly one of the two delay modes. A config the editor calls valid but the API
+ // rejects saves as a draft and then fails to activate, pointing at nothing visible on screen.
+ const delayConfigAction = (config: Record<string, unknown>): Record<string, unknown> => ({
+ id: 'delay_node',
+ name: 'Delay',
+ type: 'delay',
+ description: '',
+ config,
+ })
+
+ it.each([
+ ['a duration alone', { delay_duration: '1d' }, true],
+ ['a date alone', { delay_until: { expression: 'person.properties.expires_at' } }, true],
+ ['a date with an offset', { delay_until: { expression: 'person.properties.x', offset: '-1d' } }, true],
+ ['a date with a cap', { delay_until: { expression: 'person.properties.x' }, max_delay_duration: '7d' }, true],
+ ['both modes', { delay_duration: '1d', delay_until: { expression: 'person.properties.x' } }, false],
+ ['neither mode', {}, false],
+ ['a date with no expression', { delay_until: { expression: '' } }, false],
+ ['an offset in an unsupported unit', { delay_until: { expression: 'x', offset: '1w' } }, false],
+ ['a cap that is not a duration', { delay_until: { expression: 'x' }, max_delay_duration: '7' }, false],
+ ])('delay config with %s → valid=%p', (_label, config, valid) => {
+ expect(HogFlowActionSchema.safeParse(delayConfigAction(config)).success).toBe(valid)
+ })
+
it.each([
['5m', true],
['2h', true],
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
index e3d34f9582dc..d4f8cf2271dd 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
@@ -33,6 +33,13 @@ const DURATION_STRING = z.string().superRefine((v, ctx) => {
}
})
+// A delay offset points either side of the date it offsets, so unlike DURATION_STRING it is signed.
+const OFFSET_DURATION_STRING = z.string().superRefine((v, ctx) => {
+ if (!/^-?\d*\.?\d+[dhms]$/.test(v)) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Offset must be a number followed by s, m, h, or d' })
+ }
+})
+
const _commonActionFields = {
id: z.string(),
name: z.string(),
@@ -241,9 +248,56 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
z.object({
..._commonActionFields,
type: z.literal('delay'),
- config: z.object({
- delay_duration: DURATION_STRING,
- }),
+ // Two ways to say when to continue, exactly one of which is set. `delay_duration` waits a fixed span
+ // from when the step starts; `delay_until` waits for an instant carried by the person or the event.
+ // Keep in sync with nodejs/src/cdp/schema/hogflow.ts and the server-side validation in hog_flow.py.
+ config: z
+ .object({
+ delay_duration: DURATION_STRING.optional(),
+ delay_until: z
+ .object({
+ // HogQL evaluating to a datetime. The builder composes it from a property picker,
+ // but the API accepts any expression, so anything can turn up here.
+ expression: z.string(),
+ offset: OFFSET_DURATION_STRING.optional(),
+ // Which zone a date carrying no offset of its own is read in, the same three
+ // fields wait_until_time_window uses.
+ timezone: z.string().nullish(),
+ use_person_timezone: z.boolean().optional(),
+ fallback_timezone: z.string().nullish(),
+ // Compiled server-side at save; whatever the client sends is discarded.
+ bytecode: z.any().optional(),
+ bytecode_error: z.string().optional(),
+ })
+ .optional(),
+ max_delay_duration: DURATION_STRING.optional(),
+ })
+ .superRefine((config, ctx) => {
+ if (!config.delay_until) {
+ if (config.delay_duration === undefined) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['delay_duration'],
+ message: 'Please enter a duration',
+ })
+ }
+ return
+ }
+ if (config.delay_duration !== undefined) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['delay_until'],
+ message: 'A delay waits either for a duration or until a date, not both',
+ })
+ }
+ if (!config.delay_until.expression.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['delay_until', 'expression'],
+ message: 'Please choose a date to wait for',
+ })
+ }
+ }),
}),
z.object({
..._commonActionFields,
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index 4906fba83f77..c751713713b1 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -363,7 +363,19 @@ export interface workflowLogicActions {
}
| {
config: {
- delay_duration: string
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
}
created_at?: number | undefined
description: string
@@ -1191,7 +1203,19 @@ export interface workflowLogicActions {
}
| {
config: {
- delay_duration: string
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
}
created_at?: number | undefined
description: string
@@ -1987,9 +2011,6 @@ export interface workflowLogicActions {
percentage: number
}[]
}
- | {
- delay_duration: string
- }
| {
reason?: string | undefined
}
@@ -2059,6 +2080,21 @@ export interface workflowLogicActions {
| undefined
max_wait_duration: string
}
+ | {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
| {
inputs: Record<
string,
@@ -2350,9 +2386,6 @@ export interface workflowLogicActions {
percentage: number
}[]
}
- | {
- delay_duration: string
- }
| {
reason?: string | undefined
}
@@ -2422,6 +2455,21 @@ export interface workflowLogicActions {
| undefined
max_wait_duration: string
}
+ | {
+ delay_duration?: string | undefined
+ delay_until?:
+ | {
+ bytecode?: any
+ bytecode_error?: string | undefined
+ expression: string
+ fallback_timezone?: string | null | undefined
+ offset?: string | undefined
+ timezone?: string | null | undefined
+ use_person_timezone?: boolean | undefined
+ }
+ | undefined
+ max_delay_duration?: string | undefined
+ }
| {
inputs: Record<
string,
diff --git a/products/workflows/frontend/generated/agentContext.ts b/products/workflows/frontend/generated/agentContext.ts
index d9f956a7d70b..cc339481d2a1 100644
--- a/products/workflows/frontend/generated/agentContext.ts
+++ b/products/workflows/frontend/generated/agentContext.ts
@@ -178,7 +178,7 @@ export const BUILDING_WORKFLOWS_SKILL: EmbeddedSkill = {
description:
'Build, edit, test, enable, and monitor PostHog workflows over MCP. Author the action/edge graph so it runs and opens cleanly in the visual editor, then change drafts surgically with patch operations. Use when asked to build, set up, automate, change, fix, or debug a workflow, campaign, broadcast, drip sequence, or event-triggered automation in the workflows product.',
content:
- '# Building workflows\n\nA PostHog **workflow** is a directed graph: a list of **action nodes** (`actions`) wired by **edges** (`edges`), with exactly one `trigger` node that starts every run. You author that graph as JSON and ship it over MCP. Always call it a "workflow" to the user. "Hog flow" is the internal code name (`HogFlow`), not a user-facing term.\n\nThe single biggest failure mode is **getting the graph JSON structurally wrong**. The backend stores `actions`/`config` as loose JSON, but the visual editor parses every node against a strict schema, so a malformed node saves but then **breaks the editor view** for the whole workflow. Before composing or editing any graph, read [references/graph-schema.md](references/graph-schema.md). It is the contract; do not improvise node shapes from these examples alone.\n\n## The lifecycle\n\nWork the workflow through these stages. Don\'t jump straight to enabling it.\n\n1. **Compose the graph.** Build `actions` + `edges` per [references/graph-schema.md](references/graph-schema.md). For any `function` node, don\'t guess the template: list the live catalog with `cdp-function-templates-list` and read its required inputs with `cdp-function-templates-retrieve`.\n2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.\n3. **Test-run it.** `workflows-test-run` runs **one step at a time**. Start at the first step (omit `current_action_id`, or point it at the trigger) with sample `globals` (`{event, person, groups}`); the result includes the next step\'s id (`nextActionId`). Feed that back as `current_action_id` and run again, walking step by step to the end. Skip `delay` nodes by jumping to the action after them (delays aren\'t simulated). Async side effects (HTTP/email/SMS/push) are mocked unless you set `mock_async_functions=false`. Read each step\'s trace to confirm the path taken.\n4. **Read logs while iterating.** `workflows-logs` shows the per-step execution trace (levels DEBUG to ERROR). This is how you see _why_ a step skipped, branched, or errored.\n5. **Edit, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. On a draft workflow, edits apply directly; on an active one they stage a draft (see [Changing a live workflow](#changing-a-live-workflow)).\n6. **Enable (needs the user\'s explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. From then on it runs on real people, and every change goes through the draft → test → publish cycle before taking effect — so finish testing, then get the user\'s explicit go before enabling. Don\'t enable on your own initiative.\n7. **Dispatch (batch/schedule only).** A `batch` workflow does **not** fire on enable alone. Send a one-off broadcast with `workflows-run-batch`, or attach a recurring schedule with `workflows-schedule-create`. Confirm with `workflows-get` that `status==\'active\'` _and_ its read-only `schedules` field has an active entry.\n8. **Monitor.** Drill down: `workflows-global-stats` (which workflows are failing) to `workflows-stats` (one workflow\'s trend) to `workflows-list-invocations` (who it failed for) to `workflows-get-invocation` (the triggering payload) to `workflows-logs` (the failing step).\n\nFull tool catalog, grouped by job: [references/lifecycle-and-debugging.md](references/lifecycle-and-debugging.md).\n\n## Editing a draft\n\n**Patch, don\'t replace.** Edit a draft with `workflows-patch-graph`: a small, ordered list of id-addressed operations (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`). `update_action` deep-merges its patch, so changing one email subject is a few lines, not the whole graph. The ops apply atomically server-side (read, apply in order, validate, save only if valid), and the response echoes the **full updated graph**, so you never re-fetch before the next edit. This keeps each round-trip tiny instead of re-transmitting every action and edge.\n\n`workflows-update` covers only what a graph patch can\'t express: top-level fields like name, description, exit_condition, conversion, trigger_masking, and variables. It rejects `actions`/`edges` outright - a partial list would silently drop every step it omits - so every graph change goes through `workflows-patch-graph`.\n\nAfter **any** patch, re-test the path you changed (step 3). A patch that validates structurally can still route the wrong way.\n\nEmail content follows the same rule.\nThe email inside a `function_email` step is edited with **`workflows-patch-action-email`**: the same id-addressed design ops as the template patch, plus an `email_patch` merge for subject/preheader/text/recipients, with the HTML re-rendered server-side so it always matches the design.\nPrefer it over `workflows-patch-graph` `update_action` for email content - an `update_action` that changes `design` leaves the stored `html` stale.\nLibrary templates are edited with **`workflows-patch-email-template`**, not `workflows-update-email-template` (which resends the entire design JSON).\nCompose and edit email designs with the **`designing-email-templates`** skill.\n\n## Changing a live workflow\n\nEditing an active workflow stages a **draft** instead of changing what\'s running: nothing reaches real people until you publish. Work the cycle:\n\n1. **Edit.** `workflows-patch-graph` (or `workflows-update` for content fields) on the active workflow writes to its draft — the first edit copies the live graph into the draft, later edits compose onto it. `workflows-get` shows the staged draft in `draft`; the live config stays in `actions`/`edges`. Metadata (name, description) applies live immediately.\n2. **Test the draft.** `workflows-test-run` with `use_draft=true` executes the staged draft instead of the live config. Re-test every path you changed.\n3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs`, a `confirm_token`, and an `impact` summary: per deleted step, about how many people are parked there and whether they move to a surviving step (`moves_to`) or exit; `empty_variables` that may render empty for people already past their new producer when they reach a reference (a structural warning — it can fire even when everyone in-flight is still upstream of the producer); `schedule_conflicts` where a schedule overrides a variable the draft removes. **Echo the impact to the user and get their go-ahead**, then call again with `confirm=true` and that `confirm_token`. A 409 means the draft changed since the preview and a 400 means the token expired (15 minutes) — preview again and re-confirm either way. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.\n4. **Or bail.** `workflows-discard-draft` throws the staged draft away.\n\nIn-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don\'t re-run; people parked on a step the publish deletes skip forward to its next surviving step (or exit at a dead end), exactly as the impact preview reported.\n\nTiming edits apply to parked runs gradually, not instantly. Publishing a shortened delay (or a moved wait window) reschedules the runs parked on it via a rate-limited sweep. Runs already due to wake soon keep their original earlier wake untouched; only wakes that the sweep moves earlier are affected, and those land spread out, no sooner than a few minutes after publish (and never later than their original wake). Runs still parked shortly after publishing are expected - tell the user this rather than re-publishing or treating it as a failure.\n\n### Rolling back\n\nEvery live-content change appends a snapshot to the workflow\'s revision history. `workflows-list-revisions` lists versions (newest first); `workflows-get-revision` returns one version\'s full content. To roll back (or forward), `workflows-restore-revision` copies that version\'s content into the draft — it never touches the live config — then the normal publish cycle applies: test with `use_draft=true`, preview, confirm. The preview shows exactly what the rollback does to people in-flight, same as any publish.\n\nA restore returns 409 when a draft is already open; publish or discard it, or pass `overwrite=true` to replace it. Two things a rollback cannot undo: runs that already moved or exited while the newer version was live keep their positions (their side effects happened), and a publish that shortened a delay may have pulled parked wake times earlier — rolling back doesn\'t push them later again.\n\n## What the server owns, never send it\n\nThe server compiles and manages these. Authoring them by hand is the fastest way to a broken workflow:\n\n- **`bytecode`** on any filter, trigger, condition, conversion, or masking. Compiled server-side from the human-readable `properties`/`hash`. Omit it; send `filters: {...}`, not bytecode.\n- **`trigger`** (top-level). _Derived_ from the `trigger` action in `actions`. Read-only. Set the trigger by adding the trigger node, not by setting this field.\n- **`billable_action_types`**, `version`, `id`, `created_*`. Computed/managed.\n\n## Minimal worked example\n\nEvent trigger, wait 1 day, send email, exit. Note: exactly one `trigger`, every non-exit node has an outgoing edge, ids are referenced consistently by `edges`, and no `bytecode` is sent.\n\n```json\n{\n "name": "Nudge after signup",\n "description": "One day after signup, send a reminder.",\n "exit_condition": "exit_only_at_end",\n "actions": [\n {\n "id": "trigger_node",\n "name": "Signed up",\n "type": "trigger",\n "config": {\n "type": "event",\n "filters": { "events": [{ "id": "user signed up", "name": "user signed up", "type": "events", "order": 0 }] }\n }\n },\n {\n "id": "delay_1",\n "name": "Wait 1 day",\n "type": "delay",\n "config": { "delay_duration": "1d" }\n },\n {\n "id": "email_1",\n "name": "Reminder email",\n "type": "function_email",\n "config": {\n "template_id": "template-email",\n "template_uuid": "<uuid returned by workflows-create-email-template>",\n "message_category_type": "marketing",\n "inputs": {\n "email": {\n "value": {\n "to": { "email": "{person.properties.email}", "name": "" },\n "from": { "email": "[email protected]", "name": "Example" }\n }\n }\n }\n }\n },\n {\n "id": "exit_node",\n "name": "Exit",\n "type": "exit",\n "config": { "reason": "Done" }\n }\n ],\n "edges": [\n { "from": "trigger_node", "to": "delay_1", "type": "continue" },\n { "from": "delay_1", "to": "email_1", "type": "continue" },\n { "from": "email_1", "to": "exit_node", "type": "continue" }\n ]\n}\n```\n\nEmail bodies come from the template library, not hand-written html:\n\n1. **Reuse first.** List the library with `workflows-list-email-templates` and pick a template that fits. A drip campaign typically references one base template (say, a branded announcement) from every email step.\n2. **Create only if nothing fits.** Author a new template design-first with the **`designing-email-templates`** skill: compose the `design`, omit `html` (the server renders html from the design).\n3. **Reference it** by putting the template\'s UUID in each step\'s `config.template_uuid`, as above. The save snapshots the template\'s subject, text, html, and design into the step.\n4. **Differentiate per step** with `workflows-patch-action-email` design operations - each step\'s snapshot is edited independently, so five steps from one base template can each carry their own content.\n\nThe snapshot is one-way: editing the library template later does not change steps that already referenced it, and patching a step never touches the library template. If a user expects a template edit to flow into their workflows, correct that - the steps keep their copies, and each one is updated with `workflows-patch-action-email`.\n\nAlways give templates a real plain-text `text` alongside the design: clients that block rich content show only `text`, so filler like "placeholder" reaches real inboxes.\n\n## Hard rules to surface to the user, not work around\n\n- **Behavioral targeting is unsupported.** "Did event X at least N times over the last M days" can\'t be expressed as a trigger or a batch/schedule audience. If asked, reject it and explain; don\'t approximate it with a broken filter. (The backend rejects behavioral cohorts in batch audiences outright.)\n- **Batch audiences target _who a person is_, not what they did.** Person properties and/or static/property-based cohorts only. Event/action filters in a batch audience are silently dropped, so they\'re rejected.\n- **Prefer re-evaluating audiences.** For batch, inline person-property conditions or a dynamic (filter-based) cohort re-evaluate as people qualify; a static cohort is a frozen list, use only for an explicit given set.\n\n# Workflow graph schema\n\nThe contract for `actions` and `edges`. The stored workflow is loose JSON, but **the visual editor validates every node against a strict schema keyed on `type`**. A node that saves successfully but doesn\'t match this contract will **break the editor view for the whole workflow** when someone opens it. Treat the shapes below as required, not advisory.\n\n## Contents\n\n- Node (action) shape\n- Action types and their `config`\n- Edges\n- `function*` inputs\n- Duration strings (`delay_duration`, `max_wait_duration`)\n- Conversion & exit condition\n- Pre-submit checklist\n\n## Node (action) shape\n\nEvery action object has these common fields plus a type-specific `config`:\n\n```json\n{\n "id": "unique_within_workflow",\n "name": "Human label",\n "description": "",\n "type": "<see action types>",\n "config": {},\n "on_error": "continue",\n "filters": null,\n "output_variable": null\n}\n```\n\n- `id` — unique within the workflow; edges reference it by `from`/`to`.\n- `on_error` — optional; **only `continue` or `abort`.** Omit to use the default.\n- `filters` — optional property filters gating the action: `{properties: [<cond>]}`. Send `properties`, not `bytecode`.\n- `output_variable` — optional; store a step result into a workflow variable. `{key, result_path?, spread?}`.\n\n## Action types and their `config`\n\nUse **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor\'s parse for the entire graph.\n\n| `type` | `config` |\n| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |\n| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |\n| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |\n| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |\n| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |\n| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |\n| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don\'t guess the id or its inputs — discover them live (see below). |\n| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template\'s body into `inputs.email.value` at save (a snapshot — later template edits don\'t propagate); you still supply `from` and `to`. Set `from` to `{integrationId: <sender id>}` for one sender. To rotate across up to 10 senders, also set `integrationIds: [<sender id>, ...]`; keep `integrationId` as the first sender for compatibility. Workflow runs using the same sender list resolve to the same sender, including across multiple email steps. If you author any body key inline, your body wins and `template_uuid` is provenance only. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |\n| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |\n| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email\'s — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project\'s push integration ids for `channels`. |\n| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |\n\n### Branch and wait condition filters (the `filters` wrapper is mandatory)\n\n`conditional_branch` and `wait_until_condition` gate on a **`filters` object**, the action-filter shape (`{properties?, events?, actions?, source?, filter_test_accounts?}`). The wrapper is not optional:\n\n- Write `{ "filters": { "properties": [<cond>] } }` on each condition, **never** `{ "properties": [<cond>] }` directly on the condition object. The bare form saves but the visual editor flags it and the branch compiles to a constant, so it never evaluates your condition.\n- `conditional_branch` conditions are **property-only** (person/group `<cond>`s). Event/action filters are rejected here ("Event filters are not allowed in conditionals").\n- `wait_until_condition` is event-aware: its `condition.filters` and each `events?[].filters` may also carry `events`/`actions`. An entry naming neither an event nor an action is dropped (it would match everything).\n- `source` is optional (defaults to `events`). Never send `bytecode`; the server compiles it from `properties`.\n\n### Trigger `config` (the `trigger` node)\n\nDiscriminated on `config.type`:\n\n- `event` — `{ "type": "event", "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events", "order": 0, "properties": [<cond>] }], "properties": [<cond>], "filter_test_accounts": false } }`. Fires on **every** matching occurrence. Throttle repeats with `trigger_masking` (dedup/sampling — not behavioral filtering).\n- `webhook` / `manual` / `tracking_pixel` — `{ "type": "webhook", "template_id": "<literal>", "inputs": { ... } }`. These use a **fixed built-in source template**, not one you look up: `template-source-webhook` for both `webhook` and `manual`, `template-source-webhook-pixel` for `tracking_pixel`. Omitting or guessing it fails the create with `Template not found` against the trigger node. They are `source_webhook` templates and are **not** in the destination catalog (`cdp-function-templates-list` is `type=destination`), so don\'t try to discover them there. Each needs `inputs.event` and `inputs.distinct_id` wrapped in `{value: ...}`, and the right values **differ per trigger type** because a different request reaches the template:\n - `webhook` — a POST whose body you control: `"inputs": { "event": { "value": "{request.body.event}" }, "distinct_id": { "value": "{request.body.distinct_id}" } }`.\n - `manual` — the "trigger manually" button POSTs `{user_id, $variables}`, so the body carries no `event`: use the fixed literal `"inputs": { "event": { "value": "$workflow_triggered" }, "distinct_id": { "value": "{request.body.user_id}" } }`. Pointing `event` at `{request.body.event}` here makes every manual run return 400 (the source template rejects an empty `event`) while the UI still shows a success toast, so the workflow silently never fires.\n - `tracking_pixel` — a bodyless `GET`, so read query params: `"inputs": { "event": { "value": "{request.query.ph_event}" }, "distinct_id": { "value": "{request.query.ph_distinct_id}" } }`. Body references resolve empty here and the pixel still returns its 200 GIF, so every hit is dropped with no error to retry on.\n- `batch` — `{ "type": "batch", "filters": { "properties": [<cond>] } }`. The audience: person-property conditions and/or cohort references. **No event/action filters** (silently dropped, so rejected). Does not fire on enable — dispatch a one-off broadcast with `workflows-run-batch`, or make it **recurring** with `workflows-schedule-create` (attaches an RRULE schedule; each firing re-broadcasts to this same `config.filters.properties` audience). A recurring workflow is a `batch` trigger plus a schedule — there is no separate "schedule" trigger type to author.\n\n### Trigger masking (throttling an event trigger)\n\n`trigger_masking` is a top-level workflow field (not an action) that throttles an already-matching `event` trigger — it dedups/samples firings, it does not decide who enters.\n\n```json\n"trigger_masking": { "hash": "{person.id}", "ttl": 3600, "threshold": null }\n```\n\n- `hash` — HogQL template defining the dedup key. `"{person.id}"` = once per person.\n- `ttl` — seconds to suppress repeats of the same hash (60–94608000).\n- `threshold?` — fire once per N matches of the same hash (a sampler: N=3 fires on the 1st, 4th, 7th…). Omit to fire once then suppress within `ttl`.\n- Don\'t send `bytecode` — compiled server-side from `hash`.\n\n### Condition shape (`<cond>`)\n\nProperty conditions used in trigger/action `filters`, branch conditions, and conversion:\n\n```json\n{ "key": "plan", "value": ["pro"], "operator": "exact", "type": "person" }\n```\n\n`type` is `event` | `person` | `group`. Never include `bytecode` — the server compiles it.\n\n## Edges\n\n```json\n{ "from": "source_id", "to": "target_id", "type": "continue", "index": 0 }\n```\n\n- `type: "continue"` — fall-through: the sequential next step, or the **no-match** path out of a `conditional_branch`. For a `wait_until_condition` it is the **`max_wait_duration` timeout** path.\n- `type: "branch"` — requires `index`, matching `config.conditions[index]` on a `conditional_branch`. A `wait_until_condition` **resolves** (its `condition` matches or an `events` entry fires) out the `branch` edge at **`index: 0`**.\n- **Every non-exit node needs a reachable next action** via an outgoing edge, or execution fails with "No next action found".\n- A `conditional_branch` with N conditions typically has N `branch` edges (`index: 0..N-1`) plus one `continue` edge for the no-match path.\n- A `wait_until_condition` needs a `branch` edge at `index: 0` (resolution) **and** a `continue` edge (timeout). Without the `index: 0` branch it only ever advances on timeout, never on the event/condition firing.\n\n## `function*` inputs\n\nInputs are keyed by the template\'s input schema, each wrapped in `{value: ...}`:\n\n```json\n"inputs": { "url": { "value": "https://example.com/hook" } }\n```\n\n- **Wrap values in `{value: ...}`.** A flat string won\'t enable templating.\n- Templating uses **single-curly** `{person.x}` / `{event.x}` inside the value string. Liquid-style `{{ ... }}` is rejected on hog-templated fields ("Placeholders are not allowed in this context") — the only fields that accept Liquid are ones whose input schema declares `templating: liquid` (the email input on `function_email` does; most others don\'t).\n- **Dictionary input values are template strings too** — write booleans/numbers as single-expression templates: `"{true}"`, `"{42}"`, which evaluate to the typed value.\n- Required inputs must be present, or create fails with "This field is required".\n\n### Discovering function templates (do this, don\'t guess)\n\nThe set of available `function` templates and their required inputs is **live data**, not something to hardcode — it changes as integrations are added. For a `function` node:\n\n1. `cdp-function-templates-list` (filter `type=destination`) to find the right template and its `id`.\n2. `cdp-function-templates-retrieve` with that id to read its **`inputs_schema`** — the exact keys, types, and which are required.\n3. Build `inputs` from that schema. A `template_id` not in the live list fails with "Template not found".\n\n`function_email`, `function_sms`, and `function_push` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` / `template-native-push`, so you don\'t look the `template_id` up, and you can omit it entirely: the server infers the literal from the step type. A saved email template\'s UUID goes in `template_uuid` alongside the literal, never in `template_id` (a UUID sent as `template_id` is moved into `template_uuid` automatically). For `function_email`, referencing a template means you only author `from`/`to`: the server materializes the template\'s body at save (see the action-types table). `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.\n\n### `function_push` worked example\n\nRetrieve `template-native-push` with `cdp-function-templates-retrieve` for the full `inputs_schema` (it has many optional Android/iOS keys), but the core shape is:\n\n```json\n{\n "id": "push_1",\n "name": "Re-engagement push",\n "type": "function_push",\n "config": {\n "template_id": "template-native-push",\n "inputs": {\n "distinctId": { "value": "{event.distinct_id}" },\n "channels": { "value": [6, 7] },\n "title": { "value": "Notification from {event.event}" },\n "body": { "value": "Hi {{ person.properties.first_name }}, come finish setting up.", "templating": "liquid" }\n }\n }\n}\n```\n\n- **`channels`** is an `integration_multi` input: its `value` is an array of **integration id numbers** (e.g. `[6, 7]`), not objects. Find the FCM/APNs integration ids with `integrations-list` (look for `kind` `firebase` / `apns`); at least one is required or the send throws "No push channel configured".\n- **Templating differs per input.** `body` is **liquid** — interpolate with `{{ person.x }}` / `{{ event.x }}` (double braces) and set `"templating": "liquid"`. `title` and the other string inputs are **hog** — use `{event.x}` / `{person.x}` (single braces). The wrong brace style leaves the expression as a literal.\n- Required: `distinctId`, `channels`, `title`. Optional: `body`, `image`, `data`, `ttlSeconds`, `android_*`, `ios_*` (retrieve the `inputs_schema` for the full set).\n- Never hand-author `bytecode` — the server compiles it from `value`. Omit `order` too: the editor lays fields out in the template\'s `inputs_schema` order (fixed and consistent), not by the `order` on your inputs, so leaving it off doesn\'t change the form. Push has no delivered/opened/clicked signal (FCM/APNs respond synchronously), so a successful send means "accepted for delivery", nothing more.\n\n## Duration strings (`delay_duration`, `max_wait_duration`)\n\nMust match `^\\d*\\.?\\d+[dhms]$` — a number plus unit `s` | `m` | `h` | `d`. Examples: `30s`, `30m`, `2h`, `1d`, `1.5d` (=36h).\n\n- **No ISO-8601.** Fractions are allowed in every unit.\n- Per-unit caps are **silently clamped**: `s`≤60, `m`≤60, `h`≤24, `d`≤30. Max total 30d. Use the larger unit (`90m` → use `1.5h`) to avoid surprise clamping.\n\n## Conversion & exit condition\n\n- `exit_condition`: `exit_only_at_end` (default), `exit_on_conversion`, `exit_on_trigger_not_matched`, `exit_on_trigger_not_matched_or_conversion`.\n- The `…conversion` variants require a `conversion` goal with two slots plus a window:\n - `filters` — **property conditions only**, an array `[{key, value, operator, type}, ...]` (empty array = any event in the window converts).\n - `events` — **event-based goals**, `[{ "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events" }] } }]`.\n - `window_minutes` — minutes after entry (`null` = no window).\n- **An event goal goes in `events`, never in `filters`.** An event object stuffed into `filters` is invisible to the conversion matcher and breaks the conversion picker. Without a goal the `…conversion` exit is a silent no-op. Server compiles the bytecode.\n\n## Pre-submit checklist\n\n- [ ] Exactly **one** `type: "trigger"` action; usually exactly one `exit`.\n- [ ] Every action `type` and `config` matches a row above (no types outside the supported set).\n- [ ] `on_error` is only `continue` or `abort`.\n- [ ] `function_email.template_id == "template-email"`, `function_sms.template_id == "template-twilio"`, `function_push.template_id == "template-native-push"`.\n- [ ] A `webhook` / `manual` trigger sets `template_id == "template-source-webhook"` (a `tracking_pixel` uses `"template-source-webhook-pixel"`) — these are built-in source templates, not catalog lookups.\n- [ ] That trigger\'s `inputs.event` / `inputs.distinct_id` match its own type: `{request.body.*}` for `webhook`, `$workflow_triggered` + `{request.body.user_id}` for `manual`, `{request.query.ph_*}` for `tracking_pixel`. The wrong pair saves fine and then fails at trigger time.\n- [ ] Every non-exit node has an outgoing edge; `branch` edges have an `index` matching a condition.\n- [ ] Every `conditional_branch` / `wait_until_condition` condition is wrapped: `{filters: {properties: [...]}}`, not `{properties: [...]}`.\n- [ ] All durations match `^\\d*\\.?\\d+[dhms]$` and dodge the silent per-unit clamp.\n- [ ] Function inputs are `{key: {value: ...}}`; no hand-written `bytecode` anywhere; no top-level `trigger` field set.',
+ '# Building workflows\n\nA PostHog **workflow** is a directed graph: a list of **action nodes** (`actions`) wired by **edges** (`edges`), with exactly one `trigger` node that starts every run. You author that graph as JSON and ship it over MCP. Always call it a "workflow" to the user. "Hog flow" is the internal code name (`HogFlow`), not a user-facing term.\n\nThe single biggest failure mode is **getting the graph JSON structurally wrong**. The backend stores `actions`/`config` as loose JSON, but the visual editor parses every node against a strict schema, so a malformed node saves but then **breaks the editor view** for the whole workflow. Before composing or editing any graph, read [references/graph-schema.md](references/graph-schema.md). It is the contract; do not improvise node shapes from these examples alone.\n\n## The lifecycle\n\nWork the workflow through these stages. Don\'t jump straight to enabling it.\n\n1. **Compose the graph.** Build `actions` + `edges` per [references/graph-schema.md](references/graph-schema.md). For any `function` node, don\'t guess the template: list the live catalog with `cdp-function-templates-list` and read its required inputs with `cdp-function-templates-retrieve`.\n2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.\n3. **Test-run it.** `workflows-test-run` runs **one step at a time**. Start at the first step (omit `current_action_id`, or point it at the trigger) with sample `globals` (`{event, person, groups}`); the result includes the next step\'s id (`nextActionId`). Feed that back as `current_action_id` and run again, walking step by step to the end. Skip `delay` nodes by jumping to the action after them (delays aren\'t simulated). Async side effects (HTTP/email/SMS/push) are mocked unless you set `mock_async_functions=false`. Read each step\'s trace to confirm the path taken.\n4. **Read logs while iterating.** `workflows-logs` shows the per-step execution trace (levels DEBUG to ERROR). This is how you see _why_ a step skipped, branched, or errored.\n5. **Edit, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. On a draft workflow, edits apply directly; on an active one they stage a draft (see [Changing a live workflow](#changing-a-live-workflow)).\n6. **Enable (needs the user\'s explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. From then on it runs on real people, and every change goes through the draft → test → publish cycle before taking effect — so finish testing, then get the user\'s explicit go before enabling. Don\'t enable on your own initiative.\n7. **Dispatch (batch/schedule only).** A `batch` workflow does **not** fire on enable alone. Send a one-off broadcast with `workflows-run-batch`, or attach a recurring schedule with `workflows-schedule-create`. Confirm with `workflows-get` that `status==\'active\'` _and_ its read-only `schedules` field has an active entry.\n8. **Monitor.** Drill down: `workflows-global-stats` (which workflows are failing) to `workflows-stats` (one workflow\'s trend) to `workflows-list-invocations` (who it failed for) to `workflows-get-invocation` (the triggering payload) to `workflows-logs` (the failing step).\n\nFull tool catalog, grouped by job: [references/lifecycle-and-debugging.md](references/lifecycle-and-debugging.md).\n\n## Editing a draft\n\n**Patch, don\'t replace.** Edit a draft with `workflows-patch-graph`: a small, ordered list of id-addressed operations (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`). `update_action` deep-merges its patch, so changing one email subject is a few lines, not the whole graph. The ops apply atomically server-side (read, apply in order, validate, save only if valid), and the response echoes the **full updated graph**, so you never re-fetch before the next edit. This keeps each round-trip tiny instead of re-transmitting every action and edge.\n\n`workflows-update` covers only what a graph patch can\'t express: top-level fields like name, description, exit_condition, conversion, trigger_masking, and variables. It rejects `actions`/`edges` outright - a partial list would silently drop every step it omits - so every graph change goes through `workflows-patch-graph`.\n\nAfter **any** patch, re-test the path you changed (step 3). A patch that validates structurally can still route the wrong way.\n\nEmail content follows the same rule.\nThe email inside a `function_email` step is edited with **`workflows-patch-action-email`**: the same id-addressed design ops as the template patch, plus an `email_patch` merge for subject/preheader/text/recipients, with the HTML re-rendered server-side so it always matches the design.\nPrefer it over `workflows-patch-graph` `update_action` for email content - an `update_action` that changes `design` leaves the stored `html` stale.\nLibrary templates are edited with **`workflows-patch-email-template`**, not `workflows-update-email-template` (which resends the entire design JSON).\nCompose and edit email designs with the **`designing-email-templates`** skill.\n\n## Changing a live workflow\n\nEditing an active workflow stages a **draft** instead of changing what\'s running: nothing reaches real people until you publish. Work the cycle:\n\n1. **Edit.** `workflows-patch-graph` (or `workflows-update` for content fields) on the active workflow writes to its draft — the first edit copies the live graph into the draft, later edits compose onto it. `workflows-get` shows the staged draft in `draft`; the live config stays in `actions`/`edges`. Metadata (name, description) applies live immediately.\n2. **Test the draft.** `workflows-test-run` with `use_draft=true` executes the staged draft instead of the live config. Re-test every path you changed.\n3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs`, a `confirm_token`, and an `impact` summary: per deleted step, about how many people are parked there and whether they move to a surviving step (`moves_to`) or exit; `empty_variables` that may render empty for people already past their new producer when they reach a reference (a structural warning — it can fire even when everyone in-flight is still upstream of the producer); `schedule_conflicts` where a schedule overrides a variable the draft removes. **Echo the impact to the user and get their go-ahead**, then call again with `confirm=true` and that `confirm_token`. A 409 means the draft changed since the preview and a 400 means the token expired (15 minutes) — preview again and re-confirm either way. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.\n4. **Or bail.** `workflows-discard-draft` throws the staged draft away.\n\nIn-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don\'t re-run; people parked on a step the publish deletes skip forward to its next surviving step (or exit at a dead end), exactly as the impact preview reported.\n\nTiming edits apply to parked runs gradually, not instantly. Publishing a shortened delay (or a moved wait window) reschedules the runs parked on it via a rate-limited sweep. Runs already due to wake soon keep their original earlier wake untouched; only wakes that the sweep moves earlier are affected, and those land spread out, no sooner than a few minutes after publish (and never later than their original wake). Runs still parked shortly after publishing are expected - tell the user this rather than re-publishing or treating it as a failure.\n\n### Rolling back\n\nEvery live-content change appends a snapshot to the workflow\'s revision history. `workflows-list-revisions` lists versions (newest first); `workflows-get-revision` returns one version\'s full content. To roll back (or forward), `workflows-restore-revision` copies that version\'s content into the draft — it never touches the live config — then the normal publish cycle applies: test with `use_draft=true`, preview, confirm. The preview shows exactly what the rollback does to people in-flight, same as any publish.\n\nA restore returns 409 when a draft is already open; publish or discard it, or pass `overwrite=true` to replace it. Two things a rollback cannot undo: runs that already moved or exited while the newer version was live keep their positions (their side effects happened), and a publish that shortened a delay may have pulled parked wake times earlier — rolling back doesn\'t push them later again.\n\n## What the server owns, never send it\n\nThe server compiles and manages these. Authoring them by hand is the fastest way to a broken workflow:\n\n- **`bytecode`** on any filter, trigger, condition, conversion, or masking. Compiled server-side from the human-readable `properties`/`hash`. Omit it; send `filters: {...}`, not bytecode.\n- **`trigger`** (top-level). _Derived_ from the `trigger` action in `actions`. Read-only. Set the trigger by adding the trigger node, not by setting this field.\n- **`billable_action_types`**, `version`, `id`, `created_*`. Computed/managed.\n\n## Minimal worked example\n\nEvent trigger, wait 1 day, send email, exit. Note: exactly one `trigger`, every non-exit node has an outgoing edge, ids are referenced consistently by `edges`, and no `bytecode` is sent.\n\n```json\n{\n "name": "Nudge after signup",\n "description": "One day after signup, send a reminder.",\n "exit_condition": "exit_only_at_end",\n "actions": [\n {\n "id": "trigger_node",\n "name": "Signed up",\n "type": "trigger",\n "config": {\n "type": "event",\n "filters": { "events": [{ "id": "user signed up", "name": "user signed up", "type": "events", "order": 0 }] }\n }\n },\n {\n "id": "delay_1",\n "name": "Wait 1 day",\n "type": "delay",\n "config": { "delay_duration": "1d" }\n },\n {\n "id": "email_1",\n "name": "Reminder email",\n "type": "function_email",\n "config": {\n "template_id": "template-email",\n "template_uuid": "<uuid returned by workflows-create-email-template>",\n "message_category_type": "marketing",\n "inputs": {\n "email": {\n "value": {\n "to": { "email": "{person.properties.email}", "name": "" },\n "from": { "email": "[email protected]", "name": "Example" }\n }\n }\n }\n }\n },\n {\n "id": "exit_node",\n "name": "Exit",\n "type": "exit",\n "config": { "reason": "Done" }\n }\n ],\n "edges": [\n { "from": "trigger_node", "to": "delay_1", "type": "continue" },\n { "from": "delay_1", "to": "email_1", "type": "continue" },\n { "from": "email_1", "to": "exit_node", "type": "continue" }\n ]\n}\n```\n\nEmail bodies come from the template library, not hand-written html:\n\n1. **Reuse first.** List the library with `workflows-list-email-templates` and pick a template that fits. A drip campaign typically references one base template (say, a branded announcement) from every email step.\n2. **Create only if nothing fits.** Author a new template design-first with the **`designing-email-templates`** skill: compose the `design`, omit `html` (the server renders html from the design).\n3. **Reference it** by putting the template\'s UUID in each step\'s `config.template_uuid`, as above. The save snapshots the template\'s subject, text, html, and design into the step.\n4. **Differentiate per step** with `workflows-patch-action-email` design operations - each step\'s snapshot is edited independently, so five steps from one base template can each carry their own content.\n\nThe snapshot is one-way: editing the library template later does not change steps that already referenced it, and patching a step never touches the library template. If a user expects a template edit to flow into their workflows, correct that - the steps keep their copies, and each one is updated with `workflows-patch-action-email`.\n\nAlways give templates a real plain-text `text` alongside the design: clients that block rich content show only `text`, so filler like "placeholder" reaches real inboxes.\n\n## Hard rules to surface to the user, not work around\n\n- **Behavioral targeting is unsupported.** "Did event X at least N times over the last M days" can\'t be expressed as a trigger or a batch/schedule audience. If asked, reject it and explain; don\'t approximate it with a broken filter. (The backend rejects behavioral cohorts in batch audiences outright.)\n- **Batch audiences target _who a person is_, not what they did.** Person properties and/or static/property-based cohorts only. Event/action filters in a batch audience are silently dropped, so they\'re rejected.\n- **Prefer re-evaluating audiences.** For batch, inline person-property conditions or a dynamic (filter-based) cohort re-evaluate as people qualify; a static cohort is a frozen list, use only for an explicit given set.\n\n# Workflow graph schema\n\nThe contract for `actions` and `edges`. The stored workflow is loose JSON, but **the visual editor validates every node against a strict schema keyed on `type`**. A node that saves successfully but doesn\'t match this contract will **break the editor view for the whole workflow** when someone opens it. Treat the shapes below as required, not advisory.\n\n## Contents\n\n- Node (action) shape\n- Action types and their `config`\n- Edges\n- `function*` inputs\n- Duration strings (`delay_duration`, `max_wait_duration`)\n- Waiting until a date (`delay_until`)\n- Conversion & exit condition\n- Pre-submit checklist\n\n## Node (action) shape\n\nEvery action object has these common fields plus a type-specific `config`:\n\n```json\n{\n "id": "unique_within_workflow",\n "name": "Human label",\n "description": "",\n "type": "<see action types>",\n "config": {},\n "on_error": "continue",\n "filters": null,\n "output_variable": null\n}\n```\n\n- `id` — unique within the workflow; edges reference it by `from`/`to`.\n- `on_error` — optional; **only `continue` or `abort`.** Omit to use the default.\n- `filters` — optional property filters gating the action: `{properties: [<cond>]}`. Send `properties`, not `bytecode`.\n- `output_variable` — optional; store a step result into a workflow variable. `{key, result_path?, spread?}`.\n\n## Action types and their `config`\n\nUse **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor\'s parse for the entire graph.\n\n| `type` | `config` |\n| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |\n| `delay` | `{ "delay_duration": "30m" }`, or `{ "delay_until": {"expression": "<HogQL date>", "offset?": "-1d"}, "max_delay_duration?": "30d" }` to wait for a per-person date. Exactly one of the two. See duration rules and `delay_until` below. |\n| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |\n| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |\n| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |\n| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |\n| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don\'t guess the id or its inputs — discover them live (see below). |\n| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template\'s body into `inputs.email.value` at save (a snapshot — later template edits don\'t propagate); you still supply `from` and `to`. Set `from` to `{integrationId: <sender id>}` for one sender. To rotate across up to 10 senders, also set `integrationIds: [<sender id>, ...]`; keep `integrationId` as the first sender for compatibility. Workflow runs using the same sender list resolve to the same sender, including across multiple email steps. If you author any body key inline, your body wins and `template_uuid` is provenance only. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |\n| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |\n| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email\'s — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project\'s push integration ids for `channels`. |\n| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |\n\n### Branch and wait condition filters (the `filters` wrapper is mandatory)\n\n`conditional_branch` and `wait_until_condition` gate on a **`filters` object**, the action-filter shape (`{properties?, events?, actions?, source?, filter_test_accounts?}`). The wrapper is not optional:\n\n- Write `{ "filters": { "properties": [<cond>] } }` on each condition, **never** `{ "properties": [<cond>] }` directly on the condition object. The bare form saves but the visual editor flags it and the branch compiles to a constant, so it never evaluates your condition.\n- `conditional_branch` conditions are **property-only** (person/group `<cond>`s). Event/action filters are rejected here ("Event filters are not allowed in conditionals").\n- `wait_until_condition` is event-aware: its `condition.filters` and each `events?[].filters` may also carry `events`/`actions`. An entry naming neither an event nor an action is dropped (it would match everything).\n- `source` is optional (defaults to `events`). Never send `bytecode`; the server compiles it from `properties`.\n\n### Trigger `config` (the `trigger` node)\n\nDiscriminated on `config.type`:\n\n- `event` — `{ "type": "event", "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events", "order": 0, "properties": [<cond>] }], "properties": [<cond>], "filter_test_accounts": false } }`. Fires on **every** matching occurrence. Throttle repeats with `trigger_masking` (dedup/sampling — not behavioral filtering).\n- `webhook` / `manual` / `tracking_pixel` — `{ "type": "webhook", "template_id": "<literal>", "inputs": { ... } }`. These use a **fixed built-in source template**, not one you look up: `template-source-webhook` for both `webhook` and `manual`, `template-source-webhook-pixel` for `tracking_pixel`. Omitting or guessing it fails the create with `Template not found` against the trigger node. They are `source_webhook` templates and are **not** in the destination catalog (`cdp-function-templates-list` is `type=destination`), so don\'t try to discover them there. Each needs `inputs.event` and `inputs.distinct_id` wrapped in `{value: ...}`, and the right values **differ per trigger type** because a different request reaches the template:\n - `webhook` — a POST whose body you control: `"inputs": { "event": { "value": "{request.body.event}" }, "distinct_id": { "value": "{request.body.distinct_id}" } }`.\n - `manual` — the "trigger manually" button POSTs `{user_id, $variables}`, so the body carries no `event`: use the fixed literal `"inputs": { "event": { "value": "$workflow_triggered" }, "distinct_id": { "value": "{request.body.user_id}" } }`. Pointing `event` at `{request.body.event}` here makes every manual run return 400 (the source template rejects an empty `event`) while the UI still shows a success toast, so the workflow silently never fires.\n - `tracking_pixel` — a bodyless `GET`, so read query params: `"inputs": { "event": { "value": "{request.query.ph_event}" }, "distinct_id": { "value": "{request.query.ph_distinct_id}" } }`. Body references resolve empty here and the pixel still returns its 200 GIF, so every hit is dropped with no error to retry on.\n- `batch` — `{ "type": "batch", "filters": { "properties": [<cond>] } }`. The audience: person-property conditions and/or cohort references. **No event/action filters** (silently dropped, so rejected). Does not fire on enable — dispatch a one-off broadcast with `workflows-run-batch`, or make it **recurring** with `workflows-schedule-create` (attaches an RRULE schedule; each firing re-broadcasts to this same `config.filters.properties` audience). A recurring workflow is a `batch` trigger plus a schedule — there is no separate "schedule" trigger type to author.\n\n### Trigger masking (throttling an event trigger)\n\n`trigger_masking` is a top-level workflow field (not an action) that throttles an already-matching `event` trigger — it dedups/samples firings, it does not decide who enters.\n\n```json\n"trigger_masking": { "hash": "{person.id}", "ttl": 3600, "threshold": null }\n```\n\n- `hash` — HogQL template defining the dedup key. `"{person.id}"` = once per person.\n- `ttl` — seconds to suppress repeats of the same hash (60–94608000).\n- `threshold?` — fire once per N matches of the same hash (a sampler: N=3 fires on the 1st, 4th, 7th…). Omit to fire once then suppress within `ttl`.\n- Don\'t send `bytecode` — compiled server-side from `hash`.\n\n### Condition shape (`<cond>`)\n\nProperty conditions used in trigger/action `filters`, branch conditions, and conversion:\n\n```json\n{ "key": "plan", "value": ["pro"], "operator": "exact", "type": "person" }\n```\n\n`type` is `event` | `person` | `group`. Never include `bytecode` — the server compiles it.\n\n## Edges\n\n```json\n{ "from": "source_id", "to": "target_id", "type": "continue", "index": 0 }\n```\n\n- `type: "continue"` — fall-through: the sequential next step, or the **no-match** path out of a `conditional_branch`. For a `wait_until_condition` it is the **`max_wait_duration` timeout** path.\n- `type: "branch"` — requires `index`, matching `config.conditions[index]` on a `conditional_branch`. A `wait_until_condition` **resolves** (its `condition` matches or an `events` entry fires) out the `branch` edge at **`index: 0`**.\n- **Every non-exit node needs a reachable next action** via an outgoing edge, or execution fails with "No next action found".\n- A `conditional_branch` with N conditions typically has N `branch` edges (`index: 0..N-1`) plus one `continue` edge for the no-match path.\n- A `wait_until_condition` needs a `branch` edge at `index: 0` (resolution) **and** a `continue` edge (timeout). Without the `index: 0` branch it only ever advances on timeout, never on the event/condition firing.\n\n## `function*` inputs\n\nInputs are keyed by the template\'s input schema, each wrapped in `{value: ...}`:\n\n```json\n"inputs": { "url": { "value": "https://example.com/hook" } }\n```\n\n- **Wrap values in `{value: ...}`.** A flat string won\'t enable templating.\n- Templating uses **single-curly** `{person.x}` / `{event.x}` inside the value string. Liquid-style `{{ ... }}` is rejected on hog-templated fields ("Placeholders are not allowed in this context") — the only fields that accept Liquid are ones whose input schema declares `templating: liquid` (the email input on `function_email` does; most others don\'t).\n- **Dictionary input values are template strings too** — write booleans/numbers as single-expression templates: `"{true}"`, `"{42}"`, which evaluate to the typed value.\n- Required inputs must be present, or create fails with "This field is required".\n\n### Discovering function templates (do this, don\'t guess)\n\nThe set of available `function` templates and their required inputs is **live data**, not something to hardcode — it changes as integrations are added. For a `function` node:\n\n1. `cdp-function-templates-list` (filter `type=destination`) to find the right template and its `id`.\n2. `cdp-function-templates-retrieve` with that id to read its **`inputs_schema`** — the exact keys, types, and which are required.\n3. Build `inputs` from that schema. A `template_id` not in the live list fails with "Template not found".\n\n`function_email`, `function_sms`, and `function_push` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` / `template-native-push`, so you don\'t look the `template_id` up, and you can omit it entirely: the server infers the literal from the step type. A saved email template\'s UUID goes in `template_uuid` alongside the literal, never in `template_id` (a UUID sent as `template_id` is moved into `template_uuid` automatically). For `function_email`, referencing a template means you only author `from`/`to`: the server materializes the template\'s body at save (see the action-types table). `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.\n\n### `function_push` worked example\n\nRetrieve `template-native-push` with `cdp-function-templates-retrieve` for the full `inputs_schema` (it has many optional Android/iOS keys), but the core shape is:\n\n```json\n{\n "id": "push_1",\n "name": "Re-engagement push",\n "type": "function_push",\n "config": {\n "template_id": "template-native-push",\n "inputs": {\n "distinctId": { "value": "{event.distinct_id}" },\n "channels": { "value": [6, 7] },\n "title": { "value": "Notification from {event.event}" },\n "body": { "value": "Hi {{ person.properties.first_name }}, come finish setting up.", "templating": "liquid" }\n }\n }\n}\n```\n\n- **`channels`** is an `integration_multi` input: its `value` is an array of **integration id numbers** (e.g. `[6, 7]`), not objects. Find the FCM/APNs integration ids with `integrations-list` (look for `kind` `firebase` / `apns`); at least one is required or the send throws "No push channel configured".\n- **Templating differs per input.** `body` is **liquid** — interpolate with `{{ person.x }}` / `{{ event.x }}` (double braces) and set `"templating": "liquid"`. `title` and the other string inputs are **hog** — use `{event.x}` / `{person.x}` (single braces). The wrong brace style leaves the expression as a literal.\n- Required: `distinctId`, `channels`, `title`. Optional: `body`, `image`, `data`, `ttlSeconds`, `android_*`, `ios_*` (retrieve the `inputs_schema` for the full set).\n- Never hand-author `bytecode` — the server compiles it from `value`. Omit `order` too: the editor lays fields out in the template\'s `inputs_schema` order (fixed and consistent), not by the `order` on your inputs, so leaving it off doesn\'t change the form. Push has no delivered/opened/clicked signal (FCM/APNs respond synchronously), so a successful send means "accepted for delivery", nothing more.\n\n## Duration strings (`delay_duration`, `max_wait_duration`)\n\nMust match `^\\d*\\.?\\d+[dhms]$` — a number plus unit `s` | `m` | `h` | `d`. Examples: `30s`, `30m`, `2h`, `1d`, `1.5d` (=36h).\n\n- **No ISO-8601.** Fractions are allowed in every unit.\n- Per-unit caps are **silently clamped**: `s`≤60, `m`≤60, `h`≤24, `d`≤30. Max total 30d. Use the larger unit (`90m` → use `1.5h`) to avoid surprise clamping.\n\n## Waiting until a date (`delay_until`)\n\nA `delay` waits either a fixed span or until a date carried by the person or the event. Use `delay_until` when the date differs per person, which a duration cannot express (a trial expiry, a renewal date, a booked appointment).\n\n```json\n{\n "id": "delay_1",\n "type": "delay",\n "config": {\n "delay_until": { "expression": "person.properties.trial_expiration_at", "offset": "-1d" },\n "max_delay_duration": "30d"\n }\n}\n```\n\n- **Exactly one of `delay_duration` and `delay_until`.** Both together are rejected; so is neither.\n- `expression` is HogQL resolving to a datetime. An ISO string, a `HogDateTime`, and unix seconds all resolve to the same instant, so a stored date works whichever shape the customer set it in. A bare number is read as **seconds**: a millisecond timestamp (what `Date.now()` and most SDKs produce) is rejected rather than read as a date tens of thousands of years out. Divide it by 1000 in the expression, or store the date as an ISO string.\n- `offset` shifts that instant and is **signed**: `^-?\\d*\\.?\\d+[dhms]$`. `-1d` is a day before the date, `2h` is two hours after. Omit it to wait for the date itself. Keep the arithmetic here rather than in the expression, so the builder can still read the step back as a property plus an offset.\n- Unlike `delay_duration`, an offset is **not** clamped per unit: `-45d` means 45 days, not 30. `max_delay_duration` bounds the wait instead.\n- `timezone`, `use_person_timezone` and `fallback_timezone` work as they do on `wait_until_time_window`, and decide which zone a date **with no offset of its own** is read in (a bare `2026-03-01`, or `2026-03-01T09:00:00`). A date that states an offset, a `HogDateTime`, and unix seconds are absolute and ignore them. Default `UTC`, so a date-only value means midnight UTC unless you set a zone.\n- `max_delay_duration` caps how far past the step\'s start the wait may run (default `30d`, same duration rules as above). It exists so a far-future date cannot park a run indefinitely.\n- **Never send `bytecode`.** The server compiles the expression at save time and discards anything the client sent. A broken expression fails the save with the parse error.\n- The expression is re-read on **every wake**, not only on entry, and the only wake a parked delay schedules is the instant it computed. So a date that **moves further out** is honored: the run wakes at the old instant and parks again to the new one. A date that **moves closer** is not: nothing wakes the run early, so it waits for the original instant and then continues at once, later than the new date asked for.\n- A date that cannot be resolved aborts the run whatever `on_error` says, because a wait that cannot work out when to act has nothing safe to fall through to.\n- A person property is `person.properties.<key>`; an **event property is `properties.<key>`, with no `event.` prefix**. The expression runs against the same globals as a filter, where `event` is the event\'s name, so `event.properties.<key>` resolves to nothing and aborts the run.\n- The builder writes those two shapes (bracketed when the key is not a bare identifier). Any other expression saves fine but shows in the editor as a read-only custom expression instead of a property pick.\n\n## Conversion & exit condition\n\n- `exit_condition`: `exit_only_at_end` (default), `exit_on_conversion`, `exit_on_trigger_not_matched`, `exit_on_trigger_not_matched_or_conversion`.\n- The `…conversion` variants require a `conversion` goal with two slots plus a window:\n - `filters` — **property conditions only**, an array `[{key, value, operator, type}, ...]` (empty array = any event in the window converts).\n - `events` — **event-based goals**, `[{ "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events" }] } }]`.\n - `window_minutes` — minutes after entry (`null` = no window).\n- **An event goal goes in `events`, never in `filters`.** An event object stuffed into `filters` is invisible to the conversion matcher and breaks the conversion picker. Without a goal the `…conversion` exit is a silent no-op. Server compiles the bytecode.\n\n## Pre-submit checklist\n\n- [ ] Exactly **one** `type: "trigger"` action; usually exactly one `exit`.\n- [ ] Every action `type` and `config` matches a row above (no types outside the supported set).\n- [ ] `on_error` is only `continue` or `abort`.\n- [ ] `function_email.template_id == "template-email"`, `function_sms.template_id == "template-twilio"`, `function_push.template_id == "template-native-push"`.\n- [ ] A `webhook` / `manual` trigger sets `template_id == "template-source-webhook"` (a `tracking_pixel` uses `"template-source-webhook-pixel"`) — these are built-in source templates, not catalog lookups.\n- [ ] That trigger\'s `inputs.event` / `inputs.distinct_id` match its own type: `{request.body.*}` for `webhook`, `$workflow_triggered` + `{request.body.user_id}` for `manual`, `{request.query.ph_*}` for `tracking_pixel`. The wrong pair saves fine and then fails at trigger time.\n- [ ] Every non-exit node has an outgoing edge; `branch` edges have an `index` matching a condition.\n- [ ] Every `conditional_branch` / `wait_until_condition` condition is wrapped: `{filters: {properties: [...]}}`, not `{properties: [...]}`.\n- [ ] All durations match `^\\d*\\.?\\d+[dhms]$` and dodge the silent per-unit clamp.\n- [ ] Every `delay` sets exactly one of `delay_duration` and `delay_until`, and no `delay_until` carries hand-written `bytecode`.\n- [ ] Function inputs are `{key: {value: ...}}`; no hand-written `bytecode` anywhere; no top-level `trigger` field set.',
}
export const DESIGNING_EMAIL_TEMPLATES_SKILL: EmbeddedSkill = {
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 255cf9a89547..742250f2052a 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -417,7 +417,7 @@ export const HogFlowActionTypeEnumApi = {
} as const
/**
- * 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}.
+ * 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: waits a fixed span or until a per-person/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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 }
@@ -478,7 +478,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|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}. */
+ /** 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: waits a fixed span or until a per-person/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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?: unknown
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 183ca3e18568..4dfc6fa17d3b 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -720,7 +720,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod
),
])
.describe(
- "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}."
+ "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: waits a fixed span or until a per-person\/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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()
@@ -1075,7 +1075,7 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zod
),
])
.describe(
- "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}."
+ "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: waits a fixed span or until a per-person\/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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()
@@ -1435,7 +1435,7 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod
),
])
.describe(
- "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}."
+ "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: waits a fixed span or until a per-person\/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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()
@@ -2051,7 +2051,7 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
),
])
.describe(
- "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}."
+ "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: waits a fixed span or until a per-person\/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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()
@@ -2678,7 +2678,7 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod
),
])
.describe(
- "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}."
+ "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: waits a fixed span or until a per-person\/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.md
index 5eac11b701b2..e252af99b0ff 100644
--- a/products/workflows/skills/building-workflows/references/graph-schema.md
+++ b/products/workflows/skills/building-workflows/references/graph-schema.md
@@ -9,6 +9,7 @@ The contract for `actions` and `edges`. The stored workflow is loose JSON, but *
- Edges
- `function*` inputs
- Duration strings (`delay_duration`, `max_wait_duration`)
+- Waiting until a date (`delay_until`)
- Conversion & exit condition
- Pre-submit checklist
@@ -41,7 +42,7 @@ Use **only** these `type` values — they are the complete supported set. An unk
| `type` | `config` |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |
-| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |
+| `delay` | `{ "delay_duration": "30m" }`, or `{ "delay_until": {"expression": "<HogQL date>", "offset?": "-1d"}, "max_delay_duration?": "30d" }` to wait for a per-person date. Exactly one of the two. See duration rules and `delay_until` below. |
| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |
| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |
| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |
@@ -163,6 +164,33 @@ Must match `^\d*\.?\d+[dhms]$` — a number plus unit `s` | `m` | `h` | `d`. Exa
- **No ISO-8601.** Fractions are allowed in every unit.
- Per-unit caps are **silently clamped**: `s`≤60, `m`≤60, `h`≤24, `d`≤30. Max total 30d. Use the larger unit (`90m` → use `1.5h`) to avoid surprise clamping.
+## Waiting until a date (`delay_until`)
+
+A `delay` waits either a fixed span or until a date carried by the person or the event. Use `delay_until` when the date differs per person, which a duration cannot express (a trial expiry, a renewal date, a booked appointment).
+
+```json
+{
+ "id": "delay_1",
+ "type": "delay",
+ "config": {
+ "delay_until": { "expression": "person.properties.trial_expiration_at", "offset": "-1d" },
+ "max_delay_duration": "30d"
+ }
+}
+```
+
+- **Exactly one of `delay_duration` and `delay_until`.** Both together are rejected; so is neither.
+- `expression` is HogQL resolving to a datetime. An ISO string, a `HogDateTime`, and unix seconds all resolve to the same instant, so a stored date works whichever shape the customer set it in. A bare number is read as **seconds**: a millisecond timestamp (what `Date.now()` and most SDKs produce) is rejected rather than read as a date tens of thousands of years out. Divide it by 1000 in the expression, or store the date as an ISO string.
+- `offset` shifts that instant and is **signed**: `^-?\d*\.?\d+[dhms]$`. `-1d` is a day before the date, `2h` is two hours after. Omit it to wait for the date itself. Keep the arithmetic here rather than in the expression, so the builder can still read the step back as a property plus an offset.
+- Unlike `delay_duration`, an offset is **not** clamped per unit: `-45d` means 45 days, not 30. `max_delay_duration` bounds the wait instead.
+- `timezone`, `use_person_timezone` and `fallback_timezone` work as they do on `wait_until_time_window`, and decide which zone a date **with no offset of its own** is read in (a bare `2026-03-01`, or `2026-03-01T09:00:00`). A date that states an offset, a `HogDateTime`, and unix seconds are absolute and ignore them. Default `UTC`, so a date-only value means midnight UTC unless you set a zone.
+- `max_delay_duration` caps how far past the step's start the wait may run (default `30d`, same duration rules as above). It exists so a far-future date cannot park a run indefinitely.
+- **Never send `bytecode`.** The server compiles the expression at save time and discards anything the client sent. A broken expression fails the save with the parse error.
+- The expression is re-read on **every wake**, not only on entry, and the only wake a parked delay schedules is the instant it computed. So a date that **moves further out** is honored: the run wakes at the old instant and parks again to the new one. A date that **moves closer** is not: nothing wakes the run early, so it waits for the original instant and then continues at once, later than the new date asked for.
+- A date that cannot be resolved aborts the run whatever `on_error` says, because a wait that cannot work out when to act has nothing safe to fall through to.
+- A person property is `person.properties.<key>`; an **event property is `properties.<key>`, with no `event.` prefix**. The expression runs against the same globals as a filter, where `event` is the event's name, so `event.properties.<key>` resolves to nothing and aborts the run.
+- The builder writes those two shapes (bracketed when the key is not a bare identifier). Any other expression saves fine but shows in the editor as a read-only custom expression instead of a property pick.
+
## Conversion & exit condition
- `exit_condition`: `exit_only_at_end` (default), `exit_on_conversion`, `exit_on_trigger_not_matched`, `exit_on_trigger_not_matched_or_conversion`.
@@ -183,4 +211,5 @@ Must match `^\d*\.?\d+[dhms]$` — a number plus unit `s` | `m` | `h` | `d`. Exa
- [ ] Every non-exit node has an outgoing edge; `branch` edges have an `index` matching a condition.
- [ ] Every `conditional_branch` / `wait_until_condition` condition is wrapped: `{filters: {properties: [...]}}`, not `{properties: [...]}`.
- [ ] All durations match `^\d*\.?\d+[dhms]$` and dodge the silent per-unit clamp.
+- [ ] Every `delay` sets exactly one of `delay_duration` and `delay_until`, and no `delay_until` carries hand-written `bytecode`.
- [ ] Function inputs are `{key: {value: ...}}`; no hand-written `bytecode` anywhere; no top-level `trigger` field set.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d25df98d40ed..f94950d2b54e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40365,7 +40365,7 @@ export namespace Schemas {
} as const;
/**
- * 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}.
+ * 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: waits a fixed span or until a per-person/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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. */
@@ -40424,7 +40424,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|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}. */
+ /** 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: waits a fixed span or until a per-person/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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.ts
index 3d087c3e213e..0e08ab659fa1 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -371,7 +371,7 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod
),
])
.describe(
- "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}."
+ "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: waits a fixed span or until a per-person\/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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.json
index 4589ae606bea..bc1f11bfc5f0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json
@@ -195,7 +195,7 @@
"type": "object"
}
],
- "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}."
+ "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: waits a fixed span or until a per-person/-event date — set EXACTLY ONE of delay_duration or delay_until. {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. delay_until: {expression: '<SQL>', offset?: '<±number><unit>'} waits until the date expression evaluates to (an ISO string, unix seconds, or a date value all resolve to the same instant); offset is a signed duration shifting it ('-1d' a day before, '2h' two hours after). expression is compiled server-side, so any bytecode sent with it is discarded. A person property is person.properties.<key>; an event property is properties.<key>, as the 'event.' prefix resolves to nothing and aborts the run. Optional timezone (IANA name), use_person_timezone (read $geoip_time_zone) and fallback_timezone decide which zone a date with no offset of its own is read in; a date that states an offset, and unix seconds, ignore them. Default UTC. Optional sibling max_delay_duration (default 30d, same '<number><unit>' format) caps how far past the step's start the wait may run. 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.",