:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): draft and publish edits to transactional email templates (#118664)
Harley Alexander022348fddac5
diff --git a/products/messaging/backend/facade/templates.py b/products/messaging/backend/facade/templates.pyindex f771e5fb3f1a..91fa113d6cfc 100644--- a/products/messaging/backend/facade/templates.py+++ b/products/messaging/backend/facade/templates.py@@ -35,6 +35,7 @@ class MessageTemplateRow:message_category_id: UUID | Nonedeleted: booltransactional_hog_flow_id: UUID | None+ draft_content: dict[str, Any] | Nonedef _to_contract(row: MessageTemplate) -> MessageTemplateRow:@@ -50,6 +51,7 @@ def _to_contract(row: MessageTemplate) -> MessageTemplateRow:message_category_id=row.message_category_id,deleted=row.deleted,transactional_hog_flow_id=row.transactional_hog_flow_id,+ draft_content=row.draft_content,)@@ -87,6 +89,11 @@ def update_template(team_id: int, template_id: UUID, fields: dict[str, Any]) ->return _to_contract(templates_service.update_template(team_id, template_id, fields))+def save_template_draft(team_id: int, template_id: UUID, draft: dict[str, Any] | None) -> MessageTemplateRow:+ """Replace only the template's unpublished draft. `None` discards it."""+ return _to_contract(templates_service.save_draft(team_id, template_id, draft))++def edit_template_content(team_id: int, template_id: UUID, edit: Callable[[dict[str, Any]], dict[str, Any]]) -> MessageTemplateRow:diff --git a/products/messaging/backend/migrations/0007_messagetemplate_draft_content.py b/products/messaging/backend/migrations/0007_messagetemplate_draft_content.pynew file mode 100644index 000000000000..f1871edc9fd5--- /dev/null+++ b/products/messaging/backend/migrations/0007_messagetemplate_draft_content.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.18 on 2026-10-16 15:08++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("messaging", "0006_messagetemplate_transactional_hog_flow_id"),+ ]++ operations = [+ migrations.AddField(+ model_name="messagetemplate",+ name="draft_content",+ field=models.JSONField(blank=True, null=True),+ ),+ ]diff --git a/products/messaging/backend/migrations/max_migration.txt b/products/messaging/backend/migrations/max_migration.txtindex 2345ae4be7e7..123776e1eaf8 100644--- a/products/messaging/backend/migrations/max_migration.txt+++ b/products/messaging/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_messagetemplate_transactional_hog_flow_id+0007_messagetemplate_draft_contentdiff --git a/products/messaging/backend/models/message_template.py b/products/messaging/backend/models/message_template.pyindex 874ed7c81e8e..cada608059c3 100644--- a/products/messaging/backend/models/message_template.py+++ b/products/messaging/backend/models/message_template.py@@ -21,6 +21,8 @@ class MessageTemplate(UUIDTModel):# Set once the template is made transactional: the workflow the send API runs for it. A plain id,# because the workflow lives in the workflows product.transactional_hog_flow_id = models.UUIDField(null=True, blank=True)+ # Unpublished edits to a transactional template. Sends keep using `content` until the draft is published.+ draft_content = models.JSONField(null=True, blank=True)class Meta:db_table = "posthog_messagetemplate"diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.pyindex 29fb1eb59459..cc7de29629b9 100644--- a/products/messaging/backend/presentation/views/message_templates.py+++ b/products/messaging/backend/presentation/views/message_templates.py@@ -48,6 +48,7 @@ from products.messaging.backend.facade.templates import (edit_template_content,get_template,list_templates,+ save_template_draft,team_category_id,update_template,)@@ -109,7 +110,9 @@ class UnlayerDesignField(serializers.JSONField):class EmailTemplateSerializer(serializers.Serializer):subject = serializers.CharField(required=False,- help_text="Email subject line. Supports Liquid templating. Required for email-type templates.",+ allow_blank=True,+ help_text="Email subject line. Supports Liquid templating. Required in `content` for email-type templates. "+ "A `draft_content` may leave it blank until it is published.",)text = serializers.CharField(required=False,@@ -205,11 +208,18 @@ class MessageTemplateSerializer(serializers.Serializer):help_text="The workflow that sends this template over the transactional email API. Null until the ""template is made transactional. Each content save writes a new version of it.",)+ draft_content = MessageTemplateContentSerializer(+ required=False,+ allow_null=True,+ help_text="Unpublished edits to a transactional template's content. Sends keep using `content`. Saving "+ "`content` publishes it and clears the draft. Set null to discard the draft.",+ )def validate(self, data: Any) -> Any:template_type = data.get("type")email = data.get("content", {}).get("email") if data.get("content") else None- if template_type == "email" and email and not email.get("subject"):+ # Only published content needs a subject. A draft may still be missing one.+ if email and (template_type == "email" or "subject" in email) and not email.get("subject"):raise serializers.ValidationError({"content": {"email": {"subject": "Subject is required for email templates."}}})@@ -450,6 +460,17 @@ class MessageTemplatesViewSet(template = self.get_object()serializer = self.get_serializer(self._with_creators([template])[0], data=request.data, partial=partial)serializer.is_valid(raise_exception=True)+ fields = serializer.validated_data+ if fields.keys() == {"draft_content"}:+ # Sends never read the draft, so it skips the sendability check and the workflow sync. It is still an edit+ # of the transactional email, so it needs the same workflow access as a publish.+ if template.transactional_hog_flow_id:+ self._require_workflow_editor(template.transactional_hog_flow_id)+ updated = save_template_draft(self.team_id, template.id, fields["draft_content"])+ self._emit_resource_edited(updated)+ return Response(self._serialize(updated))+ if "content" in fields:+ fields["draft_content"] = None# Sends use the workflow's copy, so the template and its new workflow version are saved together,# under a row lock that keeps a concurrent make_transactional from slipping in between.with transaction.atomic():@@ -457,10 +478,10 @@ class MessageTemplatesViewSet(if hog_flow_id:self._require_workflow_editor(hog_flow_id)try:- check_transactional_update(template.id, self.team_id, serializer.validated_data)+ check_transactional_update(template.id, self.team_id, fields)except TransactionalEmailError as e:raise TransactionalEmailRejected(e) from None- updated = update_template(self.team_id, template.id, serializer.validated_data)+ updated = update_template(self.team_id, template.id, fields)if hog_flow_id and not updated.deleted:self._sync_transactional_workflow(template.id)# The sync unlinks the template when its workflow was deleted.diff --git a/products/messaging/backend/services/message_templates.py b/products/messaging/backend/services/message_templates.pyindex 885b66f760e5..36ea21902506 100644--- a/products/messaging/backend/services/message_templates.py+++ b/products/messaging/backend/services/message_templates.py@@ -6,6 +6,7 @@ from uuid import UUIDfrom django.db import models, transactionfrom django.db.models.fields.json import KTfrom django.db.models.functions import Cast+from django.utils import timezonefrom products.messaging.backend.facade.contracts import EmailTemplateSummaryfrom products.messaging.backend.models import MessageCategory, MessageTemplate@@ -102,6 +103,14 @@ def update_template(team_id: int, template_id: UUID | str, fields: dict[str, Anyreturn template+def save_draft(team_id: int, template_id: UUID | str, draft: dict[str, Any] | None) -> MessageTemplate:+ # Writes only the draft, so a draft save that races a publish, a delete or a conversion can't undo it.+ MessageTemplate.objects.filter(team_id=team_id, deleted=False, pk=template_id).update(+ draft_content=draft, updated_at=timezone.now()+ )+ return team_template(team_id, template_id)++def edit_content_locked(team_id: int, template_id: UUID | str, edit: Callable[[dict[str, Any]], dict[str, Any]]) -> MessageTemplate:diff --git a/products/messaging/backend/tests/api/test_message_templates.py b/products/messaging/backend/tests/api/test_message_templates.pyindex 33be978ef09d..faba06d4866a 100644--- a/products/messaging/backend/tests/api/test_message_templates.py+++ b/products/messaging/backend/tests/api/test_message_templates.py@@ -112,17 +112,25 @@ class TestMessageTemplatesAPI(APIBaseTest):)assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED- def test_create_email_template_without_subject_fails(self):- response = self.client.post(- f"/api/environments/{self.team.id}/messaging_templates/",- data={- "name": "No Subject Template",- "content": {"email": {"html": "<p>Hello</p>"}},- "type": "email",- },- format="json",- )- assert response.status_code == status.HTTP_400_BAD_REQUEST+ @parameterized.expand(+ [+ (+ "create_without_subject",+ "post",+ False,+ {"name": "No Subject Template", "content": {"email": {"html": "<p>Hello</p>"}}, "type": "email"},+ ),+ ("update_with_blank_subject", "patch", True, {"content": {"email": {"subject": "", "html": "<p>Hi</p>"}}}),+ ]+ )+ def test_email_content_without_subject_fails(self, _name, method, detail, body):+ url = f"/api/environments/{self.team.id}/messaging_templates/"+ if detail:+ url += f"{self.message_template.id}/"++ response = getattr(self.client, method)(url, data=body, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()@patch("products.messaging.backend.presentation.views.message_templates.report_user_action")def test_create_email_template_with_subject_succeeds(self, mock_report):diff --git a/products/messaging/backend/tests/api/test_transactional_email.py b/products/messaging/backend/tests/api/test_transactional_email.pyindex 7f6cf43cf933..69f3f78ecb77 100644--- a/products/messaging/backend/tests/api/test_transactional_email.py+++ b/products/messaging/backend/tests/api/test_transactional_email.py@@ -311,6 +311,7 @@ class TestTransactionalEmail(APIBaseTest):@patch("products.messaging.backend.services.transactional_email.reload_hog_flows_on_workers")def test_saving_a_transactional_template_writes_a_new_workflow_version(self, reload, mock_post, _flag, _capture):+ MessageTemplate.objects.filter(id=self.template.id).update(draft_content={"email": {"subject": "Draft"}})with self.captureOnCommitCallbacks(execute=True):response = self.client.patch(f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/",@@ -325,6 +326,22 @@ class TestTransactionalEmail(APIBaseTest):assert workflow["version"] == 2email = workflow["actions"][1]["config"]["inputs"]["email"]["value"]assert (email["subject"], email["html"]) == ("A new subject", "<p>New</p>")+ assert response.json()["draft_content"] is None++ def test_saving_a_draft_leaves_the_sent_email_unchanged(self, mock_post, _flag, _capture):+ # A draft is work in progress, so one the send path would reject still saves.+ draft = {"templating": "liquid", "email": {"subject": "", "html": "<p>Half written</p>"}}++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/",+ {"draft_content": draft},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["draft_content"]["email"] == draft["email"]+ assert response.json()["content"]["email"]["subject"] == "Reset your password"+ assert self._workflow(self.hog_flow_id)["version"] == 1@parameterized.expand([("marketing_category",), ("no_email_content",)])def test_a_template_whose_workflow_was_deleted_takes_edits_it_could_not_send_with(@@ -417,6 +434,7 @@ class TestTransactionalEmailWorkflowAccess(APIBaseTest):[("send", "post", "send/", {"to": "[email protected]"}),("update", "patch", "", {"content": {"email": {"subject": "New", "html": "<p>New</p>"}}}),+ ("save_draft", "patch", "", {"draft_content": {"email": {"subject": "Draft", "html": "<p>Draft</p>"}}}),])def test_a_member_denied_the_workflow_cannot_send_or_change_it(self, mock_post, _flag, _name, method, suffix, body):diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex 79ab7aa3efca..522d390a74cb 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -293,7 +293,7 @@ export type EmailTemplateApiDesign = {}export interface EmailTemplateApi {- /** Email subject line. Supports Liquid templating. Required for email-type templates. */+ /** Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published. */subject?: string/** Plain-text fallback body for clients that can't render the email. */text?: string@@ -400,6 +400,8 @@ export interface MessageTemplateApi {* @nullable*/readonly transactional_hog_flow_id: string | null+ /** Unpublished edits to a transactional template's content. Sends keep using `content`. Saving `content` publishes it and clears the draft. Set null to discard the draft. */+ draft_content?: MessageTemplateContentApi | null}export interface PaginatedMessageTemplateListApi {@@ -442,6 +444,8 @@ export interface PatchedMessageTemplateApi {* @nullable*/readonly transactional_hog_flow_id?: string | null+ /** Unpublished edits to a transactional template's content. Sends keep using `content`. Saving `content` publishes it and clears the draft. Set null to discard the draft. */+ draft_content?: MessageTemplateContentApi | null}/**diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.tsindex 9957e6349bc4..3ed7cfe4dc5a 100644--- a/products/messaging/frontend/generated/api.zod.ts+++ b/products/messaging/frontend/generated/api.zod.ts@@ -256,6 +256,8 @@ export const messagingTemplatesCreateBodyNameMax = 400export const messagingTemplatesCreateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesCreateBodyTypeMax = 24+export const messagingTemplatesCreateBodyDraftContentOneTemplatingDefault = `liquid`+export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -278,7 +280,7 @@ export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({.string().optional().describe(- 'Email subject line. Supports Liquid templating. Required for email-type templates.'+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'),text: zod.string()@@ -338,6 +340,77 @@ export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({.nullish().describe('Message category ID to file the template under. Must belong to the same project.'),deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),+ draft_content: zod+ .union([+ zod.object({+ templating: zod+ .enum(['liquid'])+ .describe('\* `liquid` - liquid')+ .default(messagingTemplatesCreateBodyDraftContentOneTemplatingDefault)+ .describe(+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n\* `liquid` - liquid"+ ),+ email: zod+ .union([+ zod.object({+ subject: zod+ .string()+ .optional()+ .describe(+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'+ ),+ text: zod+ .string()+ .optional()+ .describe("Plain-text fallback body for clients that can't render the email."),+ html: zod+ .string()+ .optional()+ .describe(+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."+ ),+ design: zod+ .object({+ counters: zod+ .looseObject({})+ .optional()+ .describe(+ 'Highest htmlID suffix per element type, e.g. {\"u_row\": 1, \"u_content_text\": 2}.'+ ),+ schemaVersion: zod.number().describe('Design schema version, e.g. 16.'),+ body: zod.object({+ id: zod.string().optional().describe('Any unique string.'),+ rows: zod+ .array(zod.looseObject({}))+ .describe(+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'+ ),+ headers: zod.array(zod.looseObject({})).optional(),+ footers: zod.array(zod.looseObject({})).optional(),+ values: zod+ .looseObject({})+ .optional()+ .describe(+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."+ ),+ }),+ })+ .optional()+ .describe(+ "Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill."+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ "Unpublished edits to a transactional template's content. Sends keep using `content`. Saving `content` publishes it and clears the draft. Set null to discard the draft."+ ),})export const messagingTemplatesUpdateBodyNameMax = 400@@ -345,6 +418,8 @@ export const messagingTemplatesUpdateBodyNameMax = 400export const messagingTemplatesUpdateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesUpdateBodyTypeMax = 24+export const messagingTemplatesUpdateBodyDraftContentOneTemplatingDefault = `liquid`+export const MessagingTemplatesUpdateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -367,7 +442,7 @@ export const MessagingTemplatesUpdateBody = /* @__PURE__ */ zod.object({.string().optional().describe(- 'Email subject line. Supports Liquid templating. Required for email-type templates.'+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'),text: zod.string()@@ -427,6 +502,77 @@ export const MessagingTemplatesUpdateBody = /* @__PURE__ */ zod.object({.nullish().describe('Message category ID to file the template under. Must belong to the same project.'),deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),+ draft_content: zod+ .union([+ zod.object({+ templating: zod+ .enum(['liquid'])+ .describe('\* `liquid` - liquid')+ .default(messagingTemplatesUpdateBodyDraftContentOneTemplatingDefault)+ .describe(+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n\* `liquid` - liquid"+ ),+ email: zod+ .union([+ zod.object({+ subject: zod+ .string()+ .optional()+ .describe(+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'+ ),+ text: zod+ .string()+ .optional()+ .describe("Plain-text fallback body for clients that can't render the email."),+ html: zod+ .string()+ .optional()+ .describe(+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."+ ),+ design: zod+ .object({+ counters: zod+ .looseObject({})+ .optional()+ .describe(+ 'Highest htmlID suffix per element type, e.g. {\"u_row\": 1, \"u_content_text\": 2}.'+ ),+ schemaVersion: zod.number().describe('Design schema version, e.g. 16.'),+ body: zod.object({+ id: zod.string().optional().describe('Any unique string.'),+ rows: zod+ .array(zod.looseObject({}))+ .describe(+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'+ ),+ headers: zod.array(zod.looseObject({})).optional(),+ footers: zod.array(zod.looseObject({})).optional(),+ values: zod+ .looseObject({})+ .optional()+ .describe(+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."+ ),+ }),+ })+ .optional()+ .describe(+ "Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill."+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ "Unpublished edits to a transactional template's content. Sends keep using `content`. Saving `content` publishes it and clears the draft. Set null to discard the draft."+ ),})export const messagingTemplatesPartialUpdateBodyNameMax = 400@@ -434,6 +580,8 @@ export const messagingTemplatesPartialUpdateBodyNameMax = 400export const messagingTemplatesPartialUpdateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesPartialUpdateBodyTypeMax = 24+export const messagingTemplatesPartialUpdateBodyDraftContentOneTemplatingDefault = `liquid`+export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.string()@@ -457,7 +605,7 @@ export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({.string().optional().describe(- 'Email subject line. Supports Liquid templating. Required for email-type templates.'+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'),text: zod.string()@@ -517,6 +665,77 @@ export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({.nullish().describe('Message category ID to file the template under. Must belong to the same project.'),deleted: zod.boolean().optional().describe('Soft-delete flag. Set true to remove the template from the library.'),+ draft_content: zod+ .union([+ zod.object({+ templating: zod+ .enum(['liquid'])+ .describe('\* `liquid` - liquid')+ .default(messagingTemplatesPartialUpdateBodyDraftContentOneTemplatingDefault)+ .describe(+ "Templating language for the email content. Always 'liquid' — Liquid tags pass through verbatim.\n\n\* `liquid` - liquid"+ ),+ email: zod+ .union([+ zod.object({+ subject: zod+ .string()+ .optional()+ .describe(+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'+ ),+ text: zod+ .string()+ .optional()+ .describe("Plain-text fallback body for clients that can't render the email."),+ html: zod+ .string()+ .optional()+ .describe(+ "Rendered email body — derived from the design at save time. The visual editor's save path supplies it directly; omit it otherwise."+ ),+ design: zod+ .object({+ counters: zod+ .looseObject({})+ .optional()+ .describe(+ 'Highest htmlID suffix per element type, e.g. {\"u_row\": 1, \"u_content_text\": 2}.'+ ),+ schemaVersion: zod.number().describe('Design schema version, e.g. 16.'),+ body: zod.object({+ id: zod.string().optional().describe('Any unique string.'),+ rows: zod+ .array(zod.looseObject({}))+ .describe(+ 'Rows of {id, cells, columns[{id, contents[{id, type, values}], values}], values}.'+ ),+ headers: zod.array(zod.looseObject({})).optional(),+ footers: zod.array(zod.looseObject({})).optional(),+ values: zod+ .looseObject({})+ .optional()+ .describe(+ "Body-level settings: backgroundColor, contentWidth ('600px'), fontFamily, textColor."+ ),+ }),+ })+ .optional()+ .describe(+ "Design JSON for PostHog's visual email editor — the authoring surface and source of truth. The server renders the sent email from it, and it opens as editable blocks in the editor. Full schema in the designing-email-templates skill."+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Email message content. Replaced as a whole on update — send the complete object.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ "Unpublished edits to a transactional template's content. Sends keep using `content`. Saving `content` publishes it and clears the draft. Set null to discard the draft."+ ),})export const MessagingTemplatesDesignPartialUpdateBody = /* @__PURE__ */ zod.object({diff --git a/products/workflows/frontend/TemplateLibrary/MakeTransactionalPrompt.tsx b/products/workflows/frontend/TemplateLibrary/MakeTransactionalPrompt.tsxindex 02d739e89ca6..94c014a42813 100644--- a/products/workflows/frontend/TemplateLibrary/MakeTransactionalPrompt.tsx+++ b/products/workflows/frontend/TemplateLibrary/MakeTransactionalPrompt.tsx@@ -30,7 +30,9 @@ export function MakeTransactionalPrompt(props: MessageTemplateSceneLogicProps):</div><ul className="list-disc pl-6 mb-0 flex flex-col gap-1"><li>Each send shows up here under Metrics and Sends, and on the recipient's person.</li>- <li>Saving the template updates the live email straight away. Every save keeps a version.</li>+ <li>+ Your edits save as a draft. Publishing updates the live email, and each publish keeps a version.+ </li><li>Transactional emails ignore marketing opt-outs, so don't use them for marketing.</li></ul><div>diff --git a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsxindex 9b2d9147420e..dc32b6063e62 100644--- a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx+++ b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx@@ -1,7 +1,17 @@import { BindLogic, useActions, useValues } from 'kea'import { Form } from 'kea-forms'-import { LemonBanner, LemonButton, LemonDivider, LemonTag, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'+import { IconTrash } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonDivider,+ LemonMenuOverlay,+ LemonTag,+ Spinner,+ SpinnerOverlay,+ Tooltip,+} from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { More } from 'lib/lemon-ui/LemonButton/More'@@ -54,6 +64,7 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemsyncExternalEdit,keepMyTemplateVersion,setTransactionalTab,+ discardDraft,} = useActions(logic)const {template,@@ -67,6 +78,11 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemisSyncingExternalEdit,transactionalHogFlowId,transactionalTab,+ draftsEnabled,+ hasDraft,+ hasUnsavedChanges,+ isSavingDraft,+ isDiscardingDraft,} = useValues(logic)const transactionalEmailsEnabled = useFeatureFlag('WORKFLOWS_TRANSACTIONAL_EMAIL_API')const showTransactional = transactionalEmailsEnabled && props.id !== 'new'@@ -180,9 +196,22 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemonDescriptionChange={(description) => setTemplateValue('description', description)}nameSuffix={showTransactional && transactionalHogFlowId ? (- <LemonTag type="success" className="ml-1">- Transactional- </LemonTag>+ <>+ <LemonTag type="success" className="ml-1">+ Transactional+ </LemonTag>+ {(hasDraft || hasUnsavedChanges) && (+ <Tooltip title="Your changes save as a draft. Sends use the live version until you publish.">+ <LemonTag+ type="warning"+ className="ml-1"+ data-attr="message-template-draft-tag"+ >+ {isSavingDraft ? 'Saving draft…' : 'Editing draft'}+ </LemonTag>+ </Tooltip>+ )}+ </>) : undefined}actions={@@ -197,7 +226,7 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem>Send test</LemonButton>- {templateChanged && (+ {templateChanged && !draftsEnabled && (<LemonButtondata-attr="cancel-message-template"type="secondary"@@ -214,15 +243,48 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemonClick={submitTemplate}loading={isTemplateSubmitting || templateLoading}disabledReason={- !templateChanged && props.id !== 'new'- ? 'No changes to save'- : !template.name- ? 'Name is required'- : undefined+ draftsEnabled && isSavingDraft+ ? 'Saving your draft'+ : draftsEnabled && !hasDraft && !hasUnsavedChanges+ ? 'No changes to publish'+ : !draftsEnabled && !templateChanged && props.id !== 'new'+ ? 'No changes to save'+ : !template.name+ ? 'Name is required'+ : undefined}size="small"+ sideAction={+ draftsEnabled+ ? {+ 'data-attr': 'message-template-draft-actions',+ 'aria-label': 'More draft actions',+ dropdown: {+ placement: 'bottom-end',+ overlay: (+ <LemonMenuOverlay+ items={[+ {+ label: 'Discard draft',+ icon: <IconTrash />,+ status: 'danger',+ onClick: discardDraft,+ disabledReason: !hasDraft+ ? 'There is no draft to discard'+ : isSavingDraft || isDiscardingDraft+ ? 'Wait for the draft to finish saving'+ : undefined,+ 'data-attr': 'message-template-discard-draft',+ },+ ]}+ />+ ),+ },+ }+ : undefined+ }>- {props.id === 'new' ? 'Create' : 'Save'}+ {props.id === 'new' ? 'Create' : draftsEnabled ? 'Publish' : 'Save'}</LemonButton><Moresize="small"@@ -242,7 +304,7 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemfullWidthonClick={duplicateTemplate}disabledReason={- templateChanged+ hasUnsavedChanges? 'Save your changes before duplicating': undefined}diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.tsindex 789f407f9c22..5a5aef1b91cd 100644--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts@@ -331,6 +331,91 @@ describe('messageTemplateLogic', () => {})})+ describe('transactional drafts', () => {+ const live = { templating: 'liquid', email: { subject: 'Live subject', html: '<p>Live</p>' } }+ const draft = { templating: 'liquid', email: { subject: 'Draft subject', html: '<p>Draft</p>' } }+ const serverTemplate = {+ id: 'existing-id',+ name: 'Existing',+ content: live,+ draft_content: draft,+ transactional_hog_flow_id: 'flow-id',+ updated_at: '2026-01-01T00:00:00Z',+ }+ let bodies: Record<string, unknown>[]++ beforeEach(async () => {+ bodies = []+ const patch = async ({ request }: { request: Request }): Promise<[number, Record<string, unknown>]> => {+ const body = (await request.json()) as Record<string, unknown>+ bodies.push(body)+ // Saving the content publishes it and the server clears the draft.+ return [+ 200,+ 'content' in body+ ? { ...serverTemplate, ...body, draft_content: null }+ : { ...serverTemplate, ...body, updated_at: '2026-01-01T00:01:00Z' },+ ]+ }+ useMocks({+ get: { '/api/environments/:team_id/messaging_templates/:id/': serverTemplate },+ patch: {+ '/api/environments/:team_id/messaging_templates/:id/': patch,+ '/api/projects/:team_id/messaging_templates/:id/': patch,+ },+ })+ logic = messageTemplateLogic({ id: 'existing-id' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadTemplateSuccess'])+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('edits the draft and saves edits to it without touching the live content', async () => {+ expect(logic.values.template.content).toEqual(draft)+ jest.useFakeTimers()+ const edited = { ...draft, email: { ...draft.email, subject: 'Edited subject' } }++ logic.actions.setTemplateValue('content', edited)+ await jest.advanceTimersByTimeAsync(1500)+ await expectLogic(logic).toDispatchActions(['saveDraftDone']).toMatchValues({+ hasDraft: true,+ hasUnsavedChanges: false,+ })++ expect(bodies).toEqual([{ draft_content: edited }])+ })++ it('holds autosave while an edit from elsewhere is unresolved, then saves once the person keeps theirs', async () => {+ jest.useFakeTimers()+ const edited = { ...draft, email: { ...draft.email, subject: 'Edited subject' } }++ logic.actions.setExternallyEdited(true)+ logic.actions.setTemplateValue('content', edited)+ await jest.advanceTimersByTimeAsync(3000)+ expect(bodies).toEqual([])++ logic.actions.keepMyTemplateVersion()+ await jest.advanceTimersByTimeAsync(1500)+ await expectLogic(logic).toDispatchActions(['saveDraftDone'])+ expect(bodies).toEqual([{ draft_content: edited }])+ })++ it('publishing sends the content and leaves no draft behind', async () => {+ await expectLogic(logic, () => {+ logic.actions.submitTemplate()+ })+ .toDispatchActions(['saveTemplateSuccess'])+ .toMatchValues({ hasDraft: false, hasUnsavedChanges: false })++ expect(bodies).toHaveLength(1)+ expect(bodies[0].content).toEqual(draft)+ expect(bodies[0]).not.toHaveProperty('draft_content')+ })+ })+describe('make transactional', () => {it('keeps edits made while the conversion runs', async () => {useMocks({diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.tsindex d3520d761dd9..900ad72d28a4 100644--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts@@ -4,15 +4,22 @@ import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } fromimport { loaders } from 'kea-loaders'import { beforeUnload, router, urlToAction } from 'kea-router'+import { LemonDialog } from '@posthog/lemon-ui'+import api from 'lib/api'import { dayjs } from 'lib/dayjs'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 } from 'products/messaging/frontend/generated/api'+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 type { EmailTemplate } from '../../../../frontend/src/scenes/hog-functions/email-templater/types'@@ -24,6 +31,19 @@ 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: stringmessageId?: string | null@@ -34,8 +54,14 @@ export interface messageTemplateLogicValues {aiComposerAvailable: boolean // newTemplateAgentLogiccurrentTeamIdStrict: number | string // teamLogicdeferredExternalEdit: ResourceEditedEvent | null+ draftOutOfDate: boolean+ draftsEnabled: booleanexternallyEdited: boolean+ hasDraft: boolean+ hasUnsavedChanges: boolean+ isDiscardingDraft: booleanisMakingTransactional: boolean+ isSavingDraft: booleanisSyncingExternalEdit: booleanisTemplateSubmitting: booleanisTemplateValid: boolean@@ -43,6 +69,8 @@ export interface messageTemplateLogicValues {message: anymessageLoading: booleanoriginalTemplate: MessageTemplate+ publishedContent: TemplateContent | null+ savedDraft: TemplateContent | nullshowTemplateErrors: booleantemplate: MessageTemplatetemplateAllErrors: Record<string, any>@@ -56,6 +84,7 @@ export interface messageTemplateLogicValues {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -78,6 +107,7 @@ export interface messageTemplateLogicValues {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -94,9 +124,21 @@ 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}@@ -150,6 +192,7 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -163,12 +206,29 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}}+ saveDraft: () => {+ value: true+ }+ saveDraftDone: (+ draft: TemplateContent,+ updatedAt: string+ ) => {+ draft: {+ email: EmailTemplate+ templating: 'hog' | 'liquid'+ }+ updatedAt: string+ }+ saveDraftFailed: () => {+ value: true+ }saveTemplate: (template: any) => anysaveTemplateFailure: (error: string,@@ -187,6 +247,19 @@ export interface messageTemplateLogicActions {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}@@ -221,6 +294,7 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -235,6 +309,7 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -262,6 +337,7 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -275,6 +351,7 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -289,6 +366,7 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -302,6 +380,7 @@ export interface messageTemplateLogicActions {created_at: string | nullcreated_by: UserBasicType | nulldescription: string+ draft_content?: MessageTemplateContentApi | null | undefinedid: stringname: stringtransactional_hog_flow_id?: string | null | undefined@@ -325,6 +404,31 @@ export interface messageTemplateLogicMeta {__keaTypeGenInternalSelectorTypes: {logicProps: (arg: MessageTemplateLogicProps) => MessageTemplateLogicPropstransactionalHogFlowId: (originalTemplate: MessageTemplate) => string | null+ 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}}@@ -359,6 +463,14 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([makeTransactional: true,makeTransactionalDone: (hogFlowId: string | null) => ({ hogFlowId }),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: [@@ -407,6 +519,35 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([makeTransactionalDone: () => 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,{@@ -449,8 +590,51 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([(s) => [s.originalTemplate],(originalTemplate: MessageTemplate): string | null => originalTemplate.transactional_hog_flow_id ?? null,],+ // 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 }) => ({+ loaders(({ props, actions }) => ({template: {loadTemplate: async () => {if (!props.id || props.id === 'new') {@@ -459,13 +643,19 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([} as MessageTemplate}- return await api.messaging.getTemplate(props.id)+ const { form, draft, published } = splitDraft(await api.messaging.getTemplate(props.id))+ actions.setDraftState(draft, published)+ return form},- saveTemplate: (template) => {- if (template.id === 'new') {- return api.messaging.createTemplate(template)- }- return api.messaging.updateTemplate(template.id, template)+ saveTemplate: async (template) => {+ // Saving the content publishes it, and the server clears the draft.+ const saved =+ template.id === 'new'+ ? await api.messaging.createTemplate(template)+ : await api.messaging.updateTemplate(template.id, template)+ const { form, draft, published } = splitDraft(saved)+ actions.setDraftState(draft, published)+ return form},},message: {@@ -486,7 +676,12 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([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) {+ if (+ values.templateLoading ||+ values.isMakingTransactional ||+ values.isSavingDraft ||+ values.isDiscardingDraft+ ) {actions.setDeferredExternalEdit(event)return}@@ -494,7 +689,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([if (!loadedUpdatedAt || !dayjs(event.updated_at).isAfter(dayjs(loadedUpdatedAt))) {return}- if (values.templateChanged) {+ if (values.hasUnsavedChanges) {actions.setExternallyEdited(true)} else {actions.syncExternalEdit()@@ -513,6 +708,84 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([},keepMyTemplateVersion: () => {actions.setExternallyEdited(false)+ actions.autoSaveDraft()+ },+ setTemplateValue: () => actions.autoSaveDraft(),+ 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 {@@ -582,7 +855,9 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([lemonToast.error('Failed to save template. Please try again.')},saveTemplateSuccess: async ({ template }) => {- lemonToast.success(props.id === 'new' ? 'Template created' : 'Template saved')+ 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)@@ -611,7 +886,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([})},duplicateTemplate: async () => {- if (values.templateChanged) {+ if (values.hasUnsavedChanges) {lemonToast.error('Please save your changes before duplicating')return}@@ -677,7 +952,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([// 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.templateChanged) {+ if (!values.hasUnsavedChanges) {return false}// Allow same-path changes (e.g. query params) through without warning.diff --git a/products/workflows/frontend/TemplateLibrary/types.ts b/products/workflows/frontend/TemplateLibrary/types.tsindex 975f2c20c3d0..68af8ed5b4ce 100644--- a/products/workflows/frontend/TemplateLibrary/types.ts+++ b/products/workflows/frontend/TemplateLibrary/types.ts@@ -16,4 +16,5 @@ export interface MessageTemplate {updated_at: string | nullcreated_by: UserBasicType | nulltransactional_hog_flow_id?: MessageTemplateApi['transactional_hog_flow_id']+ draft_content?: MessageTemplateApi['draft_content']}diff --git a/products/workflows/mcp/email_templates.yaml b/products/workflows/mcp/email_templates.yamlindex 6d3b677a59a8..5fd4d6dfa705 100644--- a/products/workflows/mcp/email_templates.yaml+++ b/products/workflows/mcp/email_templates.yaml@@ -30,9 +30,11 @@ tools:user.exclude_params:- content.email.html+ - draft_contentresponse:exclude:- content+ - draft_content- created_byworkflows-get-email-template:operation: messaging_templates_retrieve@@ -54,6 +56,7 @@ tools:exclude:- content.email.html- created_by+ - draft_contentworkflows-list-email-templates:operation: messaging_templates_listenabled: true@@ -73,6 +76,7 @@ tools:exclude:- content- created_by+ - draft_contentworkflows-patch-email-template:operation: messaging_templates_design_partial_updateenabled: true@@ -100,6 +104,7 @@ tools:exclude:- content- created_by+ - draft_contentworkflows-show-email-template:operation: messaging_templates_retrieveenabled: true@@ -120,6 +125,7 @@ tools:exclude:- content.email.design- created_by+ - draft_contentworkflows-update-email-template:operation: messaging_templates_partial_updateenabled: true@@ -141,7 +147,9 @@ tools:the returned _posthogUrl edit link.exclude_params:- content.email.html+ - draft_contentresponse:exclude:- content+ - draft_content- created_bydiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4e630b940199..63fdcf8ce94c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -39474,7 +39474,7 @@ export namespace Schemas {};export interface EmailTemplate {- /** Email subject line. Supports Liquid templating. Required for email-type templates. */+ /** Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published. */subject?: string;/** Plain-text fallback body for clients that can't render the email. */text?: string;@@ -67568,6 +67568,8 @@ export namespace Schemas {* @nullable*/readonly transactional_hog_flow_id: string | null;+ /** Unpublished edits to a transactional template's content. Sends keep using `content`. Saving `content` publishes it and clears the draft. Set null to discard the draft. */+ draft_content?: MessageTemplateContent | null;}export interface MessagingError {@@ -83537,6 +83539,8 @@ export namespace Schemas {* @nullable*/readonly transactional_hog_flow_id?: string | null;+ /** Unpublished edits to a transactional template's content. Sends keep using `content`. Saving `content` publishes it and clears the draft. Set null to discard the draft. */+ draft_content?: MessageTemplateContent | null;}export interface PatchedMoveTileRequest {diff --git a/services/mcp/src/generated/email_templates/api.ts b/services/mcp/src/generated/email_templates/api.tsindex 8155c6614b53..7a6f0e22cce9 100644--- a/services/mcp/src/generated/email_templates/api.ts+++ b/services/mcp/src/generated/email_templates/api.ts@@ -56,7 +56,7 @@ export const MessagingTemplatesCreateBody = () => zod.object({.string().optional().describe(- 'Email subject line. Supports Liquid templating. Required for email-type templates.'+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'),text: zod.string()@@ -158,7 +158,7 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({.string().optional().describe(- 'Email subject line. Supports Liquid templating. Required for email-type templates.'+ 'Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.'),text: zod.string()diff --git a/services/mcp/src/tools/generated/email_templates.ts b/services/mcp/src/tools/generated/email_templates.tsindex 5f29e7ff3a41..7a39142642a4 100644--- a/services/mcp/src/tools/generated/email_templates.ts+++ b/services/mcp/src/tools/generated/email_templates.ts@@ -45,7 +45,7 @@ const workflowsCreateEmailTemplate = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/`,body,})- const filtered = omitResponseFields(result, ['content', 'created_by']) as typeof result+ const filtered = omitResponseFields(result, ['content', 'draft_content', 'created_by']) as typeof resultreturn await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)},})@@ -67,7 +67,11 @@ const workflowsGetEmailTemplate = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(params.id))}/`,})- const filtered = omitResponseFields(result, ['content.email.html', 'created_by']) as typeof result+ const filtered = omitResponseFields(result, [+ 'content.email.html',+ 'created_by',+ 'draft_content',+ ]) as typeof resultreturn await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)},})@@ -95,7 +99,9 @@ const workflowsListEmailTemplates = (): ToolBase<})const filtered = {...result,- results: (result.results ?? []).map((item: any) => omitResponseFields(item, ['content', 'created_by'])),+ results: (result.results ?? []).map((item: any) =>+ omitResponseFields(item, ['content', 'created_by', 'draft_content'])+ ),} as typeof resultreturn await withPostHogUrl(context,@@ -129,7 +135,7 @@ const workflowsPatchEmailTemplate = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(id))}/design/`,body,})- const filtered = omitResponseFields(result, ['content', 'created_by']) as typeof result+ const filtered = omitResponseFields(result, ['content', 'created_by', 'draft_content']) as typeof resultreturn await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)},})@@ -152,7 +158,11 @@ const workflowsShowEmailTemplate = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(params.id))}/`,})- const filtered = omitResponseFields(result, ['content.email.design', 'created_by']) as typeof result+ const filtered = omitResponseFields(result, [+ 'content.email.design',+ 'created_by',+ 'draft_content',+ ]) as typeof resultreturn await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)},})@@ -197,7 +207,7 @@ const workflowsUpdateEmailTemplate = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/messaging_templates/${encodeURIComponent(String(params.id))}/`,body,})- const filtered = omitResponseFields(result, ['content', 'created_by']) as typeof result+ const filtered = omitResponseFields(result, ['content', 'draft_content', 'created_by']) as typeof resultreturn await withPostHogUrl(context, filtered, `/workflows/library/templates/${filtered.id}`)},})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.jsonindex dbd860a6fac9..1ba7d6a4ac98 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json@@ -67,7 +67,7 @@"type": "object"},"subject": {- "description": "Email subject line. Supports Liquid templating. Required for email-type templates.",+ "description": "Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.","type": "string"},"text": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.jsonindex 91d43313d24e..83ba50b4ca0c 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json@@ -67,7 +67,7 @@"type": "object"},"subject": {- "description": "Email subject line. Supports Liquid templating. Required for email-type templates.",+ "description": "Email subject line. Supports Liquid templating. Required in `content` for email-type templates. A `draft_content` may leave it blank until it is published.","type": "string"},"text": {