Skip to content

: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.

feat(workflows): open entry-point broadcasts and workflows ready to send (#114807)

Daniel Marchuk55528deb8e44
diff --git a/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsx b/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsx
index 27825094f979..b68ae802a328 100644
--- a/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsx
+++ b/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsx
@@ -7,6 +7,7 @@ import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { SurveyEventName } from '~/types'
import { captureMessageAudienceClicked } from 'products/workflows/frontend/MessageAudience/messageAudience'
+import { draftMessage } from 'products/workflows/frontend/MessageAudience/messageDrafts'
import {
type WorkflowTriggerConfig,
urlForNewWorkflowWithTrigger,
@@ -34,7 +35,13 @@ export function SurveyFollowUpWorkflowButton({ surveyId }: { surveyId: string })
tooltip="Open a workflow that emails each person who responds to this survey"
onClick={() => {
captureMessageAudienceClicked(SOURCE, 'workflow')
- router.actions.push(urlForNewWorkflowWithTrigger(surveyFollowUpTrigger(surveyId), SOURCE))
+ router.actions.push(
+ urlForNewWorkflowWithTrigger(
+ surveyFollowUpTrigger(surveyId),
+ SOURCE,
+ draftMessage({ kind: 'survey_responded' })
+ )
+ )
}}
data-attr="survey-start-follow-up-workflow"
>
diff --git a/products/early_access_features/frontend/EarlyAccessFeature.tsx b/products/early_access_features/frontend/EarlyAccessFeature.tsx
index efe58415c62e..bc9d2d3ce7ba 100644
--- a/products/early_access_features/frontend/EarlyAccessFeature.tsx
+++ b/products/early_access_features/frontend/EarlyAccessFeature.tsx
@@ -83,6 +83,7 @@ import { AssigneeSelect } from 'products/error_tracking/frontend/components/Assi
import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'
import { MessageAudience } from 'products/workflows/frontend/MessageAudience/messageAudience'
import { MessageAudienceButton } from 'products/workflows/frontend/MessageAudience/MessageAudienceButton'
+import { draftMessage } from 'products/workflows/frontend/MessageAudience/messageDrafts'
import { EarlyAccessFeatureLogicProps, earlyAccessFeatureLogic } from './earlyAccessFeatureLogic'
import { InstructionsModal } from './InstructionsModal'
@@ -161,6 +162,16 @@ function enrolledPeopleAudience(earlyAccessFeature: EarlyAccessFeatureType): Mes
},
],
broadcastName: `${earlyAccessFeature.name} is now available`,
+ broadcastEmail: draftMessage({
+ kind: 'feature_available',
+ featureName: earlyAccessFeature.name,
+ featureDescription: earlyAccessFeature.description,
+ }),
+ workflowEmail: draftMessage({
+ kind: 'feature_enrolled',
+ featureName: earlyAccessFeature.name,
+ featureDescription: earlyAccessFeature.description,
+ }),
workflowTrigger: {
type: 'event',
filters: {
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueWorkflowButton.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueWorkflowButton.tsx
index b3db0b336ee7..6330618bd71e 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueWorkflowButton.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueWorkflowButton.tsx
@@ -5,6 +5,7 @@ import { IconSend } from '@posthog/icons'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { captureMessageAudienceClicked } from 'products/workflows/frontend/MessageAudience/messageAudience'
+import { draftMessage } from 'products/workflows/frontend/MessageAudience/messageDrafts'
import {
type WorkflowTriggerConfig,
urlForNewWorkflowWithTrigger,
@@ -30,7 +31,13 @@ export function IssueWorkflowButton({ issueId }: { issueId: string }): JSX.Eleme
tooltip="Open a workflow that emails people each time they hit this issue"
onClick={() => {
captureMessageAudienceClicked(SOURCE, 'workflow')
- router.actions.push(urlForNewWorkflowWithTrigger(issueWorkflowTrigger(issueId), SOURCE))
+ router.actions.push(
+ urlForNewWorkflowWithTrigger(
+ issueWorkflowTrigger(issueId),
+ SOURCE,
+ draftMessage({ kind: 'issue_hit' })
+ )
+ )
}}
data-attr="issue-panel-start-workflow"
>
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts
index ea3fef99b649..f10f3a916189 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts
@@ -18,6 +18,7 @@ import {
cohortAudienceProperties,
messageAudienceUrl,
} from 'products/workflows/frontend/MessageAudience/messageAudience'
+import { draftMessage } from 'products/workflows/frontend/MessageAudience/messageDrafts'
export const AFFECTED_LOOKBACK_DAYS = 30
// pinned: sent as the broadcast's entry_source and the click event's source, so renaming it splits the history
@@ -188,6 +189,7 @@ export const issueAffectedBroadcastLogic = kea<issueAffectedBroadcastLogicType>(
properties: cohortAudienceProperties(audienceCohort),
source: SOURCE,
broadcastName: truncate(`We fixed ${props.issueName || 'an error'}`, MAX_NAME_LENGTH),
+ broadcastEmail: draftMessage({ kind: 'issue_fixed' }),
},
'broadcast'
)
diff --git a/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts b/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts
index 22656a0ae763..2d102d90d9f1 100644
--- a/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts
@@ -4,6 +4,8 @@ import { urls } from 'scenes/urls'
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+import { EMAIL_PREFILL_PARAM, MessageDraft } from '../MessageAudience/messageDrafts'
+
// pinned: URL search params, other products link to /broadcasts/new with these
export const AUDIENCE_PREFILL_PARAM = 'audience'
export const NAME_PREFILL_PARAM = 'name'
@@ -14,13 +16,15 @@ export interface BroadcastPrefill {
name?: string
/** The product surface the person came from, reported on the launch event. */
source?: string
+ email?: MessageDraft
}
-export function urlForNewBroadcastWithAudience({ properties, name, source }: BroadcastPrefill): string {
+export function urlForNewBroadcastWithAudience({ properties, name, source, email }: BroadcastPrefill): string {
return combineUrl(urls.broadcastNew(), {
[AUDIENCE_PREFILL_PARAM]: JSON.stringify(properties),
...(name ? { [NAME_PREFILL_PARAM]: name } : {}),
...(source ? { [SOURCE_PREFILL_PARAM]: source } : {}),
+ ...(email ? { [EMAIL_PREFILL_PARAM]: JSON.stringify(email) } : {}),
}).url
}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index 49d7e03c19bb..aded17e2ec02 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -9,6 +9,7 @@ import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types
import type { HogFlowApi } from 'products/workflows/frontend/generated/api.schemas'
+import { draftMessage } from '../MessageAudience/messageDrafts'
import { urlForNewBroadcastWithAudience } from './broadcastAudiencePrefill'
import { DEFAULT_BROADCAST_EMAIL, DELETED_SENDER_ERROR, broadcastWizardLogic } from './broadcastWizardLogic'
@@ -144,7 +145,56 @@ describe('broadcastWizardLogic', () => {
expect(logic.values.audienceProperties).toEqual(properties)
expect(logic.values.name).toEqual('Fix shipped')
expect(logic.values.entrySource).toEqual('cohort')
- expect(router.values.searchParams).toEqual({})
+
+ // A reload remounts the wizard from the same URL, and nothing was saved yet.
+ logic.unmount()
+ logic = broadcastWizardLogic({ id: 'new' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['prefillFromLink'])
+ expect(logic.values.audienceProperties).toEqual(properties)
+ expect(logic.values.name).toEqual('Fix shipped')
+ })
+
+ it.each([
+ {
+ link: 'a draft email and one verified sender',
+ email: draftMessage({ kind: 'issue_fixed' }),
+ verified: true,
+ step: 'review',
+ },
+ {
+ link: 'a draft email but no verified sender',
+ email: draftMessage({ kind: 'issue_fixed' }),
+ verified: false,
+ step: 'content',
+ },
+ { link: 'no email', email: undefined, verified: true, step: 'content' },
+ ])('opens a link with $link on the $step step without creating a draft', async ({ email, verified, step }) => {
+ const createDraft = jest.fn()
+ useMocks({
+ get: {
+ '/api/projects/:team_id/integrations/': {
+ results: [{ id: 1, kind: 'email', config: { verified } }],
+ count: 1,
+ },
+ },
+ post: { '/api/projects/:team_id/hog_flows/': () => createDraft() },
+ })
+ logic.unmount()
+ router.actions.push(
+ urlForNewBroadcastWithAudience({ properties: LOCAL_AUDIENCE, source: 'error_tracking', email })
+ )
+ logic = broadcastWizardLogic({ id: 'new' })
+ logic.mount()
+ integrationsLogic.mount()
+
+ await expectLogic(logic, () => {
+ integrationsLogic.actions.loadIntegrations()
+ }).toDispatchActions(['landOnStep'])
+
+ expect(logic.values.currentStep).toEqual(step)
+ expect(logic.values.email.subject).toEqual(email?.subject ?? '')
+ expect(createDraft).not.toHaveBeenCalled()
})
it('blocks the recipients step until the person chooses, when a link has an audience it cannot use', async () => {
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index d392e572c38e..0de780271951 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -49,6 +49,7 @@ import type {
} from 'products/workflows/frontend/generated/api.schemas'
import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'
+import { EMAIL_PREFILL_PARAM, messageDraftEmail, parseMessageDraftPrefill } from '../MessageAudience/messageDrafts'
import type { MissingRecipientEmailBannerProps } from '../Workflows/hogflows/steps/components/MissingRecipientEmailBanner'
import {
DEFAULT_STATE,
@@ -322,6 +323,12 @@ export interface broadcastWizardLogicActions {
hydrateFromBroadcast: (broadcast: HogFlowApi) => {
broadcast: HogFlowApi
}
+ landOnPrefilledStep: () => {
+ value: true
+ }
+ landOnStep: (step: BroadcastWizardStep) => {
+ step: BroadcastWizardStep
+ }
launchBroadcast: () => {
value: true
}
@@ -593,6 +600,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions({
setStep: (step: BroadcastWizardStep) => ({ step }),
+ landOnStep: (step: BroadcastWizardStep) => ({ step }),
+ landOnPrefilledStep: true,
nextStep: true,
prevStep: true,
continueStep: true,
@@ -744,6 +753,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
'recipients' as BroadcastWizardStep,
{
setStep: (_, { step }) => step,
+ landOnStep: (_, { step }) => step,
nextStep: (state) => {
const index = BROADCAST_WIZARD_STEPS.indexOf(state)
return BROADCAST_WIZARD_STEPS[Math.min(index + 1, BROADCAST_WIZARD_STEPS.length - 1)]
@@ -854,6 +864,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
DEFAULT_BROADCAST_EMAIL,
{
setEmail: (_, { email }) => email,
+ prefillFromLink: (state, { prefill }) =>
+ prefill.email ? { ...state, ...messageDraftEmail(prefill.email) } : state,
defaultSenderApplied: (state, { integrationId }) =>
state.from?.integrationId ? state : { ...state, from: { ...state.from, integrationId } },
applyExternalEdit: (state, { broadcast }) => {
@@ -1256,8 +1268,41 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
// pinned: analytics event name
posthog.capture('email sender preselected', { surface: 'broadcast', reason: sender.reason })
},
- [integrationsLogic.actionTypes.loadIntegrationsSuccess]: () => actions.applyDefaultSender(),
- [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => actions.applyDefaultSender(),
+ [integrationsLogic.actionTypes.loadIntegrationsSuccess]: () => {
+ actions.applyDefaultSender()
+ actions.landOnPrefilledStep()
+ },
+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => {
+ actions.applyDefaultSender()
+ actions.landOnPrefilledStep()
+ },
+ landOnPrefilledStep: () => {
+ // A link that filled the audience skips ahead to the first step that still needs input,
+ // or to Review when nothing does. It waits for the senders, because the default sender
+ // decides whether the email is complete, and it runs once.
+ if (!cache.landOnPrefilledStep || values.integrations === null || values.integrationsLoading) {
+ return
+ }
+ if (!values.currentTeam) {
+ return
+ }
+ cache.landOnPrefilledStep = false
+ if (values.currentStep !== 'recipients') {
+ return
+ }
+ const step = values.firstInvalidStep ?? 'review'
+ if (step !== 'recipients') {
+ actions.landOnStep(step)
+ }
+ },
+ landOnStep: ({ step }) => {
+ // Unlike setStep, this doesn't create a draft on the content step: following a link must
+ // not leave one behind. Continue or launch saves it.
+ if (step === 'review') {
+ actions.loadBlastRadius()
+ }
+ actions.reportReviewVisit()
+ },
expandRun: ({ runId }) => {
actions.setExpandedRunOverride([...values.expandedRunIds.filter((id) => id !== runId), runId])
},
@@ -1721,6 +1766,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
audience_filter_count: values.audienceProperties.length,
has_goal: values.goalEnabled,
entry_source: values.entrySource ?? loadEntrySource(broadcastId),
+ ...(cache.prefilledEmail
+ ? { prefilled_email_edited: !prefilledEmailUnchanged(cache.prefilledEmail, values.email) }
+ : {}),
seconds_since_created: activated
? Math.round((Date.now() - new Date(activated.created_at).getTime()) / 1000)
: null,
@@ -1891,7 +1939,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
},
})),
- afterMount(({ actions, props }) => {
+ afterMount(({ actions, props, cache }) => {
if (props.id !== 'new') {
actions.loadBroadcast()
return
@@ -1901,32 +1949,40 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
[AUDIENCE_PREFILL_PARAM]: audience,
[NAME_PREFILL_PARAM]: name,
[SOURCE_PREFILL_PARAM]: source,
- ...searchParams
+ [EMAIL_PREFILL_PARAM]: emailParam,
} = router.values.searchParams
const properties = parseBroadcastAudiencePrefill(audience)
- if (audience !== undefined || name !== undefined || source !== undefined) {
+ const email = parseMessageDraftPrefill(emailParam)
+ const fromLink =
+ audience !== undefined || name !== undefined || source !== undefined || emailParam !== undefined
+ if (fromLink) {
const prefill: BroadcastPrefill = {
properties: properties ?? [],
name: typeof name === 'string' ? name : undefined,
source: typeof source === 'string' ? source : undefined,
+ email: email ?? undefined,
}
// Not setAudienceProperties: opening /broadcasts/new must not create a draft.
actions.prefillFromLink(prefill)
+ if (email) {
+ cache.prefilledEmail = { ...DEFAULT_BROADCAST_EMAIL, ...messageDraftEmail(email) }
+ }
if (properties) {
+ cache.landOnPrefilledStep = true
// pinned: analytics event name
posthog.capture('broadcast prefilled from link', {
entry_source: prefill.source ?? null,
audience_filter_count: properties.length,
+ has_email: !!email,
})
}
}
if (audience !== undefined && !properties) {
actions.rejectLinkAudience()
}
- if (audience !== undefined || name !== undefined || source !== undefined) {
- router.actions.replace(router.values.location.pathname, searchParams, router.values.hashParams)
- }
+ // The link stays in the URL until the draft exists, so a reload before Continue opens the same prefill.
actions.loadBlastRadius()
+ actions.landOnPrefilledStep()
}),
])
@@ -2154,3 +2210,7 @@ export function buildBroadcastPayload(values: {
],
}
}
+
+function prefilledEmailUnchanged(prefilled: BroadcastEmailValue, current: BroadcastEmailValue): boolean {
+ return prefilled.subject === current.subject && prefilled.html === current.html && prefilled.text === current.text
+}
diff --git a/products/workflows/frontend/MessageAudience/messageAudience.ts b/products/workflows/frontend/MessageAudience/messageAudience.ts
index a882b9e18d86..751b9853ef97 100644
--- a/products/workflows/frontend/MessageAudience/messageAudience.ts
+++ b/products/workflows/frontend/MessageAudience/messageAudience.ts
@@ -4,6 +4,7 @@ import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types
import { urlForNewBroadcastWithAudience } from '../Broadcasts/broadcastAudiencePrefill'
import { type WorkflowTriggerConfig, urlForNewWorkflowWithTrigger } from '../Workflows/workflowTriggerPrefill'
+import { MessageDraft } from './messageDrafts'
export type MessageAudienceDestination = 'broadcast' | 'workflow'
@@ -13,6 +14,8 @@ export interface MessageAudience {
broadcastName?: string
/** The workflow to start. Without one, the workflow sends to the same people with a batch trigger. */
workflowTrigger?: WorkflowTriggerConfig
+ broadcastEmail?: MessageDraft
+ workflowEmail?: MessageDraft
}
export function cohortAudienceProperties(cohort: { id: number; name?: string | null }): AnyPropertyFilter[] {
@@ -33,11 +36,13 @@ export function messageAudienceUrl(audience: MessageAudience, destination: Messa
properties: audience.properties,
name: audience.broadcastName,
source: audience.source,
+ email: audience.broadcastEmail,
})
}
return urlForNewWorkflowWithTrigger(
audience.workflowTrigger ?? { type: 'batch', filters: { properties: audience.properties } },
- audience.source
+ audience.source,
+ audience.workflowEmail
)
}
diff --git a/products/workflows/frontend/MessageAudience/messageDrafts.test.ts b/products/workflows/frontend/MessageAudience/messageDrafts.test.ts
new file mode 100644
index 000000000000..1651c6d96ba9
--- /dev/null
+++ b/products/workflows/frontend/MessageAudience/messageDrafts.test.ts
@@ -0,0 +1,46 @@
+import { draftMessage, messageDraftEmail, parseMessageDraftPrefill } from './messageDrafts'
+
+describe('messageDrafts', () => {
+ it('escapes a feature name in the html and design but keeps it as typed in the subject and text', () => {
+ const draft = draftMessage({
+ kind: 'feature_available',
+ featureName: 'Beta <script>alert(1)</script> & co',
+ featureDescription: '',
+ })
+ const email = messageDraftEmail(parseMessageDraftPrefill(JSON.stringify(draft))!)
+
+ expect(email.subject).toEqual('Beta <script>alert(1)</script> & co is now available')
+ expect(email.text).toContain('try Beta <script>alert(1)</script> & co early')
+ expect(email.html).not.toContain('<script>')
+ expect(email.html).toContain('Beta &lt;script&gt;alert(1)&lt;/script&gt; &amp; co')
+ expect(JSON.stringify(email.design)).not.toContain('<script>')
+ expect(email.text.split('\n\n')).toEqual(draft.paragraphs)
+ })
+
+ it.each([
+ ['a feature name', messageDraftEmail(draftMessage({ kind: 'feature_available', featureName: '{{ x }}' }))],
+ [
+ 'a link',
+ messageDraftEmail(parseMessageDraftPrefill('{"subject":"{{ x }}","paragraphs":["{% endraw %}{{ x }}"]}')!),
+ ],
+ ])('makes Liquid delimiters in %s print as typed', (_label, email) => {
+ const rendered = [email.subject, email.text, email.html, JSON.stringify(email.design)].join()
+ expect(rendered).not.toMatch(/\{\{ x|\{% endraw/)
+ expect(rendered).toContain(`{{ '{{' }} x }}`)
+ })
+
+ it.each([
+ ['nothing', undefined],
+ ['a non-JSON string', 'not-json'],
+ ['a missing subject', '{"paragraphs":["Hi"]}'],
+ ['an empty subject', '{"subject":" ","paragraphs":["Hi"]}'],
+ ['no paragraphs', '{"subject":"Hi","paragraphs":[]}'],
+ ['a paragraph that is not text', '{"subject":"Hi","paragraphs":[{"html":"<b>x</b>"}]}'],
+ [
+ 'a subject longer than an email subject can be',
+ JSON.stringify({ subject: 'x'.repeat(301), paragraphs: ['Hi'] }),
+ ],
+ ])('ignores a link with %s', (_label, raw) => {
+ expect(parseMessageDraftPrefill(raw)).toBeNull()
+ })
+})
diff --git a/products/workflows/frontend/MessageAudience/messageDrafts.ts b/products/workflows/frontend/MessageAudience/messageDrafts.ts
new file mode 100644
index 000000000000..17f131490b12
--- /dev/null
+++ b/products/workflows/frontend/MessageAudience/messageDrafts.ts
@@ -0,0 +1,175 @@
+import { NEW_TEMPLATE } from '../TemplateLibrary/constants'
+
+export interface MessageDraft {
+ subject: string
+ paragraphs: string[]
+}
+
+export type MessageDraftContext =
+ | { kind: 'issue_fixed' }
+ | { kind: 'issue_hit' }
+ | { kind: 'feature_available'; featureName: string; featureDescription?: string | null }
+ | { kind: 'feature_enrolled'; featureName: string; featureDescription?: string | null }
+ | { kind: 'survey_responded' }
+
+export interface MessageDraftEmail {
+ subject: string
+ html: string
+ text: string
+ design: Record<string, any>
+}
+
+// pinned: URL search param, entry points link to /broadcasts/new and /workflows/new with it
+export const EMAIL_PREFILL_PARAM = 'email'
+
+const MAX_NAME_LENGTH = 100
+const MAX_DESCRIPTION_LENGTH = 1000
+const MAX_SUBJECT_LENGTH = 300
+const MAX_PARAGRAPHS = 10
+const MAX_PARAGRAPH_LENGTH = 2000
+
+const GREETING = 'Hi there,'
+
+function clip(value: string, max: number): string {
+ const trimmed = value.trim()
+ return trimmed.length > max ? `${trimmed.slice(0, max - 1).trimEnd()}…` : trimmed
+}
+
+export function draftMessage(context: MessageDraftContext): MessageDraft {
+ switch (context.kind) {
+ case 'issue_fixed':
+ return {
+ subject: 'We fixed an issue you ran into',
+ paragraphs: [
+ GREETING,
+ 'You recently ran into an error while using our product. We found the cause and fixed it.',
+ 'Sorry for the trouble, and thanks for your patience.',
+ ],
+ }
+ case 'issue_hit':
+ return {
+ subject: 'Sorry about the error you ran into',
+ paragraphs: [
+ GREETING,
+ "It looks like you ran into an error while using our product. We know about it and we're working on a fix.",
+ 'Sorry for the trouble.',
+ ],
+ }
+ case 'feature_available': {
+ const name = clip(context.featureName, MAX_NAME_LENGTH)
+ return {
+ subject: `${name} is now available`,
+ paragraphs: [
+ GREETING,
+ `Thanks for signing up to try ${name} early. It's now available to you.`,
+ ...descriptionParagraph(context.featureDescription),
+ 'Let us know what you think.',
+ ],
+ }
+ }
+ case 'feature_enrolled': {
+ const name = clip(context.featureName, MAX_NAME_LENGTH)
+ return {
+ subject: `You have early access to ${name}`,
+ paragraphs: [
+ GREETING,
+ `Thanks for joining the early access for ${name}. You can start using it now.`,
+ ...descriptionParagraph(context.featureDescription),
+ 'Let us know what you think.',
+ ],
+ }
+ }
+ case 'survey_responded':
+ return {
+ subject: 'Thanks for your feedback',
+ paragraphs: [
+ GREETING,
+ 'Thanks for taking the time to answer our survey. Your answers help us decide what to work on next.',
+ ],
+ }
+ }
+}
+
+function descriptionParagraph(description: string | null | undefined): string[] {
+ const text = description ? clip(description, MAX_DESCRIPTION_LENGTH) : ''
+ return text ? [text] : []
+}
+
+export function parseMessageDraftPrefill(raw: unknown): MessageDraft | null {
+ let value = raw
+ if (typeof raw === 'string') {
+ try {
+ value = JSON.parse(raw)
+ } catch {
+ return null
+ }
+ }
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return null
+ }
+ const { subject, paragraphs } = value as Record<string, unknown>
+ if (typeof subject !== 'string' || !subject.trim() || subject.length > MAX_SUBJECT_LENGTH) {
+ return null
+ }
+ if (
+ !Array.isArray(paragraphs) ||
+ paragraphs.length === 0 ||
+ paragraphs.length > MAX_PARAGRAPHS ||
+ !paragraphs.every((paragraph) => typeof paragraph === 'string' && paragraph.length <= MAX_PARAGRAPH_LENGTH)
+ ) {
+ return null
+ }
+ return { subject: subject.trim(), paragraphs: paragraphs as string[] }
+}
+
+// Quotes stay as typed: the liquid renderer only decodes &lt;, &gt; and &amp; inside a tag,
+// so an escaped quote would break a merge tag someone adds while editing the draft.
+function escapeHtml(value: string): string {
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+}
+
+// The email is rendered as Liquid, so a name like "{{ person.properties.email }}" must print as typed.
+function literalLiquid(value: string): string {
+ return value.replace(/\{[{%]/g, (delimiter) => `{{ '${delimiter}' }}`)
+}
+
+function paragraphHtml(paragraph: string): string {
+ return `<p style="line-height: 140%; margin: 0;">${escapeHtml(paragraph)}</p>`
+}
+
+/**
+ * The draft as the email step stores it. Each paragraph is its own text block in the design, so
+ * the visual editor opens with the draft in place and keeps the gap between paragraphs.
+ */
+export function messageDraftEmail(untrusted: MessageDraft): MessageDraftEmail {
+ const draft = { subject: literalLiquid(untrusted.subject), paragraphs: untrusted.paragraphs.map(literalLiquid) }
+ const body = draft.paragraphs
+ .map(
+ (paragraph) =>
+ `<div style="padding: 10px; font-family: arial, helvetica, sans-serif; font-size: 14px; line-height: 140%; text-align: left;">${paragraphHtml(paragraph)}</div>`
+ )
+ .join('')
+ return {
+ subject: draft.subject,
+ html: `<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /></head><body style="margin: 0; padding: 0; background-color: #F7F8F9; color: #000000;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: #F7F8F9;"><tr><td align="center"><table role="presentation" width="500" cellpadding="0" cellspacing="0" border="0" style="max-width: 500px; width: 100%;"><tr><td>${body}</td></tr></table></td></tr></table></body></html>`,
+ text: draft.paragraphs.join('\n\n'),
+ design: textBlocksDesign(draft.paragraphs),
+ }
+}
+
+function textBlocksDesign(paragraphs: string[]): Record<string, any> {
+ const design = JSON.parse(JSON.stringify(NEW_TEMPLATE.content.email.design))
+ const column = design.body.rows[0].columns[0]
+ const textBlock = column.contents.find((content: Record<string, any>) => content.type === 'text')
+ column.contents = paragraphs.map((paragraph, index) => ({
+ ...textBlock,
+ id: `draft-text-${index + 1}`,
+ values: {
+ ...textBlock.values,
+ text: paragraphHtml(paragraph),
+ _meta: { htmlID: `u_content_text_${index + 1}`, htmlClassNames: 'u_content_text' },
+ },
+ }))
+ design.counters = { u_row: 1, u_column: 1, u_content_text: paragraphs.length }
+ return design
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index f0b82a15576d..fc0481601565 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -23,6 +23,7 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { ActivityScope } from '~/types'
import { SOURCE_PREFILL_PARAM } from '../Broadcasts/broadcastAudiencePrefill'
+import { EMAIL_PREFILL_PARAM } from '../MessageAudience/messageDrafts'
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
import { NewWorkflowAgent } from './NewWorkflowAgent'
import { newWorkflowLogic } from './newWorkflowLogic'
@@ -74,11 +75,15 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
? JSON.stringify(rawTriggerPrefill)
: rawTriggerPrefill
const entrySource = searchParams[SOURCE_PREFILL_PARAM]
+ const rawEmailPrefill = searchParams[EMAIL_PREFILL_PARAM]
+ const emailPrefill =
+ rawEmailPrefill && typeof rawEmailPrefill !== 'string' ? JSON.stringify(rawEmailPrefill) : rawEmailPrefill
const workflowProps: WorkflowLogicProps = {
id: workflowSceneProps.id,
templateId,
editTemplateId,
triggerPrefill,
+ emailPrefill,
entrySource: typeof entrySource === 'string' ? entrySource : undefined,
}
diff --git a/products/workflows/frontend/Workflows/workflowEmailPrefill.test.ts b/products/workflows/frontend/Workflows/workflowEmailPrefill.test.ts
new file mode 100644
index 000000000000..d67b71e79f1c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowEmailPrefill.test.ts
@@ -0,0 +1,44 @@
+import { draftMessage } from '../MessageAudience/messageDrafts'
+import { prefilledWorkflow, withEmailSender } from './workflowEmailPrefill'
+import { NEW_WORKFLOW } from './workflowLogic'
+import type { WorkflowTriggerConfig } from './workflowTriggerPrefill'
+
+const EVENT_TRIGGER: WorkflowTriggerConfig = {
+ type: 'event',
+ filters: { events: [{ id: '$exception', name: '$exception', type: 'events' }] },
+}
+const BATCH_TRIGGER: WorkflowTriggerConfig = { type: 'batch', filters: { properties: [] } }
+
+describe('workflowEmailPrefill', () => {
+ it.each([
+ {
+ trigger: 'an event trigger',
+ config: EVENT_TRIGGER,
+ masking: { hash: '{person.id}', ttl: null, threshold: null },
+ },
+ { trigger: 'a batch trigger', config: BATCH_TRIGGER, masking: undefined },
+ ])('opens $trigger with a draft email as trigger, email, exit', ({ config, masking }) => {
+ const workflow = prefilledWorkflow(NEW_WORKFLOW, config, draftMessage({ kind: 'issue_hit' }))
+
+ expect(workflow.actions.map((action) => action.type)).toEqual(['trigger', 'function_email', 'exit'])
+ expect(workflow.edges.map(({ from, to }) => [from, to])).toEqual([
+ ['trigger_node', 'action_function_email_prefilled'],
+ ['action_function_email_prefilled', 'exit_node'],
+ ])
+ expect((workflow.actions[1].config as any).inputs.email.value).toMatchObject({
+ to: { email: '{{ person.properties.email }}' },
+ subject: 'Sorry about the error you ran into',
+ })
+ expect(workflow.trigger_masking).toEqual(masking)
+ })
+
+ it('keeps a sender the email step already has and fills the ones without', () => {
+ const workflow = prefilledWorkflow(NEW_WORKFLOW, EVENT_TRIGGER, draftMessage({ kind: 'issue_hit' }))
+ const filled = withEmailSender(workflow, 5)
+ const refilled = withEmailSender(filled.workflow, 9)
+
+ expect(filled.filled).toBe(true)
+ expect((filled.workflow.actions[1].config as any).inputs.email.value.from).toEqual({ integrationId: 5 })
+ expect(refilled).toEqual({ workflow: filled.workflow, filled: false })
+ })
+})
diff --git a/products/workflows/frontend/Workflows/workflowEmailPrefill.ts b/products/workflows/frontend/Workflows/workflowEmailPrefill.ts
new file mode 100644
index 000000000000..381594868b03
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowEmailPrefill.ts
@@ -0,0 +1,85 @@
+import { MessageDraft, messageDraftEmail } from '../MessageAudience/messageDrafts'
+import type { HogFlow, HogFlowAction } from './hogflows/types'
+import type { WorkflowTriggerConfig } from './workflowTriggerPrefill'
+
+const EMAIL_ACTION_ID = 'action_function_email_prefilled'
+// The same "One time" setting as the trigger's frequency picker, so the editor shows it selected.
+const ONCE_PER_PERSON_MASKING = { hash: '{person.id}', ttl: null, threshold: null }
+
+/**
+ * A new workflow that opens ready to enable: the trigger, then the email, then exit. An event
+ * trigger sends at most once per person, because someone who hits the event again would
+ * otherwise get the same email again.
+ */
+export function prefilledWorkflow(base: HogFlow, trigger: WorkflowTriggerConfig, email: MessageDraft | null): HogFlow {
+ const triggerAction = base.actions.find((action) => action.type === 'trigger')
+ const exitAction = base.actions.find((action) => action.type === 'exit')
+ if (!triggerAction || !exitAction) {
+ return base
+ }
+ const withTrigger = { ...triggerAction, config: trigger } as HogFlowAction
+ if (!email) {
+ return {
+ ...base,
+ actions: base.actions.map((action) => (action.type === 'trigger' ? withTrigger : action)),
+ }
+ }
+ const content = messageDraftEmail(email)
+ const emailAction = {
+ id: EMAIL_ACTION_ID,
+ type: 'function_email',
+ name: 'Email',
+ description: 'Send an email to the user.',
+ created_at: 0,
+ updated_at: 0,
+ config: {
+ template_id: 'template-email',
+ inputs: {
+ email: {
+ templating: 'liquid',
+ value: {
+ to: { email: '{{ person.properties.email }}', name: '' },
+ from: {},
+ replyTo: '',
+ cc: '',
+ bcc: '',
+ preheader: '',
+ ...content,
+ },
+ },
+ },
+ },
+ } as HogFlowAction
+ return {
+ ...base,
+ ...(trigger.type === 'event' ? { trigger_masking: ONCE_PER_PERSON_MASKING as HogFlow['trigger_masking'] } : {}),
+ actions: [withTrigger, emailAction, exitAction],
+ edges: [
+ { from: withTrigger.id, to: emailAction.id, type: 'continue' },
+ { from: emailAction.id, to: exitAction.id, type: 'continue' },
+ ],
+ }
+}
+
+export function withEmailSender(workflow: HogFlow, integrationId: number): { workflow: HogFlow; filled: boolean } {
+ let filled = false
+ const actions = workflow.actions.map((action) => {
+ const config = action.config as Record<string, any>
+ const value = config?.template_id === 'template-email' ? config.inputs?.email?.value : null
+ if (!value || value.from?.integrationId) {
+ return action
+ }
+ filled = true
+ return {
+ ...action,
+ config: {
+ ...config,
+ inputs: {
+ ...config.inputs,
+ email: { ...config.inputs.email, value: { ...value, from: { ...value.from, integrationId } } },
+ },
+ },
+ } as HogFlowAction
+ })
+ return { workflow: filled ? { ...workflow, actions } : workflow, filled }
+}
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index a51abf641a0c..9c0fd29b853a 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -19,6 +19,7 @@ import { objectsEqual } from 'lib/utils/objects'
import { sanitizeInputs } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'
import type { EmailFieldErrors } from 'scenes/hog-functions/email-templater/types'
import { projectLogic } from 'scenes/projectLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -29,6 +30,8 @@ import { hogFlowsResumeEmailSending } from 'products/workflows/frontend/generate
import type { ResourceEditedEvent, UserBasicType, UserType } from '../../../../frontend/src/types'
import { loadEntrySource, saveEntrySource } from '../Broadcasts/broadcastUsage'
+import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'
+import { parseMessageDraftPrefill } from '../MessageAudience/messageDrafts'
import { getRegisteredTriggerTypes } from './hogflows/registry/triggers/triggerTypeRegistry'
import {
DEFAULT_STATE,
@@ -54,6 +57,7 @@ import {
import { openPublishConfirmDialog } from './PublishImpactDialog'
import { ResourceSaveQueue } from './resourceSaveQueue'
import { prepareWorkflowDuplicate } from './workflowDuplication'
+import { prefilledWorkflow, withEmailSender } from './workflowEmailPrefill'
import { workflowSceneLogic } from './workflowSceneLogic'
import { workflowsLogic } from './workflowsLogic'
import { parseWorkflowTriggerPrefill } from './workflowTriggerPrefill'
@@ -63,6 +67,7 @@ export interface WorkflowLogicProps {
templateId?: string
editTemplateId?: string
triggerPrefill?: string
+ emailPrefill?: string
entrySource?: string
}
@@ -124,6 +129,28 @@ export const PERSON_DEPENDENT_ACTION_TYPES = new Set(['wait_until_condition', 'r
// the backend's ROW_SCOPED_TRIGGER_TYPES, which is the authoritative check.
export const ROW_SCOPED_TRIGGER_TYPES = new Set(['data-warehouse-table', 'data-warehouse-view', 'internal-event'])
+async function withDefaultEmailSender(workflow: HogFlow): Promise<HogFlow> {
+ try {
+ const team = teamLogic.findMounted()?.values.currentTeam
+ const sender = resolveDefaultEmailSender(
+ (await api.integrations.list()).results,
+ team && 'workflows_config' in team ? team.workflows_config?.default_email_integration_id : null
+ )
+ if (!sender) {
+ return workflow
+ }
+ const result = withEmailSender(workflow, sender.integrationId)
+ if (result.filled) {
+ // pinned: analytics event name
+ posthog.capture('email sender preselected', { surface: 'workflow', reason: sender.reason })
+ }
+ return result.workflow
+ } catch {
+ // The sender is a convenience. The person can still pick one, so a failed lookup doesn't block the editor.
+ return workflow
+ }
+}
+
function getTemplatingError(value: string, templating?: 'liquid' | 'hog'): string | undefined {
if (templating === 'liquid' && typeof value === 'string') {
try {
@@ -3079,7 +3106,7 @@ export const workflowLogic = kea<workflowLogicType>([
props({ id: 'new' } as WorkflowLogicProps),
key(
(props) =>
- `workflow-${props.id || 'new'}-${props.templateId || 'default'}-${props.editTemplateId || 'default'}-${props.triggerPrefill || 'default'}`
+ `workflow-${props.id || 'new'}-${props.templateId || 'default'}-${props.editTemplateId || 'default'}-${props.triggerPrefill || 'default'}-${props.emailPrefill || 'default'}`
),
connect(() => ({
values: [userLogic, ['user'], projectLogic, ['currentProjectId']],
@@ -3165,17 +3192,17 @@ export const workflowLogic = kea<workflowLogicType>([
delete (newWorkflow as any).updated_at
delete (newWorkflow as any).created_by
- return newWorkflow
+ return (await withDefaultEmailSender(newWorkflow as HogFlow)) as typeof newWorkflow
}
const triggerConfig = parseWorkflowTriggerPrefill(props.triggerPrefill)
if (triggerConfig) {
- const prefilled: HogFlow = {
- ...NEW_WORKFLOW,
- actions: NEW_WORKFLOW.actions.map((action) =>
- action.type === 'trigger' ? { ...action, config: triggerConfig } : action
- ),
- }
- return prefilled
+ return await withDefaultEmailSender(
+ prefilledWorkflow(
+ NEW_WORKFLOW,
+ triggerConfig,
+ parseMessageDraftPrefill(props.emailPrefill)
+ )
+ )
}
return { ...NEW_WORKFLOW }
}
diff --git a/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts b/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts
index 07a8a0fd1897..a1dfd7f37d77 100644
--- a/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts
+++ b/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts
@@ -3,6 +3,7 @@ import { combineUrl } from 'kea-router'
import { urls } from 'scenes/urls'
import { SOURCE_PREFILL_PARAM, parseBroadcastAudiencePrefill } from '../Broadcasts/broadcastAudiencePrefill'
+import { EMAIL_PREFILL_PARAM, MessageDraft } from '../MessageAudience/messageDrafts'
import { HogFlowTriggerSchema } from './hogflows/steps/types'
import type { HogFlowAction } from './hogflows/types'
@@ -10,10 +11,15 @@ export type WorkflowTriggerConfig = Extract<HogFlowAction, { type: 'trigger' }>[
export const TRIGGER_PREFILL_PARAM = 'trigger'
-export function urlForNewWorkflowWithTrigger(config: WorkflowTriggerConfig, source?: string): string {
+export function urlForNewWorkflowWithTrigger(
+ config: WorkflowTriggerConfig,
+ source?: string,
+ email?: MessageDraft
+): string {
return combineUrl(urls.workflowNew(), {
[TRIGGER_PREFILL_PARAM]: JSON.stringify(config),
...(source ? { [SOURCE_PREFILL_PARAM]: source } : {}),
+ ...(email ? { [EMAIL_PREFILL_PARAM]: JSON.stringify(email) } : {}),
}).url
}