: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): stop the email step from flagging errors on open (#79574)
posthog[bot]3f743b7a167e
diff --git a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsxindex 797d3bb1df98..de793378095a 100644--- a/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx+++ b/frontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx@@ -42,6 +42,7 @@ import { capitalizeFirstLetter } from 'lib/utils/strings'import { CyclotronJobInputSchemaType, CyclotronJobInputType, CyclotronJobInvocationGlobalsWithInputs } from '~/types'import { EmailTemplater } from '../../../scenes/hog-functions/email-templater/EmailTemplater'+import { EmailFieldErrors } from '../../../scenes/hog-functions/email-templater/types'import { CUSTOM_INPUT_RENDERERS } from './customInputRenderers'import { cyclotronJobInputLogic, formatJsonValue } from './cyclotronJobInputLogic'import { CyclotronJobTemplateSuggestionsButton } from './CyclotronJobTemplateSuggestions'@@ -114,6 +115,9 @@ export type CyclotronJobInputsProps = {configuration: CyclotronJobInputConfigurationerrors?: Record<string, string>warnings?: Record<string, string>+ // Per-field messages for an email input, rendered next to its sender/recipient/subject/body+ // fields. Only the email input type reads this; other input types ignore it.+ emailFieldErrors?: EmailFieldErrorsparentConfiguration?: CyclotronJobInputConfigurationonInputSchemaChange?: (schema: CyclotronJobInputSchemaType[]) => voidshowSource: boolean@@ -127,6 +131,7 @@ export function CyclotronJobInputs({onInputChange,errors,warnings,+ emailFieldErrors,showSource,sampleGlobalsWithInputs,}: CyclotronJobInputsProps): JSX.Element | null {@@ -166,6 +171,7 @@ export function CyclotronJobInputs({sampleGlobalsWithInputs={sampleGlobalsWithInputs}errors={errors}warnings={warnings}+ emailFieldErrors={emailFieldErrors}/>)})}@@ -262,11 +268,13 @@ function EmailTemplateField({value,onChange,sampleGlobalsWithInputs,+ fieldErrors,}: {schema: CyclotronJobInputSchemaTypevalue: anyonChange: (value: any) => voidsampleGlobalsWithInputs: CyclotronJobInvocationGlobalsWithInputs | null+ fieldErrors?: EmailFieldErrors}): JSX.Element {return (<EmailTemplater@@ -276,6 +284,7 @@ function EmailTemplateField({value={value}onChange={onChange}templating={schema.templating}+ fieldErrors={fieldErrors}/>)}@@ -536,6 +545,7 @@ type CyclotronJobInputProps = {configuration: CyclotronJobInputConfigurationparentConfiguration?: CyclotronJobInputConfigurationsampleGlobalsWithInputs: CyclotronJobInvocationGlobalsWithInputs | null+ emailFieldErrors?: EmailFieldErrors}function NonFailureStatusCodesField({@@ -587,6 +597,7 @@ function CyclotronJobInputRenderer({configuration,parentConfiguration,sampleGlobalsWithInputs,+ emailFieldErrors,}: CyclotronJobInputProps): JSX.Element {const templating = schema.templating ?? true@@ -699,6 +710,7 @@ function CyclotronJobInputRenderer({value={input.value}onChange={onValueChange}sampleGlobalsWithInputs={sampleGlobalsWithInputs}+ fieldErrors={emailFieldErrors}/>)case 'non_failure_status_codes':@@ -884,6 +896,7 @@ function CyclotronJobInputWithSchema({sampleGlobalsWithInputs,errors,warnings,+ emailFieldErrors,}: CyclotronJobInputWithSchemaProps): JSX.Element | null {const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: schema.key })const [editing, setEditing] = useState(false)@@ -1032,6 +1045,7 @@ function CyclotronJobInputWithSchema({configuration={configuration}parentConfiguration={parentConfiguration}sampleGlobalsWithInputs={sampleGlobalsWithInputs}+ emailFieldErrors={emailFieldErrors}/>)}{warning && !value?.secret ? (diff --git a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsxindex e8a1dc4b24d9..b65c064169ba 100644--- a/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx+++ b/frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsx@@ -21,9 +21,26 @@ import { MessageTemplateCard } from 'products/workflows/frontend/TemplateLibraryimport { unsubscribeLinkToolCustomJs } from './custom-tools/unsubscribeLinkTool'import { EMAIL_TYPE_SUPPORTED_FIELDS, EmailTemplaterLogicProps, emailTemplaterLogic } from './emailTemplaterLogic'+import { EmailFieldErrors } from './types'export type EmailEditorMode = 'full' | 'preview'+// Maps a templater field key onto its validation message slot. Only the sender, recipient, and+// subject rows have their own message; body content is reported separately near the editor.+function fieldErrorFor(fieldKey: string, fieldErrors?: EmailFieldErrors): string | undefined {+ if (fieldKey === 'from' || fieldKey === 'to' || fieldKey === 'subject') {+ return fieldErrors?.[fieldKey]+ }+ return undefined+}++function FieldErrorMessage({ error }: { error?: string }): JSX.Element | null {+ if (!error) {+ return null+ }+ return <div className="pb-1 pl-2 text-xs text-danger">{error}</div>+}+function AddAdvancedFieldButtons(): JSX.Element | null {const { hiddenAdvancedFields } = useValues(emailTemplaterLogic)const { revealAdvancedField } = useActions(emailTemplaterLogic)@@ -436,60 +453,65 @@ function NativeEmailTemplaterForm({/></div>) : (- visibleFields.map((field) => (- <LemonField- key={field.key}- name={field.key}- className="gap-1 pl-2 border-b shrink-0"- // We will handle the error display ourselves- renderError={() => null}- showOptional={field.optional}- >- {({ value, onChange, error }: ChildFunctionProps) => (- <div className="flex gap-2 items-center">- <LemonLabel- className={error ? 'text-danger' : ''}- info={field.helpText}- showOptional={field.optional}- >- {field.label}- </LemonLabel>- {field.key === 'from' ? (- <NativeEmailIntegrationChoice value={value} onChange={onChange} />- ) : field.key === 'to' ? (- /**- * In email inputs, "to" maps to { email: string; name: string; },- * whereas other fields map directly to their string value- */- <LiquidSupportedText- value={value?.email}- onChange={(email) => onChange({ ...value, email })}- globals={logicProps.variables}- />- ) : (- <LiquidSupportedText- value={value}- onChange={onChange}- globals={logicProps.variables}- />- )}- {field.isAdvancedField && (- <LemonButton- size="xsmall"- type="tertiary"- icon={<IconX />}- className="mr-2"- onClick={() => {- onChange('')- hideAdvancedField(field.key)- }}- tooltip="Remove field"- />+ visibleFields.map((field) => {+ const fieldError = fieldErrorFor(field.key, logicProps.fieldErrors)+ return (+ <div key={field.key} className="border-b shrink-0">+ <LemonField+ name={field.key}+ className="gap-1 pl-2"+ // We will handle the error display ourselves+ renderError={() => null}+ showOptional={field.optional}+ >+ {({ value, onChange }: ChildFunctionProps) => (+ <div className="flex gap-2 items-center">+ <LemonLabel+ className={fieldError ? 'text-danger' : ''}+ info={field.helpText}+ showOptional={field.optional}+ >+ {field.label}+ </LemonLabel>+ {field.key === 'from' ? (+ <NativeEmailIntegrationChoice value={value} onChange={onChange} />+ ) : field.key === 'to' ? (+ /**+ * In email inputs, "to" maps to { email: string; name: string; },+ * whereas other fields map directly to their string value+ */+ <LiquidSupportedText+ value={value?.email}+ onChange={(email) => onChange({ ...value, email })}+ globals={logicProps.variables}+ />+ ) : (+ <LiquidSupportedText+ value={value}+ onChange={onChange}+ globals={logicProps.variables}+ />+ )}+ {field.isAdvancedField && (+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconX />}+ className="mr-2"+ onClick={() => {+ onChange('')+ hideAdvancedField(field.key)+ }}+ tooltip="Remove field"+ />+ )}+ </div>)}- </div>- )}- </LemonField>- ))+ </LemonField>+ <FieldErrorMessage error={fieldError} />+ </div>+ )+ }))}{!compactHeader && <AddAdvancedFieldButtons />}@@ -579,6 +601,9 @@ function NativeEmailTemplaterForm({)}</LemonField>)}+ {/* Rendered in both modes so the message stays visible while the body is edited in+ the full editor, not just in the preview */}+ <FieldErrorMessage error={logicProps.fieldErrors?.body} /></Form></>)diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsxindex fbe4b386c03b..b32d8b6b688a 100644--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx@@ -27,7 +27,7 @@ import { PreflightStatus, PropertyDefinition, PropertyDefinitionType, Realm } frimport { MessageTemplate } from 'products/workflows/frontend/TemplateLibrary/types'-import type { EmailTemplate } from './types'+import type { EmailFieldErrors, EmailTemplate } from './types'export type { EmailTemplate }@@ -159,6 +159,10 @@ export interface EmailTemplaterLogicProps {* parent form's dirty state and save flow see them without a separate editor-level save.*/layout?: 'modal' | 'inline'+ // Validation messages owned by the parent form, shown next to each field. The templater does+ // not compute these itself; a caller that validates the email step (e.g. the workflow builder)+ // decides what and when to show.+ fieldErrors?: EmailFieldErrors}function autoRevealAdvancedFields(diff --git a/frontend/src/scenes/hog-functions/email-templater/types.ts b/frontend/src/scenes/hog-functions/email-templater/types.tsindex 0603635ef7cb..17632360739f 100644--- a/frontend/src/scenes/hog-functions/email-templater/types.ts+++ b/frontend/src/scenes/hog-functions/email-templater/types.ts@@ -14,3 +14,13 @@ export type EmailTemplate = {bcc?: stringpreheader?: string}++// Per-field validation messages surfaced next to the sender, recipient, subject, and body+// inputs. Callers that validate an email step (e.g. the workflow builder) pass these in so the+// templater can place each message on its field instead of joining them into one blob.+export type EmailFieldErrors = {+ from?: string+ to?: string+ subject?: string+ body?: string+}diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsxindex 6fdf11130ce7..173c01879653 100644--- a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx@@ -34,7 +34,6 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.ElisWorkflowSubmitting,workflowLoading,workflowHasErrors,- workflowHasActionErrors,workflowUserAccessLevel,} = useValues(workflowLogic)const { saveWorkflowPartial, submitWorkflow, setWorkflowValue, duplicate, archiveWorkflow, discardChanges } =@@ -134,19 +133,16 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El><LemonButtontype={displayStatus === 'active' ? 'primary' : 'secondary'}+ // Stays clickable when steps have errors: the attempt is what+ // reveals the per-field messages, and saveWorkflowPartial+ // guards the actual enable with a toast.onClick={() =>saveWorkflowPartial({status: workflow?.status === 'draft' ? 'active' : 'draft',})}size="small"- disabledReason={- hasUnsavedChanges- ? 'Save changes first'- : workflow?.status === 'draft' && workflowHasActionErrors- ? 'Fix all errors before enabling'- : undefined- }+ disabledReason={hasUnsavedChanges ? 'Save changes first' : undefined}className="transition-colors duration-300 ease-in-out"data-attr="workflow-launch">diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsxindex 9ef6513d6aef..1d5af921ef27 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx@@ -28,6 +28,7 @@ export function StepFunctionConfiguration({ node }: { node: StepFunctionNode }):setMappings={(mappings) => partialSetWorkflowActionConfig(node.id, { mappings })}errors={validationResult?.errors}warnings={validationResult?.warnings}+ emailFieldErrors={validationResult?.emailErrors}/></>)diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsxindex 3ca824b5d99a..479a24752576 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx@@ -7,6 +7,7 @@ import { LemonBanner, LemonButton, LemonCollapse, Link, Spinner } from '@posthogimport { CyclotronJobInputs } from 'lib/components/CyclotronJob/CyclotronJobInputs'import { templateToConfiguration } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'+import { EmailFieldErrors } from 'scenes/hog-functions/email-templater/types'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -97,6 +98,7 @@ export function HogFlowFunctionConfiguration({setMappings,errors,warnings,+ emailFieldErrors,}: {templateId: stringinputs: Record<string, CyclotronJobInputType>@@ -105,6 +107,7 @@ export function HogFlowFunctionConfiguration({setMappings?: (mappings: HogFunctionMappingType[]) => voiderrors?: Record<string, string>warnings?: Record<string, string>+ emailFieldErrors?: EmailFieldErrors}): JSX.Element {const { workflow, hogFunctionTemplatesById, hogFunctionTemplatesByIdLoading } = useValues(workflowLogic)const { currentTeam, currentTeamLoading } = useValues(teamLogic)@@ -155,6 +158,7 @@ export function HogFlowFunctionConfiguration({<CyclotronJobInputserrors={errors}warnings={warnings}+ emailFieldErrors={emailFieldErrors}configuration={{ inputs: inputs as Record<string, CyclotronJobInputType>, inputs_schema: schema }}showSource={false}sampleGlobalsWithInputs={sampleGlobals}diff --git a/products/workflows/frontend/Workflows/hogflows/types.ts b/products/workflows/frontend/Workflows/hogflows/types.tsindex 392fefddb18d..94f3d9a420a5 100644--- a/products/workflows/frontend/Workflows/hogflows/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/types.ts@@ -2,6 +2,7 @@ import { Edge, Node } from '@xyflow/react'import z from 'zod'import { CyclotronJobInputsValidationResult } from 'lib/components/CyclotronJob/CyclotronJobInputsValidation'+import { EmailFieldErrors } from 'scenes/hog-functions/email-templater/types'import { AccessControlLevel, UserBasicType } from '~/types'@@ -94,6 +95,9 @@ export type DropzoneNode = Node<{ edge: HogFlowActionEdge; isBranchJoinDropzone?export type HogFlowActionValidationResult = CyclotronJobInputsValidationResult & {schema: z.ZodError | null+ // Per-field messages for a `function_email` step, placed next to their inputs. Only populated+ // once a save/enable has been attempted, so a freshly opened step stays clean.+ emailErrors?: EmailFieldErrors}export interface HogFlowTemplate extends z.infer<typeof HogFlowTemplateSchema> {diff --git a/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.ts b/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.tsindex add341df0c3c..485417102304 100644--- a/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.emailValidation.test.ts@@ -8,6 +8,7 @@ import { workflowLogic } from './workflowLogic'const WORKFLOW_ID = 'wf-email-validation-1'const EMAIL_NODE_ID = 'email_node'+const ADDED_EMAIL_NODE_ID = 'email_node_2'const makeEmailAction = (fromValue: any): Extract<HogFlowAction, { type: 'function_email' }> => ({id: EMAIL_NODE_ID,@@ -98,6 +99,8 @@ const loadedTemplatesResponse = {count: 1,}+const SENDER_ERROR = 'Choose an email sender, or connect a new one'+describe('workflowLogic email step "from" validation', () => {let logic: ReturnType<typeof workflowLogic.build>@@ -108,7 +111,7 @@ describe('workflowLogic email step "from" validation', () => {it.each([['"from" has no integrationId (no sender picked)', {}],['"from" is completely missing', undefined],- ])('flags the step as invalid when %s', async (_name, fromValue) => {+ ])('marks the step invalid but stays quiet before any save attempt when %s', async (_name, fromValue) => {useMocks({get: {'/api/environments/:team_id/hog_flows/:id/': makeWorkflow(fromValue),@@ -121,8 +124,84 @@ describe('workflowLogic email step "from" validation', () => {await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])const result = logic.values.actionValidationErrorsById[EMAIL_NODE_ID]+ // A freshly opened template step always lacks a sender; it must read as clean (no message)+ // while still being invalid so the node badge and enable-gate keep working.expect(result?.valid).toBe(false)- expect(result?.errors.email).toBe('Choose who to send this email from')+ expect(result?.emailErrors).toBeUndefined()+ expect(result?.errors.email).toBeUndefined()+ })++ it('reveals the field messages when enabling an invalid draft, while blocking the save itself', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': makeWorkflow({}),+ '/api/projects/:team_id/hog_function_templates/': hangingTemplatesEndpoint,+ },+ })+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ // The Enable button stays clickable on an invalid draft: the dispatch is what records the+ // attempt and reveals the messages, while the listener guard aborts the actual enable.+ await expectLogic(logic, () => {+ logic.actions.saveWorkflowPartial({ status: 'active' })+ }).toNotHaveDispatchedActions(['saveWorkflow'])++ const result = logic.values.actionValidationErrorsById[EMAIL_NODE_ID]+ expect(result?.valid).toBe(false)+ expect(result?.emailErrors?.from).toBe(SENDER_ERROR)+ })++ it('keeps an email step added after a save attempt quiet until the next attempt', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': makeWorkflow({}),+ '/api/projects/:team_id/hog_function_templates/': hangingTemplatesEndpoint,+ },+ })+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ logic.actions.saveWorkflowPartial({ status: 'active' })+ expect(logic.values.actionValidationErrorsById[EMAIL_NODE_ID]?.emailErrors?.from).toBe(SENDER_ERROR)++ const addedAction = { ...makeEmailAction({}), id: ADDED_EMAIL_NODE_ID, name: 'Send another email' }+ logic.actions.setWorkflowValues({ actions: [...logic.values.workflow.actions, addedAction] })++ // The new step is invalid from the start but must not yell until the user attempts a+ // save/enable with it in place.+ expect(logic.values.actionValidationErrorsById[ADDED_EMAIL_NODE_ID]?.valid).toBe(false)+ expect(logic.values.actionValidationErrorsById[ADDED_EMAIL_NODE_ID]?.emailErrors).toBeUndefined()+ expect(logic.values.actionValidationErrorsById[EMAIL_NODE_ID]?.emailErrors?.from).toBe(SENDER_ERROR)++ logic.actions.saveWorkflowPartial({ status: 'active' })+ expect(logic.values.actionValidationErrorsById[ADDED_EMAIL_NODE_ID]?.emailErrors?.from).toBe(SENDER_ERROR)+ })++ it('surfaces the softened sender message on its field once a save is attempted', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': makeWorkflow({}),+ '/api/projects/:team_id/hog_function_templates/': hangingTemplatesEndpoint,+ },+ patch: { '/api/environments/:team_id/hog_flows/:id/': makeWorkflow({}) },+ })+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ logic.actions.submitWorkflow()++ const result = logic.values.actionValidationErrorsById[EMAIL_NODE_ID]+ expect(result?.valid).toBe(false)+ expect(result?.emailErrors?.from).toBe(SENDER_ERROR)+ // Still per-field, never joined into a single blob under the whole input.+ expect(result?.errors.email).toBeUndefined()})it('does not flag a "from" error when an integration sender has been picked', async () => {@@ -138,11 +217,11 @@ describe('workflowLogic email step "from" validation', () => {await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])const result = logic.values.actionValidationErrorsById[EMAIL_NODE_ID]- expect(result?.errors.email).toBeUndefined()+ expect(result?.emailErrors).toBeUndefined()expect(result?.valid).toBe(true)})- it('keeps the email-block error after templates load (function-action branch must not clobber it)', async () => {+ it('keeps the step invalid after templates load (generic validator must not resurface a blob)', async () => {useMocks({get: {'/api/environments/:team_id/hog_flows/:id/': makeWorkflow({}),@@ -156,10 +235,12 @@ describe('workflowLogic email step "from" validation', () => {const result = logic.values.actionValidationErrorsById[EMAIL_NODE_ID]expect(result?.valid).toBe(false)- expect(result?.errors.email).toBe('Choose who to send this email from')+ // The generic input validator also joins the sub-fields into `errors.email`; it must be+ // stripped so nothing renders under the whole input.+ expect(result?.errors.email).toBeUndefined()})- it('propagates the step error into workflowHasActionErrors', async () => {+ it('propagates the step error into workflowHasActionErrors regardless of save attempts', async () => {useMocks({get: {'/api/environments/:team_id/hog_flows/:id/': makeWorkflow({}),diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 339cadd8d799..e44f220c9228 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -16,7 +16,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { publicWebhooksHostOrigin } from 'lib/utils/apiHost'import { LiquidRenderer } from 'lib/utils/liquid'import { sanitizeInputs } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'-import type { EmailTemplate } from 'scenes/hog-functions/email-templater/types'+import type { EmailFieldErrors } from 'scenes/hog-functions/email-templater/types'import { projectLogic } from 'scenes/projectLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -171,6 +171,7 @@ export interface workflowLogicValues {}| false| null+ saveAttemptedActionIds: string[] | nullsaveBaseUpdatedAt: string | nullscheduleConfigSources: {natural_language: boolean@@ -1835,6 +1836,9 @@ export interface workflowLogicActions {markAutoSave: (isAutoSave: boolean) => {isAutoSave: boolean}+ markSaveAttempted: (actionIds: string[]) => {+ actionIds: string[]+ }partialSetWorkflowActionConfig: (actionId: string,config: Partial<HogFlowAction['config']>@@ -2544,7 +2548,8 @@ export interface workflowLogicMeta {workflow: HogFlow,hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>,hogFunctionTemplatesByIdLoading: boolean,- scheduleStartsAt: string | null+ scheduleStartsAt: string | null,+ saveAttemptedActionIds: string[] | null) => Record<string, HogFlowActionValidationResult | null>workflowHasActionErrors: (workflow: HogFlow,@@ -2707,6 +2712,7 @@ export const workflowLogic = kea<workflowLogicType>([setScheduleRepeating: (repeating: boolean) => ({ repeating }),setSchedules: (schedules: HogFlowSchedule[]) => ({ schedules }),saveWorkflowPartial: (workflow: Partial<HogFlow>) => ({ workflow }),+ markSaveAttempted: (actionIds: string[]) => ({ actionIds }),triggerManualWorkflow: (variables: Record<string, any>) => ({variables,}),@@ -2930,6 +2936,18 @@ export const workflowLogic = kea<workflowLogicType>([setAutoSaveEnabled: (_, { enabled }) => enabled,},],+ // Gates when per-field step messages become visible: the action ids that were present at+ // the last save/enable attempt. Every step is validated the whole time (so the node badge+ // and enable-gate work), but a step only shows its messages once the user has tried to+ // save or enable with that step in place, which is the point where they can act on them.+ // A step added later stays quiet until the next attempt.+ saveAttemptedActionIds: [+ null as string[] | null,+ {+ markSaveAttempted: (_, { actionIds }) => actionIds,+ loadWorkflowSuccess: () => null,+ },+ ],// Set when another channel (another UI tab, MCP, or the API) saved this workflow while we had// unsaved local edits. Surfaces a non-destructive "reload / keep mine" banner. Cleared whenever// we reload or save, since both reconcile us with the server copy.@@ -3053,12 +3071,19 @@ export const workflowLogic = kea<workflowLogicType>([],actionValidationErrorsById: [- (s) => [s.workflow, s.hogFunctionTemplatesById, s.hogFunctionTemplatesByIdLoading, s.scheduleStartsAt],+ (s) => [+ s.workflow,+ s.hogFunctionTemplatesById,+ s.hogFunctionTemplatesByIdLoading,+ s.scheduleStartsAt,+ s.saveAttemptedActionIds,+ ],(workflow: HogFlow,hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>,hogFunctionTemplatesByIdLoading: boolean,- scheduleStartsAt: string | null+ scheduleStartsAt: string | null,+ saveAttemptedActionIds: string[] | null): Record<string, HogFlowActionValidationResult | null> => {// Warehouse-triggered workflows are person-less ("row-scoped"). Person-dependent// step types make no sense without a person, so we block them at save time.@@ -3096,35 +3121,39 @@ export const workflowLogic = kea<workflowLogicType>([const emailValue = action.config.inputs?.email?.value as any | undefinedconst emailTemplating = action.config.inputs?.email?.templating- const emailTemplateErrors: Partial<EmailTemplate> = {- html:- !emailValue?.html && !emailValue?.text- ? 'HTML or plain text is required'- : emailValue?.html+ const bodyError =+ !emailValue?.html && !emailValue?.text+ ? 'Add some content to the email body'+ : ((emailValue?.html? getTemplatingError(emailValue?.html, emailTemplating)- : undefined,- text: emailValue?.text- ? getTemplatingError(emailValue?.text, emailTemplating)- : undefined,+ : undefined) ??+ (emailValue?.text+ ? getTemplatingError(emailValue?.text, emailTemplating)+ : undefined))++ const emailErrors: EmailFieldErrors = {+ body: bodyError,subject: !emailValue?.subject- ? 'Subject is required'+ ? 'Add a subject line': getTemplatingError(emailValue?.subject, emailTemplating),from: !emailValue?.from?.integrationId- ? 'Choose who to send this email from'+ ? 'Choose an email sender, or connect a new one': undefined,to: !emailValue?.to?.email- ? 'To is required'+ ? 'Add a recipient': getTemplatingError(emailValue?.to?.email, emailTemplating),}- const combinedErrors = Object.values(emailTemplateErrors)- .filter((v) => !!v)- .join(', ')+ const hasEmailErrors = Object.values(emailErrors).some((v) => !!v)- if (combinedErrors) {+ if (hasEmailErrors) {result.valid = false- result.errors = {- email: combinedErrors,+ // Placed on each input by the templater, not joined into one blob under+ // the whole field. Held back until a save/enable attempt made with this+ // step present, so opening or adding a template-started step (which+ // always lacks a sender) reads as clean.+ if (saveAttemptedActionIds?.includes(action.id)) {+ result.emailErrors = emailErrors}}} else if (isFunctionAction(action) && action.config.template_id === 'template-native-push') {@@ -3162,6 +3191,13 @@ export const workflowLogic = kea<workflowLogicType>([result.valid = result.valid && configValidation.validresult.errors = { ...configValidation.errors, ...result.errors }result.warnings = { ...result.warnings, ...configValidation.warnings }++ if (action.type === 'function_email') {+ // The generic validator also joins the email sub-fields into one+ // blob under the `email` key; drop it so nothing renders under the+ // whole input. Per-field messages come from `emailErrors` instead.+ delete result.errors.email+ }}}@@ -3306,7 +3342,13 @@ export const workflowLogic = kea<workflowLogicType>([}actions.setExternallyEdited(false)},+ submitWorkflow: () => {+ actions.markSaveAttempted(values.workflow.actions.map((action) => action.id))+ },saveWorkflowPartial: async ({ workflow }) => {+ // Recorded before the error guard: an enable attempt on an invalid draft must still+ // reveal the per-field step messages even though the save itself is aborted.+ actions.markSaveAttempted(values.workflow.actions.map((action) => action.id))const merged = { ...values.workflow, ...workflow }if (merged.status === 'active' && values.workflowHasActionErrors) {lemonToast.error('Fix all errors before enabling')