: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): add the email sending domain wizard logics (#120421)
Meikel Ratzf52663f9f8a4
diff --git a/docs/internal/workflows-email-auto-pause.md b/docs/internal/workflows-email-auto-pause.mdindex 7371a88afbc5..a50f1c371b2d 100644--- a/docs/internal/workflows-email-auto-pause.md+++ b/docs/internal/workflows-email-auto-pause.md@@ -54,4 +54,5 @@ Optionally add the pause metric name to `WORKFLOWS_EMAIL_TIER_AUTO_PAUSE_METRIC_- Gmail runs no feedback loop, so Gmail complaints never appear in these rates; true complaint rates are higher than measured.- The detector reads at most 24 hours back. Chronic slow deterioration is the tier system's job.- A workflow below every volume gate is never auto-paused, whatever its rates; the team's tier caps bound its blast radius, and staff can pause it by hand.+- Workflow completion does not confirm an email send. Test responses expose the email provider outcome separately; a skipped send retains its reason, and provider acceptance does not confirm inbox delivery.- Skipped sends log at error level in the run and record an `email_paused` metric; the run itself continues past the email step, so downstream steps still execute.diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 3954296073f6..aa3a57115717 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -38,7 +38,6 @@ import {DashboardFilter,DatabaseSerializedFieldType,DataWarehouseManagedViewsetKind,- DomainConnectProviderName,EndpointLastExecutionTimesRequest,EndpointRequest,EndpointRunRequest,@@ -217,6 +216,7 @@ import type {import type { SymbolSetOrder } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/symbol_sets/symbolSetLogic'import type { CopyFlagsResponseApi } from 'products/feature_flags/frontend/generated/api.schemas'import type {+ EmailDomainConnectCheckApi,GitHubBranchesResponseApi,GitHubReposResponseApi,} from 'products/integrations/frontend/generated/api.schemas'@@ -6079,14 +6079,7 @@ const api = {): Promise<IntegrationType> {return await new ApiRequest().integrationEmail(integrationId).update({ data })},- async domainConnectCheck(domain: string): Promise<{- supported: boolean- provider_name: DomainConnectProviderName | null- available_providers: {- endpoint: string- name: DomainConnectProviderName- }[]- }> {+ async domainConnectCheck(domain: string): Promise<EmailDomainConnectCheckApi> {return await new ApiRequest().integrationsDomainConnectCheck().withQueryString(`domain=${encodeURIComponent(domain)}`)diff --git a/frontend/src/lib/components/DomainConnect/domainConnectLogic.ts b/frontend/src/lib/components/DomainConnect/domainConnectLogic.tsindex a2a9f2caa801..e1e2e4472048 100644--- a/frontend/src/lib/components/DomainConnect/domainConnectLogic.ts+++ b/frontend/src/lib/components/DomainConnect/domainConnectLogic.ts@@ -7,16 +7,14 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { DomainConnectProviderName } from '~/queries/schema/schema-general'+import type { EmailDomainConnectCheckApi } from 'products/integrations/frontend/generated/api.schemas'+export interface DomainConnectProvider {endpoint: stringname: DomainConnectProviderName}-export interface DomainConnectInfo {- supported: boolean- provider_name: DomainConnectProviderName | null- available_providers: DomainConnectProvider[]-}+export type DomainConnectInfo = EmailDomainConnectCheckApiexport interface DomainConnectLogicProps {/** Unique key to prevent state sharing between instances (not `key` because React strips it) */@@ -54,12 +52,12 @@ export interface domainConnectLogicActions {errorObject?: any}checkDomainSuccess: (- domainConnectInfo: DomainConnectInfo | null,+ domainConnectInfo: EmailDomainConnectCheckApi | null,payload?: {value: true}) => {- domainConnectInfo: DomainConnectInfo | null+ domainConnectInfo: EmailDomainConnectCheckApi | nullpayload?: {value: true}@@ -115,13 +113,13 @@ export const domainConnectLogic = kea<domainConnectLogicType>([providerName: [(s) => [s.domainConnectInfo],(info: DomainConnectInfo | null): DomainConnectProviderName | null => {- return info?.provider_name ?? null+ return (info?.provider_name as DomainConnectProviderName | null) ?? null},],availableProviders: [(s) => [s.domainConnectInfo],(info: DomainConnectInfo | null): DomainConnectProvider[] => {- return info?.available_providers ?? []+ return (info?.available_providers as DomainConnectProvider[] | undefined) ?? []},],hasAnyOption: [diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 6ebdb129fbd3..94d1cdbf529c 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -609,6 +609,8 @@ export const FEATURE_FLAGS = {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_COHORT_CONDITIONS: 'workflows-cohort-conditions', // owner: @meikelmosby #team-workflows+ WORKFLOWS_EMAIL_DOMAIN_AGENT_SETUP: 'workflows-email-domain-agent-setup', // owner: @silthus #team-workflows+ WORKFLOWS_EMAIL_DOMAIN_WIZARD: 'workflows-email-domain-wizard', // owner: @silthus #team-workflowsWORKFLOWS_EMAIL_MEDIA_LIBRARY: 'workflows-email-media-library', // owner: @mayteio #team-workflows, backs the email editor's Uploads tab with the media libraryWORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflowsWORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsdiff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 3b65852b8dc9..54e63121e954 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -1995,6 +1995,7 @@ export const productUrls = {workflows: (tab?: WorkflowsSceneTab): string => `/workflows${tab ? `/${tab}` : ''}`,workflow: (id: string, tab: string): string => `/workflows/${id}/${tab}`,workflowNew: (): string => '/workflows/new/workflow',+ workflowsEmailDomain: (id: string | number): string => `/workflows/channels/email/${id}`,workflowsLibraryMessage: (id: string): string => `/workflows/library/messages/${id}`,workflowsLibraryTemplate: (id?: string): string => `/workflows/library/templates/${id}`,workflowsLibraryTemplateNew: (): string => '/workflows/library/templates/new',diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex e211d49a48f8..21f734e6a674 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -223,6 +223,7 @@ export enum Scene {Broadcasts = 'Broadcasts',Workflows = 'Workflows',Broadcast = 'Broadcast',+ WorkflowsEmailDomain = 'WorkflowsEmailDomain',Wizard = 'Wizard',EarlyAccessFeature = 'EarlyAccessFeature',EndpointsScene = 'EndpointsScene',diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.tsindex 1fcc77b91803..cfb6a3226e6d 100644--- a/nodejs/src/cdp/cdp-api.serial.test.ts+++ b/nodejs/src/cdp/cdp-api.serial.test.ts@@ -2744,6 +2744,7 @@ describe('CDP API', () => {Promise.resolve({invocation,finished: true,+ emailSendResult: { status: 'accepted' },logs: [],metrics: [{@@ -2767,7 +2768,23 @@ describe('CDP API', () => {emailSpy.mockRestore()})- it('sends the email inline via EmailService instead of routing to the email queue', async () => {+ it.each([+ { status: 'accepted' },+ { status: 'skipped', reason: 'The recipient has no reachable mail servers.' },+ ])('returns the inline email outcome %j without routing to the email queue', async (emailSendResult) => {+ emailSpy.mockImplementation((invocation: any) =>+ Promise.resolve({+ invocation,+ finished: true,+ emailSendResult,+ logs: [],+ metrics: [],+ capturedPostHogEvents: [],+ warehouseWebhookPayloads: [],+ messageAssets: [],+ conversionWatchers: [],+ })+ )const res = await supertest(app).post(`/api/projects/${team.id}/hog_flows/${hogFlowId}/invocations`).send({globals,configuration: {},@@ -2776,6 +2793,7 @@ describe('CDP API', () => {expect(res.status).toBe(200)expect(res.body.status).toBe('success')+ expect(res.body.emailSendResult).toEqual(emailSendResult)expect(res.body.errors).toEqual([])// EmailService was called inline — proving the test endpoint forced inline delivery// even though the team would normally be routed to the email queue.diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 9a168e1fbb32..9be10fb21696 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -942,6 +942,7 @@ export class CdpApi {logs: [...result.logs, ...logs],variables: result.invocation.state.variables ?? {},execResult: result.execResult ?? null,+ ...(result.emailSendResult ? { emailSendResult: result.emailSendResult } : {}),})} catch (e) {console.error(e)diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.tsindex 8e2b4c7553e4..d2fda75473c2 100644--- a/nodejs/src/cdp/services/hog-executor.service.ts+++ b/nodejs/src/cdp/services/hog-executor.service.ts@@ -63,7 +63,14 @@ export type HogExecutorAsyncFunctionHandler = (/** The parts of an earlier step's result that carry forward into the next one. */export type HogExecutorPreviousResult = Pick<Partial<CyclotronJobInvocationResult>,- 'finished' | 'capturedPostHogEvents' | 'warehouseWebhookPayloads' | 'logs' | 'metrics' | 'error' | 'execResult'+ | 'finished'+ | 'capturedPostHogEvents'+ | 'warehouseWebhookPayloads'+ | 'logs'+ | 'metrics'+ | 'error'+ | 'execResult'+ | 'emailSendResult'>export type HogExecutorExecuteOptions = {diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex 5c2d6c693dfa..60e53e0ed5f7 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -539,6 +539,10 @@ describe('HogFunctionHandler', () => {expect(handlerResult.nextAction?.id).toBe('exit')expect(mockFetch).not.toHaveBeenCalled()expect(invocationResult.logs[0].message).toContain('no reachable mail servers')+ expect(invocationResult.emailSendResult).toEqual({+ status: 'skipped',+ reason: 'Skipping send: the domain "dead.invalid" has no reachable mail servers, so this message would hard bounce.',+ })expect(invocationResult.metrics).toEqual([{team_id: team.id,diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex 931326f1882f..35f1b3d1fffa 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -187,6 +187,10 @@ export class HogFunctionHandler implements ActionHandler {const functionResult = await this.executeHogFunction(invocation, action, hogExecutorOptions)+ if (functionResult.emailSendResult) {+ result.emailSendResult = functionResult.emailSendResult+ }+// Add all logsfunctionResult.logs.forEach((log: MinimalLogEntry) => {result.logs.push({@@ -452,6 +456,7 @@ export class HogFunctionHandler implements ActionHandler {return {finished: true,skipped: true,+ emailSendResult: action.type === 'function_email' ? { status: 'skipped', reason: message } : undefined,invocation: hogFunctionInvocation,logs: [{ level: 'info', timestamp: DateTime.now(), message }],metrics,@@ -473,6 +478,7 @@ export class HogFunctionHandler implements ActionHandler {return {finished: true,skipped: true,+ emailSendResult: { status: 'skipped', reason: emailSkipReason },invocation: hogFunctionInvocation,logs: [{ level: 'info', timestamp: DateTime.now(), message: emailSkipReason }],metrics: [diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex dcc3675ccecd..7c3cd05338a0 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -1058,6 +1058,7 @@ describe('EmailService', () => {sendEmailSpy.mockResolvedValue({ MessageId: 'test-message-id' })const result = await service.executeSendEmail(invocation)expect(result.error).toBeUndefined()+ expect(result.emailSendResult).toEqual({ status: 'accepted' })expect(sendEmailSpy).toHaveBeenCalledTimes(1)const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }// The SES tag carries the short unsigned code (no dot); the signed code (with distinct_id)@@ -1190,6 +1191,10 @@ describe('EmailService', () => {expect(sendEmailSpy).not.toHaveBeenCalled()expect(result.metrics.map((m) => m.metric_name)).toEqual(['email_suspended'])+ expect(result.emailSendResult).toEqual({+ status: 'skipped',+ reason: 'Skipping send: email sending is suspended for this project. Contact support to get sending re-enabled.',+ })expect(invocation.state.vmState?.stack).toEqual([{ success: false }])})@@ -1216,6 +1221,8 @@ describe('EmailService', () => {expect(sendEmailSpy).not.toHaveBeenCalled()expect(result.metrics.map((m) => m.metric_name)).toEqual(['email_paused'])+ expect(result.emailSendResult?.status).toBe('skipped')+ expect(result.emailSendResult?.reason).toContain('Resume it from the workflow page')expect(invocation.state.vmState?.stack).toEqual([{ success: false }])expect(result.logs.map((l) => l.message).join(' ')).toContain('Spam complaints reached 2%')// Flags the skip so the flow-level billing gate charges nothing for a send that never sent.@@ -1805,6 +1812,7 @@ describe('EmailService', () => {sendEmailSpy.mockResolvedValue({})const result = await service.executeSendEmail(invocation)expect(result.error).toMatchInlineSnapshot(`"Failed to send email via SES: No messageId returned from SES"`)+ expect(result.emailSendResult).toEqual({ status: 'failed', reason: result.error })})it.each([diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex 396672f3e75e..9b377c8145a6 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -413,12 +413,12 @@ export class EmailService {// gating here turns wasted invocations into one clear skip.const suspensionCause = await this.teamWorkflowsConfigService.getEmailSendingSuspension(invocation.teamId)if (suspensionCause) {- addLog(- 'warn',+ const skipReason =suspensionCause === 'staff'? 'Skipping send: email sending is suspended for this project. Contact support to get sending re-enabled.': 'Skipping send: our email provider paused sending for this project. Check the Reputation tab to see what to fix.'- )+ addLog('warn', skipReason)+ result.emailSendResult = { status: 'skipped', reason: skipReason }logger.warn('Skipping email send for a suspended team', {teamId: invocation.teamId,cause: suspensionCause,@@ -450,12 +450,11 @@ export class EmailService {// Error rather than warn: the email did not go out, and warn-level lines get skimmed// past in the run logs. The run itself still continues; a pause is policy, not a// fault, so it must not enter retry or abort handling.- addLog(- 'error',- workflowPause.byStaff- ? `Skipping send: PostHog staff paused email sending for this workflow.${pauseDetail} Contact support to get sending re-enabled.`- : `Skipping send: email sending is paused for this workflow.${pauseDetail} Resume it from the workflow page once the audience is cleaned up.`- )+ const skipReason = workflowPause.byStaff+ ? `Skipping send: PostHog staff paused email sending for this workflow.${pauseDetail} Contact support to get sending re-enabled.`+ : `Skipping send: email sending is paused for this workflow.${pauseDetail} Resume it from the workflow page once the audience is cleaned up.`+ addLog('error', skipReason)+ result.emailSendResult = { status: 'skipped', reason: skipReason }if (!isTest) {result.metrics.push({team_id: invocation.teamId,@@ -519,6 +518,7 @@ export class EmailService {const skipReason = await this.buildSuppressionSkipReason(invocation.teamId, params)if (skipReason) {addLog('info', skipReason)+ result.emailSendResult = { status: 'skipped', reason: skipReason }if (!isTest) {result.metrics.push({team_id: invocation.teamId,@@ -659,6 +659,7 @@ export class EmailService {const viewEmailToken = assetRow ? ` [Email:${invocation.id}:${invocation.state.actionId ?? ''}]` : ''addLog('info', `Email sent to ${params.to.email} from ${from.name} <${from.email}>${viewEmailToken}`)success = true+ result.emailSendResult = { status: 'accepted' }} catch (error) {if (error instanceof SESThrottleError) {// Treat as a transient delivery delay — reschedule rather than fail@@ -672,6 +673,7 @@ export class EmailService {} else {addLog('error', error.message)result.error = error.message+ result.emailSendResult = { status: 'failed', reason: error.message }result.finished = true}}diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 25c0410db533..79aa6c4a11f3 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -362,6 +362,7 @@ export type CyclotronJobInvocationResult<T extends CyclotronJobInvocation = Cycl* flag nor an error, so nothing else on the result tells the two apart.*/deliveredToRecipient?: boolean+ emailSendResult?: { status: 'accepted' | 'skipped' | 'failed'; reason?: string }// The run was canceled rather than succeeding or failing. Only meaningful with// finished=true and no error: the job row and the lifecycle row both flip to// 'canceled'.diff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.tsindex 09ca1cf6363b..9fae8c75e4f5 100644--- a/nodejs/src/cdp/utils/invocation-utils.ts+++ b/nodejs/src/cdp/utils/invocation-utils.ts@@ -285,6 +285,7 @@ export function createInvocationResult<T extends CyclotronJobInvocation>(| 'metrics'| 'error'| 'execResult'+ | 'emailSendResult'> = {}): CyclotronJobInvocationResult<T> {return {diff --git a/products/workflows/frontend/Channels/EmailDomain/__mocks__/fakeEmailDomainBackend.ts b/products/workflows/frontend/Channels/EmailDomain/__mocks__/fakeEmailDomainBackend.tsnew file mode 100644index 000000000000..f69cedbb4f4e--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/__mocks__/fakeEmailDomainBackend.ts@@ -0,0 +1,507 @@+import { MockResolverInfo, Mocks } from '~/mocks/utils'+import { EmailSenderDomainStatus } from '~/types'++import type {+ EmailDomainConnectCheckApi,+ EmailDomainSetupRecordKindEnumApi,+ EmailDomainStatusApi,+ EmailDomainStatusRecordApi,+ IntegrationConfigApi,+ PaginatedIntegrationConfigListApi,+} from 'products/integrations/frontend/generated/api.schemas'++import { HogflowTestResult } from '../../../Workflows/hogflows/steps/types'+import { EmailSenderConfig, EmailSetupMethod } from '../emailDomainSenderLogic'++export type FakeDnsHost = 'cloudflare' | 'route53' | 'unknown'++/** What SES knows about the domain's identity. */+export type FakeSesState = 'none' | 'pending' | 'temporary_failure' | 'failed' | 'verified'++export type FakeEndpoint =+ | 'integration_list'+ | 'integration_get'+ | 'integration_create'+ | 'email_status'+ | 'email_verify'+ | 'email_update'+ | 'domain_connect_check'+ | 'domain_connect_apply_url'+ | 'event_hosts'+ | 'test_email'++export interface FakeFailure {+ status: number+ body?: Record<string, unknown>+}++export interface FakeRequest {+ endpoint: FakeEndpoint+ method: string+ url: string+ body: unknown+}++type RecordKind = EmailDomainSetupRecordKindEnumApi++/** A record the domain needs, before DNS or SES say anything about it. */+export type FakeRecord = Omit<EmailDomainStatusRecordApi, 'status'>++/** Which of a domain's records to touch: a list of kinds, or a predicate over the record and its position. */+export type FakeRecordSelection = RecordKind[] | ((record: FakeRecord, index: number) => boolean)++type RecordTemplate = FakeRecord+type FakeResponse = [status: number, body?: unknown] | object++interface FakeDomain {+ domain: string+ mailFromSubdomain: string+ ses: FakeSesState+ published: Set<string>+ preexisting: Set<RecordKind>+ confirmed: Set<RecordKind>+ awaitingRecord: boolean+}++interface Hold {+ promise: Promise<void>+ release: () => void+}++const CHECKED_AT = '2026-01-01T00:00:00Z'+const FIRST_SENDER_ID = 42+const VERIFICATION_TOKEN = 'pSM7OoC2Jl6dNKGRmkc4KZpesve3QP3cUUT2FGZZ1PU='+const DKIM_SELECTORS = [+ 'v4fyczifqlyachgcw4jqrsdcbbblc236',+ 'fxaevqyhjczvbnhst7funhfphvbo4hv6',+ 'xzipw445tsam4wdwe5y33mgkutbsyqaj',+]+const SPF_VALUE = 'v=spf1 include:amazonses.com ~all'++const DNS_HOSTS: Record<FakeDnsHost, EmailDomainConnectCheckApi> = {+ cloudflare: {+ supported: true,+ provider_name: 'Cloudflare',+ available_providers: [],+ dns_host: {+ name: 'Cloudflare',+ dns_settings_url: 'https://dash.cloudflare.com/?to=/:account/:zone/dns/records',+ },+ existing_email_tools: [],+ },+ route53: {+ supported: false,+ provider_name: null,+ available_providers: [],+ dns_host: { name: 'Route 53', dns_settings_url: 'https://console.aws.amazon.com/route53/v2/hostedzones' },+ existing_email_tools: ['Customer.io'],+ },+ unknown: {+ supported: false,+ provider_name: null,+ available_providers: [],+ dns_host: null,+ existing_email_tools: [],+ },+}++const FAKE_USER: IntegrationConfigApi['created_by'] = {+ id: 1,+ uuid: '00000000-0000-0000-0000-000000000001',+ distinct_id: 'fake-user',+ first_name: 'Jane',+ email: '[email protected]',+ hedgehog_config: null,+}++const recordKey = (record: Pick<EmailDomainStatusRecordApi, 'type' | 'hostname'>): string =>+ `${record.type} ${record.hostname}`++const recordTemplates = (domain: string, mailFromSubdomain: string): RecordTemplate[] => [+ { kind: 'verification', type: 'TXT', hostname: `_amazonses.${domain}`, value: VERIFICATION_TOKEN, priority: null },+ ...DKIM_SELECTORS.map(+ (selector): RecordTemplate => ({+ kind: 'dkim',+ type: 'CNAME',+ hostname: `${selector}._domainkey.${domain}`,+ value: `${selector}.dkim.amazonses.com`,+ priority: null,+ })+ ),+ { kind: 'spf', type: 'TXT', hostname: domain, value: SPF_VALUE, priority: null },+ {+ kind: 'mail_from_mx',+ type: 'MX',+ hostname: `${mailFromSubdomain}.${domain}`,+ value: 'feedback-smtp.us-east-1.amazonses.com',+ priority: 10,+ },+ {+ kind: 'mail_from_spf',+ type: 'TXT',+ hostname: `${mailFromSubdomain}.${domain}`,+ value: SPF_VALUE,+ priority: null,+ },+ { kind: 'dmarc', type: 'TXT', hostname: `_dmarc.${domain}`, value: 'v=DMARC1; p=none;', priority: null },+]++const domainOfEmail = (email: string): string => email.split('@')[1] ?? ''++const readBody = async (request: Request): Promise<unknown> => {+ try {+ return await request.clone().json()+ } catch {+ return null+ }+}++const createHold = (): Hold => {+ let release = (): void => {}+ const promise = new Promise<void>((resolve) => {+ release = resolve+ })+ return { promise, release }+}++/**+ * The email sending domain backend as the wizard sees it over HTTP: senders, their SES identity and the DNS+ * records published for each domain. A test or story seeds it, registers `mocks()` with MSW and advances the+ * domain with `publishRecords` and `verifyDomain`. Every response is typed with the generated API types.+ */+export class FakeEmailDomainBackend {+ readonly requests: FakeRequest[] = []+ eventHosts: [host: string, count: number][] = []++ private senders = new Map<number, IntegrationConfigApi>()+ private domains = new Map<string, FakeDomain>()+ private dnsHosts = new Map<string, FakeDnsHost>()+ private failures = new Map<FakeEndpoint, FakeFailure>()+ private oneOffFailures = new Map<FakeEndpoint, FakeFailure>()+ private holds = new Map<FakeEndpoint, Hold>()+ private nextSenderId = FIRST_SENDER_ID++ addSender(config: Pick<EmailSenderConfig, 'email'> & Partial<EmailSenderConfig>): IntegrationConfigApi {+ const domain = config.domain ?? domainOfEmail(config.email)+ const sender: IntegrationConfigApi = {+ id: this.nextSenderId++,+ kind: 'email',+ config: {+ provider: 'ses',+ name: 'Acme',+ mail_from_subdomain: 'feedback',+ verified: false,+ ...config,+ domain,+ } satisfies EmailSenderConfig,+ created_at: CHECKED_AT,+ created_by: FAKE_USER,+ errors: '',+ display_name: config.email,+ files_write_requestable: false,+ installation_shared: null,+ installation_status: null,+ }+ this.senders.set(sender.id, sender)+ if (!this.domains.has(domain)) {+ this.domains.set(domain, {+ domain,+ mailFromSubdomain: config.mail_from_subdomain ?? 'feedback',+ ses: 'pending',+ published: new Set(),+ preexisting: new Set(),+ confirmed: new Set(),+ awaitingRecord: false,+ })+ }+ return sender+ }++ sender(id: number): IntegrationConfigApi | undefined {+ return this.senders.get(id)+ }++ senderConfig(id: number): EmailSenderConfig | undefined {+ return this.senders.get(id)?.config as EmailSenderConfig | undefined+ }++ /** Which company answers for the domain's nameservers. Matches subdomains of the given domain too. */+ hostDnsAt(domain: string, host: FakeDnsHost): void {+ this.dnsHosts.set(domain, host)+ }++ /** SES has no identity for the domain yet, so the status has no records to hand out. */+ withoutSesIdentity(domain: string): void {+ this.domainState(domain).ses = 'none'+ }++ /** Records that existed at the DNS host before setup started, such as a DMARC policy. */+ preexistingRecords(domain: string, kinds: RecordKind[]): void {+ kinds.forEach((kind) => this.domainState(domain).preexisting.add(kind))+ }++ /** The person (or Domain Connect) published records at the DNS host. All of them when nothing is selected. */+ publishRecords(domain: string, selection?: FakeRecordSelection): void {+ const state = this.domainState(domain)+ const selected =+ typeof selection === 'function'+ ? selection+ : (record: FakeRecord): boolean => !selection || selection.includes(record.kind)+ recordTemplates(domain, state.mailFromSubdomain)+ .filter(selected)+ .forEach((record) => state.published.add(recordKey(record)))+ }++ /** SES confirmed these parts of the identity, while the domain as a whole is not verified yet. */+ sesConfirms(domain: string, kinds: RecordKind[]): void {+ this.publishRecords(domain, kinds)+ kinds.forEach((kind) => this.domainState(domain).confirmed.add(kind))+ }++ /** SES confirmed the records and marked every sender on the domain as able to send. */+ /** SES verifies the domain, but a browser poll cannot record it, so it waits for email/verify. */+ verifyAtProviderOnly(domain: string): void {+ this.publishRecords(domain)+ const state = this.domainState(domain)+ state.ses = 'verified'+ state.awaitingRecord = true+ }++ verifyDomain(domain: string): void {+ this.publishRecords(domain)+ this.domainState(domain).ses = 'verified'+ this.senders.forEach((sender) => {+ const config = sender.config as EmailSenderConfig+ if (config.domain === domain) {+ sender.config = { ...config, verified: true }+ }+ })+ }++ sesReports(domain: string, state: Exclude<FakeSesState, 'verified' | 'none'>): void {+ this.domainState(domain).ses = state+ }++ /** What the DNS host does once the person approves the Domain Connect template. */+ approveDomainConnect(domain: string): void {+ this.publishRecords(domain)+ }++ fail(endpoint: FakeEndpoint, failure: FakeFailure): void {+ this.failures.set(endpoint, failure)+ }++ failOnce(endpoint: FakeEndpoint, failure: FakeFailure): void {+ this.oneOffFailures.set(endpoint, failure)+ }++ recover(endpoint: FakeEndpoint): void {+ this.failures.delete(endpoint)+ this.oneOffFailures.delete(endpoint)+ }++ /** Keeps every response from the endpoint pending until the returned function is called. */+ hold(endpoint: FakeEndpoint): () => void {+ const hold = createHold()+ this.holds.set(endpoint, hold)+ return () => {+ this.holds.delete(endpoint)+ hold.release()+ }+ }++ requestsTo(endpoint: FakeEndpoint): FakeRequest[] {+ return this.requests.filter((request) => request.endpoint === endpoint)+ }++ statusOf(domain: string): EmailDomainStatusApi {+ const state = this.domainState(domain)+ const records =+ state.ses === 'none'+ ? []+ : recordTemplates(domain, state.mailFromSubdomain).map((record) => ({+ ...record,+ status: this.recordStatus(state, record),+ }))+ const allFound = records.length > 0 && records.every((record) => record.status !== 'pending')+ const status = this.overallStatus(state, allFound)+ return {+ status,+ verified: state.ses === 'verified' && !state.awaitingRecord,+ checked_at: CHECKED_AT,+ steps: [+ { key: 'domain_added', state: 'done' },+ { key: 'records_found', state: allFound ? 'done' : 'pending' },+ {+ key: 'verified',+ state: state.ses === 'verified' ? 'done' : state.ses === 'failed' ? 'failed' : 'pending',+ },+ ],+ records,+ }+ }++ detectionOf(domain: string): EmailDomainConnectCheckApi {+ const host = [...this.dnsHosts.entries()].find(+ ([registered]) => domain === registered || domain.endsWith(`.${registered}`)+ )?.[1]+ return DNS_HOSTS[host ?? 'unknown']+ }++ mocks(): Mocks {+ return {+ get: {+ '/api/environments/:team_id/integrations/': this.serve('integration_list', () => this.listSenders()),+ '/api/environments/:team_id/integrations/:id/': this.serve('integration_get', ({ params }) =>+ this.withSender(Number(params.id), (sender) => sender)+ ),+ '/api/environments/:team_id/integrations/:id/email/status/': this.serve('email_status', ({ params }) =>+ this.withSender(Number(params.id), (sender) =>+ this.statusOf((sender.config as EmailSenderConfig).domain)+ )+ ),+ '/api/environments/:team_id/integrations/domain-connect/check/': this.serve(+ 'domain_connect_check',+ ({ request }) => this.detectionOf(new URL(request.url).searchParams.get('domain') ?? '')+ ),+ },+ post: {+ '/api/environments/:team_id/integrations/': this.serve('integration_create', (_, body) =>+ this.createSender(body as { config: EmailSenderConfig })+ ),+ '/api/environments/:team_id/integrations/:id/email/verify/': this.serve('email_verify', ({ params }) =>+ this.withSender(Number(params.id), (sender) => this.restartVerification(sender))+ ),+ '/api/environments/:team_id/integrations/domain-connect/apply-url/': this.serve(+ 'domain_connect_apply_url',+ (_, body) => this.applyUrl(body as { integration_id: number; redirect_uri: string })+ ),+ '/api/environments/:team_id/query/': this.serve('event_hosts', () => ({ results: this.eventHosts })),+ '/api/environments/:team_id/hog_flows/:id/invocations/': this.serve(+ 'test_email',+ (): HogflowTestResult => ({+ status: 'success',+ nextActionId: null,+ logs: [],+ emailSendResult: { status: 'accepted' },+ })+ ),+ },+ patch: {+ '/api/environments/:team_id/integrations/:id/email/': this.serve('email_update', ({ params }, body) =>+ this.withSender(Number(params.id), (sender) =>+ this.updateSender(sender, (body as { config: Partial<EmailSenderConfig> }).config)+ )+ ),+ },+ }+ }++ private serve(+ endpoint: FakeEndpoint,+ respond: (info: MockResolverInfo, body: unknown) => FakeResponse+ ): (info: MockResolverInfo) => Promise<FakeResponse> {+ return async (info) => {+ const body = await readBody(info.request)+ this.requests.push({ endpoint, method: info.request.method, url: info.request.url, body })+ await this.holds.get(endpoint)?.promise+ const failure = this.failureFor(endpoint)+ if (failure) {+ return [failure.status, failure.body ?? { detail: 'The fake backend refused this request' }]+ }+ return respond(info, body)+ }+ }++ private failureFor(endpoint: FakeEndpoint): FakeFailure | undefined {+ const oneOff = this.oneOffFailures.get(endpoint)+ if (oneOff) {+ this.oneOffFailures.delete(endpoint)+ return oneOff+ }+ return this.failures.get(endpoint)+ }++ private domainState(domain: string): FakeDomain {+ const state = this.domains.get(domain)+ if (!state) {+ throw new Error(`The fake backend has no sender for ${domain}. Add one with addSender first.`)+ }+ return state+ }++ private withSender(id: number, respond: (sender: IntegrationConfigApi) => FakeResponse): FakeResponse {+ const sender = this.senders.get(id)+ return sender ? respond(sender) : [404, { detail: 'Not found.' }]+ }++ private recordStatus(state: FakeDomain, record: RecordTemplate): EmailDomainStatusRecordApi['status'] {+ if (state.ses === 'verified' || state.confirmed.has(record.kind)) {+ return 'verified'+ }+ const published = state.published.has(recordKey(record)) || state.preexisting.has(record.kind)+ if (!published) {+ return 'pending'+ }+ return record.kind === 'dmarc' ? 'verified' : 'found'+ }++ private overallStatus(state: FakeDomain, allFound: boolean): EmailDomainStatusApi['status'] {+ switch (state.ses) {+ case 'none':+ return 'not_started'+ case 'verified':+ return 'verified'+ case 'failed':+ return 'failed'+ case 'temporary_failure':+ return 'temporary_failure'+ case 'pending':+ return allFound ? 'records_found' : 'pending'+ }+ }++ private listSenders(): PaginatedIntegrationConfigListApi {+ const results = [...this.senders.values()]+ return { count: results.length, next: null, previous: null, results }+ }++ private createSender(body: { config: EmailSenderConfig }): IntegrationConfigApi {+ return this.addSender(body.config)+ }++ private updateSender(sender: IntegrationConfigApi, config: Partial<EmailSenderConfig>): IntegrationConfigApi {+ const current = sender.config as EmailSenderConfig+ sender.config = {+ ...current,+ name: config.name ?? current.name,+ mail_from_subdomain: config.mail_from_subdomain ?? current.mail_from_subdomain,+ setup_method: config.setup_method ?? current.setup_method,+ } satisfies EmailSenderConfig+ return sender+ }++ private restartVerification(sender: IntegrationConfigApi): EmailSenderDomainStatus {+ const state = this.domainState((sender.config as EmailSenderConfig).domain)+ if (state.ses === 'verified') {+ state.awaitingRecord = false+ return { status: 'success', dnsRecords: [] }+ }+ state.ses = 'pending'+ return { status: 'pending', dnsRecords: [] }+ }++ private applyUrl(body: { integration_id: number; redirect_uri: string }): FakeResponse {+ const sender = this.senders.get(body.integration_id)+ if (!sender) {+ return [404, { detail: 'Not found.' }]+ }+ const method: EmailSetupMethod = 'auto'+ this.updateSender(sender, { setup_method: method })+ const domain = (sender.config as EmailSenderConfig).domain+ const url = new URL('https://dns.example.com/domain-connect/apply')+ url.searchParams.set('domain', domain)+ url.searchParams.set('redirect_uri', body.redirect_uri)+ return { url: url.toString() }+ }+}diff --git a/products/workflows/frontend/Channels/EmailDomain/buildSetupPrompt.ts b/products/workflows/frontend/Channels/EmailDomain/buildSetupPrompt.tsnew file mode 100644index 000000000000..8a798931adf4--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/buildSetupPrompt.ts@@ -0,0 +1,80 @@+import type {+ EmailDomainDnsHostApi,+ EmailDomainStatusRecordApi,+} from 'products/integrations/frontend/generated/api.schemas'++export interface SetupPromptInput {+ domain: string+ mailFromSubdomain: string+ projectId: number+ integrationId: number+ pageUrl: string+ dnsHost: EmailDomainDnsHostApi | null+ supportsDomainConnect: boolean+ records: EmailDomainStatusRecordApi[]+ agentUsesBrowser: boolean+}++const formatRecord = (record: EmailDomainStatusRecordApi): string => {+ const priority = record.priority != null ? ` (priority ${record.priority})` : ''+ return `- ${record.type} ${record.hostname} -> ${record.value}${priority}`+}++const buildMcpPrompt = ({+ domain,+ mailFromSubdomain,+ projectId,+ integrationId,+ pageUrl,+ dnsHost,+ supportsDomainConnect,+ records,+}: SetupPromptInput): string => {+ const hostLine = dnsHost+ ? `- DNS host detected from the nameservers: ${dnsHost.name}${supportsDomainConnect ? ' (supports Domain Connect)' : ''}`+ : '- DNS host: unknown. Ask me where the DNS for this domain is managed before you change anything.'+ return [+ `Get the email sending domain ${domain} verified for PostHog Workflows.`,+ '',+ 'Facts',+ `- PostHog project id: ${projectId}`,+ `- Email sender (integration) id: ${integrationId}. It already exists. Do not create it again with integrations-create; re-creating it marks it unverified.`,+ `- Domain: ${domain}`,+ `- MAIL FROM subdomain: ${mailFromSubdomain}.${domain}. It applies to every sender on this domain. Never pick a new one; changing it needs new DNS records and breaks the other senders until they are published.`,+ hostLine,+ '',+ 'Steps',+ `1. Read the current records and status with integrations-email-status-retrieve (project ${projectId}, integration ${integrationId}). If the PostHog MCP is not available, use the records listed below.`,+ `2. If the host supports Domain Connect, ask me to open ${pageUrl} and click the button that adds the records at the host. I approve the change there. Wait for me.`,+ '3. Otherwise add the records at the DNS host yourself. Paste names and values exactly. If the host appends the domain to the name field, enter only the part before the domain. Always publish both SPF TXT records, merging include:amazonses.com into an existing SPF record at the same name instead of adding a second one. Never add a second _dmarc record; keep an existing one.',+ '4. Poll integrations-email-status-retrieve every 30 seconds until the status is "verified". Stop after 30 minutes and tell me which records are still missing.',+ `5. Then call integrations-email-verify-create once so the sender can send. If it fails, your API key cannot save the verification. Ask me to open ${pageUrl} to finish it.`,+ '',+ 'Records',+ ...records.map(formatRecord),+ ].join('\n')+}++const buildBrowserPrompt = ({ domain, dnsHost, records, pageUrl }: SetupPromptInput): string => {+ const hostLine = dnsHost+ ? `The DNS for this domain is managed at ${dnsHost.name}. Open ${dnsHost.dns_settings_url} in the browser. I am already signed in.`+ : 'Ask me where the DNS for this domain is managed, then open that provider in the browser. I am already signed in.'+ return [+ `Use the browser to add the DNS records below for ${domain}, then verify the domain in PostHog.`,+ '',+ hostLine,+ '',+ 'Rules',+ `- Never add a second _dmarc record. If a TXT record already exists at _dmarc.${domain}, keep it and skip ours.`,+ '- Do not delete or edit any existing record except to merge include:amazonses.com into an SPF record that already exists at the same name.',+ '- If the provider appends the domain to the name field, enter only the part before the domain.',+ '- Show me the list of records you added before you leave the DNS page.',+ `- Then open ${pageUrl} and click "Check again". Wait until the page says the domain is ready to send. Tell me if any record is still missing after 10 minutes.`,+ '',+ 'Records',+ ...records.map(formatRecord),+ ].join('\n')+}++export const buildSetupPrompt = (input: SetupPromptInput): string =>+ input.agentUsesBrowser ? buildBrowserPrompt(input) : buildMcpPrompt(input)diff --git a/products/workflows/frontend/Channels/EmailDomain/buildTestEmailWorkflow.ts b/products/workflows/frontend/Channels/EmailDomain/buildTestEmailWorkflow.tsnew file mode 100644index 000000000000..66656a609c28--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/buildTestEmailWorkflow.ts@@ -0,0 +1,74 @@+import { createExampleEvent } from '../../Workflows/hogflows/testEventFactory'+import type { HogFlow, HogFlowAction, HogFlowEdge } from '../../Workflows/hogflows/types'+import { EXIT_NODE_ID, NEW_WORKFLOW, TRIGGER_NODE_ID } from '../../Workflows/workflowLogic'++const TEST_EMAIL_ACTION_ID = 'send_test_email'++export interface TestEmailWorkflowInput {+ integrationId: number+ teamId: number | null+ domain: string+ recipient: string+}++export interface TestEmailInvocation {+ configuration: HogFlow+ globals: ReturnType<typeof createExampleEvent>+ mock_async_functions: false+ current_action_id: string+}++const testEmailAction = (integrationId: number, domain: string, recipient: string): HogFlowAction => {+ const text = `Your sending domain ${domain} is set up. Emails from PostHog Workflows will arrive like this one.`+ return {+ id: TEST_EMAIL_ACTION_ID,+ type: 'function_email',+ name: 'Send test email',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: {+ template_id: 'template-email',+ inputs: {+ email: {+ value: {+ design: null,+ subject: `Test email from ${domain}`,+ html: `<p>${text}</p>`,+ text,+ from: { integrationId },+ to: { email: recipient, name: '' },+ cc: '',+ bcc: '',+ },+ templating: 'liquid',+ },+ },+ },+ }+}++export const buildTestEmailInvocation = ({+ integrationId,+ teamId,+ domain,+ recipient,+}: TestEmailWorkflowInput): TestEmailInvocation => {+ const edges: HogFlowEdge[] = [+ { from: TRIGGER_NODE_ID, to: TEST_EMAIL_ACTION_ID, type: 'continue' },+ { from: TEST_EMAIL_ACTION_ID, to: EXIT_NODE_ID, type: 'continue' },+ ]+ const configuration: HogFlow = {+ ...NEW_WORKFLOW,+ team_id: teamId ?? NEW_WORKFLOW.team_id,+ name: 'Test email',+ actions: [NEW_WORKFLOW.actions[0], testEmailAction(integrationId, domain, recipient), NEW_WORKFLOW.actions[1]],+ edges,+ }+ return {+ configuration,+ globals: createExampleEvent(teamId ?? undefined, configuration.name, '$pageview', recipient),+ mock_async_functions: false,+ current_action_id: TEST_EMAIL_ACTION_ID,+ }+}diff --git a/products/workflows/frontend/Channels/EmailDomain/dnsHosts.ts b/products/workflows/frontend/Channels/EmailDomain/dnsHosts.tsnew file mode 100644index 000000000000..cc3a770f73d2--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/dnsHosts.ts@@ -0,0 +1,11 @@+const DNS_HOST_GOTCHAS: Record<string, string> = {+ Cloudflare: 'Keep the proxy off (grey cloud) on the CNAME records. Proxied CNAMEs do not work for DKIM.',+ 'Route 53': 'Route 53 asks for the full record name. Paste the name as shown, including your domain.',+ Namecheap:+ 'Namecheap adds your domain to the Host field. Paste only the part before your domain, so "feedback" and not "feedback.acme.com".',+}++const GENERIC_GOTCHA =+ 'If the name field already ends with your domain, paste only the part before it. Otherwise paste the full name.'++export const dnsHostGotcha = (hostName: string | null): string => DNS_HOST_GOTCHAS[hostName ?? ''] ?? GENERIC_GOTCHAdiff --git a/products/workflows/frontend/Channels/EmailDomain/domainInput.ts b/products/workflows/frontend/Channels/EmailDomain/domainInput.tsnew file mode 100644index 000000000000..e417b3e9bad0--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/domainInput.ts@@ -0,0 +1,72 @@+const FREE_MAILBOX_DOMAINS = new Set([+ 'gmail.com',+ 'googlemail.com',+ 'outlook.com',+ 'hotmail.com',+ 'live.com',+ 'yahoo.com',+ 'icloud.com',+ 'me.com',+ 'proton.me',+ 'protonmail.com',+ 'web.de',+])++const DOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}$/++export interface NormalizedDomainInput {+ domain: string+ localPart: string | null+}++export const normalizeDomainInput = (raw: string): NormalizedDomainInput => {+ let value = raw.trim().toLowerCase()+ let localPart: string | null = null+ if (value.includes('@')) {+ const [local, host] = value.split('@')+ localPart = local || null+ value = host ?? ''+ }+ value = value.replace(/^[a-z]+:\/\//, '')+ value = value.split('/')[0].split('?')[0].split(':')[0]+ value = value.replace(/^www\./, '')+ return { domain: value, localPart }+}++export const isFreeMailboxDomain = (domain: string): boolean =>+ FREE_MAILBOX_DOMAINS.has(domain) || domain.startsWith('gmx.')++export const isValidDomain = (domain: string): boolean => DOMAIN_PATTERN.test(domain)++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) : ''+}++export const hostnameOfUrl = (url: string): string | null => {+ try {+ const hostname = new URL(url.includes('://') ? url : `https://${url}`).hostname.toLowerCase()+ return hostname.replace(/^www\./, '')+ } catch {+ return null+ }+}++export type DomainProblem = 'free_mailbox' | 'invalid'++export const domainProblemOf = (domain: string): DomainProblem | null => {+ if (!domain) {+ return null+ }+ if (isFreeMailboxDomain(domain)) {+ return 'free_mailbox'+ }+ if (!isValidDomain(domain)) {+ return 'invalid'+ }+ return null+}++export const asSubdomainLabel = (value: string): string => value.toLowerCase().replace(/[^a-z0-9-]/g, '')diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainAgentLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainAgentLogic.tsnew file mode 100644index 000000000000..8f2f10e8ae7b--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainAgentLogic.ts@@ -0,0 +1,185 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { copyToClipboard } from 'lib/utils/copyToClipboard'++import type {+ EmailDomainDnsHostApi,+ EmailDomainStatusRecordApi,+} from 'products/integrations/frontend/generated/api.schemas'++import { buildSetupPrompt } from './buildSetupPrompt'+import { emailDomainAutoConfigureLogic } from './emailDomainAutoConfigureLogic'+import { EmailDomainLogicProps } from './emailDomainLogicProps'+import { emailDomainSenderLogic } from './emailDomainSenderLogic'+import { emailDomainStatusLogic } from './emailDomainStatusLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainAgentLogicValues {+ dnsHost: EmailDomainDnsHostApi | null // emailDomainAutoConfigureLogic+ pageUrl: string | null // emailDomainAutoConfigureLogic+ supportsDomainConnect: boolean // emailDomainAutoConfigureLogic+ currentTeamId: number | null // emailDomainSenderLogic+ domain: string | null // emailDomainSenderLogic+ integrationId: number | null // emailDomainSenderLogic+ mailFromSubdomain: string // emailDomainSenderLogic+ records: EmailDomainStatusRecordApi[] // emailDomainStatusLogic+ featureFlags: FeatureFlagsSet // featureFlagLogic+ agentModalOpen: boolean+ agentSetupEnabled: boolean+ agentUsesBrowser: boolean+ claudeUrl: string+ setupPrompt: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainAgentLogicActions {+ closeAgentModal: () => {+ value: true+ }+ copyPrompt: () => {+ value: true+ }+ openAgentModal: () => {+ value: true+ }+ promptOpenedInClaude: () => {+ value: true+ }+ setAgentUsesBrowser: (agentUsesBrowser: boolean) => {+ agentUsesBrowser: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainAgentLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ agentSetupEnabled: (featureFlags: FeatureFlagsSet) => boolean+ setupPrompt: (+ domain: string | null,+ mailFromSubdomain: string,+ currentTeamId: number | null,+ integrationId: number | null,+ pageUrl: string | null,+ dnsHost: EmailDomainDnsHostApi | null,+ supportsDomainConnect: boolean,+ records: EmailDomainStatusRecordApi[],+ agentUsesBrowser: boolean+ ) => string+ claudeUrl: (setupPrompt: string) => string+ }+}++export type emailDomainAgentLogicType = MakeLogicType<+ emailDomainAgentLogicValues,+ emailDomainAgentLogicActions,+ EmailDomainLogicProps,+ emailDomainAgentLogicMeta+>++/** Hands the DNS setup to a coding agent: builds the prompt for the sender and offers it to copy or open in Claude. */+export const emailDomainAgentLogic = kea<emailDomainAgentLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'Channels', 'EmailDomain', 'emailDomainAgentLogic', key]),+ props({} as EmailDomainLogicProps),+ key(({ id }) => id),+ connect((props: EmailDomainLogicProps) => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ emailDomainSenderLogic(props),+ ['currentTeamId', 'domain', 'integrationId', 'mailFromSubdomain'],+ emailDomainStatusLogic(props),+ ['records'],+ emailDomainAutoConfigureLogic(props),+ ['dnsHost', 'pageUrl', 'supportsDomainConnect'],+ ],+ })),+ actions({+ openAgentModal: true,+ closeAgentModal: true,+ setAgentUsesBrowser: (agentUsesBrowser: boolean) => ({ agentUsesBrowser }),+ copyPrompt: true,+ promptOpenedInClaude: true,+ }),+ reducers({+ agentModalOpen: [+ false,+ {+ openAgentModal: () => true,+ closeAgentModal: () => false,+ },+ ],+ agentUsesBrowser: [+ false,+ {+ setAgentUsesBrowser: (_, { agentUsesBrowser }) => agentUsesBrowser,+ },+ ],+ }),+ selectors({+ agentSetupEnabled: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): boolean =>+ !!featureFlags[FEATURE_FLAGS.WORKFLOWS_EMAIL_DOMAIN_AGENT_SETUP],+ ],+ setupPrompt: [+ (s) => [+ s.domain,+ s.mailFromSubdomain,+ s.currentTeamId,+ s.integrationId,+ s.pageUrl,+ s.dnsHost,+ s.supportsDomainConnect,+ s.records,+ s.agentUsesBrowser,+ ],+ (+ domain: string | null,+ mailFromSubdomain: string,+ currentTeamId: number | null,+ integrationId: number | null,+ pageUrl: string | null,+ dnsHost: EmailDomainDnsHostApi | null,+ supportsDomainConnect: boolean,+ records: EmailDomainStatusRecordApi[],+ agentUsesBrowser: boolean+ ): string =>+ domain && integrationId && currentTeamId && pageUrl+ ? buildSetupPrompt({+ domain,+ mailFromSubdomain,+ projectId: currentTeamId,+ integrationId,+ pageUrl,+ dnsHost,+ supportsDomainConnect,+ records,+ agentUsesBrowser,+ })+ : '',+ ],+ claudeUrl: [+ (s) => [s.setupPrompt],+ (setupPrompt: string): string => `https://claude.ai/new?q=${encodeURIComponent(setupPrompt)}`,+ ],+ }),+ listeners(({ values }) => ({+ copyPrompt: async () => {+ if (await copyToClipboard(values.setupPrompt, 'prompt', { silent: true })) {+ // pinned: analytics event name+ posthog.capture('email domain setup prompt copied', { browser: values.agentUsesBrowser })+ lemonToast.success('Prompt copied. Paste it into your agent.')+ }+ },+ promptOpenedInClaude: () => {+ // pinned: analytics event name+ posthog.capture('email domain setup prompt opened in claude', { browser: values.agentUsesBrowser })+ },+ })),+])diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainAutoConfigureLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainAutoConfigureLogic.tsnew file mode 100644index 000000000000..d467ddd36afb--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainAutoConfigureLogic.ts@@ -0,0 +1,251 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import api, { ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { integrationsDomainConnectCheckRetrieve } from 'products/integrations/frontend/generated/api'+import type {+ EmailDomainConnectCheckApi,+ EmailDomainDnsHostApi,+} from 'products/integrations/frontend/generated/api.schemas'++import { EmailDomainLogicProps } from './emailDomainLogicProps'+import { emailDomainPageUrl } from './emailDomainPageUrl'+import { emailDomainSenderLogic } from './emailDomainSenderLogic'+import { emailDomainStatusLogic } from './emailDomainStatusLogic'++// pinned: URL search param, the Domain Connect redirect_uri carries it back to this page+export const DOMAIN_CONNECT_RETURN_PARAM = 'domain_connect'++const UNKNOWN_HOST: EmailDomainConnectCheckApi = {+ supported: false,+ provider_name: null,+ available_providers: [],+ dns_host: null,+ existing_email_tools: [],+}++const openBlankTab = (): Window | null => window.open('', '_blank')++const showInTab = (tab: Window | null, url: string): void => {+ if (!tab) {+ window.location.assign(url)+ return+ }+ tab.opener = null+ tab.location.href = url+}++const returnedFromDomainConnect = (): boolean => {+ const { location, searchParams } = router.values+ if (searchParams[DOMAIN_CONNECT_RETURN_PARAM] !== 'email') {+ return false+ }+ const { [DOMAIN_CONNECT_RETURN_PARAM]: _, ...otherParams } = searchParams+ router.actions.replace(location.pathname, otherParams, location.hash)+ return true+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainAutoConfigureLogicValues {+ domain: string | null // emailDomainSenderLogic+ integrationId: number | null // emailDomainSenderLogic+ currentTeamId: number | null // teamLogic+ autoConfigureLoading: boolean+ detection: EmailDomainConnectCheckApi | null+ detectionLoading: boolean+ dnsHost: EmailDomainDnsHostApi | null+ hostName: string | null+ pageUrl: string | null+ returnedFromAutoConfigure: boolean+ supportsDomainConnect: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainAutoConfigureLogicActions {+ loadSenderSuccess: (+ sender: null | import('products/integrations/frontend/generated/api.schemas').IntegrationConfigApi,+ payload?: any+ ) => {+ payload?: any+ sender: null | import('products/integrations/frontend/generated/api.schemas').IntegrationConfigApi+ } // emailDomainSenderLogic+ recheck: () => {+ value: true+ } // emailDomainStatusLogic+ loadDetection: () => any+ loadDetectionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadDetectionSuccess: (+ detection: EmailDomainConnectCheckApi | null,+ payload?: any+ ) => {+ detection: EmailDomainConnectCheckApi | null+ payload?: any+ }+ openAutoConfigure: () => {+ value: true+ }+ returnFromAutoConfigure: () => {+ value: true+ }+ setAutoConfigureLoading: (loading: boolean) => {+ loading: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainAutoConfigureLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ dnsHost: (detection: EmailDomainConnectCheckApi | null) => EmailDomainDnsHostApi | null+ supportsDomainConnect: (detection: EmailDomainConnectCheckApi | null) => boolean+ hostName: (detection: EmailDomainConnectCheckApi | null, dnsHost: EmailDomainDnsHostApi | null) => string | null+ pageUrl: (currentTeamId: number | null, integrationId: number | null) => string | null+ }+}++export type emailDomainAutoConfigureLogicType = MakeLogicType<+ emailDomainAutoConfigureLogicValues,+ emailDomainAutoConfigureLogicActions,+ EmailDomainLogicProps,+ emailDomainAutoConfigureLogicMeta+>++/** Finds who hosts the domain's DNS and, when that host supports Domain Connect, sends the person there to add the records in one click. */+export const emailDomainAutoConfigureLogic = kea<emailDomainAutoConfigureLogicType>([+ path((key) => [+ 'products',+ 'workflows',+ 'frontend',+ 'Channels',+ 'EmailDomain',+ 'emailDomainAutoConfigureLogic',+ key,+ ]),+ props({} as EmailDomainLogicProps),+ key(({ id }) => id),+ connect((props: EmailDomainLogicProps) => ({+ values: [teamLogic, ['currentTeamId'], emailDomainSenderLogic(props), ['domain', 'integrationId']],+ actions: [emailDomainSenderLogic(props), ['loadSenderSuccess'], emailDomainStatusLogic(props), ['recheck']],+ })),+ actions({+ openAutoConfigure: true,+ setAutoConfigureLoading: (loading: boolean) => ({ loading }),+ returnFromAutoConfigure: true,+ }),+ loaders(({ values }) => ({+ detection: [+ null as EmailDomainConnectCheckApi | null,+ {+ loadDetection: async (): Promise<EmailDomainConnectCheckApi | null> => {+ if (!values.domain || !values.currentTeamId) {+ return null+ }+ try {+ return await integrationsDomainConnectCheckRetrieve(String(values.currentTeamId), {+ domain: values.domain,+ include_email_setup: true,+ })+ } catch {+ return UNKNOWN_HOST+ }+ },+ },+ ],+ })),+ reducers({+ autoConfigureLoading: [+ false,+ {+ setAutoConfigureLoading: (_, { loading }) => loading,+ },+ ],+ returnedFromAutoConfigure: [+ false,+ {+ returnFromAutoConfigure: () => true,+ },+ ],+ }),+ selectors({+ dnsHost: [+ (s) => [s.detection],+ (detection: EmailDomainConnectCheckApi | null): EmailDomainDnsHostApi | null => detection?.dns_host ?? null,+ ],+ supportsDomainConnect: [+ (s) => [s.detection],+ (detection: EmailDomainConnectCheckApi | null): boolean =>+ detection?.supported === true && !!detection.provider_name,+ ],+ hostName: [+ (s) => [s.detection, s.dnsHost],+ (detection: EmailDomainConnectCheckApi | null, dnsHost: EmailDomainDnsHostApi | null): string | null =>+ dnsHost?.name ?? detection?.provider_name ?? null,+ ],+ pageUrl: [+ (s) => [s.currentTeamId, s.integrationId],+ (currentTeamId: number | null, integrationId: number | null): string | null =>+ currentTeamId && integrationId ? emailDomainPageUrl(currentTeamId, integrationId) : null,+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ loadSenderSuccess: ({ sender }) => {+ if (sender && !values.detection) {+ actions.loadDetection()+ }+ },+ loadDetectionSuccess: () => {+ if (values.returnedFromAutoConfigure && !cache.returnReported) {+ cache.returnReported = true+ // pinned: analytics event name+ posthog.capture('email domain auto configure returned', { provider: values.hostName })+ }+ },+ returnFromAutoConfigure: () => {+ actions.recheck()+ },+ openAutoConfigure: async () => {+ const { integrationId, pageUrl } = values+ if (!integrationId || !pageUrl) {+ return+ }+ // pinned: analytics event name+ posthog.capture('email domain auto configure clicked', { provider: values.hostName })+ // Opened before the request so the click's user activation still covers it; a later open is a popup.+ const tab = openBlankTab()+ actions.setAutoConfigureLoading(true)+ try {+ // nosemgrep: prefer-codegen-api-namespaced-integrations -- the generated integrationsDomainConnectApplyUrlCreate returns void, and this reads the apply URL+ const { url } = await api.integrations.domainConnectApplyUrl({+ context: 'email',+ integration_id: integrationId,+ redirect_uri: `${pageUrl}?${DOMAIN_CONNECT_RETURN_PARAM}=email`,+ })+ showInTab(tab, url)+ } catch (error) {+ tab?.close()+ const detail = error instanceof ApiError ? error.detail : null+ lemonToast.error(+ detail || `Could not open ${values.hostName ?? 'your DNS host'}. Add the settings yourself instead.`+ )+ } finally {+ actions.setAutoConfigureLoading(false)+ }+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.integrationId !== null && returnedFromDomainConnect()) {+ actions.returnFromAutoConfigure()+ }+ }),+])diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.test.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.test.tsnew file mode 100644index 000000000000..fd444f690193--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.test.ts@@ -0,0 +1,127 @@+import { lemonToast } from 'lib/lemon-ui/LemonToast'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { EmailDomainSetupRecordKindEnumApi } from 'products/integrations/frontend/generated/api.schemas'++import type { HogflowTestResult } from '../../Workflows/hogflows/steps/types'+import { FakeEmailDomainBackend } from './__mocks__/fakeEmailDomainBackend'+import { VerificationStep, emailDomainLogic } from './emailDomainLogic'+import { emailDomainSenderLogic } from './emailDomainSenderLogic'++const DOMAIN = 'mail.acme.com'++describe('emailDomainLogic', () => {+ let backend: FakeEmailDomainBackend+ let logic: ReturnType<typeof emailDomainLogic.build>++ beforeEach(() => {+ jest.useFakeTimers()+ backend = new FakeEmailDomainBackend()+ backend.hostDnsAt('acme.com', 'cloudflare')+ backend.addSender({ email: `hello@${DOMAIN}` })+ useMocks(backend.mocks())+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ jest.useRealTimers()+ })++ const mountAndLoad = async (id = '42'): Promise<void> => {+ logic = emailDomainLogic({ id })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)+ }++ it('shows the domain step for a new sender', async () => {+ await mountAndLoad('new')+ expect(logic.values.phase).toBe('domain')+ expect(backend.requestsTo('integration_get')).toHaveLength(0)+ expect(backend.requestsTo('email_status')).toHaveLength(0)+ })++ it.each<[string, EmailDomainSetupRecordKindEnumApi[], string]>([+ ['an existing DMARC record', ['dmarc'], 'settings'],+ ['an existing apex SPF record', ['spf', 'dmarc'], 'settings'],+ ['a DKIM record', ['dkim', 'dmarc'], 'verifying'],+ ['the verification record', ['verification'], 'verifying'],+ ])('shows the %s phase when the first check finds %s', async (_, kinds, phase) => {+ backend.preexistingRecords(DOMAIN, kinds)+ await mountAndLoad()+ expect(logic.values.phase).toBe(phase)+ })++ it('shows the ready phase once the domain is verified', async () => {+ backend.verifyDomain(DOMAIN)+ await mountAndLoad()+ expect(logic.values.phase).toBe('ready')+ expect(logic.values.verificationSteps.map((step) => step.state)).toEqual(['done', 'done', 'done'])+ })++ it.each<[string, boolean, VerificationStep['state'][]]>([+ ['every record is published', true, ['done', 'done', 'active']],+ ['records are missing', false, ['done', 'stuck', 'todo']],+ ])('marks the records step after automatic checks stop when %s', async (_, publishAll, states) => {+ if (publishAll) {+ backend.publishRecords(DOMAIN)+ }+ await mountAndLoad()+ await jest.advanceTimersByTimeAsync(31 * 60_000)+ expect(logic.values.verificationSteps.map((step) => step.state)).toEqual(states)+ })++ 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' } })+ await mountAndLoad()+ resumeKeaLoadersErrors()+ expect(logic.values.phase).toBe('unavailable')+ const statusChecks = backend.requestsTo('email_status').length++ logic.actions.retry()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.phase).toBe('settings')+ expect(backend.requestsTo('integration_get')).toHaveLength(2)+ expect(backend.requestsTo('email_status')).toHaveLength(statusChecks)+ })+ it.each<[HogflowTestResult['emailSendResult'], boolean]>([+ [{ status: 'accepted' }, true],+ [{ status: 'skipped', reason: 'The recipient has no reachable mail servers.' }, false],+ [{ status: 'failed', reason: 'The provider refused the message.' }, false],+ [undefined, false],+ ])('requires provider acceptance before confirming a test send: %j', async (emailSendResult, sent) => {+ const warning = jest.spyOn(lemonToast, 'warning')+ const error = jest.spyOn(lemonToast, 'error')+ const mocks = backend.mocks()+ useMocks({+ ...mocks,+ post: {+ ...mocks.post,+ '/api/environments/:team_id/hog_flows/:id/invocations/': () => ({+ status: 'success',+ nextActionId: 'exit_node',+ emailSendResult,+ }),+ },+ })+ await mountAndLoad()+ const sender = emailDomainSenderLogic({ id: '42' })+ sender.actions.sendTestEmail()+ await jest.advanceTimersByTimeAsync(0)+ expect(sender.values.testEmailSent).toBe(sent)+ if (emailSendResult?.status === 'skipped') {+ expect(warning).toHaveBeenCalledWith('The recipient has no reachable mail servers.')+ } else if (!sent) {+ expect(error).toHaveBeenCalledWith(+ emailSendResult?.reason ??+ 'Could not confirm the test email was sent. Check the recipient and try again.'+ )+ }+ warning.mockRestore()+ error.mockRestore()+ })+})diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.tsnew file mode 100644index 000000000000..01da412ba9a7--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogic.ts@@ -0,0 +1,293 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, selectors } from 'kea'++import { Scene } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import type {+ EmailDomainStatusApi,+ EmailDomainStatusRecordApi,+ IntegrationConfigApi,+} from 'products/integrations/frontend/generated/api.schemas'++import { emailDomainAutoConfigureLogic } from './emailDomainAutoConfigureLogic'+import { EmailDomainLogicProps } from './emailDomainLogicProps'+import { emailDomainManualSetupLogic } from './emailDomainManualSetupLogic'+import { emailDomainSenderLogic } from './emailDomainSenderLogic'+import { emailDomainStatusLogic } from './emailDomainStatusLogic'++export type EmailDomainPhase = 'domain' | 'loading' | 'unavailable' | 'settings' | 'verifying' | 'ready'++export interface VerificationStep {+ key: 'domain_added' | 'records_found' | 'verified'+ label: string+ detail: string+ state: 'done' | 'active' | 'todo' | 'stuck'+}++interface PhaseInput {+ integrationId: number | null+ sender: IntegrationConfigApi | null+ senderFailed: boolean+ status: EmailDomainStatusApi | null+ statusUnavailable: boolean+ recordsAdded: boolean+ returnedFromAutoConfigure: boolean+ setupEvidenceFound: boolean+}++const STATUSES_IN_PROGRESS: EmailDomainStatusApi['status'][] = ['records_found', 'temporary_failure', 'failed']++const phaseOf = ({+ integrationId,+ sender,+ senderFailed,+ status,+ statusUnavailable,+ recordsAdded,+ returnedFromAutoConfigure,+ setupEvidenceFound,+}: PhaseInput): EmailDomainPhase => {+ if (integrationId === null) {+ return 'domain'+ }+ if (senderFailed || (!status && statusUnavailable)) {+ return 'unavailable'+ }+ if (!sender || !status) {+ return 'loading'+ }+ if (status.verified) {+ return 'ready'+ }+ const inProgress = recordsAdded || returnedFromAutoConfigure || STATUSES_IN_PROGRESS.includes(status.status)+ return inProgress || setupEvidenceFound ? 'verifying' : 'settings'+}++interface StepsInput {+ status: EmailDomainStatusApi | null+ phase: EmailDomainPhase+ domain: string | null+ records: EmailDomainStatusRecordApi[]+ foundCount: number+ allRecordsFound: boolean+ pollingStopped: boolean+}++const verificationStepsOf = ({+ status,+ phase,+ domain,+ records,+ foundCount,+ allRecordsFound,+ pollingStopped,+}: StepsInput): VerificationStep[] => {+ const verified = phase === 'ready'+ const verifying = phase === 'verifying'+ const sesFailed = status?.status === 'failed'+ const stuck = (pollingStopped && !allRecordsFound) || status?.status === 'temporary_failure'+ const foundState: VerificationStep['state'] = verified+ ? 'done'+ : stuck+ ? 'stuck'+ : allRecordsFound+ ? 'done'+ : verifying+ ? 'active'+ : 'todo'+ const verifiedState: VerificationStep['state'] = verified+ ? 'done'+ : sesFailed+ ? 'stuck'+ : allRecordsFound+ ? 'active'+ : 'todo'+ const foundDetail =+ verifying || verified+ ? `${foundCount} of ${records.length} found`+ : records.length+ ? `${records.length} settings to add`+ : 'Nothing to add yet'+ const verifiedDetail = verified+ ? 'Inboxes trust your emails'+ : sesFailed+ ? 'Verification stopped. Restart it below.'+ : allRecordsFound+ ? 'Records look right, waiting for confirmation'+ : 'Takes about a minute after the settings are found'+ return [+ { key: 'domain_added', label: 'Domain added', detail: domain ?? '', state: 'done' },+ { key: 'records_found', label: 'Settings found at your DNS host', detail: foundDetail, state: foundState },+ { key: 'verified', label: 'Ready to send', detail: verifiedDetail, state: verifiedState },+ ]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainLogicValues {+ returnedFromAutoConfigure: boolean // emailDomainAutoConfigureLogic+ recordsAdded: boolean // emailDomainManualSetupLogic+ domain: string | null // emailDomainSenderLogic+ integrationId: number | null // emailDomainSenderLogic+ sender: IntegrationConfigApi | null // emailDomainSenderLogic+ senderFailed: boolean // emailDomainSenderLogic+ senderLoading: boolean // emailDomainSenderLogic+ allRecordsFound: boolean // emailDomainStatusLogic+ foundCount: number // emailDomainStatusLogic+ pollingStopped: boolean // emailDomainStatusLogic+ records: EmailDomainStatusRecordApi[] // emailDomainStatusLogic+ setupEvidenceFound: boolean // emailDomainStatusLogic+ status: EmailDomainStatusApi | null // emailDomainStatusLogic+ statusLoading: boolean // emailDomainStatusLogic+ statusUnavailable: boolean // emailDomainStatusLogic+ breadcrumbs: Breadcrumb[]+ phase: EmailDomainPhase+ verificationSteps: VerificationStep[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainLogicActions {+ loadSender: () => any // emailDomainSenderLogic+ recheck: () => {+ value: true+ } // emailDomainStatusLogic+ retry: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ phase: (+ integrationId: number | null,+ sender: IntegrationConfigApi | null,+ senderFailed: boolean,+ status: EmailDomainStatusApi | null,+ statusUnavailable: boolean,+ recordsAdded: boolean,+ returnedFromAutoConfigure: boolean,+ setupEvidenceFound: boolean+ ) => EmailDomainPhase+ verificationSteps: (+ status: EmailDomainStatusApi | null,+ phase: EmailDomainPhase,+ domain: string | null,+ records: EmailDomainStatusRecordApi[],+ foundCount: number,+ allRecordsFound: boolean,+ pollingStopped: boolean+ ) => VerificationStep[]+ breadcrumbs: (domain: string | null, integrationId: number | null) => Breadcrumb[]+ }+}++export type emailDomainLogicType = MakeLogicType<+ emailDomainLogicValues,+ emailDomainLogicActions,+ EmailDomainLogicProps,+ emailDomainLogicMeta+>++/** The sending domain page: composes the step to show from the sender, its status and the setup path the person took. */+export const emailDomainLogic = kea<emailDomainLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'Channels', 'EmailDomain', 'emailDomainLogic', key]),+ props({} as EmailDomainLogicProps),+ key(({ id }) => id),+ connect((props: EmailDomainLogicProps) => ({+ values: [+ emailDomainSenderLogic(props),+ ['domain', 'integrationId', 'sender', 'senderFailed', 'senderLoading'],+ emailDomainStatusLogic(props),+ [+ 'allRecordsFound',+ 'foundCount',+ 'pollingStopped',+ 'records',+ 'setupEvidenceFound',+ 'status',+ 'statusUnavailable',+ 'statusLoading',+ ],+ emailDomainManualSetupLogic(props),+ ['recordsAdded'],+ emailDomainAutoConfigureLogic(props),+ ['returnedFromAutoConfigure'],+ ],+ actions: [emailDomainSenderLogic(props), ['loadSender'], emailDomainStatusLogic(props), ['recheck']],+ })),+ actions({+ retry: true,+ }),+ selectors({+ phase: [+ (s) => [+ s.integrationId,+ s.sender,+ s.senderFailed,+ s.status,+ s.statusUnavailable,+ s.recordsAdded,+ s.returnedFromAutoConfigure,+ s.setupEvidenceFound,+ ],+ (+ integrationId: number | null,+ sender: IntegrationConfigApi | null,+ senderFailed: boolean,+ status: EmailDomainStatusApi | null,+ statusUnavailable: boolean,+ recordsAdded: boolean,+ returnedFromAutoConfigure: boolean,+ setupEvidenceFound: boolean+ ): EmailDomainPhase =>+ phaseOf({+ integrationId,+ sender,+ senderFailed,+ status,+ statusUnavailable,+ recordsAdded,+ returnedFromAutoConfigure,+ setupEvidenceFound,+ }),+ ],+ verificationSteps: [+ (s) => [s.status, s.phase, s.domain, s.records, s.foundCount, s.allRecordsFound, s.pollingStopped],+ (+ status: EmailDomainStatusApi | null,+ phase: EmailDomainPhase,+ domain: string | null,+ records: EmailDomainStatusRecordApi[],+ foundCount: number,+ allRecordsFound: boolean,+ pollingStopped: boolean+ ): VerificationStep[] =>+ verificationStepsOf({ status, phase, domain, records, foundCount, allRecordsFound, pollingStopped }),+ ],+ breadcrumbs: [+ (s) => [s.domain, s.integrationId],+ (domain: string | null, integrationId: number | null): Breadcrumb[] => [+ { key: Scene.Workflows, name: 'Workflows', path: urls.workflows(), iconType: 'workflows' },+ { key: 'channels', name: 'Channels', path: urls.workflows('channels'), iconType: 'workflows' },+ {+ key: [Scene.WorkflowsEmailDomain, integrationId ?? 'new'],+ name: domain ?? 'New sending domain',+ iconType: 'workflows',+ },+ ],+ ],+ }),+ listeners(({ actions, values }) => ({+ retry: () => {+ if (values.senderFailed) {+ actions.loadSender()+ }+ if (values.statusUnavailable) {+ actions.recheck()+ }+ },+ })),+])diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainLogicProps.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogicProps.tsnew file mode 100644index 000000000000..8ba249b12d70--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainLogicProps.ts@@ -0,0 +1,6 @@+export interface EmailDomainLogicProps {+ /** The integration id, or `new` for the domain step. */+ id: string+}++export const integrationIdOf = (id: string): number | null => (/^\d+$/.test(id) ? Number(id) : null)diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainManualSetupLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainManualSetupLogic.tsnew file mode 100644index 000000000000..227377c0f7f7--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainManualSetupLogic.ts@@ -0,0 +1,111 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'+import posthog from 'posthog-js'++import { emailDomainAutoConfigureLogic } from './emailDomainAutoConfigureLogic'+import { EmailDomainLogicProps } from './emailDomainLogicProps'+import { EmailSetupMethod, emailDomainSenderLogic } from './emailDomainSenderLogic'+import { emailDomainStatusLogic } from './emailDomainStatusLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainManualSetupLogicValues {+ domain: string | null // emailDomainSenderLogic+ manualSetupRecorded: boolean+ recordsAdded: boolean+ recordsRevealed: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainManualSetupLogicActions {+ openAutoConfigure: () => {+ value: true+ } // emailDomainAutoConfigureLogic+ recordSetupMethod: (method: EmailSetupMethod) => {+ method: EmailSetupMethod+ } // emailDomainSenderLogic+ recheck: () => {+ value: true+ } // emailDomainStatusLogic+ markRecordsAdded: () => {+ value: true+ }+ recordManualSetup: () => {+ value: true+ }+ revealRecords: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainManualSetupLogicMeta {+ key: string+}++export type emailDomainManualSetupLogicType = MakeLogicType<+ emailDomainManualSetupLogicValues,+ emailDomainManualSetupLogicActions,+ EmailDomainLogicProps,+ emailDomainManualSetupLogicMeta+>++/** The path where the person adds the DNS records by hand: reveals them, marks them added and records that method once. */+export const emailDomainManualSetupLogic = kea<emailDomainManualSetupLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'Channels', 'EmailDomain', 'emailDomainManualSetupLogic', key]),+ props({} as EmailDomainLogicProps),+ key(({ id }) => id),+ connect((props: EmailDomainLogicProps) => ({+ values: [emailDomainSenderLogic(props), ['domain']],+ actions: [+ emailDomainSenderLogic(props),+ ['recordSetupMethod'],+ emailDomainStatusLogic(props),+ ['recheck'],+ emailDomainAutoConfigureLogic(props),+ ['openAutoConfigure'],+ ],+ })),+ actions({+ revealRecords: true,+ markRecordsAdded: true,+ recordManualSetup: true,+ }),+ reducers({+ recordsRevealed: [+ false,+ {+ revealRecords: () => true,+ markRecordsAdded: () => true,+ },+ ],+ recordsAdded: [+ false,+ {+ markRecordsAdded: () => true,+ },+ ],+ // Auto-configure writes `auto` on the backend, so a later manual step must be recorded again.+ manualSetupRecorded: [+ false,+ {+ recordSetupMethod: (_, { method }) => method === 'manual',+ openAutoConfigure: () => false,+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ revealRecords: () => {+ actions.recordManualSetup()+ },+ markRecordsAdded: () => {+ // pinned: analytics event name+ posthog.capture('email domain records added', { domain: values.domain })+ actions.recheck()+ actions.recordManualSetup()+ },+ recordManualSetup: () => {+ if (!values.manualSetupRecorded) {+ actions.recordSetupMethod('manual')+ }+ },+ })),+])diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainPageUrl.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainPageUrl.tsnew file mode 100644index 000000000000..54b503485e0a--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainPageUrl.ts@@ -0,0 +1,4 @@+import { urls } from 'scenes/urls'++export const emailDomainPageUrl = (teamId: number, integrationId: number): string =>+ `${window.location.origin}/project/${teamId}${urls.workflowsEmailDomain(integrationId)}`diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainSenderLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainSenderLogic.tsnew file mode 100644index 000000000000..a45d41eba9cd--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainSenderLogic.ts@@ -0,0 +1,317 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api, { ApiError } from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { UserType } from '~/types'++import { integrationsEmailPartialUpdate, integrationsRetrieve } from 'products/integrations/frontend/generated/api'+import type { IntegrationConfigApi } from 'products/integrations/frontend/generated/api.schemas'++import { HogflowTestResult } from '../../Workflows/hogflows/steps/types'+import { buildTestEmailInvocation } from './buildTestEmailWorkflow'+import { EmailDomainLogicProps, integrationIdOf } from './emailDomainLogicProps'++export type EmailSetupMethod = 'auto' | 'manual'++export interface EmailSenderConfig {+ domain: string+ email: string+ name: string+ provider: 'ses' | 'maildev'+ mail_from_subdomain?: string+ verified?: boolean+ setup_method?: EmailSetupMethod+}++const DEFAULT_MAIL_FROM_SUBDOMAIN = 'feedback'++const configOf = (sender: IntegrationConfigApi | null): EmailSenderConfig | null =>+ (sender?.config as EmailSenderConfig | undefined) ?? null++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainSenderLogicValues {+ currentTeamId: number | null // teamLogic+ user: UserType | null // userLogic+ domain: string | null+ fromAddress: string | null+ integrationId: number | null+ mailFromSubdomain: string+ sender: IntegrationConfigApi | null+ senderConfig: EmailSenderConfig | null+ senderFailed: boolean+ senderLoading: boolean+ senderName: string+ senderNameChanged: boolean+ senderSaving: boolean+ testEmailSent: boolean+ testSendResult: HogflowTestResult | null+ testSendResultLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainSenderLogicActions {+ loadIntegrations: (_?: any) => any // integrationsLogic+ loadSender: () => any+ loadSenderFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSenderSuccess: (+ sender: IntegrationConfigApi | null,+ payload?: any+ ) => {+ sender: IntegrationConfigApi | null+ payload?: any+ }+ recordSetupMethod: (method: EmailSetupMethod) => {+ method: EmailSetupMethod+ }+ recordSetupMethodFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ recordSetupMethodSuccess: (+ sender: IntegrationConfigApi | null,+ payload?: {+ method: EmailSetupMethod+ }+ ) => {+ sender: IntegrationConfigApi | null+ payload?: {+ method: EmailSetupMethod+ }+ }+ saveSender: () => {+ value: true+ }+ saveSenderFailed: () => {+ value: true+ }+ sendTestEmail: () => any+ sendTestEmailFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ sendTestEmailSuccess: (+ testSendResult: HogflowTestResult | null,+ payload?: any+ ) => {+ testSendResult: HogflowTestResult | null+ payload?: any+ }+ senderSaved: (sender: IntegrationConfigApi) => {+ sender: IntegrationConfigApi+ }+ setSenderName: (name: string) => {+ name: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainSenderLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ integrationId: (arg: string) => number | null+ senderConfig: (sender: IntegrationConfigApi | null) => EmailSenderConfig | null+ domain: (senderConfig: EmailSenderConfig | null) => string | null+ fromAddress: (senderConfig: EmailSenderConfig | null) => string | null+ mailFromSubdomain: (senderConfig: EmailSenderConfig | null) => string+ senderNameChanged: (senderName: string, senderConfig: EmailSenderConfig | null) => boolean+ }+}++export type emailDomainSenderLogicType = MakeLogicType<+ emailDomainSenderLogicValues,+ emailDomainSenderLogicActions,+ EmailDomainLogicProps,+ emailDomainSenderLogicMeta+>++/** The email sender behind the page: loads it, edits its name, records how its DNS was set up, and sends a test email. */+export const emailDomainSenderLogic = kea<emailDomainSenderLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'Channels', 'EmailDomain', 'emailDomainSenderLogic', key]),+ props({} as EmailDomainLogicProps),+ key(({ id }) => id),+ connect(() => ({+ values: [teamLogic, ['currentTeamId'], userLogic, ['user']],+ actions: [integrationsLogic, ['loadIntegrations']],+ })),+ actions({+ setSenderName: (name: string) => ({ name }),+ saveSender: true,+ senderSaved: (sender: IntegrationConfigApi) => ({ sender }),+ saveSenderFailed: true,+ recordSetupMethod: (method: EmailSetupMethod) => ({ method }),+ }),+ loaders(({ values }) => ({+ sender: [+ null as IntegrationConfigApi | null,+ {+ loadSender: async (): Promise<IntegrationConfigApi | null> => {+ const { integrationId, currentTeamId } = values+ if (!integrationId || !currentTeamId) {+ return null+ }+ return await integrationsRetrieve(String(currentTeamId), integrationId)+ },+ recordSetupMethod: async ({ method }): Promise<IntegrationConfigApi | null> => {+ const { integrationId, currentTeamId, senderConfig, sender } = values+ if (!integrationId || !currentTeamId || !senderConfig) {+ return sender+ }+ try {+ return await integrationsEmailPartialUpdate(String(currentTeamId), integrationId, {+ config: { ...senderConfig, setup_method: method },+ })+ } catch {+ return sender+ }+ },+ },+ ],+ testSendResult: [+ null as HogflowTestResult | null,+ {+ sendTestEmail: async (): Promise<HogflowTestResult | null> => {+ const { integrationId, currentTeamId, user, domain } = values+ const recipient = user?.email+ if (!integrationId || !domain || !recipient) {+ return null+ }+ try {+ // nosemgrep: prefer-codegen-api-namespaced-workflows -- the generated hogFlowsInvocationsCreate returns void, and this reads the test result+ return await api.hogFlows.createTestInvocation(+ 'new',+ buildTestEmailInvocation({ integrationId, teamId: currentTeamId, domain, recipient })+ )+ } catch {+ lemonToast.error('Could not send the test email. Try again in a moment.')+ return null+ }+ },+ },+ ],+ })),+ reducers({+ sender: {+ senderSaved: (_, { sender }) => sender,+ },+ senderSaving: [+ false,+ {+ saveSender: () => true,+ senderSaved: () => false,+ saveSenderFailed: () => false,+ },+ ],+ senderFailed: [+ false,+ {+ loadSender: () => false,+ loadSenderFailure: () => true,+ },+ ],+ senderName: [+ '',+ {+ setSenderName: (_, { name }) => name,+ loadSenderSuccess: (state, { sender }) => configOf(sender)?.name ?? state,+ senderSaved: (state, { sender }) => configOf(sender)?.name ?? state,+ },+ ],+ testEmailSent: [+ false,+ {+ sendTestEmailSuccess: (state, { testSendResult }) =>+ (testSendResult?.status === 'success' && testSendResult.emailSendResult?.status === 'accepted') ||+ state,+ },+ ],+ }),+ selectors({+ integrationId: [+ () => [(_, props: EmailDomainLogicProps) => props.id],+ (id: string): number | null => integrationIdOf(id),+ ],+ senderConfig: [+ (s) => [s.sender],+ (sender: IntegrationConfigApi | null): EmailSenderConfig | null => configOf(sender),+ ],+ domain: [+ (s) => [s.senderConfig],+ (senderConfig: EmailSenderConfig | null): string | null => senderConfig?.domain ?? null,+ ],+ fromAddress: [+ (s) => [s.senderConfig],+ (senderConfig: EmailSenderConfig | null): string | null => senderConfig?.email ?? null,+ ],+ mailFromSubdomain: [+ (s) => [s.senderConfig],+ (senderConfig: EmailSenderConfig | null): string =>+ senderConfig?.mail_from_subdomain || DEFAULT_MAIL_FROM_SUBDOMAIN,+ ],+ senderNameChanged: [+ (s) => [s.senderName, s.senderConfig],+ (senderName: string, senderConfig: EmailSenderConfig | null): boolean =>+ senderName !== (senderConfig?.name ?? ''),+ ],+ }),+ listeners(({ actions, values }) => ({+ saveSender: async () => {+ const { integrationId, currentTeamId, senderConfig } = values+ if (!integrationId || !currentTeamId || !senderConfig) {+ actions.saveSenderFailed()+ return+ }+ try {+ const saved = await integrationsEmailPartialUpdate(String(currentTeamId), integrationId, {+ config: { ...senderConfig, name: values.senderName },+ })+ actions.senderSaved(saved)+ } catch (error) {+ actions.saveSenderFailed()+ lemonToast.error(+ (error instanceof ApiError && error.detail) ||+ 'Could not save the sender name. Try again in a moment.'+ )+ }+ },+ senderSaved: () => {+ actions.loadIntegrations()+ lemonToast.success('Sender name saved')+ },+ sendTestEmailSuccess: ({ testSendResult }) => {+ if (testSendResult?.status === 'success' && testSendResult.emailSendResult?.status === 'accepted') {+ lemonToast.success(`The email provider accepted your test email to ${values.user?.email}.`)+ } else if (testSendResult?.emailSendResult?.status === 'skipped') {+ lemonToast.warning(+ testSendResult.emailSendResult.reason ?? 'Nothing was sent. Check the recipient settings.'+ )+ } else if (testSendResult) {+ lemonToast.error(+ testSendResult.emailSendResult?.reason ??+ 'Could not confirm the test email was sent. Check the recipient and try again.'+ )+ }+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.integrationId !== null) {+ actions.loadSender()+ }+ }),+])diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainStatusLogic.test.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainStatusLogic.test.tsnew file mode 100644index 000000000000..d8fd310d3940--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainStatusLogic.test.ts@@ -0,0 +1,243 @@+import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { FakeEmailDomainBackend } from './__mocks__/fakeEmailDomainBackend'+import { emailDomainStatusLogic } from './emailDomainStatusLogic'++const DOMAIN = 'mail.acme.com'+const MINUTE = 60_000++const setDocumentHidden = (hidden: boolean): void => {+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })+ document.dispatchEvent(new Event('visibilitychange'))+}++describe('emailDomainStatusLogic', () => {+ let backend: FakeEmailDomainBackend+ let logic: ReturnType<typeof emailDomainStatusLogic.build>++ const statusChecks = (): number => backend.requestsTo('email_status').length++ beforeEach(() => {+ jest.useFakeTimers()+ backend = new FakeEmailDomainBackend()+ backend.hostDnsAt('acme.com', 'cloudflare')+ backend.addSender({ email: `hello@${DOMAIN}` })+ useMocks(backend.mocks())+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ setDocumentHidden(false)+ jest.useRealTimers()+ })++ const mountAndLoad = async (): Promise<void> => {+ logic = emailDomainStatusLogic({ id: '42' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)+ }++ it('polls every 10 seconds for 5 minutes, then every 30 seconds, and stops after 30 minutes', async () => {+ await mountAndLoad()+ expect(statusChecks()).toBe(1)++ await jest.advanceTimersByTimeAsync(10_000)+ expect(statusChecks()).toBe(2)++ await jest.advanceTimersByTimeAsync(5 * MINUTE - 10_000)+ expect(statusChecks()).toBe(31)++ await jest.advanceTimersByTimeAsync(10_000)+ expect(statusChecks()).toBe(31)+ await jest.advanceTimersByTimeAsync(20_000)+ expect(statusChecks()).toBe(32)++ await jest.advanceTimersByTimeAsync(25 * MINUTE)+ expect(statusChecks()).toBe(81)+ expect(logic.values.pollingStopped).toBe(true)++ await jest.advanceTimersByTimeAsync(5 * MINUTE)+ expect(statusChecks()).toBe(81)+ })++ it.each([MINUTE, 31 * MINUTE])(+ 'pauses polling for %s milliseconds hidden and resumes within the original deadline',+ async (hiddenDuration) => {+ await mountAndLoad()+ expect(statusChecks()).toBe(1)++ setDocumentHidden(true)+ await jest.advanceTimersByTimeAsync(hiddenDuration)+ expect(statusChecks()).toBe(1)++ setDocumentHidden(false)+ await jest.advanceTimersByTimeAsync(10_000)+ expect(statusChecks()).toBe(hiddenDuration < 30 * MINUTE ? 2 : 1)+ expect(logic.values.pollingStopped).toBe(hiddenDuration >= 30 * MINUTE)+ }+ )++ it('asks the provider to set the domain up again and restarts the schedule when the person checks again', async () => {+ await mountAndLoad()+ await jest.advanceTimersByTimeAsync(31 * MINUTE)+ expect(logic.values.pollingStopped).toBe(true)+ const checksBefore = statusChecks()++ logic.actions.checkAgain()+ await jest.advanceTimersByTimeAsync(0)+ expect(backend.requestsTo('email_verify')).toHaveLength(1)+ expect(backend.requestsTo('email_status').at(-1)?.url).toContain('refresh=true')+ expect(logic.values.pollingStopped).toBe(false)++ await jest.advanceTimersByTimeAsync(10_000)+ expect(statusChecks()).toBe(checksBefore + 2)+ })++ it.each([+ [500, true],+ [400, false],+ [403, false],+ [404, false],+ ])('marks the status failed when a check answers %s and keeps polling: %s', async (httpStatus, keepsPolling) => {+ backend.fail('email_status', { status: httpStatus, body: { detail: 'SES read failed' } })+ await mountAndLoad()+ expect(logic.values.statusUnavailable).toBe(true)+ expect(logic.values.status).toBeNull()++ await jest.advanceTimersByTimeAsync(10_000)+ expect(statusChecks()).toBe(keepsPolling ? 2 : 1)++ backend.recover('email_status')+ logic.actions.recheck()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.statusUnavailable).toBe(false)+ expect(logic.values.status?.status).toBe('pending')+ })++ it('keeps the last status and the progress, and keeps polling, when a later check fails', async () => {+ backend.publishRecords(DOMAIN)+ await mountAndLoad()+ expect(logic.values.status?.status).toBe('records_found')++ backend.fail('email_status', { status: 503, body: { code: 'ses_unavailable', detail: 'SES is down' } })+ await jest.advanceTimersByTimeAsync(10_000)+ expect(logic.values.statusUnavailable).toBe(false)+ expect(logic.values.status?.status).toBe('records_found')+ expect(logic.values.foundCount).toBe(logic.values.records.length)++ backend.recover('email_status')+ backend.verifyDomain(DOMAIN)+ await jest.advanceTimersByTimeAsync(10_000)+ expect(statusChecks()).toBe(3)+ expect(logic.values.status?.verified).toBe(true)+ })++ it('records a verification the provider reports through email verify, once', async () => {+ backend.verifyAtProviderOnly(DOMAIN)++ await mountAndLoad()++ expect(backend.requestsTo('email_verify')).toHaveLength(1)+ expect(logic.values.status?.verified).toBe(true)+ await jest.advanceTimersByTimeAsync(MINUTE)+ expect(backend.requestsTo('email_verify')).toHaveLength(1)+ })++ it('records the verification on a later poll when email verify fails once', async () => {+ backend.verifyAtProviderOnly(DOMAIN)+ backend.failOnce('email_verify', { status: 500, body: { detail: 'SES is down' } })++ await mountAndLoad()+ expect(logic.values.status?.verified).toBe(false)++ await jest.advanceTimersByTimeAsync(MINUTE)+ expect(backend.requestsTo('email_verify')).toHaveLength(2)+ expect(logic.values.status?.verified).toBe(true)+ })++ it('stops polling once the domain is verified and refreshes the channel list and the default sender', async () => {+ backend.verifyDomain(DOMAIN)+ await mountAndLoad()+ expect(logic.values.status?.verified).toBe(true)+ expect(backend.requestsTo('integration_list').length).toBeGreaterThan(0)+ await expectLogic(teamLogic).toDispatchActions(['loadCurrentTeam'])++ await jest.advanceTimersByTimeAsync(MINUTE)+ expect(statusChecks()).toBe(1)+ })++ it('keeps a newer verified answer when an older poll answers after it', async () => {+ await mountAndLoad()++ const releasePoll = backend.hold('email_status')+ await jest.advanceTimersByTimeAsync(10_000)+ const releaseRecheck = backend.hold('email_status')+ logic.actions.recheck()+ await jest.advanceTimersByTimeAsync(0)++ backend.verifyDomain(DOMAIN)+ releaseRecheck()+ await jest.advanceTimersByTimeAsync(0)+ backend.sesReports(DOMAIN, 'pending')+ releasePoll()+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.status?.verified).toBe(true)+ })++ it('shows a check as running only while a check the person asked for is in flight', async () => {+ await mountAndLoad()++ const releasePoll = backend.hold('email_status')+ await jest.advanceTimersByTimeAsync(10_000)+ expect(logic.values.statusLoading).toBe(true)+ expect(logic.values.rechecking).toBe(false)+ releasePoll()+ await jest.advanceTimersByTimeAsync(0)++ const releaseRecheck = backend.hold('email_status')+ logic.actions.recheck()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.rechecking).toBe(true)+ releaseRecheck()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.rechecking).toBe(false)+ })++ it('rechecks right after verification restarts, and stays usable when the restart fails', async () => {+ backend.sesReports(DOMAIN, 'failed')+ await mountAndLoad()+ expect(logic.values.status?.status).toBe('failed')++ backend.failOnce('email_verify', { status: 500, body: { detail: 'SES is down' } })+ logic.actions.restartVerification()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.restartResultLoading).toBe(false)+ expect(logic.values.status?.status).toBe('failed')++ logic.actions.restartVerification()+ await jest.advanceTimersByTimeAsync(0)+ expect(backend.requestsTo('email_verify')).toHaveLength(2)+ expect(logic.values.status?.status).toBe('pending')+ })++ it('keeps checking after a restart when the first check finds the provider unavailable', async () => {+ backend.sesReports(DOMAIN, 'failed')+ await mountAndLoad()+ expect(logic.values.status?.status).toBe('failed')++ backend.failOnce('email_status', { status: 503, body: { code: 'email_provider_unavailable' } })+ logic.actions.restartVerification()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.status?.status).toBe('failed')++ await jest.advanceTimersByTimeAsync(10_000)+ expect(logic.values.status?.status).toBe('pending')+ })+})diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainStatusLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainStatusLogic.tsnew file mode 100644index 000000000000..ed66fbf6e9ac--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainStatusLogic.ts@@ -0,0 +1,377 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import api, { ApiError } from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { integrationsEmailStatusRetrieve } from 'products/integrations/frontend/generated/api'+import type {+ EmailDomainSetupRecordKindEnumApi,+ EmailDomainStatusApi,+ EmailDomainStatusRecordApi,+} from 'products/integrations/frontend/generated/api.schemas'++import { EmailDomainLogicProps, integrationIdOf } from './emailDomainLogicProps'+import { emailDomainSenderLogic } from './emailDomainSenderLogic'++export const POLL_FAST_MS = 10_000+export const POLL_FAST_WINDOW_MS = 5 * 60_000+export const POLL_SLOW_MS = 30_000+export const POLL_MAX_MS = 30 * 60_000++const STATUS_ERRORS_THAT_END_POLLING = [400, 403, 404]+const MAX_VERIFICATION_RECORD_ATTEMPTS = 3+// A DMARC or apex SPF record often exists before the person adds anything, so finding one proves nothing about setup.+const RECORD_KINDS_THAT_PREDATE_SETUP: EmailDomainSetupRecordKindEnumApi[] = ['dmarc', 'spf']++const isRecordFound = (record: EmailDomainStatusRecordApi): boolean => record.status !== 'pending'+const isSetupEvidence = (record: EmailDomainStatusRecordApi): boolean =>+ isRecordFound(record) && !RECORD_KINDS_THAT_PREDATE_SETUP.includes(record.kind)++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainStatusLogicValues {+ domain: string | null // emailDomainSenderLogic+ currentTeamId: number | null // teamLogic+ allRecordsFound: boolean+ foundCount: number+ integrationId: number | null+ lastCheckFailed: boolean+ missingRecords: EmailDomainStatusRecordApi[]+ pollingStartedAt: number | null+ pollingStopped: boolean+ rechecking: boolean+ records: EmailDomainStatusRecordApi[]+ restartResult: boolean | null+ restartResultLoading: boolean+ setupEvidenceFound: boolean+ status: EmailDomainStatusApi | null+ statusLoading: boolean+ statusUnavailable: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainStatusLogicActions {+ loadIntegrations: (_?: any) => any // integrationsLogic+ checkAgain: () => {+ value: true+ }+ loadStatus: (refresh?: boolean) => {+ refresh: boolean+ }+ loadStatusFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadStatusSuccess: (+ status: EmailDomainStatusApi | null,+ payload?: {+ refresh: boolean+ }+ ) => {+ status: EmailDomainStatusApi | null+ payload?: {+ refresh: boolean+ }+ }+ recheck: () => {+ value: true+ }+ recordVerification: () => {+ value: true+ }+ restartVerification: () => any+ restartVerificationFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ restartVerificationSuccess: (+ restartResult: boolean | null,+ payload?: any+ ) => {+ restartResult: boolean | null+ payload?: any+ }+ schedulePoll: () => {+ value: true+ }+ startPolling: () => {+ value: true+ }+ statusCheckFailed: (httpStatus: number | null) => {+ httpStatus: number | null+ }+ stopPolling: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainStatusLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ integrationId: (arg: string) => number | null+ records: (status: EmailDomainStatusApi | null) => EmailDomainStatusRecordApi[]+ foundCount: (records: EmailDomainStatusRecordApi[]) => number+ allRecordsFound: (records: EmailDomainStatusRecordApi[], foundCount: number) => boolean+ setupEvidenceFound: (records: EmailDomainStatusRecordApi[]) => boolean+ missingRecords: (+ records: EmailDomainStatusRecordApi[],+ pollingStopped: boolean,+ status: EmailDomainStatusApi | null+ ) => EmailDomainStatusRecordApi[]+ }+}++export type emailDomainStatusLogicType = MakeLogicType<+ emailDomainStatusLogicValues,+ emailDomainStatusLogicActions,+ EmailDomainLogicProps,+ emailDomainStatusLogicMeta+>++/** Reads the domain's setup status and keeps polling it while the page is open and the domain is not verified. */+export const emailDomainStatusLogic = kea<emailDomainStatusLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'Channels', 'EmailDomain', 'emailDomainStatusLogic', key]),+ props({} as EmailDomainLogicProps),+ key(({ id }) => id),+ connect((props: EmailDomainLogicProps) => ({+ values: [teamLogic, ['currentTeamId'], emailDomainSenderLogic(props), ['domain']],+ actions: [integrationsLogic, ['loadIntegrations']],+ })),+ actions({+ loadStatus: (refresh: boolean = false) => ({ refresh }),+ statusCheckFailed: (httpStatus: number | null) => ({ httpStatus }),+ startPolling: true,+ schedulePoll: true,+ stopPolling: true,+ recheck: true,+ checkAgain: true,+ recordVerification: true,+ }),+ loaders(({ values, actions }) => ({+ status: [+ null as EmailDomainStatusApi | null,+ {+ loadStatus: async ({ refresh }, breakpoint): Promise<EmailDomainStatusApi | null> => {+ const { integrationId, currentTeamId } = values+ if (!integrationId || !currentTeamId) {+ return null+ }+ let status: EmailDomainStatusApi+ try {+ status = await integrationsEmailStatusRetrieve(String(currentTeamId), integrationId, {+ refresh,+ })+ } catch (error) {+ breakpoint()+ actions.statusCheckFailed(error instanceof ApiError ? (error.status ?? null) : null)+ return values.status+ }+ // A poll and a recheck can overlap. Only the newest one's answer counts.+ breakpoint()+ return status+ },+ },+ ],+ restartResult: [+ null as boolean | null,+ {+ restartVerification: async (): Promise<boolean | null> => {+ if (!values.integrationId) {+ return null+ }+ try {+ // nosemgrep: prefer-codegen-api-namespaced-integrations -- the generated integrationsEmailVerifyCreate returns void and demands a config body the endpoint ignores+ await api.integrations.verifyEmail(values.integrationId)+ return true+ } catch (error) {+ lemonToast.error(+ (error instanceof ApiError && error.detail) ||+ 'Could not reach the email provider. Try again in a moment.'+ )+ return false+ }+ },+ },+ ],+ })),+ reducers({+ lastCheckFailed: [+ false,+ {+ loadStatus: () => false,+ statusCheckFailed: () => true,+ },+ ],+ statusUnavailable: [+ false,+ {+ statusCheckFailed: () => true,+ loadStatusSuccess: (state, { status }) => (status ? false : state),+ },+ ],+ pollingStartedAt: [+ null as number | null,+ {+ startPolling: () => Date.now(),+ recheck: () => Date.now(),+ },+ ],+ pollingStopped: [+ false,+ {+ stopPolling: () => true,+ recheck: () => false,+ },+ ],+ rechecking: [+ false,+ {+ recheck: () => true,+ loadStatusSuccess: () => false,+ loadStatusFailure: () => false,+ },+ ],+ }),+ selectors({+ integrationId: [+ () => [(_, props: EmailDomainLogicProps) => props.id],+ (id: string): number | null => integrationIdOf(id),+ ],+ records: [+ (s) => [s.status],+ (status: EmailDomainStatusApi | null): EmailDomainStatusRecordApi[] => status?.records ?? [],+ ],+ foundCount: [+ (s) => [s.records],+ (records: EmailDomainStatusRecordApi[]): number => records.filter(isRecordFound).length,+ ],+ allRecordsFound: [+ (s) => [s.records, s.foundCount],+ (records: EmailDomainStatusRecordApi[], foundCount: number): boolean =>+ records.length > 0 && foundCount === records.length,+ ],+ setupEvidenceFound: [+ (s) => [s.records],+ (records: EmailDomainStatusRecordApi[]): boolean => records.some(isSetupEvidence),+ ],+ missingRecords: [+ (s) => [s.records, s.pollingStopped, s.status],+ (+ records: EmailDomainStatusRecordApi[],+ pollingStopped: boolean,+ status: EmailDomainStatusApi | null+ ): EmailDomainStatusRecordApi[] =>+ pollingStopped || status?.status === 'temporary_failure'+ ? records.filter((record) => !isRecordFound(record))+ : [],+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ loadStatusSuccess: ({ status }) => {+ if (values.integrationId === null) {+ return+ }+ // A failed check keeps the last status, which must not end polling as if it were fresh.+ if (values.lastCheckFailed) {+ if (values.pollingStartedAt === null) {+ actions.startPolling()+ }+ actions.schedulePoll()+ return+ }+ // A poll only reports the provider's answer, and email/verify records it. The attempt cap keeps a+ // provider that answers verified but never records out of a loop.+ const recordAttempts: number = cache.verificationRecordAttempts ?? 0+ if (+ status?.status === 'verified' &&+ !status.verified &&+ recordAttempts < MAX_VERIFICATION_RECORD_ATTEMPTS+ ) {+ cache.verificationRecordAttempts = recordAttempts + 1+ actions.recordVerification()+ return+ }+ if (status?.verified || status?.status === 'failed') {+ cache.disposables.dispose('poll')+ if (status.verified) {+ actions.loadIntegrations()+ // Verifying the first sender makes it the project default on the server.+ teamLogic.findMounted()?.actions.loadCurrentTeam()+ }+ return+ }+ if (values.pollingStartedAt === null) {+ actions.startPolling()+ }+ actions.schedulePoll()+ },+ recordVerification: async () => {+ if (!values.integrationId) {+ return+ }+ try {+ // nosemgrep: prefer-codegen-api-namespaced-integrations -- the generated integrationsEmailVerifyCreate returns void and demands a config body the endpoint ignores+ await api.integrations.verifyEmail(values.integrationId)+ } catch {+ actions.schedulePoll()+ return+ }+ actions.loadStatus(true)+ },+ schedulePoll: () => {+ if (values.pollingStopped) {+ return+ }+ const elapsed = Date.now() - (values.pollingStartedAt ?? Date.now())+ if (elapsed >= POLL_MAX_MS) {+ actions.stopPolling()+ return+ }+ cache.disposables.add(() => {+ const elapsed = Date.now() - (values.pollingStartedAt ?? Date.now())+ if (elapsed >= POLL_MAX_MS) {+ actions.stopPolling()+ return () => undefined+ }+ const delay = elapsed < POLL_FAST_WINDOW_MS ? POLL_FAST_MS : POLL_SLOW_MS+ const timer = window.setTimeout(() => actions.loadStatus(), delay)+ return () => clearTimeout(timer)+ }, 'poll')+ },+ stopPolling: () => {+ cache.disposables.dispose('poll')+ },+ statusCheckFailed: ({ httpStatus }) => {+ if (httpStatus && STATUS_ERRORS_THAT_END_POLLING.includes(httpStatus)) {+ actions.stopPolling()+ }+ },+ recheck: () => {+ actions.loadStatus(true)+ },+ checkAgain: () => {+ // pinned: analytics event name+ posthog.capture('email domain check again clicked', { domain: values.domain })+ // A manual check may write: verify sets up what the provider is missing, which polling never does.+ actions.restartVerification()+ },+ restartVerificationSuccess: () => {+ actions.recheck()+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.integrationId !== null) {+ actions.loadStatus()+ }+ }),+])diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.test.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.test.tsnew file mode 100644index 000000000000..0c2b9e1c1c27--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.test.ts@@ -0,0 +1,158 @@+import { expectLogic } from 'kea-test-utils'++import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { PreflightStatus } from '~/types'++import { FakeEmailDomainBackend } from './__mocks__/fakeEmailDomainBackend'+import { emailDomainWizardLogic } from './emailDomainWizardLogic'++describe('emailDomainWizardLogic', () => {+ let backend: FakeEmailDomainBackend++ beforeEach(() => {+ backend = new FakeEmailDomainBackend()+ useMocks(backend.mocks())+ initKeaTests()+ })++ const mountWizard = (): ReturnType<typeof emailDomainWizardLogic.build> => {+ const logic = emailDomainWizardLogic({ logicKey: 'test', onCreated: () => {} })+ logic.mount()+ return logic+ }++ it.each([+ ['acme.com', 'acme.com', 'hello'],+ [' ACME.com ', 'acme.com', 'hello'],+ ['https://www.acme.com/pricing?x=1', 'acme.com', 'hello'],+ ['app.acme.com', 'app.acme.com', 'hello'],+ ['[email protected]', 'acme.com', 'jane'],+ ['[email protected]', 'acme.com', 'support'],+ ])('turns the input %s into the domain %s and the address %s@', (input, domain, localPart) => {+ const logic = mountWizard()++ logic.actions.setCustomDomainInput(input)+ logic.actions.useCustomDomain()++ expect(logic.values.selectedDomain).toBe(domain)+ expect(logic.values.localPart).toBe(localPart)+ expect(logic.values.fromAddress).toBe(`${localPart}@mail.${domain}`)+ })++ it.each([+ ['[email protected]', 'free_mailbox'],+ ['gmx.de', 'free_mailbox'],+ ['not a domain', 'invalid'],+ ['acme', 'invalid'],+ ['127.0.0.1', 'invalid'],+ ['http://10.0.0.5:3000', 'invalid'],+ ['acme.123', 'invalid'],+ ])('refuses %s as %s and keeps the domain unselected', (input, problem) => {+ const logic = mountWizard()++ logic.actions.setCustomDomainInput(input)+ logic.actions.useCustomDomain()++ expect(logic.values.customDomain.problem).toBe(problem)+ expect(logic.values.selectedDomain).toBeNull()+ })++ it.each([+ ['mail', 'news!', 'news'],+ ['send', 'Send', 'send'],+ ['', 'My Sub', 'mysub'],+ ])('keeps the sending subdomain to dns label characters: %s then %s becomes %s', (first, typed, expected) => {+ const logic = mountWizard()+ logic.actions.selectDomain('acme.com')++ logic.actions.setSendPrefix(first)+ logic.actions.setSendPrefix(typed)++ expect(logic.values.sendPrefix).toBe(expected)+ expect(logic.values.sendingDomain).toBe(`${expected}.acme.com`)+ })++ const mountWithExistingSender = async (): Promise<ReturnType<typeof emailDomainWizardLogic.build>> => {+ backend.addSender({ email: '[email protected]', mail_from_subdomain: 'bounce' })+ const logic = mountWizard()+ await expectLogic(integrationsLogic).toDispatchActions(['loadIntegrationsSuccess'])+ return logic+ }++ it.each([+ ['[email protected]', '[email protected]'],+ ['[email protected]', '[email protected]'],+ ])('adds %s to a domain that already sends as %s, keeping its bounce subdomain', async (input, address) => {+ const logic = await mountWithExistingSender()++ logic.actions.setCustomDomainInput(input)+ logic.actions.useCustomDomain()+ expect(logic.values.existingSender).toBeNull()+ await expectLogic(logic, () => logic.actions.createSender()).toFinishAllListeners()++ expect(backend.requestsTo('integration_create').at(-1)?.body).toMatchObject({+ config: { email: address, mail_from_subdomain: 'bounce' },+ })+ })++ it.each([+ ['a local stack by default', true, null, 'maildev'],+ ['a local stack set to SES', true, 'ses' as const, 'ses'],+ ['a hosted stack, whatever was picked', false, 'maildev' as const, 'ses'],+ ])('creates the sender through the right provider on %s', async (_name, isDebug, picked, provider) => {+ const logic = mountWizard()+ preflightLogic.actions.loadPreflightSuccess({ is_debug: isDebug } as PreflightStatus)+ if (picked) {+ logic.actions.setLocalProvider(picked)+ }++ logic.actions.setCustomDomainInput('acme.com')+ logic.actions.useCustomDomain()+ await expectLogic(logic, () => logic.actions.createSender()).toFinishAllListeners()++ expect(backend.requestsTo('integration_create').at(-1)?.body).toMatchObject({ config: { provider } })+ })++ it.each([+ [+ 'the typed name, address and reply-to',+ 'Support team',+ 'support',+ '[email protected]',+ { name: 'Support team', email: '[email protected]', reply_to: '[email protected]' },+ ],+ [+ 'the suggestions when the fields are left blank',+ ' ',+ '',+ ' ',+ { name: 'Acme', email: '[email protected]' },+ ],+ ])('creates the sender with %s', async (_name, typedName, typedLocalPart, typedReplyTo, config) => {+ const logic = mountWizard()++ logic.actions.setCustomDomainInput('acme.com')+ logic.actions.useCustomDomain()+ logic.actions.setSenderNameInput(typedName)+ logic.actions.setLocalPart(typedLocalPart)+ logic.actions.setReplyTo(typedReplyTo)+ await expectLogic(logic, () => logic.actions.createSender()).toFinishAllListeners()++ const body = backend.requestsTo('integration_create').at(-1)?.body as { config: Record<string, unknown> }+ expect(body.config).toMatchObject(config)+ expect('reply_to' in body.config).toBe('reply_to' in config)+ })++ it('refuses an address that already has a sender', async () => {+ const logic = await mountWithExistingSender()++ logic.actions.setCustomDomainInput('[email protected]')+ logic.actions.useCustomDomain()++ expect(logic.values.existingSender?.config.email).toBe('[email protected]')+ })+})diff --git a/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.ts b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.tsnew file mode 100644index 000000000000..5089e0adebe5--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/emailDomainWizardLogic.ts@@ -0,0 +1,447 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import api, { ApiError } from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { Scene } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'+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 {+ integrationsCreate,+ integrationsDomainConnectCheckRetrieve,+} 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 { EventHost, InferredDomain, inferDomains } from './inferDomains'++export interface EmailDomainWizardLogicProps {+ logicKey: string+ onCreated: (sender: IntegrationConfigApi) => void+}++export interface CustomDomain {+ domain: string+ localPart: string | null+ problem: DomainProblem | null+}++export const DEFAULT_SEND_PREFIX: string = 'mail'+export const DEFAULT_LOCAL_PART: string = 'hello'+export const DEFAULT_BOUNCE_PREFIX: string = 'feedback'++const EVENT_HOSTS_QUERY = hogql`SELECT properties.$host AS host, count() AS events+ FROM events+ WHERE timestamp >= now() - INTERVAL 30 DAY+ AND properties.$host IS NOT NULL+ AND properties.$host != ''+ GROUP BY host+ ORDER BY events DESC+ LIMIT 5`++export type EmailSenderProvider = 'ses' | 'maildev'++const isEmailSenderOn = (integration: IntegrationType, domain: string | null): boolean =>+ integration.kind === 'email' && integration.config?.domain === domain++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainWizardLogicValues {+ integrations: IntegrationType[] | null // integrationsLogic+ preflight: PreflightStatus | null // preflightLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ currentTeamId: number | null // teamLogic+ user: UserType | null // userLogic+ advancedOpen: boolean+ bouncePrefix: string+ createdSender: IntegrationConfigApi | null+ createdSenderLoading: boolean+ customDomain: CustomDomain+ customDomainInput: string+ customPrefixOpen: boolean+ domainSender: IntegrationType | null+ eventHosts: EventHost[]+ eventHostsLoading: boolean+ existingSender: IntegrationType | null+ fromAddress: string | null+ inferredDomains: InferredDomain[]+ isLocalStack: boolean+ localPart: string+ localProvider: EmailSenderProvider+ replyTo: string+ selectedDomain: string | null+ selectedIsInferred: boolean+ sendPrefix: string+ senderName: string+ senderNameInput: string | null+ senderProvider: EmailSenderProvider+ sendingDomain: string | null+ submitError: string | null+ suggestedSenderName: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainWizardLogicActions {+ loadIntegrations: (_?: any) => any // integrationsLogic+ clearDomain: () => {+ value: true+ }+ createSender: () => any+ createSenderFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ createSenderSuccess: (+ createdSender: IntegrationConfigApi | null,+ payload?: any+ ) => {+ createdSender: IntegrationConfigApi | null+ payload?: any+ }+ loadEventHosts: () => any+ loadEventHostsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadEventHostsSuccess: (+ eventHosts: EventHost[],+ payload?: any+ ) => {+ eventHosts: EventHost[]+ payload?: any+ }+ selectDomain: (domain: string) => {+ domain: string+ }+ setAdvancedOpen: (open: boolean) => {+ open: boolean+ }+ setBouncePrefix: (prefix: string) => {+ prefix: string+ }+ setCustomDomainInput: (value: string) => {+ value: string+ }+ setCustomPrefixOpen: (open: boolean) => {+ open: boolean+ }+ setLocalPart: (localPart: string) => {+ localPart: string+ }+ setLocalProvider: (provider: EmailSenderProvider) => {+ provider: EmailSenderProvider+ }+ setReplyTo: (replyTo: string) => {+ replyTo: string+ }+ setSendPrefix: (prefix: string) => {+ prefix: string+ }+ setSenderNameInput: (name: string) => {+ name: string+ }+ setSubmitError: (error: string | null) => {+ error: string | null+ }+ useCustomDomain: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface emailDomainWizardLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ isLocalStack: (preflight: PreflightStatus | null) => boolean+ senderProvider: (isLocalStack: boolean, localProvider: EmailSenderProvider) => EmailSenderProvider+ inferredDomains: (+ currentTeam: TeamPublicType | TeamType | null,+ user: UserType | null,+ eventHosts: EventHost[]+ ) => InferredDomain[]+ customDomain: (customDomainInput: string) => CustomDomain+ selectedIsInferred: (selectedDomain: string | null, inferredDomains: InferredDomain[]) => boolean+ sendingDomain: (selectedDomain: string | null, sendPrefix: string) => string | null+ suggestedSenderName: (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+ existingSender: (integrations: IntegrationType[] | null, fromAddress: string | null) => IntegrationType | null+ }+}++export type emailDomainWizardLogicType = MakeLogicType<+ emailDomainWizardLogicValues,+ emailDomainWizardLogicActions,+ EmailDomainWizardLogicProps,+ emailDomainWizardLogicMeta+>++/** The domain step: picks or types the domain, shapes the first sender address and creates the sender. */+export const emailDomainWizardLogic = kea<emailDomainWizardLogicType>([+ path((key) => ['products', 'workflows', 'frontend', 'Channels', 'EmailDomain', 'emailDomainWizardLogic', key]),+ props({} as EmailDomainWizardLogicProps),+ key(({ logicKey }) => logicKey),+ connect(() => ({+ values: [+ teamLogic,+ ['currentTeam', 'currentTeamId'],+ userLogic,+ ['user'],+ integrationsLogic,+ ['integrations'],+ preflightLogic,+ ['preflight'],+ ],+ actions: [integrationsLogic, ['loadIntegrations']],+ })),+ actions({+ selectDomain: (domain: string) => ({ domain }),+ clearDomain: true,+ setCustomDomainInput: (value: string) => ({ value }),+ useCustomDomain: true,+ setSendPrefix: (prefix: string) => ({ prefix }),+ setCustomPrefixOpen: (open: boolean) => ({ open }),+ setBouncePrefix: (prefix: string) => ({ prefix }),+ setAdvancedOpen: (open: boolean) => ({ open }),+ setLocalPart: (localPart: string) => ({ localPart }),+ setSenderNameInput: (name: string) => ({ name }),+ setReplyTo: (replyTo: string) => ({ replyTo }),+ setSubmitError: (error: string | null) => ({ error }),+ setLocalProvider: (provider: EmailSenderProvider) => ({ provider }),+ }),+ loaders(({ values, actions }) => ({+ eventHosts: [+ [] as EventHost[],+ {+ loadEventHosts: async (): Promise<EventHost[]> => {+ try {+ const response = await api.queryHogQL(EVENT_HOSTS_QUERY, {+ scene: Scene.WorkflowsEmailDomain,+ productKey: ProductKey.WORKFLOWS,+ name: 'email_domain_event_hosts',+ })+ return (response.results ?? []).map(([host, count]) => ({+ host: String(host),+ count: Number(count),+ }))+ } catch {+ return []+ }+ },+ },+ ],+ createdSender: [+ null as IntegrationConfigApi | null,+ {+ createSender: async (): Promise<IntegrationConfigApi | null> => {+ const { selectedDomain, sendingDomain, currentTeamId, localPart, bouncePrefix, domainSender } =+ values+ if (!selectedDomain || !sendingDomain || !currentTeamId) {+ return null+ }+ actions.setSubmitError(null)+ try {+ return await integrationsCreate(String(currentTeamId), {+ kind: 'email',+ config: {+ email: `${localPart || DEFAULT_LOCAL_PART}@${sendingDomain}`,+ name: values.senderName.trim() || values.suggestedSenderName,+ ...(values.replyTo.trim() ? { reply_to: values.replyTo.trim() } : {}),+ provider: values.senderProvider,+ // The provider keeps one bounce subdomain per domain, so a new address reuses the existing one.+ mail_from_subdomain:+ domainSender?.config?.mail_from_subdomain || bouncePrefix || DEFAULT_BOUNCE_PREFIX,+ },+ })+ } catch (error) {+ const detail = error instanceof ApiError ? error.detail : null+ actions.setSubmitError(detail || 'Could not create the sender. Try again in a moment.')+ throw error+ }+ },+ },+ ],+ })),+ reducers({+ selectedDomain: [+ null as string | null,+ {+ selectDomain: (_, { domain }) => domain,+ clearDomain: () => null,+ },+ ],+ customDomainInput: [+ '',+ {+ setCustomDomainInput: (_, { value }) => value,+ selectDomain: () => '',+ },+ ],+ // null until the person types a name, so the suggestion keeps following the picked domain.+ senderNameInput: [+ null as string | null,+ {+ setSenderNameInput: (_, { name }) => name,+ },+ ],+ replyTo: [+ '',+ {+ setReplyTo: (_, { replyTo }) => replyTo,+ },+ ],+ localPart: [+ DEFAULT_LOCAL_PART,+ {+ setLocalPart: (_, { localPart }) => localPart,+ },+ ],+ sendPrefix: [+ DEFAULT_SEND_PREFIX,+ {+ setSendPrefix: (_, { prefix }) => asSubdomainLabel(prefix),+ },+ ],+ customPrefixOpen: [+ false,+ {+ setCustomPrefixOpen: (_, { open }) => open,+ },+ ],+ bouncePrefix: [+ DEFAULT_BOUNCE_PREFIX,+ {+ setBouncePrefix: (_, { prefix }) => asSubdomainLabel(prefix),+ },+ ],+ advancedOpen: [+ false,+ {+ setAdvancedOpen: (_, { open }) => open,+ },+ ],+ submitError: [+ null as string | null,+ {+ setSubmitError: (_, { error }) => error,+ selectDomain: () => null,+ clearDomain: () => null,+ },+ ],+ localProvider: [+ 'maildev' as EmailSenderProvider,+ {+ setLocalProvider: (_, { provider }) => provider,+ },+ ],+ }),+ selectors({+ isLocalStack: [(s) => [s.preflight], (preflight: PreflightStatus | null): boolean => !!preflight?.is_debug],+ // A local stack has no SES by default, so it starts on Maildev. Elsewhere Maildev does not exist.+ senderProvider: [+ (s) => [s.isLocalStack, s.localProvider],+ (isLocalStack: boolean, localProvider: EmailSenderProvider): EmailSenderProvider =>+ isLocalStack ? localProvider : 'ses',+ ],+ inferredDomains: [+ (s) => [s.currentTeam, s.user, s.eventHosts],+ (+ currentTeam: TeamPublicType | TeamType | null,+ user: UserType | null,+ eventHosts: EventHost[]+ ): InferredDomain[] => inferDomains(currentTeam?.app_urls ?? [], user?.email ?? null, eventHosts),+ ],+ customDomain: [+ (s) => [s.customDomainInput],+ (customDomainInput: string): CustomDomain => {+ const { domain, localPart } = normalizeDomainInput(customDomainInput)+ return { domain, localPart, problem: domainProblemOf(domain) }+ },+ ],+ selectedIsInferred: [+ (s) => [s.selectedDomain, s.inferredDomains],+ (selectedDomain: string | null, inferredDomains: InferredDomain[]): boolean =>+ inferredDomains.some((candidate) => candidate.domain === selectedDomain),+ ],+ sendingDomain: [+ (s) => [s.selectedDomain, s.sendPrefix],+ (selectedDomain: string | null, sendPrefix: string): string | null =>+ selectedDomain ? (sendPrefix ? `${sendPrefix}.${selectedDomain}` : selectedDomain) : null,+ ],+ suggestedSenderName: [+ (s) => [s.selectedDomain],+ (selectedDomain: string | null): string => (selectedDomain ? nameFromDomain(selectedDomain) : ''),+ ],+ senderName: [+ (s) => [s.senderNameInput, s.suggestedSenderName],+ (senderNameInput: string | null, suggestedSenderName: string): string =>+ senderNameInput ?? suggestedSenderName,+ ],+ fromAddress: [+ (s) => [s.sendingDomain, s.localPart],+ (sendingDomain: string | null, localPart: string): string | null =>+ sendingDomain ? `${localPart || DEFAULT_LOCAL_PART}@${sendingDomain}` : null,+ ],+ domainSender: [+ (s) => [s.integrations, s.sendingDomain],+ (integrations: IntegrationType[] | null, sendingDomain: string | null): IntegrationType | null =>+ integrations?.find((integration) => isEmailSenderOn(integration, sendingDomain)) ?? null,+ ],+ existingSender: [+ (s) => [s.integrations, s.fromAddress],+ (integrations: IntegrationType[] | null, fromAddress: string | null): IntegrationType | null =>+ integrations?.find(+ (integration) => integration.kind === 'email' && integration.config?.email === fromAddress+ ) ?? null,+ ],+ }),+ listeners(({ actions, values, props }) => ({+ useCustomDomain: () => {+ const { domain, localPart, problem } = values.customDomain+ if (!domain || problem) {+ return+ }+ if (localPart) {+ actions.setLocalPart(localPart)+ }+ actions.selectDomain(domain)+ // A full address on a domain that already sends is meant exactly as typed, without the recommended subdomain.+ if (localPart && values.integrations?.some((integration) => isEmailSenderOn(integration, domain))) {+ actions.setSendPrefix('')+ }+ },+ createSenderSuccess: async ({ createdSender }) => {+ if (!createdSender) {+ return+ }+ actions.loadIntegrations()+ props.onCreated(createdSender)+ const detection = await integrationsDomainConnectCheckRetrieve(String(values.currentTeamId), {+ domain: values.sendingDomain ?? '',+ include_email_setup: true,+ }).catch(() => null)+ // pinned: analytics event name+ posthog.capture('email domain submitted', {+ detected_provider: detection?.dns_host?.name ?? detection?.provider_name ?? null,+ has_domain_connect: detection?.supported ?? false,+ existing_senders: detection?.existing_email_tools ?? [],+ })+ },+ })),+ afterMount(({ actions }) => {+ actions.loadEventHosts()+ }),+])diff --git a/products/workflows/frontend/Channels/EmailDomain/inferDomains.ts b/products/workflows/frontend/Channels/EmailDomain/inferDomains.tsnew file mode 100644index 000000000000..f976d0146ebb--- /dev/null+++ b/products/workflows/frontend/Channels/EmailDomain/inferDomains.ts@@ -0,0 +1,75 @@+import { humanFriendlyNumber } from 'lib/utils/numbers'++import { hostnameOfUrl, isFreeMailboxDomain, isValidDomain, normalizeDomainInput, rootDomainOf } from './domainInput'++export interface EventHost {+ host: string+ count: number+}++export interface InferredDomain {+ domain: string+ reasons: string[]+ recommended: boolean+}++const isUsableHost = (domain: string | null): domain is string =>+ !!domain && isValidDomain(domain) && domain !== 'localhost'++class DomainCandidates {+ private reasons = new Map<string, string[]>()+ private rootWeight = new Map<string, number>()++ has(domain: string): boolean {+ return this.reasons.has(domain)+ }++ add(domain: string, reason: string, weight: number): void {+ this.reasons.set(domain, [...(this.reasons.get(domain) ?? []), reason])+ const root = rootDomainOf(domain)+ this.rootWeight.set(root, (this.rootWeight.get(root) ?? 0) + weight)+ }++ private recommendedDomain(): string | undefined {+ const topRoot = [...this.rootWeight.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]+ const sameRoot = [...this.reasons.keys()].filter((domain) => rootDomainOf(domain) === topRoot)+ return sameRoot.includes(topRoot) ? topRoot : sameRoot[0]+ }++ ranked(): InferredDomain[] {+ const recommended = this.recommendedDomain()+ return [...this.reasons.entries()]+ .map(([domain, reasons]) => ({ domain, reasons, recommended: domain === recommended }))+ .sort((a, b) => Number(b.recommended) - Number(a.recommended))+ }+}++/** Domains the project probably sends from: where its events come from, the login email and the project URLs. */+export const inferDomains = (+ appUrls: string[],+ userEmail: string | null,+ eventHosts: EventHost[]+): InferredDomain[] => {+ const candidates = new DomainCandidates()+ for (const { host, count } of eventHosts) {+ const domain = hostnameOfUrl(host)+ if (isUsableHost(domain)) {+ candidates.add(+ domain,+ `${humanFriendlyNumber(count)} events came from ${domain} in the last 30 days`,+ count+ )+ }+ }+ const emailDomain = userEmail ? normalizeDomainInput(userEmail).domain : ''+ if (isUsableHost(emailDomain) && !isFreeMailboxDomain(emailDomain)) {+ candidates.add(emailDomain, `Your login is ${userEmail}`, 1)+ }+ for (const url of appUrls) {+ const domain = hostnameOfUrl(url)+ if (isUsableHost(domain) && !candidates.has(domain)) {+ candidates.add(domain, 'One of your project URLs', 1)+ }+ }+ return candidates.ranked()+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.tsindex 0e8286a80f0f..af89e181a616 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts@@ -471,6 +471,7 @@ export const isScheduleTrigger = (action: HogFlowAction): boolean => {}export interface HogflowTestResult {+ emailSendResult?: { status: 'accepted' | 'skipped' | 'failed'; reason?: string }status: 'success' | 'error' | 'skipped'logs?: LogEntry[]nextActionId: string | nulldiff --git a/products/workflows/manifest.tsx b/products/workflows/manifest.tsxindex 4e4b6c24f0e7..23941e27bd29 100644--- a/products/workflows/manifest.tsx+++ b/products/workflows/manifest.tsx@@ -72,6 +72,7 @@ export const manifest: ProductManifest = {workflows: (tab?: WorkflowsSceneTab): string => `/workflows${tab ? `/${tab}` : ''}`,workflow: (id: string, tab: string): string => `/workflows/${id}/${tab}`,workflowNew: (): string => '/workflows/new/workflow',+ workflowsEmailDomain: (id: string | number): string => `/workflows/channels/email/${id}`,workflowsLibraryMessage: (id: string): string => `/workflows/library/messages/${id}`,workflowsLibraryTemplate: (id?: string): string => `/workflows/library/templates/${id}`,workflowsLibraryTemplateNew: (): string => '/workflows/library/templates/new',diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 4c4ecd98763d..aba2bc4c4061 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -2024,6 +2024,11 @@"params": [],"scope": "project"},+ "workflowsEmailDomain": {+ "template": "/workflows/channels/email/{id}",+ "params": ["id"],+ "scope": "project"+ },"workflowsLibraryMessage": {"template": "/workflows/library/messages/{id}","params": ["id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex 270b949c07a6..d6d3fd626d45 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/onboarding/simple\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/onboarding/simple\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/channels/email/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},