: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): surgical email patching for workflow email steps (#76015)
Harley Alexanderae741c00f968
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex f52870ba2344..9c03203c918a 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -75,9 +75,13 @@ from products.feature_flags.backend.user_blast_radius import (get_user_blast_radius,get_user_blast_radius_persons,)+from products.messaging.backend.api.design_operations import apply_design_operations+from products.messaging.backend.api.design_validation import validate_design+from products.messaging.backend.api.message_templates import DesignOperationSerializer+from products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_htmlfrom products.notifications.backend.facade.api import publish_resource_editedfrom products.workflows.backend.api.action_redirects import compute_action_redirects-from products.workflows.backend.api.graph_operations import apply_graph_operations+from products.workflows.backend.api.graph_operations import _deep_merge, apply_graph_operationsfrom products.workflows.backend.api.graph_validation import validate_graphfrom products.workflows.backend.api.hog_flow_batch_job import HogFlowBatchJobSerializerfrom products.workflows.backend.api.message_assets import (@@ -2009,6 +2013,138 @@ class HogFlowGraphUpdateSerializer(serializers.Serializer):)+class HogFlowActionEmailUpdateSerializer(serializers.Serializer):+ base_updated_at = serializers.DateTimeField(+ required=False,+ help_text=(+ "Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored "+ "workflow is newer, the patch is rejected with 409 instead of clobbering a concurrent edit."+ ),+ )+ operations = serializers.ListField(+ child=DesignOperationSerializer(),+ required=False,+ allow_empty=False,+ help_text=(+ "Ordered design edits applied atomically to this step's email design - the same operations as "+ "the email template patch. The result is re-rendered to HTML server-side, so the sent email "+ "always matches the patched design."+ ),+ )+ email_patch = serializers.JSONField(+ required=False,+ help_text=(+ "Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, "+ "preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is "+ "always re-rendered from it."+ ),+ )++ def validate_email_patch(self, value: Any) -> dict:+ if not isinstance(value, dict) or not value:+ raise serializers.ValidationError("email_patch must be a non-empty object")+ blocked = [key for key in ("design", "html") if key in value]+ if blocked:+ raise serializers.ValidationError(+ f"email_patch can't set {', '.join(blocked)}: edit the design via operations, and html is "+ "re-rendered from the design on every change."+ )+ return value++ def validate(self, data: Any) -> Any:+ if not data.get("operations") and not data.get("email_patch"):+ raise serializers.ValidationError("Provide operations and/or email_patch.")+ return data+++def _locate_action_email_value(actions: list[dict], action_id: str) -> dict:+ target = next((a for a in actions if isinstance(a, dict) and a.get("id") == action_id), None)+ if target is None:+ raise exceptions.ValidationError({"action_id": f"Action '{action_id}' not found in this workflow."})+ if target.get("type") != "function_email":+ raise exceptions.ValidationError(+ {+ "action_id": f"Action '{action_id}' is a '{target.get('type')}' step. "+ "Only function_email steps carry an email."+ }+ )+ inputs = (target.get("config") or {}).get("inputs")+ email_input = inputs.get("email") if isinstance(inputs, dict) else None+ value = email_input.get("value") if isinstance(email_input, dict) else None+ if not isinstance(value, dict):+ raise exceptions.ValidationError(+ {+ "action_id": f"Action '{action_id}' has no email content yet. Set the full "+ "config.inputs.email.value with a graph update_action first."+ }+ )+ return value++[email protected](frozen=True, kw_only=True)+class _RenderedActionEmailDesign:+ # The design the ops were applied to, kept so the in-lock apply can detect a concurrent edit.+ base_design: dict+ design: dict+ html: str+++def _render_action_email_operations(+ actions: list[dict], action_id: str, operations: list[dict]+) -> _RenderedActionEmailDesign:+ # The design half of an email edit: ops applied to the step's design and the result rendered to+ # HTML. Split from _apply_action_email_edit because rendering is a synchronous Unlayer HTTP call+ # (up to 30s) that must run before the caller takes the row lock, never under it.+ value = _locate_action_email_value(actions, action_id)+ design = value.get("design")+ if not isinstance(design, dict):+ raise exceptions.ValidationError(+ {+ "operations": "This step's email has no editable design JSON to patch. Set the full "+ "config.inputs.email.value.design with a graph update_action first, then use surgical "+ "operations."+ }+ )+ new_design = apply_design_operations(design, operations)+ for warning in validate_design(new_design):+ logger.info("hog_flow_action_email_design_warning", warning=warning, action_id=action_id)+ try:+ html = render_design_html(new_design)+ except UnlayerNotConfiguredError:+ raise exceptions.ValidationError(+ {+ "operations": "Design rendering is not configured on this instance - an administrator "+ "must set UNLAYER_API_KEY to enable design editing."+ }+ )+ except UnlayerRenderError as e:+ raise exceptions.ValidationError({"operations": f"Rendering the design to HTML failed: {e}"})+ return _RenderedActionEmailDesign(base_design=design, design=new_design, html=html)+++def _apply_action_email_edit(+ actions: list[dict], action_id: str, email_patch: dict, rendered: Optional[_RenderedActionEmailDesign]+) -> list[dict]:+ # Twin of apply_graph_operations for one email step: returns a new actions list with the step's+ # email value patched (the pre-rendered design installed, then the field merge).+ new_actions = deepcopy(actions)+ value = _locate_action_email_value(new_actions, action_id)++ if rendered is not None:+ # The render ran before the caller took the row lock, against the state read back then. A+ # design that moved in between means the ops were applied to a stale tree, so conflict and+ # let the caller re-read rather than silently overwrite the concurrent edit.+ if value.get("design") != rendered.base_design:+ raise StaleWorkflowUpdateError()+ value["design"] = rendered.design+ value["html"] = rendered.html++ if email_patch:+ _deep_merge(value, email_patch)++ return new_actions++class HogFlowInvocationSerializer(serializers.Serializer):configuration = HogFlowSerializer(write_only=True, required=False, help_text="Optional override; omit to use saved definition."@@ -2302,6 +2438,7 @@ class HogFlowViewSet("bulk_delete","rerun","graph",+ "action_email","publish","discard_draft","restore_revision",@@ -2818,6 +2955,113 @@ class HogFlowViewSet(return Response(self.get_serializer(locked).data)+ @extend_schema(+ parameters=[+ OpenApiParameter(+ "action_id", str, OpenApiParameter.PATH, description="Id of the function_email step to edit."+ )+ ],+ request=HogFlowActionEmailUpdateSerializer,+ responses={200: HogFlowSerializer},+ )+ @action(detail=True, methods=["PATCH"], url_path=r"actions/(?P<action_id>[^/.]+)/email")+ def action_email(self, request: Request, *args, **kwargs):+ # Surgical email editing for one step: the library template patch's design ops applied to the+ # email embedded in a workflow action, with html re-rendered server-side so the design and the+ # sent content can't diverge. Rides the graph endpoint's draft/staleness/revision machinery.+ op_serializer = HogFlowActionEmailUpdateSerializer(data=request.data)+ op_serializer.is_valid(raise_exception=True)+ operations = op_serializer.validated_data.get("operations") or []+ email_patch = op_serializer.validated_data.get("email_patch") or {}+ action_id = kwargs["action_id"]++ # Authorize + team-scope via the normal lookup, then re-read FOR UPDATE inside the transaction.+ instance = self.get_object()++ # Resolved before the write transaction: the flag check can hit the network and must not+ # extend the select_for_update row-lock hold.+ revisions_enabled = use_workflows_revisions(self.team)++ # A doomed request must fail here, before the expensive render below, not under the lock.+ # The locked section re-checks and stays authoritative if the status flips in between.+ if self._is_mcp_request(request) and instance.status == HogFlow.State.ACTIVE and not revisions_enabled:+ raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)++ # Rendering is a synchronous Unlayer HTTP call, so it also runs before the transaction,+ # against the unlocked row. Draft routing is predicted the same way the locked section+ # decides it; if the routing or the design moves before the lock, the apply conflicts.+ rendered: Optional[_RenderedActionEmailDesign] = None+ if operations:+ predicts_draft = self._is_mcp_request(request) and instance.status == HogFlow.State.ACTIVE+ if predicts_draft and instance.draft:+ render_base = list(instance.draft.get("actions") or [])+ else:+ render_base = list(instance.actions or [])+ rendered = _render_action_email_operations(render_base, action_id, operations)++ with transaction.atomic():+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)+ locked = HogFlow.objects.select_for_update().get(pk=instance.pk)++ route_to_draft = False+ if self._is_mcp_request(request) and locked.status == HogFlow.State.ACTIVE:+ if not revisions_enabled:+ raise exceptions.ValidationError(MCP_ACTIVE_EDIT_REJECTION)+ route_to_draft = True++ # Same staleness contract as /graph: draft edits race against other draft edits, so the+ # baseline is the draft's timestamp once one exists.+ base_updated_at_raw = request.data.get("base_updated_at")+ base_updated_at = parse_datetime(base_updated_at_raw) if base_updated_at_raw else None+ if base_updated_at is not None and timezone.is_naive(base_updated_at):+ base_updated_at = timezone.make_aware(base_updated_at)+ guard_timestamp = locked.updated_at+ if route_to_draft and locked.draft_updated_at:+ guard_timestamp = locked.draft_updated_at+ if base_updated_at and guard_timestamp and guard_timestamp > base_updated_at:+ raise StaleWorkflowUpdateError()++ # Draft edits compose on the staged draft, not on live - a second patch must see the first.+ if route_to_draft and locked.draft:+ base_actions = list(locked.draft.get("actions") or [])+ else:+ base_actions = list(locked.actions or [])++ new_actions = _apply_action_email_edit(base_actions, action_id, email_patch, rendered)++ serializer = self.get_serializer(locked, data={"actions": new_actions}, partial=True)+ serializer.context["enforce_graph_structure"] = True+ serializer.is_valid(raise_exception=True)++ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)+ before_update = HogFlow.objects.get(pk=instance.pk)+ if route_to_draft:+ self._write_draft(locked, locked, serializer.validated_data)+ else:+ bump = self._stage_revision_bump(+ locked, before_update, serializer.validated_data, enabled=revisions_enabled+ )+ # save() mutates and returns `locked` in place, so it's the saved HogFlow from here on.+ serializer.save()+ if bump:+ self._append_revisions(locked, before_update)++ # Unlike /graph, no action-redirect refresh or timing reschedule: an email edit can't delete+ # steps or change timing config.+ log_activity_from_viewset(self, locked, activity="updated", name=locked.name, previous=before_update)+ self._emit_resource_edited(locked)+ self._report_workflow_action(+ "hog_flow_action_email_updated",+ locked,+ {+ "operations_count": len(operations),+ "merged_fields": sorted(email_patch.keys()),+ "routed_to_draft": route_to_draft,+ },+ )++ return Response(self.get_serializer(locked).data)+def _maybe_reschedule_timing_edits(self, before: Optional[HogFlow], after: HogFlow) -> None:"""Kick off a reschedule sweep of parked runs when a go-live config change could movetheir wake times earlier or change what they resolve to (issue #66380): shorteneddiff --git a/products/workflows/backend/api/test/test_hog_flow_action_email.py b/products/workflows/backend/api/test/test_hog_flow_action_email.pynew file mode 100644index 000000000000..e22922124a31--- /dev/null+++ b/products/workflows/backend/api/test/test_hog_flow_action_email.py@@ -0,0 +1,381 @@+from copy import deepcopy++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.cdp.templates.hog_function_template import sync_template_to_db++from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES+from products.messaging.backend.unlayer import UnlayerRenderError+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow_revision import HogFlowRevision++webhook_template = MOCK_NODE_TEMPLATES[0]++FLAG_PATH = "products.workflows.backend.api.hog_flow.use_workflows_revisions"+RENDER_PATH = "products.workflows.backend.api.hog_flow.render_design_html"+RENDERED_HTML = "<html>rendered</html>"+++def _email_function_template() -> dict:+ template = deepcopy(webhook_template)+ template["id"] = "template-email"+ template["name"] = "Email"+ template["inputs_schema"] = [+ {+ "key": "email",+ "type": "native_email",+ "label": "Email",+ "secret": False,+ "hidden": False,+ "required": True,+ "templating": "liquid",+ }+ ]+ return template+++def _design() -> dict:+ return {+ "counters": {"u_row": 1, "u_column": 1, "u_content_text": 1},+ "schemaVersion": 16,+ "body": {+ "id": "body_1",+ "rows": [+ {+ "id": "row_1",+ "cells": [1],+ "columns": [+ {+ "id": "col_1",+ "contents": [{"id": "text_1", "type": "text", "values": {"text": "<p>Hello</p>"}}],+ "values": {},+ }+ ],+ "values": {},+ }+ ],+ "values": {},+ },+ }+++def _email_value(with_design: bool = True) -> dict:+ value = {+ "to": {"email": "{{ person.properties.email }}", "name": ""},+ "from": "[email protected]",+ "subject": "Old subject",+ "preheader": "Old preheader",+ "text": "Hello",+ "html": "<p>Hello</p>",+ }+ if with_design:+ value["design"] = _design()+ return value+++def _trigger_action() -> dict:+ return {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ }+++def _email_action(with_design: bool = True) -> dict:+ return {+ "id": "email_1",+ "name": "Email step",+ "type": "function_email",+ "config": {+ "template_id": "template-email",+ "inputs": {"email": {"value": _email_value(with_design), "templating": "liquid"}},+ },+ }+++def _webhook_action() -> dict:+ return {+ "id": "action_1",+ "name": "action_1",+ "type": "function",+ "config": {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}},+ }+++def _stored_email_value(flow: HogFlow, from_draft: bool = False) -> dict:+ actions = ((flow.draft or {}).get("actions") if from_draft else flow.actions) or []+ action = next(a for a in actions if a["id"] == "email_1")+ return action["config"]["inputs"]["email"]["value"]+++class TestHogFlowActionEmailAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ sync_template_to_db(webhook_template)+ sync_template_to_db(_email_function_template())++ def _create_flow(self, status: str = "draft", with_design: bool = True) -> str:+ flow = {+ "name": "Email Flow",+ "status": "draft",+ "actions": [_trigger_action(), _email_action(with_design), _webhook_action()],+ "edges": [+ {"from": "trigger_node", "to": "email_1", "type": "continue"},+ {"from": "email_1", "to": "action_1", "type": "continue"},+ ],+ }+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", flow)+ assert create.status_code == 201, create.json()+ flow_id = create.json()["id"]+ if status != "draft":+ activate = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": status})+ assert activate.status_code == 200, activate.json()+ return flow_id++ def _patch_email(self, flow_id: str, body: dict, action_id: str = "email_1", mcp: bool = True):+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}/actions/{action_id}/email"+ if mcp:+ return self.client.patch(url, body, HTTP_X_POSTHOG_CLIENT="mcp")+ return self.client.patch(url, body)++ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_design_op_updates_block_and_rerenders_html(self, mock_render):+ flow_id = self._create_flow()+ response = self._patch_email(+ flow_id,+ {+ "operations": [+ {"op": "update_content", "id": "text_1", "patch": {"values": {"text": "<p>New copy</p>"}}}+ ]+ },+ )+ assert response.status_code == 200, response.json()++ email = _stored_email_value(HogFlow.objects.get(pk=flow_id))+ contents = email["design"]["body"]["rows"][0]["columns"][0]["contents"]+ assert contents[0]["values"]["text"] == "<p>New copy</p>"+ # html is re-rendered from the patched design so the sent email can't go stale.+ assert email["html"] == RENDERED_HTML+ assert email["subject"] == "Old subject"+ mock_render.assert_called_once()++ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_email_patch_merges_fields_without_rerendering(self, mock_render):+ flow_id = self._create_flow()+ response = self._patch_email(+ flow_id, {"email_patch": {"subject": "New subject", "preheader": None, "text": "New text"}}+ )+ assert response.status_code == 200, response.json()++ email = _stored_email_value(HogFlow.objects.get(pk=flow_id))+ assert email["subject"] == "New subject"+ assert email["text"] == "New text"+ # A null leaf deletes the key, mirroring the design ops' merge semantics.+ assert "preheader" not in email+ # No design change, so the stored html must be preserved, not re-rendered.+ assert email["html"] == "<p>Hello</p>"+ mock_render.assert_not_called()++ @parameterized.expand(+ [+ ("design", {"design": {"body": {}}}),+ ("html", {"html": "<p>injected</p>"}),+ ]+ )+ def test_email_patch_rejects_derived_keys(self, _name, patch_body):+ flow_id = self._create_flow()+ response = self._patch_email(flow_id, {"email_patch": patch_body})+ assert response.status_code == 400, response.json()+ assert "email_patch" in str(response.json())++ def test_requires_operations_or_email_patch(self):+ flow_id = self._create_flow()+ response = self._patch_email(flow_id, {})+ assert response.status_code == 400, response.json()++ def test_unknown_action_id_rejected(self):+ flow_id = self._create_flow()+ response = self._patch_email(flow_id, {"email_patch": {"subject": "x"}}, action_id="ghost")+ assert response.status_code == 400, response.json()+ assert "ghost" in str(response.json())++ def test_non_email_action_rejected(self):+ flow_id = self._create_flow()+ response = self._patch_email(flow_id, {"email_patch": {"subject": "x"}}, action_id="action_1")+ assert response.status_code == 400, response.json()+ assert "email" in str(response.json())++ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_operations_without_design_rejected(self, _mock_render):+ flow_id = self._create_flow(with_design=False)+ response = self._patch_email(+ flow_id,+ {"operations": [{"op": "update_content", "id": "text_1", "patch": {"values": {"text": "x"}}}]},+ )+ assert response.status_code == 400, response.json()+ assert "design" in str(response.json())++ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_unknown_content_id_rejected_without_partial_write(self, _mock_render):+ flow_id = self._create_flow()+ response = self._patch_email(+ flow_id,+ {+ "operations": [{"op": "update_content", "id": "nope", "patch": {"values": {"text": "x"}}}],+ "email_patch": {"subject": "New subject"},+ },+ )+ assert response.status_code == 400, response.json()+ # Atomicity: the rejected batch leaves the stored email untouched, including the merge half.+ email = _stored_email_value(HogFlow.objects.get(pk=flow_id))+ assert email["subject"] == "Old subject"++ @patch(RENDER_PATH, side_effect=UnlayerRenderError("render exploded"))+ def test_render_failure_rejected_without_partial_write(self, _mock_render):+ flow_id = self._create_flow()+ response = self._patch_email(+ flow_id,+ {"operations": [{"op": "update_content", "id": "text_1", "patch": {"values": {"text": "x"}}}]},+ )+ assert response.status_code == 400, response.json()+ email = _stored_email_value(HogFlow.objects.get(pk=flow_id))+ assert email["html"] == "<p>Hello</p>"+ assert email["design"]["body"]["rows"][0]["columns"][0]["contents"][0]["values"]["text"] == "<p>Hello</p>"++ def test_design_moved_between_render_and_lock_rejected_with_409(self):+ flow_id = self._create_flow()++ def concurrent_edit_lands_during_render(design: dict) -> str:+ # Stand in for another writer committing between the pre-lock render and the locked+ # apply: the render call is the last thing that runs before the transaction opens.+ flow = HogFlow.objects.get(pk=flow_id)+ email = next(a for a in flow.actions if a["id"] == "email_1")+ text_block = email["config"]["inputs"]["email"]["value"]["design"]["body"]["rows"][0]["columns"][0][+ "contents"+ ][0]+ text_block["values"]["text"] = "<p>Concurrent copy</p>"+ HogFlow.objects.filter(pk=flow_id).update(actions=flow.actions)+ return RENDERED_HTML++ with patch(RENDER_PATH, side_effect=concurrent_edit_lands_during_render):+ response = self._patch_email(+ flow_id,+ {"operations": [{"op": "update_content", "id": "text_1", "patch": {"values": {"text": "<p>New</p>"}}}]},+ )++ assert response.status_code == 409, response.json()+ email = _stored_email_value(HogFlow.objects.get(pk=flow_id))+ # The concurrent edit survives, and the stale pre-rendered html never lands.+ assert (+ email["design"]["body"]["rows"][0]["columns"][0]["contents"][0]["values"]["text"]+ == "<p>Concurrent copy</p>"+ )+ assert email["html"] == "<p>Hello</p>"++ # ── Draft routing (mirrors the /graph endpoint's contract) ────────++ @patch(FLAG_PATH, return_value=True)+ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_mcp_patch_on_active_flow_lands_in_draft(self, _mock_render, _flag):+ flow_id = self._create_flow(status="active")+ live_actions_before = HogFlow.objects.get(pk=flow_id).actions++ response = self._patch_email(flow_id, {"email_patch": {"subject": "Draft subject"}})+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.actions == live_actions_before+ assert flow.draft is not None+ assert _stored_email_value(flow, from_draft=True)["subject"] == "Draft subject"+ assert response.json()["draft"] is not None++ @patch(FLAG_PATH, return_value=False)+ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_mcp_patch_on_active_flow_rejected_when_flag_off(self, mock_render, _flag):+ flow_id = self._create_flow(status="active")+ response = self._patch_email(+ flow_id,+ {+ "operations": [{"op": "update_content", "id": "text_1", "patch": {"values": {"text": "x"}}}],+ "email_patch": {"subject": "x"},+ },+ )+ assert response.status_code == 400, response.json()+ assert "active workflow isn't supported via MCP" in response.json()["detail"]+ # The rejection must land before the render, or a doomed request pays the Unlayer HTTP call.+ mock_render.assert_not_called()++ @patch(FLAG_PATH, return_value=True)+ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_mcp_patch_composes_on_existing_draft(self, _mock_render, _flag):+ # A graph patch stages a draft first; the email patch must apply on that draft, not reset it.+ flow_id = self._create_flow(status="active")+ graph = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",+ {"operations": [{"op": "update_action", "id": "email_1", "patch": {"name": "Renamed step"}}]},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert graph.status_code == 200, graph.json()++ response = self._patch_email(flow_id, {"email_patch": {"subject": "Draft subject"}})+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is not None+ draft_action = next(a for a in flow.draft["actions"] if a["id"] == "email_1")+ assert draft_action["name"] == "Renamed step"+ assert draft_action["config"]["inputs"]["email"]["value"]["subject"] == "Draft subject"++ @patch(FLAG_PATH, return_value=True)+ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_design_ops_compose_on_a_drafted_design(self, _mock_render, _flag):+ # Two consecutive draft design edits: the second must render against the draft's design,+ # not the live one, or the apply reads it as a concurrent edit and conflicts.+ flow_id = self._create_flow(status="active")+ ops = [{"op": "update_content", "id": "text_1", "patch": {"values": {"text": "<p>First</p>"}}}]+ first = self._patch_email(flow_id, {"operations": ops})+ assert first.status_code == 200, first.json()++ ops[0]["patch"] = {"values": {"text": "<p>Second</p>"}}+ second = self._patch_email(flow_id, {"operations": ops})+ assert second.status_code == 200, second.json()++ email = _stored_email_value(HogFlow.objects.get(pk=flow_id), from_draft=True)+ assert email["design"]["body"]["rows"][0]["columns"][0]["contents"][0]["values"]["text"] == "<p>Second</p>"++ @patch(FLAG_PATH, return_value=True)+ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_stale_base_updated_at_rejected_with_409(self, _mock_render, _flag):+ flow_id = self._create_flow(status="active")+ first = self._patch_email(flow_id, {"email_patch": {"subject": "First"}})+ assert first.status_code == 200, first.json()++ response = self._patch_email(+ flow_id,+ {"email_patch": {"subject": "Second"}, "base_updated_at": "2020-01-01T00:00:00Z"},+ )+ assert response.status_code == 409, response.json()++ @patch(FLAG_PATH, return_value=True)+ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_web_patch_on_active_flow_applies_live_and_bumps_revision(self, _mock_render, _flag):+ flow_id = self._create_flow(status="active")++ response = self._patch_email(flow_id, {"email_patch": {"subject": "Live subject"}}, mcp=False)+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is None+ assert _stored_email_value(flow)["subject"] == "Live subject"+ # A live content change must land in the revision history so it can be rolled back to.+ latest = HogFlowRevision.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).order_by("-version").first()+ assert latest is not None+ latest_email = next(a for a in latest.content["actions"] if a["id"] == "email_1")+ assert latest_email["config"]["inputs"]["email"]["value"]["subject"] == "Live subject"diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex eb918acdd263..c3a48135fdf2 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -665,6 +665,68 @@ export interface PatchedHogFlowApi {readonly action_redirects?: PatchedHogFlowApiActionRedirects}+/**+ * * `update_content` - update_content+ * * `update_column` - update_column+ * * `update_row` - update_row+ * * `update_body` - update_body+ * * `add_content` - add_content+ * * `remove_content` - remove_content+ * * `move_content` - move_content+ * * `add_row` - add_row+ * * `remove_row` - remove_row+ */+export type EmailTemplateDesignOperationEnumApi =+ (typeof EmailTemplateDesignOperationEnumApi)[keyof typeof EmailTemplateDesignOperationEnumApi]++export const EmailTemplateDesignOperationEnumApi = {+ UpdateContent: 'update_content',+ UpdateColumn: 'update_column',+ UpdateRow: 'update_row',+ UpdateBody: 'update_body',+ AddContent: 'add_content',+ RemoveContent: 'remove_content',+ MoveContent: 'move_content',+ AddRow: 'add_row',+ RemoveRow: 'remove_row',+} as const++export interface DesignOperationApi {+ /** Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null leaf deletes that key) — the surgical path, e.g. change just values.text. update_row / update_column {id, patch} and update_body {patch}: same deep-merge for row/column/body-level settings. add_content {column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are filled in for you). remove_content {id} / move_content {id, column_id, index?}: delete or relocate a block. add_row {row, index?} / remove_row {id}: add or delete a row.+ *+ * * `update_content` - update_content+ * * `update_column` - update_column+ * * `update_row` - update_row+ * * `update_body` - update_body+ * * `add_content` - add_content+ * * `remove_content` - remove_content+ * * `move_content` - move_content+ * * `add_row` - add_row+ * * `remove_row` - remove_row */+ op: EmailTemplateDesignOperationEnumApi+ /** Target node id. Required for update_content/column/row, remove_content, remove_row, move_content. */+ id?: string+ /** Target column id. Required for add_content and move_content. */+ column_id?: string+ /** update_* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text. */+ patch?: unknown+ /** add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned server-side. type is one of text, heading, button, image, divider, html, etc. */+ content?: unknown+ /** add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it. */+ row?: unknown+ /** add_*\/move_content only. 0-based insert position; omit to append to the end. */+ index?: number+}++export interface PatchedHogFlowActionEmailUpdateApi {+ /** Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored workflow is newer, the patch is rejected with 409 instead of clobbering a concurrent edit. */+ base_updated_at?: string+ /** Ordered design edits applied atomically to this step's email design - the same operations as the email template patch. The result is re-rendered to HTML server-side, so the sent email always matches the patched design. */+ operations?: DesignOperationApi[]+ /** Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is always re-rendered from it. */+ email_patch?: unknown+}+export interface MessageAssetApi {/** The workflow run this email was sent in. */invocation_id: stringdiff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex 1b71b3b5528a..ce70605dd815 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -43,6 +43,7 @@ import type {PaginatedHogFlowMinimalListApi,PaginatedHogFlowRevisionBasicListApi,PaginatedHogFlowTemplateListApi,+ PatchedHogFlowActionEmailUpdateApi,PatchedHogFlowApi,PatchedHogFlowGraphUpdateApi,PatchedHogFlowScheduleApi,@@ -330,6 +331,25 @@ export const hogFlowsDestroy = async (projectId: string, id: string, options?: R})}+export const getHogFlowsActionsEmailPartialUpdateUrl = (projectId: string, id: string, actionId: string) => {+ return `/api/projects/${projectId}/hog_flows/${id}/actions/${actionId}/email/`+}++export const hogFlowsActionsEmailPartialUpdate = async (+ projectId: string,+ id: string,+ actionId: string,+ patchedHogFlowActionEmailUpdateApi?: PatchedHogFlowActionEmailUpdateApi,+ options?: RequestInit+): Promise<HogFlowApi> => {+ return apiMutator<HogFlowApi>(getHogFlowsActionsEmailPartialUpdateUrl(projectId, id, actionId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedHogFlowActionEmailUpdateApi),+ })+}+export const getHogFlowsAssetsRetrieveUrl = (projectId: string, id: string, params?: HogFlowsAssetsRetrieveParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex b217864a89b5..e212a23b5386 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -1420,6 +1420,80 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod}).describe('Mixin for serializers to add user access control fields')+export const HogFlowsActionsEmailPartialUpdateBody = /* @__PURE__ */ zod.object({+ base_updated_at: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored workflow is newer, the patch is rejected with 409 instead of clobbering a concurrent edit.'+ ),+ operations: zod+ .array(+ zod.object({+ op: zod+ .enum([+ 'update_content',+ 'update_column',+ 'update_row',+ 'update_body',+ 'add_content',+ 'remove_content',+ 'move_content',+ 'add_row',+ 'remove_row',+ ])+ .describe(+ '\* `update_content` - update_content\n\* `update_column` - update_column\n\* `update_row` - update_row\n\* `update_body` - update_body\n\* `add_content` - add_content\n\* `remove_content` - remove_content\n\* `move_content` - move_content\n\* `add_row` - add_row\n\* `remove_row` - remove_row'+ )+ .describe(+ "Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null leaf deletes that key) — the surgical path, e.g. change just values.text. update_row \/ update_column {id, patch} and update_body {patch}: same deep-merge for row\/column\/body-level settings. add_content {column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are filled in for you). remove_content {id} \/ move_content {id, column_id, index?}: delete or relocate a block. add_row {row, index?} \/ remove_row {id}: add or delete a row.\n\n\* `update_content` - update_content\n\* `update_column` - update_column\n\* `update_row` - update_row\n\* `update_body` - update_body\n\* `add_content` - add_content\n\* `remove_content` - remove_content\n\* `move_content` - move_content\n\* `add_row` - add_row\n\* `remove_row` - remove_row"+ ),+ id: zod+ .string()+ .optional()+ .describe(+ 'Target node id. Required for update_content\/column\/row, remove_content, remove_row, move_content.'+ ),+ column_id: zod+ .string()+ .optional()+ .describe('Target column id. Required for add_content and move_content.'),+ patch: zod+ .unknown()+ .optional()+ .describe(+ "update_\* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. e.g. {values: {text: '<p>Hi<\/p>'}} changes only the block's text."+ ),+ content: zod+ .unknown()+ .optional()+ .describe(+ "add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned server-side. type is one of text, heading, button, image, divider, html, etc."+ ),+ row: zod+ .unknown()+ .optional()+ .describe(+ 'add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it.'+ ),+ index: zod+ .number()+ .optional()+ .describe('add_\*\/move_content only. 0-based insert position; omit to append to the end.'),+ })+ )+ .optional()+ .describe(+ "Ordered design edits applied atomically to this step's email design - the same operations as the email template patch. The result is re-rendered to HTML server-side, so the sent email always matches the patched design."+ ),+ email_patch: zod+ .unknown()+ .optional()+ .describe(+ "Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is always re-rendered from it."+ ),+})+export const HogFlowsBatchJobsCreateBody = /* @__PURE__ */ zod.object({status: zod.enum(['waiting', 'queued', 'active', 'completed', 'cancelled', 'failed'])diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex 82475611ca30..f99d0501df69 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -304,6 +304,28 @@ tools:Retrieve execution logs for a specific workflow by ID. Returns log entries with timestamp, level (DEBUG,LOG, INFO, WARN, ERROR), and message. Use to debug why a workflow is failing or not producing expectedresults. Supports filtering by log level, text search, time range (after/before), and pagination via limit.+ workflows-patch-action-email:+ operation: hog_flows_actions_email_partial_update+ enabled: true+ scopes:+ - hog_flow:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ input_schema: WorkflowActionEmailPatchSchema+ title: Patch a workflow step's email+ description: >+ Surgically edit the email inside one function_email step - the fastest path for copy tweaks and design+ changes on a workflow email. Use operations (the same design ops as workflows-patch-email-template,+ addressing blocks by id from the step's config.inputs.email.value.design) to edit the design, and+ email_patch to change subject, preheader, text, or recipients. After design ops the HTML is re-rendered+ server-side, so the sent email always matches the design. Edits apply atomically: an invalid batch changes+ nothing. On an active workflow, edits stage a draft (composing with any staged graph edits) and nothing+ reaches real people until workflows-publish; a rejection saying active workflows can't be edited means draft+ editing isn't enabled for this project yet. The full updated workflow is returned. Prefer this over+ workflows-patch-graph update_action for email content - it's smaller to send and keeps design and HTML in+ sync. For library templates use workflows-patch-email-template instead.workflows-patch-graph:operation: hog_flows_graph_partial_updateenabled: truediff --git a/products/workflows/skills/building-workflows/SKILL.md b/products/workflows/skills/building-workflows/SKILL.mdindex bb8776d6a441..32b593c89ed7 100644--- a/products/workflows/skills/building-workflows/SKILL.md+++ b/products/workflows/skills/building-workflows/SKILL.md@@ -32,7 +32,11 @@ Full tool catalog, grouped by job: [references/lifecycle-and-debugging.md](referAfter **any** patch, re-test the path you changed (step 3). A patch that validates structurally can still route the wrong way.-Email templates follow the same rule: edit a template's design with **`workflows-patch-email-template`** (surgical, id-addressed ops over the Unlayer blocks), not `workflows-update-email-template`, which resends the entire design JSON. Compose and edit templates with the **`designing-email-templates`** skill.+Email content follows the same rule.+The email inside a `function_email` step is edited with **`workflows-patch-action-email`**: the same id-addressed design ops as the template patch, plus an `email_patch` merge for subject/preheader/text/recipients, with the HTML re-rendered server-side so it always matches the design.+Prefer it over `workflows-patch-graph` `update_action` for email content - an `update_action` that changes `design` leaves the stored `html` stale.+Library templates are edited with **`workflows-patch-email-template`**, not `workflows-update-email-template` (which resends the entire design JSON).+Compose and edit email designs with the **`designing-email-templates`** skill.## Changing a live workflowdiff --git a/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.mdindex 891a5dffed9c..998013c4384f 100644--- a/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md+++ b/products/workflows/skills/building-workflows/references/lifecycle-and-debugging.md@@ -8,6 +8,7 @@ The MCP tools for the workflows product, grouped by job. The lifecycle that stri- `workflows-create` — create a workflow. Always created as a `draft`.- `workflows-patch-graph` — **the way to edit a workflow's graph.** An ordered, id-addressed op list (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`) applied atomically; `update_action` deep-merges (a `null` leaf deletes a key). Returns the full updated graph, so no re-fetch. On an active workflow, patches stage a draft (published with `workflows-publish`) instead of changing what's running.+- `workflows-patch-action-email` — **the way to edit the email inside a `function_email` step.** The template patch's design ops (id-addressed Unlayer blocks) plus an `email_patch` merge for subject/preheader/text/recipients; HTML is re-rendered server-side so it can't go stale. Stages a draft on active workflows, same as `workflows-patch-graph`.- `workflows-update` — **fallback editor.** Top-level metadata a graph patch can't express (renaming), or an escape hatch to replace the whole workflow when `workflows-patch-graph` won't land a change. On an active workflow, content fields stage a draft; name/description apply live.- `workflows-enable` — draft → `active`. It starts running on real people, so test first and get the user's explicit approval before enabling. Later changes stage as drafts and take effect only on publish.- `workflows-publish` — apply an active workflow's staged draft to its live config. Call without `confirm` first: it echoes `in_flight_runs` + `draft_updated_at` and changes nothing. Get the user's go-ahead, then confirm with that exact `draft_updated_at` (409 = draft changed under you; re-read).diff --git a/products/workflows/skills/designing-email-templates/SKILL.md b/products/workflows/skills/designing-email-templates/SKILL.mdindex e98b4a1b3afe..3aad8e35bd52 100644--- a/products/workflows/skills/designing-email-templates/SKILL.md+++ b/products/workflows/skills/designing-email-templates/SKILL.md@@ -79,6 +79,18 @@ Pass the design directly in the tool call — no scratch files, no pre-validatio3. `workflows-update-email-template` — send the complete `content` back. The server re-renders the sent email from the edited design.4. `workflows-show-email-template` — render the updated template so the user sees the change; its response carries the final rendered html, so read it before describing the result.+For small changes to an existing design, prefer `workflows-patch-email-template`: id-addressed operations over the Unlayer blocks, so you send only the edit instead of the whole design.++## Editing the email inside a workflow step++A `function_email` step carries its own email snapshot (`config.inputs.email.value` with subject/text/html/design), independent of any library template.+Edit it with `workflows-patch-action-email`: the same design operations as `workflows-patch-email-template`, plus an `email_patch` merge for subject, preheader, text, and recipients.++1. `workflows-get` — the step's current design (and its block ids) is in `config.inputs.email.value.design`.+2. `workflows-patch-action-email` with the workflow id, the step's `action_id`, and your operations and/or `email_patch`.+3. The HTML is re-rendered server-side from the patched design, so it never goes stale.+4. On an active workflow the edit stages a draft — test with `workflows-test-run` (`use_draft=true`) and apply it with `workflows-publish`.+## Using templates- List what exists with `workflows-list-email-templates` (metadata only; fetch one for its content).diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 0306c16fcdee..ff6834b37fd1 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -10610,6 +10610,20 @@"readOnlyHint": true}},+ "workflows-patch-action-email": {+ "description": "Surgically edit the email inside one function_email step - the fastest path for copy tweaks and design changes on a workflow email. Use operations (the same design ops as workflows-patch-email-template, addressing blocks by id from the step's config.inputs.email.value.design) to edit the design, and email_patch to change subject, preheader, text, or recipients. After design ops the HTML is re-rendered server-side, so the sent email always matches the design. Edits apply atomically: an invalid batch changes nothing. On an active workflow, edits stage a draft (composing with any staged graph edits) and nothing reaches real people until workflows-publish; a rejection saying active workflows can't be edited means draft editing isn't enabled for this project yet. The full updated workflow is returned. Prefer this over workflows-patch-graph update_action for email content - it's smaller to send and keeps design and HTML in sync. For library templates use workflows-patch-email-template instead.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Patch a workflow step's email",+ "title": "Patch a workflow step's email",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-patch-email-template": {"description": "Surgically edit an email template's design by sending a small, ordered list of operations instead of resending the whole design JSON. Prefer this over workflows-update-email-template for any change to an existing design. Reference blocks by their id (call workflows-get-email-template first to read the current design and its ids). For the common case — tweak one block — use update_content with a deep-merge patch (e.g. {op: update_content, id: '<block-id>', patch: {values: {text: '<p>New copy</p>'}}}); a null leaf deletes that key. Use add_content / remove_content / move_content / add_row / remove_row for structural changes; ids and Unlayer numbering for added blocks are assigned for you. Operations apply atomically — the design is read, the ops applied in order, the result validated and re-rendered to HTML, and saved only if valid, otherwise nothing changes. After patching, call workflows-show-email-template so the user sees the result.","category": "Workflows",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8a2b9d0e1de4..8f9460618d70 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -11292,6 +11292,20 @@"readOnlyHint": true}},+ "workflows-patch-action-email": {+ "description": "Surgically edit the email inside one function_email step - the fastest path for copy tweaks and design changes on a workflow email. Use operations (the same design ops as workflows-patch-email-template, addressing blocks by id from the step's config.inputs.email.value.design) to edit the design, and email_patch to change subject, preheader, text, or recipients. After design ops the HTML is re-rendered server-side, so the sent email always matches the design. Edits apply atomically: an invalid batch changes nothing. On an active workflow, edits stage a draft (composing with any staged graph edits) and nothing reaches real people until workflows-publish; a rejection saying active workflows can't be edited means draft editing isn't enabled for this project yet. The full updated workflow is returned. Prefer this over workflows-patch-graph update_action for email content - it's smaller to send and keeps design and HTML in sync. For library templates use workflows-patch-email-template instead.",+ "category": "Workflows",+ "feature": "workflows",+ "summary": "Patch a workflow step's email",+ "title": "Patch a workflow step's email",+ "required_scopes": ["hog_flow:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"workflows-patch-email-template": {"description": "Surgically edit an email template's design by sending a small, ordered list of operations instead of resending the whole design JSON. Prefer this over workflows-update-email-template for any change to an existing design. Reference blocks by their id (call workflows-get-email-template first to read the current design and its ids). For the common case — tweak one block — use update_content with a deep-merge patch (e.g. {op: update_content, id: '<block-id>', patch: {values: {text: '<p>New copy</p>'}}}); a null leaf deletes that key. Use add_content / remove_content / move_content / add_row / remove_row for structural changes; ids and Unlayer numbering for added blocks are assigned for you. Operations apply atomically — the design is read, the ops applied in order, the result validated and re-rendered to HTML, and saved only if valid, otherwise nothing changes. After patching, call workflows-show-email-template so the user sees the result.","category": "Workflows",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 63ad130b9e4f..3a1741e71549 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -1158,6 +1158,229 @@],"description": "Filter definition. Pick exactly one branch: `data_warehouse` (set `source: \"data_warehouse\"` plus `table_name`/`timestamp_field`/`key_field`) or `events` (HogFunction filter shape with an `events` array)."},+ "WorkflowActionEmailPatchSchema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "description": "The workflow (HogFlow) id."+ },+ "action_id": {+ "type": "string",+ "description": "Id of the function_email step whose email to edit."+ },+ "operations": {+ "description": "Ordered edits applied atomically to the step's email design - the same operations as workflows-patch-email-template. The result is re-rendered to HTML server-side, so the sent email always matches the patched design. Reference blocks by id (read them via workflows-get).",+ "minItems": 1,+ "type": "array",+ "items": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_content"+ },+ "id": {+ "type": "string",+ "description": "Id of the content block to update."+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "Partial content-block fields, deep-merged into the existing block; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text."+ }+ },+ "required": ["op", "id", "patch"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_column"+ },+ "id": {+ "type": "string",+ "description": "Id of the column to update."+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "Partial column fields, deep-merged; a null leaf deletes that key."+ }+ },+ "required": ["op", "id", "patch"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_row"+ },+ "id": {+ "type": "string",+ "description": "Id of the row to update."+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "Partial row fields, deep-merged; a null leaf deletes that key."+ }+ },+ "required": ["op", "id", "patch"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "update_body"+ },+ "patch": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}."+ }+ },+ "required": ["op", "patch"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "add_content"+ },+ "column_id": {+ "type": "string",+ "description": "Id of the column to insert the block into."+ },+ "content": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "A content block {type, values: {...}}; omit id and values._meta — they are assigned server-side. type is one of text, heading, button, image, divider, html, etc."+ },+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ }+ },+ "required": ["op", "column_id", "content"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "remove_content"+ },+ "id": {+ "type": "string",+ "description": "Id of the content block to remove."+ }+ },+ "required": ["op", "id"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "move_content"+ },+ "id": {+ "type": "string",+ "description": "Id of the content block to move."+ },+ "column_id": {+ "type": "string",+ "description": "Id of the destination column."+ },+ "index": {+ "description": "0-based position in the destination column; omit to append.",+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ }+ },+ "required": ["op", "id", "column_id"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "add_row"+ },+ "row": {+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {},+ "description": "A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it."+ },+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ }+ },+ "required": ["op", "row"]+ },+ {+ "type": "object",+ "properties": {+ "op": {+ "type": "string",+ "const": "remove_row"+ },+ "id": {+ "type": "string",+ "description": "Id of the row to remove."+ }+ },+ "required": ["op", "id"]+ }+ ]+ }+ },+ "email_patch": {+ "description": "Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is always re-rendered from it.",+ "type": "object",+ "propertyNames": {+ "type": "string"+ },+ "additionalProperties": {}+ },+ "base_updated_at": {+ "description": "Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored workflow is newer, the patch is rejected with 409 instead of clobbering a concurrent edit.",+ "type": "string"+ }+ },+ "required": ["id", "action_id"]+ },"WorkflowGraphPatchSchema": {"type": "object","properties": {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6ea4fb0f602c..cc31f0a9c9ca 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -51882,6 +51882,15 @@ export namespace Schemas {readonly action_redirects?: PatchedHogFlowActionRedirects;}+ export interface PatchedHogFlowActionEmailUpdate {+ /** Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored workflow is newer, the patch is rejected with 409 instead of clobbering a concurrent edit. */+ base_updated_at?: string;+ /** Ordered design edits applied atomically to this step's email design - the same operations as the email template patch. The result is re-rendered to HTML server-side, so the sent email always matches the patched design. */+ operations?: DesignOperation[];+ /** Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is always re-rendered from it. */+ email_patch?: unknown;+ }+export interface PatchedHogFlowGraphUpdate {/** Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored graph is newer, the patch is rejected with 409 instead of clobbering a concurrent edit. */base_updated_at?: string;diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex fd74d1436098..9eafc051330c 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 18 enabled ops+ * PostHog API - MCP 19 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -521,6 +521,90 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod}).describe('Mixin for serializers to add user access control fields')+export const HogFlowsActionsEmailPartialUpdateParams = /* @__PURE__ */ zod.object({+ action_id: zod.string().describe('Id of the function_email step to edit.'),+ id: zod.string().describe('A UUID string identifying this hog flow.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const HogFlowsActionsEmailPartialUpdateBody = /* @__PURE__ */ zod.object({+ base_updated_at: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe(+ 'Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored workflow is newer, the patch is rejected with 409 instead of clobbering a concurrent edit.'+ ),+ operations: zod+ .array(+ zod.object({+ op: zod+ .enum([+ 'update_content',+ 'update_column',+ 'update_row',+ 'update_body',+ 'add_content',+ 'remove_content',+ 'move_content',+ 'add_row',+ 'remove_row',+ ])+ .describe(+ '\* `update_content` - update_content\n\* `update_column` - update_column\n\* `update_row` - update_row\n\* `update_body` - update_body\n\* `add_content` - add_content\n\* `remove_content` - remove_content\n\* `move_content` - move_content\n\* `add_row` - add_row\n\* `remove_row` - remove_row'+ )+ .describe(+ "Design edit. update_content {id, patch}: deep-merge patch into the content block's fields (a null leaf deletes that key) — the surgical path, e.g. change just values.text. update_row \/ update_column {id, patch} and update_body {patch}: same deep-merge for row\/column\/body-level settings. add_content {column_id, content, index?}: insert a content block into a column (id and Unlayer numbering are filled in for you). remove_content {id} \/ move_content {id, column_id, index?}: delete or relocate a block. add_row {row, index?} \/ remove_row {id}: add or delete a row.\n\n\* `update_content` - update_content\n\* `update_column` - update_column\n\* `update_row` - update_row\n\* `update_body` - update_body\n\* `add_content` - add_content\n\* `remove_content` - remove_content\n\* `move_content` - move_content\n\* `add_row` - add_row\n\* `remove_row` - remove_row"+ ),+ id: zod+ .string()+ .optional()+ .describe(+ 'Target node id. Required for update_content\/column\/row, remove_content, remove_row, move_content.'+ ),+ column_id: zod+ .string()+ .optional()+ .describe('Target column id. Required for add_content and move_content.'),+ patch: zod+ .unknown()+ .optional()+ .describe(+ "update_\* only. Partial fields deep-merged into the existing node; a null leaf deletes that key. e.g. {values: {text: '<p>Hi<\/p>'}} changes only the block's text."+ ),+ content: zod+ .unknown()+ .optional()+ .describe(+ "add_content only. A content block {type, values: {...}}; omit id and values._meta — they're assigned server-side. type is one of text, heading, button, image, divider, html, etc."+ ),+ row: zod+ .unknown()+ .optional()+ .describe(+ 'add_row only. A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it.'+ ),+ index: zod+ .number()+ .optional()+ .describe('add_\*\/move_content only. 0-based insert position; omit to append to the end.'),+ })+ )+ .optional()+ .describe(+ "Ordered design edits applied atomically to this step's email design - the same operations as the email template patch. The result is re-rendered to HTML server-side, so the sent email always matches the patched design."+ ),+ email_patch: zod+ .unknown()+ .optional()+ .describe(+ "Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is always re-rendered from it."+ ),+})+export const HogFlowsBatchJobsListParams = /* @__PURE__ */ zod.object({id: zod.string().describe('A UUID string identifying this hog flow.'),project_id: zoddiff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 5dc63da62ee0..8a09eb399ce0 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -804,3 +804,41 @@ export const EmailTemplateDesignPatchSchema = z.object({'otherwise the template is left unchanged. Reference blocks by id so you never resend the whole design.'),})++export const WorkflowActionEmailPatchSchema = z+ .object({+ id: z.string().describe('The workflow (HogFlow) id.'),+ action_id: z.string().describe('Id of the function_email step whose email to edit.'),+ operations: z+ .array(EmailDesignPatchOperationSchema)+ .min(1)+ .optional()+ .describe(+ "Ordered edits applied atomically to the step's email design - the same operations as " ++ 'workflows-patch-email-template. The result is re-rendered to HTML server-side, so the sent ' ++ 'email always matches the patched design. Reference blocks by id (read them via workflows-get).'+ ),+ email_patch: z+ .record(z.string(), z.unknown())+ .optional()+ .describe(+ "Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, " ++ 'preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is ' ++ 'always re-rendered from it.'+ ),+ base_updated_at: z+ .string()+ .optional()+ .describe(+ 'Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored workflow ' ++ 'is newer, the patch is rejected with 409 instead of clobbering a concurrent edit.'+ ),+ })+ .superRefine((data, ctx) => {+ if (!data.operations?.length && !data.email_patch) {+ ctx.addIssue({+ code: 'custom',+ message: 'Provide operations and/or email_patch.',+ })+ }+ })diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex 74eefd5eb26a..85e9e8fa1709 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -31,7 +31,7 @@ import {HogFlowsSchedulesPartialUpdateParams,} from '@/generated/workflows/api'import { withUiApp } from '@/resources/ui-apps'-import { WorkflowGraphPatchSchema } from '@/schema/tool-inputs'+import { WorkflowActionEmailPatchSchema, WorkflowGraphPatchSchema } from '@/schema/tool-inputs'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -287,6 +287,24 @@ const workflowsLogs = (): ToolBase<typeof WorkflowsLogsSchema, unknown> => ({},})+const WorkflowsPatchActionEmailSchema = WorkflowActionEmailPatchSchema++const workflowsPatchActionEmail = (): ToolBase<typeof WorkflowsPatchActionEmailSchema, Schemas.HogFlow> => ({+ name: 'workflows-patch-action-email',+ schema: WorkflowsPatchActionEmailSchema,+ handler: async (context: Context, params: z.infer<typeof WorkflowsPatchActionEmailSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const parsedParams = WorkflowsPatchActionEmailSchema.parse(params)+ const { id, action_id, ...body } = parsedParams+ const result = await context.api.request<Schemas.HogFlow>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(id))}/actions/${encodeURIComponent(String(action_id))}/email/`,+ body,+ })+ return result+ },+})+const WorkflowsPatchGraphSchema = WorkflowGraphPatchSchemaconst workflowsPatchGraph = (): ToolBase<typeof WorkflowsPatchGraphSchema, Schemas.HogFlow> => ({@@ -490,6 +508,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'workflows-list-invocations': workflowsListInvocations,'workflows-list-revisions': workflowsListRevisions,'workflows-logs': workflowsLogs,+ 'workflows-patch-action-email': workflowsPatchActionEmail,'workflows-patch-graph': workflowsPatchGraph,'workflows-publish': workflowsPublish,'workflows-restore-revision': workflowsRestoreRevision,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-action-email.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-action-email.jsonnew file mode 100644index 000000000000..3d7874ec84bc--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-patch-action-email.json@@ -0,0 +1,224 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "action_id": {+ "description": "Id of the function_email step whose email to edit.",+ "type": "string"+ },+ "base_updated_at": {+ "description": "Optimistic concurrency: the updated_at (or draft_updated_at) last loaded. If the stored workflow is newer, the patch is rejected with 409 instead of clobbering a concurrent edit.",+ "type": "string"+ },+ "email_patch": {+ "additionalProperties": {},+ "description": "Partial email fields deep-merged into the step's email (a null leaf deletes the key): subject, preheader, text, to, from, replyTo, cc, bcc. The design is edited via operations, and html is always re-rendered from it.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "id": {+ "description": "The workflow (HogFlow) id.",+ "type": "string"+ },+ "operations": {+ "description": "Ordered edits applied atomically to the step's email design - the same operations as workflows-patch-email-template. The result is re-rendered to HTML server-side, so the sent email always matches the patched design. Reference blocks by id (read them via workflows-get).",+ "items": {+ "oneOf": [+ {+ "properties": {+ "id": {+ "description": "Id of the content block to update.",+ "type": "string"+ },+ "op": {+ "const": "update_content",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "description": "Partial content-block fields, deep-merged into the existing block; a null leaf deletes that key. e.g. {values: {text: '<p>Hi</p>'}} changes only the block's text.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "id", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the column to update.",+ "type": "string"+ },+ "op": {+ "const": "update_column",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "description": "Partial column fields, deep-merged; a null leaf deletes that key.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "id", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the row to update.",+ "type": "string"+ },+ "op": {+ "const": "update_row",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "description": "Partial row fields, deep-merged; a null leaf deletes that key.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "id", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "op": {+ "const": "update_body",+ "type": "string"+ },+ "patch": {+ "additionalProperties": {},+ "description": "Partial body fields, deep-merged. e.g. {values: {backgroundColor: '#ffffff'}}.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "patch"],+ "type": "object"+ },+ {+ "properties": {+ "column_id": {+ "description": "Id of the column to insert the block into.",+ "type": "string"+ },+ "content": {+ "additionalProperties": {},+ "description": "A content block {type, values: {...}}; omit id and values._meta — they are assigned server-side. type is one of text, heading, button, image, divider, html, etc.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "op": {+ "const": "add_content",+ "type": "string"+ }+ },+ "required": ["op", "column_id", "content"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the content block to remove.",+ "type": "string"+ },+ "op": {+ "const": "remove_content",+ "type": "string"+ }+ },+ "required": ["op", "id"],+ "type": "object"+ },+ {+ "properties": {+ "column_id": {+ "description": "Id of the destination column.",+ "type": "string"+ },+ "id": {+ "description": "Id of the content block to move.",+ "type": "string"+ },+ "index": {+ "description": "0-based position in the destination column; omit to append.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "op": {+ "const": "move_content",+ "type": "string"+ }+ },+ "required": ["op", "id", "column_id"],+ "type": "object"+ },+ {+ "properties": {+ "index": {+ "description": "0-based insert position; omit to append to the end.",+ "maximum": 9007199254740991,+ "minimum": -9007199254740991,+ "type": "integer"+ },+ "op": {+ "const": "add_row",+ "type": "string"+ },+ "row": {+ "additionalProperties": {},+ "description": "A full row {cells, columns: [{contents: [...], values}], values}; ids and Unlayer numbering are assigned server-side for the row and everything nested in it.",+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": ["op", "row"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Id of the row to remove.",+ "type": "string"+ },+ "op": {+ "const": "remove_row",+ "type": "string"+ }+ },+ "required": ["op", "id"],+ "type": "object"+ }+ ]+ },+ "minItems": 1,+ "type": "array"+ }+ },+ "required": ["id", "action_id"],+ "type": "object"+}diff --git a/tach.toml b/tach.tomlindex a8ada575f25b..01ffe931bdb2 100644--- a/tach.toml+++ b/tach.toml@@ -792,6 +792,7 @@ depends_on = ["products.actions","products.cdp","products.feature_flags",+ "products.messaging","products.notifications",]layer = "modules"