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.

42.4 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { beforeUnload, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import { LemonDialog } from '@posthog/lemon-ui'

import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { objectsEqual } from 'lib/utils/objects'
import { EDITOR_MODE_PARAM, EDITOR_MODE_VALUE } from 'scenes/max/aiFirstCreate/aiFirstMode'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import {
    messagingTemplatesMakeTransactionalCreate,
    messagingTemplatesPartialUpdate,
} from 'products/messaging/frontend/generated/api'
import type { MessageTemplateContentApi } from 'products/messaging/frontend/generated/api.schemas'
import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'

import {
    senderAddressError,
    senderFrom,
    senderIntegrationFor,
} from '../../../../frontend/src/scenes/hog-functions/email-templater/emailSenderFields'
import type { EmailTemplate } from '../../../../frontend/src/scenes/hog-functions/email-templater/types'
import type { HogFunctionType, ResourceEditedEvent, UserBasicType } from '../../../../frontend/src/types'
import type { IntegrationType } from '../../../../frontend/src/types'
import { workflowLogic } from '../Workflows/workflowLogic'
import { NEW_TEMPLATE } from './constants'
import { newTemplateAgentLogic } from './newTemplateAgentLogic'
import { omitNullDesign } from './omitNullDesign'
import { TemplateSection, templateLibraryUrl, templateSectionFor, templateUrlInSection } from './templateSection'
import { MessageTemplate } from './types'

export type TransactionalTemplateTab = 'design' | 'metrics' | 'sends' | 'versions' | 'api'

type TemplateContent = MessageTemplate['content']

/** The form edits the draft when there is one. The draft field stays off the form value, so a publish never sends it. */
function splitDraft(template: MessageTemplate): {
    form: MessageTemplate
    draft: TemplateContent | null
    published: TemplateContent
} {
    const { draft_content, ...form } = template
    const draft = (draft_content as TemplateContent | null | undefined) ?? null
    return { form: draft ? { ...form, content: draft } : form, draft, published: template.content }
}

export interface MessageTemplateLogicProps {
    id: string
    messageId?: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageTemplateLogicValues {
    integrations: IntegrationType[] | null // integrationsLogic
    aiComposerAvailable: boolean // newTemplateAgentLogic
    currentTeamIdStrict: number | string // teamLogic
    deferredExternalEdit: ResourceEditedEvent | null
    draftOutOfDate: boolean
    draftsEnabled: boolean
    externallyEdited: boolean
    hasDraft: boolean
    hasUnsavedChanges: boolean
    isDiscardingDraft: boolean
    isMakingTransactional: boolean
    isSavingDraft: boolean
    isSavingSensitive: boolean
    isSyncingExternalEdit: boolean
    isTemplateSubmitting: boolean
    isTemplateValid: boolean
    isTransactional: boolean
    listUrl: string
    logicProps: MessageTemplateLogicProps
    message: any
    messageLoading: boolean
    originalTemplate: MessageTemplate
    publishedContent: TemplateContent | null
    savedDraft: TemplateContent | null
    section: TemplateSection
    showTemplateErrors: boolean
    template: MessageTemplate
    templateAllErrors: Record<string, any>
    templateChanged: boolean
    templateErrors: DeepPartialMap<
        {
            content: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            }
            created_at: string | null
            created_by: UserBasicType | null
            description: string
            draft_content?: MessageTemplateContentApi | null | undefined
            id: string
            name: string
            sensitive?: boolean | undefined
            tags?: string[] | undefined
            transactional_hog_flow_id?: string | null | undefined
            updated_at: string | null
        },
        ValidationErrorType
    >
    templateHasErrors: boolean
    templateLoading: boolean
    templateManualErrors: Record<string, any>
    templatePickerOpen: boolean
    templateTouched: boolean
    templateTouches: Record<string, boolean>
    templateValidationErrors: DeepPartialMap<
        {
            content: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            }
            created_at: string | null
            created_by: UserBasicType | null
            description: string
            draft_content?: MessageTemplateContentApi | null | undefined
            id: string
            name: string
            sensitive?: boolean | undefined
            tags?: string[] | undefined
            transactional_hog_flow_id?: string | null | undefined
            updated_at: string | null
        },
        ValidationErrorType
    >
    transactionalHogFlowId: string | null
    transactionalTab: TransactionalTemplateTab
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageTemplateLogicActions {
    resourceEdited: (event: ResourceEditedEvent) => {
        event: ResourceEditedEvent
    } // resourceEditedLogic
    autoSaveDraft: () => {
        value: true
    }
    confirmDiscardDraft: () => {
        value: true
    }
    deleteTemplate: () => {
        value: true
    }
    discardDraft: () => {
        value: true
    }
    discardDraftDone: () => {
        value: true
    }
    duplicateTemplate: () => {
        value: true
    }
    keepMyTemplateVersion: () => {
        value: true
    }
    loadMessage: () => any
    loadMessageFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMessageSuccess: (
        message: HogFunctionType | null,
        payload?: any
    ) => {
        message: HogFunctionType | null
        payload?: any
    }
    loadTemplate: () => any
    loadTemplateFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTemplateSuccess: (
        template: MessageTemplate,
        payload?: any
    ) => {
        template: MessageTemplate
        payload?: any
    }
    makeTransactional: () => {
        value: true
    }
    makeTransactionalDone: (hogFlowId: string | null) => {
        hogFlowId: string | null
    }
    replayDeferredExternalEdit: () => {
        value: true
    }
    resetTemplate: (values?: {
        content: {
            email: EmailTemplate
            templating: 'hog' | 'liquid'
        }
        created_at: string | null
        created_by: UserBasicType | null
        description: string
        draft_content?: MessageTemplateContentApi | null | undefined
        id: string
        name: string
        sensitive?: boolean | undefined
        tags?: string[] | undefined
        transactional_hog_flow_id?: string | null | undefined
        updated_at: string | null
    }) => {
        values?: {
            content: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            }
            created_at: string | null
            created_by: UserBasicType | null
            description: string
            draft_content?: MessageTemplateContentApi | null | undefined
            id: string
            name: string
            sensitive?: boolean | undefined
            tags?: string[] | undefined
            transactional_hog_flow_id?: string | null | undefined
            updated_at: string | null
        }
    }
    saveDraft: () => {
        value: true
    }
    saveDraftDone: (
        draft: TemplateContent,
        updatedAt: string
    ) => {
        draft: {
            email: EmailTemplate
            templating: 'hog' | 'liquid'
        }
        updatedAt: string
    }
    saveDraftFailed: () => {
        value: true
    }
    saveTags: (tags: string[]) => {
        tags: string[]
    }
    saveTemplate: (template: any) => any
    saveTemplateFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveTemplateSuccess: (
        template: MessageTemplate,
        payload?: any
    ) => {
        template: MessageTemplate
        payload?: any
    }
    setDeferredExternalEdit: (event: ResourceEditedEvent | null) => {
        event: ResourceEditedEvent | null
    }
    setDraftState: (
        draft: TemplateContent | null,
        published: TemplateContent
    ) => {
        draft: {
            email: EmailTemplate
            templating: 'hog' | 'liquid'
        } | null
        published: {
            email: EmailTemplate
            templating: 'hog' | 'liquid'
        }
    }
    setExternallyEdited: (externallyEdited: boolean) => {
        externallyEdited: boolean
    }
    setOriginalTemplate: (template: MessageTemplate) => {
        template: MessageTemplate
    }
    setSensitive: (sensitive: boolean) => {
        sensitive: boolean
    }
    setSensitiveDone: () => {
        value: true
    }
    setSyncingExternalEdit: (syncing: boolean) => {
        syncing: boolean
    }
    setTemplate: (template: MessageTemplate) => {
        template: MessageTemplate
    }
    setTemplateManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setTemplatePickerOpen: (open: boolean) => {
        open: boolean
    }
    setTemplateValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setTemplateValues: (
        values: DeepPartial<{
            content: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            }
            created_at: string | null
            created_by: UserBasicType | null
            description: string
            draft_content?: MessageTemplateContentApi | null | undefined
            id: string
            name: string
            sensitive?: boolean | undefined
            tags?: string[] | undefined
            transactional_hog_flow_id?: string | null | undefined
            updated_at: string | null
        }>
    ) => {
        values: DeepPartial<{
            content: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            }
            created_at: string | null
            created_by: UserBasicType | null
            description: string
            draft_content?: MessageTemplateContentApi | null | undefined
            id: string
            name: string
            sensitive?: boolean | undefined
            tags?: string[] | undefined
            transactional_hog_flow_id?: string | null | undefined
            updated_at: string | null
        }>
    }
    setTransactionalTab: (tab: TransactionalTemplateTab) => {
        tab: TransactionalTemplateTab
    }
    submitTemplate: () => {
        value: boolean
    }
    submitTemplateFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitTemplateRequest: (template: {
        content: {
            email: EmailTemplate
            templating: 'hog' | 'liquid'
        }
        created_at: string | null
        created_by: UserBasicType | null
        description: string
        draft_content?: MessageTemplateContentApi | null | undefined
        id: string
        name: string
        sensitive?: boolean | undefined
        tags?: string[] | undefined
        transactional_hog_flow_id?: string | null | undefined
        updated_at: string | null
    }) => {
        template: {
            content: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            }
            created_at: string | null
            created_by: UserBasicType | null
            description: string
            draft_content?: MessageTemplateContentApi | null | undefined
            id: string
            name: string
            sensitive?: boolean | undefined
            tags?: string[] | undefined
            transactional_hog_flow_id?: string | null | undefined
            updated_at: string | null
        }
    }
    submitTemplateSuccess: (template: {
        content: {
            email: EmailTemplate
            templating: 'hog' | 'liquid'
        }
        created_at: string | null
        created_by: UserBasicType | null
        description: string
        draft_content?: MessageTemplateContentApi | null | undefined
        id: string
        name: string
        sensitive?: boolean | undefined
        tags?: string[] | undefined
        transactional_hog_flow_id?: string | null | undefined
        updated_at: string | null
    }) => {
        template: {
            content: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            }
            created_at: string | null
            created_by: UserBasicType | null
            description: string
            draft_content?: MessageTemplateContentApi | null | undefined
            id: string
            name: string
            sensitive?: boolean | undefined
            tags?: string[] | undefined
            transactional_hog_flow_id?: string | null | undefined
            updated_at: string | null
        }
    }
    syncExternalEdit: () => {
        value: true
    }
    templateEditedElsewhere: (event: ResourceEditedEvent) => {
        event: ResourceEditedEvent
    }
    touchTemplateField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface messageTemplateLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        logicProps: (arg: MessageTemplateLogicProps) => MessageTemplateLogicProps
        transactionalHogFlowId: (originalTemplate: MessageTemplate) => string | null
        isTransactional: (transactionalHogFlowId: string | null) => boolean
        section: (location: { hash: string; pathname: string; search: string }) => TemplateSection
        listUrl: (isTransactional: boolean, section: TemplateSection) => string
        draftsEnabled: (transactionalHogFlowId: string | null) => boolean
        hasDraft: (
            savedDraft: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            } | null
        ) => boolean
        draftOutOfDate: (
            template: MessageTemplate,
            savedDraft: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            } | null,
            publishedContent: {
                email: EmailTemplate
                templating: 'hog' | 'liquid'
            } | null
        ) => boolean
        hasUnsavedChanges: (
            draftsEnabled: boolean,
            templateChanged: boolean,
            template: MessageTemplate,
            originalTemplate: MessageTemplate,
            draftOutOfDate: boolean
        ) => boolean
    }
}

export type messageTemplateLogicType = MakeLogicType<
    messageTemplateLogicValues,
    messageTemplateLogicActions,
    MessageTemplateLogicProps,
    messageTemplateLogicMeta
>

export const messageTemplateLogic = kea<messageTemplateLogicType>([
    path(['products', 'workflows', 'frontend', 'messageTemplateLogic']),
    props({} as MessageTemplateLogicProps),
    key(({ id }) => id ?? 'new'),
    connect(() => ({
        values: [
            teamLogic,
            ['currentTeamIdStrict'],
            newTemplateAgentLogic,
            ['aiComposerAvailable'],
            integrationsLogic,
            ['integrations'],
        ],
        actions: [resourceEditedLogic, ['resourceEdited']],
    })),
    actions({
        setTemplate: (template: MessageTemplate) => ({ template }),
        setOriginalTemplate: (template: MessageTemplate) => ({ template }),
        duplicateTemplate: true,
        deleteTemplate: true,
        setTemplatePickerOpen: (open: boolean) => ({ open }),
        saveTags: (tags: string[]) => ({ tags }),
        templateEditedElsewhere: (event: ResourceEditedEvent) => ({ event }),
        setDeferredExternalEdit: (event: ResourceEditedEvent | null) => ({ event }),
        replayDeferredExternalEdit: true,
        syncExternalEdit: true,
        keepMyTemplateVersion: true,
        setExternallyEdited: (externallyEdited: boolean) => ({ externallyEdited }),
        setSyncingExternalEdit: (syncing: boolean) => ({ syncing }),
        makeTransactional: true,
        makeTransactionalDone: (hogFlowId: string | null) => ({ hogFlowId }),
        setSensitive: (sensitive: boolean) => ({ sensitive }),
        setSensitiveDone: true,
        setTransactionalTab: (tab: TransactionalTemplateTab) => ({ tab }),
        setDraftState: (draft: TemplateContent | null, published: TemplateContent) => ({ draft, published }),
        autoSaveDraft: true,
        saveDraft: true,
        saveDraftDone: (draft: TemplateContent, updatedAt: string) => ({ draft, updatedAt }),
        saveDraftFailed: true,
        discardDraft: true,
        confirmDiscardDraft: true,
        discardDraftDone: true,
    }),
    selectors({
        logicProps: [
            () => [(_, props: MessageTemplateLogicProps) => props],
            (props: MessageTemplateLogicProps): MessageTemplateLogicProps => props,
        ],
    }),
    forms(({ actions, values }) => ({
        template: {
            defaults: {
                ...NEW_TEMPLATE,
            },
            errors: (template: MessageTemplate) => ({
                name: !template.name ? 'Name is required' : undefined,
                content: {
                    email: {
                        subject: !template.content.email.subject ? 'Subject is required' : undefined,
                        from: {
                            email:
                                senderAddressError(
                                    senderFrom(template.content.email).email,
                                    senderIntegrationFor(template.content.email, values.integrations)
                                ) ?? undefined,
                        },
                    },
                },
            }),
            submit: async (template) => {
                actions.saveTemplate(template)
            },
        },
    })),
    reducers({
        template: [
            { ...NEW_TEMPLATE } as MessageTemplate,
            {
                setTemplate: (_, { template }) => template,
            },
        ],
        originalTemplate: [
            { ...NEW_TEMPLATE } as MessageTemplate,
            {
                setOriginalTemplate: (_, { template }) => template,
                loadTemplateSuccess: (_, { template }) => {
                    return template
                },
            },
        ],
        isMakingTransactional: [
            false,
            {
                makeTransactional: () => true,
                makeTransactionalDone: () => false,
            },
        ],
        isSavingSensitive: [
            false,
            {
                setSensitive: () => true,
                setSensitiveDone: () => false,
            },
        ],
        // The draft as last saved, and the content sends use. Both come from the server.
        savedDraft: [
            null as TemplateContent | null,
            {
                setDraftState: (_, { draft }) => draft,
                saveDraftDone: (_, { draft }) => draft,
            },
        ],
        publishedContent: [
            null as TemplateContent | null,
            {
                setDraftState: (_, { published }) => published ?? null,
            },
        ],
        isSavingDraft: [
            false,
            {
                saveDraft: () => true,
                saveDraftDone: () => false,
                saveDraftFailed: () => false,
            },
        ],
        isDiscardingDraft: [
            false,
            {
                confirmDiscardDraft: () => true,
                discardDraftDone: () => false,
            },
        ],
        transactionalTab: [
            'design' as TransactionalTemplateTab,
            {
                setTransactionalTab: (_, { tab }) => tab,
            },
        ],
        templatePickerOpen: [
            false,
            {
                setTemplatePickerOpen: (_, { open }) => open,
            },
        ],
        // Another channel (the PostHog AI agent, the API, another tab) saved this template while the form
        // holds unsaved edits. The banner lets the person choose which version wins.
        externallyEdited: [
            false,
            {
                setExternallyEdited: (_, { externallyEdited }) => externallyEdited,
            },
        ],
        isSyncingExternalEdit: [
            false,
            {
                setSyncingExternalEdit: (_, { syncing }) => syncing,
            },
        ],
        // An edit event that arrived while our own save or load was in flight. Replayed once it settles.
        // The newest stamp wins, so our own echo cannot displace an external edit that arrived before it.
        deferredExternalEdit: [
            null as ResourceEditedEvent | null,
            {
                setDeferredExternalEdit: (state, { event }) =>
                    !event || !state || dayjs(event.updated_at).isAfter(dayjs(state.updated_at)) ? event : state,
            },
        ],
    }),
    selectors({
        // The saved state decides it: an unsaved template can't be transactional yet.
        transactionalHogFlowId: [
            (s) => [s.originalTemplate],
            (originalTemplate: MessageTemplate): string | null => originalTemplate.transactional_hog_flow_id ?? null,
        ],
        isTransactional: [
            (s) => [s.transactionalHogFlowId],
            (transactionalHogFlowId: string | null): boolean => !!transactionalHogFlowId,
        ],
        // The nav section the page was opened under. Links from the page stay in it.
        section: [
            () => [router.selectors.location],
            (location: { pathname: string }): TemplateSection => templateSectionFor(location.pathname),
        ],
        // The list a person returns to: transactional emails live in their own section.
        listUrl: [
            (s) => [s.isTransactional, s.section],
            (isTransactional: boolean, section: TemplateSection): string =>
                isTransactional ? urls.transactional() : templateLibraryUrl(section),
        ],
        // Sends use a transactional template's content, so its edits save as a draft until they are published.
        draftsEnabled: [
            (s) => [s.transactionalHogFlowId],
            (transactionalHogFlowId: string | null): boolean => !!transactionalHogFlowId,
        ],
        hasDraft: [
            (s) => [s.savedDraft],
            (
                savedDraft: {
                    email: EmailTemplate
                    templating: 'hog' | 'liquid'
                } | null
            ): boolean => savedDraft !== null,
        ],
        draftOutOfDate: [
            (s) => [s.template, s.savedDraft, s.publishedContent],
            (
                template: MessageTemplate,
                savedDraft: {
                    email: EmailTemplate
                    templating: 'hog' | 'liquid'
                } | null,
                publishedContent: {
                    email: EmailTemplate
                    templating: 'hog' | 'liquid'
                } | null
            ): boolean => !objectsEqual(template.content, savedDraft ?? publishedContent),
        ],
        hasUnsavedChanges: [
            (s) => [s.draftsEnabled, s.templateChanged, s.template, s.originalTemplate, s.draftOutOfDate],
            (
                draftsEnabled: boolean,
                templateChanged: boolean,
                template: MessageTemplate,
                originalTemplate: MessageTemplate,
                draftOutOfDate: boolean
            ): boolean =>
                draftsEnabled
                    ? template.name !== originalTemplate.name ||
                      template.description !== originalTemplate.description ||
                      draftOutOfDate
                    : templateChanged,
        ],
    }),
    loaders(({ props, actions }) => ({
        template: {
            loadTemplate: async () => {
                if (!props.id || props.id === 'new') {
                    return {
                        ...NEW_TEMPLATE,
                    } as MessageTemplate
                }

                const { form, draft, published } = splitDraft(await api.messaging.getTemplate(props.id))
                actions.setDraftState(draft, published)
                return form
            },
            saveTemplate: async (template) => {
                // Saving the content publishes it, and the server clears the draft. The sensitive setting
                // and the tags each save on their own, so a publish never sends them and can't undo a
                // change made in another tab since this one loaded the template.
                const payload = template.content?.email
                    ? { ...template, content: { ...template.content, email: omitNullDesign(template.content.email) } }
                    : template
                const { sensitive: _sensitive, tags: _tags, ...content } = payload
                const saved =
                    template.id === 'new'
                        ? await api.messaging.createTemplate(payload)
                        : await api.messaging.updateTemplate(template.id, content)
                const { form, draft, published } = splitDraft(saved)
                actions.setDraftState(draft, published)
                return form
            },
        },
        message: {
            loadMessage: async () => {
                if (!props.messageId) {
                    return null
                }
                return await api.hogFunctions.get(props.messageId)
            },
        },
    })),
    listeners(({ actions, props, values }) => ({
        resourceEdited: ({ event }) => {
            if (event.resource_type === 'MessageTemplate' && event.resource_id === props.id) {
                actions.templateEditedElsewhere(event)
            }
        },
        templateEditedElsewhere: ({ event }) => {
            // The echo of our own save can arrive before its response. Parked until the flight settles,
            // it then compares equal to the loaded stamp and is dropped.
            if (
                values.templateLoading ||
                values.isMakingTransactional ||
                values.isSavingSensitive ||
                values.isSavingDraft ||
                values.isDiscardingDraft
            ) {
                actions.setDeferredExternalEdit(event)
                return
            }
            const loadedUpdatedAt = values.originalTemplate.updated_at
            if (!loadedUpdatedAt || !dayjs(event.updated_at).isAfter(dayjs(loadedUpdatedAt))) {
                return
            }
            if (values.hasUnsavedChanges) {
                actions.setExternallyEdited(true)
            } else {
                actions.syncExternalEdit()
            }
        },
        replayDeferredExternalEdit: () => {
            const event = values.deferredExternalEdit
            if (event) {
                actions.setDeferredExternalEdit(null)
                actions.templateEditedElsewhere(event)
            }
        },
        syncExternalEdit: () => {
            actions.setSyncingExternalEdit(true)
            actions.loadTemplate()
        },
        keepMyTemplateVersion: () => {
            actions.setExternallyEdited(false)
            actions.autoSaveDraft()
        },
        setTemplateValue: () => actions.autoSaveDraft(),
        saveTags: async ({ tags }, breakpoint) => {
            // An unsaved template has no row yet, so its tags ride the create.
            if (!props.id || props.id === 'new') {
                actions.setTemplateValue('tags', tags)
                return
            }
            // The editor fires one save per tag added or removed. Without this, a burst of clicks puts
            // several writes in flight at once, and the one that lands last wins rather than the latest
            // selection. The wait collapses the burst into a single write.
            await breakpoint(300)
            // Tags are metadata: they apply live and must not publish a transactional template's draft,
            // which a full form save would.
            let updated: MessageTemplate
            try {
                updated = await api.messaging.updateTemplate(props.id, { tags })
            } catch (error: any) {
                lemonToast.error(`Failed to save tags: ${error?.detail || error?.message || 'Unknown error'}`)
                return
            }
            // Outside the catch: a breakpoint throws to unwind a superseded listener, and catching that
            // would report it as a failed save.
            breakpoint()
            actions.setTemplate({ ...values.template, tags: updated.tags })
            actions.setOriginalTemplate({ ...values.originalTemplate, tags: updated.tags })
        },
        setTemplateValues: () => actions.autoSaveDraft(),
        autoSaveDraft: async (_, breakpoint) => {
            if (!values.draftsEnabled) {
                return
            }
            await breakpoint(1500)
            // A save in flight starts the next one when it lands, so edits made meanwhile are not lost.
            // While the edited-elsewhere banner is up, a save would overwrite the other edit before the person chooses.
            if (
                !values.draftOutOfDate ||
                values.externallyEdited ||
                values.isTemplateSubmitting ||
                values.isSavingDraft ||
                values.isDiscardingDraft
            ) {
                return
            }
            actions.saveDraft()
        },
        saveDraft: async () => {
            const content = values.template.content
            try {
                const updated = await messagingTemplatesPartialUpdate(String(values.currentTeamIdStrict), props.id, {
                    // The form type still allows the legacy 'hog' templating, which templates never use.
                    draft_content: content as MessageTemplateContentApi,
                })
                actions.saveDraftDone(content, updated.updated_at)
            } catch {
                actions.saveDraftFailed()
                lemonToast.error("Couldn't save your draft. Your changes are still in the editor.")
            }
        },
        saveDraftDone: ({ updatedAt }) => {
            // The echo of this save then matches the loaded stamp and is not read as an edit from elsewhere.
            actions.setOriginalTemplate({ ...values.originalTemplate, updated_at: updatedAt })
            actions.replayDeferredExternalEdit()
            actions.autoSaveDraft()
        },
        saveDraftFailed: () => {
            actions.replayDeferredExternalEdit()
        },
        discardDraft: () => {
            LemonDialog.open({
                title: 'Discard your draft?',
                description: 'This deletes your unpublished changes. The live email stays as it is.',
                primaryButton: {
                    children: 'Discard draft',
                    status: 'danger',
                    onClick: () => actions.confirmDiscardDraft(),
                },
                secondaryButton: { children: 'Cancel' },
            })
        },
        confirmDiscardDraft: async (_, breakpoint) => {
            // A draft save that lands after the discard would bring the draft back, so let it finish first.
            while (values.isSavingDraft) {
                await breakpoint(100)
            }
            try {
                const updated = await messagingTemplatesPartialUpdate(String(values.currentTeamIdStrict), props.id, {
                    draft_content: null,
                })
                const published = updated.content as TemplateContent
                actions.setDraftState(null, published)
                actions.setOriginalTemplate({
                    ...values.originalTemplate,
                    content: published,
                    updated_at: updated.updated_at,
                })
                actions.resetTemplate({ ...values.template, content: published, updated_at: updated.updated_at })
            } catch {
                lemonToast.error("Couldn't discard your draft. Try again.")
            }
            actions.discardDraftDone()
            actions.replayDeferredExternalEdit()
        },
        makeTransactional: async () => {
            try {
                const updated = await messagingTemplatesMakeTransactionalCreate(
                    String(values.currentTeamIdStrict),
                    props.id,
                    {}
                )
                // Only these fields changed. Merging them in keeps edits made while this ran.
                const changes = {
                    transactional_hog_flow_id: updated.transactional_hog_flow_id ?? null,
                    updated_at: updated.updated_at,
                }
                // Conversion stores the sender it sends from on the template, so the editor shows it.
                const from = updated.content?.email?.from as EmailTemplate['from'] | undefined
                const withSender = (template: MessageTemplate): MessageTemplate =>
                    from
                        ? {
                              ...template,
                              ...changes,
                              content: { ...template?.content, email: { ...template?.content?.email, from } },
                          }
                        : { ...template, ...changes }
                actions.setOriginalTemplate(withSender(values.originalTemplate))
                if (values.templateChanged) {
                    actions.setTemplateValues(changes)
                    if (from) {
                        actions.setTemplateValue('content.email.from', from)
                    }
                } else {
                    // Resetting moves the form's baseline too, so the form doesn't read as edited.
                    actions.resetTemplate(withSender(values.template))
                }
                actions.makeTransactionalDone(updated.transactional_hog_flow_id ?? null)
                actions.replayDeferredExternalEdit()
                lemonToast.success('Template is now transactional. You can send it over the API.')
            } catch (error: any) {
                actions.makeTransactionalDone(null)
                actions.replayDeferredExternalEdit()
                lemonToast.error(error?.detail ?? 'Could not make the template transactional.')
            }
        },
        setSensitive: async ({ sensitive }) => {
            try {
                // Saved on its own, so it applies to sends at once and leaves any content draft untouched.
                const updated = await messagingTemplatesPartialUpdate(String(values.currentTeamIdStrict), props.id, {
                    sensitive,
                })
                const changes = { sensitive: updated.sensitive, updated_at: updated.updated_at }
                actions.setOriginalTemplate({ ...values.originalTemplate, ...changes })
                if (values.templateChanged) {
                    actions.setTemplateValues(changes)
                } else {
                    actions.resetTemplate({ ...values.template, ...changes })
                }
                posthog.capture('email template sensitive changed', { template_id: props.id, sensitive })
            } catch (error: any) {
                lemonToast.error(error?.detail ?? "Couldn't change the setting. Try again.")
            }
            actions.setSensitiveDone()
            actions.replayDeferredExternalEdit()
        },
        loadTemplateFailure: () => {
            // The form is still the stale copy. The banner keeps the conflict visible and offers the retry.
            if (values.isSyncingExternalEdit) {
                actions.setSyncingExternalEdit(false)
                actions.setExternallyEdited(true)
            }
        },
        loadTemplateSuccess: ({ template }) => {
            if (values.isSyncingExternalEdit) {
                // The server copy replaces the form. A Reload from the banner discards the local edits on purpose.
                actions.resetTemplate(template)
                actions.setSyncingExternalEdit(false)
                actions.setExternallyEdited(false)
            }
            actions.replayDeferredExternalEdit()
        },
        submitTemplateFailure: () => {
            const errors = values.templateAllErrors
            if (errors?.name) {
                lemonToast.error('Name is required')
            } else if (errors?.content?.email?.subject) {
                lemonToast.error('Subject is required')
            } else if (typeof errors?.content?.email?.from === 'object' && errors.content.email.from.email) {
                lemonToast.error(errors.content.email.from.email)
            }
        },
        saveTemplateFailure: ({ errorObject }) => {
            actions.replayDeferredExternalEdit()
            // A 404 means the template no longer resolves for this environment - it was soft-deleted,
            // or it belongs to a different environment than the one currently selected.
            if (errorObject?.status === 404) {
                lemonToast.error('This template no longer exists in this environment. It may have been deleted.', {
                    button: {
                        label: 'Back to library',
                        action: () => router.actions.push(urls.workflows('library')),
                    },
                })
                return
            }
            lemonToast.error('Failed to save template. Please try again.')
        },
        saveTemplateSuccess: async ({ template }) => {
            lemonToast.success(
                props.id === 'new' ? 'Template created' : values.draftsEnabled ? 'Published' : 'Template saved'
            )
            // Clear the unsaved-changes state before navigating so the beforeUnload guard
            // does not intercept the post-save redirect.
            actions.resetTemplate(template)
            actions.setOriginalTemplate(template)
            if (values.transactionalHogFlowId) {
                // The save wrote a new workflow version, and nothing else tells the bound workflow tabs.
                workflowLogic.findMounted({ id: values.transactionalHogFlowId })?.actions.loadWorkflow()
            }
            if (props.id === 'new') {
                router.actions.push(urls.workflows('library'))
            } else if (template.id) {
                router.actions.replace(templateUrlInSection(template.id, values.section))
            }
            actions.replayDeferredExternalEdit()
        },
        loadMessageSuccess: async ({ message }) => {
            if (!message) {
                return
            }
            actions.setTemplateValues({
                name: message.name,
                description: message.description,
                content: {
                    email: message.inputs?.email?.value,
                },
            })
        },
        duplicateTemplate: async () => {
            if (values.hasUnsavedChanges) {
                lemonToast.error('Please save your changes before duplicating')
                return
            }
            const template = values.template
            try {
                const duplicatedTemplate = await api.messaging.createTemplate({
                    name: `${template.name} (copy)`,
                    description: template.description,
                    content: template.content,
                })
                lemonToast.success('Template duplicated successfully')
                router.actions.push(templateUrlInSection(duplicatedTemplate.id, values.section))
            } catch {
                lemonToast.error('Failed to duplicate template')
            }
        },
        deleteTemplate: async () => {
            const template = values.template
            if (!template || template.id === 'new') {
                return
            }
            await deleteWithUndo({
                endpoint: `environments/${values.currentTeamIdStrict}/messaging_templates`,
                object: {
                    id: template.id,
                    name: template.name,
                },
                callback: (undo) => {
                    if (!undo) {
                        router.actions.push(values.listUrl)
                    }
                },
            })
        },
    })),
    urlToAction(({ actions, props }) => ({
        // The escape hatch from the AI composer changes only the search params, so this logic sees no remount.
        [urls.workflowsLibraryTemplateNew()]: (_, searchParams) => {
            if (props.id === 'new' && !props.messageId && searchParams[EDITOR_MODE_PARAM] === EDITOR_MODE_VALUE) {
                actions.setTemplatePickerOpen(true)
            }
        },
    })),
    afterMount(({ props, actions, values }) => {
        if (props.id !== 'new') {
            actions.loadTemplate()
        }

        if (props.messageId) {
            actions.loadMessage()
        } else {
            // If we've previously loaded a message, reset the template to the default
            actions.resetTemplate(NEW_TEMPLATE)
        }

        // A fresh template starts from the picker: blank, or one of the existing templates. The AI composer
        // is its own starting point, so the picker waits for the escape hatch there.
        if (props.id === 'new' && !props.messageId && !values.aiComposerAvailable) {
            actions.setTemplatePickerOpen(true)
        }
    }),
    beforeUnload(({ values, actions }) => ({
        // Guards both new and existing templates - a brand-new template only exists in form
        // state until "Create" is pressed, so leaving without saving would discard it entirely.
        enabled: (newLocation) => {
            if (!values.hasUnsavedChanges) {
                return false
            }
            // Allow same-path changes (e.g. query params) through without warning.
            if (newLocation && newLocation.pathname === router.values.location.pathname) {
                return false
            }
            return true
        },
        message: 'Leave template?\nChanges you made will be discarded.',
        onConfirm: () => actions.resetTemplate(values.originalTemplate),
    })),
])