: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): reload the email template editor after edits elsewhere (#102211)
Harley Alexander41c8cdd99ee1
diff --git a/products/messaging/backend/api/message_templates.py b/products/messaging/backend/api/message_templates.pyindex 527da2195ee1..0a3778696999 100644--- a/products/messaging/backend/api/message_templates.py+++ b/products/messaging/backend/api/message_templates.py@@ -22,6 +22,7 @@ from products.messaging.backend.api.design_validation import validate_designfrom products.messaging.backend.models.message_category import MessageCategoryfrom products.messaging.backend.models.message_template import MessageTemplatefrom products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_html+from products.notifications.backend.facade.api import publish_resource_editedlogger = structlog.get_logger(__name__)@@ -304,6 +305,27 @@ class MessageTemplatesViewSet(.order_by("-created_at"))+ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ instance: MessageTemplate = serializer.save()+ self._emit_resource_edited(instance)++ def _emit_resource_edited(self, instance: MessageTemplate) -> None:+ # Realtime "edited elsewhere" signal so an open editor can refresh instead of overwriting a write+ # from another channel (UI/MCP/API). Fires for every channel; the frontend drops its own echo by+ # comparing updated_at. Transient, so no inbox notification. The write is already committed when+ # this runs, so a publish failure must not turn a saved template into an error response.+ try:+ publish_resource_edited(+ team=self.team,+ resource_type="MessageTemplate",+ resource_id=str(instance.id),+ updated_at=instance.updated_at.isoformat(),+ actor_user_id=getattr(self.request.user, "id", None),+ ac_resource_type=self.scope_object,+ )+ except Exception as e:+ logger.warning("Failed to publish message template edited event", error=str(e))+@extend_schema(request=DesignPatchSerializer, responses={200: MessageTemplateSerializer})@action(detail=True, methods=["PATCH"])def design(self, request: Request, *args: Any, **kwargs: Any) -> Response:@@ -346,4 +368,5 @@ class MessageTemplatesViewSet(serializer.is_valid(raise_exception=True)serializer.save()+ self._emit_resource_edited(locked)return Response(self.get_serializer(locked).data)diff --git a/products/messaging/backend/api/test/test_message_templates.py b/products/messaging/backend/api/test/test_message_templates.pyindex 1d3dbd241edf..cd8f4ce70e7a 100644--- a/products/messaging/backend/api/test/test_message_templates.py+++ b/products/messaging/backend/api/test/test_message_templates.py@@ -296,7 +296,8 @@ class TestMessageTemplatesAPI(APIBaseTest):response = getattr(self.client, method)(url, data=data, format="json")assert response.status_code == expected_status, response.json()- def test_update_replaces_content_wholesale(self):+ @patch("products.messaging.backend.api.message_templates.publish_resource_edited")+ def test_update_replaces_content_wholesale(self, mock_emit):"""The content JSONField is replaced as a unit on update, never deep-merged —a payload without design makes the submitted html canonical."""self.message_template.content = {@@ -317,6 +318,15 @@ class TestMessageTemplatesAPI(APIBaseTest):assert email["html"] == "<p>New</p>"# The stored design is a wrap of the new html, not a merge of the old designassert email["design"]["body"]["rows"][0]["columns"][0]["contents"][0]["values"]["html"] == "<p>New</p>"+ self._assert_resource_edited_emitted(mock_emit)++ def _assert_resource_edited_emitted(self, mock_emit):+ assert mock_emit.call_count == 1+ kwargs = mock_emit.call_args.kwargs+ assert kwargs["resource_type"] == "MessageTemplate"+ assert kwargs["resource_id"] == str(self.message_template.id)+ assert kwargs["updated_at"] == self.message_template.updated_at.isoformat()+ assert kwargs["actor_user_id"] == self.user.iddef test_personal_api_key_cannot_access_other_teams_template(self):api_key = self.create_personal_api_key_with_scopes(["hog_flow:read"])@@ -363,8 +373,9 @@ class TestMessageTemplatesAPI(APIBaseTest):},}+ @patch("products.messaging.backend.api.message_templates.publish_resource_edited")@patch("products.messaging.backend.api.message_templates.render_design_html")- def test_design_patch_updates_one_block_and_rerenders(self, mock_render):+ def test_design_patch_updates_one_block_and_rerenders(self, mock_render, mock_emit):mock_render.return_value = "<html>patched</html>"self.message_template.content = {"email": {"subject": "Hi", "design": self._design_with_text()}}self.message_template.save()@@ -383,9 +394,11 @@ class TestMessageTemplatesAPI(APIBaseTest):assert email["subject"] == "Hi"assert email["html"] == "<html>patched</html>"mock_render.assert_called_once()+ self._assert_resource_edited_emitted(mock_emit)+ @patch("products.messaging.backend.api.message_templates.publish_resource_edited")@patch("products.messaging.backend.api.message_templates.render_design_html")- def test_design_patch_unknown_id_leaves_template_untouched(self, mock_render):+ def test_design_patch_unknown_id_leaves_template_untouched(self, mock_render, mock_emit):mock_render.return_value = "<html>x</html>"original = self._design_with_text()self.message_template.content = {"email": {"subject": "Hi", "design": original}}@@ -401,6 +414,7 @@ class TestMessageTemplatesAPI(APIBaseTest):self.message_template.refresh_from_db()assert self.message_template.content["email"]["design"] == originalmock_render.assert_not_called()+ mock_emit.assert_not_called()def test_design_patch_without_design_returns_400(self):# self.message_template has no design in content.emaildiff --git a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsxindex 9b446d56908f..d6982f604985 100644--- a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx+++ b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'-import { LemonButton, LemonDivider, Spinner } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonDivider, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'import { More } from 'lib/lemon-ui/LemonButton/More'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'@@ -38,6 +38,8 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemduplicateTemplate,deleteTemplate,setTemplatePickerOpen,+ syncExternalEdit,+ keepMyTemplateVersion,} = useActions(logic)const {template,@@ -47,6 +49,8 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemmessageLoading,templateLoading,templatePickerOpen,+ externallyEdited,+ isSyncingExternalEdit,} = useValues(logic)const { setIsSaveTemplateModalOpen } = useActions(emailTemplaterLogic)@@ -160,8 +164,35 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem<TemplatePickerModal isOpen={templatePickerOpen} onClose={() => setTemplatePickerOpen(false)} /><SendTestEmailModal {...props} isOpen={isSendTestEmailModalOpen} />+ {externallyEdited && (+ <LemonBanner type="warning">+ <div className="flex items-center justify-between gap-2">+ <span>+ This template was updated elsewhere (for example via the API or an AI assistant) while+ you have unsaved changes. Reload to get the latest version, or keep editing and save to+ overwrite the other changes.+ </span>+ <div className="flex items-center gap-2 shrink-0">+ <LemonButton type="secondary" size="small" onClick={() => keepMyTemplateVersion()}>+ Keep mine+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => syncExternalEdit()}+ loading={isSyncingExternalEdit}+ >+ Reload+ </LemonButton>+ </div>+ </div>+ </LemonBanner>+ )}+<div className="flex flex-col flex-1 gap-2 min-h-0 relative">- {messageLoading || templateLoading ? (+ {/* The editor stays mounted through a sync: the templater pushes the new design into the open canvas. */}+ {isSyncingExternalEdit && <SpinnerOverlay />}+ {(messageLoading || templateLoading) && !isSyncingExternalEdit ? (<Spinner className="text-lg" />) : (<EmailTemplaterdiff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.tsindex 7f757e953e47..7dbaed75ae11 100644--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.test.ts@@ -3,6 +3,9 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import type { ResourceEditedEvent } from '~/types'++import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'import { messageTemplateLogic } from './messageTemplateLogic'@@ -139,6 +142,133 @@ describe('messageTemplateLogic', () => {})})+ describe('edited elsewhere', () => {+ const LOADED_AT = '2026-01-01T00:00:00Z'+ const LATER = '2026-01-01T00:01:00Z'+ let serverTemplate: { id: string; name: string; updated_at: string }++ const edited = (overrides: Partial<ResourceEditedEvent> = {}): ResourceEditedEvent => ({+ notification_type: 'resource_edited',+ team_id: 1,+ resource_type: 'MessageTemplate',+ resource_id: 'existing-id',+ updated_at: LATER,+ actor_user_id: null,+ ...overrides,+ })++ beforeEach(async () => {+ serverTemplate = { id: 'existing-id', name: 'Existing', updated_at: LOADED_AT }+ useMocks({+ get: {+ '/api/environments/:team_id/messaging_templates/:id/': () => [200, serverTemplate],+ },+ patch: {+ '/api/environments/:team_id/messaging_templates/:id/': () => [+ 200,+ { ...serverTemplate, name: 'Saved here', updated_at: LATER },+ ],+ },+ })+ logic = messageTemplateLogic({ id: 'existing-id' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadTemplateSuccess'])+ // From here a reload shows as this name on the form.+ serverTemplate = { ...serverTemplate, name: 'Renamed by the agent', updated_at: LATER }+ })++ // A clean form takes the server copy at once. Unsaved edits get the banner instead of a silent replacement.+ it.each([+ { description: 'reloads a clean form', dirty: false, reloads: true },+ { description: 'warns instead of replacing unsaved edits', dirty: true, reloads: false },+ ])('$description', async ({ dirty, reloads }) => {+ if (dirty) {+ logic.actions.setTemplateValue('name', 'My edit')+ }++ await expectLogic(logic, () => {+ resourceEditedLogic.actions.resourceEdited(edited())+ }).toFinishAllListeners()++ await expectLogic(logic).toMatchValues({+ externallyEdited: !reloads,+ isSyncingExternalEdit: false,+ templateChanged: dirty,+ })+ expect(logic.values.template.name).toBe(reloads ? 'Renamed by the agent' : 'My edit')+ })++ it.each([+ { description: 'its own save echo', event: edited({ updated_at: LOADED_AT }) },+ { description: 'another template', event: edited({ resource_id: 'other-id' }) },+ { description: 'another resource type', event: edited({ resource_type: 'HogFlow' }) },+ ])('ignores $description', async ({ event }) => {+ await expectLogic(logic, () => {+ resourceEditedLogic.actions.resourceEdited(event)+ }).toFinishAllListeners()++ await expectLogic(logic).toMatchValues({ externallyEdited: false, isSyncingExternalEdit: false })+ expect(logic.values.template.name).toBe('Existing')+ })++ // The realtime echo of our own save can beat its HTTP response, while the loaded stamp is still the old one.+ // An external edit that lands in the same window must survive that echo.+ it.each([+ { description: 'drops the own echo once the save lands', events: [LATER], name: 'Saved here' },+ {+ description: 'keeps a newer external edit that the own echo arrived after',+ events: ['2026-01-01T00:02:00Z', LATER],+ name: 'Renamed by the agent',+ },+ ])('parks events that arrive during a save and $description', async ({ events, name }) => {+ await expectLogic(logic, () => {+ logic.actions.saveTemplate({ ...logic.values.template, name: 'Saved here' })+ events.forEach((updated_at) => resourceEditedLogic.actions.resourceEdited(edited({ updated_at })))+ })+ .toDispatchActions(['setDeferredExternalEdit', 'saveTemplateSuccess', 'replayDeferredExternalEdit'])+ .toFinishAllListeners()++ await expectLogic(logic).toMatchValues({ externallyEdited: false, deferredExternalEdit: null })+ expect(logic.values.template.name).toBe(name)+ })++ // A failed reload leaves the stale copy on the form, so the conflict must stay visible with its retry.+ it('shows the banner when the reload of a clean form fails', async () => {+ useMocks({+ get: { '/api/environments/:team_id/messaging_templates/:id/': () => [500, { detail: 'nope' }] },+ })++ await expectLogic(logic, () => {+ resourceEditedLogic.actions.resourceEdited(edited())+ })+ .toDispatchActions(['loadTemplateFailure'])+ .toFinishAllListeners()++ await expectLogic(logic).toMatchValues({ externallyEdited: true, isSyncingExternalEdit: false })+ expect(logic.values.template.name).toBe('Existing')+ })++ it('reload from the banner replaces the unsaved edits with the server copy', async () => {+ logic.actions.setTemplateValue('name', 'My edit')+ await expectLogic(logic, () => {+ resourceEditedLogic.actions.resourceEdited(edited())+ }).toMatchValues({ externallyEdited: true })++ await expectLogic(logic, () => {+ logic.actions.syncExternalEdit()+ })+ .toDispatchActions(['loadTemplateSuccess'])+ .toFinishAllListeners()++ await expectLogic(logic).toMatchValues({+ externallyEdited: false,+ isSyncingExternalEdit: false,+ templateChanged: false,+ })+ expect(logic.values.template.name).toBe('Renamed by the agent')+ })+ })+describe('starting-point picker', () => {it.each([{diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.tsindex ed7c86fa1db5..97a11167aeed 100644--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts@@ -5,13 +5,16 @@ import { loaders } from 'kea-loaders'import { beforeUnload, router } from 'kea-router'import api from 'lib/api'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'+import type { EmailTemplate } from '../../../../frontend/src/scenes/hog-functions/email-templater/types'-import type { HogFunctionType, UserBasicType } from '../../../../frontend/src/types'+import type { HogFunctionType, ResourceEditedEvent, UserBasicType } from '../../../../frontend/src/types'import { NEW_TEMPLATE } from './constants'import { MessageTemplate } from './types'@@ -23,6 +26,9 @@ export interface MessageTemplateLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface messageTemplateLogicValues {currentTeamIdStrict: number | string // teamLogic+ deferredExternalEdit: ResourceEditedEvent | null+ externallyEdited: boolean+ isSyncingExternalEdit: booleanisTemplateSubmitting: booleanisTemplateValid: booleanlogicProps: MessageTemplateLogicProps@@ -73,12 +79,18 @@ export interface messageTemplateLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface messageTemplateLogicActions {+ resourceEdited: (event: ResourceEditedEvent) => {+ event: ResourceEditedEvent+ } // resourceEditedLogicdeleteTemplate: () => {value: true}duplicateTemplate: () => {value: true}+ keepMyTemplateVersion: () => {+ value: true+ }loadMessage: () => anyloadMessageFailure: (error: string,@@ -109,6 +121,9 @@ export interface messageTemplateLogicActions {template: MessageTemplatepayload?: any}+ replayDeferredExternalEdit: () => {+ value: true+ }resetTemplate: (values?: {content: {email: EmailTemplate@@ -149,9 +164,18 @@ export interface messageTemplateLogicActions {template: MessageTemplatepayload?: any}+ setDeferredExternalEdit: (event: ResourceEditedEvent | null) => {+ event: ResourceEditedEvent | null+ }+ setExternallyEdited: (externallyEdited: boolean) => {+ externallyEdited: boolean+ }setOriginalTemplate: (template: MessageTemplate) => {template: MessageTemplate}+ setSyncingExternalEdit: (syncing: boolean) => {+ syncing: boolean+ }setTemplate: (template: MessageTemplate) => {template: MessageTemplate}@@ -255,6 +279,12 @@ export interface messageTemplateLogicActions {updated_at: string | null}}+ syncExternalEdit: () => {+ value: true+ }+ templateEditedElsewhere: (event: ResourceEditedEvent) => {+ event: ResourceEditedEvent+ }touchTemplateField: (key: string) => {key: string}@@ -281,6 +311,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([key(({ id }) => id ?? 'new'),connect(() => ({values: [teamLogic, ['currentTeamIdStrict']],+ actions: [resourceEditedLogic, ['resourceEdited']],})),actions({setTemplate: (template: MessageTemplate) => ({ template }),@@ -288,6 +319,13 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([duplicateTemplate: true,deleteTemplate: true,setTemplatePickerOpen: (open: boolean) => ({ open }),+ templateEditedElsewhere: (event: ResourceEditedEvent) => ({ event }),+ setDeferredExternalEdit: (event: ResourceEditedEvent | null) => ({ event }),+ replayDeferredExternalEdit: true,+ syncExternalEdit: true,+ keepMyTemplateVersion: true,+ setExternallyEdited: (externallyEdited: boolean) => ({ externallyEdited }),+ setSyncingExternalEdit: (syncing: boolean) => ({ syncing }),}),selectors({logicProps: [@@ -335,6 +373,29 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([setTemplatePickerOpen: (_, { open }) => open,},],+ // Another channel (the PostHog AI agent, the API, another tab) saved this template while the form+ // holds unsaved edits. The banner lets the person choose which version wins.+ externallyEdited: [+ false,+ {+ setExternallyEdited: (_, { externallyEdited }) => externallyEdited,+ },+ ],+ isSyncingExternalEdit: [+ false,+ {+ setSyncingExternalEdit: (_, { syncing }) => syncing,+ },+ ],+ // An edit event that arrived while our own save or load was in flight. Replayed once it settles.+ // The newest stamp wins, so our own echo cannot displace an external edit that arrived before it.+ deferredExternalEdit: [+ null as ResourceEditedEvent | null,+ {+ setDeferredExternalEdit: (state, { event }) =>+ !event || !state || dayjs(event.updated_at).isAfter(dayjs(state.updated_at)) ? event : state,+ },+ ],}),loaders(({ props }) => ({template: {@@ -363,7 +424,59 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([},},})),- listeners(({ actions, values }) => ({+ listeners(({ actions, props, values }) => ({+ resourceEdited: ({ event }) => {+ if (event.resource_type === 'MessageTemplate' && event.resource_id === props.id) {+ actions.templateEditedElsewhere(event)+ }+ },+ templateEditedElsewhere: ({ event }) => {+ // The echo of our own save can arrive before its response. Parked until the flight settles,+ // it then compares equal to the loaded stamp and is dropped.+ if (values.templateLoading) {+ actions.setDeferredExternalEdit(event)+ return+ }+ const loadedUpdatedAt = values.originalTemplate.updated_at+ if (!loadedUpdatedAt || !dayjs(event.updated_at).isAfter(dayjs(loadedUpdatedAt))) {+ return+ }+ if (values.templateChanged) {+ actions.setExternallyEdited(true)+ } else {+ actions.syncExternalEdit()+ }+ },+ replayDeferredExternalEdit: () => {+ const event = values.deferredExternalEdit+ if (event) {+ actions.setDeferredExternalEdit(null)+ actions.templateEditedElsewhere(event)+ }+ },+ syncExternalEdit: () => {+ actions.setSyncingExternalEdit(true)+ actions.loadTemplate()+ },+ keepMyTemplateVersion: () => {+ actions.setExternallyEdited(false)+ },+ loadTemplateFailure: () => {+ // The form is still the stale copy. The banner keeps the conflict visible and offers the retry.+ if (values.isSyncingExternalEdit) {+ actions.setSyncingExternalEdit(false)+ actions.setExternallyEdited(true)+ }+ },+ loadTemplateSuccess: ({ template }) => {+ if (values.isSyncingExternalEdit) {+ // The server copy replaces the form. A Reload from the banner discards the local edits on purpose.+ actions.resetTemplate(template)+ actions.setSyncingExternalEdit(false)+ actions.setExternallyEdited(false)+ }+ actions.replayDeferredExternalEdit()+ },submitTemplateFailure: () => {const errors = values.templateAllErrorsif (errors?.name) {@@ -373,6 +486,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([}},saveTemplateFailure: ({ errorObject }) => {+ actions.replayDeferredExternalEdit()// A 404 means the template no longer resolves for this environment - it was soft-deleted,// or it belongs to a different environment than the one currently selected.if (errorObject?.status === 404) {@@ -393,6 +507,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([actions.resetTemplate(template)actions.setOriginalTemplate(template)template.id && router.actions.replace(urls.workflowsLibraryTemplate(template.id))+ actions.replayDeferredExternalEdit()},loadMessageSuccess: async ({ message }) => {if (!message) {diff --git a/tach.toml b/tach.tomlindex f772e1cb47ad..93869edc5539 100644--- a/tach.toml+++ b/tach.toml@@ -625,6 +625,9 @@ layer = "modules"path = "products.messaging"depends_on = ["posthog",+ # Facade-only: template writes publish the realtime edited-elsewhere event through+ # products.notifications.backend.facade.api.+ "products.notifications",]layer = "modules"