: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(messaging): tag email templates and filter the library by tag (#120931)
Meikel Ratz710841b6686f
diff --git a/posthog/models/tagged_item_registry.py b/posthog/models/tagged_item_registry.pyindex 3141608dcae5..fdcd028734b0 100644--- a/posthog/models/tagged_item_registry.py+++ b/posthog/models/tagged_item_registry.py@@ -77,6 +77,7 @@ TAGGABLE_MODELS: tuple[TaggableModel, ...] = (TaggableModel(model_label="experiments.Experiment", legacy_field="experiment", object_field=OBJECT_ID),TaggableModel(model_label="tasks.Task", legacy_field="task", object_field=OBJECT_UUID),TaggableModel(model_label="workflows.HogFlow", legacy_field="hog_flow", object_field=OBJECT_UUID),+ TaggableModel(model_label="messaging.MessageTemplate", legacy_field="message_template", object_field=OBJECT_UUID),)_BY_LABEL: dict[str, TaggableModel] = {entry.model_label: entry for entry in TAGGABLE_MODELS}diff --git a/products/messaging/backend/facade/templates.py b/products/messaging/backend/facade/templates.pyindex 4ddaca4df6d0..24033eb2ec79 100644--- a/products/messaging/backend/facade/templates.py+++ b/products/messaging/backend/facade/templates.py@@ -7,6 +7,7 @@ from uuid import UUIDfrom django.core.exceptions import ObjectDoesNotExist, ValidationError+from posthog.api.tagged_item import current_tag_namesfrom posthog.dataclasses import frozenfrom products.messaging.backend.models.message_template import MessageTemplate@@ -37,6 +38,8 @@ class MessageTemplateRow:transactional_hog_flow_id: UUID | Nonedraft_content: dict[str, Any] | Nonesensitive: bool+ # Tag names, sorted. Keeps its default last, so every field without one stays above it.+ tags: tuple[str, ...] = ()def _to_contract(row: MessageTemplate) -> MessageTemplateRow:@@ -54,6 +57,7 @@ def _to_contract(row: MessageTemplate) -> MessageTemplateRow:transactional_hog_flow_id=row.transactional_hog_flow_id,draft_content=row.draft_content,sensitive=row.sensitive,+ tags=tuple(sorted(current_tag_names(row))),)diff --git a/products/messaging/backend/models/message_template.py b/products/messaging/backend/models/message_template.pyindex cdda6142dfb8..dbfbb701529d 100644--- a/products/messaging/backend/models/message_template.py+++ b/products/messaging/backend/models/message_template.py@@ -1,9 +1,11 @@from django.db import models+from posthog.models.tagged_items_relation import Taggablefrom posthog.models.utils import UUIDTModel-class MessageTemplate(UUIDTModel):+# nosemgrep: no-new-uuidt-models -- an existing model, and its stored ids cannot change.+class MessageTemplate(Taggable, UUIDTModel):"""A model for storing message templates used for email and eventually other messaging channels."""diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.pyindex c2e307bb8b6c..69592fb4079e 100644--- a/products/messaging/backend/presentation/views/message_templates.py+++ b/products/messaging/backend/presentation/views/message_templates.py@@ -29,6 +29,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.auth import ProjectSecretAPIKeyAuthenticationfrom posthog.event_usage import groups, report_user_actionfrom posthog.models import User+from posthog.models.tag import tagifyfrom posthog.permissions import is_authenticated_via_project_secret_api_keyfrom posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle@@ -177,6 +178,11 @@ class MessageTemplateCategoryField(serializers.Field):return value+# Each tag costs get_or_create round trips in set_tags_on_object, so cap the list.+_MAX_TEMPLATE_TAGS = 10+_MAX_TAG_LENGTH = 255 # Tag.name column limit.++class MessageTemplateSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True)name = serializers.CharField(max_length=400, help_text="Human-readable template name shown in the library.")@@ -186,6 +192,15 @@ class MessageTemplateSerializer(serializers.Serializer):style={"base_template": "textarea.html"},help_text="What the template is for and when to use it.",)+ tags = serializers.ListField(+ child=serializers.CharField(max_length=_MAX_TAG_LENGTH),+ required=False,+ max_length=_MAX_TEMPLATE_TAGS,+ help_text=(+ "Tags for organizing templates, for example by team or use case. Tags are shared with the rest of "+ "the project. Omit to keep the current tags, send an empty list to remove them all."+ ),+ )created_at = serializers.DateTimeField(read_only=True)updated_at = serializers.DateTimeField(read_only=True)content = MessageTemplateContentSerializer(@@ -225,6 +240,13 @@ class MessageTemplateSerializer(serializers.Serializer):"`content` publishes it and clears the draft. Set null to discard the draft.",)+ def validate_tags(self, tags: list[str]) -> list[str]:+ # The stored name is the tagified one, and lowercasing can lengthen a string: "\u0130" becomes two+ # code points. Checking the submitted length alone lets an over-long name reach Tag.name.+ if any(len(tagify(tag)) > _MAX_TAG_LENGTH for tag in tags):+ raise serializers.ValidationError(f"A tag may be at most {_MAX_TAG_LENGTH} characters once lowercased.")+ return tags+def validate(self, data: Any) -> Any:template_type = data.get("type")email = data.get("content", {}).get("email") if data.get("content") else None@@ -493,6 +515,12 @@ class MessageTemplatesViewSet(updated = save_template_draft(self.team_id, template.id, fields["draft_content"])self._emit_resource_edited(updated)return Response(self._serialize(updated))+ if fields.keys() == {"tags"}:+ # Tags are library metadata. Sends never read them, so a tag edit skips the sendability check+ # and must not write a new version of the template's transactional workflow.+ updated = update_template(self.team_id, template.id, fields)+ self._emit_resource_edited(updated)+ return Response(self._serialize(updated))if "content" in fields:fields["draft_content"] = None# Sends use the workflow's copy, so the template and its new workflow version are saved together,diff --git a/products/messaging/backend/services/message_templates.py b/products/messaging/backend/services/message_templates.pyindex 36ea21902506..ce0fc04b7331 100644--- a/products/messaging/backend/services/message_templates.py+++ b/products/messaging/backend/services/message_templates.py@@ -8,6 +8,10 @@ from django.db.models.fields.json import KTfrom django.db.models.functions import Castfrom django.utils import timezone+from posthog.api.tagged_item import cleanup_orphan_tags, current_tag_names, set_tags_on_object+from posthog.models import TaggedItem+from posthog.models.tag import tagify+from products.messaging.backend.facade.contracts import EmailTemplateSummaryfrom products.messaging.backend.models import MessageCategory, MessageTemplate@@ -70,9 +74,16 @@ def rewrite_content(return occurrences+def _with_tags(queryset: models.QuerySet[MessageTemplate]) -> models.QuerySet[MessageTemplate]:+ # The contract reads prefetched_tags, so a page costs one tag query rather than one per row.+ return queryset.prefetch_related(+ models.Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags")+ )++def team_templates(team_id: int) -> models.QuerySet[MessageTemplate]:# The pk tiebreak keeps pages stable, as the mixin ordering did for the queryset view.- return MessageTemplate.objects.filter(team_id=team_id, deleted=False).order_by("-created_at", "-pk")+ return _with_tags(MessageTemplate.objects.filter(team_id=team_id, deleted=False)).order_by("-created_at", "-pk")def team_template(team_id: int, template_id: UUID | str) -> MessageTemplate:@@ -90,16 +101,32 @@ def _apply_fields(template: MessageTemplate, fields: dict[str, Any]) -> None:def create_template(team_id: int, created_by_id: int | None, fields: dict[str, Any]) -> MessageTemplate:- template = MessageTemplate(team_id=team_id, created_by_id=created_by_id)- _apply_fields(template, fields)- template.save(force_insert=True)+ fields = dict(fields)+ tags = fields.pop("tags", None)+ with transaction.atomic():+ template = MessageTemplate(team_id=team_id, created_by_id=created_by_id)+ _apply_fields(template, fields)+ template.save(force_insert=True)+ if tags:+ set_tags_on_object(tags, template)return templatedef update_template(team_id: int, template_id: UUID | str, fields: dict[str, Any]) -> MessageTemplate:- template = team_template(team_id, template_id)- _apply_fields(template, fields)- template.save()+ fields = dict(fields)+ tags = fields.pop("tags", None)+ with transaction.atomic():+ template = team_template(team_id, template_id)+ # The editor sends the tags with every save, so only write them when they change.+ tags_changed = tags is not None and {tagify(tag) for tag in tags} != current_tag_names(template)+ # Tags live on their own rows. Saving the template too would write back every column this+ # read saw, so a tag edit would overwrite content a concurrent publish had just committed.+ if fields:+ _apply_fields(template, fields)+ template.save()+ if tags_changed:+ set_tags_on_object(tags, template)+ cleanup_orphan_tags(team_id)return templatediff --git a/products/messaging/backend/tests/api/test_message_templates.py b/products/messaging/backend/tests/api/test_message_templates.pyindex e65057fc9481..326e1a3a17e8 100644--- a/products/messaging/backend/tests/api/test_message_templates.py+++ b/products/messaging/backend/tests/api/test_message_templates.py@@ -78,6 +78,58 @@ class TestMessageTemplatesAPI(APIBaseTest):assert pages == [[str(ids[2]), str(ids[1])], [str(ids[0]), str(self.message_template.id)]]+ def test_tags_round_trip_through_create_update_and_list(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/messaging_templates/",+ {+ "name": "Tagged",+ "content": {"email": {"subject": "Hi", "text": "Body"}},+ "type": "email",+ "tags": ["Onboarding", "growth"],+ },+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ template_id = response.json()["id"]+ assert response.json()["tags"] == ["growth", "onboarding"]++ url = f"/api/projects/{self.team.id}/messaging_templates/{template_id}/"+ response = self.client.patch(url, {"name": "Renamed"}, format="json")+ assert response.json()["tags"] == ["growth", "onboarding"]++ response = self.client.patch(url, {"tags": ["growth"]}, format="json")+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["tags"] == ["growth"]++ listed = self.client.get(f"/api/projects/{self.team.id}/messaging_templates/").json()["results"]+ assert {row["id"]: row["tags"] for row in listed}[template_id] == ["growth"]++ response = self.client.patch(url, {"tags": []}, format="json")+ assert response.json()["tags"] == []++ def test_rejects_a_tag_that_grows_past_the_column_limit_when_lowercased(self):+ # "\u0130" lowercases to two code points, so 128 of them fit the field but not Tag.name.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/",+ {"tags": ["\u0130" * 128]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_tags_only_update_leaves_the_template_row_alone(self):+ before = MessageTemplate.objects.get(pk=self.message_template.id).updated_at++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/",+ {"tags": ["growth"]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["tags"] == ["growth"]+ # A row save here would write back every column this request read, losing a concurrent content edit.+ assert MessageTemplate.objects.get(pk=self.message_template.id).updated_at == before+def test_retrieve_message_template(self):response = self.client.get(f"/api/environments/{self.team.id}/messaging_templates/{self.message_template.id}/")assert response.status_code == status.HTTP_200_OKdiff --git a/products/messaging/backend/tests/api/test_transactional_email.py b/products/messaging/backend/tests/api/test_transactional_email.pyindex a6fdf900ecf9..7ab7b9b227dc 100644--- a/products/messaging/backend/tests/api/test_transactional_email.py+++ b/products/messaging/backend/tests/api/test_transactional_email.py@@ -397,6 +397,20 @@ class TestTransactionalEmail(APIBaseTest):self.template.refresh_from_db()assert self.template.deleted+ def test_tagging_a_transactional_template_leaves_its_workflow_untouched(self, mock_post, _flag, _capture):+ before = self._workflow(self.hog_flow_id)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/messaging_templates/{self.template.id}/",+ {"tags": ["growth"]},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["tags"] == ["growth"]+ after = self._workflow(self.hog_flow_id)+ assert (after["version"], after["updated_at"]) == (before["version"], before["updated_at"])+def test_rejects_an_update_that_would_stop_a_transactional_template_sending(self, mock_post, _flag, _capture):category = MessageCategory.objects.create(team=self.team, key="news", name="News", category_type=MessageCategoryType.MARKETINGdiff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex ee1430abd4c7..879c33567d85 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -380,6 +380,12 @@ export interface MessageTemplateApi {name: string/** What the template is for and when to use it. */description?: string+ /**+ * Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[]readonly created_at: stringreadonly updated_at: string/** Template content keyed by channel. Replaced as a whole on update, not merged. */@@ -426,6 +432,12 @@ export interface PatchedMessageTemplateApi {name?: string/** What the template is for and when to use it. */description?: string+ /**+ * Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[]readonly created_at?: stringreadonly updated_at?: string/** Template content keyed by channel. Replaced as a whole on update, not merged. */diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.tsindex 4b463f034491..6adc370fab50 100644--- a/products/messaging/frontend/generated/api.zod.ts+++ b/products/messaging/frontend/generated/api.zod.ts@@ -253,6 +253,10 @@ export const MessagingSuppressionsRemoveSuppressionCreateBody = /* @__PURE__ */export const messagingTemplatesCreateBodyNameMax = 400+export const messagingTemplatesCreateBodyTagsItemMax = 255++export const messagingTemplatesCreateBodyTagsMax = 10+export const messagingTemplatesCreateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesCreateBodyTypeMax = 24@@ -264,6 +268,13 @@ export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({.max(messagingTemplatesCreateBodyNameMax).describe('Human-readable template name shown in the library.'),description: zod.string().optional().describe('What the template is for and when to use it.'),+ tags: zod+ .array(zod.string().max(messagingTemplatesCreateBodyTagsItemMax))+ .max(messagingTemplatesCreateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),content: zod.object({templating: zod@@ -433,6 +444,10 @@ export const MessagingTemplatesCreateBody = /* @__PURE__ */ zod.object({export const messagingTemplatesUpdateBodyNameMax = 400+export const messagingTemplatesUpdateBodyTagsItemMax = 255++export const messagingTemplatesUpdateBodyTagsMax = 10+export const messagingTemplatesUpdateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesUpdateBodyTypeMax = 24@@ -444,6 +459,13 @@ export const MessagingTemplatesUpdateBody = /* @__PURE__ */ zod.object({.max(messagingTemplatesUpdateBodyNameMax).describe('Human-readable template name shown in the library.'),description: zod.string().optional().describe('What the template is for and when to use it.'),+ tags: zod+ .array(zod.string().max(messagingTemplatesUpdateBodyTagsItemMax))+ .max(messagingTemplatesUpdateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),content: zod.object({templating: zod@@ -613,6 +635,10 @@ export const MessagingTemplatesUpdateBody = /* @__PURE__ */ zod.object({export const messagingTemplatesPartialUpdateBodyNameMax = 400+export const messagingTemplatesPartialUpdateBodyTagsItemMax = 255++export const messagingTemplatesPartialUpdateBodyTagsMax = 10+export const messagingTemplatesPartialUpdateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesPartialUpdateBodyTypeMax = 24@@ -625,6 +651,13 @@ export const MessagingTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({.optional().describe('Human-readable template name shown in the library.'),description: zod.string().optional().describe('What the template is for and when to use it.'),+ tags: zod+ .array(zod.string().max(messagingTemplatesPartialUpdateBodyTagsItemMax))+ .max(messagingTemplatesPartialUpdateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),content: zod.object({templating: zoddiff --git a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsxindex 885f5ce10d86..335473d96d4e 100644--- a/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx+++ b/products/workflows/frontend/TemplateLibrary/MessageTemplate.tsx@@ -15,6 +15,7 @@ import {Tooltip,} from '@posthog/lemon-ui'+import { SceneTags } from 'lib/components/Scenes/SceneTags'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'@@ -68,6 +69,7 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.ElemkeepMyTemplateVersion,setTransactionalTab,discardDraft,+ saveTags,setSensitive,} = useActions(logic)const {@@ -404,6 +406,13 @@ export function MessageTemplate(props: MessageTemplateSceneLogicProps): JSX.Elem}/>+ <SceneTags+ tags={[...(template.tags ?? [])]}+ onSave={saveTags}+ loading={isTemplateSubmitting}+ dataAttrKey="message-template"+ />+<TemplatePickerModal isOpen={templatePickerOpen} onClose={() => setTemplatePickerOpen(false)} /><SendTestEmailModal {...props} isOpen={isSendTestEmailModalOpen} />diff --git a/products/workflows/frontend/TemplateLibrary/MessageTemplateCard.tsx b/products/workflows/frontend/TemplateLibrary/MessageTemplateCard.tsxindex 4e96a05cde49..5a76815a1de0 100644--- a/products/workflows/frontend/TemplateLibrary/MessageTemplateCard.tsx+++ b/products/workflows/frontend/TemplateLibrary/MessageTemplateCard.tsx@@ -1,6 +1,7 @@import { LemonTag } from '@posthog/lemon-ui'import { FallbackCoverImage } from 'lib/components/FallbackCoverImage/FallbackCoverImage'+import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { TZLabel } from 'lib/components/TZLabel'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'@@ -11,11 +12,13 @@ export function MessageTemplateCard({index,onClick,actions,+ onTagClick,}: {template: MessageTemplateindex: numberonClick: () => voidactions?: React.ReactNode+ onTagClick?: (tag: string) => void}): JSX.Element {const emailHtml = template.content?.email?.html@@ -52,6 +55,17 @@ export function MessageTemplateCard({{template.description && (<p className="text-secondary text-xs line-clamp-1 mb-1">{template.description}</p>)}+ {!!template.tags?.length && (+ <div className="mb-1" onClick={(e) => e.stopPropagation()}>+ <ObjectTags+ tags={[...template.tags]}+ staticOnly+ onTagClick={onTagClick}+ maxVisibleTags={3}+ data-attr="message-template-tags"+ />+ </div>+ )}{(template.created_by || template.created_at) && (<div className="flex items-center gap-2 text-xs text-secondary">{template.created_by && <ProfilePicture user={template.created_by} size="sm" showName />}diff --git a/products/workflows/frontend/TemplateLibrary/MessageTemplatesTable.tsx b/products/workflows/frontend/TemplateLibrary/MessageTemplatesTable.tsxindex 62eeb6389858..d042857c11d6 100644--- a/products/workflows/frontend/TemplateLibrary/MessageTemplatesTable.tsx+++ b/products/workflows/frontend/TemplateLibrary/MessageTemplatesTable.tsx@@ -10,10 +10,15 @@ import { LemonCheckbox } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'import { MemberSelect } from 'lib/components/MemberSelect'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { TagSelect } from 'lib/components/TagSelect'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'+import { lemonToast } from 'lib/lemon-ui/LemonToast'import { Spinner } from 'lib/lemon-ui/Spinner'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import MaxTool from 'scenes/max/MaxTool'@@ -22,17 +27,32 @@ import { urls } from 'scenes/urls'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { MessageTemplateCard } from './MessageTemplateCard'-import { messageTemplatesLogic } from './messageTemplatesLogic'+import { messageTemplatesLogic, saveTemplateTags } from './messageTemplatesLogic'import { newTemplateAgentLogic } from './newTemplateAgentLogic'const HedgehogReadingIsMagic = pngHoggie(readingIsMagicPng)export function MessageTemplatesTable(): JSX.Element {useMountedLogic(messageTemplatesLogic)- const { filteredTemplates, templates, templatesLoading, search, createdByFilter, transactionalOnly } =- useValues(messageTemplatesLogic)- const { deleteTemplate, createTemplate, duplicateTemplate, setSearch, setCreatedByFilter, setTransactionalOnly } =- useActions(messageTemplatesLogic)+ const {+ filteredTemplates,+ templates,+ templatesLoading,+ search,+ createdByFilter,+ transactionalOnly,+ tagsFilter,+ tags: allTags,+ } = useValues(messageTemplatesLogic)+ const {+ deleteTemplate,+ createTemplate,+ duplicateTemplate,+ setSearch,+ setCreatedByFilter,+ setTransactionalOnly,+ setTagsFilter,+ } = useActions(messageTemplatesLogic)const transactionalEmailsEnabled = useFeatureFlag('WORKFLOWS_TRANSACTIONAL_EMAIL_API')const { startNewTemplate } = useActions(newTemplateAgentLogic)@@ -76,6 +96,16 @@ export function MessageTemplatesTable(): JSX.Element {<span className="text-secondary whitespace-nowrap">Created by:</span><MemberSelect value={createdByFilter} onChange={(user) => setCreatedByFilter(user?.id ?? null)} /></div>+ <div className="flex items-center gap-2">+ <span className="text-secondary whitespace-nowrap">Tags:</span>+ <TagSelect+ size="small"+ defaultLabel="Any tags"+ value={tagsFilter}+ onChange={setTagsFilter}+ listDataAttr="templates-tags-filter-list"+ />+ </div>{transactionalEmailsEnabled && (<LemonCheckboxlabel="Transactional only"@@ -119,6 +149,7 @@ export function MessageTemplatesTable(): JSX.Element {template={template}index={index}onClick={() => router.actions.push(urls.workflowsLibraryTemplate(template.id))}+ onTagClick={(tag) => !tagsFilter.includes(tag) && setTagsFilter([...tagsFilter, tag])}actions={<Moresize="small"@@ -129,6 +160,42 @@ export function MessageTemplatesTable(): JSX.Element {label: 'Duplicate',onClick: () => duplicateTemplate(template),},+ {+ label: 'Edit tags',+ onClick: () =>+ LemonDialog.openForm({+ title: 'Edit tags',+ // A rejected save keeps the dialog open, so the+ // selection survives a validation error or a retry.+ shouldAwaitSubmit: true,+ initialValues: { tags: [...(template.tags ?? [])] },+ content: (+ <LemonField name="tags">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ options={allTags.map((tag) => ({+ key: tag,+ label: tag,+ }))}+ placeholder='try "growth"'+ autoFocus+ data-attr="template-tags-input"+ />+ </LemonField>+ ),+ onSubmit: async ({ tags }) => {+ try {+ await saveTemplateTags(template, tags)+ } catch (error: any) {+ lemonToast.error(+ `Failed to save tags: ${error?.detail || error?.message || 'Unknown error'}`+ )+ throw error+ }+ },+ }),+ },{label: 'Delete',status: 'danger' as const,diff --git a/products/workflows/frontend/TemplateLibrary/constants.ts b/products/workflows/frontend/TemplateLibrary/constants.tsindex a1920c3fcebc..5f0da6261b3f 100644--- a/products/workflows/frontend/TemplateLibrary/constants.ts+++ b/products/workflows/frontend/TemplateLibrary/constants.ts@@ -4,6 +4,7 @@ export const NEW_TEMPLATE: MessageTemplate = {id: 'new',name: 'Untitled email',description: '',+ tags: [],content: {templating: 'liquid' as const,email: {diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.tsindex f5bafce1ea72..3dc1a4cd444a 100644--- a/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts+++ b/products/workflows/frontend/TemplateLibrary/messageTemplateLogic.ts@@ -90,6 +90,7 @@ export interface messageTemplateLogicValues {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null},@@ -114,6 +115,7 @@ export interface messageTemplateLogicValues {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null},@@ -200,6 +202,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}) => {@@ -215,6 +218,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}@@ -235,6 +239,9 @@ export interface messageTemplateLogicActions {saveDraftFailed: () => {value: true}+ saveTags: (tags: string[]) => {+ tags: string[]+ }saveTemplate: (template: any) => anysaveTemplateFailure: (error: string,@@ -310,6 +317,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}>@@ -326,6 +334,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}>@@ -355,6 +364,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}) => {@@ -370,6 +380,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}@@ -386,6 +397,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}) => {@@ -401,6 +413,7 @@ export interface messageTemplateLogicActions {id: stringname: stringsensitive?: boolean | undefined+ tags?: string[] | undefinedtransactional_hog_flow_id?: string | null | undefinedupdated_at: string | null}@@ -471,6 +484,7 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([duplicateTemplate: true,deleteTemplate: true,setTemplatePickerOpen: (open: boolean) => ({ open }),+ saveTags: (tags: string[]) => ({ tags }),templateEditedElsewhere: (event: ResourceEditedEvent) => ({ event }),setDeferredExternalEdit: (event: ResourceEditedEvent | null) => ({ event }),replayDeferredExternalEdit: true,@@ -676,8 +690,9 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([},saveTemplate: async (template) => {// Saving the content publishes it, and the server clears the draft. The sensitive setting- // saves on its own, so a publish never sends it and can't undo a change still in flight.- const { sensitive: _sensitive, ...content } = template+ // and the tags each save on their own, so a publish never sends them and can't undo a+ // change made in another tab since this one loaded the template.+ const { sensitive: _sensitive, tags: _tags, ...content } = templateconst saved =template.id === 'new'? await api.messaging.createTemplate(template)@@ -741,6 +756,31 @@ export const messageTemplateLogic = kea<messageTemplateLogicType>([actions.autoSaveDraft()},setTemplateValue: () => actions.autoSaveDraft(),+ saveTags: async ({ tags }, breakpoint) => {+ // An unsaved template has no row yet, so its tags ride the create.+ if (!props.id || props.id === 'new') {+ actions.setTemplateValue('tags', tags)+ return+ }+ // The editor fires one save per tag added or removed. Without this, a burst of clicks puts+ // several writes in flight at once, and the one that lands last wins rather than the latest+ // selection. The wait collapses the burst into a single write.+ await breakpoint(300)+ // Tags are metadata: they apply live and must not publish a transactional template's draft,+ // which a full form save would.+ let updated: MessageTemplate+ try {+ updated = await api.messaging.updateTemplate(props.id, { tags })+ } catch (error: any) {+ lemonToast.error(`Failed to save tags: ${error?.detail || error?.message || 'Unknown error'}`)+ return+ }+ // Outside the catch: a breakpoint throws to unwind a superseded listener, and catching that+ // would report it as a failed save.+ breakpoint()+ actions.setTemplate({ ...values.template, tags: updated.tags })+ actions.setOriginalTemplate({ ...values.originalTemplate, tags: updated.tags })+ },setTemplateValues: () => actions.autoSaveDraft(),autoSaveDraft: async (_, breakpoint) => {if (!values.draftsEnabled) {diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.test.ts b/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.test.tsnew file mode 100644index 000000000000..9e686e1c311d--- /dev/null+++ b/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.test.ts@@ -0,0 +1,81 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { messageTemplatesLogic, saveTemplateTags } from './messageTemplatesLogic'+import type { MessageTemplate } from './types'++const template = (id: string, name: string, tags: string[]): MessageTemplate =>+ ({ id, name, description: '', tags }) as unknown as MessageTemplate++describe('messageTemplatesLogic', () => {+ let logic: ReturnType<typeof messageTemplatesLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team_id/messaging_templates/': {+ results: [+ template('a', 'Welcome', ['growth', 'onboarding']),+ template('b', 'Invoice', ['billing']),+ template('c', 'Plain', []),+ ],+ },+ '/api/projects/:team_id/tags': ['billing', 'growth', 'onboarding'],+ },+ })+ initKeaTests()+ logic = messageTemplatesLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it.each([+ ['tag filter', { tagsFilter: ['growth'] }, ['Welcome']],+ ['tag filter matching any', { tagsFilter: ['growth', 'billing'] }, ['Welcome', 'Invoice']],+ ['search by tag name', { search: 'onboard' }, ['Welcome']],+ ['search by name still works', { search: 'invoice' }, ['Invoice']],+ ])('filters the library by %s', async (_name, filters: any, expected) => {+ await expectLogic(logic).toFinishAllListeners()+ if (filters.tagsFilter) {+ logic.actions.setTagsFilter(filters.tagsFilter)+ }+ if (filters.search) {+ logic.actions.setSearch(filters.search)+ }++ expect(logic.values.filteredTemplates.map((t) => t.name)).toEqual(expected)+ })++ it('saves a tag edit with only the tags, so it never republishes the content', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const bodies: unknown[] = []+ useMocks({+ patch: {+ '/api/projects/:team_id/messaging_templates/:id/': async ({ request }) => {+ bodies.push(await request.json())+ return [200, template('a', 'Welcome', ['growth'])]+ },+ },+ })++ await saveTemplateTags(template('a', 'Welcome', []), ['growth'])++ expect(bodies).toEqual([{ tags: ['growth'] }])+ expect(logic.values.templates.find((t) => t.id === 'a')?.tags).toEqual(['growth'])+ })++ it('rejects a failed tag save, so the editor it was opened from stays open', async () => {+ await expectLogic(logic).toFinishAllListeners()+ useMocks({+ patch: {+ '/api/projects/:team_id/messaging_templates/:id/': () => [400, { detail: 'too many tags' }],+ },+ })++ await expect(saveTemplateTags(template('a', 'Welcome', []), ['growth'])).rejects.toThrow()+ expect(logic.values.templates.find((t) => t.id === 'a')?.tags).toEqual(['growth', 'onboarding'])+ })+})diff --git a/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.ts b/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.tsindex e63b5074ef8d..b216d5931008 100644--- a/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.ts+++ b/products/workflows/frontend/TemplateLibrary/messageTemplatesLogic.ts@@ -6,16 +6,20 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { teamLogic } from 'scenes/teamLogic'+import { tagsModel } from '~/models/tagsModel'+import { MessageTemplate } from './types'export type { MessageTemplate }// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface messageTemplatesLogicValues {+ tags: string[] // tagsModelcurrentTeamIdStrict: number | string // teamLogiccreatedByFilter: number | nullfilteredTemplates: MessageTemplate[]search: string+ tagsFilter: string[]templates: MessageTemplate[]templatesLoading: booleantransactionalOnly: boolean@@ -23,6 +27,12 @@ export interface messageTemplatesLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface messageTemplatesLogicActions {+ loadTags: () => {+ value: true+ } // tagsModel+ loadTagsIfNeeded: () => {+ value: true+ } // tagsModelcreateTemplate: ({ template }: { template: Partial<MessageTemplate> }) => {template: Partial<MessageTemplate>}@@ -95,9 +105,15 @@ export interface messageTemplatesLogicActions {setSearch: (search: string) => {search: string}+ setTagsFilter: (tagsFilter: string[]) => {+ tagsFilter: string[]+ }setTransactionalOnly: (transactionalOnly: boolean) => {transactionalOnly: boolean}+ templateTagsSaved: (template: MessageTemplate) => {+ template: MessageTemplate+ }updateTemplate: ({ templateId, template }: { template: Partial<MessageTemplate>; templateId: string }) => {templateId: stringtemplate: Partial<MessageTemplate>@@ -131,7 +147,8 @@ export interface messageTemplatesLogicMeta {templates: MessageTemplate[],search: string,createdByFilter: number | null,- transactionalOnly: boolean+ transactionalOnly: boolean,+ tagsFilter: string[]) => MessageTemplate[]}}@@ -146,17 +163,28 @@ export type messageTemplatesLogicType = MakeLogicType<export const messageTemplatesLogic = kea<messageTemplatesLogicType>([path(['products', 'workflows', 'frontend', 'library', 'messageTemplatesLogic']),connect(() => ({- values: [teamLogic, ['currentTeamIdStrict']],+ values: [teamLogic, ['currentTeamIdStrict'], tagsModel, ['tags']],+ actions: [tagsModel, ['loadTags', 'loadTagsIfNeeded']],})),actions({setSearch: (search: string) => ({ search }),setCreatedByFilter: (createdBy: number | null) => ({ createdBy }),setTransactionalOnly: (transactionalOnly: boolean) => ({ transactionalOnly }),+ setTagsFilter: (tagsFilter: string[]) => ({ tagsFilter }),+ templateTagsSaved: (template: MessageTemplate) => ({ template }),}),reducers({search: ['' as string, { setSearch: (_, { search }) => search }],createdByFilter: [null as number | null, { setCreatedByFilter: (_, { createdBy }) => createdBy }],transactionalOnly: [false, { setTransactionalOnly: (_, { transactionalOnly }) => transactionalOnly }],+ tagsFilter: [[] as string[], { setTagsFilter: (_, { tagsFilter }) => tagsFilter }],+ templates: [+ [] as MessageTemplate[],+ {+ templateTagsSaved: (state, { template }) =>+ state.map((t: MessageTemplate) => (t.id === template.id ? template : t)),+ },+ ],}),loaders(({ values, actions }) => ({templates: [@@ -226,12 +254,13 @@ export const messageTemplatesLogic = kea<messageTemplatesLogicType>([})),selectors({filteredTemplates: [- (s) => [s.templates, s.search, s.createdByFilter, s.transactionalOnly],+ (s) => [s.templates, s.search, s.createdByFilter, s.transactionalOnly, s.tagsFilter],(templates: MessageTemplate[],search: string,createdByFilter: number | null,- transactionalOnly: boolean+ transactionalOnly: boolean,+ tagsFilter: string[]): MessageTemplate[] => {let filtered = templatesif (search) {@@ -239,9 +268,13 @@ export const messageTemplatesLogic = kea<messageTemplatesLogicType>([filtered = filtered.filter((t) =>(t.name ?? '').toLowerCase().includes(lowerSearch) ||- (t.description ?? '').toLowerCase().includes(lowerSearch)+ (t.description ?? '').toLowerCase().includes(lowerSearch) ||+ (t.tags ?? []).some((tag) => tag.toLowerCase().includes(lowerSearch)))}+ if (tagsFilter.length) {+ filtered = filtered.filter((t) => (t.tags ?? []).some((tag) => tagsFilter.includes(tag)))+ }if (createdByFilter !== null) {filtered = filtered.filter((t) => t.created_by?.id === createdByFilter)}@@ -254,5 +287,14 @@ export const messageTemplatesLogic = kea<messageTemplatesLogicType>([}),afterMount(({ actions }) => {actions.loadTemplates()+ actions.loadTagsIfNeeded()}),])++// A plain function rather than a listener, because the caller awaits it to keep its editor open on+// a rejection, and a kea listener that rethrows raises an unhandled rejection on the way out.+export async function saveTemplateTags(template: MessageTemplate, tags: string[]): Promise<void> {+ const updated = await api.messaging.updateTemplate(template.id, { tags })+ messageTemplatesLogic.findMounted()?.actions.templateTagsSaved(updated)+ tagsModel.findMounted()?.actions.loadTags()+}diff --git a/products/workflows/frontend/TemplateLibrary/types.ts b/products/workflows/frontend/TemplateLibrary/types.tsindex b7abd6019c09..c55a39f5e7a9 100644--- a/products/workflows/frontend/TemplateLibrary/types.ts+++ b/products/workflows/frontend/TemplateLibrary/types.ts@@ -18,4 +18,5 @@ export interface MessageTemplate {transactional_hog_flow_id?: MessageTemplateApi['transactional_hog_flow_id']draft_content?: MessageTemplateApi['draft_content']sensitive?: MessageTemplateApi['sensitive']+ tags?: MessageTemplateApi['tags']}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b7a2225ae595..53768a16c984 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -68604,6 +68604,12 @@ export namespace Schemas {name: string;/** What the template is for and when to use it. */description?: string;+ /**+ * Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[];readonly created_at: string;readonly updated_at: string;/** Template content keyed by channel. Replaced as a whole on update, not merged. */@@ -84608,6 +84614,12 @@ export namespace Schemas {name?: string;/** What the template is for and when to use it. */description?: string;+ /**+ * Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[];readonly created_at?: string;readonly updated_at?: string;/** Template content keyed by channel. Replaced as a whole on update, not merged. */diff --git a/services/mcp/src/generated/email_templates/api.ts b/services/mcp/src/generated/email_templates/api.tsindex 6f2070c225fb..12d6a3c232fa 100644--- a/services/mcp/src/generated/email_templates/api.ts+++ b/services/mcp/src/generated/email_templates/api.ts@@ -31,6 +31,10 @@ export const MessagingTemplatesCreateParams = () => zod.object({export const messagingTemplatesCreateBodyNameMax = 400+export const messagingTemplatesCreateBodyTagsItemMax = 255++export const messagingTemplatesCreateBodyTagsMax = 10+export const messagingTemplatesCreateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesCreateBodyTypeMax = 24@@ -40,6 +44,13 @@ export const MessagingTemplatesCreateBody = () => zod.object({.max(messagingTemplatesCreateBodyNameMax).describe('Human-readable template name shown in the library.'),description: zod.string().optional().describe('What the template is for and when to use it.'),+ tags: zod+ .array(zod.string().max(messagingTemplatesCreateBodyTagsItemMax))+ .max(messagingTemplatesCreateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),content: zod.object({templating: zod@@ -144,6 +155,10 @@ export const MessagingTemplatesPartialUpdateParams = () => zod.object({export const messagingTemplatesPartialUpdateBodyNameMax = 400+export const messagingTemplatesPartialUpdateBodyTagsItemMax = 255++export const messagingTemplatesPartialUpdateBodyTagsMax = 10+export const messagingTemplatesPartialUpdateBodyContentOneTemplatingDefault = `liquid`export const messagingTemplatesPartialUpdateBodyTypeMax = 24@@ -154,6 +169,13 @@ export const MessagingTemplatesPartialUpdateBody = () => zod.object({.optional().describe('Human-readable template name shown in the library.'),description: zod.string().optional().describe('What the template is for and when to use it.'),+ tags: zod+ .array(zod.string().max(messagingTemplatesPartialUpdateBodyTagsItemMax))+ .max(messagingTemplatesPartialUpdateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),content: zod.object({templating: zoddiff --git a/services/mcp/src/tools/generated/email_templates.ts b/services/mcp/src/tools/generated/email_templates.tsindex 316692ea3039..4771f42e4c62 100644--- a/services/mcp/src/tools/generated/email_templates.ts+++ b/services/mcp/src/tools/generated/email_templates.ts@@ -28,6 +28,9 @@ const workflowsCreateEmailTemplate = (): ToolBase<if (params.description !== undefined) {body['description'] = params.description}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }if (params.content !== undefined) {body['content'] = params.content}@@ -193,6 +196,9 @@ const workflowsUpdateEmailTemplate = (): ToolBase<if (params.description !== undefined) {body['description'] = params.description}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }if (params.content !== undefined) {body['content'] = params.content}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.jsonindex e1a73f067ef9..49cea65ca000 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create-email-template.json@@ -124,6 +124,15 @@"description": "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time.","type": "boolean"},+ "tags": {+ "description": "Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.",+ "items": {+ "maxLength": 255,+ "type": "string"+ },+ "maxItems": 10,+ "type": "array"+ },"type": {"description": "Message channel of the template. Currently 'email'.","maxLength": 24,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.jsonindex 03e3c404741a..2182f75acc70 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update-email-template.json@@ -128,6 +128,15 @@"description": "For emails that carry login codes, reset links or other secrets. PostHog keeps no copy of each sent email's body or filled-in subject, and clicked links keep only the site address. Can change at any time.","type": "boolean"},+ "tags": {+ "description": "Tags for organizing templates, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.",+ "items": {+ "maxLength": 255,+ "type": "string"+ },+ "maxItems": 10,+ "type": "array"+ },"type": {"description": "Message channel of the template. Currently 'email'.","maxLength": 24,