:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): expand custom tool blocks before the Unlayer export (#102454)
ruby childsb540aaeb34a2
diff --git a/products/messaging/backend/api/design_validation.py b/products/messaging/backend/api/design_validation.pyindex decac52ae72e..9b673fc58296 100644--- a/products/messaging/backend/api/design_validation.py+++ b/products/messaging/backend/api/design_validation.py@@ -2,6 +2,8 @@ from typing import NoReturnfrom rest_framework import serializers+from products.messaging.backend.unlayer import CUSTOM_TOOL_HTML_OPTIONS+# Structural validation for an Unlayer email design after operations are applied. Hard errors (raised)# are things Unlayer's renderer can't recover from — a missing body, a non-list rows, or duplicate ids# that would make later id-addressed edits ambiguous. Everything else is advisory: returned as warnings@@ -23,6 +25,7 @@ KNOWN_CONTENT_TYPES = frozenset("timer","table","carousel",+ "custom",})@@ -68,5 +71,10 @@ def validate_design(design: dict) -> list[str]:content_type = content.get("type")if content_type not in KNOWN_CONTENT_TYPES:warnings.append(f"content '{content.get('id')}' has unknown type '{content_type}'")+ elif content_type == "custom" and content.get("slug") not in CUSTOM_TOOL_HTML_OPTIONS:+ warnings.append(+ f"content '{content.get('id')}' uses custom tool '{content.get('slug')}', which the "+ "renderer can't expand — it will export as a 'Missing' placeholder"+ )return warningsdiff --git a/products/messaging/backend/api/test/test_design_operations.py b/products/messaging/backend/api/test/test_design_operations.pyindex db7f5862fb91..bfc9019d327a 100644--- a/products/messaging/backend/api/test/test_design_operations.py+++ b/products/messaging/backend/api/test/test_design_operations.py@@ -223,3 +223,17 @@ class TestValidateDesign:design = _sample_design()design["body"]["rows"][0]["columns"][0]["contents"][0]["type"] = "hologram"assert any("unknown type" in w for w in validate_design(design))++ def test_known_custom_tool_does_not_warn(self):+ design = _sample_design()+ content = design["body"]["rows"][0]["columns"][0]["contents"][0]+ content["type"] = "custom"+ content["slug"] = "unsubscribe_link"+ assert validate_design(design) == []++ def test_unexpandable_custom_tool_warns(self):+ design = _sample_design()+ content = design["body"]["rows"][0]["columns"][0]["contents"][0]+ content["type"] = "custom"+ content["slug"] = "hologram"+ assert any("Missing" in w for w in validate_design(design))diff --git a/products/messaging/backend/tests/test_unlayer.py b/products/messaging/backend/tests/test_unlayer.pyindex b685b07799f1..609b2c32868e 100644--- a/products/messaging/backend/tests/test_unlayer.py+++ b/products/messaging/backend/tests/test_unlayer.py@@ -6,11 +6,46 @@ from django.test import override_settingsimport requestsfrom parameterized import parameterized-from products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_html+from products.messaging.backend.unlayer import (+ UnlayerNotConfiguredError,+ UnlayerRenderError,+ expand_custom_tools,+ render_design_html,+)DESIGN = {"schemaVersion": 16, "body": {"rows": []}}+def _design_with_custom_block(slug: str = "unsubscribe_link") -> dict:+ return {+ "schemaVersion": 16,+ "body": {+ "rows": [+ {+ "id": "row1",+ "columns": [+ {+ "id": "col1",+ "contents": [+ {+ "id": "custom1",+ "slug": slug,+ "type": "custom",+ "values": {+ "containerPadding": "10px",+ "unsubscribe_link_content": '<a href="{{ unsubscribe_url }}">Unsubscribe</a>',+ "_meta": {"htmlID": "u_content_custom_unsubscribe_link_1"},+ },+ }+ ],+ }+ ],+ }+ ]+ },+ }++def _response(status_code: int = 200, payload: dict | None = None) -> MagicMock:response = MagicMock()response.status_code = status_code@@ -53,3 +88,49 @@ class TestRenderDesignHtml:with pytest.raises(UnlayerRenderError):render_design_html(DESIGN)+++class TestExpandCustomTools:+ def test_expands_unsubscribe_block_into_html_block(self):+ content = expand_custom_tools(_design_with_custom_block())["body"]["rows"][0]["columns"][0]["contents"][0]++ assert content["type"] == "html"+ assert content["values"]["html"] == '<a href="{{ unsubscribe_url }}">Unsubscribe</a>'+ assert content["id"] == "custom1"+ assert content["values"]["containerPadding"] == "10px"++ def test_leaves_the_stored_design_untouched(self):+ design = _design_with_custom_block()++ expand_custom_tools(design)++ assert design["body"]["rows"][0]["columns"][0]["contents"][0]["type"] == "custom"++ def test_leaves_unknown_custom_tools_alone(self):+ design = _design_with_custom_block(slug="hologram")++ content = expand_custom_tools(design)["body"]["rows"][0]["columns"][0]["contents"][0]++ assert content["type"] == "custom"+ assert "html" not in content["values"]++ @parameterized.expand(+ [+ ("body_not_an_object", {"body": "nope"}),+ ("rows_not_a_list", {"body": {"rows": "nope"}}),+ ("row_not_an_object", {"body": {"rows": ["nope"]}}),+ ]+ )+ def test_tolerates_a_malformed_design(self, _name, design):+ assert expand_custom_tools(design) == design++ @override_settings(UNLAYER_API_KEY="test-key", UNLAYER_API_BASE_URL="https://api.unlayer.com")+ @patch("products.messaging.backend.unlayer.requests.post")+ def test_export_is_sent_the_expanded_design(self, mock_post):+ mock_post.return_value = _response(200, {"success": True, "data": {"html": "<html>ok</html>"}})++ render_design_html(_design_with_custom_block())++ _, kwargs = mock_post.call_args+ exported = kwargs["json"]["design"]["body"]["rows"][0]["columns"][0]["contents"][0]+ assert exported["type"] == "html"diff --git a/products/messaging/backend/unlayer.py b/products/messaging/backend/unlayer.pyindex fd517896578e..6d39d677573d 100644--- a/products/messaging/backend/unlayer.py+++ b/products/messaging/backend/unlayer.py@@ -1,3 +1,4 @@+import copyfrom typing import Anyfrom django.conf import settings@@ -7,6 +8,13 @@ import requests# Unlayer renders synchronously; exports of large designs take a few seconds.EXPORT_TIMEOUT_SECONDS = 30+# Custom block types come from tools the visual editor registers in its customJS+# (frontend/src/scenes/hog-functions/email-templater/custom-tools/). The export API has no access to+# that registration, so it replaces every custom block with a "Missing" placeholder. Each entry maps+# a tool's slug to the option holding the html its editor-side exporter returns, so the block can be+# expanded before the export call. Keep in sync with the registered tools.+CUSTOM_TOOL_HTML_OPTIONS = {"unsubscribe_link": "unsubscribe_link_content"}+class UnlayerError(Exception):pass@@ -20,11 +28,42 @@ class UnlayerRenderError(UnlayerError):pass+def _dicts(value: Any) -> list[dict[str, Any]]:+ return [item for item in value if isinstance(item, dict)] if isinstance(value, list) else []+++def expand_custom_tools(design: dict[str, Any]) -> dict[str, Any]:+ """Return a copy of the design with known custom tool blocks rewritten as plain html blocks.++ The block keeps its id, container values and _meta, so the export renders the same padding and+ class names the editor shows. Only the copy sent to Unlayer is rewritten — the stored design+ keeps the custom block, so the template still opens with the tool's own editing UI.+ """++ expanded = copy.deepcopy(design)+ body = expanded.get("body")+ if not isinstance(body, dict):+ return expanded++ for row in _dicts(body.get("rows")) + _dicts(body.get("headers")) + _dicts(body.get("footers")):+ for column in _dicts(row.get("columns")):+ for content in _dicts(column.get("contents")):+ slug = content.get("slug")+ option = CUSTOM_TOOL_HTML_OPTIONS.get(slug) if isinstance(slug, str) else None+ values = content.get("values")+ if content.get("type") != "custom" or option is None or not isinstance(values, dict):+ continue+ content["type"] = "html"+ values["html"] = values.get(option) or ""++ return expanded++def render_design_html(design: dict[str, Any]) -> str:"""Render an Unlayer design to email HTML via the Unlayer export API.- This is the server-side equivalent of the visual editor's exportHtml() —- same renderer, so design-only saves produce the same HTML a human save would.+ This is the server-side equivalent of the visual editor's exportHtml() — same renderer, with+ custom tool blocks expanded first, so design-only saves produce the same HTML a human save would."""if not settings.UNLAYER_API_KEY:raise UnlayerNotConfiguredError("UNLAYER_API_KEY is not set")@@ -33,7 +72,7 @@ def render_design_html(design: dict[str, Any]) -> str:response = requests.post(f"{settings.UNLAYER_API_BASE_URL}/v2/export/html",auth=(settings.UNLAYER_API_KEY, ""),- json={"displayMode": "email", "design": design},+ json={"displayMode": "email", "design": expand_custom_tools(design)},timeout=EXPORT_TIMEOUT_SECONDS,)except requests.RequestException as e: