: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(messaging): per-link click metrics for workflow emails (#75097)
Daniel Marchuk816ede5a62e9
diff --git a/.test_quarantine.json b/.test_quarantine.jsonindex a00035e4e4a2..2445d90e7ced 100644--- a/.test_quarantine.json+++ b/.test_quarantine.json@@ -10,6 +10,15 @@"added": "2026-07-24","expires": "2026-08-07","mode": "run"+ },+ {+ "id": "products/ai_observability/frontend/e2e/multimodal-trace.spec.ts",+ "runner": "playwright",+ "reason": "Ingested screenshot does not reach a phaiblob:// pointer before the poll window ends, so the assertion sees the raw value; fails on master and gates every PR",+ "owner": "@team-ai-observability",+ "added": "2026-08-10",+ "expires": "2026-08-17",+ "mode": "run"}]}diff --git a/frontend/src/lib/components/AppMetrics/appMetricsLogic.ts b/frontend/src/lib/components/AppMetrics/appMetricsLogic.tsindex 01c9b67baae4..3cf040859404 100644--- a/frontend/src/lib/components/AppMetrics/appMetricsLogic.ts+++ b/frontend/src/lib/components/AppMetrics/appMetricsLogic.ts@@ -60,6 +60,15 @@ export type AppMetricsTimeSeriesResponse = {export type AppMetricsTotalsRequest = Omit<AppMetricsCommonParams, 'interval' | 'breakdownBy'> & {breakdownBy: ('metric_name' | 'metric_kind' | 'app_source_id' | 'instance_id')[]+ /**+ * Caps the number of breakdown groups returned, highest total first.+ *+ * Without this the executor applies its own default (`DEFAULT_RETURNED_ROWS`, 100) to a query+ * that has no ORDER BY, so an over-100 breakdown silently returns an arbitrary 100 groups.+ * Callers whose breakdown cardinality can exceed that must set it; ordering by total means+ * truncation keeps the groups worth showing.+ */+ limit?: number}export type AppMetricsTotalsResponse = Record<@@ -106,6 +115,12 @@ export const loadAppMetricsTotals = async (GROUP BY ${hogql.raw(breakdownBy.join(', '))}`) as HogQLQueryString+ if (request.limit) {+ query = (query ++ hogql`+ORDER BY total DESC LIMIT ${request.limit}`) as HogQLQueryString+ }+const response = await api.queryHogQL(query,{ scene: 'HogFunction', productKey: 'pipeline_destinations' },diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex 56a5ff6e2df3..06ec332ba173 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -120,6 +120,44 @@ describe('EmailTrackingService', () => {expect(out).toContain('target=')})+ describe('ses mode', () => {+ const sesTrack = (html: string): string => addTrackingToEmail(html, invocation, signer, false, 'ses')++ it('leaves hrefs pointing at the destination and tags each anchor by position', () => {+ const out = sesTrack(+ '<body><a href="https://example.com/a">a</a><a href="https://example.com/b">b</a></body>'+ )+ // A wrapper here would bury the destination inside a per-send URL that SES then+ // reports verbatim as click.link, which is what makes per-link counts impossible.+ expect(out).not.toContain('/public/m/redirect')+ expect(out).toContain('<a href="https://example.com/a" ses:tags="phl:0">')+ expect(out).toContain('<a href="https://example.com/b" ses:tags="phl:1">')+ })++ it.each([+ ['clicktracking="off"', '<body><a href="https://example.com" clicktracking="off">x</a></body>'],+ ['data-ph-no-track', '<body><a href="https://example.com" data-ph-no-track>x</a></body>'],+ ])('translates the %s opt-out into ses:no-track', (_name, html) => {+ // SES honors only its own attribute, so without this the anchor is still rewritten+ // to awstrack.me and app deeplinks stop resolving.+ const out = sesTrack(html)+ expect(out).toContain('ses:no-track')+ expect(out).not.toContain('ses:tags')+ })++ it('merges into an author-supplied ses:tags value instead of emitting a second attribute', () => {+ const out = sesTrack('<body><a href="https://example.com" ses:tags="campaign:spring">x</a></body>')+ expect(out).toContain('ses:tags="campaign:spring;phl:0"')+ })++ it('keeps anchor positions stable when an earlier link opts out', () => {+ const out = sesTrack(+ '<body><a href="https://example.com/a" data-ph-no-track>a</a><a href="https://example.com/b">b</a></body>'+ )+ expect(out).toContain('ses:tags="phl:1"')+ })+ })+const invocationWithDistinctId = {functionId: 'fn-1',id: 'inv-1',diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex 06e8136633d2..1e6fa13d1b54 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -15,7 +15,7 @@ import { HogFunctionManagerService } from '../managers/hog-function-manager.servimport { TeamWorkflowsConfigService } from '../managers/team-workflows-config.service'import { HogFunctionMonitoringService } from '../monitoring/hog-function-monitoring.service'import { EmailSuppressionService } from './email-suppression.service'-import { SesWebhookHandler } from './helpers/ses'+import { SES_LINK_INDEX_TAG, SesWebhookHandler } from './helpers/ses'import { EmailTrackingCodeSigner, trackingCodeFormatCounter } from './helpers/tracking-code'export const PIXEL_GIF = Buffer.from('R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'base64')@@ -25,6 +25,41 @@ const LINK_REGEX =// Anchors carrying either opt-out marker are left unwrapped (no click-tracking redirect).const LINK_TRACKING_OPT_OUT_REGEX = /\bclicktracking\s*=\s*["']?off["']?|\bdata-ph-no-track\b/i+// Matches an existing `ses:tags` attribute so our link tag can be merged into its value.+const SES_TAGS_ATTR_REGEX = /\bses:tags\s*=\s*(?:"([^"]*)"|'([^']*)'|([^'">\s]+))/i+const SES_NO_TRACK_ATTR_REGEX = /\bses:no-track\b/i++/**+ * How anchors in the email body are prepared for click attribution.+ *+ * `redirect` rewrites each href to our own `/public/m/redirect` endpoint, which records the click+ * before forwarding. Used on the maildev path, where no provider webhook exists.+ *+ * `ses` leaves hrefs pointing at their real destination and instead annotates each anchor with the+ * attributes SES reads when it rewrites links for its own click tracking. SES is the sole click+ * source on this path, so wrapping the href as well would only bury the destination inside a+ * per-send URL that the Click event then reports verbatim.+ */+export type EmailTrackingMode = 'redirect' | 'ses'++const addAttributeToOpeningTag = (openingTag: string, attribute: string): string => {+ return openingTag.replace(/\s*\/?>$/, ` ${attribute}>`)+}++const withSesLinkIndexTag = (openingTag: string, linkIndex: number): string => {+ const tag = `${SES_LINK_INDEX_TAG}:${linkIndex}`+ const existing = openingTag.match(SES_TAGS_ATTR_REGEX)+ if (!existing) {+ return addAttributeToOpeningTag(openingTag, `ses:tags="${tag}"`)+ }+ // An HTML parser keeps only the first of two same-named attributes, so emitting a second+ // `ses:tags` would silently discard whichever set loses. Merge into the author's existing+ // value instead so both their tags and ours reach SES. SES separates pairs with `;` and+ // allows only `0-9 A-Z a-z - _` in a value, so any other separator makes one malformed tag.+ const value = existing[1] ?? existing[2] ?? existing[3] ?? ''+ return openingTag.replace(SES_TAGS_ATTR_REGEX, () => `ses:tags="${value ? `${value};` : ''}${tag}"`)+}+const trackingEventsCounter = new Counter({name: 'email_tracking_events_total',help: 'Total number of email tracking events received',@@ -96,7 +131,8 @@ export const addTrackingToEmail = (html: string,invocation: CyclotronJobInvocationHogFunction,signer: EmailTrackingCodeSigner,- isTest = false+ isTest = false,+ mode: EmailTrackingMode = 'redirect'): string => {// Only carry distinct_id in the in-email pixel/redirect URLs in dev/test, where those handlers// record metrics. In production they don't (SES webhooks own open/click attribution via the@@ -106,7 +142,14 @@ export const addTrackingToEmail = (const trackingInvocation = { ...invocation, distinctId }const trackingUrl = signer.pixelUrl(trackingInvocation, isTest)+ // Incremented for every anchor LINK_REGEX matches, including ones that turn out to be opted+ // out or unsafe, so the index stays tied to document position instead of shifting with how+ // many anchors happened to be trackable. The same template therefore yields the same indices+ // on every send, which is what makes counts comparable across recipients.+ let anchorIndex = 0+html = html.replace(LINK_REGEX, (m, d, s, u) => {+ const linkIndex = anchorIndex++const href = decodeHtmlEntitiesInHref(d || s || u || '')// LINK_REGEX skips literal `javascript:` hrefs, but an attacker could entity-encode// the scheme (e.g. `javascript:`) to slip past it; re-check after decoding.@@ -119,7 +162,22 @@ export const addTrackingToEmail = (// Match only the opening <a> tag so a marker in the link's inner HTML (a child// element's attribute or literal link text) can't silently disable tracking.const openingTag = m.match(/^<a\b[^>]*>/i)?.[0] ?? ''- if (LINK_TRACKING_OPT_OUT_REGEX.test(openingTag)) {+ const optedOut = LINK_TRACKING_OPT_OUT_REGEX.test(openingTag)++ if (mode === 'ses') {+ // SES rewrites every http(s) anchor once click tracking is on, and it honors only its+ // own `ses:no-track`. Translating the opt-out into that attribute is what actually+ // keeps a universal link or app deeplink off awstrack.me; leaving the href alone (the+ // `redirect` mode's opt-out) does nothing here.+ if (optedOut) {+ return SES_NO_TRACK_ATTR_REGEX.test(openingTag)+ ? m+ : addAttributeToOpeningTag(openingTag, 'ses:no-track') + m.slice(openingTag.length)+ }+ return withSesLinkIndexTag(openingTag, linkIndex) + m.slice(openingTag.length)+ }++ if (optedOut) {return m}const tracked = signer.redirectUrl(trackingInvocation, href, isTest)@@ -159,6 +217,8 @@ export class EmailTrackingService {source,properties,timestamp,+ instanceIdOverride,+ deferFlush = false,workflowVersion,}: {functionId?: string@@ -170,6 +230,10 @@ export class EmailTrackingService {source: 'direct' | 'ses'properties?: Record<string, unknown>timestamp?: string+ instanceIdOverride?: string+ // Skips the per-call Kafka flush so a caller handling several metrics can queue them all+ // and pay a single broker round-trip. The caller owns flushing when it sets this.+ deferFlush?: booleanworkflowVersion?: number}): Promise<void> {if (!functionId || !invocationId) {@@ -207,7 +271,7 @@ export class EmailTrackingService {// Mirror email.service.ts's `parentRunId ?? functionId` so batch-triggered// runs get their webhook metrics attributed to the batch run, not the workflow.app_source_id: parentRunId ?? appSourceId,- instance_id: actionId || invocationId,+ instance_id: instanceIdOverride || actionId || invocationId,metric_name: metricName,metric_kind: 'email',count: 1,@@ -237,7 +301,9 @@ export class EmailTrackingService {await this.capturedEventsService.flush()}- await this.hogFunctionMonitoringService.flush()+ if (!deferFlush) {+ await this.hogFunctionMonitoringService.flush()+ }trackingEventsCounter.inc({ event_type: metricName, source })logger.debug('[EmailTrackingService] trackMetric: Email tracking event', {@@ -331,6 +397,9 @@ export class EmailTrackingService {verifySignature: true,})+ // A single SNS notification can yield several metrics (a Click emits its rollup plus a+ // per-link row, a Bounce its rollup plus a per-type row). Flushing inside each call would+ // make those serial Kafka round-trips, so defer and flush once for the batch.for (const metric of metrics || []) {await this.trackMetric({functionId: metric.functionId,@@ -342,9 +411,14 @@ export class EmailTrackingService {source: 'ses',properties: metric.properties,timestamp: metric.timestamp,+ instanceIdOverride: metric.instanceIdOverride,+ deferFlush: true,workflowVersion: metric.workflowVersion,})}+ if (metrics?.length) {+ await this.hogFunctionMonitoringService.flush()+ }// Wrapped so a failure here doesn't skip the suppression writes below.try {diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.tsindex 80d645c1880a..a1ea7cda8c24 100644--- a/nodejs/src/cdp/services/messaging/email.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts@@ -820,7 +820,10 @@ describe('EmailService', () => {const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html.Dataif (expectTracked) {- expect(sentHtml).toContain('/redirect?ph_id=')+ // SES sends tag each anchor and let SES report the click, instead of+ // rewriting the href to a redirect URL. The open pixel is unchanged.+ expect(sentHtml).toContain('ses:tags="phl:')+ expect(sentHtml).toContain('ph_id=')} else {expect(sentHtml).toEqual(trackableHtml)}@@ -833,7 +836,8 @@ describe('EmailService', () => {const result = await service.executeSendEmail(invocation)expect(result.error).toBeUndefined()const sentHtml = (sendEmailSpy.mock.calls[0][0] as { input: any }).input.Content.Simple.Body.Html.Data- expect(sentHtml).toContain('/redirect?ph_id=')+ expect(sentHtml).toContain('ses:tags="phl:')+ expect(sentHtml).toContain('ph_id=')})it('the step-level toggle wins over consent: tracking_enabled false is untracked even for opted-in recipients', async () => {diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.tsindex d4452c40a522..8c1ceebe07b7 100644--- a/nodejs/src/cdp/services/messaging/email.service.ts+++ b/nodejs/src/cdp/services/messaging/email.service.ts@@ -530,7 +530,13 @@ export class EmailService {Html: {Data: maybeAddPreheaderToEmail(trackingEnabled- ? addTrackingToEmail(params.html, result.invocation, this.trackingCodeSigner, isTest)+ ? addTrackingToEmail(+ params.html,+ result.invocation,+ this.trackingCodeSigner,+ isTest,+ 'ses'+ ): params.html,params.preheader),diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.tsindex fc6c9f4e901d..eec71c9d6421 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts@@ -1,6 +1,6 @@import { defaultConfig } from '~/common/config/config'-import { SesWebhookHandler } from './ses'+import { SesWebhookHandler, normalizeClickUrl, resolveClickDestination } from './ses'import { EmailTrackingCodeSigner } from './tracking-code'// Hardcoded (not imported) so a change to the header constant fails this test.@@ -105,6 +105,158 @@ describe('SesWebhookHandler', () => {expect(result.metrics?.[0].timestamp).toBe('2025-10-03T12:02:00Z')})+ it('unwraps a legacy redirect link and surfaces the SES link tag', async () => {+ const body = [+ {+ eventType: 'Click',+ mail: baseMail,+ click: {+ link: `http://localhost:8010/public/m/redirect?ph_id=${signer.generate(+ baseInvocation+ )}&target=${encodeURIComponent('https://example.com/pricing?a=1')}`,+ linkTags: { phl: ['2'] },+ timestamp: '2025-10-03T12:02:00Z',+ },+ },+ ]+ const result = await handler.handleWebhook({ body, headers: {} })+ expect(result.status).toBe(200)+ expect(result.metrics?.[0].properties).toEqual({+ $email_to: '[email protected]',+ $link_url: 'https://example.com/pricing?a=1',+ $link_index: '2',+ })+ })++ it('emits a per-link companion metric keyed by action, link index and normalized url', async () => {+ const body = [+ {+ eventType: 'Click',+ mail: baseMail,+ click: {+ link: 'https://example.com/pricing/?utm_content=hero&uid=abc',+ linkTags: { phl: ['3'] },+ timestamp: '2025-10-03T12:02:00Z',+ },+ },+ ]+ const result = await handler.handleWebhook({ body, headers: {} })+ // The rollup keeps its own name so existing totals and trends can't double-count the+ // per-link row, and the query string is dropped so per-recipient values don't fragment it.+ expect(result.metrics?.map((m) => [m.metricName, m.instanceIdOverride])).toEqual([+ ['email_link_clicked', undefined],+ ['email_link_clicked_by_link', 'act789|3|https://example.com/pricing'],+ ])+ })++ it('skips the per-link metric when the send has no action id', async () => {+ const noActionInvocation = { functionId: 'abc123', id: 'inv456', teamId: 1 } as const+ const body = [+ {+ eventType: 'Click',+ mail: {+ ...baseMail,+ headers: [{ name: TRACKING_CODE_HEADER, value: signer.generate(noActionInvocation) }],+ tags: undefined,+ },+ click: { link: 'https://example.com/a', timestamp: '2025-10-03T12:02:00Z' },+ },+ ]+ const result = await handler.handleWebhook({ body, headers: {} })+ // Without an action id the key would fall back to the invocation id, producing one row per+ // send per link instead of an aggregate.+ expect(result.metrics?.map((m) => m.metricName)).toEqual(['email_link_clicked'])+ })++ describe('normalizeClickUrl', () => {+ it.each([+ ['drops the query string', 'https://example.com/a?b=1', 'https://example.com/a'],+ ['drops the fragment', 'https://example.com/a#top', 'https://example.com/a'],+ ['drops a trailing slash', 'https://example.com/a/', 'https://example.com/a'],+ ['keeps the path', 'https://example.com/a/b/c', 'https://example.com/a/b/c'],+ ['passes through a hostless scheme', 'mailto:x', 'mailto:x'],+ ['passes through an unparseable link', 'not a url', 'not a url'],+ ])('%s', (_name, link, expected) => {+ expect(normalizeClickUrl(link)).toBe(expected)+ })++ // Per-recipient tokens in the path would otherwise land in the metrics sort key, making its+ // cardinality scale with audience size and putting recipient secrets in a team-readable store.+ it.each([+ [+ 'a uuid',+ 'https://example.com/verify/123e4567-e89b-12d3-a456-426614174000',+ 'https://example.com/verify/*',+ ],+ [+ 'a long hex digest',+ 'https://example.com/unsubscribe/a1b2c3d4e5f6a7b8',+ 'https://example.com/unsubscribe/*',+ ],+ ['a bare numeric id', 'https://example.com/users/1234567', 'https://example.com/users/*'],+ [+ 'a long opaque token',+ 'https://example.com/magic/AbCdEfGhIjKlMnOpQrStUvWx',+ 'https://example.com/magic/*',+ ],+ [+ 'a dot-separated jwt',+ 'https://example.com/reset/eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dBjftJeZ4CV',+ 'https://example.com/reset/*',+ ],+ [+ 'a percent-encoded token',+ 'https://example.com/verify/%31%32%33e4567-e89b-12d3-a456-426614174000',+ 'https://example.com/verify/*',+ ],+ ['a mixed-case token', 'https://example.com/m/aB3xK9mZq2LpW7fT', 'https://example.com/m/*'],+ [+ 'a token carrying base64url separators',+ 'https://example.com/m/aB3-xK9_mZq2LpW7fT5vN8cR1jH4gY6s',+ 'https://example.com/m/*',+ ],+ ])('redacts %s from the path', (_name, link, expected) => {+ expect(normalizeClickUrl(link)).toBe(expected)+ })++ // Over-redacting empties the breakdown of the very thing it exists to show, so slugs long+ // enough to resemble a token have to survive.+ it.each([+ ['a hyphenated slug', 'https://example.com/blog/how-to-set-up-feature-flags'],+ ['a title-cased slug', 'https://example.com/blog/Getting-Started-With-PostHog'],+ ['an unbroken lowercase word', 'https://example.com/docs/gettingstartedguide'],+ ['a dated filename', 'https://example.com/files/annual-report-2026.pdf'],+ ['a short path word', 'https://example.com/pricing/enterprise-plan'],+ ])('keeps %s', (_name, link) => {+ expect(normalizeClickUrl(link)).toBe(link)+ })++ it('caps the length so a long url cannot bloat the metrics sort key', () => {+ // Many short segments, because a single long segment is collapsed by the redaction above+ // and would never reach the cap.+ expect(normalizeClickUrl(`https://example.com/${'ab/'.repeat(100)}`)).toHaveLength(200)+ })+ })++ describe('resolveClickDestination', () => {+ it.each([+ ['a destination link is passed through', 'https://example.com/x?a=1', 'https://example.com/x?a=1'],+ [+ 'a redirect wrapper resolves to its target',+ 'https://webhooks.us.posthog.com/public/m/redirect?ph_id=abc.def&target=https%3A%2F%2Fexample.com%2Fx',+ 'https://example.com/x',+ ],+ [+ 'a redirect wrapper with no target falls back to the raw link',+ 'https://webhooks.us.posthog.com/public/m/redirect?ph_id=abc.def',+ 'https://webhooks.us.posthog.com/public/m/redirect?ph_id=abc.def',+ ],+ ['an unparseable link is passed through', 'not a url', 'not a url'],+ ])('%s', (_name, link, expected) => {+ expect(resolveClickDestination(link)).toBe(expected)+ })+ })+it('parses tracking code from header only when SES tag is absent', async () => {// Simulates a future state where the EmailTag backwards-compat carrier has been removed.const headerOnlyMail = {diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.tsindex 4d5fabc67b83..4b9b03963682 100644--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts@@ -76,6 +76,8 @@ const SesClickEventSchema = SesCommonEventBase.extend({click: z.object({ipAddress: z.string().optional(),link: z.string(),+ // Echoes the `ses:tags` we set on each anchor at send time, as {name: [value]}.+ linkTags: z.record(z.string(), z.array(z.string())).optional(),userAgent: z.string().optional(),timestamp: z.string(),}),@@ -178,6 +180,111 @@ export type SesEventLogLine = {message: string}+// SES link tag naming an anchor's ordinal position in the email body. Set on each `<a>` at send+// time and echoed back on the Click event, which is what lets two anchors pointing at the same URL+// (a header logo and a footer link, say) be counted separately. SES restricts tag names and values+// to alphanumerics, hyphens and underscores, so an integer index is the only stable identifier+// cheap enough to carry here.+export const SES_LINK_INDEX_TAG = 'phl'++// Path of our own click-tracking redirect, which used to wrap every anchor before SES saw it.+const TRACKING_REDIRECT_PATH = '/public/m/redirect'++/**+ * The destination the recipient actually asked for.+ *+ * SES reports the link as it appeared in the HTML, before SES rewrote it. Messages sent while we+ * still wrapped anchors in our own redirect therefore report that wrapper, whose `ph_id` differs on+ * every send, so the raw value is both unaggregatable and a carrier for a signed tracking code that+ * should not be stored on an event. Unwrap it back to `target`. Anything else is passed through.+ */+export const resolveClickDestination = (link: string): string => {+ try {+ const url = new URL(link)+ if (!url.pathname.endsWith(TRACKING_REDIRECT_PATH)) {+ return link+ }+ return url.searchParams.get('target') || link+ } catch {+ return link+ }+}++// Bounds how much of a URL rides in the app_metrics2 sort key. Long enough to stay recognizable in+// the UI, short enough that a pathological query-less URL can't bloat the index.+const MAX_LINK_URL_LENGTH = 200++/**+ * Collapses a clicked URL to the identity we count by.+ *+ * The query string and fragment are dropped because merge tags and per-recipient UTM values make+ * them differ on every send, which would scatter one link's clicks across thousands of buckets. Two+ * anchors that genuinely point at the same path stay distinguishable through the link index, which+ * is carried alongside this value.+ */+// Templates routinely build hrefs like `/unsubscribe/{{token}}` or `/users/12345`, so a path segment+// is often a per-recipient identifier rather than part of the page's identity. Collapsing those is+// what keeps the metrics sort key bounded by pages rather than by audience size, and keeps recipient+// tokens out of a store the whole team can read.+//+// A token is recognized by its runs of unbroken alphanumerics rather than by the segment as a whole,+// because tokens arrive glued together with punctuation: a JWT is dot-separated, and base64url+// tokens carry `-` and `_`. Testing runs also stops long slugs from being mistaken for tokens, since+// `how-to-set-up-feature-flags` is only ever short words once split.+const UUID_SEGMENT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+const TOKEN_RUN_SEPARATORS = /[.\-_~]/+const HEX_RUN = /^[0-9a-f]{12,}$/i+const NUMERIC_RUN = /^[0-9]{6,}$/+const SINGLE_CASE_WORD = /^([a-z]+|[A-Z]+)$/+// Below this, mixed-case runs are still plausibly words (`Introduction`, `CHANGELOG`).+const MIN_RANDOM_RUN_LENGTH = 16+const OPAQUE_PATH_SEGMENT_PLACEHOLDER = '*'++const isOpaqueRun = (run: string): boolean =>+ HEX_RUN.test(run) || NUMERIC_RUN.test(run) || (run.length >= MIN_RANDOM_RUN_LENGTH && !SINGLE_CASE_WORD.test(run))++const isOpaquePathSegment = (segment: string): boolean => {+ // Percent-encoding would otherwise hide a token's shape behind `%`, which none of the runs match.+ let decoded = segment+ try {+ decoded = decodeURIComponent(segment)+ } catch {+ // Malformed escapes are left as-is; the raw segment is still worth testing.+ }+ return UUID_SEGMENT.test(decoded) || decoded.split(TOKEN_RUN_SEPARATORS).some(isOpaqueRun)+}++const redactOpaquePathSegments = (pathname: string): string =>+ pathname+ .split('/')+ .map((segment) => (isOpaquePathSegment(segment) ? OPAQUE_PATH_SEGMENT_PLACEHOLDER : segment))+ .join('/')++export const normalizeClickUrl = (link: string): string => {+ try {+ const url = new URL(link)+ // `new URL` also parses hostless schemes (mailto:, tel:, sms:), where `host` is empty and+ // rebuilding as `scheme://host+path` would invent an authority — `mailto:x` becoming+ // `mailto://x`. Only http(s)-shaped links have a host to normalize; the rest pass through.+ if (!url.host) {+ return link.slice(0, MAX_LINK_URL_LENGTH)+ }+ const path = redactOpaquePathSegments(url.pathname)+ return `${url.protocol}//${url.host}${path}`.replace(/\/$/, '').slice(0, MAX_LINK_URL_LENGTH)+ } catch {+ return link.slice(0, MAX_LINK_URL_LENGTH)+ }+}++// Separator between the parts of a per-link metric's `instance_id`. The frontend splits on this to+// recover (action id, link index, url); see LINK_INSTANCE_SEPARATOR in workflowMetricsSummaryLogic.+// A URL may legitimately contain this character, so parsers must limit themselves to the first two+// separators and treat the remainder as the URL.+export const LINK_INSTANCE_SEPARATOR = '|'++export const buildLinkInstanceId = (actionId: string, linkIndex: string, normalizedUrl: string): string =>+ [actionId, linkIndex, normalizedUrl].join(LINK_INSTANCE_SEPARATOR)+const MAX_SES_FIELD_LENGTH = 1024// Strip control chars, neutralize rich-log bracket tokens, and cap length.@@ -420,6 +527,9 @@ export class SesWebhookHandler {parentRunId?: stringdistinctId?: stringmetricName: MinimalAppMetric['metric_name']+ // Replaces the instance_id trackMetric would derive, for metrics keyed by something+ // other than the action or invocation (see buildLinkInstanceId).+ instanceIdOverride?: stringproperties?: Record<string, any>timestamp?: stringworkflowVersion?: number@@ -518,6 +628,7 @@ export class SesWebhookHandler {parentRunId?: stringdistinctId?: stringmetricName: MinimalAppMetric['metric_name']+ instanceIdOverride?: stringproperties?: Record<string, any>timestamp?: stringworkflowVersion?: number@@ -586,7 +697,11 @@ export class SesWebhookHandler {timestamp = rec.open.timestamp} else if ('click' in rec && rec.click) {timestamp = rec.click.timestamp- properties.$link_url = rec.click.link+ properties.$link_url = resolveClickDestination(rec.click.link)+ const linkIndex = rec.click.linkTags?.[SES_LINK_INDEX_TAG]?.[0]+ if (linkIndex !== undefined) {+ properties.$link_index = linkIndex+ }} else if ('delivery' in rec && rec.delivery) {timestamp = rec.delivery.timestamp} else if ('bounce' in rec && rec.bounce) {@@ -608,6 +723,29 @@ export class SesWebhookHandler {workflowVersion,})+ // Per-link companion row for the workflow Metrics tab's link breakdown. Emitted only+ // when the send came from a workflow step: without an action id the key would fall+ // back to the invocation id, producing a row per send per link rather than an+ // aggregate, and the breakdown is per-action anyway. It carries its own metric name+ // so the existing `email_link_clicked` totals and trends can't double-count it.+ if (rec.eventType === 'Click' && actionId) {+ metrics.push({+ functionId,+ invocationId,+ actionId,+ parentRunId,+ distinctId,+ metricName: 'email_link_clicked_by_link',+ instanceIdOverride: buildLinkInstanceId(+ actionId,+ rec.click.linkTags?.[SES_LINK_INDEX_TAG]?.[0] ?? '',+ normalizeClickUrl(resolveClickDestination(rec.click.link))+ ),+ timestamp,+ workflowVersion,+ })+ }+// email_bounced stays the catch-all rollup; each bounce additionally emits a// per-type sub-metric (hard + transient + undetermined = email_bounced). AWS's// account bounce rate — what the email reputation feature calibrates against —diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex c267f15f73fe..deb056f6098b 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -236,6 +236,7 @@ export type MinimalAppMetric = {| 'email_failed'| 'email_opened'| 'email_link_clicked'+ | 'email_link_clicked_by_link'| 'email_bounced'| 'email_bounced_hard'| 'email_bounced_transient'diff --git a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsxindex 26ce524953f1..475b5dc8c9b6 100644--- a/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx+++ b/products/workflows/frontend/Workflows/WorkflowMetricsSummary.tsx@@ -7,10 +7,12 @@ import { LemonLabel, LemonTable, LemonTableColumns, LemonTag, Link, SpinnerOverlimport { getColorVar } from 'lib/colors'import { type AppMetricsTimeSeriesResponse } from 'lib/components/AppMetrics/appMetricsLogic'import { AppMetricsTrends } from 'lib/components/AppMetrics/AppMetricsTrends'+import { type ExpandableConfig } from 'lib/lemon-ui/LemonTable'import { humanFriendlyNumber } from 'lib/utils/numbers'import { WorkflowMetricCard } from './WorkflowMetricCard'import {+ type EmailLinkRow,type EmailMetric,type EmailMetricRow,METRIC_COLORS,@@ -64,6 +66,7 @@ export function WorkflowMetricsSummary({workflowSummaryTrends,emailMetricsRows,emailTotalsByActionIdLoading,+ emailLinkTotalsByActionId,pushMetricsRows,pushTotalsByActionIdLoading,conversionRate,@@ -171,6 +174,58 @@ export function WorkflowMetricsSummary({]}, [onSelectAction, onMetricClick, viewMetricsColumn])+ const emailLinkColumns: LemonTableColumns<EmailLinkRow> = useMemo(+ () => [+ {+ title: 'Link',+ key: 'url',+ render: (_: unknown, row: EmailLinkRow) => (+ <div className="flex items-center gap-2">+ {row.truncated ? (+ // Navigating to a URL that was cut mid-path would land somewhere wrong,+ // so show it as text rather than something clickable.+ <span className="break-all" title="This link was too long to store in full">+ {row.url}…+ </span>+ ) : (+ <Link to={row.url} target="_blank" className="break-all">+ {row.url}+ </Link>+ )}+ {row.duplicateUrl && row.linkIndex ? (+ <LemonTag type="muted" title="Another link in this email points to the same page">+ Position {row.linkIndex}+ </LemonTag>+ ) : null}+ </div>+ ),+ },+ {+ title: 'Clicks',+ key: 'clicks',+ align: 'right',+ render: (_: unknown, row: EmailLinkRow) => humanFriendlyNumber(row.clicks),+ },+ ],+ []+ )++ const emailExpandable: ExpandableConfig<EmailMetricRow> = useMemo(+ () => ({+ rowExpandable: (row: EmailMetricRow) => (emailLinkTotalsByActionId[row.id]?.length ?? 0) > 0,+ expandedRowRender: (row: EmailMetricRow) => (+ <LemonTable+ columns={emailLinkColumns}+ dataSource={emailLinkTotalsByActionId[row.id] ?? []}+ rowKey={(link) => `${link.linkIndex}:${link.url}`}+ size="small"+ embedded+ />+ ),+ }),+ [emailLinkTotalsByActionId, emailLinkColumns]+ )+const pushColumns: LemonTableColumns<PushMetricRow> = useMemo(() => {return [{@@ -329,6 +384,7 @@ export function WorkflowMetricsSummary({loading={emailTotalsByActionIdLoading}rowKey="id"size="small"+ expandable={emailExpandable}/></div>) : null}diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.tsindex 5e25a0a53f44..5a7b2d7c1637 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.test.ts@@ -7,6 +7,7 @@ import {buildPushMetricRows,channelSentLabel,detectMessagingChannels,+ parseEmailLinkTotals,subtractSeries,withDisplayName,} from './workflowMetricsSummaryLogic'@@ -214,3 +215,62 @@ describe('buildPushMetricRows', () => {])})})++describe('parseEmailLinkTotals', () => {+ const totals = (...instanceIds: [string, number][]): Record<string, { total: number; breakdowns: string[] }> =>+ Object.fromEntries(instanceIds.map(([id, total]) => [id, { total, breakdowns: [id] }]))++ it('groups links under their action, most clicked first', () => {+ expect(+ parseEmailLinkTotals(+ totals(+ ['act-1|0|https://example.com/a', 3],+ ['act-1|1|https://example.com/b', 9],+ ['act-2|0|https://example.com/c', 1]+ )+ )+ ).toEqual({+ 'act-1': [+ { linkIndex: '1', url: 'https://example.com/b', clicks: 9, truncated: false, duplicateUrl: false },+ { linkIndex: '0', url: 'https://example.com/a', clicks: 3, truncated: false, duplicateUrl: false },+ ],+ 'act-2': [+ { linkIndex: '0', url: 'https://example.com/c', clicks: 1, truncated: false, duplicateUrl: false },+ ],+ })+ })++ it('keeps a url containing the field separator intact', () => {+ expect(parseEmailLinkTotals(totals(['act-1|0|https://example.com/a|b', 2]))['act-1']).toEqual([+ { linkIndex: '0', url: 'https://example.com/a|b', clicks: 2, truncated: false, duplicateUrl: false },+ ])+ })++ it('flags links that share a url within a step, so position can tell them apart', () => {+ const rows = parseEmailLinkTotals(+ totals(+ ['act-1|0|https://example.com/a', 4],+ ['act-1|7|https://example.com/a', 1],+ ['act-1|2|https://example.com/b', 2]+ )+ )['act-1']+ expect(rows.map((r) => [r.linkIndex, r.duplicateUrl])).toEqual([+ ['0', true],+ ['2', false],+ ['7', true],+ ])+ })++ it('flags a url stored at the length cap as truncated', () => {+ const longUrl = `https://example.com/${'x'.repeat(200)}`.slice(0, 200)+ expect(parseEmailLinkTotals(totals([`act-1|0|${longUrl}`, 1]))['act-1'][0].truncated).toBe(true)+ })++ it.each([+ ['an instance id with no link fields', 'act-1'],+ ['an instance id missing the url field', 'act-1|0'],+ ['an empty url', 'act-1|0|'],+ ])('ignores %s', (_name, instanceId) => {+ expect(parseEmailLinkTotals(totals([instanceId, 5]))).toEqual({})+ })+})diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.tsindex b96151e6ee8b..908d6941712a 100644--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts@@ -35,6 +35,77 @@ const CONVERSION_EVENT = '$workflows_conversion'// early-exited runs too, and keeps "In progress" from treating those finished runs as still live.const RUN_LEVEL_INSTANCE_ID = ''+// Per-link click counts ride on app_metrics2 under their own metric name, with the link identity+// packed into `instance_id` as `<action id>|<link index>|<normalized url>`. The producer is+// buildLinkInstanceId in the plugin server's SES webhook handler (helpers/ses.ts); this separator+// and metric name must match it. A URL can itself contain the separator, so only the first two+// occurrences delimit fields and the remainder is the URL.+const EMAIL_LINK_METRIC_NAME = 'email_link_clicked_by_link'+const LINK_INSTANCE_SEPARATOR = '|'++// One group per (action, link), so a workflow with many email steps clears the executor's default+// 100-row cap easily. The request orders by total so the cap keeps the most-clicked links rather+// than an arbitrary slice; `parseEmailLinkTotals` then sorts within each action for display.+const EMAIL_LINK_TOTALS_LIMIT = 1000++// Mirrors MAX_LINK_URL_LENGTH in the plugin server's helpers/ses.ts. A stored URL at exactly this+// length was cut to fit the metrics key, so it is not safe to navigate to.+const EMAIL_LINK_URL_MAX_LENGTH = 200++export type EmailLinkRow = {+ /** Position of the anchor in the email body, blank for clicks recorded without a link tag. */+ linkIndex: string+ url: string+ clicks: number+ /** The stored URL was cut to fit the metrics key, so it may not resolve to the real page. */+ truncated: boolean+ /** Another link in the same step resolves to this same URL, so position is what tells them apart. */+ duplicateUrl: boolean+}++export function parseEmailLinkTotals(totalsResponse: AppMetricsTotalsResponse): Record<string, EmailLinkRow[]> {+ const byActionId: Record<string, EmailLinkRow[]> = {}++ Object.values(totalsResponse).forEach(({ total, breakdowns }) => {+ const instanceId = breakdowns[0]+ if (!instanceId) {+ return+ }+ const separatorIndex = instanceId.indexOf(LINK_INSTANCE_SEPARATOR)+ const indexEnd = instanceId.indexOf(LINK_INSTANCE_SEPARATOR, separatorIndex + 1)+ if (separatorIndex === -1 || indexEnd === -1) {+ return+ }+ const actionId = instanceId.slice(0, separatorIndex)+ const url = instanceId.slice(indexEnd + 1)+ if (!actionId || !url) {+ return+ }+ byActionId[actionId] = byActionId[actionId] || []+ byActionId[actionId].push({+ linkIndex: instanceId.slice(separatorIndex + 1, indexEnd),+ url,+ clicks: total,+ truncated: url.length >= EMAIL_LINK_URL_MAX_LENGTH,+ duplicateUrl: false,+ })+ })++ Object.values(byActionId).forEach((rows) => {+ // Two anchors pointing at the same URL are counted separately by design (a header logo and a+ // footer link, say). Without flagging them the table shows two identical-looking rows with+ // different counts, which reads as a double-count bug.+ const urlCounts = new Map<string, number>()+ rows.forEach((row) => urlCounts.set(row.url, (urlCounts.get(row.url) ?? 0) + 1))+ rows.forEach((row) => {+ row.duplicateUrl = (urlCounts.get(row.url) ?? 0) > 1+ })+ // Most-clicked first so the interesting links are visible without scrolling an expanded row.+ rows.sort((a, b) => b.clicks - a.clicks)+ })+ return byActionId+}+export type WorkflowSummaryMetric = 'started' | 'in_progress' | 'persons_messaged' | 'completed' | 'converted'export type EmailMetric =| 'email_sent'@@ -404,6 +475,8 @@ export interface workflowMetricsSummaryLogicValues {type: 'function_email'updated_at?: number | undefined} & Record<string, unknown>)[]+ emailLinkTotalsByActionId: Record<string, EmailLinkRow[]>+ emailLinkTotalsByActionIdLoading: booleanemailMetricsRows: EmailMetricRow[]emailTotalsByActionId: Record<string, Partial<Record<EmailMetric, number>>>emailTotalsByActionIdLoading: boolean@@ -511,6 +584,21 @@ export interface workflowMetricsSummaryLogicActions {}payload?: any}+ loadEmailLinkTotals: (_: any) => any+ loadEmailLinkTotalsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadEmailLinkTotalsSuccess: (+ emailLinkTotalsByActionId: Record<string, EmailLinkRow[]>,+ payload?: any+ ) => {+ emailLinkTotalsByActionId: Record<string, EmailLinkRow[]>+ payload?: any+ }loadEmailTotals: (_: any) => anyloadEmailTotalsFailure: (error: string,@@ -868,6 +956,29 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(},},],+ emailLinkTotalsByActionId: [+ {} as Record<string, EmailLinkRow[]>,+ {+ loadEmailLinkTotals: async (_, breakpoint) => {+ await breakpoint(10)+ const dateRange = values.getDateRangeAbsolute()+ const request: AppMetricsTotalsRequest = {+ appSource: values.params.appSource,+ appSourceId: values.params.appSourceId,+ breakdownBy: ['instance_id'],+ metricName: [EMAIL_LINK_METRIC_NAME],+ limit: EMAIL_LINK_TOTALS_LIMIT,+ dateFrom: dateRange.dateFrom.toISOString(),+ dateTo: dateRange.dateTo.toISOString(),+ }++ const totalsResponse = await loadAppMetricsTotals(request, values.currentTeam?.timezone ?? 'UTC')+ await breakpoint(10)++ return parseEmailLinkTotals(totalsResponse)+ },+ },+ ],pushTotalsByActionId: [{} as Record<string, Partial<Record<PushMetric, number>>>,{@@ -1246,6 +1357,7 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(afterMount(({ actions }) => {actions.loadEmailTotals({})+ actions.loadEmailLinkTotals({})actions.loadPushTotals({})actions.loadInProgressTotal({})actions.loadConversionStats({})@@ -1263,6 +1375,7 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(dateTo: values.params.dateTo,})actions.loadEmailTotals({})+ actions.loadEmailLinkTotals({})actions.loadPushTotals({})actions.loadConversionStats({})},