Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(analytics): link mobile email captures to desktop signups (#9342)

juliawest4ac7a211f055
diff --git a/apps/marketing/src/app/components/forms/FormMobileSignup.tsx b/apps/marketing/src/app/components/forms/FormMobileSignup.tsx
index ee36407dd8..17a07976b1 100644
--- a/apps/marketing/src/app/components/forms/FormMobileSignup.tsx
+++ b/apps/marketing/src/app/components/forms/FormMobileSignup.tsx
@@ -1,9 +1,8 @@
import { useNavigate } from '@solidjs/router';
import { createSignal, Show } from 'solid-js';
-import { analytics } from '../../utils/utilAnalytic';
import {
- isLikelyEmail,
MOBILE_SIGNUP_SENT_PATH,
+ recordMobileSignupSubmitted,
submitMobileSignup,
} from '../../utils/utilMobileSignup';
@@ -46,8 +45,11 @@ export function FormMobileSignup(props: FormMobileSignupProps) {
const submit = async () => {
if (pending()) return;
- const trimmed = email().trim();
- if (!isLikelyEmail(trimmed)) {
+ const normalized = recordMobileSignupSubmitted(email(), {
+ buttonName: props.buttonName,
+ pageLocation: window.location.href,
+ });
+ if (!normalized) {
setError('Enter a valid email address.');
focusEmail();
return;
@@ -55,12 +57,8 @@ export function FormMobileSignup(props: FormMobileSignupProps) {
setError(null);
setPending(true);
- analytics.track('mobile_signup_submitted', {
- page_location: window.location.href,
- button_name: props.buttonName,
- });
- const result = await submitMobileSignup(trimmed);
+ const result = await submitMobileSignup(normalized);
setPending(false);
if (!result.ok) {
@@ -74,7 +72,7 @@ export function FormMobileSignup(props: FormMobileSignupProps) {
// The email rides along in history state as well as session storage, so
// the confirmation page can name the address (and dedupe its conversion
// fire) even where storage is unavailable.
- navigate(MOBILE_SIGNUP_SENT_PATH, { state: { email: trimmed } });
+ navigate(MOBILE_SIGNUP_SENT_PATH, { state: { email: normalized } });
};
const buttonLabel = () =>
diff --git a/apps/marketing/src/app/utils/utilAnalytic.ts b/apps/marketing/src/app/utils/utilAnalytic.ts
index 094ca735a7..041d71cc55 100644
--- a/apps/marketing/src/app/utils/utilAnalytic.ts
+++ b/apps/marketing/src/app/utils/utilAnalytic.ts
@@ -1,5 +1,10 @@
import { isServer } from 'solid-js/web';
import { createDeferredPosthog } from './utilDeferredPosthog';
+import {
+ mobileCaptureDevice,
+ mobileCaptureSetOnce,
+ normalizeAnalyticsEmail,
+} from './utilMobileCaptureIdentity';
declare const gtag: (
command: 'config' | 'event' | 'js',
@@ -227,20 +232,29 @@ const createAnalytics = () => {
};
/**
- * Attaches a known email to the current visitor across providers, so a lead
- * captured on the site is the same person downstream marketing automation
- * and the app's post-signup events see. Also feeds Meta's advanced matching
- * (`em`), which materially improves ad attribution for the lead.
+ * Attaches the captured email to the current visitor before the submit
+ * event. PostHog's distinct id is the normalized email, so the event is
+ * captured on an identified person. Also feeds Meta's advanced matching
+ * (`em`) before the confirmation page fires Lead.
*/
- const identifyEmail = (email: string) => {
+ const identifyMobileCapture = (email: string) => {
if (disabled) {
return;
}
+ const distinctId = normalizeAnalyticsEmail(email);
+ if (!distinctId) return;
tryCatch(() => {
- gtag('config', GA_ID, { user_id: email, email });
- fbq('init', META_PIXEL_ID, { em: email });
+ gtag('config', GA_ID, { user_id: distinctId, email: distinctId });
+ fbq('init', META_PIXEL_ID, { em: distinctId });
}, '[Analytics] Failed to identify visitor:');
- posthog?.identify(email);
+ posthog?.identify(
+ distinctId,
+ mobileCaptureSetOnce({
+ capturedAt: new Date().toISOString(),
+ device: mobileCaptureDevice(navigator.userAgent),
+ search: window.location.search,
+ })
+ );
};
const trackPosthog = (event: string, data?: Record<string, unknown>) => {
@@ -253,7 +267,7 @@ const createAnalytics = () => {
trackPosthog,
trackMeta,
trackGoogleConversion,
- identifyEmail,
+ identifyMobileCapture,
};
};
diff --git a/apps/marketing/src/app/utils/utilBaseUrl.test.ts b/apps/marketing/src/app/utils/utilBaseUrl.test.ts
new file mode 100644
index 0000000000..8cdcbca7bc
--- /dev/null
+++ b/apps/marketing/src/app/utils/utilBaseUrl.test.ts
@@ -0,0 +1,33 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { capturedAttribution } from './utilBaseUrl';
+
+afterEach(() => {
+ sessionStorage.clear();
+ window.history.replaceState({}, '', '/');
+});
+
+describe('capturedAttribution', () => {
+ it('keeps ad parameters after the query string is gone and drops anything else', () => {
+ sessionStorage.clear();
+ window.history.replaceState(
+ {},
+ '',
+ '/?utm_source=facebook&utm_medium=paid&utm_campaign=spring&fbclid=IwAR&ref=friend'
+ );
+
+ expect(capturedAttribution()).toEqual({
+ utm_source: 'facebook',
+ utm_medium: 'paid',
+ utm_campaign: 'spring',
+ fbclid: 'IwAR',
+ });
+
+ window.history.replaceState({}, '', '/mobile-signup');
+ expect(capturedAttribution()).toEqual({
+ utm_source: 'facebook',
+ utm_medium: 'paid',
+ utm_campaign: 'spring',
+ fbclid: 'IwAR',
+ });
+ });
+});
diff --git a/apps/marketing/src/app/utils/utilBaseUrl.ts b/apps/marketing/src/app/utils/utilBaseUrl.ts
index 364d6553bf..f74e3ce9a4 100644
--- a/apps/marketing/src/app/utils/utilBaseUrl.ts
+++ b/apps/marketing/src/app/utils/utilBaseUrl.ts
@@ -69,18 +69,36 @@ const captureAttributionParams = (): URLSearchParams => {
}
};
-const attributionParams = captureAttributionParams();
+let attributionParams = captureAttributionParams();
+
+/**
+ * Ad parameters captured from the landing URL, including ones stored before a
+ * client-side navigation dropped the query string. Sent with the mobile
+ * email capture so the desktop link can carry them.
+ */
+export const capturedAttribution = (): Record<string, string> => {
+ attributionParams = captureAttributionParams();
+ const result: Record<string, string> = {};
+ for (const [key, value] of attributionParams) {
+ if (value) result[key] = value;
+ }
+ return result;
+};
/** App URL (e.g. `/app/welcome`) with any captured attribution params appended. */
export const buildAppUrl = (path: string): string => {
const url = new URL(`${APP_BASE_URL}${path}`);
- attributionParams.forEach((value, key) => url.searchParams.set(key, value));
+ for (const [key, value] of attributionParams) {
+ url.searchParams.set(key, value);
+ }
return url.toString();
};
/** Google SSO URL with any captured attribution params appended. */
export const buildGoogleSsoUrl = (): string => {
const url = new URL(GOOGLE_SSO_URL);
- attributionParams.forEach((value, key) => url.searchParams.set(key, value));
+ for (const [key, value] of attributionParams) {
+ url.searchParams.set(key, value);
+ }
return url.toString();
};
diff --git a/apps/marketing/src/app/utils/utilDeferredPosthog.test.ts b/apps/marketing/src/app/utils/utilDeferredPosthog.test.ts
index 6fa6b52e8f..53a85cc1e7 100644
--- a/apps/marketing/src/app/utils/utilDeferredPosthog.test.ts
+++ b/apps/marketing/src/app/utils/utilDeferredPosthog.test.ts
@@ -7,10 +7,24 @@ const settle = async () => {
const setup = () => {
const order: string[] = [];
+ const distinctIdsAtCapture: string[] = [];
+ let distinctId = 'anonymous';
const client = {
init: vi.fn(() => order.push('init')),
- capture: vi.fn((event: string) => order.push(event)),
- identify: vi.fn((email: string) => order.push(`identify:${email}`)),
+ capture: vi.fn((event: string) => {
+ order.push(event);
+ distinctIdsAtCapture.push(distinctId);
+ }),
+ identify: vi.fn(
+ (
+ email: string,
+ _properties?: Record<string, unknown>,
+ _setOnce?: Record<string, unknown>
+ ) => {
+ distinctId = email;
+ order.push(`identify:${email}`);
+ }
+ ),
set_config: vi.fn(() => order.push('automatic pageviews')),
};
let resolve!: (value: typeof client) => void;
@@ -21,7 +35,14 @@ const setup = () => {
})
);
const analytics = createDeferredPosthog('public-key', load);
- return { analytics, load, client, order, resolve: () => resolve(client) };
+ return {
+ analytics,
+ load,
+ client,
+ order,
+ distinctIdsAtCapture,
+ resolve: () => resolve(client),
+ };
};
describe('deferred website PostHog', () => {
@@ -174,6 +195,51 @@ describe('deferred website PostHog', () => {
]);
});
+ it('identifies the normalized email before the following capture', async () => {
+ window.history.replaceState(
+ {},
+ '',
+ '/mobile-signup?utm_source=ig&utm_medium=paid&utm_campaign=spring&utm_content=story&fbclid=click&gclid=ads'
+ );
+ const fixture = setup();
+ fixture.analytics.identify(' [email protected] ', {
+ mobile_capture_at: '2026-10-14T12:00:00.000Z',
+ mobile_capture_device: 'mobile',
+ });
+ fixture.analytics.capture('mobile_signup_submitted', {
+ button_name: 'mobile_signup_page',
+ });
+ await settle();
+ fixture.resolve();
+ await settle();
+
+ expect(fixture.order).toEqual([
+ 'init',
+ '$pageview',
+ 'identify:[email protected]',
+ 'mobile_signup_submitted',
+ 'automatic pageviews',
+ ]);
+ expect(fixture.distinctIdsAtCapture).toEqual([
+ 'anonymous',
+ ]);
+ expect(fixture.client.identify).toHaveBeenCalledWith(
+ { email: '[email protected]' },
+ expect.objectContaining({
+ utm_source: 'ig',
+ utm_medium: 'paid',
+ utm_campaign: 'spring',
+ utm_content: 'story',
+ fbclid: 'click',
+ mobile_capture_at: '2026-10-14T12:00:00.000Z',
+ mobile_capture_device: 'mobile',
+ })
+ );
+ expect(fixture.client.identify.mock.calls[0]?.[2]?.gclid).toBeUndefined();
+ });
+
it('starts in background tabs where animation frames are suspended', async () => {
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
const fixture = setup();
diff --git a/apps/marketing/src/app/utils/utilDeferredPosthog.ts b/apps/marketing/src/app/utils/utilDeferredPosthog.ts
index 137cda5373..d800ab9815 100644
--- a/apps/marketing/src/app/utils/utilDeferredPosthog.ts
+++ b/apps/marketing/src/app/utils/utilDeferredPosthog.ts
@@ -1,4 +1,5 @@
import type { CaptureOptions, PostHogConfig } from 'posthog-js';
+import { pickMobileCaptureAttribution } from './utilMobileCaptureIdentity';
type Properties = Record<string, unknown>;
@@ -24,7 +25,7 @@ type PendingEvent =
properties: Properties;
timestamp: Date;
}
- | { type: 'identify'; email: string };
+ | { type: 'identify'; email: string; setOnce?: Properties };
const pageProperties = (): Properties => ({
$current_url: window.location.href,
@@ -111,7 +112,17 @@ export const createDeferredPosthog = (
// A rejected individual event must not strand later captures/identity.
try {
if (next.type === 'identify') {
- client.identify(next.email, { email: next.email }, initialProperties);
+ // Landing params survive client-side navigation that drops the query
+ // string. `$set_once` from the caller wins when both have a key.
+ client.identify(
+ next.email,
+ { email: next.email },
+ {
+ ...initialProperties,
+ ...pickMobileCaptureAttribution(campaign),
+ ...next.setOnce,
+ }
+ );
} else {
client.capture(next.event, next.properties, {
timestamp: next.timestamp,
@@ -179,8 +190,10 @@ export const createDeferredPosthog = (
return {
capture,
- identify: (email: string) => {
- pending.push({ type: 'identify', email });
+ identify: (email: string, setOnce?: Properties) => {
+ const distinctId = email.trim().toLowerCase();
+ if (!distinctId) return;
+ pending.push({ type: 'identify', email: distinctId, setOnce });
if (client) drain();
else start();
},
diff --git a/apps/marketing/src/app/utils/utilMobileCaptureIdentity.test.ts b/apps/marketing/src/app/utils/utilMobileCaptureIdentity.test.ts
new file mode 100644
index 0000000000..88a0033804
--- /dev/null
+++ b/apps/marketing/src/app/utils/utilMobileCaptureIdentity.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+import {
+ mobileCaptureDevice,
+ mobileCaptureSetOnce,
+ normalizeAnalyticsEmail,
+ pickMobileCaptureAttribution,
+} from './utilMobileCaptureIdentity';
+
+describe('mobile capture identity', () => {
+ it('normalizes email casing and surrounding space', () => {
+ expect(normalizeAnalyticsEmail(' [email protected] ')).toBe(
+ );
+ expect(normalizeAnalyticsEmail(null)).toBe('');
+ });
+
+ it.each([
+ ['Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)', 'mobile'],
+ ['Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X)', 'tablet'],
+ ['Mozilla/5.0 (Linux; Android 14; Pixel) Mobile', 'mobile'],
+ ['Mozilla/5.0 (Linux; Android 14; SM-T870)', 'tablet'],
+ ['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', 'desktop'],
+ ])('classifies %s as %s', (userAgent, device) => {
+ expect(mobileCaptureDevice(userAgent)).toBe(device);
+ });
+
+ it('keeps the ad click ids the capture should remember', () => {
+ expect(
+ mobileCaptureSetOnce({
+ capturedAt: '2026-10-14T12:00:00.000Z',
+ device: 'mobile',
+ search:
+ '?utm_source=ig&utm_medium=paid&utm_campaign=spring&utm_content=story&utm_term=skip&fbclid=click&gclid=ads',
+ })
+ ).toEqual({
+ mobile_capture_at: '2026-10-14T12:00:00.000Z',
+ mobile_capture_device: 'mobile',
+ utm_source: 'ig',
+ utm_medium: 'paid',
+ utm_campaign: 'spring',
+ utm_content: 'story',
+ fbclid: 'click',
+ });
+ expect(
+ pickMobileCaptureAttribution({
+ utm_source: 'ig',
+ gclid: 'ads',
+ fbclid: '',
+ })
+ ).toEqual({ utm_source: 'ig' });
+ });
+});
diff --git a/apps/marketing/src/app/utils/utilMobileCaptureIdentity.ts b/apps/marketing/src/app/utils/utilMobileCaptureIdentity.ts
new file mode 100644
index 0000000000..9624225cc3
--- /dev/null
+++ b/apps/marketing/src/app/utils/utilMobileCaptureIdentity.ts
@@ -0,0 +1,57 @@
+/**
+ * Identity payload for the phone email-capture flow.
+ *
+ * The web app has a copy in `apps/web/src/lib/analytics/mobileCaptureIdentity.ts`.
+ * Keep the two in step: the marketing site cannot import the app.
+ */
+
+export const MOBILE_CAPTURE_ATTRIBUTION_KEYS = [
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_content',
+ 'fbclid',
+] as const;
+
+/** Distinct id for a captured email. Mixed case must not create a second person. */
+export const normalizeAnalyticsEmail = (
+ email: string | null | undefined
+): string => (email ?? '').trim().toLowerCase();
+
+/** Coarse device label stored once on the captured person. */
+export const mobileCaptureDevice = (userAgent: string): string => {
+ if (/iPad|Tablet|PlayBook|Silk/i.test(userAgent)) return 'tablet';
+ if (/Android/i.test(userAgent) && !/Mobile/i.test(userAgent)) return 'tablet';
+ if (/Mobi|iPhone|iPod|Android/i.test(userAgent)) return 'mobile';
+ return 'desktop';
+};
+
+/** Landing-page campaign fields worth keeping on the person (`$set_once`). */
+export const pickMobileCaptureAttribution = (
+ source: Record<string, unknown>
+): Record<string, string> => {
+ const picked: Record<string, string> = {};
+ for (const key of MOBILE_CAPTURE_ATTRIBUTION_KEYS) {
+ const value = source[key];
+ if (typeof value === 'string' && value) picked[key] = value;
+ }
+ return picked;
+};
+
+/** Person properties set once when the email is first captured. */
+export const mobileCaptureSetOnce = (input: {
+ capturedAt: string;
+ device: string;
+ search: string;
+}): Record<string, string> => {
+ const query = input.search.startsWith('?')
+ ? input.search.slice(1)
+ : input.search;
+ return {
+ mobile_capture_at: input.capturedAt,
+ mobile_capture_device: input.device,
+ ...pickMobileCaptureAttribution(
+ Object.fromEntries(new URLSearchParams(query))
+ ),
+ };
+};
diff --git a/apps/marketing/src/app/utils/utilMobileSignup.test.ts b/apps/marketing/src/app/utils/utilMobileSignup.test.ts
index 263720c48c..dfa3779967 100644
--- a/apps/marketing/src/app/utils/utilMobileSignup.test.ts
+++ b/apps/marketing/src/app/utils/utilMobileSignup.test.ts
@@ -1,6 +1,23 @@
-import { describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { isIOS } from './utilMobileSignup';
+const analytics = vi.hoisted(() => ({
+ order: [] as string[],
+ identifyMobileCapture: vi.fn((email: string) => {
+ analytics.order.push(`identify:${email}`);
+ }),
+ track: vi.fn((event: string, data?: Record<string, unknown>) => {
+ analytics.order.push(`${event}:${String(data?.button_name)}`);
+ }),
+}));
+
+vi.mock('./utilAnalytic', () => ({
+ analytics: {
+ identifyMobileCapture: analytics.identifyMobileCapture,
+ track: analytics.track,
+ },
+}));
+
describe('isIOS', () => {
it.each([
['Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)', 5, true],
@@ -12,3 +29,40 @@ describe('isIOS', () => {
expect(isIOS(userAgent, maxTouchPoints)).toBe(expected);
});
});
+
+describe('recordMobileSignupSubmitted', () => {
+ beforeEach(() => {
+ analytics.order.length = 0;
+ analytics.identifyMobileCapture.mockClear();
+ analytics.track.mockClear();
+ });
+
+ it('identifies the normalized email before mobile_signup_submitted', async () => {
+ const { recordMobileSignupSubmitted } = await import('./utilMobileSignup');
+ expect(
+ recordMobileSignupSubmitted(' [email protected] ', {
+ buttonName: 'mobile_signup_page',
+ pageLocation: 'https://macro.com/mobile-signup',
+ })
+ ).toBe('[email protected]');
+ expect(analytics.order).toEqual([
+ 'identify:[email protected]',
+ 'mobile_signup_submitted:mobile_signup_page',
+ ]);
+ expect(analytics.track).toHaveBeenCalledWith('mobile_signup_submitted', {
+ page_location: 'https://macro.com/mobile-signup',
+ button_name: 'mobile_signup_page',
+ });
+ });
+
+ it('does not identify or track an address the form would reject', async () => {
+ const { recordMobileSignupSubmitted } = await import('./utilMobileSignup');
+ expect(
+ recordMobileSignupSubmitted('not-an-email', {
+ buttonName: 'mobile_signup_page',
+ pageLocation: 'https://macro.com/mobile-signup',
+ })
+ ).toBeNull();
+ expect(analytics.order).toEqual([]);
+ });
+});
diff --git a/apps/marketing/src/app/utils/utilMobileSignup.ts b/apps/marketing/src/app/utils/utilMobileSignup.ts
index fe2ee60c9a..87b19451c8 100644
--- a/apps/marketing/src/app/utils/utilMobileSignup.ts
+++ b/apps/marketing/src/app/utils/utilMobileSignup.ts
@@ -1,5 +1,6 @@
import { analytics } from './utilAnalytic';
-import { buildAuthServiceUrl } from './utilBaseUrl';
+import { buildAuthServiceUrl, capturedAttribution } from './utilBaseUrl';
+import { normalizeAnalyticsEmail } from './utilMobileCaptureIdentity';
/**
* Mobile-web email capture, served by the site itself.
@@ -84,30 +85,56 @@ const WORK_EMAIL_REQUIRED = 'Please use your work email or Gmail';
export type MobileSignupResult = { ok: true } | { ok: false; message: string };
+/**
+ * Identifies the visitor as this email, then records `mobile_signup_submitted`
+ * on that person. Identification has to happen first: an event captured on the
+ * anonymous id does not reliably move onto the email person afterward.
+ *
+ * Returns the normalized email, or null when the address should not be sent.
+ */
+export const recordMobileSignupSubmitted = (
+ email: string,
+ input: { buttonName: string; pageLocation: string }
+): string | null => {
+ const normalized = normalizeAnalyticsEmail(email);
+ if (!isLikelyEmail(normalized)) return null;
+ analytics.identifyMobileCapture(normalized);
+ analytics.track('mobile_signup_submitted', {
+ page_location: input.pageLocation,
+ button_name: input.buttonName,
+ });
+ return normalized;
+};
+
/**
* Sends the "open Macro on your computer" email to `email` via the auth
- * service's public `/mobile-welcome-email` endpoint, and identifies the
- * visitor to the analytics providers so the lead is attributable.
+ * service's public `/mobile-welcome-email` endpoint.
*
- * Resolves with a visitor-facing message instead of throwing — every failure
- * mode here is something the person can act on (fix the address, wait, retry).
+ * The caller identifies the visitor and records `mobile_signup_submitted`
+ * first (`recordMobileSignupSubmitted`), so this request does not touch
+ * analytics. Resolves with a visitor-facing message instead of throwing —
+ * every failure mode here is something the person can act on (fix the
+ * address, wait, retry).
*/
export const submitMobileSignup = async (
email: string
): Promise<MobileSignupResult> => {
- const trimmed = email.trim();
- if (!isLikelyEmail(trimmed)) {
+ const normalized = normalizeAnalyticsEmail(email);
+ if (!isLikelyEmail(normalized)) {
return { ok: false, message: 'Enter a valid email address.' };
}
- analytics.identifyEmail(trimmed);
-
let response: Response;
try {
+ const attribution = capturedAttribution();
response = await fetch(buildAuthServiceUrl('/mobile-welcome-email'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ email: trimmed }),
+ body: JSON.stringify(
+ Object.keys(attribution).length > 0
+ ? { email: normalized, attribution }
+ : { email: normalized }
+ ),
});
} catch {
return { ok: false, message: 'Network error. Please try again.' };
@@ -116,7 +143,7 @@ export const submitMobileSignup = async (
// 200 covers both "sent" and `sent: false` (we already emailed this address).
// The confirmation page is accurate either way, so both advance.
if (response.ok) {
- writeSession(SUBMITTED_EMAIL_KEY, trimmed);
+ writeSession(SUBMITTED_EMAIL_KEY, normalized);
return { ok: true };
}
diff --git a/apps/web/src/features/auth/context/auth-context.tsx b/apps/web/src/features/auth/context/auth-context.tsx
index bf4d08a543..bb123b6d11 100644
--- a/apps/web/src/features/auth/context/auth-context.tsx
+++ b/apps/web/src/features/auth/context/auth-context.tsx
@@ -63,7 +63,12 @@ export type AuthContext = {
/** Refreshes everything that depends on who is signed in. */
completeLogin(): Promise<void>;
sendMobileWelcomeEmail(email: string): Promise<MobileWelcomeResult>;
- identify(user: { id: string; email: string | undefined }): void;
+ identify(user: {
+ id: string;
+ email: string | undefined;
+ /** Person properties set once. Mobile capture uses this for attribution. */
+ setOnce?: Record<string, string>;
+ }): void;
/** Ad conversions for a mobile-web lead, deduplicated by email. */
trackMobileSignupLead(email: string): void;
pageView(name: 'login' | 'signup'): void;
diff --git a/apps/web/src/features/auth/create-app-auth-context.ts b/apps/web/src/features/auth/create-app-auth-context.ts
index 6b0f6fa8be..a919806b8b 100644
--- a/apps/web/src/features/auth/create-app-auth-context.ts
+++ b/apps/web/src/features/auth/create-app-auth-context.ts
@@ -1,5 +1,6 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { MOBILE_WEB_SIGNUP_LEAD_VALUE } from '@app/lib/analytics/leadValues';
+import { adAttributionForCapture } from '@app/lib/analytics/signupAttribution';
import { GOOGLE_GMAIL_IDP } from '@core/auth/email';
import { toast } from '@core/component/Toast/Toast';
import { deriveIsAuthenticated } from '@core/context/user';
@@ -79,7 +80,10 @@ export function createAppAuthContext(): AuthContext {
},
completeLogin,
sendMobileWelcomeEmail: async (email) => {
- const result = await sendWelcomeEmail.mutateAsync(email);
+ const attribution = adAttributionForCapture();
+ const result = await sendWelcomeEmail.mutateAsync(
+ Object.keys(attribution).length > 0 ? { email, attribution } : { email }
+ );
if (result.isOk()) return { t: 'sent', alreadySent: !result.value.sent };
const code = result.error[0]?.code;
if (code === 'INVALID_EMAIL') return { t: 'invalid-email' };
@@ -90,6 +94,7 @@ export function createAppAuthContext(): AuthContext {
analytics.identify(user.id, {
email: user.email,
os: detect(navigator.userAgent)?.os?.replaceAll(' ', ''),
+ setOnce: user.setOnce,
}),
trackMobileSignupLead: (email) => {
// Lead feeds an existing custom conversion; Meta's Maximize Value
diff --git a/apps/web/src/features/auth/primitives/mobile-signup.ts b/apps/web/src/features/auth/primitives/mobile-signup.ts
index 2b224d5b04..c27cd0b71a 100644
--- a/apps/web/src/features/auth/primitives/mobile-signup.ts
+++ b/apps/web/src/features/auth/primitives/mobile-signup.ts
@@ -1,3 +1,8 @@
+import {
+ mobileCaptureDevice,
+ mobileCaptureSetOnce,
+ normalizeAnalyticsEmail,
+} from '@app/lib/analytics/mobileCaptureIdentity';
import { createSignal } from 'solid-js';
import type { AuthContext } from '../context/auth-context';
import { mobileWelcomeFailure } from '../core/mobile-welcome';
@@ -16,10 +21,18 @@ export function createMobileSignup(
const [submitted, setSubmitted] = createSignal<string>();
const submit = async (email: string) => {
- const address = email.trim();
+ const address = normalizeAnalyticsEmail(email);
// An empty submit keeps the visitor on the capture step.
if (!address || pending()) return;
- context.identify({ id: address, email: address });
+ context.identify({
+ id: address,
+ email: address,
+ setOnce: mobileCaptureSetOnce({
+ capturedAt: new Date().toISOString(),
+ device: mobileCaptureDevice(navigator.userAgent),
+ search: window.location.search,
+ }),
+ });
setPending(true);
try {
const result = await context.sendMobileWelcomeEmail(address);
diff --git a/apps/web/src/features/auth/tests/fake-auth-context.ts b/apps/web/src/features/auth/tests/fake-auth-context.ts
index 5eb24e139a..20f673b004 100644
--- a/apps/web/src/features/auth/tests/fake-auth-context.ts
+++ b/apps/web/src/features/auth/tests/fake-auth-context.ts
@@ -93,6 +93,9 @@ export function createFakeAuth(
const [events, setEvents] = createSignal<FakeAuthEvent[]>([]);
const [notifications, setNotifications] = createSignal<string[]>([]);
const [calls, setCalls] = createSignal<string[]>([]);
+ const [identifiedUsers, setIdentifiedUsers] = createSignal<
+ Parameters<AuthContext['identify']>[0][]
+ >([]);
const call = (name: string) => setCalls((list) => [...list, name]);
const update = (change: (draft: FakeAuthWorld) => void) => {
@@ -183,12 +186,23 @@ export function createFakeAuth(
? { t: 'sent', alreadySent: false }
: { t: outcome };
},
- identify: (user) => call(`identify:${user.id}`),
+ identify: (user) => {
+ call(`identify:${user.id}`);
+ setIdentifiedUsers((list) => [...list, user]);
+ },
trackMobileSignupLead: (email) => call(`lead:${email}`),
pageView: (name) => call(`pageView:${name}`),
track: (event, data) => setEvents((list) => [...list, { event, data }]),
notifyFailure: (message) => setNotifications((list) => [...list, message]),
};
- return { context, world, update, events, notifications, calls };
+ return {
+ context,
+ world,
+ update,
+ events,
+ notifications,
+ calls,
+ identifiedUsers,
+ };
}
diff --git a/apps/web/src/features/auth/views/mobile-web-signup-view.test.tsx b/apps/web/src/features/auth/views/mobile-web-signup-view.test.tsx
index 8f1c857881..b63cd541c3 100644
--- a/apps/web/src/features/auth/views/mobile-web-signup-view.test.tsx
+++ b/apps/web/src/features/auth/views/mobile-web-signup-view.test.tsx
@@ -23,17 +23,42 @@ const submit = (email: string) => {
};
describe('mobile-web sign-up', () => {
- it('emails a desktop link and records the lead', async () => {
+ it('emails a desktop link and records the lead on the normalized email', async () => {
+ window.history.replaceState(
+ {},
+ '',
+ '/?utm_source=ig&utm_medium=paid&utm_campaign=spring&utm_content=story&fbclid=click&gclid=ads'
+ );
const { fake } = setup();
- submit(' [email protected] ');
+ submit(' [email protected] ');
await screen.findByText('Macro is better on desktop.');
- expect(fake.calls()).toEqual(
+ const calls = fake.calls();
+ expect(calls).toEqual(
expect.arrayContaining([
- 'identify:[email protected]',
- 'mobileWelcome:[email protected]',
+ 'identify:[email protected]',
+ 'mobileWelcome:[email protected]',
])
);
+ expect(calls.indexOf('identify:[email protected]')).toBeLessThan(
+ calls.indexOf('mobileWelcome:[email protected]')
+ );
+ expect(fake.identifiedUsers()[0]).toMatchObject({
+ email: '[email protected]',
+ setOnce: {
+ mobile_capture_device: expect.any(String),
+ utm_source: 'ig',
+ utm_medium: 'paid',
+ utm_campaign: 'spring',
+ utm_content: 'story',
+ fbclid: 'click',
+ },
+ });
+ expect(fake.identifiedUsers()[0]?.setOnce?.mobile_capture_at).toMatch(
+ /^\d{4}-\d{2}-\d{2}T/
+ );
+ expect(fake.identifiedUsers()[0]?.setOnce?.gclid).toBeUndefined();
});
it('stays on the capture step for an empty or rejected address', async () => {
diff --git a/apps/web/src/lib/analytics/analytics.test.ts b/apps/web/src/lib/analytics/analytics.test.ts
index b73b0b242b..ab075366b6 100644
--- a/apps/web/src/lib/analytics/analytics.test.ts
+++ b/apps/web/src/lib/analytics/analytics.test.ts
@@ -3,6 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
platform: 'web' as 'web' | 'ios' | 'android' | 'desktop',
touch: false,
+ distinctId: 'anon-id',
+ identified: false,
capture: vi.fn(),
identify: vi.fn(),
init: vi.fn(),
@@ -31,6 +33,8 @@ vi.mock('posthog-js', () => ({
PostHog: class {
capture = mocks.capture;
identify = mocks.identify;
+ get_distinct_id = () => mocks.distinctId;
+ _isIdentified = () => mocks.identified;
init = mocks.init;
group = mocks.group;
resetGroups = mocks.resetGroups;
@@ -51,10 +55,23 @@ beforeEach(() => {
mocks.platform = 'web';
mocks.touch = false;
mocks.groups = {};
+ mocks.distinctId = 'anon-id';
+ mocks.identified = false;
+ localStorage.clear();
+ mocks.identify.mockImplementation((id: string) => {
+ // PostHog drops identify() when this browser is already identified as
+ // someone else. Callers have to merge instead of switching.
+ if (mocks.identified && mocks.distinctId !== id) return;
+ mocks.distinctId = id;
+ mocks.identified = true;
+ });
});
afterEach(() => {
document.head.replaceChildren();
+ document.cookie =
+ 'macro_mobile_email_attribution=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
+ window.history.replaceState({}, '', '/');
vi.unstubAllEnvs();
vi.unstubAllGlobals();
vi.restoreAllMocks();
@@ -323,3 +340,138 @@ describe('PostHog team group', () => {
expect(mocks.resetGroups).toHaveBeenCalledTimes(1);
});
});
+
+describe('mobile capture linked to the account', () => {
+ it('merges the normalized email into the account after identify', async () => {
+ const { analytics } = await import('./analytics');
+ analytics.identify('macro|[email protected]', {
+ email: '[email protected]',
+ });
+
+ expect(mocks.identify).toHaveBeenCalledWith('macro|[email protected]', {
+ email: '[email protected]',
+ });
+ expect(mocks.gtag).toHaveBeenCalledWith(
+ 'config',
+ expect.any(String),
+ expect.objectContaining({
+ user_id: 'macro|[email protected]',
+ email: '[email protected]',
+ })
+ );
+ expect(mocks.capture).toHaveBeenCalledWith('$merge_dangerously', {
+ alias: '[email protected]',
+ });
+ expect(mocks.distinctId).toBe('macro|[email protected]');
+
+ analytics.identify('macro|[email protected]', {
+ email: '[email protected]',
+ });
+ expect(mocks.capture).toHaveBeenCalledTimes(1);
+ });
+
+ it('merges the account into a browser already identified as that email', async () => {
+ mocks.distinctId = '[email protected]';
+ mocks.identified = true;
+ const { analytics } = await import('./analytics');
+
+ analytics.identify('macro|[email protected]', {
+ email: '[email protected]',
+ });
+
+ expect(mocks.distinctId).toBe('[email protected]');
+ expect(mocks.capture).toHaveBeenCalledWith('$merge_dangerously', {
+ alias: 'macro|[email protected]',
+ });
+ });
+
+ it('does not merge a browser identified as a different account', async () => {
+ mocks.distinctId = 'macro|[email protected]';
+ mocks.identified = true;
+ const { analytics } = await import('./analytics');
+
+ analytics.linkMobileCapturePerson(
+ );
+
+ expect(mocks.capture).not.toHaveBeenCalled();
+ });
+
+ it('sets mobile-capture properties once and does not merge the email into itself', async () => {
+ const { analytics } = await import('./analytics');
+ analytics.identify('[email protected]', {
+ email: '[email protected]',
+ setOnce: {
+ mobile_capture_at: '2026-10-14T12:00:00.000Z',
+ mobile_capture_device: 'mobile',
+ },
+ });
+
+ expect(mocks.identify).toHaveBeenCalledWith(
+ { email: '[email protected]' },
+ {
+ mobile_capture_at: '2026-10-14T12:00:00.000Z',
+ mobile_capture_device: 'mobile',
+ }
+ );
+ expect(mocks.capture).not.toHaveBeenCalled();
+ });
+});
+
+describe('mobile email signup attribution', () => {
+ it('copies the desktop link parameters onto the person and does not apply them again', async () => {
+ window.history.replaceState(
+ {},
+ '',
+ '/app/signup?signup_flow=mobile_email&utm_source=facebook&utm_campaign=spring'
+ );
+ const { rememberMobileEmailAttribution } = await import(
+ './signupAttribution'
+ );
+ rememberMobileEmailAttribution();
+ window.history.replaceState({}, '', '/app/onboarding');
+
+ const { analytics } = await import('./analytics');
+ analytics.identify('user-id', {});
+
+ expect(mocks.setPersonProperties).toHaveBeenCalledWith(
+ {
+ signup_flow: 'mobile_email',
+ utm_source: 'facebook',
+ utm_campaign: 'spring',
+ },
+ {
+ $initial_signup_flow: 'mobile_email',
+ $initial_utm_source: 'facebook',
+ $initial_utm_campaign: 'spring',
+ }
+ );
+ expect(mocks.setPersonProperties).toHaveBeenCalledTimes(1);
+
+ analytics.identify('other-user', {});
+ expect(mocks.setPersonProperties).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the desktop link parameters when applying them fails', async () => {
+ window.history.replaceState(
+ {},
+ '',
+ '/app/signup?signup_flow=mobile_email&utm_source=facebook'
+ );
+ const { rememberMobileEmailAttribution, mobileEmailPersonProperties } =
+ await import('./signupAttribution');
+ rememberMobileEmailAttribution();
+ window.history.replaceState({}, '', '/app/onboarding');
+ mocks.setPersonProperties.mockImplementationOnce(() => {
+ throw new Error('posthog down');
+ });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const { analytics } = await import('./analytics');
+ analytics.identify('user-id', {});
+
+ expect(mobileEmailPersonProperties()?.set.utm_source).toBe('facebook');
+ });
+});
diff --git a/apps/web/src/lib/analytics/analytics.ts b/apps/web/src/lib/analytics/analytics.ts
index 77a19cb74b..a555cf057a 100644
--- a/apps/web/src/lib/analytics/analytics.ts
+++ b/apps/web/src/lib/analytics/analytics.ts
@@ -21,7 +21,12 @@ import type { Team } from '@service-auth/generated/schemas/team';
import { type CaptureOptions, PostHog } from 'posthog-js';
import { match } from 'ts-pattern';
import { isIgnorableException, rewriteNativeFrameUrls } from './exceptionList';
+import { normalizeAnalyticsEmail } from './mobileCaptureIdentity';
import { getPlanAnalyticsProperties } from './planProperties';
+import {
+ clearMobileEmailAttribution,
+ mobileEmailPersonProperties,
+} from './signupAttribution';
/**
* Resolves the user's device context for analytics enrichment.
@@ -86,8 +91,29 @@ type TeamGroupInfo = Pick<Team, 'id' | 'name' | 'enterprise'>;
interface UserIdentifyInfo {
email: string;
os: string;
+ /** Person properties applied once (`$set_once`), not on the event. */
+ setOnce: Record<string, string>;
}
+const MERGED_EMAIL_KEY = 'macro_ph_merged_email:';
+
+const readMergedEmail = (userId: string): string | null => {
+ try {
+ return localStorage.getItem(MERGED_EMAIL_KEY + userId);
+ } catch {
+ return null;
+ }
+};
+
+const rememberMergedEmail = (userId: string, email: string) => {
+ try {
+ localStorage.setItem(MERGED_EMAIL_KEY + userId, email);
+ } catch {
+ // The merge was still sent. A repeat is safe; PostHog no-ops an id that
+ // already belongs to this person.
+ }
+};
+
interface PageViewOptions {
/** Override the page path (defaults to window.location.pathname) */
path?: string;
@@ -147,6 +173,9 @@ const initializePosthog = (instance: PostHog) => {
// reads window geometry, forcing a layout per scroll. The app shell never
// scrolls the window, so the depth it reports is always zero.
disable_scroll_properties: true,
+ // PostHog captures utm_* and click ids on its own. `signup_flow` is added
+ // on the mobile-email desktop link so that path is its own campaign field.
+ custom_campaign_params: ['signup_flow'],
prepare_external_dependency_script: (script) => {
const url = new URL(script.src);
@@ -326,24 +355,82 @@ const createAnalytics = () => {
}
};
+ /**
+ * Mobile capture identifies PostHog as the normalized email. This app and
+ * the create-user webhook use `macro|{email}`. `identify` only merges an
+ * anonymous id into an identified one, and `alias` refuses an id that was
+ * already passed to `identify`, so those two persons stay split.
+ * `$merge_dangerously` is the merge PostHog applies; the event's distinct
+ * id is the person that survives.
+ *
+ * The account id is preferred, matching server `sign_up`. When this browser
+ * is already identified as the email (in-app capture), `identify(accountId)`
+ * is dropped, so the account id is merged into that email person instead.
+ */
+ const linkMobileCapturePerson = (
+ userId: string,
+ email: string | null | undefined
+ ) => {
+ if (disabled) return;
+ const normalized = normalizeAnalyticsEmail(email);
+ if (!normalized || normalized === userId) return;
+ if (readMergedEmail(userId) === normalized) return;
+
+ try {
+ const current = posthog.get_distinct_id();
+ if (current === userId) {
+ posthog.capture('$merge_dangerously', { alias: normalized });
+ rememberMergedEmail(userId, normalized);
+ return;
+ }
+ if (current === normalized) {
+ posthog.capture('$merge_dangerously', { alias: userId });
+ rememberMergedEmail(userId, normalized);
+ }
+ } catch (e) {
+ console.error('[Analytics] Failed to link mobile capture:', e);
+ }
+ };
+
const identify = (userID: string, info: Partial<UserIdentifyInfo>) => {
if (disabled) return;
+ const { setOnce, email: rawEmail, ...rest } = info;
+ const email = normalizeAnalyticsEmail(rawEmail);
+ const properties = {
+ ...rest,
+ ...(email ? { email } : {}),
+ };
+
try {
gtag('config', GA_ID, {
user_id: userID,
- ...(info.email && { email: info.email }),
- ...(info.os && { os: info.os }),
+ ...(email && { email }),
+ ...(rest.os && { os: rest.os }),
});
if (metaPixelEnabled) {
fbq('init', '639142540393286', {
external_id: userID,
- em: info.email,
+ em: email || undefined,
});
}
- posthog.identify(userID, { ...info });
+ if (setOnce && Object.keys(setOnce).length > 0) {
+ posthog.identify(userID, properties, setOnce);
+ } else {
+ posthog.identify(userID, properties);
+ }
+ linkMobileCapturePerson(userID, email);
+ // The desktop link's parameters are cookied before the identity-provider
+ // redirect strips the query string. Apply them only after this identify
+ // succeeds, then drop the cookie so a later account on this browser
+ // cannot inherit the campaign.
+ const attribution = mobileEmailPersonProperties();
+ if (attribution) {
+ posthog.setPersonProperties(attribution.set, attribution.once);
+ clearMobileEmailAttribution();
+ }
} catch (e) {
console.error('[Analytics] Failed to identify user:', e);
}
@@ -477,6 +564,7 @@ const createAnalytics = () => {
trackMeta,
trackGoogleConversion,
identify,
+ linkMobileCapturePerson,
setPlanProperties,
setInterfaceLanguage,
setTeamGroup,
@@ -499,6 +587,10 @@ export type AnalyticsInterface = {
data?: { value?: number; currency?: string; transaction_id?: string }
) => void;
identify: (userID: string, info: Partial<UserIdentifyInfo>) => void;
+ linkMobileCapturePerson: (
+ userId: string,
+ email: string | null | undefined
+ ) => void;
setPlanProperties: (licenseStatus: string | undefined) => void;
/** Records the interface language currently shown, for usage breakdowns. */
setInterfaceLanguage: (language: Language) => void;
diff --git a/apps/web/src/lib/analytics/mobileCaptureIdentity.test.ts b/apps/web/src/lib/analytics/mobileCaptureIdentity.test.ts
new file mode 100644
index 0000000000..ab9ff45335
--- /dev/null
+++ b/apps/web/src/lib/analytics/mobileCaptureIdentity.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import {
+ mobileCaptureDevice,
+ mobileCaptureSetOnce,
+ normalizeAnalyticsEmail,
+} from './mobileCaptureIdentity';
+
+describe('mobile capture identity', () => {
+ it('normalizes email casing and surrounding space', () => {
+ expect(normalizeAnalyticsEmail(' [email protected] ')).toBe(
+ );
+ expect(normalizeAnalyticsEmail(undefined)).toBe('');
+ });
+
+ it.each([
+ ['Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)', 'mobile'],
+ ['Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X)', 'tablet'],
+ ['Mozilla/5.0 (Linux; Android 14; Pixel) Mobile', 'mobile'],
+ ['Mozilla/5.0 (Linux; Android 14; SM-T870)', 'tablet'],
+ ['Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', 'desktop'],
+ ])('classifies %s as %s', (userAgent, device) => {
+ expect(mobileCaptureDevice(userAgent)).toBe(device);
+ });
+
+ it('keeps the ad click ids the capture should remember', () => {
+ expect(
+ mobileCaptureSetOnce({
+ capturedAt: '2026-10-14T12:00:00.000Z',
+ device: 'mobile',
+ search:
+ '?utm_source=ig&utm_medium=paid&utm_campaign=spring&utm_content=story&utm_term=skip&fbclid=click&gclid=ads',
+ })
+ ).toEqual({
+ mobile_capture_at: '2026-10-14T12:00:00.000Z',
+ mobile_capture_device: 'mobile',
+ utm_source: 'ig',
+ utm_medium: 'paid',
+ utm_campaign: 'spring',
+ utm_content: 'story',
+ fbclid: 'click',
+ });
+ });
+});
diff --git a/apps/web/src/lib/analytics/mobileCaptureIdentity.ts b/apps/web/src/lib/analytics/mobileCaptureIdentity.ts
new file mode 100644
index 0000000000..8eeec9ba65
--- /dev/null
+++ b/apps/web/src/lib/analytics/mobileCaptureIdentity.ts
@@ -0,0 +1,58 @@
+/**
+ * Identity payload for the phone email-capture flow.
+ *
+ * The marketing site has a copy in
+ * `apps/marketing/src/app/utils/utilMobileCaptureIdentity.ts`.
+ * Keep the two in step: the site cannot import the app.
+ */
+
+export const MOBILE_CAPTURE_ATTRIBUTION_KEYS = [
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_content',
+ 'fbclid',
+] as const;
+
+/** Distinct id for a captured email. Mixed case must not create a second person. */
+export const normalizeAnalyticsEmail = (
+ email: string | null | undefined
+): string => (email ?? '').trim().toLowerCase();
+
+/** Coarse device label stored once on the captured person. */
+export const mobileCaptureDevice = (userAgent: string): string => {
+ if (/iPad|Tablet|PlayBook|Silk/i.test(userAgent)) return 'tablet';
+ if (/Android/i.test(userAgent) && !/Mobile/i.test(userAgent)) return 'tablet';
+ if (/Mobi|iPhone|iPod|Android/i.test(userAgent)) return 'mobile';
+ return 'desktop';
+};
+
+/** Landing-page campaign fields worth keeping on the person (`$set_once`). */
+export const pickMobileCaptureAttribution = (
+ source: Record<string, unknown>
+): Record<string, string> => {
+ const picked: Record<string, string> = {};
+ for (const key of MOBILE_CAPTURE_ATTRIBUTION_KEYS) {
+ const value = source[key];
+ if (typeof value === 'string' && value) picked[key] = value;
+ }
+ return picked;
+};
+
+/** Person properties set once when the email is first captured. */
+export const mobileCaptureSetOnce = (input: {
+ capturedAt: string;
+ device: string;
+ search: string;
+}): Record<string, string> => {
+ const query = input.search.startsWith('?')
+ ? input.search.slice(1)
+ : input.search;
+ return {
+ mobile_capture_at: input.capturedAt,
+ mobile_capture_device: input.device,
+ ...pickMobileCaptureAttribution(
+ Object.fromEntries(new URLSearchParams(query))
+ ),
+ };
+};
diff --git a/apps/web/src/lib/analytics/signupAttribution.test.ts b/apps/web/src/lib/analytics/signupAttribution.test.ts
new file mode 100644
index 0000000000..c617266517
--- /dev/null
+++ b/apps/web/src/lib/analytics/signupAttribution.test.ts
@@ -0,0 +1,96 @@
+import { setCookie } from '@core/util/cookies';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ adAttributionForCapture,
+ clearMobileEmailAttribution,
+ mobileEmailPersonProperties,
+ rememberMobileEmailAttribution,
+} from './signupAttribution';
+
+const clearCookies = () => {
+ for (const part of document.cookie.split(';')) {
+ const name = part.split('=')[0]?.trim();
+ if (!name) continue;
+ document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
+ }
+};
+
+afterEach(() => {
+ clearCookies();
+ window.history.replaceState({}, '', '/');
+});
+
+describe('mobile email attribution', () => {
+ it('keeps the desktop link parameters after the query string is gone', () => {
+ window.history.replaceState(
+ {},
+ '',
+ '/app/signup?utm_source=facebook&utm_campaign=spring%20sale&fbclid=IwAR&signup_flow=mobile_email&unrelated=1'
+ );
+ rememberMobileEmailAttribution();
+ window.history.replaceState({}, '', '/app/onboarding?signed_up=true');
+
+ expect(mobileEmailPersonProperties()).toEqual({
+ set: {
+ signup_flow: 'mobile_email',
+ utm_source: 'facebook',
+ utm_campaign: 'spring sale',
+ fbclid: 'IwAR',
+ },
+ once: {
+ $initial_signup_flow: 'mobile_email',
+ $initial_utm_source: 'facebook',
+ $initial_utm_campaign: 'spring sale',
+ $initial_fbclid: 'IwAR',
+ },
+ });
+ });
+
+ it('ignores an ordinary visit and drops values that are not safe in a url', () => {
+ window.history.replaceState({}, '', '/app/signup?utm_source=facebook');
+ rememberMobileEmailAttribution();
+ window.history.replaceState({}, '', '/app/onboarding');
+ expect(mobileEmailPersonProperties()).toBeNull();
+
+ window.history.replaceState(
+ {},
+ '',
+ '/app/signup?signup_flow=mobile_email&utm_source=%3Cscript%3E&utm_medium=paid'
+ );
+ rememberMobileEmailAttribution();
+ window.history.replaceState({}, '', '/app/welcome');
+ expect(mobileEmailPersonProperties()).toEqual({
+ set: { signup_flow: 'mobile_email', utm_medium: 'paid' },
+ once: {
+ $initial_signup_flow: 'mobile_email',
+ $initial_utm_medium: 'paid',
+ },
+ });
+ });
+
+ it('sends the capture page parameters, with the url winning over an older cookie', () => {
+ setCookie('utm_source', 'newsletter', 1);
+ setCookie('utm_medium', 'email', 1);
+ window.history.replaceState(
+ {},
+ '',
+ '/app/mobile-email-signup?utm_source=facebook&page=1'
+ );
+ expect(adAttributionForCapture()).toEqual({
+ utm_source: 'facebook',
+ utm_medium: 'email',
+ });
+ });
+
+ it('forgets the stored parameters once they have been applied', () => {
+ window.history.replaceState(
+ {},
+ '',
+ '/app/signup?signup_flow=mobile_email&utm_source=facebook'
+ );
+ rememberMobileEmailAttribution();
+ window.history.replaceState({}, '', '/app/onboarding');
+ clearMobileEmailAttribution();
+ expect(mobileEmailPersonProperties()).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/analytics/signupAttribution.ts b/apps/web/src/lib/analytics/signupAttribution.ts
new file mode 100644
index 0000000000..887a9ba31e
--- /dev/null
+++ b/apps/web/src/lib/analytics/signupAttribution.ts
@@ -0,0 +1,174 @@
+import { setCookie } from '@core/util/cookies';
+
+/**
+ * Ad parameters forwarded from the page that captured a mobile email onto the
+ * desktop signup link. Keep this in step with `MobileWelcomeAttribution` in
+ * the auth service and `ATTRIBUTION_PARAMS` on the marketing site.
+ */
+export const AD_ATTRIBUTION_PARAMS = [
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_term',
+ 'utm_content',
+ 'fbclid',
+ 'gclid',
+ 'twclid',
+ 'rdt_cid',
+] as const;
+
+/** Query parameter the desktop link always carries. */
+export const SIGNUP_FLOW_PARAM = 'signup_flow';
+
+/** Value that marks a signup started from the mobile email capture. */
+export const MOBILE_EMAIL_SIGNUP_FLOW = 'mobile_email';
+
+/**
+ * One cookie for the whole set from the email link. Individual utm cookies
+ * can still hold an older visit, and mixing those with this link would
+ * attribute the signup to the wrong campaign.
+ */
+const MOBILE_EMAIL_ATTRIBUTION_COOKIE = 'macro_mobile_email_attribution';
+
+/** How long the desktop link's parameters survive a closed tab, in days. */
+const ATTRIBUTION_COOKIE_DAYS = 7;
+
+const MAX_ATTRIBUTION_VALUE_CHARS = 512;
+
+const acceptedAttributionValue = (value: string): string | null => {
+ const trimmed = value.trim();
+ if (!trimmed || [...trimmed].length > MAX_ATTRIBUTION_VALUE_CHARS) {
+ return null;
+ }
+ for (const char of trimmed) {
+ const code = char.codePointAt(0) ?? 0;
+ if (code < 32 || (code >= 127 && code <= 159)) return null;
+ if ('<>"\'`\\'.includes(char)) return null;
+ }
+ return trimmed;
+};
+
+const readCookie = (name: string): string | null => {
+ if (typeof document === 'undefined') return null;
+ const prefix = `${name}=`;
+ for (const part of document.cookie.split(';')) {
+ const trimmed = part.trim();
+ if (!trimmed.startsWith(prefix)) continue;
+ const raw = trimmed.slice(prefix.length);
+ try {
+ return decodeURIComponent(raw);
+ } catch {
+ return raw;
+ }
+ }
+ return null;
+};
+
+const searchParams = (): URLSearchParams => {
+ const search = new URLSearchParams(window.location.search);
+ const hashIndex = window.location.hash.indexOf('?');
+ if (hashIndex === -1) return search;
+ const hashParams = new URLSearchParams(
+ window.location.hash.slice(hashIndex + 1)
+ );
+ for (const [key, value] of hashParams) {
+ if (!search.get(key)) search.set(key, value);
+ }
+ return search;
+};
+
+const recordFrom = (params: URLSearchParams): Record<string, string> => {
+ const result: Record<string, string> = {};
+ const flow = params.get(SIGNUP_FLOW_PARAM);
+ if (flow === MOBILE_EMAIL_SIGNUP_FLOW) {
+ result[SIGNUP_FLOW_PARAM] = MOBILE_EMAIL_SIGNUP_FLOW;
+ }
+ for (const key of AD_ATTRIBUTION_PARAMS) {
+ const value = params.get(key);
+ const accepted = value ? acceptedAttributionValue(value) : null;
+ if (accepted) result[key] = accepted;
+ }
+ return result;
+};
+
+/**
+ * Stores the email link's parameters before signup leaves for the identity
+ * provider. No-ops unless this page is that link.
+ */
+export const rememberMobileEmailAttribution = (): void => {
+ if (typeof document === 'undefined') return;
+ const params = searchParams();
+ if (params.get(SIGNUP_FLOW_PARAM) !== MOBILE_EMAIL_SIGNUP_FLOW) return;
+ const kept = new URLSearchParams();
+ kept.set(SIGNUP_FLOW_PARAM, MOBILE_EMAIL_SIGNUP_FLOW);
+ for (const key of AD_ATTRIBUTION_PARAMS) {
+ const accepted = acceptedAttributionValue(params.get(key) ?? '');
+ if (accepted) kept.set(key, accepted);
+ }
+ setCookie(
+ MOBILE_EMAIL_ATTRIBUTION_COOKIE,
+ kept.toString(),
+ ATTRIBUTION_COOKIE_DAYS
+ );
+};
+
+/**
+ * Ad parameters for a capture that is still on the phone: the current URL,
+ * filled in from the utm cookies root preload already stores.
+ */
+export const adAttributionForCapture = (): Record<string, string> => {
+ const found: Record<string, string> = {};
+ if (typeof document === 'undefined') return found;
+ for (const key of AD_ATTRIBUTION_PARAMS) {
+ const fromCookie = readCookie(key);
+ const accepted = fromCookie ? acceptedAttributionValue(fromCookie) : null;
+ if (accepted) found[key] = accepted;
+ }
+ const params = searchParams();
+ for (const key of AD_ATTRIBUTION_PARAMS) {
+ const accepted = acceptedAttributionValue(params.get(key) ?? '');
+ if (accepted) found[key] = accepted;
+ }
+ return found;
+};
+
+/**
+ * Person properties for a desktop signup that followed the mobile email.
+ * Null when this browser did not open that link.
+ */
+export const mobileEmailPersonProperties = (): {
+ set: Record<string, string>;
+ once: Record<string, string>;
+} | null => {
+ const live = recordFrom(searchParams());
+ const storedRaw = readCookie(MOBILE_EMAIL_ATTRIBUTION_COOKIE);
+ const stored = storedRaw ? recordFrom(new URLSearchParams(storedRaw)) : null;
+ const attribution =
+ live[SIGNUP_FLOW_PARAM] === MOBILE_EMAIL_SIGNUP_FLOW ? live : stored;
+ if (
+ !attribution ||
+ attribution[SIGNUP_FLOW_PARAM] !== MOBILE_EMAIL_SIGNUP_FLOW
+ ) {
+ return null;
+ }
+
+ const set: Record<string, string> = {
+ [SIGNUP_FLOW_PARAM]: MOBILE_EMAIL_SIGNUP_FLOW,
+ };
+ const once: Record<string, string> = {
+ $initial_signup_flow: MOBILE_EMAIL_SIGNUP_FLOW,
+ };
+ for (const key of AD_ATTRIBUTION_PARAMS) {
+ const value = attribution[key];
+ if (!value) continue;
+ set[key] = value;
+ once[`$initial_${key}`] = value;
+ }
+ return { set, once };
+};
+
+/** Drops the stored desktop-link parameters after they were applied to a person. */
+export const clearMobileEmailAttribution = (): void => {
+ if (typeof document === 'undefined') return;
+ document.cookie = `${MOBILE_EMAIL_ATTRIBUTION_COOKIE}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
+};
diff --git a/apps/web/src/lib/queries/auth/mobile-welcome-email.ts b/apps/web/src/lib/queries/auth/mobile-welcome-email.ts
index e10ff1e902..c570861cac 100644
--- a/apps/web/src/lib/queries/auth/mobile-welcome-email.ts
+++ b/apps/web/src/lib/queries/auth/mobile-welcome-email.ts
@@ -8,8 +8,14 @@ import { useMutation } from '@tanstack/solid-query';
*/
export function useSendMobileWelcomeEmail() {
return useMutation(() => ({
- mutationFn: async (email: string) => {
- return authServiceClient.sendMobileWelcomeEmail(email);
+ mutationFn: async (input: {
+ email: string;
+ attribution?: Record<string, string>;
+ }) => {
+ return authServiceClient.sendMobileWelcomeEmail(
+ input.email,
+ input.attribution
+ );
},
}));
}
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index 3fe1da5a2c..6cd5d1b073 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -1219,7 +1219,16 @@ export const authServiceClient = {
return authServiceClient.initGithubLink(originalUrl);
},
- async sendMobileWelcomeEmail(email: string) {
+ async sendMobileWelcomeEmail(
+ email: string,
+ attribution?: Record<string, string>
+ ) {
+ const body: { email: string; attribution?: Record<string, string> } = {
+ email,
+ };
+ if (attribution && Object.keys(attribution).length > 0) {
+ body.attribution = attribution;
+ }
return safeFetch<
SendMobileWelcomeEmailResponse,
'RATE_LIMITED' | 'INVALID_EMAIL'
@@ -1227,7 +1236,7 @@ export const authServiceClient = {
`${authHost}/mobile-welcome-email`,
{
method: 'POST',
- body: JSON.stringify({ email }),
+ body: JSON.stringify(body),
credentials: 'include',
},
async (response) => {
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index a320faef73..34876ceb21 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -7,6 +7,7 @@ import {
useAnalytics,
} from '@app/lib/analytics/analytics-context';
import { PosthogProvider, usePosthog } from '@app/lib/analytics/posthog';
+import { rememberMobileEmailAttribution } from '@app/lib/analytics/signupAttribution';
import { trackSignupCompletion } from '@app/lib/analytics/signupCompletion';
import { setHotkeyRoot } from '@app/signal/hotkeyRoot';
import { IncomingCallEvents } from '@block-call/sidebar/incoming-calls';
@@ -61,6 +62,10 @@ import { AppRouterView } from './app-router-view';
import { useSyncLoginCookie } from './use-sync-login-cookie';
const rootPreload: RoutePreloadFunc = async (args) => {
+ // Before any await: the desktop link's ad parameters have to be stored
+ // before signup navigates away to the identity provider.
+ rememberMobileEmailAttribution();
+
await prefetchUserInfo();
// even though we are using the transformUrl prop, we may still need to replace the url in the history
@@ -148,6 +153,10 @@ function useUserInfoSideEffects() {
email: user.email,
os,
});
+ } else {
+ // Already identified, including as the mobile-capture email on this
+ // browser. identify() will not switch that browser to the account id.
+ analytics.linkMobileCapturePerson(user.id, user.email);
}
const planKey = `${user.id}:${user.licenseStatus}`;
diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.md
index 1499601f93..167542f693 100644
--- a/services/authentication_service/AGENTS.md
+++ b/services/authentication_service/AGENTS.md
@@ -83,6 +83,10 @@ inputs cannot select an agent, and ordinary user credentials remain unattributed
## Gotchas
+- `/mobile-welcome-email` copies allowlisted ad parameters from the capture
+ request onto the desktop signup link and always sets
+ `signup_flow=mobile_email`. The web app keeps that set on the PostHog person
+ when the account is identified. Do not take `signup_flow` from the request.
- Answer third-party failures as 502/503, not 500: match
`GithubError::Upstream(error)` before a route's 500 catch-all, and answer a
`FusionAuthClientError` whose `upstream()` is set with that error's
diff --git a/services/authentication_service/src/api/mobile_welcome_email.rs b/services/authentication_service/src/api/mobile_welcome_email.rs
index 3586daaef0..b17372291f 100644
--- a/services/authentication_service/src/api/mobile_welcome_email.rs
+++ b/services/authentication_service/src/api/mobile_welcome_email.rs
@@ -52,10 +52,44 @@ impl IntoResponse for SendMobileWelcomeEmailError {
}
}
+/// Ad parameters from the page that captured the email.
+///
+/// Only these keys are copied onto the desktop link. Anything else in the
+/// JSON is ignored, and values that are empty, too long, or not safe to put
+/// in a URL are dropped.
+#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)]
+pub struct MobileWelcomeAttribution {
+ #[serde(default)]
+ pub utm_source: Option<String>,
+ #[serde(default)]
+ pub utm_medium: Option<String>,
+ #[serde(default)]
+ pub utm_campaign: Option<String>,
+ #[serde(default)]
+ pub utm_term: Option<String>,
+ #[serde(default)]
+ pub utm_content: Option<String>,
+ #[serde(default)]
+ pub fbclid: Option<String>,
+ #[serde(default)]
+ pub gclid: Option<String>,
+ #[serde(default)]
+ pub twclid: Option<String>,
+ #[serde(default)]
+ pub rdt_cid: Option<String>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct SendMobileWelcomeEmailRequest {
/// The email address to send the welcome email to
pub email: String,
+ /// Ad parameters from the capture page. Omitted when the visit had none.
+ ///
+ /// Left out of the generated schema: the web and marketing clients send
+ /// the object directly, and the public SDK skips this endpoint.
+ #[serde(default)]
+ #[schema(ignore)]
+ pub attribution: MobileWelcomeAttribution,
}
#[derive(Debug, serde::Serialize, ToSchema)]
@@ -126,7 +160,9 @@ pub async fn handler(
}
// The "continue on desktop" link the phone confirmation screen promises.
- let url = desktop_signup_url(&default_redirect_url());
+ // The capture page's ad parameters ride along so the laptop session,
+ // which is a different browser, still has them for PostHog.
+ let url = desktop_signup_url(&default_redirect_url(), &req.attribution);
if let Err(e) = ctx
.ses_client
.send_email(
@@ -189,17 +225,72 @@ fn is_personal_email(email: &str) -> bool {
})
}
+/// Marks a signup that started from the mobile email capture, as opposed to
+/// someone who opened the ad on a computer and signed up directly.
+const SIGNUP_FLOW_PARAM: &str = "signup_flow";
+const SIGNUP_FLOW_MOBILE_EMAIL: &str = "mobile_email";
+
+/// Campaign names and click ids are short. Longer values are not attribution.
+const MAX_ATTRIBUTION_VALUE_CHARS: usize = 512;
+
/// Desktop signup page. The local frontend origin has no `/app` prefix.
-fn desktop_signup_url(base: &url::Url) -> String {
+///
+/// Copies the allowlisted ad parameters and always sets
+/// `signup_flow=mobile_email`. The flow parameter is not taken from the
+/// request, so a caller cannot relabel the link.
+fn desktop_signup_url(base: &url::Url, attribution: &MobileWelcomeAttribution) -> String {
let mut url = base.clone();
let path = url.path().trim_end_matches('/').to_string();
url.set_path(&format!("{path}/signup"));
url.set_query(None);
+ {
+ let mut pairs = url.query_pairs_mut();
+ for (key, value) in [
+ ("utm_source", attribution.utm_source.as_deref()),
+ ("utm_medium", attribution.utm_medium.as_deref()),
+ ("utm_campaign", attribution.utm_campaign.as_deref()),
+ ("utm_term", attribution.utm_term.as_deref()),
+ ("utm_content", attribution.utm_content.as_deref()),
+ ("fbclid", attribution.fbclid.as_deref()),
+ ("gclid", attribution.gclid.as_deref()),
+ ("twclid", attribution.twclid.as_deref()),
+ ("rdt_cid", attribution.rdt_cid.as_deref()),
+ ] {
+ let Some(value) = value.and_then(accepted_attribution_value) else {
+ continue;
+ };
+ pairs.append_pair(key, value);
+ }
+ pairs.append_pair(SIGNUP_FLOW_PARAM, SIGNUP_FLOW_MOBILE_EMAIL);
+ }
url.to_string()
}
+/// Keeps values that can sit in a query string and an HTML attribute.
+fn accepted_attribution_value(value: &str) -> Option<&str> {
+ let value = value.trim();
+ if value.is_empty() || value.chars().count() > MAX_ATTRIBUTION_VALUE_CHARS {
+ return None;
+ }
+ if value
+ .chars()
+ .any(|c| c.is_control() || matches!(c, '<' | '>' | '"' | '\'' | '`' | '\\'))
+ {
+ return None;
+ }
+ Some(value)
+}
+
+fn escape_html_attr(value: &str) -> String {
+ value
+ .replace('&', "&amp;")
+ .replace('"', "&quot;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+}
+
fn desktop_email_html(url: &str) -> String {
- let url = url.replace('&', "&amp;").replace('"', "&quot;");
+ let url = escape_html_attr(url);
format!(
r##"<!doctype html>
<html lang="en">
@@ -254,12 +345,105 @@ fn desktop_email_html(url: &str) -> String {
mod tests {
use super::*;
+ fn query(url: &str) -> Vec<(String, String)> {
+ url::Url::parse(url)
+ .unwrap()
+ .query_pairs()
+ .map(|(key, value)| (key.into_owned(), value.into_owned()))
+ .collect()
+ }
+
#[test]
fn desktop_link_points_at_signup() {
let prod = url::Url::parse("https://macro.com/app").unwrap();
- assert_eq!(desktop_signup_url(&prod), "https://macro.com/app/signup");
+ assert_eq!(
+ desktop_signup_url(&prod, &MobileWelcomeAttribution::default()),
+ "https://macro.com/app/signup?signup_flow=mobile_email"
+ );
let local = url::Url::parse("http://localhost:3000").unwrap();
- assert_eq!(desktop_signup_url(&local), "http://localhost:3000/signup");
+ assert_eq!(
+ desktop_signup_url(&local, &MobileWelcomeAttribution::default()),
+ "http://localhost:3000/signup?signup_flow=mobile_email"
+ );
+ }
+
+ #[test]
+ fn desktop_link_keeps_ad_parameters_from_the_capture_page() {
+ let prod = url::Url::parse("https://macro.com/app").unwrap();
+ let url = desktop_signup_url(
+ &prod,
+ &MobileWelcomeAttribution {
+ utm_source: Some(" facebook ".into()),
+ utm_medium: Some("paid".into()),
+ utm_campaign: Some("spring & summer".into()),
+ utm_term: Some("lookalike".into()),
+ utm_content: Some("video a".into()),
+ fbclid: Some("IwAR123".into()),
+ gclid: None,
+ twclid: None,
+ rdt_cid: None,
+ },
+ );
+ assert_eq!(
+ query(&url),
+ vec![
+ ("utm_source".into(), "facebook".into()),
+ ("utm_medium".into(), "paid".into()),
+ ("utm_campaign".into(), "spring & summer".into()),
+ ("utm_term".into(), "lookalike".into()),
+ ("utm_content".into(), "video a".into()),
+ ("fbclid".into(), "IwAR123".into()),
+ ("signup_flow".into(), "mobile_email".into()),
+ ]
+ );
+ }
+
+ #[test]
+ fn desktop_link_drops_values_that_cannot_be_a_query_parameter() {
+ let prod = url::Url::parse("https://macro.com/app").unwrap();
+ let url = desktop_signup_url(
+ &prod,
+ &MobileWelcomeAttribution {
+ utm_source: Some("facebook".into()),
+ utm_campaign: Some("<script>alert(1)</script>".into()),
+ utm_content: Some(" ".into()),
+ utm_term: Some("x".repeat(513)),
+ ..MobileWelcomeAttribution::default()
+ },
+ );
+ assert_eq!(
+ query(&url),
+ vec![
+ ("utm_source".into(), "facebook".into()),
+ ("signup_flow".into(), "mobile_email".into()),
+ ]
+ );
+ let html = desktop_email_html(&url);
+ assert!(html.contains("&amp;"));
+ assert!(!html.contains("<script"));
+ assert!(html.contains(DESKTOP_EMAIL_SUBJECT));
+ }
+
+ #[test]
+ fn attribution_json_uses_the_query_parameter_names() {
+ let parsed: SendMobileWelcomeEmailRequest = serde_json::from_str(
+ r#"{"email":"lead","attribution":{"utm_source":"facebook","fbclid":"x","signup_flow":"nope"}}"#,
+ )
+ .unwrap();
+ assert_eq!(parsed.attribution.utm_source.as_deref(), Some("facebook"));
+ assert_eq!(parsed.attribution.fbclid.as_deref(), Some("x"));
+ let url = desktop_signup_url(
+ &url::Url::parse("https://macro.com/app").unwrap(),
+ &parsed.attribution,
+ );
+ let has_mobile_email_flow = query(&url)
+ .iter()
+ .any(|(key, value)| key == "signup_flow" && value == "mobile_email");
+ assert!(has_mobile_email_flow);
+
+ let bare: SendMobileWelcomeEmailRequest =
+ serde_json::from_str(r#"{"email":"lead"}"#).unwrap();
+ assert!(bare.attribution.utm_source.is_none());
}
#[test]