: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): fill entry-point emails with an ai draft (#114832)
Daniel Marchuk19d2155d3312
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 83db3a66734f..2e183a43fb96 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -642,6 +642,7 @@ export const FEATURE_FLAGS = {WORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflowsWORKFLOW_CLASSIFY_ACTION: 'workflow-classify-action', // owner: #team-workflowsWORKFLOW_RUN_SCOUT_ACTION: 'workflow-run-scout-action', // owner: #team-workflows+ WORKFLOWS_AI_EMAIL_DRAFT: 'workflows-ai-email-draft', // owner: @dmarchuk #team-workflows, AI first draft for cross-product entry pointsWORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflowsWORKFLOWS_BROADCAST_RECIPIENT_LISTS: 'workflows-broadcast-recipient-lists', // owner: @mayteio #team-workflowsWORKFLOWS_COHORT_CONDITIONS: 'workflows-cohort-conditions', // owner: @meikelmosby #team-workflowsdiff --git a/frontend/src/scenes/cohorts/cohortSavedToast.ts b/frontend/src/scenes/cohorts/cohortSavedToast.tsindex 06fba288c4f6..20297d1728fc 100644--- a/frontend/src/scenes/cohorts/cohortSavedToast.ts+++ b/frontend/src/scenes/cohorts/cohortSavedToast.ts@@ -26,7 +26,14 @@ export function cohortSavedToast(cohort: Pick<CohortType, 'id' | 'name'>, sourceaction: () => {captureMessageAudienceClicked(source, 'broadcast')router.actions.push(- messageAudienceUrl({ properties: cohortAudienceProperties(savedCohort), source }, 'broadcast')+ messageAudienceUrl(+ {+ properties: cohortAudienceProperties(savedCohort),+ source,+ draftSource: { source: 'cohort', source_id: String(savedCohort.id) },+ },+ 'broadcast'+ ))},},diff --git a/frontend/src/scenes/cohorts/cohortUtils.tsx b/frontend/src/scenes/cohorts/cohortUtils.tsxindex ba5a920116d7..312bfa37e5c6 100644--- a/frontend/src/scenes/cohorts/cohortUtils.tsx+++ b/frontend/src/scenes/cohorts/cohortUtils.tsx@@ -727,5 +727,12 @@ export function cohortBroadcastDisabledReason(cohort: CohortType): string | null}export function urlForCohortBroadcast(cohort: { id: number; name?: string }): string {- return messageAudienceUrl({ properties: cohortAudienceProperties(cohort), source: 'cohort' }, 'broadcast')+ return messageAudienceUrl(+ {+ properties: cohortAudienceProperties(cohort),+ source: 'cohort',+ draftSource: { source: 'cohort', source_id: String(cohort.id) },+ },+ 'broadcast'+ )}diff --git a/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsx b/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsxindex b68ae802a328..72d09ed4437b 100644--- a/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsx+++ b/frontend/src/scenes/surveys/components/SurveyFollowUpWorkflowButton.tsx@@ -39,7 +39,8 @@ export function SurveyFollowUpWorkflowButton({ surveyId }: { surveyId: string })urlForNewWorkflowWithTrigger(surveyFollowUpTrigger(surveyId),SOURCE,- draftMessage({ kind: 'survey_responded' })+ draftMessage({ kind: 'survey_responded' }),+ { source: 'survey', source_id: surveyId }))}}diff --git a/products/early_access_features/frontend/EarlyAccessFeature.tsx b/products/early_access_features/frontend/EarlyAccessFeature.tsxindex bc9d2d3ce7ba..9573f3a14628 100644--- a/products/early_access_features/frontend/EarlyAccessFeature.tsx+++ b/products/early_access_features/frontend/EarlyAccessFeature.tsx@@ -172,6 +172,7 @@ function enrolledPeopleAudience(earlyAccessFeature: EarlyAccessFeatureType): MesfeatureName: earlyAccessFeature.name,featureDescription: earlyAccessFeature.description,}),+ draftSource: { source: 'early_access', source_id: earlyAccessFeature.id },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.tsxindex 6330618bd71e..d8c18f768483 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueWorkflowButton.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/IssueWorkflowButton.tsx@@ -35,7 +35,8 @@ export function IssueWorkflowButton({ issueId }: { issueId: string }): JSX.ElemeurlForNewWorkflowWithTrigger(issueWorkflowTrigger(issueId),SOURCE,- draftMessage({ kind: 'issue_hit' })+ draftMessage({ kind: 'issue_hit' }),+ { source: 'error_tracking', source_id: issueId }))}}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.tsindex f10f3a916189..e8236c88b08a 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ScenePanel/issueAffectedBroadcastLogic.ts@@ -190,6 +190,7 @@ export const issueAffectedBroadcastLogic = kea<issueAffectedBroadcastLogicType>(source: SOURCE,broadcastName: truncate(`We fixed ${props.issueName || 'an error'}`, MAX_NAME_LENGTH),broadcastEmail: draftMessage({ kind: 'issue_fixed' }),+ draftSource: { source: 'error_tracking', source_id: props.issueId },},'broadcast')diff --git a/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.ts b/products/workflows/frontend/Broadcasts/broadcastAudiencePrefill.tsindex 2d102d90d9f1..0d66f226dd40 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 type { EmailDraftRequestApi } from '../generated/api.schemas'+import { DRAFT_SOURCE_PARAM } from '../MessageAudience/aiEmailDraft'import { EMAIL_PREFILL_PARAM, MessageDraft } from '../MessageAudience/messageDrafts'// pinned: URL search params, other products link to /broadcasts/new with these@@ -17,14 +19,22 @@ export interface BroadcastPrefill {/** The product surface the person came from, reported on the launch event. */source?: stringemail?: MessageDraft+ draftSource?: EmailDraftRequestApi}-export function urlForNewBroadcastWithAudience({ properties, name, source, email }: BroadcastPrefill): string {+export function urlForNewBroadcastWithAudience({+ properties,+ name,+ source,+ email,+ draftSource,+}: 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) } : {}),+ ...(draftSource ? { [DRAFT_SOURCE_PARAM]: JSON.stringify(draftSource) } : {}),}).url}diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.tsindex aded17e2ec02..8579b22be8e5 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts@@ -1,7 +1,9 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { FEATURE_FLAGS } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -197,6 +199,70 @@ describe('broadcastWizardLogic', () => {expect(createDraft).not.toHaveBeenCalled()})+ it.each([+ { case: 'untouched', edit: null, fallback: null, subject: 'Written by the model', status: 'applied' },+ {+ case: 'edited while it loads',+ edit: 'Typed by the person',+ fallback: null,+ subject: 'Typed by the person',+ status: null,+ },+ { case: 'rate limited', edit: null, fallback: 'rate_limited', subject: null, status: 'failed' },+ ])(+ 'replaces the link email with the AI draft only when it is $case',+ async ({ edit, fallback, subject, status }) => {+ let respond: (value: unknown) => void = () => {}+ useMocks({+ post: {+ '/api/projects/:team_id/workflow_email_drafts/': () =>+ new Promise((resolve) => {+ respond = resolve+ }).then((body) => [200, body]),+ },+ })+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.WORKFLOWS_AI_EMAIL_DRAFT]: true })+ logic.unmount()+ router.actions.push(+ urlForNewBroadcastWithAudience({+ properties: LOCAL_AUDIENCE,+ source: 'error_tracking',+ name: 'We fixed it',+ email: draftMessage({ kind: 'issue_fixed' }),+ draftSource: { source: 'error_tracking', source_id: 'issue-1' },+ })+ )+ logic = broadcastWizardLogic({ id: 'new' })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadAiEmailDraft'])+ expect(logic.values.aiEmailDraftLoading).toBe(true)+ if (edit) {+ logic.actions.setEmail({ ...logic.values.email, subject: edit })+ }+ respond({+ subject: 'Written by the model',+ preheader: '',+ html: '<p>Hi there,</p>\n<p>Second paragraph.</p>',+ text: 'Hi there,\n\nSecond paragraph.',+ generated_by: fallback ? 'template' : 'ai',+ template_reason: fallback,+ })+ await expectLogic(logic).toDispatchActions(['loadAiEmailDraftSuccess'])++ const applied = status === 'applied'+ const template = draftMessage({ kind: 'issue_fixed' })+ expect(logic.values.aiEmailDraftStatus?.status ?? null).toEqual(status)+ expect(logic.values.email.subject).toEqual(subject ?? template.subject)+ expect(logic.values.email.text).toEqual(+ applied ? 'Hi there,\n\nSecond paragraph.' : template.paragraphs.join('\n\n')+ )+ // The name was the link's, so it follows the AI subject and stays put otherwise.+ expect(logic.values.name).toEqual(applied ? 'Written by the model' : 'We fixed it')+ }+ )+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 0de780271951..cb6ba813a051 100644--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts@@ -5,8 +5,10 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { humanFriendlyDuration } from 'lib/utils/durations'import { humanFriendlyNumber } from 'lib/utils/numbers'import { objectsEqual } from 'lib/utils/objects'@@ -44,12 +46,27 @@ import type {HogFlowApi,HogFlowBatchJobApi,HogFlowConversionApi,+ EmailDraftRequestApi,HogFlowEmailSendingRateLimitApi,HogFlowScheduleApi,} from 'products/workflows/frontend/generated/api.schemas'import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'-import { EMAIL_PREFILL_PARAM, messageDraftEmail, parseMessageDraftPrefill } from '../MessageAudience/messageDrafts'+import {+ AiEmailDraftResult,+ DRAFT_SOURCE_PARAM,+ aiEmailDraftFailureMessage,+ captureAiEmailDraft,+ parseEmailDraftSource,+ requestAiEmailDraft,+} from '../MessageAudience/aiEmailDraft'+import type { AiEmailDraftStatusProps } from '../MessageAudience/AiEmailDraftStatus'+import {+ EMAIL_PREFILL_PARAM,+ MessageDraft,+ messageDraftEmail,+ parseMessageDraftPrefill,+} from '../MessageAudience/messageDrafts'import type { MissingRecipientEmailBannerProps } from '../Workflows/hogflows/steps/components/MissingRecipientEmailBanner'import {DEFAULT_STATE,@@ -94,6 +111,7 @@ import {export type BroadcastWizardStep = 'recipients' | 'goal' | 'content' | 'schedule' | 'review'+const DEFAULT_BROADCAST_NAME = 'New broadcast'const EMAIL_AUTOSAVE_RETRIES = 3const EMAIL_AUTOSAVE_RETRY_MS = 2000@@ -219,10 +237,15 @@ export interface BroadcastWizardLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface broadcastWizardLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicintegrations: IntegrationType[] | null // integrationsLogicintegrationsLoading: boolean // integrationsLogiccurrentProjectId: number | null // projectLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogic+ aiEmailDraft: AiEmailDraftResult | null+ aiEmailDraftApplied: boolean+ aiEmailDraftLoading: boolean+ aiEmailDraftStatus: AiEmailDraftStatusProps | nullaudienceCohortLaunchErrors: string[]audienceProperties: AnyPropertyFilter[]batchJobs: HogFlowBatchJobApi[]@@ -280,6 +303,9 @@ export interface broadcastWizardLogicActions {resourceEdited: (event: ResourceEditedEvent) => {event: ResourceEditedEvent} // resourceEditedLogic+ applyAiEmailDraft: (draft: MessageDraft) => {+ draft: MessageDraft+ }applyDefaultSender: () => {value: true}@@ -335,6 +361,21 @@ export interface broadcastWizardLogicActions {launchBroadcastFinished: () => {value: true}+ loadAiEmailDraft: (request: EmailDraftRequestApi) => EmailDraftRequestApi+ loadAiEmailDraftFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAiEmailDraftSuccess: (+ aiEmailDraft: AiEmailDraftResult,+ payload?: EmailDraftRequestApi+ ) => {+ aiEmailDraft: AiEmailDraftResult+ payload?: EmailDraftRequestApi+ }loadBatchJobs: () => anyloadBatchJobsFailure: (error: string,@@ -508,6 +549,11 @@ export interface broadcastWizardLogicActions {export interface broadcastWizardLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ aiEmailDraftStatus: (+ aiEmailDraftLoading: boolean,+ aiEmailDraftApplied: boolean,+ aiEmailDraft: AiEmailDraftResult | null+ ) => AiEmailDraftStatusProps | nullbroadcastAsWorkflow: (broadcast: HogFlowApi | null,name: string,@@ -594,6 +640,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([['currentTeam'],integrationsLogic,['integrations', 'integrationsLoading'],+ featureFlagLogic,+ ['featureFlags'],],actions: [resourceEditedLogic, ['resourceEdited']],})),@@ -618,6 +666,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([setEmailRateLimit: (emailRateLimit: HogFlowEmailSendingRateLimitApi | null) => ({ emailRateLimit }),setEmailSettings: (settings: Partial<BroadcastEmailSettings>) => ({ settings }),setEmail: (email: BroadcastEmailValue) => ({ email }),+ applyAiEmailDraft: (draft: MessageDraft) => ({ draft }),applyDefaultSender: true,defaultSenderApplied: (integrationId: number) => ({ integrationId }),setScheduleMode: (mode: BroadcastScheduleMode) => ({ mode }),@@ -716,6 +765,13 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([},},],+ aiEmailDraft: [+ null as AiEmailDraftResult | null,+ {+ loadAiEmailDraft: async (request: EmailDraftRequestApi) =>+ await requestAiEmailDraft(String(values.currentProjectId), request),+ },+ ],batchJobs: [[] as HogFlowBatchJobApi[],{@@ -765,7 +821,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([},],name: [- 'New broadcast',+ DEFAULT_BROADCAST_NAME as string,{setName: (_, { name }) => name,prefillFromLink: (state, { prefill }) => prefill.name || state,@@ -774,6 +830,12 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([changedElsewhere(broadcast, base, (b) => b.name) ? broadcast.name || state : state,},],+ aiEmailDraftApplied: [+ false,+ {+ applyAiEmailDraft: () => true,+ },+ ],// Kept for the launch event, so a launch counts toward the product it started from.// Set when a link's audience couldn't be used. While the audience is empty, sending to everyone needs an explicit choice.linkAudienceRejected: [@@ -866,6 +928,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([setEmail: (_, { email }) => email,prefillFromLink: (state, { prefill }) =>prefill.email ? { ...state, ...messageDraftEmail(prefill.email) } : state,+ applyAiEmailDraft: (state, { draft }) => ({ ...state, ...messageDraftEmail(draft) }),defaultSenderApplied: (state, { integrationId }) =>state.from?.integrationId ? state : { ...state, from: { ...state.from, integrationId } },applyExternalEdit: (state, { broadcast }) => {@@ -981,6 +1044,19 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([})),selectors({+ aiEmailDraftStatus: [+ (s) => [s.aiEmailDraftLoading, s.aiEmailDraftApplied, s.aiEmailDraft],+ (loading: boolean, applied: boolean, result: AiEmailDraftResult | null): AiEmailDraftStatusProps | null => {+ if (loading) {+ return { status: 'loading' }+ }+ if (applied) {+ return { status: 'applied' }+ }+ const message = aiEmailDraftFailureMessage(result)+ return message ? { status: 'failed', message } : null+ },+ ],// The saved broadcast overlaid with the editor's unsaved state, in the shape the AI assistant reads.broadcastAsWorkflow: [(s) => [@@ -1295,6 +1371,34 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([actions.landOnStep(step)}},+ loadAiEmailDraftSuccess: ({ aiEmailDraft, payload: request }) => {+ if (!aiEmailDraft || !request) {+ return+ }+ let skipped: 'edited' | 'saved' | null = null+ if (aiEmailDraft.draft) {+ // Once the person edits the email or a draft broadcast exists, their version wins.+ if (+ values.broadcastId ||+ values.saving ||+ values.launching ||+ getSaveQueue(cache, values).inFlight > 0+ ) {+ skipped = 'saved'+ } else if (!prefilledEmailUnchanged(cache.prefilledEmail ?? DEFAULT_BROADCAST_EMAIL, values.email)) {+ skipped = 'edited'+ } else {+ if (values.name === (cache.prefilledName ?? DEFAULT_BROADCAST_NAME)) {+ // The name was written for the template, so it follows the new subject until someone renames it.+ actions.setName(aiEmailDraft.draft.subject)+ }+ actions.applyAiEmailDraft(aiEmailDraft.draft)+ cache.prefilledEmail = { ...DEFAULT_BROADCAST_EMAIL, ...messageDraftEmail(aiEmailDraft.draft) }+ cache.prefilledEmailGeneratedBy = 'ai'+ }+ }+ captureAiEmailDraft('broadcast', request, aiEmailDraft, skipped)+ },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.@@ -1767,7 +1871,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([has_goal: values.goalEnabled,entry_source: values.entrySource ?? loadEntrySource(broadcastId),...(cache.prefilledEmail- ? { prefilled_email_edited: !prefilledEmailUnchanged(cache.prefilledEmail, values.email) }+ ? {+ prefilled_email_edited: !prefilledEmailUnchanged(cache.prefilledEmail, values.email),+ prefilled_email_generated_by: cache.prefilledEmailGeneratedBy ?? 'template',+ }: {}),seconds_since_created: activated? Math.round((Date.now() - new Date(activated.created_at).getTime()) / 1000)@@ -1939,7 +2046,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([},})),- afterMount(({ actions, props, cache }) => {+ afterMount(({ actions, props, values, cache }) => {if (props.id !== 'new') {actions.loadBroadcast()return@@ -1950,11 +2057,16 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([[NAME_PREFILL_PARAM]: name,[SOURCE_PREFILL_PARAM]: source,[EMAIL_PREFILL_PARAM]: emailParam,+ [DRAFT_SOURCE_PARAM]: draftSourceParam,} = router.values.searchParamsconst properties = parseBroadcastAudiencePrefill(audience)const email = parseMessageDraftPrefill(emailParam)const fromLink =- audience !== undefined || name !== undefined || source !== undefined || emailParam !== undefined+ audience !== undefined ||+ name !== undefined ||+ source !== undefined ||+ emailParam !== undefined ||+ draftSourceParam !== undefinedif (fromLink) {const prefill: BroadcastPrefill = {properties: properties ?? [],@@ -1964,6 +2076,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([}// Not setAudienceProperties: opening /broadcasts/new must not create a draft.actions.prefillFromLink(prefill)+ cache.prefilledName = values.nameif (email) {cache.prefilledEmail = { ...DEFAULT_BROADCAST_EMAIL, ...messageDraftEmail(email) }}@@ -1983,6 +2096,10 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([// The link stays in the URL until the draft exists, so a reload before Continue opens the same prefill.actions.loadBlastRadius()actions.landOnPrefilledStep()+ const draftSource = parseEmailDraftSource(draftSourceParam)+ if (draftSource && values.featureFlags[FEATURE_FLAGS.WORKFLOWS_AI_EMAIL_DRAFT]) {+ actions.loadAiEmailDraft(draftSource)+ }}),])@@ -2212,5 +2329,10 @@ export function buildBroadcastPayload(values: {}function prefilledEmailUnchanged(prefilled: BroadcastEmailValue, current: BroadcastEmailValue): boolean {- return prefilled.subject === current.subject && prefilled.html === current.html && prefilled.text === current.text+ return (+ prefilled.subject === current.subject &&+ (prefilled.preheader ?? '') === (current.preheader ?? '') &&+ prefilled.html === current.html &&+ prefilled.text === current.text+ )}diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsxindex cb95137ddb59..a0bd5fc919ed 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx@@ -10,6 +10,7 @@ import type { EmailFieldErrors, EmailTemplate } from 'scenes/hog-functions/emailimport { IntegrationType } from '~/types'import { EmailSetupModal } from '../../Channels/EmailSetup/EmailSetupModal'+import { AiEmailDraftStatus } from '../../MessageAudience/AiEmailDraftStatus'import { buildSampleGlobals } from '../../Workflows/hogflows/steps/components/HogFlowFunctionConfiguration'import { UtmTagFields } from '../../Workflows/hogflows/steps/components/UtmTagFields'import {@@ -21,7 +22,7 @@ import {} from '../broadcastWizardLogic'export function BroadcastContentStep(): JSX.Element {- const { broadcast, email, name, stepValidationErrors, selectedSender, emailSettings } =+ const { broadcast, email, name, stepValidationErrors, selectedSender, emailSettings, aiEmailDraftStatus } =useValues(broadcastWizardLogic)const { setEmail, setEmailSettings } = useActions(broadcastWizardLogic)const { integrations, integrationsLoading } = useValues(integrationsLogic)@@ -119,6 +120,7 @@ export function BroadcastContentStep(): JSX.Element {onComplete={closeSenderSetup}/>) : null}+ {aiEmailDraftStatus ? <AiEmailDraftStatus {...aiEmailDraftStatus} /> : null}<EmailTemplatertype="native_email"templating="liquid"diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsxindex 2f9aef0b85e6..bf3879215511 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx@@ -7,6 +7,7 @@ import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/Primport { integrationsLogic } from 'lib/integrations/integrationsLogic'import { humanFriendlyNumber } from 'lib/utils/numbers'+import { AiEmailDraftStatus } from '../../MessageAudience/AiEmailDraftStatus'import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'import { MissingRecipientEmailBanner } from '../../Workflows/hogflows/steps/components/MissingRecipientEmailBanner'import { BroadcastAudienceCohorts } from '../audience/BroadcastAudienceCohorts'@@ -72,6 +73,7 @@ export function BroadcastReviewStep(): JSX.Element {stepValidationErrors,emailSettings,missingRecipientEmail,+ aiEmailDraftStatus,} = useValues(broadcastWizardLogic)const { categories } = useValues(optOutCategoriesLogic())const category = categories.find((item) => item.id === emailSettings.messageCategoryId)@@ -152,6 +154,7 @@ export function BroadcastReviewStep(): JSX.Element {<div className="text-xs text-secondary">Open and click tracking is off.</div>)}{emailSettings.utmTagsEnabled && <div className="text-xs text-secondary">Links get UTM tags.</div>}+ {aiEmailDraftStatus ? <AiEmailDraftStatus {...aiEmailDraftStatus} /> : null}<BroadcastEmailPreview /></ReviewRow>diff --git a/products/workflows/frontend/MessageAudience/AiEmailDraftStatus.tsx b/products/workflows/frontend/MessageAudience/AiEmailDraftStatus.tsxnew file mode 100644index 000000000000..c9fefef64928--- /dev/null+++ b/products/workflows/frontend/MessageAudience/AiEmailDraftStatus.tsx@@ -0,0 +1,44 @@+import { IconInfo, IconSparkles } from '@posthog/icons'+import { LemonButton, Spinner } from '@posthog/lemon-ui'++export type AiEmailDraftStatusProps =+ | { status: 'loading' }+ | { status: 'applied'; onReview?: () => void }+ | { status: 'failed'; message: string }++export function AiEmailDraftStatus(props: AiEmailDraftStatusProps): JSX.Element {+ if (props.status === 'loading') {+ return (+ <div className="flex items-center gap-2 text-sm text-secondary" data-attr="ai-email-draft-loading">+ <Spinner />+ <span>Writing a first draft with AI. If you edit the email before it's ready, your version stays.</span>+ </div>+ )+ }+ if (props.status === 'failed') {+ return (+ <div className="flex items-center gap-2 text-sm text-secondary" data-attr="ai-email-draft-failed">+ <IconInfo className="shrink-0" />+ <span>{props.message}</span>+ </div>+ )+ }+ return (+ <div+ className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-secondary"+ data-attr="ai-email-draft-applied"+ >+ <IconSparkles className="shrink-0" />+ <span>+ {props.onReview+ ? 'AI wrote the first draft of this email. Check it before anyone gets it.'+ : 'AI wrote this first draft. Check it before you send it.'}+ </span>+ {props.onReview ? (+ <LemonButton size="xsmall" type="secondary" onClick={props.onReview} data-attr="ai-email-draft-review">+ Review email+ </LemonButton>+ ) : null}+ </div>+ )+}diff --git a/products/workflows/frontend/MessageAudience/aiEmailDraft.ts b/products/workflows/frontend/MessageAudience/aiEmailDraft.tsnew file mode 100644index 000000000000..c85006bfa22e--- /dev/null+++ b/products/workflows/frontend/MessageAudience/aiEmailDraft.ts@@ -0,0 +1,112 @@+import posthog from 'posthog-js'++import { workflowEmailDraftsCreate } from '../generated/api'+import { type EmailDraftApi, type EmailDraftRequestApi, EmailDraftSourceEnumApi } from '../generated/api.schemas'+import { MessageDraft, parseMessageDraftPrefill } from './messageDrafts'++// pinned: URL search param, entry points link to /broadcasts/new and /workflows/new with it+export const DRAFT_SOURCE_PARAM = 'draft_source'++// The endpoint bounds the model call itself. This only stops the loading state hanging on a stuck request.+const REQUEST_TIMEOUT_MS = 20000++export type AiEmailDraftSurface = 'broadcast' | 'workflow'++export interface AiEmailDraftResult {+ draft: MessageDraft | null+ generatedBy: EmailDraftApi['generated_by']+ /** The endpoint's `template_reason`, or `request_failed` when the request itself failed. */+ templateReason: string | null+}++export function parseEmailDraftSource(raw: unknown): EmailDraftRequestApi | 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 { source, source_id } = value as Record<string, unknown>+ const sources: readonly unknown[] = Object.values(EmailDraftSourceEnumApi)+ if (!sources.includes(source) || (typeof source_id !== 'string' && typeof source_id !== 'number')) {+ return null+ }+ const id = String(source_id)+ return id ? { source: source as EmailDraftRequestApi['source'], source_id: id } : null+}++export async function requestAiEmailDraft(+ projectId: string,+ request: EmailDraftRequestApi+): Promise<AiEmailDraftResult> {+ let response: EmailDraftApi+ try {+ response = await workflowEmailDraftsCreate(projectId, request, {+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ })+ } catch {+ return { draft: null, generatedBy: 'template', templateReason: 'request_failed' }+ }+ if (response.generated_by !== 'ai') {+ return { draft: null, generatedBy: 'template', templateReason: response.template_reason ?? null }+ }+ const draft = parseMessageDraftPrefill({+ subject: response.subject,+ paragraphs: response.text+ .split(/\n{2,}/)+ .map((paragraph) => paragraph.trim())+ .filter(Boolean),+ })+ if (!draft) {+ return { draft: null, generatedBy: 'template', templateReason: 'invalid_output' }+ }+ return {+ draft: { ...draft, preheader: response.preheader.trim() || undefined },+ generatedBy: 'ai',+ templateReason: null,+ }+}++/** What to tell the person when they waited for an AI draft and got none, or null when there is nothing to say. */+export function aiEmailDraftFailureMessage(result: AiEmailDraftResult | null): string | null {+ if (!result || result.draft) {+ return null+ }+ switch (result.templateReason) {+ case 'rate_limited':+ return "This project used its AI drafts for the hour, so the email wasn't changed."+ case 'timeout':+ case 'model_error':+ case 'invalid_output':+ case 'gateway_unconfigured':+ case 'request_failed':+ return "AI couldn't write a draft this time, so the email wasn't changed."+ default:+ // The project or organization turned AI off, which the person already knows about.+ return null+ }+}++export type AiEmailDraftSkipReason = 'edited' | 'saved'++export function captureAiEmailDraft(+ surface: AiEmailDraftSurface,+ request: EmailDraftRequestApi,+ result: AiEmailDraftResult,+ skipped: AiEmailDraftSkipReason | null+): void {+ // pinned: analytics event name+ posthog.capture('email draft prefilled', {+ surface,+ source: request.source,+ generated_by: result.generatedBy,+ template_reason: result.templateReason,+ applied: !!result.draft && !skipped,+ skipped_reason: result.draft ? skipped : null,+ })+}diff --git a/products/workflows/frontend/MessageAudience/messageAudience.ts b/products/workflows/frontend/MessageAudience/messageAudience.tsindex 751b9853ef97..c937ba6abc35 100644--- a/products/workflows/frontend/MessageAudience/messageAudience.ts+++ b/products/workflows/frontend/MessageAudience/messageAudience.ts@@ -3,6 +3,7 @@ import posthog from 'posthog-js'import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import { urlForNewBroadcastWithAudience } from '../Broadcasts/broadcastAudiencePrefill'+import type { EmailDraftRequestApi } from '../generated/api.schemas'import { type WorkflowTriggerConfig, urlForNewWorkflowWithTrigger } from '../Workflows/workflowTriggerPrefill'import { MessageDraft } from './messageDrafts'@@ -16,6 +17,7 @@ export interface MessageAudience {workflowTrigger?: WorkflowTriggerConfigbroadcastEmail?: MessageDraftworkflowEmail?: MessageDraft+ draftSource?: EmailDraftRequestApi}export function cohortAudienceProperties(cohort: { id: number; name?: string | null }): AnyPropertyFilter[] {@@ -37,12 +39,14 @@ export function messageAudienceUrl(audience: MessageAudience, destination: Messaname: audience.broadcastName,source: audience.source,email: audience.broadcastEmail,+ draftSource: audience.draftSource,})}return urlForNewWorkflowWithTrigger(audience.workflowTrigger ?? { type: 'batch', filters: { properties: audience.properties } },audience.source,- audience.workflowEmail+ audience.workflowEmail,+ audience.draftSource)}diff --git a/products/workflows/frontend/MessageAudience/messageDrafts.ts b/products/workflows/frontend/MessageAudience/messageDrafts.tsindex 17f131490b12..dfbdfa01ef77 100644--- a/products/workflows/frontend/MessageAudience/messageDrafts.ts+++ b/products/workflows/frontend/MessageAudience/messageDrafts.ts@@ -3,6 +3,7 @@ import { NEW_TEMPLATE } from '../TemplateLibrary/constants'export interface MessageDraft {subject: stringparagraphs: string[]+ preheader?: string}export type MessageDraftContext =@@ -14,6 +15,7 @@ export type MessageDraftContext =export interface MessageDraftEmail {subject: string+ preheader: stringhtml: stringtext: stringdesign: Record<string, any>@@ -151,6 +153,8 @@ export function messageDraftEmail(untrusted: MessageDraft): MessageDraftEmail {.join('')return {subject: draft.subject,+ // The preheader is inserted into the sent HTML as is, so it must not carry markup.+ preheader: literalLiquid((untrusted.preheader ?? '').replace(/[<>]/g, '')),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),diff --git a/products/workflows/frontend/Workflows/WorkflowAiEmailDraftStatus.tsx b/products/workflows/frontend/Workflows/WorkflowAiEmailDraftStatus.tsxnew file mode 100644index 000000000000..eb2bbbfb87e3--- /dev/null+++ b/products/workflows/frontend/Workflows/WorkflowAiEmailDraftStatus.tsx@@ -0,0 +1,18 @@+import { useActions, useValues } from 'kea'++import { AiEmailDraftStatus } from '../MessageAudience/AiEmailDraftStatus'+import { hogFlowEditorLogic } from './hogflows/hogFlowEditorLogic'+import { EMAIL_ACTION_ID } from './workflowEmailPrefill'+import { WorkflowLogicProps, workflowLogic } from './workflowLogic'++export function WorkflowAiEmailDraftStatus(props: WorkflowLogicProps): JSX.Element | null {+ const { aiEmailDraftStatus } = useValues(workflowLogic(props))+ const { setSelectedNodeId } = useActions(hogFlowEditorLogic(props))+ if (!aiEmailDraftStatus) {+ return null+ }+ if (aiEmailDraftStatus.status === 'applied') {+ return <AiEmailDraftStatus status="applied" onReview={() => setSelectedNodeId(EMAIL_ACTION_ID)} />+ }+ return <AiEmailDraftStatus {...aiEmailDraftStatus} />+}diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 3a189371949b..353c542b15eb 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -21,6 +21,7 @@ import { ProductKey } from '~/queries/schema/schema-general'import { ActivityScope } from '~/types'import { SOURCE_PREFILL_PARAM } from '../Broadcasts/broadcastAudiencePrefill'+import { DRAFT_SOURCE_PARAM } from '../MessageAudience/aiEmailDraft'import { EMAIL_PREFILL_PARAM } from '../MessageAudience/messageDrafts'import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'import { NewWorkflowAgent } from './NewWorkflowAgent'@@ -38,6 +39,7 @@ import {buildWorkflowAgentContext,isEditingEmailAction,} from './workflowAgentContext'+import { WorkflowAiEmailDraftStatus } from './WorkflowAiEmailDraftStatus'import { WorkflowAssets } from './WorkflowAssets'import { WorkflowEmailPauseBanner } from './WorkflowEmailPauseBanner'import { WorkflowInvocations } from './WorkflowInvocations'@@ -77,12 +79,16 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {const rawEmailPrefill = searchParams[EMAIL_PREFILL_PARAM]const emailPrefill =rawEmailPrefill && typeof rawEmailPrefill !== 'string' ? JSON.stringify(rawEmailPrefill) : rawEmailPrefill+ const rawDraftSource = searchParams[DRAFT_SOURCE_PARAM]+ const draftSource =+ rawDraftSource && typeof rawDraftSource !== 'string' ? JSON.stringify(rawDraftSource) : rawDraftSourceconst workflowProps: WorkflowLogicProps = {id: workflowSceneProps.id,templateId,editTemplateId,triggerPrefill,emailPrefill,+ draftSource,entrySource: typeof entrySource === 'string' ? entrySource : undefined,}@@ -229,6 +235,7 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {<BindLogic logic={workflowLogic} props={workflowProps}><WorkflowSceneHeader {...props} /><WorkflowEmailPauseBanner />+ {!isSavedWorkflow && <WorkflowAiEmailDraftStatus {...workflowProps} />}{suggestionsAvailable && isSavedWorkflow && <WorkflowSuggestionsNotice id={props.id!} />}{/* Only show Logs and Metrics tabs if the workflow has already been created */}{!props.id || props.id === 'new' ? (diff --git a/products/workflows/frontend/Workflows/workflowEmailPrefill.ts b/products/workflows/frontend/Workflows/workflowEmailPrefill.tsindex 381594868b03..1ae94083ed01 100644--- a/products/workflows/frontend/Workflows/workflowEmailPrefill.ts+++ b/products/workflows/frontend/Workflows/workflowEmailPrefill.ts@@ -2,7 +2,7 @@ import { MessageDraft, messageDraftEmail } from '../MessageAudience/messageDraftimport type { HogFlow, HogFlowAction } from './hogflows/types'import type { WorkflowTriggerConfig } from './workflowTriggerPrefill'-const EMAIL_ACTION_ID = 'action_function_email_prefilled'+export 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 }@@ -43,7 +43,6 @@ export function prefilledWorkflow(base: HogFlow, trigger: WorkflowTriggerConfig,replyTo: '',cc: '',bcc: '',- preheader: '',...content,},},@@ -61,6 +60,39 @@ export function prefilledWorkflow(base: HogFlow, trigger: WorkflowTriggerConfig,}}+export function prefilledEmailContent(+ workflow: HogFlow+): { subject: string; preheader: string; html: string; text: string } | null {+ const action = workflow.actions.find((action) => action.id === EMAIL_ACTION_ID)+ const value = (action?.config as Record<string, any> | undefined)?.inputs?.email?.value+ return value+ ? { subject: value.subject, preheader: value.preheader ?? '', html: value.html, text: value.text }+ : null+}++export function withPrefilledEmail(workflow: HogFlow, email: MessageDraft): HogFlow {+ const content = messageDraftEmail(email)+ return {+ ...workflow,+ actions: workflow.actions.map((action) => {+ const config = action.config as Record<string, any>+ if (action.id !== EMAIL_ACTION_ID || !config?.inputs?.email?.value) {+ return action+ }+ return {+ ...action,+ config: {+ ...config,+ inputs: {+ ...config.inputs,+ email: { ...config.inputs.email, value: { ...config.inputs.email.value, ...content } },+ },+ },+ } as HogFlowAction+ }),+ }+}+export function withEmailSender(workflow: HogFlow, integrationId: number): { workflow: HogFlow; filled: boolean } {let filled = falseconst actions = workflow.actions.map((action) => {diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 6ec1d55053d1..4703dea2605c 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -11,9 +11,11 @@ import api, { ApiError } from 'lib/api'import { CyclotronJobInputsValidation } from 'lib/components/CyclotronJob/CyclotronJobInputsValidation'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { publicWebhooksHostOrigin } from 'lib/utils/apiHost'import { LiquidRenderer } from 'lib/utils/liquid'import { objectsEqual } from 'lib/utils/objects'@@ -28,10 +30,19 @@ import { AccessControlLevel, HogFunctionTemplateType, IntegrationType } from '~/import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'import { hogFlowsResumeEmailSending } from 'products/workflows/frontend/generated/api'+import type { EmailDraftRequestApi } from 'products/workflows/frontend/generated/api.schemas'import type { ResourceEditedEvent, UserBasicType, UserType } from '../../../../frontend/src/types'import { loadEntrySource, saveEntrySource } from '../Broadcasts/broadcastUsage'import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'+import {+ AiEmailDraftResult,+ aiEmailDraftFailureMessage,+ captureAiEmailDraft,+ parseEmailDraftSource,+ requestAiEmailDraft,+} from '../MessageAudience/aiEmailDraft'+import type { AiEmailDraftStatusProps } from '../MessageAudience/AiEmailDraftStatus'import { parseMessageDraftPrefill } from '../MessageAudience/messageDrafts'import { getRegisteredTriggerTypes } from './hogflows/registry/triggers/triggerTypeRegistry'import {@@ -58,7 +69,7 @@ import {import { openPublishConfirmDialog } from './PublishImpactDialog'import { ResourceSaveQueue } from './resourceSaveQueue'import { prepareWorkflowDuplicate } from './workflowDuplication'-import { prefilledWorkflow, withEmailSender } from './workflowEmailPrefill'+import { prefilledEmailContent, prefilledWorkflow, withEmailSender, withPrefilledEmail } from './workflowEmailPrefill'import { workflowSceneLogic } from './workflowSceneLogic'import { workflowsLogic } from './workflowsLogic'import { parseWorkflowTriggerPrefill } from './workflowTriggerPrefill'@@ -69,6 +80,7 @@ export interface WorkflowLogicProps {editTemplateId?: stringtriggerPrefill?: stringemailPrefill?: string+ draftSource?: stringentrySource?: string}@@ -238,10 +250,15 @@ function omitWorkflowContent(workflow: HogFlow): Partial<HogFlow> {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicintegrations: IntegrationType[] | null // integrationsLogiccurrentProjectId: number | null // projectLogicuser: UserType | null // userLogicactionValidationErrorsById: Record<string, HogFlowActionValidationResult | null>+ aiEmailDraft: AiEmailDraftResult | null+ aiEmailDraftApplied: boolean+ aiEmailDraftLoading: boolean+ aiEmailDraftStatus: AiEmailDraftStatusProps | nullautoSaveBlockedByValidation: booleanautoSaveEnabled: booleancurrentSchedule: HogFlowSchedule | null@@ -342,6 +359,21 @@ export interface workflowLogicActions {keepMyWorkflowVersion: () => {value: true}+ loadAiEmailDraft: (request: EmailDraftRequestApi) => EmailDraftRequestApi+ loadAiEmailDraftFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAiEmailDraftSuccess: (+ aiEmailDraft: AiEmailDraftResult,+ payload?: EmailDraftRequestApi+ ) => {+ aiEmailDraft: AiEmailDraftResult+ payload?: EmailDraftRequestApi+ }loadHogFunctionTemplatesById: () => anyloadHogFunctionTemplatesByIdFailure: (error: string,@@ -2096,6 +2128,9 @@ export interface workflowLogicActions {}payload?: any}+ markAiEmailDraftApplied: () => {+ value: true+ }markAutoSave: (isAutoSave: boolean) => {isAutoSave: boolean}@@ -2877,6 +2912,11 @@ export interface workflowLogicActions {export interface workflowLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ aiEmailDraftStatus: (+ aiEmailDraftLoading: boolean,+ aiEmailDraftApplied: boolean,+ aiEmailDraft: AiEmailDraftResult | null+ ) => AiEmailDraftStatusProps | nulllogicProps: (arg: WorkflowLogicProps) => WorkflowLogicPropsworkflowUserAccessLevel: (originalWorkflow: HogFlow | null) => AccessControlLevel | nullcurrentSchedule: (schedules: HogFlowSchedule[]) => HogFlowSchedule | null@@ -3112,7 +3152,16 @@ export const workflowLogic = kea<workflowLogicType>([`workflow-${props.id || 'new'}-${props.templateId || 'default'}-${props.editTemplateId || 'default'}-${props.triggerPrefill || 'default'}-${props.emailPrefill || 'default'}`),connect(() => ({- values: [userLogic, ['user'], projectLogic, ['currentProjectId'], integrationsLogic, ['integrations']],+ values: [+ userLogic,+ ['user'],+ projectLogic,+ ['currentProjectId'],+ featureFlagLogic,+ ['featureFlags'],+ integrationsLogic,+ ['integrations'],+ ],actions: [workflowsLogic, ['archiveWorkflow'], resourceEditedLogic, ['resourceEdited']],})),actions({@@ -3165,8 +3214,16 @@ export const workflowLogic = kea<workflowLogicType>([resumeEmailSending: true,confirmResumeEmailSending: true,setResumeEmailSendingPending: (pending: boolean) => ({ pending }),+ markAiEmailDraftApplied: true,}),loaders(({ props, values, actions, cache }) => ({+ aiEmailDraft: [+ null as AiEmailDraftResult | null,+ {+ loadAiEmailDraft: async (request: EmailDraftRequestApi) =>+ await requestAiEmailDraft(String(values.currentProjectId), request),+ },+ ],originalWorkflow: [null as HogFlow | null,{@@ -3411,6 +3468,12 @@ export const workflowLogic = kea<workflowLogicType>([},})),reducers({+ aiEmailDraftApplied: [+ false,+ {+ markAiEmailDraftApplied: () => true,+ },+ ],schedules: [[] as HogFlowSchedule[],{@@ -3569,6 +3632,19 @@ export const workflowLogic = kea<workflowLogicType>([],}),selectors({+ aiEmailDraftStatus: [+ (s) => [s.aiEmailDraftLoading, s.aiEmailDraftApplied, s.aiEmailDraft],+ (loading: boolean, applied: boolean, result: AiEmailDraftResult | null): AiEmailDraftStatusProps | null => {+ if (loading) {+ return { status: 'loading' }+ }+ if (applied) {+ return { status: 'applied' }+ }+ const message = aiEmailDraftFailureMessage(result)+ return message ? { status: 'failed', message } : null+ },+ ],logicProps: [() => [(_, props: WorkflowLogicProps) => props],(props: WorkflowLogicProps): WorkflowLogicProps => props,@@ -4150,6 +4226,17 @@ export const workflowLogic = kea<workflowLogicType>([// This response is now the save baseline. Discarding a draft moves its stamp backwards,// so a copy kept from an earlier save would fence later saves too loosely.cache.lastSavedWorkflow = undefined+ const draftSource = parseEmailDraftSource(props.draftSource)+ if (+ draftSource &&+ !cache.aiEmailDraftRequested &&+ (!props.id || props.id === 'new') &&+ prefilledEmailContent(originalWorkflow) &&+ values.featureFlags[FEATURE_FLAGS.WORKFLOWS_AI_EMAIL_DRAFT]+ ) {+ cache.aiEmailDraftRequested = true+ actions.loadAiEmailDraft(draftSource)+ }// The form edits the staged draft when one exists; the live config keeps running underneath.actions.resetWorkflow(withStagedDraft(originalWorkflow))actions.replayDeferredResourceEdited()@@ -4363,6 +4450,30 @@ export const workflowLogic = kea<workflowLogicType>([actions.setWorkflowActionConfig(actionId, { ...action.config, ...config } as HogFlowAction['config'])},+ loadAiEmailDraftSuccess: ({ aiEmailDraft, payload: request }) => {+ if (!aiEmailDraft || !request) {+ return+ }+ let skipped: 'edited' | 'saved' | null = null+ if (aiEmailDraft.draft) {+ const loaded = values.originalWorkflow+ if (!loaded || (loaded.id && loaded.id !== NEW_WORKFLOW.id)) {+ skipped = 'saved'+ } else if (!objectsEqual(prefilledEmailContent(values.workflow), prefilledEmailContent(loaded))) {+ skipped = 'edited'+ } else if (values.workflowChanged) {+ actions.setWorkflowValues({+ actions: withPrefilledEmail(values.workflow, aiEmailDraft.draft).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.markAiEmailDraftApplied()+ }+ }+ captureAiEmailDraft('workflow', request, aiEmailDraft, skipped)+ },setWorkflowAction: async ({ actionId, action }) => {const newActions = values.workflow.actions.map((a) => (a.id === actionId ? action : a))actions.setWorkflowValues({ actions: newActions })diff --git a/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts b/products/workflows/frontend/Workflows/workflowTriggerPrefill.tsindex a1dfd7f37d77..249ab78cb68b 100644--- a/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts+++ b/products/workflows/frontend/Workflows/workflowTriggerPrefill.ts@@ -3,6 +3,8 @@ import { combineUrl } from 'kea-router'import { urls } from 'scenes/urls'import { SOURCE_PREFILL_PARAM, parseBroadcastAudiencePrefill } from '../Broadcasts/broadcastAudiencePrefill'+import type { EmailDraftRequestApi } from '../generated/api.schemas'+import { DRAFT_SOURCE_PARAM } from '../MessageAudience/aiEmailDraft'import { EMAIL_PREFILL_PARAM, MessageDraft } from '../MessageAudience/messageDrafts'import { HogFlowTriggerSchema } from './hogflows/steps/types'import type { HogFlowAction } from './hogflows/types'@@ -14,12 +16,14 @@ export const TRIGGER_PREFILL_PARAM = 'trigger'export function urlForNewWorkflowWithTrigger(config: WorkflowTriggerConfig,source?: string,- email?: MessageDraft+ email?: MessageDraft,+ draftSource?: EmailDraftRequestApi): string {return combineUrl(urls.workflowNew(), {[TRIGGER_PREFILL_PARAM]: JSON.stringify(config),...(source ? { [SOURCE_PREFILL_PARAM]: source } : {}),...(email ? { [EMAIL_PREFILL_PARAM]: JSON.stringify(email) } : {}),+ ...(draftSource ? { [DRAFT_SOURCE_PARAM]: JSON.stringify(draftSource) } : {}),}).url}