: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): put entry-point drafts in the project's email design (#114837)
Daniel Marchuk4c9de8e8392c
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex f7adadfb9277..6c0eed204f31 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -22574,6 +22574,7 @@ export namespace Endpoints {created_at: string;created_by: string;id: string;+ latest_send_first: boolean;limit: number;offset: number;optimization_enabled: boolean;diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 0b800a78613c..1adbe803c266 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -734,6 +734,7 @@ class WorkflowListQuery:suggestions_first: bool = False# A workflow matches when it carries at least one of these tags.tags: frozenset[str] = frozenset()+ latest_send_first: bool = Falsefield_filters: Mapping[str, str] = field(default_factory=dict)diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 856ede87d870..936369623ff1 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -4979,6 +4979,11 @@ class HogFlowVersionMetricsRequestSerializer(AppMetricsRequestSerializer):"whether a schedule still has sends to come."),),+ OpenApiParameter(+ "latest_send_first",+ OpenApiTypes.BOOL,+ description="Pass `true` to order by when each workflow's newest completed run finished, newest first. Workflows that never finished a run come last.",+ ),]),# The mixin action's default schema documents integer ids; workflows are keyed by UUID.@@ -5275,6 +5280,7 @@ class HogFlowViewSet(broadcast_statuses=frozenset(broadcast_statuses),suggestions_first=params.get("suggestions_first") in ("true", "1"),tags=tags,+ latest_send_first=params.get("latest_send_first") == "true",field_filters={name: params[name] for name in WORKFLOW_FIELD_FILTER_PARAMS if name in params},)diff --git a/products/workflows/backend/services/batch_jobs.py b/products/workflows/backend/services/batch_jobs.pyindex d11bff76624c..414ea76b4220 100644--- a/products/workflows/backend/services/batch_jobs.py+++ b/products/workflows/backend/services/batch_jobs.py@@ -3,7 +3,7 @@ from typing import Anyfrom uuid import UUIDfrom django.core.exceptions import ValidationError as DjangoValidationError-from django.db.models import Exists, OuterRef, Q, Subquery+from django.db.models import Exists, OuterRef, Q, QuerySet, Subqueryfrom django.utils import timezoneimport structlog@@ -89,7 +89,7 @@ def set_batch_job_status(jobs.update(status=status, updated_at=timezone.now())-def hog_flow_ids_with_broadcast_status(*, team_id: int, statuses: Collection[str]) -> list[UUID]:+def filter_by_broadcast_status(queryset: QuerySet[HogFlow], statuses: Collection[str]) -> QuerySet[HogFlow]:# The status a sender sees on a broadcast, derived the way the broadcasts UI derives it: from the# latest run and whether a schedule still has sends to come.latest_run_status = (@@ -97,7 +97,7 @@ def hog_flow_ids_with_broadcast_status(*, team_id: int, statuses: Collection[str.order_by("-created_at").values("status")[:1])- queryset = HogFlow.objects.filter(team_id=team_id).annotate(+ queryset = queryset.annotate(_latest_run_status=Subquery(latest_run_status),_has_pending_schedule=Exists(HogFlowSchedule.objects.filter(@@ -129,7 +129,25 @@ def hog_flow_ids_with_broadcast_status(*, team_id: int, statuses: Collection[strcombined = Q()for broadcast_status in statuses:combined |= conditions[broadcast_status]- return list(queryset.filter(combined).values_list("id", flat=True))+ return queryset.filter(combined)+++def hog_flow_ids_with_broadcast_status(*, team_id: int, statuses: Collection[str]) -> list[UUID]:+ return list(+ filter_by_broadcast_status(HogFlow.objects.filter(team_id=team_id), statuses).values_list("id", flat=True)+ )+++def annotate_latest_send(queryset: QuerySet[HogFlow]) -> QuerySet[HogFlow]:+ """Adds `_latest_send_at`: when the workflow's newest completed run finished, or null."""+ latest_send = (+ HogFlowBatchJob.objects.filter(+ team_id=OuterRef("team_id"), hog_flow_id=OuterRef("pk"), status=HogFlowBatchJobState.COMPLETED+ )+ .order_by("-updated_at")+ .values("updated_at")[:1]+ )+ return queryset.annotate(_latest_send_at=Subquery(latest_send))def delete_batch_jobs_for_teams(team_ids: Collection[int], batch_size: int = 1000) -> None:diff --git a/products/workflows/backend/services/hog_flow_reads.py b/products/workflows/backend/services/hog_flow_reads.pyindex 5a0f1eabb212..9f8e59bd1d74 100644--- a/products/workflows/backend/services/hog_flow_reads.py+++ b/products/workflows/backend/services/hog_flow_reads.py@@ -33,7 +33,7 @@ from products.workflows.backend.facade.enums import HogFlowScheduleStatus, Workffrom products.workflows.backend.models.hog_flow.hog_flow import MESSAGING_ACTION_TYPES, HogFlowfrom products.workflows.backend.models.hog_flow_schedule import HogFlowSchedulefrom products.workflows.backend.models.workflow_proposal import WorkflowProposal-from products.workflows.backend.services.batch_jobs import hog_flow_ids_with_broadcast_status+from products.workflows.backend.services.batch_jobs import annotate_latest_send, filter_by_broadcast_statusfrom products.workflows.backend.services.hog_flow_schedules import list_schedules_oldest_firstfrom products.workflows.backend.services.hog_flow_secrets import TemplateCache, mask_workflow_fieldsfrom products.workflows.backend.services.publish_impact import build_publish_impact@@ -239,7 +239,7 @@ def _list_queryset(user_access_control: "UserAccessControl | None",include_all_if_admin: bool,) -> QuerySet:- queryset = (+ queryset: QuerySet = (HogFlow.objects.filter(team_id=team_id).select_related("created_by")# _to_workflow reads prefetched_tags, so a page costs one tag query rather than one per row.@@ -266,6 +266,10 @@ def _list_queryset(# otherwise repeat on one page and never appear on another.if query.suggestions_first:queryset = queryset.order_by("-pending_suggestions", "-updated_at", "-id")+ elif query.latest_send_first:+ queryset = annotate_latest_send(queryset).order_by(+ F("_latest_send_at").desc(nulls_last=True), "-updated_at", "-id"+ )else:queryset = queryset.order_by("-updated_at", "-id")@@ -287,9 +291,7 @@ def _list_queryset()if query.broadcast_statuses:- queryset = queryset.filter(- id__in=hog_flow_ids_with_broadcast_status(team_id=team_id, statuses=query.broadcast_statuses)- )+ queryset = filter_by_broadcast_status(queryset, query.broadcast_statuses)# `?type=loop` and `?type=broadcast` return the same rows, but Desktop's Loops list sends# this param and ships on its own release cadence, so installed builds keep sending it.diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex fa9ca13db56d..94e3439e6cc9 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -763,6 +763,37 @@ class TestHogFlowAPI(APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?broadcast_status=paused")assert response.status_code == 400+ @patch(+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"+ )+ def test_list_latest_send_first_orders_by_run_completion_not_edit_time(self, _mock_dispatch):+ def create(name: str, finished_minutes_ago: int | None) -> None:+ flow = HogFlow.objects.create(+ team=self.team, name=name, created_by=self.user, origin_product="broadcasts", status="active"+ )+ if finished_minutes_ago is not None:+ job = HogFlowBatchJob.objects.create(+ team=self.team, hog_flow=flow, status="completed", filters={}, variables={}+ )+ HogFlowBatchJob.objects.filter(pk=job.pk).update(+ updated_at=timezone.now() - timedelta(minutes=finished_minutes_ago)+ )++ # Created, and so edited, in the reverse of the order their runs finished.+ create("Finished last", finished_minutes_ago=1)+ create("Finished first", finished_minutes_ago=30)+ create("Never ran", finished_minutes_ago=None)++ response = self.client.get(+ f"/api/projects/{self.team.id}/hog_flows?broadcast_status=sent&latest_send_first=true&limit=1"+ )+ assert response.status_code == 200, response.json()+ assert response.json()["count"] == 2+ assert [flow["name"] for flow in response.json()["results"]] == ["Finished last"]++ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?latest_send_first=true")+ assert [flow["name"] for flow in response.json()["results"]] == ["Finished last", "Finished first", "Never ran"]+def test_list_field_filter_rejection_keeps_the_validation_code(self):response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?status=invalid-status")assert response.status_code == 400, response.json()diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.tsindex 6bc4783205f3..12a7f833d91c 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts@@ -297,6 +297,91 @@ describe('broadcastWizardLogic', () => {})+ it.each([+ { case: 'lands after the template was branded', withLinkEmail: true },+ { case: 'comes from a link without a template email', withLinkEmail: false },+ ])('keeps the project brand on an AI draft that $case', async ({ withLinkEmail }) => {+ const cell = (inner: string): string =>+ `<table role="presentation"><tbody><tr><td style="padding:10px;"><div>${inner}</div></td></tr></tbody></table>`+ const brandEmail = {+ design: {+ counters: { u_content_text: 1 },+ body: {+ values: {},+ rows: [+ {+ columns: [+ {+ contents: [+ { type: 'image', values: { src: { url: 'https://example.com/logo.png' } } },+ { type: 'text', values: { text: '<p>Template body copy</p>' } },+ { type: 'custom', values: { unsubscribe: true } },+ ],+ },+ ],+ },+ ],+ },+ },+ html: `<html><body><div class="u-row-container"><div class="u-row"><div class="u-col u-col-100"><div><div>${[+ cell('<img src="https://example.com/logo.png" />'),+ cell('<p>Template body copy</p>'),+ cell('<a href="{{ unsubscribe_url }}">Unsubscribe</a>'),+ ].join('')}</div></div></div></div></div></body></html>`,+ }+ let respond: (value: unknown) => void = () => {}+ let markRequested: () => void = () => {}+ const requested = new Promise<void>((resolve) => {+ markRequested = resolve+ })+ useMocks({+ get: {+ '/api/projects/:team_id/messaging_templates/': () => [+ 200,+ { count: 1, results: [{ content: { email: brandEmail } }] },+ ],+ },+ post: {+ '/api/projects/:team_id/workflow_email_drafts/': () =>+ new Promise((resolve) => {+ respond = resolve+ markRequested()+ }).then((body) => [200, body]),+ },+ })+ logic.unmount()+ router.actions.push(+ urlForNewBroadcastWithAudience({+ properties: LOCAL_AUDIENCE,+ source: 'error_tracking',+ ...(withLinkEmail ? { email: draftMessage({ kind: 'issue_fixed' }) } : {}),+ draftSource: { source: 'error_tracking', source_id: 'issue-1' },+ })+ )+ logic = broadcastWizardLogic({ id: 'new' })+ logic.mount()++ await expectLogic(logic).toDispatchActions([withLinkEmail ? 'brandApplied' : 'loadAiEmailDraft'])+ await requested+ respond({+ subject: 'Written by the model',+ preheader: '',+ html: '<p>Model paragraph.</p>',+ text: 'Model paragraph.',+ generated_by: 'ai',+ template_reason: null,+ })+ await expectLogic(logic).toDispatchActions(+ withLinkEmail+ ? ['loadAiEmailDraftSuccess']+ : ['loadAiEmailDraftSuccess', 'loadEmailBrandSuccess', 'brandApplied']+ )++ expect(logic.values.email.subject).toEqual('Written by the model')+ expect(logic.values.email.html).toContain('Model paragraph.')+ expect(logic.values.email.html).toContain('https://example.com/logo.png')+ })+it('blocks the recipients step until the person chooses, when a link has an audience it cannot use', async () => {logic.unmount()router.actions.push(diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.tsindex 558615b8b755..45a03938e08e 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts@@ -61,6 +61,7 @@ import {requestAiEmailDraft,} from '../MessageAudience/aiEmailDraft'import type { AiEmailDraftStatusProps } from '../MessageAudience/AiEmailDraftStatus'+import { EmailBrand, applyEmailBrand, loadEmailBrand } from '../MessageAudience/emailBrand'import {EMAIL_PREFILL_PARAM,MessageDraft,@@ -288,6 +289,8 @@ export interface broadcastWizardLogicValues {duplicating: booleaneffectiveTimezone: stringemail: BroadcastEmailValue+ emailBrand: EmailBrand | null+ emailBrandLoading: booleanemailRateLimit: HogFlowEmailSendingRateLimitApi | nullemailSettings: BroadcastEmailSettingsentrySource: string | null@@ -344,6 +347,9 @@ export interface broadcastWizardLogicActions {archiveBroadcast: () => {value: true}+ brandApplied: (content: Pick<BroadcastEmailValue, 'design' | 'html'>) => {+ content: Pick<BroadcastEmailValue, 'design' | 'html'>+ }collapseRun: (runId: string) => {runId: string}@@ -446,6 +452,21 @@ export interface broadcastWizardLogicActions {broadcast: HogFlowApi | nullpayload?: any}+ loadEmailBrand: () => any+ loadEmailBrandFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadEmailBrandSuccess: (+ emailBrand: EmailBrand | null,+ payload?: any+ ) => {+ emailBrand: EmailBrand | null+ payload?: any+ }loadExternalEdit: () => {value: true}@@ -709,6 +730,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([settings: Pick<BroadcastEmailSettings, 'utmTagsEnabled' | 'utmParams' | 'utmParamsFromDefault'>) => ({ settings }),setEmail: (email: BroadcastEmailValue) => ({ email }),+ brandApplied: (content: Pick<BroadcastEmailValue, 'html' | 'design'>) => ({ content }),applyAiEmailDraft: (draft: MessageDraft) => ({ draft }),applyDefaultSender: true,defaultSenderApplied: (integrationId: number) => ({ integrationId }),@@ -811,6 +833,17 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([},},],+ emailBrand: [+ null as EmailBrand | null,+ {+ loadEmailBrand: async () => {+ if (!values.currentProjectId) {+ return null+ }+ return await loadEmailBrand(String(values.currentProjectId), values.email)+ },+ },+ ],aiEmailDraft: [null as AiEmailDraftResult | null,{@@ -993,6 +1026,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([DEFAULT_BROADCAST_EMAIL,{setEmail: (_, { email }) => email,+ brandApplied: (state, { content }) => ({ ...state, ...content }),prefillFromLink: (state, { prefill }) =>prefill.email ? { ...state, ...messageDraftEmail(prefill.email) } : state,applyAiEmailDraft: (state, { draft }) => ({ ...state, ...messageDraftEmail(draft) }),@@ -1480,6 +1514,15 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([actions.applyAiEmailDraft(aiEmailDraft.draft)cache.prefilledEmail = { ...DEFAULT_BROADCAST_EMAIL, ...messageDraftEmail(aiEmailDraft.draft) }cache.prefilledEmailGeneratedBy = 'ai'+ // The draft arrives unstyled, so it takes the brand the template already had.+ const branded = values.emailBrand ? applyEmailBrand(values.email, values.emailBrand) : null+ if (branded) {+ actions.brandApplied(branded)+ cache.prefilledEmail = { ...cache.prefilledEmail, ...branded }+ } else if (cache.brandAwaitsAiDraft) {+ cache.brandAwaitsAiDraft = false+ actions.loadEmailBrand()+ }}}captureAiEmailDraft('broadcast', request, aiEmailDraft, skipped)@@ -1492,6 +1535,25 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([}actions.reportReviewVisit()},+ loadEmailBrandSuccess: ({ emailBrand }) => {+ // Only a draft nobody has touched yet takes the brand, so it never overwrites an edit.+ if (+ !emailBrand ||+ cache.brandClosed ||+ !cache.prefilledEmail ||+ !prefilledEmailUnchanged(cache.prefilledEmail, values.email)+ ) {+ return+ }+ const branded = applyEmailBrand(values.email, emailBrand)+ if (!branded) {+ return+ }+ actions.brandApplied(branded)+ cache.prefilledEmail = { ...cache.prefilledEmail, ...branded }+ // pinned: analytics event name+ posthog.capture('broadcast email branded', { source: emailBrand.source })+ },expandRun: ({ runId }) => {actions.setExpandedRunOverride([...values.expandedRunIds.filter((id) => id !== runId), runId])},@@ -1832,6 +1894,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([}},launchBroadcast: async (_, breakpoint) => {+ // Launch sends the email as saved, so a brand that arrives after this click must not change the preview.+ cache.brandClosed = trueif (!values.currentProjectId) {actions.launchBroadcastFinished()return@@ -2254,6 +2318,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([cache.prefilledName = values.nameif (email) {cache.prefilledEmail = { ...DEFAULT_BROADCAST_EMAIL, ...messageDraftEmail(email) }+ actions.loadEmailBrand()}if (properties) {cache.landOnPrefilledStep = true@@ -2274,6 +2339,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([const draftSource = parseEmailDraftSource(draftSourceParam)if (draftSource) {actions.loadAiEmailDraft(draftSource)+ if (!email) {+ // The lookup checks each brand against the draft's text, so it waits until the draft exists.+ cache.brandAwaitsAiDraft = true+ }}}),])diff --git a/products/workflows/frontend/MessageAudience/emailBrand.test.ts b/products/workflows/frontend/MessageAudience/emailBrand.test.tsnew file mode 100644index 000000000000..538660e4fc4f--- /dev/null+++ b/products/workflows/frontend/MessageAudience/emailBrand.test.ts@@ -0,0 +1,171 @@+import { messagingTemplatesList } from 'products/messaging/frontend/generated/api'+import { hogFlowsList } from 'products/workflows/frontend/generated/api'++import { EmailBrand, applyEmailBrand, loadEmailBrand } from './emailBrand'+import { draftMessage, messageDraftEmail } from './messageDrafts'++const block = (inner: string): string =>+ `<table role="presentation" cellpadding="0" cellspacing="0" width="100%" border="0"><tbody><tr><td style="padding:10px;font-family:georgia;">${inner}</td></tr></tbody></table>`++jest.mock('products/messaging/frontend/generated/api', () => ({ messagingTemplatesList: jest.fn() }))+jest.mock('products/workflows/frontend/generated/api', () => ({ hogFlowsList: jest.fn() }))++const BRAND: EmailBrand = {+ source: 'template',+ design: {+ counters: { u_content_text: 2 },+ body: {+ values: { backgroundColor: '#fdf6e3' },+ rows: [+ {+ columns: [+ {+ contents: [+ { type: 'image', values: { src: { url: 'https://example.com/logo.png' } } },+ { type: 'heading', values: { text: 'Template headline' } },+ {+ type: 'text',+ values: {+ text: '<p>Template body copy that is the longest text here.</p>',+ color: '#123456',+ },+ },+ { type: 'text', values: { text: '<p>Short note</p>' } },+ { type: 'custom', values: { unsubscribe: true } },+ ],+ },+ ],+ },+ ],+ },+ },+ html: `<html><body style="background-color:#fdf6e3"><div class="u-row-container"><div class="u-row"><div class="u-col u-col-100"><div><div>${[+ block('<img src="https://example.com/logo.png" />'),+ block('<h1>Template headline</h1>'),+ block('<div style="color:#123456"><p>Template body copy that is the longest text here.</p></div>'),+ block('<div><p>Short note</p></div>'),+ block('<a href="{{ unsubscribe_url }}">Unsubscribe</a>'),+ ].join('')}</div></div></div></div></div></body></html>`,+}++describe('applyEmailBrand', () => {+ it('puts the draft in place of the template wording and keeps the rest of the brand', () => {+ const draft = draftMessage({ kind: 'issue_fixed' })+ const branded = applyEmailBrand(messageDraftEmail(draft), BRAND)!++ const contents = branded.design.body.rows[0].columns[0].contents+ expect(contents.map((content: any) => content.type)).toEqual([+ 'image',+ ...draft.paragraphs.map(() => 'text'),+ 'custom',+ ])+ expect(contents[1].values.color).toEqual('#123456')+ expect(branded.design.body.values.backgroundColor).toEqual('#fdf6e3')+ for (const paragraph of draft.paragraphs) {+ expect(branded.html).toContain(paragraph)+ }+ expect(branded.html).toContain('https://example.com/logo.png')+ expect(branded.html).toContain('{{ unsubscribe_url }}')+ expect(branded.html).toContain('color:#123456')+ expect(branded.html).not.toContain('Template')+ expect(branded.html).not.toContain('Short note')+ })++ it.each([+ { case: 'html the visual editor did not export', brand: { ...BRAND, html: '<p>Hand written</p>' } },+ { case: 'a design with no text block', brand: { ...BRAND, design: { body: { rows: [] } } } },+ ])('leaves the draft unbranded for $case', ({ brand }) => {+ expect(applyEmailBrand(messageDraftEmail(draftMessage({ kind: 'issue_fixed' })), brand)).toBeNull()+ })++ it('keeps a text block that holds the unsubscribe link and skips a body hidden on desktop', () => {+ const columns = BRAND.design.body.rows[0].columns[0].contents+ const brand: EmailBrand = {+ ...BRAND,+ design: {+ ...BRAND.design,+ body: {+ ...BRAND.design.body,+ rows: [+ {+ columns: [+ {+ contents: [+ columns[0],+ {+ type: 'text',+ values: {+ text: '<p>A much longer mobile only version of the template body copy.</p>',+ hideDesktop: true,+ },+ },+ columns[2],+ columns[3],+ {+ type: 'text',+ values: { text: '<p><a href="{{ unsubscribe_url }}">Unsubscribe</a></p>' },+ },+ ],+ },+ ],+ },+ ],+ },+ },+ html: BRAND.html+ .replace(+ '<h1>Template headline</h1>',+ '<div><p>A much longer mobile only version of the template body copy.</p></div>'+ )+ .replace(+ '<a href="{{ unsubscribe_url }}">Unsubscribe</a>',+ '<div><p><a href="{{ unsubscribe_url }}">Unsubscribe</a></p></div>'+ ),+ }+ const draft = draftMessage({ kind: 'issue_fixed' })+ const branded = applyEmailBrand(messageDraftEmail(draft), brand)!++ const contents = branded.design.body.rows[0].columns[0].contents+ expect(contents.filter((content: any) => content.values?.hideDesktop)).toEqual([])+ expect(contents[1].values.color).toEqual('#123456')+ expect(branded.html).toContain('{{ unsubscribe_url }}')+ expect(branded.html).not.toContain('mobile only')+ })++ it('ignores a saved template written for Hog templating', async () => {+ jest.mocked(messagingTemplatesList).mockResolvedValue({+ results: [{ content: { email: { templating: 'hog', html: BRAND.html, design: BRAND.design } } }],+ } as never)+ jest.mocked(hogFlowsList).mockResolvedValue({ results: [] } as never)++ expect(await loadEmailBrand('1', messageDraftEmail(draftMessage({ kind: 'issue_fixed' })))).toBeNull()+ })++ it('drops the template preheader and keeps draft text as text', () => {+ const brand: EmailBrand = {+ ...BRAND,+ design: {+ ...BRAND.design,+ body: {+ ...BRAND.design.body,+ values: { ...BRAND.design.body.values, preheaderText: 'Old campaign teaser' },+ },+ },+ html: BRAND.html.replace(+ '<body style="background-color:#fdf6e3">',+ '<body style="background-color:#fdf6e3"><div style="display:none;max-height:0px;overflow:hidden;">Old campaign teaser</div>'+ ),+ }+ const draft = {+ ...draftMessage({ kind: 'issue_fixed' }),+ paragraphs: ['<img src="https://example.com/pixel">'],+ }++ const branded = applyEmailBrand(messageDraftEmail(draft), brand)!++ expect(branded.design.body.values.preheaderText).toEqual('')+ expect(branded.html).not.toContain('Old campaign teaser')+ expect(branded.html).not.toContain('<img src="https://example.com/pixel">')+ expect(branded.html).toContain('<img')+ })+})diff --git a/products/workflows/frontend/MessageAudience/emailBrand.ts b/products/workflows/frontend/MessageAudience/emailBrand.tsnew file mode 100644index 000000000000..77d8fd8728d5--- /dev/null+++ b/products/workflows/frontend/MessageAudience/emailBrand.ts@@ -0,0 +1,232 @@+import { messagingTemplatesList } from 'products/messaging/frontend/generated/api'+import { hogFlowsList } from 'products/workflows/frontend/generated/api'++import type { MessageDraftEmail } from './messageDrafts'++export type EmailBrandSource = 'template' | 'last_sent'++/** An email someone already designed, whose layout, colors, images and footer a new draft can borrow. */+export interface EmailBrand {+ source: EmailBrandSource+ html: string+ design: Record<string, any>+}++type DesignContent = Record<string, any>++// The template's own words. The draft replaces them, and everything else in the design stays.+const WORDING_TYPES = new Set(['text', 'heading', 'button'])+const SENT_BROADCASTS_TO_CHECK = 5+// The brand only decorates the draft, so a slow lookup must not hold up the draft itself.+const BRAND_TIMEOUT_MS = 5000++function plainText(html: string): string {+ return html+ .replace(/<[^>]*>/g, '')+ .replace(/&[a-z#0-9]+;/gi, ' ')+ .trim()+}++function holdsUnsubscribe(content: DesignContent): boolean {+ return JSON.stringify(content.values ?? {}).includes('unsubscribe_url')+}++function visibleEverywhere(content: DesignContent): boolean {+ return !content.values?.hideDesktop && !content.values?.hideMobile+}++/** The inbox preview text belongs to the template's own campaign, so the draft must not inherit it. */+function clearPreheader(doc: Document, design: Record<string, any>): void {+ const preheader = String(design.body?.values?.preheaderText ?? '').trim()+ if (!preheader) {+ return+ }+ design.body.values.preheaderText = ''+ for (const element of Array.from(doc.body.querySelectorAll('div, span'))) {+ const hidden = /display\s*:\s*none/i.test(element.getAttribute('style') ?? '')+ if (hidden && element.textContent?.trim() === preheader) {+ element.remove()+ }+ }+}++function designContents(design: Record<string, any>): DesignContent[][] | null {+ const rows = design?.body?.rows+ if (!Array.isArray(rows)) {+ return null+ }+ const columns: DesignContent[][] = []+ for (const row of rows) {+ if (!Array.isArray(row?.columns)) {+ return null+ }+ for (const column of row.columns) {+ if (!Array.isArray(column?.contents)) {+ return null+ }+ columns.push(column.contents)+ }+ }+ return columns+}++/**+ * The rendered block for each design block, column by column. Only HTML exported by the visual editor has this+ * shape, so anything else returns null and the draft keeps its plain layout.+ */+function renderedBlocks(doc: Document, columns: DesignContent[][]): Element[][] | null {+ const renderedColumns = Array.from(doc.querySelectorAll('.u-col'))+ if (renderedColumns.length !== columns.length) {+ return null+ }+ const blocks = renderedColumns.map((column) => Array.from(column.querySelectorAll(':scope > div > div > table')))+ return blocks.every((rendered, index) => rendered.length === columns[index].length) ? blocks : null+}++/**+ * The draft inside the brand's design: the brand keeps its layout, colors, images, dividers, social links and+ * unsubscribe block, its longest text block becomes the draft's paragraphs, and its other text is dropped.+ * Returns null when the brand can't be read, so the caller keeps the unbranded draft.+ */+export function applyEmailBrand(+ email: { design?: Record<string, any> | null },+ brand: EmailBrand+): Pick<MessageDraftEmail, 'html' | 'design'> | null {+ const draftColumns = email.design ? designContents(email.design) : null+ const draftParagraphs = (draftColumns ?? []).flat().filter((content) => content.type === 'text')+ if (draftParagraphs.length === 0 || typeof DOMParser === 'undefined') {+ return null+ }+ const design = JSON.parse(JSON.stringify(brand.design))+ const columns = designContents(design)+ if (!columns) {+ return null+ }+ const doc = new DOMParser().parseFromString(brand.html, 'text/html')+ const rendered = renderedBlocks(doc, columns)+ if (!rendered) {+ return null+ }++ let body: { column: number; index: number; length: number } | null = null+ columns.forEach((contents, column) =>+ contents.forEach((content, index) => {+ const candidate = content.type === 'text' && !holdsUnsubscribe(content) && visibleEverywhere(content)+ const length = candidate ? plainText(String(content.values?.text ?? '')).length : -1+ if (length >= 0 && (!body || length > body.length)) {+ body = { column, index, length }+ }+ })+ )+ if (!body) {+ return null+ }+ const { column: bodyColumn, index: bodyIndex } = body as { column: number; index: number }+ const bodyContent = columns[bodyColumn][bodyIndex]+ const bodyRendered = rendered[bodyColumn][bodyIndex]+ const bodyCell = bodyRendered.querySelector('td')+ const bodyWrapper = bodyCell?.firstElementChild+ if (!bodyCell || !bodyWrapper) {+ return null+ }++ const paragraphs = draftParagraphs.map((paragraph, index) => ({+ design: {+ ...bodyContent,+ id: `brand-draft-text-${index + 1}`,+ values: {+ ...bodyContent.values,+ text: paragraph.values?.text ?? '',+ _meta: { htmlID: `u_content_text_draft_${index + 1}`, htmlClassNames: 'u_content_text' },+ },+ },+ html: String(paragraph.values?.text ?? ''),+ }))++ columns.forEach((contents, column) => {+ for (let index = contents.length - 1; index >= 0; index--) {+ const isBody = column === bodyColumn && index === bodyIndex+ if (isBody) {+ for (const paragraph of paragraphs) {+ const block = bodyRendered.cloneNode(true) as Element+ const wrapper = block.querySelector('td')?.firstElementChild+ if (wrapper) {+ wrapper.innerHTML = paragraph.html+ }+ bodyRendered.parentNode?.insertBefore(block, bodyRendered)+ }+ bodyRendered.remove()+ contents.splice(index, 1, ...paragraphs.map((paragraph) => paragraph.design))+ } else if (WORDING_TYPES.has(contents[index].type) && !holdsUnsubscribe(contents[index])) {+ rendered[column][index].remove()+ contents.splice(index, 1)+ }+ }+ })+ design.counters = { ...design.counters, u_content_text: (design.counters?.u_content_text ?? 0) + paragraphs.length }+ clearPreheader(doc, design)++ return { html: `<!DOCTYPE html>${doc.documentElement.outerHTML}`, design }+}++function emailContent(value: unknown, templating: unknown): { html: string; design: Record<string, any> } | null {+ const email = value as { html?: unknown; design?: unknown } | null | undefined+ // Drafts render with Liquid, so a design written for Hog would keep its expressions as literal text.+ if (templating === 'hog') {+ return null+ }+ return email && typeof email.html === 'string' && email.design && typeof email.design === 'object'+ ? { html: email.html, design: email.design as Record<string, any> }+ : null+}++/**+ * The brand a new draft borrows: the newest saved email template, or when there is none, the email of the+ * broadcast sent most recently. Null when neither has a design the draft can go into.+ */+export async function loadEmailBrand(+ projectId: string,+ probe: { design?: Record<string, any> | null }+): Promise<EmailBrand | null> {+ try {+ return await Promise.race([+ findEmailBrand(projectId, probe),+ new Promise<null>((resolve) => setTimeout(() => resolve(null), BRAND_TIMEOUT_MS)),+ ])+ } catch {+ // The brand is a nicety. A draft without it is still complete, so a failed lookup stays quiet.+ return null+ }+}++async function findEmailBrand(+ projectId: string,+ probe: { design?: Record<string, any> | null }+): Promise<EmailBrand | null> {+ const templates = await messagingTemplatesList(projectId, { limit: 1 })+ const templateEmail = templates.results[0]?.content?.email+ const template = emailContent(templateEmail, (templateEmail as { templating?: unknown } | undefined)?.templating)+ if (template) {+ const brand: EmailBrand = { source: 'template', ...template }+ return applyEmailBrand(probe, brand) ? brand : null+ }+ const sent = await hogFlowsList(projectId, {+ origin_product: 'broadcasts',+ broadcast_status: 'sent',+ latest_send_first: true,+ limit: SENT_BROADCASTS_TO_CHECK,+ })+ for (const broadcast of sent.results ?? []) {+ const action = (broadcast.actions as Record<string, any>[] | undefined)?.find(+ (candidate) => candidate?.config?.template_id === 'template-email'+ )+ const content = emailContent(action?.config?.inputs?.email?.value, action?.config?.inputs?.email?.templating)+ if (content) {+ const brand: EmailBrand = { source: 'last_sent', ...content }+ if (applyEmailBrand(probe, brand)) {+ return brand+ }+ }+ }+ return null+}diff --git a/products/workflows/frontend/Workflows/workflowEmailPrefill.ts b/products/workflows/frontend/Workflows/workflowEmailPrefill.tsindex 1ae94083ed01..126bf022e72c 100644--- a/products/workflows/frontend/Workflows/workflowEmailPrefill.ts+++ b/products/workflows/frontend/Workflows/workflowEmailPrefill.ts@@ -1,3 +1,4 @@+import { EmailBrand, applyEmailBrand } from '../MessageAudience/emailBrand'import { MessageDraft, messageDraftEmail } from '../MessageAudience/messageDrafts'import type { HogFlow, HogFlowAction } from './hogflows/types'import type { WorkflowTriggerConfig } from './workflowTriggerPrefill'@@ -115,3 +116,31 @@ export function withEmailSender(workflow: HogFlow, integrationId: number): { wor})return { workflow: filled ? { ...workflow, actions } : workflow, filled }}++/** The prefilled email step inside the brand's design, or the workflow unchanged when the brand doesn't fit. */+export function withEmailBrand(workflow: HogFlow, brand: EmailBrand | null): HogFlow {+ if (!brand) {+ return workflow+ }+ let branded = false+ const actions = workflow.actions.map((action) => {+ if (action.id !== EMAIL_ACTION_ID) {+ return action+ }+ const config = action.config as Record<string, any>+ const value = config.inputs?.email?.value+ const content = value ? applyEmailBrand(value, brand) : null+ if (!content) {+ return action+ }+ branded = true+ return {+ ...action,+ config: {+ ...config,+ inputs: { ...config.inputs, email: { ...config.inputs.email, value: { ...value, ...content } } },+ },+ } as HogFlowAction+ })+ return branded ? { ...workflow, actions } : workflow+}diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 5eb0536c19e9..6eeb3f1c01f9 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -54,6 +54,7 @@ import {requestAiEmailDraft,} from '../MessageAudience/aiEmailDraft'import type { AiEmailDraftStatusProps } from '../MessageAudience/AiEmailDraftStatus'+import { loadEmailBrand } from '../MessageAudience/emailBrand'import { parseMessageDraftPrefill } from '../MessageAudience/messageDrafts'import { getRegisteredTriggerTypes } from './hogflows/registry/triggers/triggerTypeRegistry'import {@@ -80,7 +81,13 @@ import {import { openPublishConfirmDialog } from './PublishImpactDialog'import { ResourceSaveQueue } from './resourceSaveQueue'import { prepareWorkflowDuplicate } from './workflowDuplication'-import { prefilledEmailContent, prefilledWorkflow, withEmailSender, withPrefilledEmail } from './workflowEmailPrefill'+import {+ prefilledEmailContent,+ prefilledWorkflow,+ withEmailBrand,+ withEmailSender,+ withPrefilledEmail,+} from './workflowEmailPrefill'import { workflowSceneLogic } from './workflowSceneLogic'import { workflowsLogic } from './workflowsLogic'import { parseWorkflowTriggerPrefill } from './workflowTriggerPrefill'@@ -3389,13 +3396,20 @@ export const workflowLogic = kea<workflowLogicType>([}const triggerConfig = parseWorkflowTriggerPrefill(props.triggerPrefill)if (triggerConfig) {- return await withDefaultEmailSender(- prefilledWorkflow(- NEW_WORKFLOW,- triggerConfig,- parseMessageDraftPrefill(props.emailPrefill)- )+ const prefilled = prefilledWorkflow(+ NEW_WORKFLOW,+ triggerConfig,+ parseMessageDraftPrefill(props.emailPrefill))+ const emailAction = prefilled.actions.find((action) => action.type === 'function_email')+ const brand = emailAction+ ? await loadEmailBrand(+ String(values.currentProjectId),+ (emailAction.config as Record<string, any>).inputs?.email?.value ?? {}+ )+ : null+ cache.emailBrand = brand+ return await withDefaultEmailSender(withEmailBrand(prefilled, brand))}return { ...NEW_WORKFLOW }}@@ -4831,12 +4845,17 @@ export const workflowLogic = kea<workflowLogicType>([skipped = 'edited'} else if (values.workflowChanged) {actions.setWorkflowValues({- actions: withPrefilledEmail(values.workflow, aiEmailDraft.draft).actions,+ actions: withEmailBrand(+ withPrefilledEmail(values.workflow, aiEmailDraft.draft),+ cache.emailBrand+ ).actions,})actions.markAiEmailDraftApplied()} else {// Untouched, so the draft becomes the baseline and "Clear changes" doesn't offer the template back.- actions.loadWorkflowSuccess(withPrefilledEmail(loaded, aiEmailDraft.draft))+ actions.loadWorkflowSuccess(+ withEmailBrand(withPrefilledEmail(loaded, aiEmailDraft.draft), cache.emailBrand)+ )actions.markAiEmailDraftApplied()}}diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex efe1c45a3231..998e57e06b95 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -2904,6 +2904,10 @@ export type HogFlowsListParams = {*/created_by?: stringid?: string+ /**+ * Pass `true` to order by when each workflow's newest completed run finished, newest first. Workflows that never finished a run come last.+ */+ latest_send_first?: boolean/*** Number of results to return per page.*/diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3ec6502cdaa9..08b914a1bccd 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -134809,6 +134809,10 @@ export namespace Schemas {*/created_by?: string;id?: string;+ /**+ * Pass `true` to order by when each workflow's newest completed run finished, newest first. Workflows that never finished a run come last.+ */+ latest_send_first?: boolean;/*** Number of results to return per page.*/diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex 75f8c6a8d5b3..306bd7dd6d4c 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -32,6 +32,12 @@ export const HogFlowsListQueryParams = () => zod.object({created_at: zod.iso.datetime({ offset: true }).optional(),created_by: zod.string().optional().describe('Filter to workflows created by the user with this uuid.'),id: zod.string().optional(),+ latest_send_first: zod+ .boolean()+ .optional()+ .describe(+ "Pass `true` to order by when each workflow's newest completed run finished, newest first. Workflows that never finished a run come last."+ ),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),optimization_enabled: zod.boolean().optional().describe('Only workflows someone turned suggestions on for.'),diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex 0c7525aa56a4..e320ba1883f7 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -391,6 +391,7 @@ const workflowsList = (): ToolBase<created_at: params.created_at,created_by: params.created_by,id: params.id,+ latest_send_first: params.latest_send_first,limit: params.limit,offset: params.offset,optimization_enabled: params.optimization_enabled,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.jsonindex 55a7ccd9804f..438c56b10baf 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json@@ -21,6 +21,10 @@"id": {"type": "string"},+ "latest_send_first": {+ "description": "Pass `true` to order by when each workflow's newest completed run finished, newest first. Workflows that never finished a run come last.",+ "type": "boolean"+ },"limit": {"description": "Number of results to return per page.","type": "number"