: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): capture sent emails as browsable assets (#65974)
Meikel Ratz2558916f5f31
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 9797070a30a1..5f47c4c8f629 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -516,6 +516,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TILE_SKELETONS: 'web-analytics-tile-skeletons', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics+ WORKFLOW_EMAIL_ASSETS_UI: 'workflow-email-assets-ui', // owner: #team-workflowsWORKFLOWS_BATCH_TRIGGERS: 'workflows-batch-triggers', // owner: #team-workflowsWORKFLOWS_ENGAGEMENT_EVENTS: 'workflows-engagement-events', // owner: #team-workflowsWORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsdiff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex c8fc5f9fca33..b596b0be3c1b 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -1089,6 +1089,7 @@ describe('CDP API', () => {],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],}))})diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex abe01cba716b..08d52e39d150 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -33,6 +33,7 @@ import { RecipientsManagerService } from './services/managers/recipients-managerimport { TeamWorkflowsConfigService } from './services/managers/team-workflows-config.service'import { EmailService } from './services/messaging/email.service'import { EmailTrackingCodeSigner } from './services/messaging/helpers/tracking-code'+import { MessageAssetsService } from './services/messaging/message-assets.service'import { RecipientPreferencesService } from './services/messaging/recipient-preferences.service'import { RecipientTokensService } from './services/messaging/recipient-tokens.service'import { HogFunctionMonitoringService } from './services/monitoring/hog-function-monitoring.service'@@ -100,6 +101,8 @@ export interface CdpCoreServices {/** Resolved outputs shared across every CDP service/consumer. */outputs: CdpOutputsemailService: EmailService+ /** Buffers rendered-email asset rows and bulk-flushes them at the batch boundary. */+ messageAssetsService: MessageAssetsService}export type CdpCoreServicesConfig = Pick<@@ -152,6 +155,9 @@ export type CdpCoreServicesConfig = Pick<| 'HOG_INVOCATION_RESULTS_TOPIC'| 'HOG_INVOCATION_RESULTS_PRODUCER'| 'HOG_INVOCATION_RESULTS_ENABLED'+ | 'MESSAGE_ASSETS_TOPIC'+ | 'MESSAGE_ASSETS_PRODUCER'+ | 'MESSAGE_ASSETS_CAPTURE_ENABLED'| 'CDP_PREFILTERED_EVENTS_TOPIC'| 'CDP_PREFILTERED_EVENTS_PRODUCER'| 'CDP_PRECALCULATED_PERSON_PROPERTIES_TOPIC'@@ -378,6 +384,8 @@ export function createCdpCoreServices(const hogInputsService = new HogInputsService(deps.integrationManager, config.ENCRYPTION_SALT_KEYS, config.SITE_URL)const trackingCodeSigner = new EmailTrackingCodeSigner(config.ENCRYPTION_SALT_KEYS, config.CDP_EMAIL_TRACKING_URL)const teamWorkflowsConfigService = new TeamWorkflowsConfigService(deps.postgres)+ const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, config)+ const messageAssetsService = new MessageAssetsService(outputs, config)const emailService = new EmailService({sesAccessKeyId: config.SES_ACCESS_KEY_ID,@@ -389,7 +397,8 @@ export function createCdpCoreServices(teamWorkflowsConfigService,config.ENCRYPTION_SALT_KEYS,config.SITE_URL,- trackingCodeSigner+ trackingCodeSigner,+ messageAssetsService)const recipientTokensService = new RecipientTokensService(config.ENCRYPTION_SALT_KEYS, config.SITE_URL)@@ -425,8 +434,6 @@ export function createCdpCoreServices(hogFlowDuplicateObserver)- const outputs = createCdpOutputsRegistry().build(deps.cdpProducerRegistry, config)-const hogFunctionMonitoringService = new HogFunctionMonitoringService(outputs)const hogInvocationResultsService = new HogInvocationResultsService(outputs, config)const warehouseWebhooksService = new WarehouseWebhooksService(outputs)@@ -435,7 +442,8 @@ export function createCdpCoreServices(hogFunctionMonitoringService,hogInvocationResultsService,warehouseWebhooksService,- capturedEventsService+ capturedEventsService,+ messageAssetsService)const nativeDestinationExecutorService = new NativeDestinationExecutorService(config)@@ -465,5 +473,6 @@ export function createCdpCoreServices(recipientTokensService,outputs,emailService,+ messageAssetsService,}}diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex d7e212316bb1..58a5e16ab81b 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -5,6 +5,7 @@ import {KAFKA_EVENTS_JSON,KAFKA_HOG_INVOCATION_RESULTS,KAFKA_LOG_ENTRIES,+ KAFKA_MESSAGE_ASSETS,KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,} from '~/common/config/kafka-topics'import { isDevEnv, isProdEnv, isTestEnv } from '~/common/utils/env-utils'@@ -104,6 +105,12 @@ export type CdpConfig = ClickhouseConfig & {HOG_INVOCATION_RESULTS_TOPIC: stringHOG_INVOCATION_RESULTS_PRODUCER: CdpProducerNameHOG_INVOCATION_RESULTS_ENABLED: boolean+ // Message assets: rendered emails snapshotted to object storage + a metadata+ // row in the message_assets ClickHouse table, surfaced in the workflow+ // "Assets" tab. Capture is a global ops kill-switch, not a per-team toggle.+ MESSAGE_ASSETS_TOPIC: string+ MESSAGE_ASSETS_PRODUCER: CdpProducerName+ MESSAGE_ASSETS_CAPTURE_ENABLED: booleanHOG_INVOCATION_RERUN_MAX_COUNT: number// How many rerun wrapper jobs the worker dequeues per cyclotron-v2 poll.// Kept small by default — each job runs a full ClickHouse query per page.@@ -227,6 +234,11 @@ export function getDefaultCdpConfig(): CdpConfig {// Off by default — flip to true once the table is migrated and we want to start writing.// Per-team rollout still happens at the call site.HOG_INVOCATION_RESULTS_ENABLED: isDevEnv() ? true : false,+ MESSAGE_ASSETS_TOPIC: KAFKA_MESSAGE_ASSETS,+ // Same cyclotron Warpstream cluster as hog_invocation_results — ClickHouse+ // consumes message_assets from the warpstream_cyclotron named collection.+ MESSAGE_ASSETS_PRODUCER: WARPSTREAM_CYCLOTRON_PRODUCER,+ MESSAGE_ASSETS_CAPTURE_ENABLED: isDevEnv() ? true : false,// Hard cap on rows a single rerun wrapper job will drain. Mirrors the// Django serializer's HOG_INVOCATION_RERUN_MAX_COUNT (same env var).HOG_INVOCATION_RERUN_MAX_COUNT: 10000,diff --git a/nodejs/src/cdp/outputs/registry.ts b/nodejs/src/cdp/outputs/registry.tsindex c3e628401cac..61d2f18b21c0 100644--- a/nodejs/src/cdp/outputs/registry.ts+++ b/nodejs/src/cdp/outputs/registry.ts@@ -1,4 +1,9 @@-import { APP_METRICS_OUTPUT, HOG_INVOCATION_RESULTS_OUTPUT, LOG_ENTRIES_OUTPUT } from '~/common/outputs'+import {+ APP_METRICS_OUTPUT,+ HOG_INVOCATION_RESULTS_OUTPUT,+ LOG_ENTRIES_OUTPUT,+ MESSAGE_ASSETS_OUTPUT,+} from '~/common/outputs'import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'import {@@ -33,6 +38,10 @@ export function createCdpOutputsRegistry() {topicKey: 'HOG_INVOCATION_RESULTS_TOPIC',producerKey: 'HOG_INVOCATION_RESULTS_PRODUCER',})+ .register(MESSAGE_ASSETS_OUTPUT, {+ topicKey: 'MESSAGE_ASSETS_TOPIC',+ producerKey: 'MESSAGE_ASSETS_PRODUCER',+ }).register(PREFILTERED_EVENTS_OUTPUT, {topicKey: 'CDP_PREFILTERED_EVENTS_TOPIC',producerKey: 'CDP_PREFILTERED_EVENTS_PRODUCER',diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex cfdc4c081ded..733abadb406a 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -107,6 +107,7 @@ describe('Hog Executor', () => {expect(result).toEqual({capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],invocation: {state: {globals: invocation.state.globals,diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex bd7adaa9e39d..bce47c813d20 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -388,6 +388,7 @@ describe('HogFunctionHandler', () => {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],})const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex fe8f10820f94..3d9f2722109a 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -51,6 +51,7 @@ export class HogFunctionHandler implements ActionHandler {...functionResult.warehouseWebhookPayloads,]result.metrics = [...result.metrics, ...functionResult.metrics]+ result.emailAssets = [...result.emailAssets, ...functionResult.emailAssets]if (!functionResult.finished) {// Set the state of the function result on the substate of the flow for the next execution@@ -125,6 +126,7 @@ export class HogFunctionHandler implements ActionHandler {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],}}diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 9ca4348ebd22..b00725bd4be8 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -203,6 +203,7 @@ describe('Hogflow Executor', () => {expect(result).toEqual({capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],invocation: {state: {actionStepCount: 1,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex c063ece5f1df..8eb05add61d3 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -13,6 +13,7 @@ import {HogFunctionInvocationGlobals,LogEntry,LogEntryLevel,+ MessageAssetRow,MinimalAppMetric,MinimalLogEntry,WarehouseWebhookPayload,@@ -176,6 +177,7 @@ export class HogFlowExecutorService {const logs: MinimalLogEntry[] = []const capturedPostHogEvents: HogFunctionCapturedEvent[] = []const warehouseWebhookPayloads: WarehouseWebhookPayload[] = []+ const emailAssets: MessageAssetRow[] = []const earlyExitResult = await this.shouldExitEarly(invocation, metrics, capturedPostHogEvents)if (earlyExitResult) {@@ -213,6 +215,7 @@ export class HogFlowExecutorService {metrics.push(...result.metrics)capturedPostHogEvents.push(...result.capturedPostHogEvents)warehouseWebhookPayloads.push(...result.warehouseWebhookPayloads)+ emailAssets.push(...result.emailAssets)if (this.shouldEndHogFlowExecution(result, logs)) {break@@ -223,6 +226,7 @@ export class HogFlowExecutorService {result.metrics = metricsresult.capturedPostHogEvents = capturedPostHogEventsresult.warehouseWebhookPayloads = warehouseWebhookPayloads+ result.emailAssets = emailAssetsreturn result}diff --git a/nodejs/src/cdp/services/invocation-results.service.test.ts b/nodejs/src/cdp/services/invocation-results.service.test.tsindex 53d327a16e32..0332f382eab7 100644--- a/nodejs/src/cdp/services/invocation-results.service.test.ts+++ b/nodejs/src/cdp/services/invocation-results.service.test.ts@@ -1,6 +1,7 @@import { CyclotronJobInvocationResult } from '../types'import { CapturedEventsService } from './captured-events/captured-events.service'import { InvocationResultsService } from './invocation-results.service'+import { MessageAssetsService } from './messaging/message-assets.service'import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'import { HogInvocationResultsService } from './monitoring/hog-invocation-results.service'import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service'@@ -10,6 +11,7 @@ describe('InvocationResultsService', () => {let invocationResultsRowsService: jest.Mocked<HogInvocationResultsService>let warehouseWebhooksService: jest.Mocked<WarehouseWebhooksService>let capturedEventsService: jest.Mocked<CapturedEventsService>+ let messageAssetsService: jest.Mocked<MessageAssetsService>let service: InvocationResultsServiceconst results = [@@ -38,11 +40,17 @@ describe('InvocationResultsService', () => {flush: jest.fn().mockResolvedValue(undefined),} as unknown as jest.Mocked<CapturedEventsService>+ messageAssetsService = {+ queueInvocationResults: jest.fn(),+ flush: jest.fn().mockResolvedValue(undefined),+ } as unknown as jest.Mocked<MessageAssetsService>+service = new InvocationResultsService(monitoringService,invocationResultsRowsService,warehouseWebhooksService,- capturedEventsService+ capturedEventsService,+ messageAssetsService)})@@ -58,6 +66,8 @@ describe('InvocationResultsService', () => {expect(warehouseWebhooksService.queueInvocationResults).toHaveBeenCalledWith(results)expect(capturedEventsService.queueInvocationResults).toHaveBeenCalledTimes(1)expect(capturedEventsService.queueInvocationResults).toHaveBeenCalledWith(results)+ expect(messageAssetsService.queueInvocationResults).toHaveBeenCalledTimes(1)+ expect(messageAssetsService.queueInvocationResults).toHaveBeenCalledWith(results)})it('awaits the captured-events service (which is async)', async () => {@@ -95,6 +105,7 @@ describe('InvocationResultsService', () => {expect(invocationResultsRowsService.flush).toHaveBeenCalledTimes(1)expect(warehouseWebhooksService.flush).toHaveBeenCalledTimes(1)expect(capturedEventsService.flush).toHaveBeenCalledTimes(1)+ expect(messageAssetsService.flush).toHaveBeenCalledTimes(1)})it('flushes all in parallel (all start before any finish)', async () => {diff --git a/nodejs/src/cdp/services/invocation-results.service.ts b/nodejs/src/cdp/services/invocation-results.service.tsindex 2592a945d1ed..0effda1d2631 100644--- a/nodejs/src/cdp/services/invocation-results.service.ts+++ b/nodejs/src/cdp/services/invocation-results.service.ts@@ -2,6 +2,7 @@ import { instrumentFn } from '~/common/tracing/tracing-utils'import { CyclotronJobInvocationResult } from '../types'import { CapturedEventsService } from './captured-events/captured-events.service'+import { MessageAssetsService } from './messaging/message-assets.service'import { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'import { HogInvocationResultsService } from './monitoring/hog-invocation-results.service'import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service'@@ -15,9 +16,11 @@ import { WarehouseWebhooksService } from './warehouse/warehouse-webhooks.service* (powers the new runs UI + rerun path)* - `WarehouseWebhooksService` — warehouse source webhook payloads* - `CapturedEventsService` — PostHog events emitted via posthog.capture()+ * - `MessageAssetsService` — rendered-email snapshots for the workflow+ * Assets tab** Callers interact with this one service instead of coordinating queue/flush- * calls across the four individually. `queueInvocationResultsAndFlush` is the+ * calls across the five individually. `queueInvocationResultsAndFlush` is the* common path — `queueInvocationResults` + `flush` are exposed for the rare* cases that split the two (e.g. source webhooks, which queue inline and flush* asynchronously after the HTTP response).@@ -27,7 +30,8 @@ export class InvocationResultsService {public readonly monitoringService: HogFunctionMonitoringService,public readonly invocationResultsRowsService: HogInvocationResultsService,public readonly warehouseWebhooksService: WarehouseWebhooksService,- public readonly capturedEventsService: CapturedEventsService+ public readonly capturedEventsService: CapturedEventsService,+ public readonly messageAssetsService: MessageAssetsService) {}queueInvocationResults(results: CyclotronJobInvocationResult[]): Promise<void> {@@ -35,6 +39,7 @@ export class InvocationResultsService {this.monitoringService.queueInvocationResults(results)this.invocationResultsRowsService.queueInvocationResults(results)this.warehouseWebhooksService.queueInvocationResults(results)+ this.messageAssetsService.queueInvocationResults(results)await this.capturedEventsService.queueInvocationResults(results)})}@@ -45,6 +50,7 @@ export class InvocationResultsService {this.invocationResultsRowsService.flush(),this.warehouseWebhooksService.flush(),this.capturedEventsService.flush(),+ this.messageAssetsService.flush(),])}diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.tsindex 867ecab28aa6..e3c30363cb8d 100644--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts@@ -52,6 +52,7 @@ describe('CyclotronJobQueuePostgresV2', () => {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],...overrides,}}diff --git a/nodejs/src/cdp/services/job-queue/shared.test.ts b/nodejs/src/cdp/services/job-queue/shared.test.tsindex b36a0b779824..1806437d5e6e 100644--- a/nodejs/src/cdp/services/job-queue/shared.test.ts+++ b/nodejs/src/cdp/services/job-queue/shared.test.ts@@ -266,6 +266,7 @@ describe('createInvocationSanitizer', () => {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],}const [sanitized] = sanitizer.sanitizeResults([result])diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex da229c5ca5d0..7bf0937571d3 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -4,7 +4,12 @@ import { SendMailOptions } from 'nodemailer'import { Counter } from 'prom-client'import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'-import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, IntegrationType } from '~/cdp/types'+import {+ CyclotronJobInvocationHogFunction,+ CyclotronJobInvocationResult,+ IntegrationType,+ MessageAssetRow,+} from '~/cdp/types'import { createAddLogFunction, logEntry } from '~/cdp/utils'import { createInvocationResult } from '~/cdp/utils/invocation-utils'@@ -15,6 +20,7 @@ import { addTrackingToEmail, resolveEmailEngagementDistinctId } from './email-trimport { mailDevTransport, mailDevWebUrl } from './helpers/maildev'import { maybeAddPreheaderToEmail } from './helpers/preheader'import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME } from './helpers/tracking-code'+import { MessageAssetsService } from './message-assets.service'import { RecipientTokensService } from './recipient-tokens.service'const sesThrottleResponsesTotal = new Counter({@@ -108,7 +114,8 @@ export class EmailService {private teamWorkflowsConfigService: TeamWorkflowsConfigService,encryptionSaltKeys: string,siteUrl: string,- private trackingCodeSigner: EmailTrackingCodeSigner+ private trackingCodeSigner: EmailTrackingCodeSigner,+ private messageAssetsService?: MessageAssetsService) {this.sesV2Client = this.sesConfig.sesRegion? new SESv2Client({@@ -143,6 +150,7 @@ export class EmailService {let success: boolean = falselet throttled: boolean = false+ let assetRow: MessageAssetRow | null = nulltry {// Wrong-team references deliberately read as not-found so an ID's existence on another team can't be probed@@ -171,7 +179,15 @@ export class EmailService {throw new Error('Email delivery mode not supported')}- addLog('info', `Email sent to ${params.to.email}`)+ // Emit the `[Email:…]` token in the success log only when an asset row+ // will actually be captured; `renderWorkflowLogMessage` renders it as the+ // "View email" chip, so suppressing it for skipped captures keeps the chip+ // from 404-ing on click.+ if (!isTest && this.messageAssetsService) {+ assetRow = this.messageAssetsService.buildRowForEmail(invocation, params)+ }+ const viewEmailToken = assetRow ? ` [Email:${invocation.id}:${invocation.state.actionId ?? ''}]` : ''+ addLog('info', `Email sent to ${params.to.email}${viewEmailToken}`)success = true} catch (error) {if (error instanceof SESThrottleError) {@@ -213,6 +229,10 @@ export class EmailService {metric_name: success ? 'email_sent' : 'email_failed',count: 1,})++ if (success && assetRow) {+ result.emailAssets.push(assetRow)+ }}const distinctId = resolveEmailEngagementDistinctId(invocation)diff --git a/nodejs/src/cdp/services/messaging/message-assets.service.test.ts b/nodejs/src/cdp/services/messaging/message-assets.service.test.tsnew file mode 100644index 000000000000..b718408bdada--- /dev/null+++ b/nodejs/src/cdp/services/messaging/message-assets.service.test.ts@@ -0,0 +1,201 @@+import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { parseJSON } from '~/common/utils/json-parse'++import { createExampleInvocation } from '../../_tests/fixtures'+import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, MessageAssetRow } from '../../types'+import { MessageAssetsService } from './message-assets.service'++const CONFIG = {+ MESSAGE_ASSETS_CAPTURE_ENABLED: true,+}++const buildOutputsMock = (): jest.Mocked<IngestionOutputs<'message_assets'>> =>+ ({ produce: jest.fn().mockResolvedValue(undefined) }) as unknown as jest.Mocked<IngestionOutputs<'message_assets'>>++const emailParams = (+ overrides: Partial<CyclotronInvocationQueueParametersEmailType> = {}+): CyclotronInvocationQueueParametersEmailType =>+ ({+ type: 'email',+ to: { email: '[email protected]' },+ from: { integrationId: 1 },+ subject: 'Welcome aboard',+ text: 'plain text',+ html: '<p>Hello</p>',+ ...overrides,+ }) as CyclotronInvocationQueueParametersEmailType++const invocationWithAction = (id: string, teamId = 7): CyclotronJobInvocationHogFunction => {+ const invocation = createExampleInvocation({ id, team_id: teamId })+ invocation.state.actionId = 'email-step'+ return invocation+}++const resultWith = (assets: MessageAssetRow[]): CyclotronJobInvocationResult =>+ ({+ emailAssets: assets,+ }) as unknown as CyclotronJobInvocationResult++const producedRowAt = (outputs: jest.Mocked<IngestionOutputs<'message_assets'>>, index: number): MessageAssetRow => {+ const call = outputs.produce.mock.calls[index]+ const value = (call[1] as { value: Buffer }).value+ return parseJSON(value.toString('utf8')) as MessageAssetRow+}++describe('MessageAssetsService', () => {+ let outputs: jest.Mocked<IngestionOutputs<'message_assets'>>+ let service: MessageAssetsService++ beforeEach(() => {+ jest.clearAllMocks()+ outputs = buildOutputsMock()+ service = new MessageAssetsService(outputs, CONFIG)+ })++ describe('buildRowForEmail', () => {+ it('returns a populated row for an in-workflow email step', () => {+ const invocation = invocationWithAction('flow-1', 7)++ const row = service.buildRowForEmail(invocation, emailParams())++ expect(row).not.toBeNull()+ expect(row!.team_id).toBe(7)+ expect(row!.function_id).toBe('flow-1')+ expect(row!.invocation_id).toBe(invocation.id)+ expect(row!.action_id).toBe('email-step')+ expect(row!.function_kind).toBe('hog_flow')+ expect(row!.kind).toBe('email')+ expect(row!.status).toBe('sent')+ expect(row!.recipient).toBe('[email protected]')+ expect(row!.subject).toBe('Welcome aboard')+ expect(row!.html).toBe('<p>Hello</p>')+ })++ it('returns null for a standalone email send (no action id — unretrievable from the Assets API)', () => {+ const invocation = createExampleInvocation({ id: 'fn-1', team_id: 3 })++ const row = service.buildRowForEmail(invocation, emailParams())++ expect(row).toBeNull()+ })++ it('returns null when capture is globally disabled', () => {+ service = new MessageAssetsService(outputs, { MESSAGE_ASSETS_CAPTURE_ENABLED: false })++ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams())++ expect(row).toBeNull()+ })++ it('wraps the text body in a <pre> when the email has no HTML, so plain-text sends still surface in the Assets tab', () => {+ const row = service.buildRowForEmail(+ invocationWithAction('flow-1'),+ emailParams({ html: '', text: 'hi <bob> & co' })+ )++ expect(row).not.toBeNull()+ // The raw `<`/`>`/`&` from the text body are HTML-escaped so they can't+ // break the surrounding <pre> markup or inject anything.+ expect(row!.html).toContain('<pre')+ expect(row!.html).toContain('hi <bob> & co')+ expect(row!.html).not.toContain('hi <bob>')+ })++ it('returns null when both HTML and text bodies are empty', () => {+ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams({ html: '', text: '' }))++ expect(row).toBeNull()+ })++ it('substitutes a placeholder body when the rendered HTML exceeds the Kafka message-size budget', () => {+ // 5 MiB of 'a' — comfortably over the 4 MiB threshold. If we let this through the+ // producer would blow up mid-flush, take the whole batch's Promise.all with it, and+ // the "View email" chip would 404 for every recipient in that batch.+ const oversized = 'a'.repeat(5 * 1024 * 1024)++ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams({ html: oversized }))++ expect(row).not.toBeNull()+ expect(row!.html).not.toContain('a'.repeat(1024))+ expect(row!.html).toContain('Email too large to capture')+ // Everything else on the row must be preserved so the tab shows the correct+ // recipient/subject/timing even when the body itself was too big.+ expect(row!.recipient).toBe('[email protected]')+ expect(row!.subject).toBe('Welcome aboard')+ })+ })++ describe('queueInvocationResults + flush', () => {+ it('does not produce anything until flush is called', () => {+ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams())!++ service.queueInvocationResults([resultWith([row])])++ expect(outputs.produce).not.toHaveBeenCalled()+ })++ it('bulk-produces every queued row on flush', async () => {+ const row1 = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams())!+ const row2 = service.buildRowForEmail(invocationWithAction('flow-2'), emailParams({ subject: 'Second' }))!++ service.queueInvocationResults([resultWith([row1]), resultWith([row2])])+ await service.flush()++ expect(outputs.produce).toHaveBeenCalledTimes(2)+ const subjects = [producedRowAt(outputs, 0).subject, producedRowAt(outputs, 1).subject].sort()+ expect(subjects).toEqual(['Second', 'Welcome aboard'])+ })++ it('partitions each row by invocation_id so retries collapse via the ReplacingMergeTree', async () => {+ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams())!++ service.queueInvocationResults([resultWith([row])])+ await service.flush()++ const key = (outputs.produce.mock.calls[0][1] as { key: Buffer }).key+ expect(key.toString('utf8')).toBe(row.invocation_id)+ })++ it('clears the buffer after a successful flush so a second flush is a no-op', async () => {+ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams())!+ service.queueInvocationResults([resultWith([row])])++ await service.flush()+ expect(outputs.produce).toHaveBeenCalledTimes(1)++ await service.flush()+ expect(outputs.produce).toHaveBeenCalledTimes(1)+ })++ it('skips results that carry an empty emailAssets array', async () => {+ service.queueInvocationResults([resultWith([]), resultWith([])])+ await service.flush()+ expect(outputs.produce).not.toHaveBeenCalled()+ })++ it('swallows broker failure so the CDP consumer keeps making progress', async () => {+ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams())!+ outputs.produce.mockRejectedValueOnce(new Error('kafka down'))++ service.queueInvocationResults([resultWith([row])])++ // No throw — the surrounding consumer batch must not be aborted just+ // because a few asset rows didn't make it to Kafka.+ await expect(service.flush()).resolves.toBeUndefined()+ })++ it('drops the buffer on flush failure so the next flush does not retry the failed rows', async () => {+ const row = service.buildRowForEmail(invocationWithAction('flow-1'), emailParams())!+ outputs.produce.mockRejectedValueOnce(new Error('kafka down'))++ service.queueInvocationResults([resultWith([row])])+ await service.flush()++ // Second flush with no new queuing is a no-op — failed rows are gone,+ // we don't get a second produce attempt against the broker.+ await service.flush()+ expect(outputs.produce).toHaveBeenCalledTimes(1)+ })+ })+})diff --git a/nodejs/src/cdp/services/messaging/message-assets.service.ts b/nodejs/src/cdp/services/messaging/message-assets.service.tsnew file mode 100644index 000000000000..7ee55c336b49--- /dev/null+++ b/nodejs/src/cdp/services/messaging/message-assets.service.ts@@ -0,0 +1,193 @@+import { Counter, Gauge } from 'prom-client'++import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'+import { MESSAGE_ASSETS_OUTPUT, MessageAssetsOutput } from '~/common/outputs'+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { safeClickhouseString } from '~/common/utils/db/utils'+import { logger } from '~/common/utils/logger'+import { captureException } from '~/common/utils/posthog'++import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult, MessageAssetRow } from '../../types'+import { resolveEmailEngagementDistinctId } from './email-tracking.service'++export type { MessageAssetRow } from '../../types'++const counterMessageAssetsCaptured = new Counter({+ name: 'cdp_message_assets_captured',+ help: 'Sent-email assets produced to the message_assets Kafka topic (ClickHouse-backed).',+ labelNames: ['kind'],+})++const counterMessageAssetsFailed = new Counter({+ name: 'cdp_message_assets_failed',+ help: 'Asset captures that failed at Kafka produce and were dropped. Best-effort like logs/metrics — watch this counter to size the gap between sends and Assets-tab rows.',+})++const counterMessageAssetsTruncated = new Counter({+ name: 'cdp_message_assets_truncated',+ help: 'Sent-email assets whose rendered body exceeded the Kafka message-size budget. A placeholder is captured so the "View email" chip still works, but the original body is not viewable.',+})++const messageAssetsPendingRows = new Gauge({+ name: 'cdp_message_assets_pending_rows',+ help: 'Message-asset rows queued in-memory waiting for the next flush. Resets to 0 after each flush.',+})++export interface MessageAssetsServiceConfig {+ MESSAGE_ASSETS_CAPTURE_ENABLED: boolean+}++const microsecondsSinceEpoch = (): string => {+ const ms = BigInt(Date.now())+ const subMs = BigInt(Math.floor((performance.now() % 1) * 1000))+ return (ms * 1000n + subMs).toString()+}++const isoMicroseconds = (date: Date): string => {+ // ClickHouse DateTime64(6) accepts 'YYYY-MM-DD HH:MM:SS.ffffff'.+ return date.toISOString().replace('T', ' ').replace('Z', '000')+}++const HTML_ESCAPE: Record<string, string> = {+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+}++// Escape user-typed `<`/`>`/`&` so a `<pre>`-wrapped plain-text body can't break+// surrounding markup or inject scripts.+const wrapPlainTextAsHtml = (text: string): string => {+ const escaped = text.replace(/[&<>"']/g, (c) => HTML_ESCAPE[c])+ return `<!doctype html><meta charset="utf-8"><pre style="white-space:pre-wrap;font-family:ui-monospace,Menlo,monospace;margin:0;padding:1rem">${escaped}</pre>`+}++// The CDP Kafka producer caps message size at 6 MB in prod (1 MB elsewhere) but SES accepts+// up to 10 MB. In the gap the send succeeds and the log-line token is already emitted, so an+// oversized row that dropped at flush time would make the "View email" chip 404. Worse: since+// flush is a single Promise.all, one oversized row blows up the entire batch and every+// unrelated row in it gets swallowed too. Substitute a small placeholder body when we cross+// the safe budget — the row still lands, the chip works, and the batch is unaffected.+const MAX_HTML_BYTES = 4 * 1024 * 1024++const oversizedPlaceholderHtml = (bytes: number): string => {+ const mb = (bytes / 1024 / 1024).toFixed(1)+ return `<!doctype html><meta charset="utf-8"><div style="padding:1rem;font-family:ui-sans-serif,system-ui,sans-serif;color:#555;max-width:640px;margin:2rem auto"><h3 style="margin:0 0 0.5rem">Email too large to capture</h3><p style="margin:0">The rendered email was ${mb} MB, which exceeds the ${MAX_HTML_BYTES / 1024 / 1024} MB capture limit. The send itself succeeded — this placeholder is stored so the “View email” link works, but the original body is not viewable here.</p></div>`+}++/**+ * Buffers rendered-email snapshots and flushes them as a single bulk Kafka+ * produce at the batch boundary — one round-trip per partition for the whole+ * batch instead of one per email.+ *+ * Flush is best-effort: on broker failure the batch is dropped and the+ * `cdp_message_assets_failed` counter is incremented. We prefer losing a+ * handful of Assets-tab rows during a Kafka incident over stalling the+ * whole CDP consumer (which would also re-trigger email sends on replay).+ */+export class MessageAssetsService {+ private queuedRows: MessageAssetRow[] = []++ constructor(+ private outputs: IngestionOutputs<MessageAssetsOutput>,+ private config: MessageAssetsServiceConfig+ ) {}++ // Returns null when capture is disabled, no content (neither html nor+ // text), or no action id — the Assets API filters by `function_kind='hog_flow'`+ // and keys off the action node id, so a row without one is unreachable.+ buildRowForEmail(+ invocation: CyclotronJobInvocationHogFunction,+ params: CyclotronInvocationQueueParametersEmailType+ ): MessageAssetRow | null {+ if (!this.config.MESSAGE_ASSETS_CAPTURE_ENABLED) {+ return null+ }+ if (!invocation.state.actionId) {+ return null+ }+ const body = params.html || (params.text ? wrapPlainTextAsHtml(params.text) : '')+ if (!body) {+ return null+ }+ const bodyBytes = Buffer.byteLength(body, 'utf8')+ let html = body+ if (bodyBytes > MAX_HTML_BYTES) {+ counterMessageAssetsTruncated.inc()+ html = oversizedPlaceholderHtml(bodyBytes)+ }+ return {+ team_id: invocation.teamId,+ function_kind: 'hog_flow',+ function_id: invocation.functionId,+ parent_run_id: invocation.parentRunId ?? '',+ invocation_id: invocation.id,+ action_id: invocation.state.actionId ?? '',+ kind: 'email',+ distinct_id: resolveEmailEngagementDistinctId(invocation) ?? '',+ person_id: invocation.state.globals.person?.id ?? '',+ recipient: params.to.email,+ subject: params.subject,+ status: 'sent',+ sent_at: isoMicroseconds(new Date()),+ version: microsecondsSinceEpoch(),+ is_deleted: 0,+ html,+ }+ }++ queueInvocationResults(results: CyclotronJobInvocationResult[]): void {+ for (const result of results) {+ if (!result.emailAssets || result.emailAssets.length === 0) {+ continue+ }+ for (const row of result.emailAssets) {+ this.queuedRows.push(row)+ }+ }+ messageAssetsPendingRows.set(this.queuedRows.length)+ }++ async flush(): Promise<void> {+ if (this.queuedRows.length === 0) {+ return+ }+ const rows = this.queuedRows+ this.queuedRows = []+ messageAssetsPendingRows.set(0)++ try {+ await Promise.all(+ rows.map((row) =>+ this.outputs.produce(MESSAGE_ASSETS_OUTPUT, {+ // Partition by invocation_id so retried produces for the+ // same asset collapse cleanly via the ReplacingMergeTree.+ key: Buffer.from(row.invocation_id),+ value: Buffer.from(safeClickhouseString(JSON.stringify(row))),+ })+ )+ )+ counterMessageAssetsCaptured.inc({ kind: 'email' }, rows.length)+ } catch (error) {+ counterMessageAssetsFailed.inc(rows.length)+ logger.error('⚠️', `failed to flush message assets — dropping batch: ${error}`, {+ error: String(error),+ dropped: rows.length,+ // Row identifiers so the dropped sends can be reconstructed from logs+ // (the Assets tab won't have them and the rows can't be backfilled+ // automatically — the in-memory buffer is cleared above).+ rows: rows.map((r) => ({+ team_id: r.team_id,+ function_id: r.function_id,+ invocation_id: r.invocation_id,+ action_id: r.action_id,+ person_id: r.person_id,+ recipient: r.recipient,+ sent_at: r.sent_at,+ })),+ })+ captureException(error)+ }+ }+}diff --git a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.tsindex 90363545db42..8480a8ae668c 100644--- a/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts+++ b/nodejs/src/cdp/services/monitoring/hog-invocation-results.service.test.ts@@ -48,6 +48,7 @@ describe('HogInvocationResultsService', () => {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],} as any,])@@ -195,6 +196,7 @@ describe('HogInvocationResultsService', () => {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],} as any,])await service.flush()@@ -216,6 +218,7 @@ describe('HogInvocationResultsService', () => {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],} as any,])await service.flush()@@ -238,6 +241,7 @@ describe('HogInvocationResultsService', () => {metrics: [],capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],} as any,])await service.flush()diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 885a9c45e43f..02381dd89920 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -292,6 +292,7 @@ export type CyclotronJobInvocationResult<T extends CyclotronJobInvocation = Cyclmetrics: MinimalAppMetric[]capturedPostHogEvents: HogFunctionCapturedEvent[]warehouseWebhookPayloads: WarehouseWebhookPayload[]+ emailAssets: MessageAssetRow[]execResult?: unknown}@@ -522,6 +523,25 @@ export type WarehouseWebhookPayload = {payload: Record<string, any>}+export type MessageAssetRow = {+ team_id: number+ function_kind: 'hog_flow' | 'hog_function'+ function_id: string+ parent_run_id: string+ invocation_id: string+ action_id: string+ kind: 'email'+ distinct_id: string+ person_id: string+ recipient: string+ subject: string+ status: 'sent'+ sent_at: string // ISO microsecond DateTime64+ version: string // microsecond-precision UInt64, serialized as string to dodge JS's 53-bit cap+ is_deleted: 0 | 1+ html: string+}+export type Response = {status: numberdata: anydiff --git a/nodejs/src/cdp/utils/invocation-utils.ts b/nodejs/src/cdp/utils/invocation-utils.tsindex 96ff3d8a3835..0be28a99e3a2 100644--- a/nodejs/src/cdp/utils/invocation-utils.ts+++ b/nodejs/src/cdp/utils/invocation-utils.ts@@ -67,7 +67,14 @@ export function createInvocationResult<T extends CyclotronJobInvocation>(> = {},resultParams: Pick<Partial<CyclotronJobInvocationResult>,- 'finished' | 'capturedPostHogEvents' | 'warehouseWebhookPayloads' | 'logs' | 'metrics' | 'error' | 'execResult'+ | 'finished'+ | 'capturedPostHogEvents'+ | 'warehouseWebhookPayloads'+ | 'emailAssets'+ | 'logs'+ | 'metrics'+ | 'error'+ | 'execResult'> = {}): CyclotronJobInvocationResult<T> {return {@@ -75,6 +82,7 @@ export function createInvocationResult<T extends CyclotronJobInvocation>(finished: true,capturedPostHogEvents: [],warehouseWebhookPayloads: [],+ emailAssets: [],logs: [],metrics: [],...resultParams,diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 9f8e50e5e39f..42d49e26453b 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -23,7 +23,7 @@ import express from 'ultimate-express'import { HogFlow } from '~/cdp/schema/hogflow'import { setupExpressApp } from '~/common/api/router'-import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '~/common/config/kafka-topics'+import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES, KAFKA_MESSAGE_ASSETS } from '~/common/config/kafka-topics'import { KafkaProducerWrapper } from '~/common/kafka/producer'import { InternalPersonWithDistinctId, PersonReadRepository } from '~/common/persons/repositories/person-repository'import { deleteKeysWithPrefix } from '~/common/redis/_tests/redis'@@ -1609,6 +1609,12 @@ describe('Workflows E2E (email queue)', () => {hub = await createHub()hub.CDP_CYCLOTRON_BATCH_DELAY_MS = 50+ // Default in non-dev envs is `false`, so the message-assets capture path stays+ // dormant in CI. The asset-capture tests below assert the row lands in the+ // dedicated Kafka topic, so we flip the kill-switch on for this describe block.+ // Set before `createCdpConsumerDeps` / worker construction so the value is+ // captured in `MessageAssetsService` at instantiation.+ hub.MESSAGE_ASSETS_CAPTURE_ENABLED = truekafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)mockProducerObserver = new KafkaProducerObserver(kafkaProducer)@@ -2671,6 +2677,173 @@ describe('Workflows E2E (email queue)', () => {const pool = parseFloat(bucket?.pool ?? '0')expect(pool).toBeGreaterThanOrEqual(capacity - 1)})++ // ---- Message-assets bulk flush at the batch boundary ----+ //+ // Email assets used to be produced one-at-a-time via a fire-and-forget Kafka call+ // from `email.service.ts → MessageAssetsService.captureSentEmail`. We've moved that+ // to a buffer-then-flush pattern that drains `result.emailAssets` at the batch+ // boundary and bulk-produces, gated on broker ack before the consumer commits+ // offsets. These tests pin the end-to-end behavior: one workflow → one asset row in+ // the `message_assets` Kafka topic with the right metadata, and a single batch with+ // multiple emails produces all rows. The kill-switch is flipped on in this block's+ // `beforeEach` so the asset Kafka topic actually receives writes.+ describe('message_assets bulk capture', () => {+ const buildEmailWorkflow = (subject: string) =>+ new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withStatus('active')+ .withExitCondition('exit_only_at_end')+ .withWorkflow({+ actions: {+ trigger: {+ type: 'trigger',+ config: { type: 'event', filters: HOG_FILTERS_EXAMPLES.no_filters.filters ?? {} },+ },+ email_1: {+ type: 'function_email',+ config: {+ template_id: 'template-workflows-e2e-email',+ inputs: {+ email: {+ value: {+ to: { email: '[email protected]', name: 'Recipient' },+ from: { integrationId: 1, email: '[email protected]' },+ subject,+ text: 'plain text body',+ html: `<p>${subject}</p>`,+ },+ },+ },+ },+ },+ exit: { type: 'exit', config: {} },+ },+ edges: [+ { from: 'trigger', to: 'email_1', type: 'continue' },+ { from: 'email_1', to: 'exit', type: 'continue' },+ ],+ })+ .build()++ const assetMessages = (): { key: string; value: any }[] =>+ mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_MESSAGE_ASSETS) as any++ it('produces one message_assets row per workflow email with the rendered HTML and metadata', async () => {+ const hogFlow = buildEmailWorkflow('Asset bulk-capture single')+ await insertHogFlow(hub.postgres, hogFlow)++ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])+ await backgroundTask++ // The asset row only lands once the email worker's batch flushes — wait for+ // the workflow to reach a terminal state, then assert against the topic.+ await waitForExpect(async () => {+ const jobs = await queryCyclotronJobs()+ const terminal = jobs.filter(+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'+ )+ expect(terminal.length).toBeGreaterThanOrEqual(1)+ }, 15000)++ await waitForExpect(() => {+ const rows = assetMessages()+ expect(rows).toHaveLength(1)++ const row = rows[0].value as Record<string, any>+ expect(row.team_id).toBe(team.id)+ expect(row.function_kind).toBe('hog_flow')+ expect(row.kind).toBe('email')+ expect(row.status).toBe('sent')+ expect(row.action_id).toBe('email_1')+ expect(row.recipient).toBe('[email protected]')+ expect(row.subject).toBe('Asset bulk-capture single')+ expect(row.html).toBe('<p>Asset bulk-capture single</p>')+ // Partition key must match invocation_id so retries collapse via the+ // destination ReplacingMergeTree(version).+ expect(rows[0].key).toBe(row.invocation_id)+ }, 15000)+ })++ it('bulk-captures every asset when multiple workflow runs share a batch', async () => {+ // Use distinct subjects so we can assert on row content regardless of the+ // partition-level ordering the Kafka producer chooses.+ const hogFlow = buildEmailWorkflow('Bulk asset capture')+ await insertHogFlow(hub.postgres, hogFlow)++ // Three globals dispatched in one `processBatch` call — they go through the+ // events consumer together. Each fires its own workflow run, each emits one+ // asset; the bulk-flush is what we're exercising.+ const { backgroundTask } = await eventsConsumer.processBatch([+ createGlobals({ uuid: 'aaaaaaaa-0000-0000-0000-000000000001' as any }),+ createGlobals({ uuid: 'aaaaaaaa-0000-0000-0000-000000000002' as any }),+ createGlobals({ uuid: 'aaaaaaaa-0000-0000-0000-000000000003' as any }),+ ])+ await backgroundTask++ await waitForExpect(async () => {+ const jobs = await queryCyclotronJobs()+ const terminal = jobs.filter(+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'+ )+ expect(terminal.length).toBeGreaterThanOrEqual(3)+ }, 20000)++ await waitForExpect(() => {+ const rows = assetMessages()+ expect(rows.length).toBeGreaterThanOrEqual(3)++ // Every produced row must carry distinct invocation_id values (one per+ // workflow run) — otherwise the buffer is dropping or aliasing rows.+ const invocationIds = new Set(rows.map((r) => (r.value as any).invocation_id))+ expect(invocationIds.size).toBeGreaterThanOrEqual(3)++ // Subject and HTML are constant across the three runs (same flow), so we+ // just sanity-check that every row carries the expected shape.+ for (const row of rows) {+ const value = row.value as Record<string, any>+ expect(value.subject).toBe('Bulk asset capture')+ expect(value.html).toBe('<p>Bulk asset capture</p>')+ expect(value.kind).toBe('email')+ expect(value.status).toBe('sent')+ expect(row.key).toBe(value.invocation_id)+ }+ }, 20000)+ })++ it('emits no message_assets rows when the kill-switch is disabled', async () => {+ // Restart the email worker with capture disabled — `MessageAssetsService` reads+ // the config at construction time, so we have to recreate the deps + worker.+ await emailWorker.stop()+ hub.MESSAGE_ASSETS_CAPTURE_ENABLED = false+ deps = createCdpConsumerDeps(hub, kafkaProducer)+ const restartedQueue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)+ emailWorker = new CdpCyclotronWorkerEmail(hub, deps, restartedQueue)+ await emailWorker.start()++ mockProducerObserver.resetKafkaProducer()++ const hogFlow = buildEmailWorkflow('Capture disabled')+ await insertHogFlow(hub.postgres, hogFlow)++ const { backgroundTask } = await eventsConsumer.processBatch([createGlobals()])+ await backgroundTask++ await waitForExpect(async () => {+ const jobs = await queryCyclotronJobs()+ const terminal = jobs.filter(+ (j: any) => j.status === 'completed' || j.status === 'failed' || j.status === 'canceled'+ )+ expect(terminal.length).toBeGreaterThanOrEqual(1)+ }, 15000)++ // Give the asset producer a chance to run — if anything is going to fire it+ // happens within the same flush window. Re-check after a short delay so we+ // don't accept a false negative from races.+ await new Promise((resolve) => setTimeout(resolve, 500))+ expect(assetMessages()).toHaveLength(0)+ })+ })})/**diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.tsindex ff6ef33c44ce..84c7bf888594 100644--- a/nodejs/src/common/config/kafka-topics.ts+++ b/nodejs/src/common/config/kafka-topics.ts@@ -52,6 +52,9 @@ export const KAFKA_LOG_ENTRIES = `${prefix}log_entries${suffix}`// per-invocation result rows for hog functions and hog flowsexport const KAFKA_HOG_INVOCATION_RESULTS = `${prefix}clickhouse_hog_invocation_results${suffix}`+// metadata rows for sent message assets (rendered emails stored in object storage)+export const KAFKA_MESSAGE_ASSETS = `${prefix}clickhouse_message_assets${suffix}`+// CDP topicsexport const KAFKA_CDP_FUNCTION_OVERFLOW = `${prefix}cdp_function_overflow${suffix}`export const KAFKA_CDP_INTERNAL_EVENTS = `${prefix}cdp_internal_events${suffix}`diff --git a/nodejs/src/common/outputs/index.ts b/nodejs/src/common/outputs/index.tsindex 0ad6dd6b0681..e6e46d30421d 100644--- a/nodejs/src/common/outputs/index.ts+++ b/nodejs/src/common/outputs/index.ts@@ -34,3 +34,6 @@ export type TophogOutput = typeof TOPHOG_OUTPUTexport const HOG_INVOCATION_RESULTS_OUTPUT = 'hog_invocation_results' as constexport type HogInvocationResultsOutput = typeof HOG_INVOCATION_RESULTS_OUTPUT++export const MESSAGE_ASSETS_OUTPUT = 'message_assets' as const+export type MessageAssetsOutput = typeof MESSAGE_ASSETS_OUTPUTdiff --git a/nodejs/tests/helpers/kafka.ts b/nodejs/tests/helpers/kafka.tsindex aff56022530d..bc7a9b9afd63 100644--- a/nodejs/tests/helpers/kafka.ts+++ b/nodejs/tests/helpers/kafka.ts@@ -23,6 +23,7 @@ import {KAFKA_GROUPS,KAFKA_INGESTION_WARNINGS,KAFKA_LOG_ENTRIES,+ KAFKA_MESSAGE_ASSETS,KAFKA_PERFORMANCE_EVENTS,KAFKA_PERSON,KAFKA_PERSON_DISTINCT_ID,@@ -94,6 +95,7 @@ export const TEST_KAFKA_TOPICS = [KAFKA_CLICKHOUSE_SESSION_RECORDING_EVENTS,KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,KAFKA_LOG_ENTRIES,+ KAFKA_MESSAGE_ASSETS,KAFKA_EVENTS_RECENT_JSON,KAFKA_ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES,KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES,diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex c24a06f061b0..25ffeebedd3b 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -7,6 +7,7 @@ from typing import Optional, castfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import transactionfrom django.db.models import QuerySet+from django.http import HttpResponsefrom django.utils import timezonefrom django.utils.dateparse import parse_datetime@@ -14,6 +15,7 @@ import structlogimport posthoganalyticsfrom django_filters import BaseInFilter, CharFilter, FilterSetfrom django_filters.rest_framework import DjangoFilterBackend+from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_fieldfrom rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.decorators import action@@ -69,6 +71,14 @@ from products.notifications.backend.facade.api import publish_resource_editedfrom products.workflows.backend.api.graph_operations import apply_graph_operationsfrom products.workflows.backend.api.graph_validation import validate_graphfrom products.workflows.backend.api.hog_flow_batch_job import HogFlowBatchJobSerializer+from products.workflows.backend.api.message_assets import (+ MessageAssetContentRequestSerializer,+ MessageAssetSerializer,+ MessageAssetsRequestSerializer,+ fetch_message_asset_html,+ fetch_message_assets,+ workflow_email_assets_ui_enabled,+)from products.workflows.backend.models.hog_flow.hog_flow import (BILLABLE_ACTION_TYPES,PERSON_DEPENDENT_ACTION_TYPES,@@ -1180,6 +1190,8 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie"metrics_totals","metrics_global","user_blast_radius",+ "assets",+ "asset_content",]scope_object_write_actions = ["create",@@ -1218,6 +1230,10 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie# able to enumerate who a workflow ran for.if self.action in ("invocation_results", "invocation_result"):return ["hog_flow:read", "person:read"]+ # Assets expose recipient/distinct_id/person_id and the message bytes — require+ # person:read so a hog_flow:read-only token can't enumerate who got emailed.+ if self.action in ("assets", "asset_content"):+ return ["hog_flow:read", "person:read"]# A test invocation resolves the event's $groups into real group properties server-side, so a# hog_flow:write-only token could branch on group_0.properties and read the returned logs/variables# as a group-property oracle. Require group:read on top. The web builder uses session auth, so@@ -1581,6 +1597,82 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vieraise exceptions.NotFound("Invocation not found.")return Response(HogInvocationResultDetailSerializer(data).data)+ @extend_schema(+ operation_id="hog_flows_assets_retrieve",+ parameters=[MessageAssetsRequestSerializer],+ responses=MessageAssetSerializer(many=True),+ )+ @action(detail=True, methods=["GET"], pagination_class=None, filter_backends=[])+ def assets(self, request: Request, *args, **kwargs):+ obj = self.get_object()+ if not workflow_email_assets_ui_enabled(self.team, request.user):+ raise exceptions.NotFound()+ tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)++ param_serializer = MessageAssetsRequestSerializer(data=request.query_params)+ param_serializer.is_valid(raise_exception=True)+ params = param_serializer.validated_data++ after_date, _, _ = relative_date_parse_with_delta_mapping(params["after"], self.team.timezone_info)+ before_date = None+ if params.get("before"):+ before_date, _, _ = relative_date_parse_with_delta_mapping(params["before"], self.team.timezone_info)++ data = fetch_message_assets(+ team_id=self.team_id,+ function_kind=self.function_kind,+ function_id=str(obj.id),+ limit=params["limit"],+ offset=params["offset"],+ parent_run_id=params.get("parent_run_id"),+ action_id=params.get("action_id"),+ invocation_id=params.get("invocation_id"),+ distinct_id=params.get("distinct_id"),+ search=params.get("search"),+ after=after_date,+ before=before_date,+ )+ return Response(MessageAssetSerializer(data, many=True).data)++ @extend_schema(+ operation_id="hog_flows_asset_content_retrieve",+ parameters=[MessageAssetContentRequestSerializer],+ responses={(200, "text/html"): OpenApiTypes.STR},+ )+ @action(detail=True, methods=["GET"], url_path="assets/content", pagination_class=None, filter_backends=[])+ def asset_content(self, request: Request, *args, **kwargs):+ # Ownership-check the HogFlow first so other teams' assets can't be probed.+ obj = self.get_object()+ if not workflow_email_assets_ui_enabled(self.team, request.user):+ raise exceptions.NotFound()++ param_serializer = MessageAssetContentRequestSerializer(data=request.query_params)+ param_serializer.is_valid(raise_exception=True)+ params = param_serializer.validated_data++ tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)++ html = fetch_message_asset_html(+ team_id=self.team_id,+ function_kind=self.function_kind,+ function_id=str(obj.id),+ invocation_id=params["invocation_id"],+ action_id=params.get("action_id", ""),+ )+ if html is None:+ raise exceptions.NotFound("Asset content is no longer available.")+ response = HttpResponse(html, content_type="text/html; charset=utf-8")+ # Enforce sandboxing at the response layer so direct navigation to the asset URL+ # (bypassing the iframe with `sandbox=""` on the frontend) still can't execute+ # scripts or make same-origin requests as the viewer. `sandbox` (no allow-list)+ # is the most restrictive CSP mode; the other directives are defense-in-depth.+ response["Content-Security-Policy"] = (+ "sandbox; default-src 'none'; img-src https: data:; style-src 'unsafe-inline'"+ )+ response["X-Content-Type-Options"] = "nosniff"+ response["Referrer-Policy"] = "no-referrer"+ return response+@extend_schema(operation_id="hog_flows_metrics_global_retrieve",parameters=[WorkflowGlobalStatsRequestSerializer],diff --git a/products/workflows/backend/api/message_assets.py b/products/workflows/backend/api/message_assets.pynew file mode 100644index 000000000000..5a1b154743f4--- /dev/null+++ b/products/workflows/backend/api/message_assets.py@@ -0,0 +1,278 @@+import dataclasses+from datetime import UTC, datetime+from typing import TYPE_CHECKING, Any, Optional, cast++import posthoganalytics+from rest_framework import serializers++from posthog.clickhouse.client.execute import sync_execute++if TYPE_CHECKING:+ from django.contrib.auth.models import AbstractBaseUser, AnonymousUser++ from posthog.models import Team+++WORKFLOW_EMAIL_ASSETS_UI_FLAG = "workflow-email-assets-ui"+++def workflow_email_assets_ui_enabled(team: "Team", user: "AbstractBaseUser | AnonymousUser") -> bool:+ # DRF's `request.user` is User | AnonymousUser. Permissions reject anonymous before+ # we get here, but typing it broadly lets callers pass `request.user` without casting.+ distinct_id = getattr(user, "distinct_id", None)+ if not distinct_id:+ return False+ return bool(+ posthoganalytics.feature_enabled(+ WORKFLOW_EMAIL_ASSETS_UI_FLAG,+ str(distinct_id),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+++# `latest_` prefix on the argMax aliases prevents collision with the raw column+# names in any outer WHERE — ClickHouse resolves the bare name to the aggregate+# and errors otherwise.+_COLLAPSED_AGGREGATES = """+ invocation_id,+ action_id,+ argMax(parent_run_id, version) AS latest_parent_run_id,+ argMax(kind, version) AS latest_kind,+ argMax(distinct_id, version) AS latest_distinct_id,+ argMax(person_id, version) AS latest_person_id,+ argMax(recipient, version) AS latest_recipient,+ argMax(subject, version) AS latest_subject,+ argMax(status, version) AS latest_status,+ argMax(sent_at, version) AS latest_sent_at,+ argMax(is_deleted, version) AS latest_is_deleted+""".strip()++_OUTER_COLUMNS = """+ invocation_id,+ action_id,+ latest_parent_run_id,+ latest_kind,+ latest_distinct_id,+ latest_person_id,+ latest_recipient,+ latest_subject,+ latest_status,+ latest_sent_at+""".strip()++[email protected](frozen=True)+class MessageAsset:+ invocation_id: str+ action_id: str+ parent_run_id: str+ kind: str+ distinct_id: str+ person_id: str+ recipient: str+ subject: str+ status: str+ sent_at: datetime+++class MessageAssetSerializer(serializers.Serializer):+ invocation_id = serializers.CharField(help_text="The workflow run this email was sent in.")+ action_id = serializers.CharField(+ help_text="The email step (action node) within the workflow that sent this email."+ )+ parent_run_id = serializers.CharField(+ help_text="The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs."+ )+ kind = serializers.CharField(help_text="Asset kind. Currently always 'email'.")+ distinct_id = serializers.CharField(help_text="The recipient's distinct_id.")+ person_id = serializers.CharField(help_text="The recipient's person UUID, if resolved.")+ recipient = serializers.CharField(help_text="The recipient email address.")+ subject = serializers.CharField(help_text="The email subject line.")+ status = serializers.CharField(help_text="Delivery status at capture time. Currently always 'sent'.")+ sent_at = serializers.DateTimeField(help_text="When the email was sent.")+++class MessageAssetsRequestSerializer(serializers.Serializer):+ parent_run_id = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="Only return assets for this batch run (HogFlowBatchJob id). Pass an empty string to return only "+ "event-triggered (non-batch) assets; omit to return all.",+ )+ action_id = serializers.CharField(+ required=False,+ help_text="Only return assets sent by this email step (action node id) — used to drill in from a step's metric.",+ )+ invocation_id = serializers.CharField(+ required=False,+ help_text="Only return the asset for this specific workflow run — used to deep-link from a single log entry "+ "to the email it sent. Returns 0 rows when the send had no captured asset (text-only, kill-switch off, "+ "or standalone email).",+ )+ distinct_id = serializers.CharField(+ required=False,+ help_text="Only return assets sent to this distinct_id.",+ )+ search = serializers.CharField(+ required=False,+ help_text="Case-insensitive substring match on recipient email or subject.",+ )+ after = serializers.CharField(+ required=False,+ default="-30d",+ help_text="Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. "+ "Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.",+ )+ before = serializers.CharField(+ required=False,+ help_text="End of the time range, matched on sent time. Same format as 'after'. Defaults to now.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=50,+ max_value=500,+ min_value=1,+ help_text="Maximum number of assets to return (1-500, default 50).",+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text="Number of assets to skip, for pagination.",+ )+++class MessageAssetContentRequestSerializer(serializers.Serializer):+ invocation_id = serializers.CharField(help_text="The workflow run the email was sent in.")+ action_id = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="The email step (action node) that sent the email. Defaults to empty for standalone email sends.",+ )+++def _build_asset(row: tuple) -> MessageAsset:+ return MessageAsset(+ invocation_id=row[0],+ action_id=row[1],+ parent_run_id=row[2],+ kind=row[3],+ distinct_id=row[4],+ person_id=row[5],+ recipient=row[6],+ subject=row[7],+ status=row[8],+ sent_at=row[9],+ )+++def fetch_message_assets(+ team_id: int,+ function_kind: str,+ function_id: str,+ limit: int,+ offset: int = 0,+ parent_run_id: Optional[str] = None,+ action_id: Optional[str] = None,+ invocation_id: Optional[str] = None,+ distinct_id: Optional[str] = None,+ search: Optional[str] = None,+ after: Optional[datetime] = None,+ before: Optional[datetime] = None,+) -> list[MessageAsset]:+ where = [+ "team_id = %(team_id)s",+ "function_kind = %(function_kind)s",+ "function_id = %(function_id)s",+ ]+ kwargs: dict[str, Any] = {+ "team_id": team_id,+ "function_kind": function_kind,+ "function_id": function_id,+ "limit": limit,+ "offset": offset,+ }++ # Filter stable-across-versions fields pre-aggregation to hit the bloom-filter+ # skip indexes. `is_deleted` flips per version, so it's filtered post-collapse.+ if parent_run_id is not None:+ where.append("parent_run_id = %(parent_run_id)s")+ kwargs["parent_run_id"] = parent_run_id+ if action_id:+ where.append("action_id = %(action_id)s")+ kwargs["action_id"] = action_id+ if invocation_id:+ where.append("invocation_id = %(invocation_id)s")+ kwargs["invocation_id"] = invocation_id+ if distinct_id:+ where.append("distinct_id = %(distinct_id)s")+ kwargs["distinct_id"] = distinct_id+ if search:+ where.append("(recipient ILIKE %(search)s OR subject ILIKE %(search)s)")+ kwargs["search"] = f"%{search}%"+ if after:+ where.append("sent_at >= toDateTime64(%(after)s, 6)")+ kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if before:+ where.append("sent_at <= toDateTime64(%(before)s, 6)")+ kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")++ query = f"""+ SELECT {_OUTER_COLUMNS}+ FROM (+ SELECT {_COLLAPSED_AGGREGATES}+ FROM message_assets+ WHERE {" AND ".join(where)}+ GROUP BY invocation_id, action_id+ )+ WHERE latest_is_deleted = 0+ ORDER BY latest_sent_at DESC+ LIMIT %(limit)s OFFSET %(offset)s+ """++ results = cast(list, sync_execute(query, kwargs))+ return [_build_asset(row) for row in results]+++def fetch_message_asset_html(+ team_id: int,+ function_kind: str,+ function_id: str,+ invocation_id: str,+ action_id: str,+) -> Optional[str]:+ kwargs = {+ "team_id": team_id,+ "function_kind": function_kind,+ "function_id": function_id,+ "invocation_id": invocation_id,+ "action_id": action_id,+ }+ # GROUP BY so a no-match query returns zero rows — a bare aggregate would+ # return one default-valued row and the action would serve HTTP 200 + empty.+ query = """+ SELECT latest_html+ FROM (+ SELECT+ argMax(html, version) AS latest_html,+ argMax(is_deleted, version) AS latest_is_deleted+ FROM message_assets+ WHERE team_id = %(team_id)s+ AND function_kind = %(function_kind)s+ AND function_id = %(function_id)s+ AND invocation_id = %(invocation_id)s+ AND action_id = %(action_id)s+ GROUP BY invocation_id, action_id+ )+ WHERE latest_is_deleted = 0+ """++ results = cast(list, sync_execute(query, kwargs))+ if not results:+ return None+ return results[0][0]diff --git a/products/workflows/backend/api/test/test_message_assets.py b/products/workflows/backend/api/test/test_message_assets.pynew file mode 100644index 000000000000..49d11c3c6b15--- /dev/null+++ b/products/workflows/backend/api/test/test_message_assets.py@@ -0,0 +1,234 @@+from datetime import UTC, datetime, timedelta+from typing import Any, Optional++from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++from posthog.clickhouse.client.execute import sync_execute+from posthog.models.message_assets.sql import INSERT_MESSAGE_ASSET_SQL+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+++def create_message_asset(+ team_id: int,+ function_id: str,+ invocation_id: str,+ *,+ action_id: str = "email-step",+ function_kind: str = "hog_flow",+ parent_run_id: str = "",+ kind: str = "email",+ distinct_id: str = "user-1",+ person_id: str = "person-1",+ recipient: str = "[email protected]",+ subject: str = "Welcome",+ html: str = "<html><body>Hello</body></html>",+ asset_status: str = "sent",+ sent_at: Optional[datetime] = None,+ version: int = 1,+ is_deleted: int = 0,+) -> None:+ sent = sent_at or datetime.now(tz=UTC)+ params: dict[str, Any] = {+ "team_id": team_id,+ "function_kind": function_kind,+ "function_id": function_id,+ "parent_run_id": parent_run_id,+ "invocation_id": invocation_id,+ "action_id": action_id,+ "kind": kind,+ "distinct_id": distinct_id,+ "person_id": person_id,+ "recipient": recipient,+ "subject": subject,+ "html": html,+ "status": asset_status,+ "sent_at": sent,+ "version": version,+ "is_deleted": is_deleted,+ }+ sync_execute(INSERT_MESSAGE_ASSET_SQL, params)+++class TestMessageAssets(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.hog_flow = HogFlow.objects.create(team=self.team, name="Test Flow")+ ff_patcher = patch(+ "products.workflows.backend.api.message_assets.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self.feature_enabled_mock = ff_patcher.start()+ self.addCleanup(ff_patcher.stop)++ def _base(self) -> str:+ return f"/api/projects/{self.team.id}/hog_flows/{self.hog_flow.id}"++ def _list(self, params=None):+ return self.client.get(f"{self._base()}/assets/", params)++ def _seed(self, invocation_id: str, **kwargs):+ create_message_asset(+ team_id=self.team.pk, function_id=str(self.hog_flow.pk), invocation_id=invocation_id, **kwargs+ )++ def test_returns_empty_when_no_assets(self):+ res = self._list()+ assert res.status_code == status.HTTP_200_OK+ assert res.json() == []++ def test_listing_returns_metadata_without_html(self):+ self._seed("inv-1", recipient="[email protected]", subject="Hi Bob", distinct_id="user-7")+ results = self._list().json()+ assert len(results) == 1+ row = results[0]+ assert row["invocation_id"] == "inv-1"+ assert row["recipient"] == "[email protected]"+ assert row["subject"] == "Hi Bob"+ assert row["distinct_id"] == "user-7"+ assert "html" not in row++ def test_collapses_to_latest_version(self):+ self._seed("inv-1", subject="first", version=1)+ self._seed("inv-1", subject="second", version=2)+ results = self._list().json()+ assert len(results) == 1+ assert results[0]["subject"] == "second"++ def test_excludes_deleted_assets(self):+ self._seed("inv-1", version=1)+ self._seed("inv-1", version=2, is_deleted=1)+ assert self._list().json() == []++ def test_filters_by_parent_run_id(self):+ self._seed("inv-batch", parent_run_id="batch-1")+ self._seed("inv-continuous", parent_run_id="")+ batch = self._list({"parent_run_id": "batch-1"}).json()+ assert {r["invocation_id"] for r in batch} == {"inv-batch"}+ continuous = self._list({"parent_run_id": ""}).json()+ assert {r["invocation_id"] for r in continuous} == {"inv-continuous"}++ def test_filters_by_action_id(self):+ self._seed("inv-1", action_id="step-a")+ self._seed("inv-2", action_id="step-b")+ results = self._list({"action_id": "step-a"}).json()+ assert {r["invocation_id"] for r in results} == {"inv-1"}++ def test_filters_by_invocation_id(self):+ self._seed("inv-1")+ self._seed("inv-2")+ results = self._list({"invocation_id": "inv-1"}).json()+ assert {r["invocation_id"] for r in results} == {"inv-1"}++ def test_invocation_id_filter_returns_empty_when_no_asset_was_captured(self):+ self._seed("inv-1")+ results = self._list({"invocation_id": "inv-nonexistent"}).json()+ assert results == []++ def test_filters_by_distinct_id(self):+ self._seed("inv-1", distinct_id="user-a")+ self._seed("inv-2", distinct_id="user-b")+ results = self._list({"distinct_id": "user-a"}).json()+ assert {r["invocation_id"] for r in results} == {"inv-1"}++ @parameterized.expand(+ [+ ("bob", {"inv-1"}),+ ("Newsletter", {"inv-2"}),+ ("example.com", {"inv-1", "inv-2"}),+ ]+ )+ def test_search_matches_recipient_or_subject(self, term: str, expected_ids: set):+ self._seed("inv-1", recipient="[email protected]", subject="Welcome")+ self._seed("inv-2", recipient="[email protected]", subject="Newsletter")+ results = self._list({"search": term}).json()+ assert {r["invocation_id"] for r in results} == expected_ids++ def test_isolated_from_other_flow_and_function_kind(self):+ self._seed("inv-mine")+ create_message_asset(+ team_id=self.team.pk,+ function_id=str(self.hog_flow.pk),+ invocation_id="inv-fn",+ function_kind="hog_function",+ )+ create_message_asset(team_id=self.team.pk, function_id="other-flow", invocation_id="inv-other")+ results = self._list().json()+ assert {r["invocation_id"] for r in results} == {"inv-mine"}++ def test_default_window_excludes_rows_older_than_30d(self):+ now = datetime.now(tz=UTC)+ self._seed("recent", sent_at=now - timedelta(days=2))+ self._seed("old", sent_at=now - timedelta(days=45))+ results = self._list().json()+ assert {r["invocation_id"] for r in results} == {"recent"}++ def test_respects_limit_and_offset(self):+ for i in range(5):+ self._seed(f"inv-{i}")+ assert len(self._list({"limit": 2}).json()) == 2+ assert len(self._list({"limit": 2, "offset": 4}).json()) == 1++ def test_content_returns_html_bytes_inline(self):+ self._seed("inv-1", action_id="step-a", html="<html><body>Hello Bob</body></html>")+ res = self.client.get(f"{self._base()}/assets/content/?invocation_id=inv-1&action_id=step-a")+ assert res.status_code == status.HTTP_200_OK+ assert res["Content-Type"] == "text/html; charset=utf-8"+ assert res.content == b"<html><body>Hello Bob</body></html>"+ # Sandbox at the response layer so direct navigation to this URL still can't+ # run scripts as the viewer — the iframe's `sandbox=""` alone doesn't protect+ # someone who opens the asset URL in a new tab. Regressing this reintroduces+ # stored-XSS in captured email HTML.+ assert "sandbox" in res["Content-Security-Policy"]+ assert res["X-Content-Type-Options"] == "nosniff"++ def test_content_returns_latest_version_html(self):+ self._seed("inv-1", action_id="step-a", html="<p>old</p>", version=1)+ self._seed("inv-1", action_id="step-a", html="<p>new</p>", version=2)+ res = self.client.get(f"{self._base()}/assets/content/?invocation_id=inv-1&action_id=step-a")+ assert res.status_code == status.HTTP_200_OK+ assert res.content == b"<p>new</p>"++ def test_content_404_for_unknown_asset(self):+ res = self.client.get(f"{self._base()}/assets/content/?invocation_id=nope&action_id=step-a")+ assert res.status_code == status.HTTP_404_NOT_FOUND++ def test_content_404_for_deleted_asset(self):+ self._seed("inv-1", action_id="step-a", version=1)+ self._seed("inv-1", action_id="step-a", version=2, is_deleted=1)+ res = self.client.get(f"{self._base()}/assets/content/?invocation_id=inv-1&action_id=step-a")+ assert res.status_code == status.HTTP_404_NOT_FOUND++ @parameterized.expand(+ [+ "assets/",+ "assets/content/?invocation_id=inv-1&action_id=step-a",+ ]+ )+ def test_personal_api_key_requires_person_read_scope(self, path: str):+ self._seed("inv-1", action_id="step-a")+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="hog_flow only", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:read"]+ )+ res = self.client.get(f"{self._base()}/{path}", headers={"authorization": f"Bearer {key}"})+ assert res.status_code == 403, res.json()+ assert "person:read" in res.json().get("detail", "")++ @parameterized.expand(+ [+ "assets/",+ "assets/content/?invocation_id=inv-1&action_id=step-a",+ ]+ )+ def test_404_when_ui_flag_disabled(self, path: str):+ self._seed("inv-1", action_id="step-a")+ self.feature_enabled_mock.return_value = False+ res = self.client.get(f"{self._base()}/{path}")+ assert res.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsxindex e4b5e534a4d9..22be591b6810 100644--- a/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx+++ b/products/workflows/frontend/Workflows/EmailMetricsSummary.tsx@@ -15,7 +15,6 @@ export function EmailMetricsSummary({onMetricClick,}: {logicKey: string- /** Invoked when a drill-down-able metric tile (e.g. Bounced) is clicked. */onMetricClick?: (metricKey: EmailMetric) => void}): JSX.Element {const { appMetricsTrendsLoading, appMetricsTrends, getSingleTrendSeries } = useValues(appMetricsLogic({ logicKey }))diff --git a/products/workflows/frontend/Workflows/WorkflowAssets.tsx b/products/workflows/frontend/Workflows/WorkflowAssets.tsxnew file mode 100644index 000000000000..a8c17ac6eff9--- /dev/null+++ b/products/workflows/frontend/Workflows/WorkflowAssets.tsx@@ -0,0 +1,214 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'+import { useEffect } from 'react'++import { HedgehogGreek } from '@posthog/brand/hoggies'+import { LemonCollapse, LemonInput, LemonModal, LemonTable, ProfilePicture, Spinner } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'+import { HogFlowBatchJob } from './hogflows/types'+import { MessageAsset } from './messageAssetsApi'+import { workflowAssetsLogic } from './workflowAssetsLogic'+import { WorkflowLogicProps, workflowLogic } from './workflowLogic'++function EmptyAssets(): JSX.Element {+ return (+ <div className="flex flex-col bg-surface-primary rounded px-4 py-8 items-center text-center mx-auto">+ <HedgehogGreek width="100" height="100" className="mb-4" />+ <h2 className="text-xl leading-tight">No emails sent yet</h2>+ <p className="text-sm text-balance text-tertiary">+ Every email this workflow sends is captured here, so you can see exactly what each person received.+ </p>+ </div>+ )+}++function AssetViewerModal({ workflowId, parentRunId, actionId, invocationId }: AssetsTableProps): JSX.Element {+ const logic = workflowAssetsLogic({ id: workflowId, parentRunId, actionId, invocationId })+ const { selectedAsset, contentUrl } = useValues(logic)+ const { closeAsset } = useActions(logic)++ return (+ <LemonModal+ isOpen={!!selectedAsset}+ onClose={closeAsset}+ width={720}+ title={selectedAsset?.subject || 'Email'}+ description={selectedAsset ? `Sent to ${selectedAsset.recipient}` : undefined}+ >+ {selectedAsset ? (+ // sandbox="" disables scripts so the captured email HTML can't run anything.+ <iframe+ title="Rendered email"+ sandbox=""+ src={contentUrl(selectedAsset)}+ className="w-full h-[60vh] bg-white rounded border"+ />+ ) : null}+ </LemonModal>+ )+}++interface AssetsTableProps {+ workflowId: string+ parentRunId?: string+ actionId?: string+ invocationId?: string+}++function AssetsTable({ workflowId, parentRunId, actionId, invocationId }: AssetsTableProps): JSX.Element {+ const logic = workflowAssetsLogic({ id: workflowId, parentRunId, actionId, invocationId })+ const { assets, assetsLoading, search, selectedAsset } = useValues(logic)+ const { setSearch, openAsset } = useActions(logic)++ // Auto-open the asset when arriving via ?assetInvocation=<id>. Skip if one is+ // already open (user dismissed it) or the search box has focus.+ useEffect(() => {+ if (invocationId && assets.length === 1 && !selectedAsset && !search) {+ openAsset(assets[0])+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [invocationId, assets.length])+ const { workflow } = useValues(workflowLogic)++ const stepNameById = new Map(workflow.actions.map((action) => [action.id, action.name]))++ return (+ <div className="flex flex-col gap-2">+ <LemonInput+ type="search"+ placeholder="Search by recipient or subject"+ value={search}+ onChange={setSearch}+ className="max-w-100"+ />+ <LemonTable+ loading={assetsLoading}+ dataSource={assets}+ onRow={(asset: MessageAsset) => ({+ onClick: () => openAsset(asset),+ className: 'cursor-pointer',+ })}+ emptyState={<EmptyAssets />}+ columns={[+ {+ title: 'Recipient',+ key: 'recipient',+ render: (_, asset: MessageAsset) => (+ <div className="flex items-center gap-2">+ <ProfilePicture user={{ email: asset.recipient }} size="sm" />+ <span>{asset.recipient}</span>+ </div>+ ),+ },+ {+ title: 'Subject',+ dataIndex: 'subject',+ key: 'subject',+ },+ {+ title: 'Step',+ key: 'action_id',+ render: (_, asset: MessageAsset) => stepNameById.get(asset.action_id) ?? '—',+ },+ {+ title: 'Sent',+ key: 'sent_at',+ render: (_, asset: MessageAsset) => <TZLabel time={asset.sent_at} />,+ },+ ]}+ />+ <AssetViewerModal+ workflowId={workflowId}+ parentRunId={parentRunId}+ actionId={actionId}+ invocationId={invocationId}+ />+ </div>+ )+}++function BatchJobAssetsHeader({ job }: { job: HogFlowBatchJob }): JSX.Element {+ return (+ <div className="flex gap-2 w-full justify-between">+ <strong>{job.id}</strong>+ <div className="flex items-center gap-2">+ <TZLabel title="Created at" time={job.created_at} />+ {job.created_by ? (+ <ProfilePicture user={{ email: job.created_by.email || '' }} showName size="sm" />+ ) : (+ <span className="text-muted text-sm">Scheduled run</span>+ )}+ </div>+ </div>+ )+}++function WorkflowBatchAssets({+ workflowId,+ actionId,+ invocationId,+}: {+ workflowId: string+ actionId?: string+ invocationId?: string+}): JSX.Element {+ const { jobs, batchWorkflowJobsLoading } = useValues(batchWorkflowJobsLogic({ id: workflowId }))++ if (batchWorkflowJobsLoading) {+ return (+ <div className="flex justify-center">+ <Spinner size="medium" />+ </div>+ )+ }++ if (!jobs.length) {+ return <EmptyAssets />+ }++ return (+ <LemonCollapse+ panels={jobs.map((job) => ({+ key: job.id,+ header: <BatchJobAssetsHeader job={job} />,+ content: (+ <AssetsTable+ workflowId={workflowId}+ parentRunId={job.id}+ actionId={actionId}+ invocationId={invocationId}+ />+ ),+ }))}+ />+ )+}++export function WorkflowAssets(props: WorkflowLogicProps): JSX.Element {+ const { workflow, workflowLoading } = useValues(workflowLogic(props))+ const { searchParams } = useValues(router)+ const workflowId = props.id ?? 'new'+ const actionId = (searchParams.assetAction as string | undefined) || undefined+ const invocationId = (searchParams.assetInvocation as string | undefined) || undefined++ if (workflowLoading) {+ return (+ <div className="flex justify-center">+ <Spinner size="medium" />+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-2" data-attr="workflow-assets">+ {workflow?.trigger?.type === 'batch' ? (+ <WorkflowBatchAssets workflowId={workflowId} actionId={actionId} invocationId={invocationId} />+ ) : (+ <AssetsTable workflowId={workflowId} actionId={actionId} invocationId={invocationId} />+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx b/products/workflows/frontend/Workflows/WorkflowMetrics.tsxindex 0705d47ea4f5..370691e25704 100644--- a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx+++ b/products/workflows/frontend/Workflows/WorkflowMetrics.tsx@@ -3,7 +3,8 @@ import { router } from 'kea-router'import { useMemo } from 'react'import { HedgehogGreek } from '@posthog/brand/hoggies'-import { LemonCollapse, LemonSelect, ProfilePicture, Spinner } from '@posthog/lemon-ui'+import { IconLetter } from '@posthog/icons'+import { LemonButton, LemonCollapse, LemonSelect, ProfilePicture, Spinner } from '@posthog/lemon-ui'import { getColorVar } from 'lib/colors'import { AppMetricsFilters } from 'lib/components/AppMetrics/AppMetricsFilters'@@ -113,7 +114,7 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {return (<div className="flex flex-col gap-2" data-attr="workflow-metrics"><div className="flex flex-row gap-2 flex-wrap justify-between">- <div>+ <div className="flex flex-row gap-2 items-center flex-wrap"><LemonSelectsize="small"options={workflowStepOptions.filter((option) => option.value !== 'trigger_node')}@@ -125,6 +126,16 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {})}/>+ {selectedAction?.type === 'function_email' && props.id ? (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconLetter />}+ to={`${urls.workflow(props.id, 'assets')}?assetAction=${encodeURIComponent(params.instanceId as string)}`}+ >+ View sent emails+ </LemonButton>+ ) : null}</div><AppMetricsFilters logicKey={logicKey} /></div>@@ -241,7 +252,7 @@ function BatchJobMetrics({ job }: { job: HogFlowBatchJob }): JSX.Element {return (<div className="flex flex-col gap-2"><div className="flex flex-row gap-2 flex-wrap justify-between">- <div>+ <div className="flex flex-row gap-2 items-center flex-wrap"><LemonSelectsize="small"options={workflowStepOptions.filter((option) => option.value !== 'trigger_node')}@@ -253,6 +264,16 @@ function BatchJobMetrics({ job }: { job: HogFlowBatchJob }): JSX.Element {})}/>+ {selectedAction?.type === 'function_email' ? (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconLetter />}+ to={`${urls.workflow(workflow.id, 'assets')}?assetAction=${encodeURIComponent(params.instanceId as string)}`}+ >+ View sent emails+ </LemonButton>+ ) : null}</div><AppMetricsFilters logicKey={logicKey} /></div>diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 8d8266e2257e..301e9516951c 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -8,11 +8,13 @@ import { LemonSwitch, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'import { NotFound } from 'lib/components/NotFound'+import { FEATURE_FLAGS } from 'lib/constants'import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -23,6 +25,7 @@ import { ActivityScope } from '~/types'import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'import { Workflow } from './Workflow'+import { WorkflowAssets } from './WorkflowAssets'import { WorkflowInvocations } from './WorkflowInvocations'import { workflowLogic } from './workflowLogic'import { WorkflowLogs } from './WorkflowLogs'@@ -47,6 +50,8 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {}const sceneLogic = workflowSceneLogic(workflowSceneProps)const { currentTab } = useValues(sceneLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const emailAssetsUIEnabled = !!featureFlags[FEATURE_FLAGS.WORKFLOW_EMAIL_ASSETS_UI]const { searchParams } = useValues(router)const templateId = searchParams.templateId as string | undefinedconst editTemplateId = searchParams.editTemplateId as string | undefined@@ -110,6 +115,17 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {*/content: <WorkflowMetrics id={workflowSceneProps.id!} />,},+ emailAssetsUIEnabled+ ? {+ label: 'Assets',+ key: 'assets',+ /**+ * If we're rendering tabs, props.id is guaranteed to be+ * defined and not "new" (see return statement below)+ */+ content: <WorkflowAssets id={workflowSceneProps.id!} />,+ }+ : null,{label: 'History',key: 'history',diff --git a/products/workflows/frontend/Workflows/logs/log-utils.tsx b/products/workflows/frontend/Workflows/logs/log-utils.tsxindex 1940e081a312..a616091b6f51 100644--- a/products/workflows/frontend/Workflows/logs/log-utils.tsx+++ b/products/workflows/frontend/Workflows/logs/log-utils.tsx@@ -1,11 +1,17 @@-import { IconTrash } from '@posthog/icons'-import { Link } from '@posthog/lemon-ui'+import { useValues } from 'kea'+import { useState } from 'react'+import { IconLetter, IconTrash } from '@posthog/icons'+import { LemonModal, Link } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { urls } from 'scenes/urls'import { getHogFlowStep } from '../hogflows/steps/HogFlowSteps'import { HogFlow } from '../hogflows/types'+import { getMessageAssetContentUrl } from '../messageAssetsApi'// We pull out actions like [Action:action_function_webhook_13ec288f-10af-4e98-abd4-e2828de3305e] and replace them with a link to the action@@ -15,6 +21,48 @@ const ACTION_REGEX = /\[Action:([a-zA-Z0-9_-]+)\]/const PERSON_REGEX = /\[Person:([a-zA-Z0-9_-]+)\|(.*?)\]/const EVENT_REGEX = /\[Event:([a-zA-Z0-9_-]+)\|(.*?)\|(.*?)\]/const ACTOR_REGEX = /\[Actor:(.*?)\]/+const EMAIL_REGEX = /\[Email:([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]*)\]/++function EmailViewerChip({+ workflowId,+ invocationId,+ actionId,+}: {+ workflowId: HogFlow['id']+ invocationId: string+ actionId: string+}): JSX.Element | null {+ const { featureFlags } = useValues(featureFlagLogic)+ const [open, setOpen] = useState(false)+ if (!featureFlags[FEATURE_FLAGS.WORKFLOW_EMAIL_ASSETS_UI]) {+ return null+ }+ return (+ <>+ <Link+ className="rounded p-1 -m-1 bg-border text-bg-primary"+ onClick={(e) => {+ e.stopPropagation()+ setOpen(true)+ }}+ >+ <span className="mr-1">+ <IconLetter />+ </span>+ View email+ </Link>+ <LemonModal isOpen={open} onClose={() => setOpen(false)} width={720} title="Email">+ {/* sandbox="" disables scripts so the captured email HTML can't run anything. */}+ <iframe+ title="Rendered email"+ sandbox=""+ src={getMessageAssetContentUrl(workflowId, invocationId, actionId)}+ className="w-full h-[60vh] bg-white rounded border"+ />+ </LemonModal>+ </>+ )+}export const renderWorkflowLogMessage = (workflow: HogFlow, message: string): JSX.Element => {// Modifies the rendered log message to auto-detect action or person parts and replace them with a link@@ -73,6 +121,16 @@ export const renderWorkflowLogMessage = (workflow: HogFlow, message: string): JScontinue}+ const matchesEmailRegex = EMAIL_REGEX.exec(part)+ if (matchesEmailRegex) {+ const invocationId = matchesEmailRegex[1]+ const actionId = matchesEmailRegex[2]+ elements.push(+ <EmailViewerChip key={part} workflowId={workflow.id} invocationId={invocationId} actionId={actionId} />+ )+ continue+ }+const matchesEventRegex = EVENT_REGEX.exec(part)if (matchesEventRegex) {const eventUuid = matchesEventRegex[1]diff --git a/products/workflows/frontend/Workflows/messageAssetsApi.ts b/products/workflows/frontend/Workflows/messageAssetsApi.tsnew file mode 100644index 000000000000..e5bd83fa9642--- /dev/null+++ b/products/workflows/frontend/Workflows/messageAssetsApi.ts@@ -0,0 +1,49 @@+import { ApiRequest } from 'lib/api'++import { HogFlow } from './hogflows/types'++// Scoped to this product to keep Jest's `--findRelatedTests` selection small —+// lib/api.ts and hogflows/types.ts are both imported by half the app.++export interface MessageAsset {+ invocation_id: string+ action_id: string+ /** HogFlowBatchJob id for batch-triggered sends; empty for event-triggered runs. */+ parent_run_id: string+ kind: string+ distinct_id: string+ person_id: string+ recipient: string+ subject: string+ status: string+ sent_at: string+}++export interface MessageAssetsParams {+ parent_run_id?: string+ action_id?: string+ /** Pre-filter to a single invocation — used to deep-link from a log entry to the email that run sent. */+ invocation_id?: string+ distinct_id?: string+ search?: string+ after?: string+ before?: string+ limit?: number+ offset?: number+}++export async function getMessageAssets(+ hogFlowId: HogFlow['id'],+ params: MessageAssetsParams = {}+): Promise<MessageAsset[]> {+ return await new ApiRequest().hogFlow(hogFlowId).withAction('assets').withQueryString(params).get()+}++// Same-origin URL — used as an `<iframe src>` so the browser carries session auth.+export function getMessageAssetContentUrl(hogFlowId: HogFlow['id'], invocationId: string, actionId: string): string {+ return new ApiRequest()+ .hogFlow(hogFlowId)+ .withAction('assets/content')+ .withQueryString({ invocation_id: invocationId, action_id: actionId })+ .assembleFullUrl(true)+}diff --git a/products/workflows/frontend/Workflows/workflowAssetsLogic.ts b/products/workflows/frontend/Workflows/workflowAssetsLogic.tsnew file mode 100644index 000000000000..9adf2c99e0e0--- /dev/null+++ b/products/workflows/frontend/Workflows/workflowAssetsLogic.ts@@ -0,0 +1,72 @@+import { actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { lazyLoaders } from 'kea-loaders'++import { getMessageAssetContentUrl, getMessageAssets, MessageAsset } from './messageAssetsApi'+import type { workflowAssetsLogicType } from './workflowAssetsLogicType'++export interface WorkflowAssetsLogicProps {+ id: string+ /** Scope the list to a single batch run (HogFlowBatchJob id). Omit for the event-triggered/all view. */+ parentRunId?: string+ /** Pre-filter to a single email step, e.g. when arriving from a step's metric. */+ actionId?: string+ /** Pre-filter to a single invocation — used to deep-link from a log entry to its email. */+ invocationId?: string+}++export const workflowAssetsLogic = kea<workflowAssetsLogicType>([+ path(['products', 'workflows', 'frontend', 'Workflows', 'workflowAssetsLogic']),+ props({ id: 'new' } as WorkflowAssetsLogicProps),+ key(+ (props) =>+ `${props.id || 'new'}-${props.parentRunId ?? 'all'}-${props.actionId ?? 'all'}-${props.invocationId ?? 'all'}`+ ),+ actions({+ setSearch: (search: string) => ({ search }),+ openAsset: (asset: MessageAsset) => ({ asset }),+ closeAsset: true,+ }),+ reducers({+ search: ['', { setSearch: (_, { search }) => search }],+ selectedAsset: [+ null as MessageAsset | null,+ {+ openAsset: (_, { asset }) => asset,+ closeAsset: () => null,+ },+ ],+ }),+ lazyLoaders(({ props, values }) => ({+ assets: [+ [] as MessageAsset[],+ {+ loadAssets: async () => {+ if (!props.id || props.id === 'new') {+ return []+ }+ return await getMessageAssets(props.id, {+ parent_run_id: props.parentRunId,+ action_id: props.actionId,+ invocation_id: props.invocationId,+ search: values.search || undefined,+ })+ },+ },+ ],+ })),+ selectors({+ contentUrl: [+ () => [(_, props) => props.id as string],+ (id): ((asset: MessageAsset) => string) => {+ return (asset: MessageAsset) => getMessageAssetContentUrl(id, asset.invocation_id, asset.action_id)+ },+ ],+ }),+ listeners(({ actions }) => ({+ // Debounce so typing in the search box doesn't fire a request per keystroke.+ setSearch: async (_, breakpoint) => {+ await breakpoint(250)+ actions.loadAssets()+ },+ })),+])diff --git a/products/workflows/frontend/Workflows/workflowSceneLogic.ts b/products/workflows/frontend/Workflows/workflowSceneLogic.tsindex c3dcbe188ae1..0c50afe62e2c 100644--- a/products/workflows/frontend/Workflows/workflowSceneLogic.ts+++ b/products/workflows/frontend/Workflows/workflowSceneLogic.ts@@ -8,7 +8,7 @@ import { Breadcrumb } from '~/types'import type { workflowSceneLogicType } from './workflowSceneLogicType'-export const WorkflowTabs = ['workflow', 'logs', 'invocations', 'metrics', 'history'] as const+export const WorkflowTabs = ['workflow', 'logs', 'invocations', 'metrics', 'assets', 'history'] as constexport type WorkflowTab = (typeof WorkflowTabs)[number]export interface WorkflowSceneLogicProps {diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex b6e343a12e9e..32e6dcdfce12 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -562,6 +562,29 @@ export interface PatchedHogFlowApi {readonly schedules?: readonly HogFlowScheduleApi[]}+export interface MessageAssetApi {+ /** The workflow run this email was sent in. */+ invocation_id: string+ /** The email step (action node) within the workflow that sent this email. */+ action_id: string+ /** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */+ parent_run_id: string+ /** Asset kind. Currently always 'email'. */+ kind: string+ /** The recipient's distinct_id. */+ distinct_id: string+ /** The recipient's person UUID, if resolved. */+ person_id: string+ /** The recipient email address. */+ recipient: string+ /** The email subject line. */+ subject: string+ /** Delivery status at capture time. Currently always 'sent'. */+ status: string+ /** When the email was sent. */+ sent_at: string+}+/*** * `waiting` - Waiting* * `queued` - Queued@@ -927,6 +950,66 @@ export const HogFlowsListStatus = {Draft: 'draft',} as const+export type HogFlowsAssetsRetrieveParams = {+ /**+ * Only return assets sent by this email step (action node id) — used to drill in from a step's metric.+ * @minLength 1+ */+ action_id?: string+ /**+ * Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.+ * @minLength 1+ */+ after?: string+ /**+ * End of the time range, matched on sent time. Same format as 'after'. Defaults to now.+ * @minLength 1+ */+ before?: string+ /**+ * Only return assets sent to this distinct_id.+ * @minLength 1+ */+ distinct_id?: string+ /**+ * Only return the asset for this specific workflow run — used to deep-link from a single log entry to the email it sent. Returns 0 rows when the send had no captured asset (text-only, kill-switch off, or standalone email).+ * @minLength 1+ */+ invocation_id?: string+ /**+ * Maximum number of assets to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Number of assets to skip, for pagination.+ * @minimum 0+ */+ offset?: number+ /**+ * Only return assets for this batch run (HogFlowBatchJob id). Pass an empty string to return only event-triggered (non-batch) assets; omit to return all.+ */+ parent_run_id?: string+ /**+ * Case-insensitive substring match on recipient email or subject.+ * @minLength 1+ */+ search?: string+}++export type HogFlowsAssetContentRetrieveParams = {+ /**+ * The email step (action node) that sent the email. Defaults to empty for standalone email sends.+ */+ action_id?: string+ /**+ * The workflow run the email was sent in.+ * @minLength 1+ */+ invocation_id: string+}+export type HogFlowsInvocationResultsRetrieveParams = {/*** Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex 6214091f01ca..5d91adc52eef 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -20,6 +20,8 @@ import type {HogFlowTemplateApi,HogFlowTemplatesListParams,HogFlowTemplatesLogsRetrieveParams,+ HogFlowsAssetContentRetrieveParams,+ HogFlowsAssetsRetrieveParams,HogFlowsInvocationResultsRetrieveParams,HogFlowsListParams,HogFlowsLogsRetrieveParams,@@ -30,6 +32,7 @@ import type {HogInvocationRerunResponseApi,HogInvocationResultApi,HogInvocationResultDetailApi,+ MessageAssetApi,PaginatedHogFlowMinimalListApi,PaginatedHogFlowTemplateListApi,PatchedHogFlowApi,@@ -318,6 +321,66 @@ export const hogFlowsDestroy = async (projectId: string, id: string, options?: R})}+export const getHogFlowsAssetsRetrieveUrl = (projectId: string, id: string, params?: HogFlowsAssetsRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/hog_flows/${id}/assets/?${stringifiedParams}`+ : `/api/projects/${projectId}/hog_flows/${id}/assets/`+}++export const hogFlowsAssetsRetrieve = async (+ projectId: string,+ id: string,+ params?: HogFlowsAssetsRetrieveParams,+ options?: RequestInit+): Promise<MessageAssetApi[]> => {+ return apiMutator<MessageAssetApi[]>(getHogFlowsAssetsRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}++export const getHogFlowsAssetContentRetrieveUrl = (+ projectId: string,+ id: string,+ params: HogFlowsAssetContentRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/hog_flows/${id}/assets/content/?${stringifiedParams}`+ : `/api/projects/${projectId}/hog_flows/${id}/assets/content/`+}++export const hogFlowsAssetContentRetrieve = async (+ projectId: string,+ id: string,+ params: HogFlowsAssetContentRetrieveParams,+ options?: RequestInit+): Promise<string> => {+ return apiMutator<string>(getHogFlowsAssetContentRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getHogFlowsBatchJobsListUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/hog_flows/${id}/batch_jobs/`}diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex deb254391bfe..b9cd1f031e6d 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -36,6 +36,12 @@ tools:hog-flow-templates-update:operation: hog_flow_templates_updateenabled: false+ hog-flows-asset-content-retrieve:+ operation: hog_flows_asset_content_retrieve+ enabled: false+ hog-flows-assets-retrieve:+ operation: hog_flows_assets_retrieve+ enabled: falsehog-flows-batch-jobs-create:operation: hog_flows_batch_jobs_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 12ded8778251..072aa2c2427d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29759,6 +29759,29 @@ export namespace Schemas {resume_payload?: unknown;}+ export interface MessageAsset {+ /** The workflow run this email was sent in. */+ invocation_id: string;+ /** The email step (action node) within the workflow that sent this email. */+ action_id: string;+ /** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */+ parent_run_id: string;+ /** Asset kind. Currently always 'email'. */+ kind: string;+ /** The recipient's distinct_id. */+ distinct_id: string;+ /** The recipient's person UUID, if resolved. */+ person_id: string;+ /** The recipient email address. */+ recipient: string;+ /** The email subject line. */+ subject: string;+ /** Delivery status at capture time. Currently always 'sent'. */+ status: string;+ /** When the email was sent. */+ sent_at: string;+ }+export interface MessageCategory {readonly id: string;/** @maxLength 64 */@@ -57088,6 +57111,66 @@ export namespace Schemas {Draft: 'draft',} as const;+ export type EnvironmentsHogFlowsAssetsRetrieveParams = {+ /**+ * Only return assets sent by this email step (action node id) — used to drill in from a step's metric.+ * @minLength 1+ */+ action_id?: string;+ /**+ * Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.+ * @minLength 1+ */+ after?: string;+ /**+ * End of the time range, matched on sent time. Same format as 'after'. Defaults to now.+ * @minLength 1+ */+ before?: string;+ /**+ * Only return assets sent to this distinct_id.+ * @minLength 1+ */+ distinct_id?: string;+ /**+ * Only return the asset for this specific workflow run — used to deep-link from a single log entry to the email it sent. Returns 0 rows when the send had no captured asset (text-only, kill-switch off, or standalone email).+ * @minLength 1+ */+ invocation_id?: string;+ /**+ * Maximum number of assets to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of assets to skip, for pagination.+ * @minimum 0+ */+ offset?: number;+ /**+ * Only return assets for this batch run (HogFlowBatchJob id). Pass an empty string to return only event-triggered (non-batch) assets; omit to return all.+ */+ parent_run_id?: string;+ /**+ * Case-insensitive substring match on recipient email or subject.+ * @minLength 1+ */+ search?: string;+ };++ export type EnvironmentsHogFlowsAssetContentRetrieveParams = {+ /**+ * The email step (action node) that sent the email. Defaults to empty for standalone email sends.+ */+ action_id?: string;+ /**+ * The workflow run the email was sent in.+ * @minLength 1+ */+ invocation_id: string;+ };+export type EnvironmentsHogFlowsInvocationResultsRetrieveParams = {/*** Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.@@ -63667,6 +63750,66 @@ export namespace Schemas {Draft: 'draft',} as const;+ export type HogFlowsAssetsRetrieveParams = {+ /**+ * Only return assets sent by this email step (action node id) — used to drill in from a step's metric.+ * @minLength 1+ */+ action_id?: string;+ /**+ * Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.+ * @minLength 1+ */+ after?: string;+ /**+ * End of the time range, matched on sent time. Same format as 'after'. Defaults to now.+ * @minLength 1+ */+ before?: string;+ /**+ * Only return assets sent to this distinct_id.+ * @minLength 1+ */+ distinct_id?: string;+ /**+ * Only return the asset for this specific workflow run — used to deep-link from a single log entry to the email it sent. Returns 0 rows when the send had no captured asset (text-only, kill-switch off, or standalone email).+ * @minLength 1+ */+ invocation_id?: string;+ /**+ * Maximum number of assets to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of assets to skip, for pagination.+ * @minimum 0+ */+ offset?: number;+ /**+ * Only return assets for this batch run (HogFlowBatchJob id). Pass an empty string to return only event-triggered (non-batch) assets; omit to return all.+ */+ parent_run_id?: string;+ /**+ * Case-insensitive substring match on recipient email or subject.+ * @minLength 1+ */+ search?: string;+ };++ export type HogFlowsAssetContentRetrieveParams = {+ /**+ * The email step (action node) that sent the email. Defaults to empty for standalone email sends.+ */+ action_id?: string;+ /**+ * The workflow run the email was sent in.+ * @minLength 1+ */+ invocation_id: string;+ };+export type HogFlowsInvocationResultsRetrieveParams = {/*** Start of the time range, matched on scheduled time. Relative ('-7d', '-24h') or ISO 8601. Defaults to -7d — bounds the ClickHouse partition scan, so widen it explicitly for older runs.