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): offer workflow suggestions on the email domain wizard's last step (#121999)

Meikel Ratz0c83a692124f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fe86a02ce4ed..953c56231b0d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15945,9 +15945,17 @@ snapshots:
scenes-app-workflows-email-domain-setup--domain-step--light:
hash: v1.k794b7964.7e18430997c1e715034e832316d53a49f739cb65b502a993b67d27251f48ab0c.hDMDffZBhSfaVOGABAWtiAid9Oc8BrkvaOWsAQQm8Vc
scenes-app-workflows-email-domain-setup--ready--dark:
- hash: v1.k794b7964.b8c9bf82888036b0531195d03a3cde74707c7fa3ffa34ea846e09390bb6e67a9.n0n9apB1NCh7klnrDcyDkEqRT-rhkr-td3gKPdTiW0A
+ hash: v1.k794b7964.ba7e8591b20b5afecf73a2405e65e47a83148fbecc4dad37f360807f1c1a09c5.mWJ1qgIcRQKqCO4xAcIbLwngcXOW5BEMA4Kbkj49uGs
scenes-app-workflows-email-domain-setup--ready--light:
- hash: v1.k794b7964.af9862fdbe9465830d4c11c2586315bf01ed9b55aba52caa78c485697d33bcfc.U9NNvRqsz7F2nkHkoabxQwQU5aeEbJLNaUBG-VRyvJc
+ hash: v1.k794b7964.5ccaf41fa22e61e2169cb30b4b61d0d1f7a3c27b757abb5c2b549b225c447242.1shG5cFPJI1wCSkWyjLD6gyu9d8K937n5dZTqrdKIOg
+ scenes-app-workflows-email-domain-setup--ready-long-domain--dark:
+ hash: v1.k794b7964.b4071c74a16e680b00b03b792ebe88ba98f8157ecf7c33d15f7b767a462eda59.XwaNY7eh1mRwYfz6t8D6KGAxWzcR6WWZ8Rn6hdPAUpw
+ scenes-app-workflows-email-domain-setup--ready-long-domain--light:
+ hash: v1.k794b7964.3163830f856038d1b360b4c14ca6385bb87d3ca908b33ac68ac234ea8a3a492a.FkG-14iLYhJG5kC95THwOv8HMzPpowPHXCLH2snfGyo
+ scenes-app-workflows-email-domain-setup--ready-with-suggestions--dark:
+ hash: v1.k794b7964.44c718c71df7e045ca519225ee188f306a1a0d0af6488375b738969d740ddbe0.bmyfC-mtvjZVlnGxWD3CF19Ne-gUyrxMxgfVo1dLsG8
+ scenes-app-workflows-email-domain-setup--ready-with-suggestions--light:
+ hash: v1.k794b7964.8851e532812fd04d188fecac850a171cabaadb52f719e8371fc3f94e09e23a74.-yR5UtlkX-ZoOxlW1q2NR_gXfohlHCKtXNihOXeEpjs
scenes-app-workflows-email-domain-setup--settings-cloudflare--dark:
hash: v1.k794b7964.9e3bd23d6d107f8cc6a8d5d482152945ee45e9d8fa63c4b8bf2bfdf7c2719ca7.ZrO_h6pJgHU1ZMi0TXHqxCPePvgZItDlz3NNd1L3XUo
scenes-app-workflows-email-domain-setup--settings-cloudflare--light:
diff --git a/products/workflows/frontend/Channels/EmailDomain/EmailDomain.stories.tsx b/products/workflows/frontend/Channels/EmailDomain/EmailDomain.stories.tsx
index fafe232c3e50..6de6c373e57b 100644
--- a/products/workflows/frontend/Channels/EmailDomain/EmailDomain.stories.tsx
+++ b/products/workflows/frontend/Channels/EmailDomain/EmailDomain.stories.tsx
@@ -1,10 +1,15 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import { Meta, StoryObj } from '@storybook/react'
+import { useActions } from 'kea'
import { useEffect, useMemo } from 'react'
import { FEATURE_FLAGS } from 'lib/constants'
+import { organizationLogic } from 'scenes/organizationLogic'
import { useStorybookMocks } from '~/mocks/browser'
+import type { DataSuggestionApi } from '../../generated/api.schemas'
import { FakeDnsHost, FakeEmailDomainBackend, FakeRecord } from './__mocks__/fakeEmailDomainBackend'
import { emailDomainAgentLogic } from './emailDomainAgentLogic'
import { emailDomainManualSetupLogic } from './emailDomainManualSetupLogic'
@@ -13,6 +18,43 @@ import { emailDomainStatusLogic } from './emailDomainStatusLogic'
const DOMAIN = 'mail.acme.com'
const EMAIL = `hello@${DOMAIN}`
+const LONG_DOMAIN = 'updates.hedgebox-mail.com'
+
+const SUGGESTED_WORKFLOWS: DataSuggestionApi[] = [
+ {
+ id: 'suggestion-welcome',
+ name: 'Welcome new teammates',
+ description: 'Email a new teammate a getting started guide after they join a workspace.',
+ reason: 'teammate_joined fires every day.',
+ trigger_event: 'teammate_joined',
+ weekly_count: 1_840,
+ stage: 'onboarding',
+ premade: false,
+ step_outline: ['email', 'delay', 'email'],
+ },
+ {
+ id: 'suggestion-trial',
+ name: 'Nudge trials before they end',
+ description: 'Remind a workspace on a trial three days before it ends, and again on the last day.',
+ reason: 'trial_started fires every week.',
+ trigger_event: 'trial_started',
+ weekly_count: 320,
+ stage: 'trial',
+ premade: false,
+ step_outline: ['delay', 'email', 'delay', 'email'],
+ },
+ {
+ id: 'suggestion-inactive',
+ name: 'Win back quiet workspaces',
+ description: 'Email the owner of a workspace that has not created a board in 14 days.',
+ reason: 'board_created drops off for some workspaces.',
+ trigger_event: 'board_created',
+ weekly_count: 9_600,
+ stage: 'churn_risk',
+ premade: false,
+ step_outline: ['wait_until', 'branch', 'email'],
+ },
+]
const halfPublished = (record: FakeRecord, index: number): boolean =>
['verification', 'spf'].includes(record.kind) || (record.kind === 'dkim' && index < 3)
@@ -22,14 +64,20 @@ type Stage = (backend: FakeEmailDomainBackend, id: string) => void
interface DomainPageArgs {
host: FakeDnsHost
+ email?: string
seed?: (backend: FakeEmailDomainBackend) => void
stage?: Stage
+ aiApproved?: boolean
}
-const seededBackend = (host: FakeDnsHost, seed?: DomainPageArgs['seed']): FakeEmailDomainBackend => {
+const seededBackend = (
+ host: FakeDnsHost,
+ seed?: DomainPageArgs['seed'],
+ email: string = EMAIL
+): FakeEmailDomainBackend => {
const backend = new FakeEmailDomainBackend()
backend.hostDnsAt('acme.com', host)
- backend.addSender({ email: EMAIL })
+ backend.addSender({ email })
seed?.(backend)
return backend
}
@@ -41,10 +89,14 @@ function Staged({ backend, id, stage }: { backend: FakeEmailDomainBackend; id: s
return null
}
-function DomainPage({ host, seed, stage }: DomainPageArgs): JSX.Element {
- const backend = useMemo(() => seededBackend(host, seed), [host, seed])
+function DomainPage({ host, email, seed, stage, aiApproved = false }: DomainPageArgs): JSX.Element {
+ const backend = useMemo(() => seededBackend(host, seed, email), [host, seed, email])
const id = String(backend.sender(42)?.id)
useStorybookMocks(backend.mocks())
+ const { loadCurrentOrganizationSuccess } = useActions(organizationLogic)
+ useEffect(() => {
+ loadCurrentOrganizationSuccess({ ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: aiApproved })
+ }, [aiApproved, loadCurrentOrganizationSuccess])
return (
<>
<EmailDomainScene id={id} />
@@ -167,6 +219,25 @@ export const VerifyingFailed: Story = {
export const Ready: Story = { args: { host: 'cloudflare', seed: (backend) => backend.verifyDomain(DOMAIN) } }
+export const ReadyLongDomain: Story = {
+ args: {
+ host: 'cloudflare',
+ email: `hello@${LONG_DOMAIN}`,
+ seed: (backend) => backend.verifyDomain(LONG_DOMAIN),
+ },
+}
+
+export const ReadyWithSuggestions: Story = {
+ args: {
+ host: 'cloudflare',
+ seed: (backend) => {
+ backend.verifyDomain(DOMAIN)
+ backend.suggestWorkflows(SUGGESTED_WORKFLOWS)
+ },
+ aiApproved: true,
+ },
+}
+
export const Unavailable: Story = { render: () => <UnavailableDomainPage /> }
export const AgentHandoff: Story = {
diff --git a/products/workflows/frontend/Channels/EmailDomain/EmailDomainScene.test.tsx b/products/workflows/frontend/Channels/EmailDomain/EmailDomainScene.test.tsx
index eb101d6ee576..443ba229d798 100644
--- a/products/workflows/frontend/Channels/EmailDomain/EmailDomainScene.test.tsx
+++ b/products/workflows/frontend/Channels/EmailDomain/EmailDomainScene.test.tsx
@@ -1,21 +1,37 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import '@testing-library/jest-dom'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { Provider, useValues } from 'kea'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { urls } from 'scenes/urls'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import type { DataSuggestionApi } from '../../generated/api.schemas'
import { FakeEmailDomainBackend } from './__mocks__/fakeEmailDomainBackend'
import { EmailDomainScene } from './EmailDomainScene'
const DOMAIN = 'mail.acme.com'
+const SUGGESTED_WORKFLOW: DataSuggestionApi = {
+ id: 'suggestion-1',
+ name: 'Welcome new teammates',
+ description: 'Email a new teammate a getting started guide after they join a workspace.',
+ reason: 'teammate_joined fires every day.',
+ trigger_event: 'teammate_joined',
+ weekly_count: 120,
+ stage: 'onboarding',
+ premade: false,
+ step_outline: ['email', 'delay', 'email'],
+}
const SENDER_ID = 42
const POLL_MS = 10_000
@@ -69,6 +85,14 @@ describe('EmailDomainScene', () => {
await flush()
}
+ const turnOnSuggestions = (on: boolean): void => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.WORKFLOWS_EMAIL_DOMAIN_WIZARD]: true })
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: on,
+ })
+ }
+
const seedSender = (): void => {
backend.addSender({ email: `hello@${DOMAIN}` })
}
@@ -134,6 +158,8 @@ describe('EmailDomainScene', () => {
backend.verifyDomain(DOMAIN)
await flush(POLL_MS)
expectStep(/You can send from/)
+ expect(screen.getByText('Your first sender')).toBeInTheDocument()
+ expect(screen.getByText(`Send your first email from ${DOMAIN}`)).toBeInTheDocument()
typeInto('email-domain-sender-name', 'Acme Team')
click('email-domain-save-sender-name')
@@ -196,6 +222,79 @@ describe('EmailDomainScene', () => {
expectStep(/You can send from/)
})
+ it('replaces the template with workflows suggested from the data, loaded while DNS was checked', async () => {
+ const capture = jest.spyOn(posthog, 'capture')
+ const shownEvents = (): unknown[][] =>
+ capture.mock.calls.filter(([event]) => event === 'workflows data suggestions shown')
+ turnOnSuggestions(true)
+ seedSender()
+ backend.publishRecords(DOMAIN)
+ backend.suggestWorkflows([
+ SUGGESTED_WORKFLOW,
+ { ...SUGGESTED_WORKFLOW, id: 'suggestion-2', name: 'Nudge trials before they end', stage: 'trial' },
+ ])
+ await open(urls.workflowsEmailDomain(SENDER_ID))
+ expectStep('Checking your settings…')
+ expect(screen.queryByText('Welcome new teammates')).not.toBeInTheDocument()
+ expect(shownEvents()).toHaveLength(0)
+
+ backend.verifyDomain(DOMAIN)
+ await flush(POLL_MS)
+ expectStep(/You can send from/)
+ expect(screen.getByText('Welcome new teammates')).toBeInTheDocument()
+ expect(element('workflows-data-suggestion-ai')).toHaveTextContent('Create workflow')
+ expect(document.querySelector('[data-attr="email-domain-create-welcome-workflow"]')).toBeNull()
+ expect(document.querySelector('[data-attr="email-domain-create-blank-workflow"]')).toBeNull()
+ expect(backend.requestsTo('data_suggestions_generate')).toHaveLength(1)
+ expect(shownEvents()).toEqual([
+ [
+ 'workflows data suggestions shown',
+ expect.objectContaining({ surface: 'email_domain_wizard', stages: ['onboarding'] }),
+ ],
+ ])
+
+ expect(screen.queryByText('Nudge trials before they end')).not.toBeInTheDocument()
+ click('email-domain-show-more-suggestions')
+ await flush()
+ expect(screen.getByText('Nudge trials before they end')).toBeInTheDocument()
+ expect(shownEvents().at(-1)?.[1]).toMatchObject({ stages: ['onboarding', 'trial'] })
+
+ click('email-domain-skip-suggestions')
+ expect(screen.queryByText('Welcome new teammates')).not.toBeInTheDocument()
+ expect(element('email-domain-create-welcome-workflow')).toBeInTheDocument()
+ click('email-domain-create-blank-workflow')
+ expect(router.values.location.pathname).toContain(urls.workflowNew())
+ expect(router.values.searchParams).not.toHaveProperty('templateId')
+ })
+
+ it.each<[string, boolean, (backend: FakeEmailDomainBackend) => void]>([
+ ['suggestions are off', false, (fake) => fake.suggestWorkflows([SUGGESTED_WORKFLOW])],
+ ['no suggestion could be made', true, () => {}],
+ ['the suggestions fail to load', true, (fake) => fake.fail('data_suggestions_generate', { status: 500 })],
+ ['the suggestions request is still pending', true, (fake) => void fake.hold('data_suggestions_generate')],
+ [
+ 'the suggestions are still being written',
+ true,
+ (fake) => (fake.dataSuggestions = { status: 'generating', suggestions: [] }),
+ ],
+ ])(
+ 'keeps the welcome template and a blank workflow on the last step when %s',
+ async (_, suggestionsOn, prepare) => {
+ turnOnSuggestions(suggestionsOn)
+ seedSender()
+ backend.verifyDomain(DOMAIN)
+ prepare(backend)
+ await open(urls.workflowsEmailDomain(SENDER_ID))
+ expectStep(/You can send from/)
+ expect(document.querySelector('[data-attr="workflows-data-suggestion-ai"]')).toBeNull()
+ expect(element('email-domain-create-welcome-workflow')).toHaveClass('LemonButton--primary')
+ expect(element('email-domain-create-blank-workflow')).toHaveTextContent('Blank workflow')
+ click('email-domain-create-welcome-workflow')
+ expect(router.values.location.pathname).toContain(urls.workflowNew())
+ expect(router.values.searchParams).toHaveProperty('templateId')
+ }
+ )
+
it('refuses a second submit while creating, shows the error, and lets the person try again', async () => {
const release = backend.hold('integration_create')
backend.failOnce('integration_create', {
@@ -224,6 +323,19 @@ describe('EmailDomainScene', () => {
expectStep('Add 8 settings at Cloudflare')
})
+ it('drops "first" from the ready step when the project already sends from another domain', async () => {
+ seedSender()
+ backend.verifyDomain(DOMAIN)
+ backend.addSender({ email: '[email protected]' })
+ backend.verifyDomain('mail.acme.org')
+ await open(urls.workflowsEmailDomain(SENDER_ID))
+ expectStep(/You can send from/)
+
+ expect(screen.getByText('Your sender')).toBeInTheDocument()
+ expect(screen.getByText(`Send email from ${DOMAIN}`)).toBeInTheDocument()
+ expect(screen.queryByText(/first/i)).toBeNull()
+ })
+
it('keeps the edited sender name on screen when the save fails, and saves it on the next try', async () => {
seedSender()
backend.verifyDomain(DOMAIN)
diff --git a/products/workflows/frontend/Channels/EmailDomain/__mocks__/fakeEmailDomainBackend.ts b/products/workflows/frontend/Channels/EmailDomain/__mocks__/fakeEmailDomainBackend.ts
index f69cedbb4f4e..efe5901e40b3 100644
--- a/products/workflows/frontend/Channels/EmailDomain/__mocks__/fakeEmailDomainBackend.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/__mocks__/fakeEmailDomainBackend.ts
@@ -10,6 +10,7 @@ import type {
PaginatedIntegrationConfigListApi,
} from 'products/integrations/frontend/generated/api.schemas'
+import type { DataSuggestionApi, DataSuggestionsResponseApi } from '../../../generated/api.schemas'
import { HogflowTestResult } from '../../../Workflows/hogflows/steps/types'
import { EmailSenderConfig, EmailSetupMethod } from '../emailDomainSenderLogic'
@@ -29,6 +30,8 @@ export type FakeEndpoint =
| 'domain_connect_apply_url'
| 'event_hosts'
| 'test_email'
+ | 'data_suggestions_generate'
+ | 'data_suggestions_current'
export interface FakeFailure {
status: number
@@ -172,6 +175,8 @@ const createHold = (): Hold => {
export class FakeEmailDomainBackend {
readonly requests: FakeRequest[] = []
eventHosts: [host: string, count: number][] = []
+ /** What the AI workflow suggestions answer. The real backend answers unavailable when it can make none. */
+ dataSuggestions: Omit<DataSuggestionsResponseApi, 'email_sender_ready'> = { status: 'unavailable', suggestions: [] }
private senders = new Map<number, IntegrationConfigApi>()
private domains = new Map<string, FakeDomain>()
@@ -278,6 +283,11 @@ export class FakeEmailDomainBackend {
})
}
+ /** The AI wrote these workflow suggestions from the project's events. */
+ suggestWorkflows(suggestions: DataSuggestionApi[]): void {
+ this.dataSuggestions = { status: 'ready', suggestions }
+ }
+
sesReports(domain: string, state: Exclude<FakeSesState, 'verified' | 'none'>): void {
this.domainState(domain).ses = state
}
@@ -364,6 +374,10 @@ export class FakeEmailDomainBackend {
'domain_connect_check',
({ request }) => this.detectionOf(new URL(request.url).searchParams.get('domain') ?? '')
),
+ '/api/projects/:team_id/workflow_data_suggestions/current/': this.serve(
+ 'data_suggestions_current',
+ () => this.dataSuggestionsResponse()
+ ),
},
post: {
'/api/environments/:team_id/integrations/': this.serve('integration_create', (_, body) =>
@@ -376,6 +390,10 @@ export class FakeEmailDomainBackend {
'domain_connect_apply_url',
(_, body) => this.applyUrl(body as { integration_id: number; redirect_uri: string })
),
+ '/api/projects/:team_id/workflow_data_suggestions/generate/': this.serve(
+ 'data_suggestions_generate',
+ () => this.dataSuggestionsResponse()
+ ),
'/api/environments/:team_id/query/': this.serve('event_hosts', () => ({ results: this.eventHosts })),
'/api/environments/:team_id/hog_flows/:id/invocations/': this.serve(
'test_email',
@@ -413,6 +431,11 @@ export class FakeEmailDomainBackend {
}
}
+ private dataSuggestionsResponse(): DataSuggestionsResponseApi {
+ const anyVerified = [...this.domains.values()].some((state) => state.ses === 'verified')
+ return { ...this.dataSuggestions, email_sender_ready: anyVerified }
+ }
+
private failureFor(endpoint: FakeEndpoint): FakeFailure | undefined {
const oneOff = this.oneOffFailures.get(endpoint)
if (oneOff) {
diff --git a/products/workflows/frontend/Channels/EmailDomain/components/CreateWelcomeWorkflowAction.tsx b/products/workflows/frontend/Channels/EmailDomain/components/CreateWelcomeWorkflowAction.tsx
new file mode 100644
index 000000000000..0d91863d2e36
--- /dev/null
+++ b/products/workflows/frontend/Channels/EmailDomain/components/CreateWelcomeWorkflowAction.tsx
@@ -0,0 +1,22 @@
+import { router } from 'kea-router'
+
+import { IconPlus } from '@posthog/icons'
+
+import { urls } from 'scenes/urls'
+
+import { BigAction } from './BigAction'
+
+// The id of the "Welcome email sequence" template shipped in products/workflows/backend/templates.
+const WELCOME_EMAIL_TEMPLATE_ID = '019b6f44-f9a3-0000-c4a7-b8050d25d690'
+
+export function CreateWelcomeWorkflowAction({ 'data-attr': dataAttr }: { 'data-attr': string }): JSX.Element {
+ return (
+ <BigAction
+ icon={<IconPlus />}
+ onClick={() => router.actions.push(urls.workflowNew(), { templateId: WELCOME_EMAIL_TEMPLATE_ID })}
+ data-attr={dataAttr}
+ >
+ Create the welcome email workflow
+ </BigAction>
+ )
+}
diff --git a/products/workflows/frontend/Channels/EmailDomain/components/FirstWorkflowChoices.tsx b/products/workflows/frontend/Channels/EmailDomain/components/FirstWorkflowChoices.tsx
new file mode 100644
index 000000000000..2abf419d9979
--- /dev/null
+++ b/products/workflows/frontend/Channels/EmailDomain/components/FirstWorkflowChoices.tsx
@@ -0,0 +1,119 @@
+import { useActions, useValues } from 'kea'
+import { ReactNode, useEffect, useState } from 'react'
+
+import { IconSparkles } from '@posthog/icons'
+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { SuggestionCard } from '../../../setupGuide/suggestions/suggestionCards'
+import { WorkflowDataSuggestions } from '../../../setupGuide/suggestions/WorkflowDataSuggestions'
+import {
+ WorkflowDataSuggestionsSurface,
+ workflowDataSuggestionsLogic,
+} from '../../../setupGuide/suggestions/workflowDataSuggestionsLogic'
+import { WorkflowSuggestionCard } from '../../../setupGuide/suggestions/WorkflowSuggestionCard'
+import { WorkflowTemplateBlankCard } from '../../../Workflows/templates/WorkflowTemplateBlankCard'
+import { emailDomainLogic } from '../emailDomainLogic'
+import { CreateWelcomeWorkflowAction } from './CreateWelcomeWorkflowAction'
+
+const SURFACE: WorkflowDataSuggestionsSurface = 'email_domain_wizard'
+
+/** The ways to start a first workflow from the domain wizard: the best suggestion once loaded, else the welcome template and a blank workflow. */
+export function FirstWorkflowChoices(): JSX.Element {
+ const { offersDataSuggestions } = useValues(emailDomainLogic)
+
+ // The suggestions logic loads on mount, so it only mounts when the organization allows AI processing.
+ return offersDataSuggestions ? <ChoicesWithSuggestions /> : <TemplateChoices />
+}
+
+function ChoicesWithSuggestions(): JSX.Element {
+ const { cards, generating } = useValues(workflowDataSuggestionsLogic({ surface: SURFACE }))
+ const [skipped, setSkipped] = useState(false)
+
+ if (skipped) {
+ return (
+ <TemplateChoices>
+ <LemonButton
+ type="tertiary"
+ size="small"
+ className="self-center"
+ onClick={() => setSkipped(false)}
+ data-attr="email-domain-back-to-suggestions"
+ >
+ Back to the suggestions
+ </LemonButton>
+ </TemplateChoices>
+ )
+ }
+ // Until suggestions load, and when none come back, the welcome template stays the first choice.
+ if (generating || cards.length === 0) {
+ return (
+ <TemplateChoices>
+ <WorkflowDataSuggestions surface={SURFACE} />
+ </TemplateChoices>
+ )
+ }
+ return <SuggestedChoices cards={cards} onSkip={() => setSkipped(true)} />
+}
+
+function SuggestedChoices({ cards, onSkip }: { cards: SuggestionCard[]; onSkip: () => void }): JSX.Element {
+ const logic = workflowDataSuggestionsLogic({ surface: SURFACE })
+ const { buildingKey } = useValues(logic)
+ const { reportCardsShown } = useActions(logic)
+ const [expanded, setExpanded] = useState(false)
+ const [best, ...others] = cards
+
+ // Only the cards on screen count as shown, so expanding reports the rest.
+ useEffect(() => {
+ reportCardsShown((expanded ? cards : [best]).map((card) => card.suggestionId))
+ }, [cards, best, expanded, reportCardsShown])
+
+ return (
+ <div className="flex flex-col gap-3" data-attr="workflows-data-suggestions">
+ <span className="inline-flex items-center gap-1 self-center text-xs text-tertiary">
+ <IconSparkles className="size-3" />
+ Suggested from your project's events
+ <Tooltip title="AI writes these suggestions from your project's events. Check each draft before you turn it on.">
+ <LemonTag type="completion" size="small">
+ Beta
+ </LemonTag>
+ </Tooltip>
+ </span>
+ <WorkflowSuggestionCard card={best} surface={SURFACE} primary />
+ {expanded &&
+ others.map((card) => (
+ <WorkflowSuggestionCard key={card.key} card={card} surface={SURFACE} primary={false} />
+ ))}
+ <div className="flex flex-wrap justify-center gap-x-2">
+ {others.length > 0 && !expanded && (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ onClick={() => setExpanded(true)}
+ data-attr="email-domain-show-more-suggestions"
+ >
+ Show {others.length} more {others.length === 1 ? 'suggestion' : 'suggestions'}
+ </LemonButton>
+ )}
+ <LemonButton
+ type="tertiary"
+ size="small"
+ onClick={onSkip}
+ disabledReason={buildingKey ? 'Wait until the suggested workflow is built' : undefined}
+ data-attr="email-domain-skip-suggestions"
+ >
+ Start without a suggestion
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
+
+function TemplateChoices({ children }: { children?: ReactNode }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-5">
+ <CreateWelcomeWorkflowAction data-attr="email-domain-create-welcome-workflow" />
+ <WorkflowTemplateBlankCard data-attr="email-domain-create-blank-workflow" />
+ {children}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Channels/EmailDomain/components/NextWorkflowCard.tsx b/products/workflows/frontend/Channels/EmailDomain/components/NextWorkflowCard.tsx
index 1341b50ba1b8..f6adb0e1e07c 100644
--- a/products/workflows/frontend/Channels/EmailDomain/components/NextWorkflowCard.tsx
+++ b/products/workflows/frontend/Channels/EmailDomain/components/NextWorkflowCard.tsx
@@ -1,41 +1,31 @@
import { useValues } from 'kea'
-import { router } from 'kea-router'
-import { IconPlus } from '@posthog/icons'
import { Link } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
import { emailDomainSenderLogic } from '../emailDomainSenderLogic'
import { HedgehogMailbox } from '../hoggies'
-import { BigAction } from './BigAction'
-
-// The id of the "Welcome email sequence" template shipped in products/workflows/backend/templates.
-const WELCOME_EMAIL_TEMPLATE_ID = '019b6f44-f9a3-0000-c4a7-b8050d25d690'
+import { FirstWorkflowChoices } from './FirstWorkflowChoices'
export function NextWorkflowCard(): JSX.Element {
- const { domain, senderName, fromAddress } = useValues(emailDomainSenderLogic)
+ const { domain, senderName, fromAddress, isFirstVerifiedSender } = useValues(emailDomainSenderLogic)
return (
<section className="rounded-xl border border-accent bg-accent-highlight-secondary p-6 @md:p-8 flex flex-col gap-5">
<div className="flex items-start gap-4">
<HedgehogMailbox className="w-20 shrink-0" />
<div className="flex flex-col gap-1 min-w-0">
<span className="text-xs uppercase tracking-wide text-secondary">Next</span>
- <h2 className="m-0 text-xl font-semibold">Send your first email from {domain}</h2>
+ <h2 className="m-0 text-xl font-semibold">
+ {isFirstVerifiedSender ? 'Send your first email from' : 'Send email from'} {domain}
+ </h2>
<p className="m-0 text-sm text-secondary">
- Start with a welcome email that goes out when someone signs up. We open the Welcome email
- sequence template so you can pick <span className="font-medium">{senderName}</span>{' '}
- <span className="font-mono">&lt;{fromAddress}&gt;</span> as the sender.
+ Start a workflow, and pick <span className="font-medium">{senderName}</span>{' '}
+ <span className="font-mono">&lt;{fromAddress}&gt;</span> as the sender in its emails.
</p>
</div>
</div>
- <BigAction
- icon={<IconPlus />}
- onClick={() => router.actions.push(urls.workflowNew(), { templateId: WELCOME_EMAIL_TEMPLATE_ID })}
- data-attr="email-domain-create-welcome-workflow"
- >
- Create the welcome email workflow
- </BigAction>
+ <FirstWorkflowChoices />
<div className="flex flex-wrap justify-center gap-x-4 gap-y-1 text-sm">
<Link to={urls.workflows('library')}>Pick another template</Link>
<Link to={urls.workflows()}>Go to workflows</Link>
diff --git a/products/workflows/frontend/Channels/EmailDomain/components/FirstSenderCard.tsx b/products/workflows/frontend/Channels/EmailDomain/components/SenderCard.tsx
similarity index 92%
rename from products/workflows/frontend/Channels/EmailDomain/components/FirstSenderCard.tsx
rename to products/workflows/frontend/Channels/EmailDomain/components/SenderCard.tsx
index ac19fbbc7556..4e28a3b05494 100644
--- a/products/workflows/frontend/Channels/EmailDomain/components/FirstSenderCard.tsx
+++ b/products/workflows/frontend/Channels/EmailDomain/components/SenderCard.tsx
@@ -57,12 +57,14 @@ function TestEmailButton(): JSX.Element {
)
}
-export function FirstSenderCard(): JSX.Element {
- const { senderName, fromAddress } = useValues(emailDomainSenderLogic)
+export function SenderCard(): JSX.Element {
+ const { senderName, fromAddress, isFirstVerifiedSender } = useValues(emailDomainSenderLogic)
return (
<section className="rounded-lg border bg-surface-primary p-5 flex flex-col gap-4">
<div className="flex flex-col gap-0.5">
- <h2 className="m-0 text-lg font-semibold">Your first sender</h2>
+ <h2 className="m-0 text-lg font-semibold">
+ {isFirstVerifiedSender ? 'Your first sender' : 'Your sender'}
+ </h2>
<p className="m-0 text-sm text-secondary">The name and address people see in their inbox.</p>
</div>
<div className="grid gap-3 @md:grid-cols-2">
diff --git a/products/workflows/frontend/Channels/EmailDomain/domainInput.ts b/products/workflows/frontend/Channels/EmailDomain/domainInput.ts
index e417b3e9bad0..46c67801347e 100644
--- a/products/workflows/frontend/Channels/EmailDomain/domainInput.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/domainInput.ts
@@ -40,9 +40,33 @@ export const isValidDomain = (domain: string): boolean => DOMAIN_PATTERN.test(do
export const rootDomainOf = (hostname: string): string => hostname.split('.').filter(Boolean).slice(-2).join('.')
-export const nameFromDomain = (domain: string): string => {
- const label = domain.split('.').filter(Boolean).slice(-2)[0] ?? domain
- return label ? label.charAt(0).toUpperCase() + label.slice(1) : ''
+const SECOND_LEVEL_SUFFIX_LABELS = new Set(['co', 'com', 'org', 'net', 'ac', 'gov', 'edu'])
+
+const PLACEHOLDER_ORGANIZATION_NAME = /^(?:default(?: organization)?|.*['’]s organization)$/i
+const PRINTABLE_ASCII = /^[\x20-\x7E]+$/
+const ADDRESS_SYNTAX = /["<>\\]/
+
+const fitsUnencodedInFromHeader = (name: string): boolean => PRINTABLE_ASCII.test(name) && !ADDRESS_SYNTAX.test(name)
+
+const isUsableOrganizationName = (name: string): boolean =>
+ Boolean(name) && !PLACEHOLDER_ORGANIZATION_NAME.test(name) && fitsUnencodedInFromHeader(name)
+
+const isCountryCodeSuffix = (labels: string[]): boolean => {
+ const [secondLevel, topLevel] = labels.slice(-2)
+ return topLevel?.length === 2 && SECOND_LEVEL_SUFFIX_LABELS.has(secondLevel)
+}
+
+const brandLabelOf = (domain: string): string => {
+ const labels = domain.split('.').filter(Boolean)
+ const suffixLength = labels.length > 2 && isCountryCodeSuffix(labels) ? 2 : 1
+ return labels.at(-suffixLength - 1) ?? domain
+}
+
+const capitalize = (label: string): string => label.charAt(0).toUpperCase() + label.slice(1)
+
+export const defaultSenderName = (organizationName: string | null | undefined, domain: string): string => {
+ const name = organizationName?.trim() ?? ''
+ return isUsableOrganizationName(name) ? name : capitalize(brandLabelOf(domain))
}
export const hostnameOfUrl = (url: string): string | null => {
diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.test.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.test.ts
index fd444f690193..44d4d8551a68 100644
--- a/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.test.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.test.ts
@@ -1,4 +1,7 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { organizationLogic } from 'scenes/organizationLogic'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
@@ -31,6 +34,14 @@ describe('emailDomainLogic', () => {
jest.useRealTimers()
})
+ const turnOnSuggestions = (on: boolean): void => {
+ organizationLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: on,
+ })
+ }
+
const mountAndLoad = async (id = '42'): Promise<void> => {
logic = emailDomainLogic({ id })
logic.mount()
@@ -38,10 +49,12 @@ describe('emailDomainLogic', () => {
}
it('shows the domain step for a new sender', async () => {
+ turnOnSuggestions(true)
await mountAndLoad('new')
expect(logic.values.phase).toBe('domain')
expect(backend.requestsTo('integration_get')).toHaveLength(0)
expect(backend.requestsTo('email_status')).toHaveLength(0)
+ expect(backend.requestsTo('data_suggestions_generate')).toHaveLength(0)
})
it.each<[string, EmailDomainSetupRecordKindEnumApi[], string]>([
@@ -74,6 +87,24 @@ describe('emailDomainLogic', () => {
expect(logic.values.verificationSteps.map((step) => step.state)).toEqual(states)
})
+ it.each<[string, boolean, number]>([
+ ['suggestions on', true, 1],
+ ['suggestions off', false, 0],
+ ])('preloads workflow suggestions once a domain is picked, with %s, and loads them once', async (_, on, loads) => {
+ turnOnSuggestions(on)
+ await mountAndLoad()
+ expect(logic.values.phase).toBe('settings')
+ expect(backend.requestsTo('data_suggestions_generate')).toHaveLength(loads)
+
+ backend.publishRecords(DOMAIN)
+ await jest.advanceTimersByTimeAsync(10_000)
+ expect(logic.values.phase).toBe('verifying')
+ backend.verifyDomain(DOMAIN)
+ await jest.advanceTimersByTimeAsync(10_000)
+ expect(logic.values.phase).toBe('ready')
+ expect(backend.requestsTo('data_suggestions_generate')).toHaveLength(loads)
+ })
+
it('reloads only what failed when the person tries again', async () => {
silenceKeaLoadersErrors()
backend.failOnce('integration_get', { status: 500, body: { detail: 'Could not reach the email provider' } })
diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.ts
index 01da412ba9a7..6f07b43969c8 100644
--- a/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.ts
@@ -1,9 +1,10 @@
-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'
+import { organizationLogic } from 'scenes/organizationLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
-import { Breadcrumb } from '~/types'
+import { Breadcrumb, OrganizationType } from '~/types'
import type {
EmailDomainStatusApi,
@@ -11,6 +12,7 @@ import type {
IntegrationConfigApi,
} from 'products/integrations/frontend/generated/api.schemas'
+import { workflowDataSuggestionsLogic } from '../../setupGuide/suggestions/workflowDataSuggestionsLogic'
import { emailDomainAutoConfigureLogic } from './emailDomainAutoConfigureLogic'
import { EmailDomainLogicProps } from './emailDomainLogicProps'
import { emailDomainManualSetupLogic } from './emailDomainManualSetupLogic'
@@ -141,8 +143,11 @@ export interface emailDomainLogicValues {
status: EmailDomainStatusApi | null // emailDomainStatusLogic
statusLoading: boolean // emailDomainStatusLogic
statusUnavailable: boolean // emailDomainStatusLogic
+ currentOrganization: OrganizationType | null // organizationLogic
breadcrumbs: Breadcrumb[]
+ offersDataSuggestions: boolean
phase: EmailDomainPhase
+ preloadsDataSuggestions: boolean
verificationSteps: VerificationStep[]
}
@@ -152,6 +157,16 @@ export interface emailDomainLogicActions {
recheck: () => {
value: true
} // emailDomainStatusLogic
+ loadCurrentOrganizationSuccess: (
+ currentOrganization: OrganizationType | null,
+ payload?: any
+ ) => {
+ currentOrganization: OrganizationType | null
+ payload?: any
+ } // organizationLogic
+ preloadDataSuggestions: () => {
+ value: true
+ }
retry: () => {
value: true
}
@@ -180,6 +195,8 @@ export interface emailDomainLogicMeta {
allRecordsFound: boolean,
pollingStopped: boolean
) => VerificationStep[]
+ offersDataSuggestions: (currentOrganization: OrganizationType | null) => boolean
+ preloadsDataSuggestions: (offersDataSuggestions: boolean, integrationId: number | null) => boolean
breadcrumbs: (domain: string | null, integrationId: number | null) => Breadcrumb[]
}
}
@@ -215,11 +232,21 @@ export const emailDomainLogic = kea<emailDomainLogicType>([
['recordsAdded'],
emailDomainAutoConfigureLogic(props),
['returnedFromAutoConfigure'],
+ organizationLogic,
+ ['currentOrganization'],
+ ],
+ actions: [
+ emailDomainSenderLogic(props),
+ ['loadSender'],
+ emailDomainStatusLogic(props),
+ ['recheck'],
+ organizationLogic,
+ ['loadCurrentOrganizationSuccess'],
],
- actions: [emailDomainSenderLogic(props), ['loadSender'], emailDomainStatusLogic(props), ['recheck']],
})),
actions({
retry: true,
+ preloadDataSuggestions: true,
}),
selectors({
phase: [
@@ -267,6 +294,18 @@ export const emailDomainLogic = kea<emailDomainLogicType>([
): VerificationStep[] =>
verificationStepsOf({ status, phase, domain, records, foundCount, allRecordsFound, pollingStopped }),
],
+ // The suggestions are written by an LLM, so they follow the organization's AI data processing approval.
+ offersDataSuggestions: [
+ (s) => [s.currentOrganization],
+ (currentOrganization: OrganizationType | null): boolean =>
+ currentOrganization?.is_ai_data_processing_approved === true,
+ ],
+ // Suggestions take up to a minute to write, so they start once the domain is picked and are ready by the last step.
+ preloadsDataSuggestions: [
+ (s) => [s.offersDataSuggestions, s.integrationId],
+ (offersDataSuggestions: boolean, integrationId: number | null): boolean =>
+ offersDataSuggestions && integrationId !== null,
+ ],
breadcrumbs: [
(s) => [s.domain, s.integrationId],
(domain: string | null, integrationId: number | null): Breadcrumb[] => [
@@ -280,7 +319,20 @@ export const emailDomainLogic = kea<emailDomainLogicType>([
],
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
+ loadCurrentOrganizationSuccess: () => actions.preloadDataSuggestions(),
+ preloadDataSuggestions: () => {
+ if (!values.preloadsDataSuggestions || cache.dataSuggestionsPreloaded) {
+ return
+ }
+ cache.dataSuggestionsPreloaded = true
+ // The person often leaves the tab to edit DNS, and a remount on return would start the run again.
+ cache.disposables.add(
+ () => workflowDataSuggestionsLogic({ surface: 'email_domain_wizard' }).mount(),
+ 'dataSuggestions',
+ { pauseOnPageHidden: false }
+ )
+ },
retry: () => {
if (values.senderFailed) {
actions.loadSender()
@@ -290,4 +342,7 @@ export const emailDomainLogic = kea<emailDomainLogicType>([
}
},
})),
+ afterMount(({ actions }) => {
+ actions.preloadDataSuggestions()
+ }),
])
diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainSenderLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainSenderLogic.ts
index a45d41eba9cd..86969db1244e 100644
--- a/products/workflows/frontend/Channels/EmailDomain/emailDomainSenderLogic.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainSenderLogic.ts
@@ -7,7 +7,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
-import { UserType } from '~/types'
+import { IntegrationType, UserType } from '~/types'
import { integrationsEmailPartialUpdate, integrationsRetrieve } from 'products/integrations/frontend/generated/api'
import type { IntegrationConfigApi } from 'products/integrations/frontend/generated/api.schemas'
@@ -35,11 +35,13 @@ const configOf = (sender: IntegrationConfigApi | null): EmailSenderConfig | null
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface emailDomainSenderLogicValues {
+ integrations: IntegrationType[] | null // integrationsLogic
currentTeamId: number | null // teamLogic
user: UserType | null // userLogic
domain: string | null
fromAddress: string | null
integrationId: number | null
+ isFirstVerifiedSender: boolean
mailFromSubdomain: string
sender: IntegrationConfigApi | null
senderConfig: EmailSenderConfig | null
@@ -131,6 +133,7 @@ export interface emailDomainSenderLogicMeta {
fromAddress: (senderConfig: EmailSenderConfig | null) => string | null
mailFromSubdomain: (senderConfig: EmailSenderConfig | null) => string
senderNameChanged: (senderName: string, senderConfig: EmailSenderConfig | null) => boolean
+ isFirstVerifiedSender: (integrations: IntegrationType[] | null, integrationId: number | null) => boolean
}
}
@@ -147,7 +150,7 @@ export const emailDomainSenderLogic = kea<emailDomainSenderLogicType>([
props({} as EmailDomainLogicProps),
key(({ id }) => id),
connect(() => ({
- values: [teamLogic, ['currentTeamId'], userLogic, ['user']],
+ values: [teamLogic, ['currentTeamId'], userLogic, ['user'], integrationsLogic, ['integrations']],
actions: [integrationsLogic, ['loadIntegrations']],
})),
actions({
@@ -269,6 +272,15 @@ export const emailDomainSenderLogic = kea<emailDomainSenderLogicType>([
(senderName: string, senderConfig: EmailSenderConfig | null): boolean =>
senderName !== (senderConfig?.name ?? ''),
],
+ isFirstVerifiedSender: [
+ (s) => [s.integrations, s.integrationId],
+ (integrations: IntegrationType[] | null, integrationId: number | null): boolean =>
+ integrations !== null &&
+ !integrations.some(
+ (integration) =>
+ integration.kind === 'email' && integration.id !== integrationId && integration.config?.verified
+ ),
+ ],
}),
listeners(({ actions, values }) => ({
saveSender: async () => {
diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.test.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.test.ts
index 0c2b9e1c1c27..ebccee3653d6 100644
--- a/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.test.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.test.ts
@@ -1,6 +1,9 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import { expectLogic } from 'kea-test-utils'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { useMocks } from '~/mocks/jest'
@@ -76,6 +79,28 @@ describe('emailDomainWizardLogic', () => {
expect(logic.values.sendingDomain).toBe(`${expected}.acme.com`)
})
+ it.each([
+ ['Hedgebox Inc.', 'hedgebox.example.com', 'Hedgebox Inc.'],
+ [' Acme Labs ', 'acme.com', 'Acme Labs'],
+ ['', 'acme.com', 'Acme'],
+ ["Jane's Organization", 'shop.acme.co.uk', 'Acme'],
+ ['Default', 'acme.com.au', 'Acme'],
+ ['', 'acme.io', 'Acme'],
+ ['Müller GmbH', 'mueller.de', 'Mueller'],
+ ['Acme "Labs"', 'acme.com', 'Acme'],
+ ])('names the sender for the organization %p on %s as %s', async (organizationName, domain, senderName) => {
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ name: organizationName,
+ })
+ const logic = mountWizard()
+ logic.actions.selectDomain(domain)
+
+ await expectLogic(logic, () => logic.actions.createSender()).toFinishAllListeners()
+
+ expect(backend.requestsTo('integration_create')[0].body).toMatchObject({ config: { name: senderName } })
+ })
+
const mountWithExistingSender = async (): Promise<ReturnType<typeof emailDomainWizardLogic.build>> => {
backend.addSender({ email: '[email protected]', mail_from_subdomain: 'bounce' })
const logic = mountWizard()
@@ -130,7 +155,7 @@ describe('emailDomainWizardLogic', () => {
' ',
'',
' ',
- { name: 'Acme', email: '[email protected]' },
+ { name: 'MockHog', email: '[email protected]' },
],
])('creates the sender with %s', async (_name, typedName, typedLocalPart, typedReplyTo, config) => {
const logic = mountWizard()
diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.ts
index 5089e0adebe5..a285de2ad513 100644
--- a/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.ts
+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.ts
@@ -4,6 +4,7 @@ import posthog from 'posthog-js'
import api, { ApiError } from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
@@ -11,7 +12,7 @@ import { userLogic } from 'scenes/userLogic'
import { ProductKey } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
-import { IntegrationType, PreflightStatus, TeamPublicType, TeamType, UserType } from '~/types'
+import { IntegrationType, OrganizationType, PreflightStatus, TeamPublicType, TeamType, UserType } from '~/types'
import {
integrationsCreate,
@@ -19,7 +20,13 @@ import {
} from 'products/integrations/frontend/generated/api'
import type { IntegrationConfigApi } from 'products/integrations/frontend/generated/api.schemas'
-import { DomainProblem, asSubdomainLabel, domainProblemOf, nameFromDomain, normalizeDomainInput } from './domainInput'
+import {
+ DomainProblem,
+ asSubdomainLabel,
+ defaultSenderName,
+ domainProblemOf,
+ normalizeDomainInput,
+} from './domainInput'
import { EventHost, InferredDomain, inferDomains } from './inferDomains'
export interface EmailDomainWizardLogicProps {
@@ -54,6 +61,7 @@ const isEmailSenderOn = (integration: IntegrationType, domain: string | null): b
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface emailDomainWizardLogicValues {
integrations: IntegrationType[] | null // integrationsLogic
+ currentOrganization: OrganizationType | null // organizationLogic
preflight: PreflightStatus | null // preflightLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
currentTeamId: number | null // teamLogic
@@ -174,7 +182,7 @@ export interface emailDomainWizardLogicMeta {
customDomain: (customDomainInput: string) => CustomDomain
selectedIsInferred: (selectedDomain: string | null, inferredDomains: InferredDomain[]) => boolean
sendingDomain: (selectedDomain: string | null, sendPrefix: string) => string | null
- suggestedSenderName: (selectedDomain: string | null) => string
+ suggestedSenderName: (currentOrganization: OrganizationType | null, selectedDomain: string | null) => string
senderName: (senderNameInput: string | null, suggestedSenderName: string) => string
fromAddress: (sendingDomain: string | null, localPart: string) => string | null
domainSender: (integrations: IntegrationType[] | null, sendingDomain: string | null) => IntegrationType | null
@@ -189,7 +197,7 @@ export type emailDomainWizardLogicType = MakeLogicType<
emailDomainWizardLogicMeta
>
-/** The domain step: picks or types the domain, shapes the first sender address and creates the sender. */
+/** The domain step: picks or types the domain, shapes the sender address and creates the sender. */
export const emailDomainWizardLogic = kea<emailDomainWizardLogicType>([
path((key) => ['products', 'workflows', 'frontend', 'Channels', 'EmailDomain', 'emailDomainWizardLogic', key]),
props({} as EmailDomainWizardLogicProps),
@@ -200,6 +208,8 @@ export const emailDomainWizardLogic = kea<emailDomainWizardLogicType>([
['currentTeam', 'currentTeamId'],
userLogic,
['user'],
+ organizationLogic,
+ ['currentOrganization'],
integrationsLogic,
['integrations'],
preflightLogic,
@@ -382,8 +392,9 @@ export const emailDomainWizardLogic = kea<emailDomainWizardLogicType>([
selectedDomain ? (sendPrefix ? `${sendPrefix}.${selectedDomain}` : selectedDomain) : null,
],
suggestedSenderName: [
- (s) => [s.selectedDomain],
- (selectedDomain: string | null): string => (selectedDomain ? nameFromDomain(selectedDomain) : ''),
+ (s) => [s.currentOrganization, s.selectedDomain],
+ (currentOrganization: OrganizationType | null, selectedDomain: string | null): string =>
+ selectedDomain ? defaultSenderName(currentOrganization?.name, selectedDomain) : '',
],
senderName: [
(s) => [s.senderNameInput, s.suggestedSenderName],
diff --git a/products/workflows/frontend/Channels/EmailDomain/steps/ReadyStep.tsx b/products/workflows/frontend/Channels/EmailDomain/steps/ReadyStep.tsx
index b5d043209378..41db67753c81 100644
--- a/products/workflows/frontend/Channels/EmailDomain/steps/ReadyStep.tsx
+++ b/products/workflows/frontend/Channels/EmailDomain/steps/ReadyStep.tsx
@@ -4,8 +4,8 @@ import { IconCheck, IconWarning } from '@posthog/icons'
import { LemonCollapse } from '@posthog/lemon-ui'
import { DnsRecordRows } from '../components/DnsRecordRows'
-import { FirstSenderCard } from '../components/FirstSenderCard'
import { NextWorkflowCard } from '../components/NextWorkflowCard'
+import { SenderCard } from '../components/SenderCard'
import { StepHeading } from '../components/StepHeading'
import { emailDomainAutoConfigureLogic } from '../emailDomainAutoConfigureLogic'
import { emailDomainSenderLogic } from '../emailDomainSenderLogic'
@@ -24,7 +24,7 @@ export function ReadyStep(): JSX.Element {
Hoggie={HedgehogRocket}
title={
<>
- You can send from <span className="font-mono break-all">{domain}</span>
+ You can send from <span className="inline-block max-w-full wrap-anywhere">{domain}</span>
</>
}
lead={
@@ -34,7 +34,7 @@ export function ReadyStep(): JSX.Element {
}
/>
</div>
- <FirstSenderCard />
+ <SenderCard />
<LemonCollapse
defaultActiveKey={allRecordsFound ? undefined : 'records'}
panels={[
diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateBlankCard.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateBlankCard.tsx
new file mode 100644
index 000000000000..4bdcf3d24256
--- /dev/null
+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateBlankCard.tsx
@@ -0,0 +1,19 @@
+import { useActions } from 'kea'
+
+import { newWorkflowLogic } from '../newWorkflowLogic'
+import { WorkflowTemplateBlankPreview } from './WorkflowTemplateBlankPreview'
+import { WorkflowTemplateCard } from './WorkflowTemplateCard'
+
+/** The "blank workflow" choice: opens a new workflow with no template. */
+export function WorkflowTemplateBlankCard({ 'data-attr': dataAttr }: { 'data-attr': string }): JSX.Element {
+ const { createEmptyWorkflow } = useActions(newWorkflowLogic)
+ return (
+ <WorkflowTemplateCard
+ name="Blank workflow"
+ description="Start from scratch and add your own trigger and steps."
+ preview={<WorkflowTemplateBlankPreview />}
+ onClick={createEmptyWorkflow}
+ data-attr={dataAttr}
+ />
+ )
+}
diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsx
index 60134a156fe7..4c9a764e2915 100644
--- a/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsx
+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsx
@@ -13,7 +13,7 @@ import { userLogic } from 'scenes/userLogic'
import type { HogFlowTemplate } from '../hogflows/types'
import { newWorkflowLogic } from '../newWorkflowLogic'
import { WorkflowTemplateAiBadge } from './WorkflowTemplateAiBadge'
-import { WorkflowTemplateBlankPreview } from './WorkflowTemplateBlankPreview'
+import { WorkflowTemplateBlankCard } from './WorkflowTemplateBlankCard'
import { WorkflowTemplateCard } from './WorkflowTemplateCard'
import { isAiTemplate } from './workflowTemplateDisplay'
import { WorkflowTemplateMeta } from './WorkflowTemplateMeta'
@@ -29,7 +29,7 @@ export function WorkflowTemplateChooser(props: WorkflowTemplateChooserProps): JS
const { deleteHogflowTemplate } = useActions(workflowTemplatesLogic)
const { user } = useValues(userLogic)
- const { createWorkflowFromTemplate, createEmptyWorkflow } = useActions(newWorkflowLogic)
+ const { createWorkflowFromTemplate } = useActions(newWorkflowLogic)
const canEditTemplate = (template: HogFlowTemplate): boolean => {
if (template.scope === 'global') {
@@ -47,15 +47,7 @@ export function WorkflowTemplateChooser(props: WorkflowTemplateChooserProps): JS
return (
<div className="flex flex-col gap-3">
<div className="WorkflowTemplateChooser">
- {props.showEmptyWorkflow && (
- <WorkflowTemplateCard
- name="Blank workflow"
- description="Start from scratch and add your own trigger and steps."
- preview={<WorkflowTemplateBlankPreview />}
- onClick={createEmptyWorkflow}
- data-attr="create-workflow-blank"
- />
- )}
+ {props.showEmptyWorkflow && <WorkflowTemplateBlankCard data-attr="create-workflow-blank" />}
{filteredTemplates.map((template: HogFlowTemplate) => (
<WorkflowTemplateCard
key={template.id}
diff --git a/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsx b/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsx
index a405cfff6828..f90c4cc93c09 100644
--- a/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsx
+++ b/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsx
@@ -14,7 +14,7 @@ export function WorkflowsPathChoice(): JSX.Element {
return (
<div className="flex flex-col gap-4">
<PathButtons messagingIsPrimary={cards.length === 0} />
- <WorkflowDataSuggestions />
+ <WorkflowDataSuggestions surface="empty_state" />
</div>
)
}
diff --git a/products/workflows/frontend/setupGuide/suggestions/WorkflowDataSuggestions.tsx b/products/workflows/frontend/setupGuide/suggestions/WorkflowDataSuggestions.tsx
index f55e57f6f92b..39c1ee2d184e 100644
--- a/products/workflows/frontend/setupGuide/suggestions/WorkflowDataSuggestions.tsx
+++ b/products/workflows/frontend/setupGuide/suggestions/WorkflowDataSuggestions.tsx
@@ -1,15 +1,22 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
import { IconSparkles } from '@posthog/icons'
import { LemonSkeleton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
-import { workflowDataSuggestionsLogic } from './workflowDataSuggestionsLogic'
+import { WorkflowDataSuggestionsSurface, workflowDataSuggestionsLogic } from './workflowDataSuggestionsLogic'
import { WorkflowSuggestionCard } from './WorkflowSuggestionCard'
const LOADING_CARD_COUNT = 3
-export function WorkflowDataSuggestions(): JSX.Element | null {
- const { cards, generating } = useValues(workflowDataSuggestionsLogic({ surface: 'empty_state' }))
+export function WorkflowDataSuggestions({ surface }: { surface: WorkflowDataSuggestionsSurface }): JSX.Element | null {
+ const logic = workflowDataSuggestionsLogic({ surface })
+ const { cards, generating } = useValues(logic)
+ const { reportCardsShown } = useActions(logic)
+
+ useEffect(() => {
+ reportCardsShown()
+ }, [cards, reportCardsShown])
// Suggestions are optional: a failed or empty run shows nothing, not even the divider.
if (!generating && cards.length === 0) {
@@ -42,7 +49,7 @@ export function WorkflowDataSuggestions(): JSX.Element | null {
</>
) : (
cards.map((card, index) => (
- <WorkflowSuggestionCard key={card.key} card={card} surface="empty_state" primary={index === 0} />
+ <WorkflowSuggestionCard key={card.key} card={card} surface={surface} primary={index === 0} />
))
)}
</div>
diff --git a/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.ts b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.ts
index eebe583b62e5..afa634afbdf6 100644
--- a/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.ts
+++ b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.ts
@@ -42,7 +42,7 @@ const POLL_REQUEST_TIMEOUT_MS = 10_000
const BUILD_FAILED_MESSAGE = "We couldn't build this workflow. Try again, or start from a template."
// pinned: analytics property values for the `workflows data suggestion*` events - renaming breaks dashboards
-export type WorkflowDataSuggestionsSurface = 'empty_state' | 'onboarding_wizard'
+export type WorkflowDataSuggestionsSurface = 'empty_state' | 'onboarding_wizard' | 'email_domain_wizard'
export interface WorkflowDataSuggestionsLogicProps {
surface: WorkflowDataSuggestionsSurface
@@ -94,6 +94,9 @@ export interface workflowDataSuggestionsLogicActions {
aiResult: DataSuggestionsResponseApi | null
payload?: any
}
+ reportCardsShown: (shownSuggestionIds?: string[]) => {
+ shownSuggestionIds: string[] | undefined
+ }
setBuildingKey: (key: string | null) => {
key: string | null
}
@@ -139,6 +142,8 @@ export const workflowDataSuggestionsLogic = kea<workflowDataSuggestionsLogicType
})),
actions({
giveUpPolling: true,
+ // Without ids every loaded suggestion counts as shown.
+ reportCardsShown: (shownSuggestionIds?: string[]) => ({ shownSuggestionIds }),
startSuggestion: (card: SuggestionCard) => ({ card }),
setBuildingKey: (key: string | null) => ({ key }),
}),
@@ -217,17 +222,27 @@ export const workflowDataSuggestionsLogic = kea<workflowDataSuggestionsLogicType
}, 'poll')
return
}
- if (aiResult?.status === 'ready' && aiResult.suggestions.length > 0) {
- // pinned: analytics event name - renaming breaks dashboards
- posthog.capture('workflows data suggestions shown', {
- surface: props.surface,
- source: aiResult.suggestions.some((suggestion) => suggestion.premade) ? 'premade' : 'ai',
- trigger_events: aiResult.suggestions.map((suggestion) => suggestion.trigger_event),
- stages: aiResult.suggestions.map((suggestion) => suggestion.stage),
- })
- }
}
return {
+ // The logic can load before its cards are on screen, so the component that renders them reports the view.
+ reportCardsShown: ({ shownSuggestionIds }) => {
+ const aiResult = values.aiResult
+ const shown =
+ aiResult?.status === 'ready'
+ ? aiResult.suggestions.filter(
+ (suggestion) => !shownSuggestionIds || shownSuggestionIds.includes(suggestion.id)
+ )
+ : []
+ if (shown.length > 0) {
+ // pinned: analytics event name - renaming breaks dashboards
+ posthog.capture('workflows data suggestions shown', {
+ surface: props.surface,
+ source: shown.some((suggestion) => suggestion.premade) ? 'premade' : 'ai',
+ trigger_events: shown.map((suggestion) => suggestion.trigger_event),
+ stages: shown.map((suggestion) => suggestion.stage),
+ })
+ }
+ },
loadAiResultSuccess: ({ aiResult }) => {
cache.pollDeadline = Date.now() + POLL_DEADLINE_MS
handleResult(aiResult)
diff --git a/products/workflows/frontend/setupGuide/wizard/WizardSuggestionsStep.tsx b/products/workflows/frontend/setupGuide/wizard/WizardSuggestionsStep.tsx
index 259a3837aebb..99d87b230d1f 100644
--- a/products/workflows/frontend/setupGuide/wizard/WizardSuggestionsStep.tsx
+++ b/products/workflows/frontend/setupGuide/wizard/WizardSuggestionsStep.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
import { IconArrowRight, IconSparkles } from '@posthog/icons'
import { LemonButton, LemonSkeleton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
@@ -8,9 +9,15 @@ import { WorkflowSuggestionCard } from '../suggestions/WorkflowSuggestionCard'
import { workflowsOnboardingWizardLogic } from './workflowsOnboardingWizardLogic'
export function WizardSuggestionsStep({ fallback }: { fallback: JSX.Element }): JSX.Element {
- const { cards, generating } = useValues(workflowDataSuggestionsLogic({ surface: 'onboarding_wizard' }))
+ const suggestionsLogic = workflowDataSuggestionsLogic({ surface: 'onboarding_wizard' })
+ const { cards, generating } = useValues(suggestionsLogic)
+ const { reportCardsShown } = useActions(suggestionsLogic)
const { setTemplatesShown } = useActions(workflowsOnboardingWizardLogic)
+ useEffect(() => {
+ reportCardsShown()
+ }, [cards, reportCardsShown])
+
if (!generating && cards.length === 0) {
return fallback
}