:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): keep delay unit and cleared value in duration step (#69036)
Sachin Ranchod5fa3a68dbd6d
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.test.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.test.tsxnew file mode 100644index 000000000000..a09515b4139c--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.test.tsx@@ -0,0 +1,52 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { HogFlowDuration } from './HogFlowDuration'++describe('HogFlowDuration', () => {+ afterEach(cleanup)++ it('keeps the unit and does not fall back to a default when the number is cleared', () => {+ const onChange = jest.fn()+ render(<HogFlowDuration value="3d" onChange={onChange} />)++ const input = screen.getByRole('spinbutton')+ fireEvent.change(input, { target: { value: '' } })++ // Clearing must preserve the unit (days) and must not reset the number to a default like "10m"+ expect(onChange).toHaveBeenCalledWith('d')+ })++ it('renders an empty field instead of a default number when the value has no number', () => {+ render(<HogFlowDuration value="d" onChange={jest.fn()} />)+ expect(screen.getByRole('spinbutton')).toHaveValue(null)+ })++ it('floors a stored decimal value on display so old data upgrades to a whole number', () => {+ render(<HogFlowDuration value="1.5d" onChange={jest.fn()} />)+ expect(screen.getByRole('spinbutton')).toHaveValue(1)+ })++ it('floors a fractional value emitted by the input to a whole number', () => {+ const onChange = jest.fn()+ render(<HogFlowDuration value="3d" onChange={onChange} />)++ const input = screen.getByRole('spinbutton')+ fireEvent.change(input, { target: { value: '2.7' } })++ expect(onChange).toHaveBeenCalledWith('2d')+ })++ it('clears the field immediately on change even before the parent commits the new value', () => {+ render(<HogFlowDuration value="2h" onChange={jest.fn()} />)++ const input = screen.getByRole('spinbutton')+ expect(input).toHaveValue(2)+ fireEvent.change(input, { target: { value: '' } })++ // The parent commits config through an async listener, so value is still "2h" here. The field must+ // read empty rather than snapping back to 2 (the swallowed-keystroke regression).+ expect(input).toHaveValue(null)+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsxindex 79d099bdf095..b2bd1f6c6e03 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowDuration.tsx@@ -1,6 +1,12 @@+import { useEffect, useState } from 'react'+import { LemonInput, LemonSelect } from '@posthog/lemon-ui'-const DURATION_REGEX = /^(\d*\.?\d+)([dhm])$/+// Allow an empty numeric part so a cleared input keeps its unit instead of resetting to a default.+// Also tolerate a decimal in stored values (older workflows) so we can floor it on display rather than lose the unit.+const DURATION_REGEX = /^(\d*\.?\d*)([dhm])$/++const MIN_VALUE_FOR_DURATION_UNIT = 1const MAX_VALUE_FOR_DURATION_UNIT: Record<string, number> = {d: 30,@@ -8,6 +14,9 @@ const MAX_VALUE_FOR_DURATION_UNIT: Record<string, number> = {m: 60,}+// Type=number lets browsers accept ".", ",", "e", "+", "-" — none of which are valid for a whole-number duration+const BLOCKED_NUMBER_INPUT_KEYS = new Set(['.', ',', 'e', 'E', '+', '-'])+export function HogFlowDuration({value,onChange,@@ -15,22 +24,45 @@ export function HogFlowDuration({value: stringonChange: (value: string) => void}): JSX.Element {- const parts = value.match(DURATION_REGEX) ?? ['', '10', 'm']- const [, numberValueString, unit] = parts+ const parts = value.match(DURATION_REGEX)+ const numberValueString = parts?.[1] ?? ''+ const unit = parts?.[2] ?? 'm'++ // Keep undefined (empty field) distinct from a real number so clearing doesn't snap back to a default.+ // Floor any decimal so a stored value like "1.5d" shows as "1d" and gets rewritten to a whole number on next save.+ const numberValue = numberValueString === '' ? undefined : Math.floor(parseFloat(numberValueString))- const numberValue = parseFloat(numberValueString)+ // The parent commits config through an async kea listener, so binding the field straight to the derived+ // value re-applies the previous digit for one render and swallows a keystroke on clear. Mirror it locally+ // so the user's edit shows immediately; reconcile only when the derived value changes externally (unit+ // clamp, switching nodes). NaN (not undefined) keeps LemonInput controlled when empty.+ const [displayNumber, setDisplayNumber] = useState(numberValue)+ useEffect(() => {+ setDisplayNumber(numberValue)+ }, [numberValue])++ const clamp = (n: number): number =>+ Math.min(Math.max(MIN_VALUE_FOR_DURATION_UNIT, Math.floor(n)), MAX_VALUE_FOR_DURATION_UNIT[unit])return (<div className="flex gap-2"><LemonInputtype="number"- value={numberValue}- min={0}+ value={displayNumber ?? NaN}+ min={MIN_VALUE_FOR_DURATION_UNIT}max={MAX_VALUE_FOR_DURATION_UNIT[unit]}- onChange={(v) => onChange(`${v}${unit}`)}- onBlur={() =>- onChange(`${Math.min(Math.max(0, numberValue), MAX_VALUE_FOR_DURATION_UNIT[unit])}${unit}`)- }+ step={1}+ onKeyDown={(e) => {+ if (BLOCKED_NUMBER_INPUT_KEYS.has(e.key)) {+ e.preventDefault()+ }+ }}+ onChange={(v) => {+ const next = v == null || !Number.isFinite(v) ? undefined : Math.floor(v)+ setDisplayNumber(next)+ onChange(next === undefined ? `${unit}` : `${next}${unit}`)+ }}+ onBlur={() => displayNumber !== undefined && onChange(`${clamp(displayNumber)}${unit}`)}/><LemonSelect@@ -40,7 +72,11 @@ export function HogFlowDuration({{ label: 'Day(s)', value: 'd' },]}value={unit}- onChange={(v) => onChange(`${Math.min(numberValue, MAX_VALUE_FOR_DURATION_UNIT[v])}${v}`)}+ onChange={(v) =>+ onChange(+ `${displayNumber === undefined ? '' : Math.min(displayNumber, MAX_VALUE_FOR_DURATION_UNIT[v])}${v}`+ )+ }/></div>)diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/StepSchemaErrors.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/StepSchemaErrors.tsxindex 775d51ff59c2..347c6928a14d 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/StepSchemaErrors.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/StepSchemaErrors.tsx@@ -15,7 +15,7 @@ export function StepSchemaErrors(): JSX.Element | null {}return (- <div className="flex flex-col gap-1">+ <div className="flex flex-col gap-1 mb-2">{validationResult.schema.issues.map(({ path, message }) => (<LemonBanner type="error" key={path.join('.')}>{path.join('.')}: {message}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.tsindex ec3d33d0b7cd..167f534f0914 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts@@ -3,14 +3,18 @@ import { actions, connect, kea, key, listeners, path, props } from 'kea'import { WorkflowLogicProps, workflowLogic } from '../../workflowLogic'import type { stepDelayLogicType } from './stepDelayLogicType'-const DURATION_REGEX = /^(\d*\.?\d+)([dhm])$/+const DURATION_REGEX = /^(\d*\.?\d*)([dhm])$/const AUTO_DESCRIPTION_REGEX = /^Wait for \d*\.?\d+ (minute|hour|day)s?\.$/const LEGACY_DEFAULT_DESCRIPTION = 'Wait for a specified duration.'export function getDelayDescription(duration: string): string {- const parts = duration.match(DURATION_REGEX) ?? ['', '10', 'm']- const [, numberValueString, unit] = parts- const number = parseFloat(numberValueString)+ 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+ }const unitLabel = unit === 'm' ? 'minute' : unit === 'h' ? 'hour' : 'day'const durationText = `${number} ${unitLabel}${number !== 1 ? 's' : ''}`return `Wait for ${durationText}.`diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.test.tsindex 95105a1cee37..2977c532ff98 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.test.ts@@ -41,4 +41,79 @@ describe('HogFlowActionSchema', () => {const result = HogFlowActionSchema.safeParse(action)expect(result.success).toBe(true)})++ // A cleared HogFlowDuration input emits just the unit (e.g. "d") and clobbering that with a+ // permissive schema lets users activate a wait step with no real timeout, so the workflow could+ // wait indefinitely. These cases lock in that only real durations pass.+ const delayAction = (delay_duration: string): Record<string, unknown> => ({+ id: 'delay_node',+ name: 'Delay',+ type: 'delay',+ description: '',+ config: { delay_duration },+ })++ const waitAction = (max_wait_duration: string): Record<string, unknown> => ({+ id: 'wait_node',+ name: 'Wait',+ type: 'wait_until_condition',+ description: '',+ config: { condition: { filters: {} }, max_wait_duration },+ })++ it.each([+ ['3d', true],+ ['10m', true],+ ['1m', true],+ ['1h', true],+ ['d', false],+ ['h', false],+ ['m', false],+ ['', false],+ ['NaNd', false],+ ['3', false],+ ['0m', false],+ ['0d', false],+ ['1.5h', false],+ ['0.5h', false],+ ['.5d', false],+ ['0.1m', false],+ ])('delay_duration %p → valid=%p', (duration, valid) => {+ expect(HogFlowActionSchema.safeParse(delayAction(duration)).success).toBe(valid)+ })++ it.each([+ ['5m', true],+ ['2h', true],+ ['1d', true],+ ['d', false],+ ['h', false],+ ['m', false],+ ['', false],+ ['NaNd', false],+ ['0m', false],+ ['0d', false],+ ['1.5h', false],+ ['0.5h', false],+ ])('max_wait_duration %p → valid=%p', (duration, valid) => {+ expect(HogFlowActionSchema.safeParse(waitAction(duration)).success).toBe(valid)+ })++ // The message the user sees depends on which rule failed, and the order matters: an empty field must+ // read "Please enter a duration", not the technical format/min messages. delay_duration and+ // max_wait_duration share DURATION_STRING, so testing one covers both.+ it.each([+ ['', 'Please enter a duration'],+ ['m', 'Please enter a duration'],+ ['3', 'Duration must be a whole number followed by d, h, or m'],+ ['1.5h', 'Duration must be a whole number followed by d, h, or m'],+ ['0m', 'Duration must be at least 1'],+ ])('delay_duration %p → message %p', (duration, message) => {+ const result = HogFlowActionSchema.safeParse(delayAction(duration))+ expect(result.success).toBe(false)+ if (!result.success) {+ const issue = result.error.issues.find((i) => i.path.at(-1) === 'delay_duration')+ expect(issue?.message).toBe(message)+ }+ })})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.tsindex 96735c5d77a9..b5fd25895801 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts@@ -19,6 +19,20 @@ const ActionFiltersSchema = z.object({actions: z.array(z.any()).optional(),})+const DURATION_STRING = z.string().superRefine((v, ctx) => {+ if (!/\d/.test(v)) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Please enter a duration' })+ return+ }+ if (!/^\d+[dhm]$/.test(v)) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duration must be a whole number followed by d, h, or m' })+ return+ }+ if (parseInt(v, 10) < 1) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Duration must be at least 1' })+ }+})+const _commonActionFields = {id: z.string(),name: z.string(),@@ -200,7 +214,7 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [..._commonActionFields,type: z.literal('delay'),config: z.object({- delay_duration: z.string().min(2),+ delay_duration: DURATION_STRING,}),}),z.object({@@ -219,7 +233,7 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [})).optional(),- max_wait_duration: z.string(),+ max_wait_duration: DURATION_STRING,}),}),