Skip to content

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

feat(workflows): auto-wrap html-only emails into an editable design (#78876)

Harley Alexander42286aaf3ec5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 469b5b87530a..c5d3ef9a3de5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6265,7 +6265,7 @@ snapshots:
scenes-app-inbox-scene--self-driving-paused--dark:
hash: v1.k794b7964.bd2bee28eee6668bfd9f1e5c00191e38189bc27ac734c8adf8ddc55da8381b1b.HFfADdkZDnQv2BGCHc-yzXZ4Z0Rpk-xn9cn7uRUXIyg
scenes-app-inbox-scene--self-driving-paused--light:
- hash: v1.k794b7964.4af393b7f3b9cdb056c518fe5cfcc7c99e4503ad008af2b031867e6811560083.dF3I6JAteRnokBIPAdvOuUT0Gf6MwR1rhRHygDUW2V0
+ hash: v1.k794b7964.5f8c26b5f2a35d63e9e3817ee3c8923ca19d249bef13d8e78196f3a544d5451d.iDetyRF2JiZuSAhHnuuzMdBenEEdjTxlgKUbmQ-bmSk
scenes-app-inbox-tabs--pull-requests--dark:
hash: v1.k794b7964.474d8e744637e08afd4bb7540f0f5dafd6a79342c2f547188cb436b55f9ef8e7.PiyD1Zkhkot-_DKLU3W0T5uA7rvpTUTn5bKChCa3AV4
scenes-app-inbox-tabs--pull-requests--light:
diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
index f4f87b9fe426..edbc3b38a6b2 100644
--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.test.ts
@@ -170,6 +170,97 @@ describe('emailTemplaterLogic', () => {
})
})
+ describe('html-only emails', () => {
+ it('loads a design wrapping the html so the canvas shows the email instead of starting blank', () => {
+ const loadDesign = jest.fn()
+ logic = emailTemplaterLogic(
+ makeProps({ value: { ...DEFAULT_EMAIL_TEMPLATE, design: null, html: '<p>raw</p>' } })
+ )
+ logic.mount()
+ logic.actions.setEmailEditorRef({
+ editor: { loadDesign, addEventListener: jest.fn() },
+ } as unknown as EditorRef)
+ logic.actions.onEmailEditorReady()
+
+ expect(loadDesign).toHaveBeenCalledTimes(1)
+ const design = loadDesign.mock.calls[0][0]
+ expect(design.body.rows[0].columns[0].contents[0]).toMatchObject({
+ type: 'html',
+ values: { html: '<p>raw</p>' },
+ })
+ })
+
+ it('does not load anything when there is neither design nor html', () => {
+ const loadDesign = jest.fn()
+ logic = emailTemplaterLogic(makeProps({ value: { ...DEFAULT_EMAIL_TEMPLATE, design: null, html: '' } }))
+ logic.mount()
+ logic.actions.setEmailEditorRef({
+ editor: { loadDesign, addEventListener: jest.fn() },
+ } as unknown as EditorRef)
+ logic.actions.onEmailEditorReady()
+
+ expect(loadDesign).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('modal save', () => {
+ let onChange: jest.Mock
+ let editorListeners: Record<string, () => void>
+ let editorDesign: Record<string, any>
+
+ const DESIGN_NORMALIZED = { body: { id: 'normalized', rows: [{ id: 'r1' }] } }
+ const DESIGN_EDITED = { body: { id: 'edited', rows: [{ id: 'r2' }] } }
+
+ const fakeEditorRef = (): EditorRef =>
+ ({
+ editor: {
+ loadDesign: jest.fn(),
+ addEventListener: (event: string, callback: () => void) => {
+ editorListeners[event] = callback
+ },
+ exportHtml: (callback: (data: any) => void) =>
+ callback({ html: '<p>edited</p>', design: editorDesign }),
+ exportPlainText: (callback: (data: any) => void) => callback({ text: 'edited' }),
+ },
+ }) as unknown as EditorRef
+
+ beforeEach(async () => {
+ onChange = jest.fn()
+ editorListeners = {}
+ editorDesign = DESIGN_NORMALIZED
+ logic = emailTemplaterLogic(
+ makeProps({ value: { ...DEFAULT_EMAIL_TEMPLATE, design: null, html: '<p>raw</p>' }, onChange })
+ )
+ logic.mount()
+ logic.actions.setEmailEditorRef(fakeEditorRef())
+ logic.actions.onEmailEditorReady()
+ // The load echo rebaselines to the editor's normalized export
+ editorListeners['design:loaded']?.()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('a save without canvas edits keeps the stored html instead of the editor re-render', async () => {
+ logic.actions.submitEmailTemplate()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0][0]).toMatchObject({ html: '<p>raw</p>' })
+ })
+
+ it('a save after a canvas edit persists the editor export', async () => {
+ editorDesign = DESIGN_EDITED
+ logic.actions.submitEmailTemplate()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(onChange).toHaveBeenCalledTimes(1)
+ expect(onChange.mock.calls[0][0]).toMatchObject({
+ html: '<p>edited</p>',
+ text: 'edited',
+ design: DESIGN_EDITED,
+ })
+ })
+ })
+
describe('inline layout live propagation', () => {
let onChange: jest.Mock
let loadDesign: jest.Mock
diff --git a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
index 4d05643005bd..fbe4b386c03b 100644
--- a/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
+++ b/frontend/src/scenes/hog-functions/email-templater/emailTemplaterLogic.tsx
@@ -101,6 +101,50 @@ export interface EditorRef extends _EditorRef {}
type JSONTemplate = Parameters<Editor['loadDesign']>[0]
+/**
+ * Wrap raw html in an Unlayer design holding a single custom HTML block. Emails authored
+ * programmatically (API/MCP) often have html but no design; loading a wrapped design shows the
+ * email in the canvas instead of a blank editor whose save would clobber the stored html.
+ * Mirrors build_html_wrap_design in posthog/cdp/validation.py.
+ */
+export function buildHtmlWrapDesign(html: string): JSONTemplate {
+ // Fixed ids keep the wrap deterministic: re-wrapping the same html yields an identical
+ // design, so backend content-equality checks (revisions, draft diffing) see no change.
+ return {
+ counters: { u_row: 1, u_column: 1, u_content_html: 1 },
+ schemaVersion: 16,
+ body: {
+ id: 'html-wrap-body',
+ headers: [],
+ footers: [],
+ rows: [
+ {
+ id: 'html-wrap-row',
+ cells: [1],
+ columns: [
+ {
+ id: 'html-wrap-column',
+ contents: [
+ {
+ id: 'html-wrap-content',
+ type: 'html',
+ values: {
+ html,
+ _meta: { htmlID: 'u_content_html_1', htmlClassNames: 'u_content_html' },
+ },
+ },
+ ],
+ values: { _meta: { htmlID: 'u_column_1', htmlClassNames: 'u_column' } },
+ },
+ ],
+ values: { _meta: { htmlID: 'u_row_1', htmlClassNames: 'u_row' } },
+ },
+ ],
+ values: {},
+ },
+ } as unknown as JSONTemplate
+}
+
export interface EmailTemplaterLogicProps {
value: EmailTemplate | null
onChange: (value: EmailTemplate) => void
@@ -497,6 +541,16 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
new Promise<any>((res) => editor.exportPlainText(res)),
])
+ // A save with no canvas edits keeps the stored html/text/design byte-identical
+ // instead of replacing them with the editor's re-render - the export wraps raw
+ // html emails in Unlayer chrome, so an unconditional overwrite would silently
+ // change what recipients receive on a no-op save. Meta field edits still apply.
+ if (objectsEqual(htmlData.design, cache.lastEditorDesign)) {
+ props.onChange({ ...formValues })
+ actions.setIsModalOpen(false)
+ return
+ }
+
const finalValues: EmailTemplate = {
...formValues,
html: ['native_email', 'native_email_template'].includes(props.type)
@@ -519,11 +573,17 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
// rebaselines - otherwise the load echo is indistinguishable from a user edit.
if (props.layout === 'inline') {
values.emailEditorRef?.editor?.addEventListener('design:updated', () => actions.designUpdated())
- values.emailEditorRef?.editor?.addEventListener('design:loaded', () => actions.designLoaded())
}
+ // Both layouts rebaseline on load: the modal submit compares its export against the
+ // baseline to tell a no-op save from a real edit.
+ values.emailEditorRef?.editor?.addEventListener('design:loaded', () => actions.designLoaded())
if (props.value?.design) {
cache.lastEditorDesign = props.value.design
values.emailEditorRef?.editor?.loadDesign(props.value.design)
+ } else if (props.value?.html) {
+ const wrapped = buildHtmlWrapDesign(props.value.html)
+ cache.lastEditorDesign = wrapped
+ values.emailEditorRef?.editor?.loadDesign(wrapped)
}
},
@@ -532,7 +592,7 @@ export const emailTemplaterLogic = kea<emailTemplaterLogicType>([
// (defaults, ids), so comparing raw stored designs against later exports would flag
// every load echo as an edit and falsely dirty the parent form.
const editor = values.emailEditorRef?.editor
- if (!editor || props.layout !== 'inline') {
+ if (!editor) {
return
}
const htmlData: { design: JSONTemplate } = await new Promise<any>((res) => editor.exportHtml(res))
diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.py
index 68859bfa65f4..3f7987b0b8cd 100644
--- a/posthog/cdp/test/test_validation.py
+++ b/posthog/cdp/test/test_validation.py
@@ -17,6 +17,8 @@ from posthog.cdp.validation import (
generate_template_bytecode,
)
+from products.messaging.backend.api.design_validation import validate_design
+
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
@@ -412,6 +414,60 @@ class TestHogFunctionValidation(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
validated = validate_inputs(inputs_schema, inputs)
assert validated["field"]["value"] == "Hey {{ person.properties.name }}"
+ @parameterized.expand([("email",), ("native_email",)])
+ def test_html_only_email_value_gets_design_wrapping_the_html(self, item_type):
+ inputs_schema = [{"key": "email", "type": item_type, "required": True, "templating": "liquid"}]
+ html = "<html><body><p>Hello</p></body></html>"
+ value = {"from": "[email protected]", "to": "[email protected]", "subject": "hi", "html": html, "text": "Hello"}
+
+ validated = validate_inputs(inputs_schema, {"email": {"value": value}})
+
+ result = validated["email"]["value"]
+ assert result["html"] == html
+ contents = result["design"]["body"]["rows"][0]["columns"][0]["contents"]
+ assert len(contents) == 1
+ assert contents[0]["type"] == "html"
+ assert contents[0]["values"]["html"] == html
+ assert validate_design(result["design"]) == []
+
+ @parameterized.expand(
+ [
+ (
+ "existing_design_untouched",
+ {
+ "from": "[email protected]",
+ "subject": "hi",
+ "html": "<p>hi</p>",
+ "design": {"body": {"rows": []}},
+ },
+ {"body": {"rows": []}},
+ ),
+ (
+ "text_only_email_gets_no_design",
+ {"from": "[email protected]", "to": "[email protected]", "subject": "hi", "text": "hi"},
+ None,
+ ),
+ ]
+ )
+ def test_email_value_wrap_no_ops(self, _name, value, expected_design):
+ inputs_schema = [{"key": "email", "type": "native_email", "required": True, "templating": "liquid"}]
+
+ validated = validate_inputs(inputs_schema, {"email": {"value": value}})
+
+ assert validated["email"]["value"].get("design") == expected_design
+
+ def test_html_only_email_wrap_is_deterministic(self):
+ # Callers resend the same html-only value on every save; a fresh design each time would
+ # register as a content change in revision and draft-diff equality checks.
+ inputs_schema = [{"key": "email", "type": "native_email", "required": True, "templating": "liquid"}]
+ value = {"from": "[email protected]", "to": "[email protected]", "subject": "hi", "html": "<p>Hello</p>"}
+
+ first = validate_inputs(inputs_schema, {"email": {"value": dict(value)}})["email"]["value"]["design"]
+ second = validate_inputs(inputs_schema, {"email": {"value": dict(value)}})["email"]["value"]["design"]
+
+ assert first == second
+
@parameterized.expand(
[
(
diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.py
index 96d3864e792b..472a6392e9dd 100644
--- a/posthog/cdp/validation.py
+++ b/posthog/cdp/validation.py
@@ -32,6 +32,54 @@ CORE_SUPPORTED_FUNCTIONS = {"fetch", "postHogCapture"}
PRODUCT_ASYNC_FUNCTIONS: set[str] = set()
+def build_html_wrap_design(html: str) -> dict:
+ """Build an Unlayer design holding the given html in a single custom HTML block.
+
+ Emails authored programmatically (API/MCP) often carry html without a design, which the
+ visual editor cannot open. Wrapping the html keeps the stored html byte-identical (sends
+ don't change) while giving the editor a design to load. _meta numbering mirrors what the
+ Unlayer editor emits so id-addressed design operations keep working. Ids are fixed so the
+ wrap is deterministic: callers that resend the same html-only value on every save would
+ otherwise produce a fresh design each time, and the content-equality checks behind
+ workflow revisions and hog function draft diffing would register a change on every no-op
+ resave.
+ """
+
+ return {
+ "counters": {"u_row": 1, "u_column": 1, "u_content_html": 1},
+ "schemaVersion": 16,
+ "body": {
+ "id": "html-wrap-body",
+ "headers": [],
+ "footers": [],
+ "rows": [
+ {
+ "id": "html-wrap-row",
+ "cells": [1],
+ "columns": [
+ {
+ "id": "html-wrap-column",
+ "contents": [
+ {
+ "id": "html-wrap-content",
+ "type": "html",
+ "values": {
+ "html": html,
+ "_meta": {"htmlID": "u_content_html_1", "htmlClassNames": "u_content_html"},
+ },
+ }
+ ],
+ "values": {"_meta": {"htmlID": "u_column_1", "htmlClassNames": "u_column"}},
+ }
+ ],
+ "values": {"_meta": {"htmlID": "u_row_1", "htmlClassNames": "u_row"}},
+ }
+ ],
+ "values": {},
+ },
+ }
+
+
def register_supported_function(name: str) -> None:
PRODUCT_ASYNC_FUNCTIONS.add(name)
@@ -421,6 +469,12 @@ class InputsItemSerializer(serializers.Serializer):
if missing:
label = "value" if len(missing) == 1 else "values"
raise serializers.ValidationError({"input": f"Missing {label} for {', '.join(missing)}."})
+
+ if isinstance(value.get("html"), str) and value["html"] and not value.get("design"):
+ # Programmatically authored emails often supply html without a design, which the
+ # visual editor can't open. Wrap it so every stored email has an editable design.
+ value = {**value, "design": build_html_wrap_design(value["html"])}
+ attrs["value"] = value
elif item_type == "non_failure_status_codes":
if not isinstance(value, list):
raise serializers.ValidationError({"input": "Value must be a list of status codes."})
diff --git a/products/messaging/backend/api/message_templates.py b/products/messaging/backend/api/message_templates.py
index 4deb59ca1a0f..7eb8b2bccce7 100644
--- a/products/messaging/backend/api/message_templates.py
+++ b/products/messaging/backend/api/message_templates.py
@@ -15,6 +15,7 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
+from posthog.cdp.validation import build_html_wrap_design
from products.messaging.backend.api.design_operations import apply_design_operations
from products.messaging.backend.api.design_validation import validate_design
@@ -142,6 +143,11 @@ class MessageTemplateSerializer(serializers.ModelSerializer):
raise serializers.ValidationError(
{"content": {"email": {"subject": "Subject is required for email templates."}}}
)
+ # Programmatically authored templates often supply html without a design, which the
+ # visual editor can't open. Wrap the html in a single custom HTML block; the stored
+ # html stays untouched, so nothing about the sent email changes.
+ if email and email.get("html") and not email.get("design"):
+ email["design"] = build_html_wrap_design(email["html"])
# Design-only saves get their html rendered server-side (the send path uses html
# verbatim). A submitted html is trusted as-is — that's the visual editor's own export.
if email and email.get("design") and not email.get("html"):
diff --git a/products/messaging/backend/api/test/test_message_templates.py b/products/messaging/backend/api/test/test_message_templates.py
index 2463df171521..1d3dbd241edf 100644
--- a/products/messaging/backend/api/test/test_message_templates.py
+++ b/products/messaging/backend/api/test/test_message_templates.py
@@ -117,6 +117,23 @@ class TestMessageTemplatesAPI(APIBaseTest):
assert response.json()["name"] == "Valid Template"
assert response.json()["content"]["email"]["subject"] == "Hello"
+ def test_create_with_html_only_wraps_design_without_rerendering(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/messaging_templates/",
+ data={
+ "name": "HTML only",
+ "content": {"email": {"subject": "Hello", "html": "<p>Hello</p>"}},
+ "type": "email",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED
+ email = response.json()["content"]["email"]
+ assert email["html"] == "<p>Hello</p>"
+ contents = email["design"]["body"]["rows"][0]["columns"][0]["contents"]
+ assert contents[0]["type"] == "html"
+ assert contents[0]["values"]["html"] == "<p>Hello</p>"
+
def test_create_email_template_without_email_content_succeeds(self):
response = self.client.post(
f"/api/environments/{self.team.id}/messaging_templates/",
@@ -295,7 +312,11 @@ class TestMessageTemplatesAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK, response.json()
self.message_template.refresh_from_db()
- assert self.message_template.content["email"] == {"subject": "New", "html": "<p>New</p>"}
+ email = self.message_template.content["email"]
+ assert email["subject"] == "New"
+ assert email["html"] == "<p>New</p>"
+ # The stored design is a wrap of the new html, not a merge of the old design
+ assert email["design"]["body"]["rows"][0]["columns"][0]["contents"][0]["values"]["html"] == "<p>New</p>"
def test_personal_api_key_cannot_access_other_teams_template(self):
api_key = self.create_personal_api_key_with_scopes(["hog_flow:read"])
diff --git a/products/workflows/backend/api/test/test_hog_flow_action_email.py b/products/workflows/backend/api/test/test_hog_flow_action_email.py
index fcdb688761a3..758fa1c7128c 100644
--- a/products/workflows/backend/api/test/test_hog_flow_action_email.py
+++ b/products/workflows/backend/api/test/test_hog_flow_action_email.py
@@ -145,6 +145,16 @@ class TestHogFlowActionEmailAPI(APIBaseTest):
return self.client.patch(url, body, HTTP_X_POSTHOG_CLIENT="mcp")
return self.client.patch(url, body)
+ def test_html_only_email_saves_with_design_wrapping_the_html(self):
+ flow_id = self._create_flow(with_design=False)
+
+ value = _stored_email_value(HogFlow.objects.get(id=flow_id))
+
+ assert value["html"] == "<p>Hello</p>"
+ contents = value["design"]["body"]["rows"][0]["columns"][0]["contents"]
+ assert contents[0]["type"] == "html"
+ assert contents[0]["values"]["html"] == "<p>Hello</p>"
+
@patch(RENDER_PATH, return_value=RENDERED_HTML)
def test_design_op_updates_block_and_rerenders_html(self, mock_render):
flow_id = self._create_flow()
@@ -215,6 +225,13 @@ class TestHogFlowActionEmailAPI(APIBaseTest):
@patch(RENDER_PATH, return_value=RENDERED_HTML)
def test_operations_without_design_rejected(self, _mock_render):
flow_id = self._create_flow(with_design=False)
+ # New saves auto-wrap html into a design; strip it to simulate a row saved before that,
+ # which design operations must still reject rather than partially apply.
+ flow = HogFlow.objects.get(id=flow_id)
+ for flow_action in flow.actions:
+ if flow_action["id"] == "email_1":
+ flow_action["config"]["inputs"]["email"]["value"].pop("design", None)
+ flow.save(update_fields=["actions"])
response = self._patch_email(
flow_id,
{"operations": [{"op": "update_content", "id": "text_1", "patch": {"values": {"text": "x"}}}]},
@@ -493,7 +510,9 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
assert response.status_code == 201, response.json()
stored = _stored_email_value(HogFlow.objects.get(pk=response.json()["id"]))
assert stored["subject"] == "Caller subject"
- assert "design" not in stored
+ # The stored design wraps the caller's html - the library template's design must not leak in
+ contents = stored["design"]["body"]["rows"][0]["columns"][0]["contents"]
+ assert contents[0]["values"]["html"] == "<p>Caller html</p>"
def test_unresolvable_template_uuid_is_rejected_on_strict_save(self):
deleted = self._create_library_template(deleted=True)