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.

refactor(analytics): generic entity events + backend signup tracking (#4485)

teod5fb484c3656
diff --git a/js/app/packages/app/component/Launcher.tsx b/js/app/packages/app/component/Launcher.tsx
index c16977817c..649ad12e52 100644
--- a/js/app/packages/app/component/Launcher.tsx
+++ b/js/app/packages/app/component/Launcher.tsx
@@ -1,4 +1,3 @@
-import { analytics } from '@app/lib/analytics';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { setAutomationComposerOpen } from '@block-automation/component';
import { EMAIL_COMPOSE_TO_INPUT_ID } from '@block-email/constants';
@@ -100,11 +99,6 @@ const createBlock = async (spec: {
return;
}
- analytics.track('create_entity', {
- entityType: blockName,
- source: 'launcher',
- });
-
// If we are creating a new markdown document "from scratch" then we can let
// them instantly start editing
const createMdParams =
@@ -168,9 +162,12 @@ const createComponent = async (spec: {
export function runCreateAction(
blockName: BlockName | BlockAlias,
- options: { shouldInsert?: boolean } = {}
+ options: { shouldInsert?: boolean; source?: string } = {}
) {
const shouldInsert = options.shouldInsert ?? false;
+ // Creation analytics fire at the data-layer chokepoints (create.ts /
+ // projects.ts); `source` just attributes which surface initiated it.
+ const source = options.source ?? 'create_menu';
switch (blockName) {
case 'md':
@@ -182,6 +179,7 @@ export function runCreateAction(
title: '',
content: '',
projectId: undefined,
+ source,
}),
shouldInsert,
});
@@ -194,6 +192,7 @@ export function runCreateAction(
const result = await createCanvasFileFromJsonString({
json: JSON.stringify({ nodes: [], edges: [] }),
title: 'New Canvas',
+ source,
});
if ('error' in result) return;
return result.documentId ?? undefined;
@@ -215,6 +214,7 @@ export function runCreateAction(
createSnippet({
title: '',
content: '',
+ source,
}),
shouldInsert,
});
@@ -240,7 +240,7 @@ export function runCreateAction(
createBlock({
blockName: 'chat',
createFn: async () => {
- const result = await createChat();
+ const result = await createChat(undefined, { source });
if ('error' in result) {
return;
}
@@ -252,7 +252,7 @@ export function runCreateAction(
case 'project':
createBlock({
blockName: 'project',
- createFn: () => createProject({ name: 'New Folder' }),
+ createFn: () => createProject({ name: 'New Folder', source }),
shouldInsert,
});
return;
@@ -265,6 +265,7 @@ export function runCreateAction(
code: 'print("Hello, World!")',
extension: 'py',
title: 'New Code File',
+ source,
});
if (result.isErr()) return;
return result.value.documentId ?? undefined;
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index ecc652838a..1c499d6904 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -6,6 +6,7 @@ import { GlobalShareInboxConflictDialog } from '@app/component/ShareInboxConflic
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
import { ROUTER_BASE } from '@app/constants/routerBase';
import { PosthogProvider, usePosthog } from '@app/lib/analytics/posthog';
+import { trackSignupCompletion } from '@app/lib/analytics/signupCompletion';
import { setHotkeyRoot } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
import { CallKitSync } from '@channel/Call';
@@ -460,19 +461,21 @@ function UserInfoSideEffects() {
if (!user || !user.authenticated) return;
- if (posthog.instance._isIdentified() || identified) {
- return;
- }
+ if (!posthog.instance._isIdentified() && !identified) {
+ identified = true;
- identified = true;
+ const platform = detect(navigator.userAgent);
+ const os = platform?.os?.replaceAll(' ', '');
- const platform = detect(navigator.userAgent);
- const os = platform?.os?.replaceAll(' ', '');
+ analytics.identify(user.id, {
+ email: user.email,
+ os,
+ });
+ }
- analytics.identify(user.id, {
- email: user.email,
- os,
- });
+ // Fires sign_up + ad conversions once when the auth service flagged this
+ // session as a freshly created account (signed_up=true redirect param).
+ trackSignupCompletion(analytics, { id: user.id });
})
);
diff --git a/js/app/packages/app/component/auth/useSsoLogin.ts b/js/app/packages/app/component/auth/useSsoLogin.ts
index b49db0df5e..24cab754bf 100644
--- a/js/app/packages/app/component/auth/useSsoLogin.ts
+++ b/js/app/packages/app/component/auth/useSsoLogin.ts
@@ -17,10 +17,11 @@ export function useSsoLogin(opts?: { signupMode?: boolean }) {
const { initEmailLink } = useEmailLinks();
return async (idp_name: string) => {
- const analyticsEvent = opts?.signupMode ? 'sign_up' : 'login';
- const analyticsProviders: AnalyticsProvider[] = opts?.signupMode
- ? ['ga', 'meta-pixel', 'posthog']
- : ['posthog'];
+ // Both events are pre-redirect *intent*. The authoritative sign_up (and
+ // the ad conversions) fire post-auth when the backend marks the session
+ // as a freshly created account — see lib/analytics/signupCompletion.ts.
+ const analyticsEvent = opts?.signupMode ? 'sign_up_click' : 'login';
+ const analyticsProviders: AnalyticsProvider[] = ['posthog'];
const authUrl = new URL(`${SERVER_HOSTS['auth-service']}/login/sso`);
authUrl.searchParams.set('idp_name', idp_name);
diff --git a/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx
index 468278eb4c..ef95435e22 100644
--- a/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx
+++ b/js/app/packages/app/component/bulk-edit-entity/BulkMoveToProjectView.tsx
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { EntityIcon } from '@core/component/EntityIcon';
import { toast } from '@core/component/Toast/Toast';
import { scrollToKeepGap } from '@core/util/scrollToKeepGap';
@@ -404,6 +405,19 @@ export const BulkMoveToProjectView = (props: {
project: { id: projectId, name: projectName },
});
+ const isBulk = props.entities.length > 1;
+ for (const entity of props.entities) {
+ analytics.track('update_entity', {
+ entityType: entity.type,
+ entityId: entity.id,
+ property: 'parent_project',
+ newProjectId: projectId,
+ isBulk,
+ bulkCount: props.entities.length,
+ source: 'bulk_move',
+ });
+ }
+
props.onFinish();
} catch (error) {
console.error('Failed to move entities to folder:', error);
diff --git a/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx b/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx
index 63e9c37f18..2b0968e45b 100644
--- a/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/InteractiveOnboarding.tsx
@@ -133,14 +133,11 @@ function InteractiveOnboardingInner(props: InteractiveOnboardingProps) {
const advanceLesson = () => {
const current = state.currentLesson();
if (!current) return;
- analytics.track(
- `onboarding_step_${current.definition.id.replaceAll('-', '_')}`,
- {
- id: current.definition.id,
- index: current.index,
- state: 'completed',
- }
- );
+ analytics.track('tutorial_step', {
+ id: current.definition.id,
+ index: current.index,
+ state: 'completed',
+ });
state.completeLesson(current.definition.id);
setReadyToContinue(false);
setContinueLabel(undefined);
@@ -150,14 +147,11 @@ function InteractiveOnboardingInner(props: InteractiveOnboardingProps) {
const current = state.currentLesson();
if (!current) return;
- analytics.track(
- `onboarding_step_${current.definition.id.replaceAll('-', '_')}`,
- {
- id: current.definition.id,
- index: current.index,
- state: 'skipped',
- }
- );
+ analytics.track('tutorial_step', {
+ id: current.definition.id,
+ index: current.index,
+ state: 'skipped',
+ });
state.skipLesson(current.definition.id);
setReadyToContinue(false);
@@ -168,14 +162,11 @@ function InteractiveOnboardingInner(props: InteractiveOnboardingProps) {
const current = state.currentLesson();
if (!current || !readyToContinue()) return;
- analytics.track(
- `onboarding_step_${current.definition.id.replaceAll('-', '_')}`,
- {
- id: current.definition.id,
- index: current.index,
- state: 'completed',
- }
- );
+ analytics.track('tutorial_step', {
+ id: current.definition.id,
+ index: current.index,
+ state: 'completed',
+ });
state.completeLesson(current.definition.id);
setReadyToContinue(false);
@@ -328,8 +319,10 @@ function InteractiveOnboardingInner(props: InteractiveOnboardingProps) {
() => state.isFinished(),
(finished) => {
if (finished && !testMode) {
+ analytics.track('tutorial_completed', {
+ isFirstTime: props.isFirstTimeOnboarding === true,
+ });
if (props.isFirstTimeOnboarding) {
- analytics.track('onboarding_completed');
completeTutorial.mutate(undefined);
}
}
@@ -340,7 +333,9 @@ function InteractiveOnboardingInner(props: InteractiveOnboardingProps) {
onMount(() => {
if (state.currentIndex() > 0) return;
- analytics.track('onboarding_start');
+ analytics.track('tutorial_started', {
+ isFirstTime: props.isFirstTimeOnboarding === true,
+ });
});
createEffect(
@@ -349,14 +344,11 @@ function InteractiveOnboardingInner(props: InteractiveOnboardingProps) {
(lesson) => {
if (!lesson) return;
- analytics.track(
- `onboarding_step_${lesson.definition.id.replaceAll('-', '_')}`,
- {
- id: lesson.definition.id,
- index: lesson.index,
- state: 'viewed',
- }
- );
+ analytics.track('tutorial_step', {
+ id: lesson.definition.id,
+ index: lesson.index,
+ state: 'viewed',
+ });
}
)
);
diff --git a/js/app/packages/app/component/interactive-onboarding/InteractiveOnboardingModal.tsx b/js/app/packages/app/component/interactive-onboarding/InteractiveOnboardingModal.tsx
index eb8868f86c..480d9ac5da 100644
--- a/js/app/packages/app/component/interactive-onboarding/InteractiveOnboardingModal.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/InteractiveOnboardingModal.tsx
@@ -1,8 +1,4 @@
import { useAnalytics } from '@app/component/analytics-context';
-import {
- SIGNUP_LEAD_VALUE_BY_TIER,
- SIGNUP_LEAD_VALUE_DEFAULT,
-} from '@app/lib/analytics/leadValues';
import { globalSplitManager } from '@app/signal/splitLayout';
import MacroLogo from '@core/component/MacroLogo';
import { isMobile } from '@core/mobile/isMobile';
@@ -257,8 +253,12 @@ function InteractiveOnboardingModalLayout(props: {
}) {
const [phase, setPhase] = createSignal<ModalPhase>('start');
const onboarding = useOnboarding();
+ const analytics = useAnalytics();
const handleSkip = () => {
+ analytics.track('tutorial_skipped', {
+ isFirstTime: props.isFirstTimeOnboarding,
+ });
props.onClose();
};
@@ -295,37 +295,14 @@ export function InteractiveOnboardingModal(
props.defaultOpen ?? false
);
const completeTutorial = useCompleteTutorialMutation();
- const analytics = useAnalytics();
const open = () => props.open ?? internalOpen();
- // Closing the modal is the single chokepoint every completion path routes
- // through (finish lessons, skip tutorial, or dismiss), so the signup
- // conversion fires here rather than on lesson completion — the tour is
- // optional and most users skip it. Guarded because we send no dedup id.
- let signupConversionFired = false;
- const fireSignupConversion = () => {
- if (signupConversionFired || !props.isFirstTimeOnboarding) return;
- signupConversionFired = true;
-
- // `type` is set on the Stripe success redirect (see
- // use-onboarding-checkout.ts). Free users skip Stripe so the param is
- // absent — default to 'free'.
- const tier =
- new URLSearchParams(window.location.search).get('type') ?? 'free';
- const value = SIGNUP_LEAD_VALUE_BY_TIER[tier] ?? SIGNUP_LEAD_VALUE_DEFAULT;
- analytics.trackMeta('CompleteRegistration', {
- content_name: 'onboarding_launch',
- content_category: tier,
- value,
- currency: 'USD',
- });
- analytics.trackGoogleConversion('signup', { value, currency: 'USD' });
- };
-
+ // NOTE: signup/acquisition conversions used to fire when this modal closed.
+ // The tutorial is optional, so acquisition tracking now fires at actual
+ // account creation instead (see lib/analytics/signupCompletion.ts).
const setOpen = (nextOpen: boolean) => {
if (!nextOpen) {
- fireSignupConversion();
completeTutorial.mutate(undefined);
}
setInternalOpen(nextOpen);
diff --git a/js/app/packages/app/component/interactive-onboarding/MobileWebWelcome.tsx b/js/app/packages/app/component/interactive-onboarding/MobileWebWelcome.tsx
index bb2b5cc01b..4f28db6eff 100644
--- a/js/app/packages/app/component/interactive-onboarding/MobileWebWelcome.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/MobileWebWelcome.tsx
@@ -14,11 +14,6 @@ export default function MobileWebWelcome(props: MobileWebWelcomeProps) {
onMount(() => {
analytics.track('mobile_web_welcome_viewed');
- analytics.track('onboarding_step_welcome', {
- id: 'welcome',
- index: 0,
- state: 'viewed',
- });
});
const handleSignUp = () => {
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-mobile-create-button.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-mobile-create-button.tsx
index b6358ac75b..5b689641a4 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-mobile-create-button.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-mobile-create-button.tsx
@@ -43,38 +43,24 @@ export function SoupViewMobileCreateButton(props: {
const analytics = useAnalytics();
const [animating, setAnimating] = createSignal(false);
+ // Entity creation analytics fire at the data-layer chokepoints (create.ts
+ // etc.) once the entity actually exists; the dock only attributes `source`.
const VIEW_CREATE_ACTIONS: Partial<Record<ListView, () => void>> = {
agents: () => {
- analytics.track('create_entity', {
- entityType: 'chat',
- source: 'mobile_dock',
- });
- runCreateAction('chat');
+ runCreateAction('chat', { source: 'mobile_dock' });
},
mail: () => {
- analytics.track('create_entity', {
- entityType: 'email',
- source: 'mobile_dock',
- });
- runCreateAction('email');
+ runCreateAction('email', { source: 'mobile_dock' });
},
documents: () => {
analytics.track('create_menu_open', { from: 'mobile_dock' });
setCreateMenuOpen(true);
},
tasks: () => {
- analytics.track('create_entity', {
- entityType: 'task',
- source: 'mobile_dock',
- });
- runCreateAction('task');
+ runCreateAction('task', { source: 'mobile_dock' });
},
channels: () => {
- analytics.track('create_entity', {
- entityType: 'channel',
- source: 'mobile_dock',
- });
- runCreateAction('channel');
+ runCreateAction('channel', { source: 'mobile_dock' });
},
};
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsx
index 279a36c4cf..7216c274c8 100644
--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx
+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx
@@ -28,6 +28,7 @@ function usePageViewTracking(pageTitle: string) {
const analytics = useAnalytics();
onMount(() => {
analytics.pageView(pageTitle);
+ analytics.track('open_view', { viewId: pageTitle });
});
}
diff --git a/js/app/packages/app/lib/analytics/app-events.ts b/js/app/packages/app/lib/analytics/app-events.ts
index 6f2da95e4d..90f168f62d 100644
--- a/js/app/packages/app/lib/analytics/app-events.ts
+++ b/js/app/packages/app/lib/analytics/app-events.ts
@@ -1,15 +1,50 @@
+/**
+ * Payload shared by the generic entity lifecycle events (`create_entity`,
+ * `update_entity`, `delete_entity`, `share_entity`).
+ *
+ * Only the identifying fields are structured; any event-specific context
+ * (e.g. `hasDueDate` on task creation, `newProjectId` on a move) rides along
+ * as unstructured extra properties instead of minting a new event type.
+ */
+export type EntityEventPayload = {
+ /**
+ * Coarse entity/block type: 'md' | 'task' | 'snippet' | 'code' | 'canvas' |
+ * 'chat' | 'project' | 'channel' | 'email' | 'document' | ... Open-ended on
+ * purpose — different layers know the entity at different granularities.
+ */
+ entityType: string;
+ entityId?: string;
+ /** UI surface the action originated from (e.g. 'launcher', 'mobile_dock'). */
+ source?: string;
+} & Record<string, unknown>;
+
export type AppEvents = {
- sign_up: Record<string, unknown>; // payload - include link status
- sign_out: Record<string, unknown>;
+ // --- Acquisition & auth -------------------------------------------------
+ /**
+ * Account creation, browser side (GA only). The authoritative PostHog
+ * `sign_up` is emitted server-side from the create-user webhook; the
+ * browser fires this GA event plus the ad conversions when the backend
+ * flags the session via the `signed_up=true` redirect param. See
+ * signupCompletion.ts.
+ */
+ sign_up: Record<string, unknown>;
+ /** Signup intent: user clicked a sign-up CTA (pre-redirect, may not convert). */
+ sign_up_click: { method?: string } & Record<string, unknown>;
login: Record<string, unknown>; // payload - include link status
- onboarding_start: Record<string, unknown>;
- onboarding_step: Record<string, unknown>; // payload -
- onboarding_completed: Record<string, unknown>;
+ sign_out: Record<string, unknown>;
login_from_onboarding: Record<string, unknown>;
mobile_web_welcome_viewed: Record<string, unknown>;
mobile_web_signup_sent_viewed: Record<string, unknown>;
- onboarding_team_created: { teamId: string; inviteCount: number };
- onboarding_team_skipped: Record<string, unknown>;
+
+ // --- Interactive tutorial (optional; decoupled from acquisition) ---------
+ tutorial_started: { isFirstTime: boolean };
+ tutorial_step: {
+ id: string;
+ index: number;
+ state: 'viewed' | 'completed' | 'skipped';
+ };
+ tutorial_completed: { isFirstTime: boolean };
+ tutorial_skipped: Record<string, unknown>;
subscription_start: Record<string, unknown>;
subscription_cancel: Record<string, unknown>;
@@ -18,9 +53,6 @@ export type AppEvents = {
sidebar_click: Record<string, unknown>;
notifications_toggled: Record<string, unknown>;
- references_panel_open: { blockType: string };
- notifications_panel_open: { blockType: string };
- properties_panel_open: { blockType: string };
share_menu_open: { blockType: string };
copy_share_link: Record<string, unknown>;
@@ -46,24 +78,47 @@ export type AppEvents = {
hotkey_use: Record<string, unknown>;
preview_panel_use: Record<string, unknown>;
mentions_menu_use: { itemType: string };
+ snippets_menu_use: Record<string, unknown>;
split_created: { from: string };
- share_entity: Record<string, unknown>; // payload - entity type, location
- create_entity: Record<string, unknown>; // payload - entity type
- delete_entity: Record<string, unknown>; // payload - entity type
- update_entity: Record<string, unknown>; // payload - properties updated and entity type
+ // --- Entity lifecycle ----------------------------------------------------
+ // Fired at data-layer chokepoints (core/util/create.ts, FileList
+ // itemOperations, property-save mutations, share/forward flows, BlockLoader)
+ // so every UI surface is covered without per-surface instrumentation.
+ /**
+ * An entity was opened in a split (md, task, pdf, chat, email, channel,
+ * canvas, code, project, company, contact, ...). Fired from BlockLoader on
+ * successful load; nested blocks and preview-panel peeks are excluded.
+ */
+ open_entity: EntityEventPayload;
+ /**
+ * A top-level view was opened (soup list views like inbox/mail/documents/
+ * tasks/channels, plus home, search, and the compose views). Fired from the
+ * split-layout component registry.
+ */
+ open_view: { viewId: string } & Record<string, unknown>;
+ create_entity: EntityEventPayload;
+ update_entity: EntityEventPayload & {
+ /** Which property changed: 'name' | 'parent_project' | 'status' | ... */
+ property: string;
+ };
+ delete_entity: EntityEventPayload & { deleteType?: 'soft' | 'permanent' };
+ share_entity: EntityEventPayload & {
+ shareMethod?:
+ | 'public_link'
+ | 'channel'
+ | 'forward'
+ | 'attachment_public'
+ | (string & {});
+ };
task_copy_branch_name: Record<string, unknown>;
- search: Record<string, unknown>;
-
theme_changed: { themeId: string };
ai_message_sent: Record<string, unknown>;
ai_attachment_add: Record<string, unknown>;
- email_authorized: Record<string, unknown>;
- email_unauthorized: Record<string, unknown>;
email_message_sent: Record<string, unknown>;
channel_message_sent: Record<string, unknown>;
@@ -71,8 +126,20 @@ export type AppEvents = {
emoji: string;
action: 'add' | 'remove';
};
- channel_participant_add: Record<string, unknown>;
- channel_participant_remove: Record<string, unknown>;
+
+ // --- Calls ---------------------------------------------------------------
+ // Frontend call interactions. Authoritative lifecycle (ended, recording,
+ // summary) is server-driven and tracked backend-side.
+ call_action: {
+ action:
+ | 'join_clicked'
+ | 'started'
+ | 'joined'
+ | 'left'
+ | 'screen_share_toggled';
+ channelId: string;
+ callId?: string;
+ } & Record<string, unknown>;
block_pdf_definition_open: Record<string, unknown>;
block_pdf_section_open: Record<string, unknown>;
diff --git a/js/app/packages/app/lib/analytics/signupCompletion.ts b/js/app/packages/app/lib/analytics/signupCompletion.ts
new file mode 100644
index 0000000000..18d3a02019
--- /dev/null
+++ b/js/app/packages/app/lib/analytics/signupCompletion.ts
@@ -0,0 +1,131 @@
+/**
+ * Signup-completion tracking.
+ *
+ * `sign_up` used to fire only from the /signup page, *before* redirecting to
+ * SSO — so it counted intent rather than created accounts, and missed everyone
+ * who signed up through the regular SSO sign-in (which is where the website
+ * sends people). The ad-platform conversions were even further off: they fired
+ * when the (now optional) interactive tutorial modal closed.
+ *
+ * The authoritative product-analytics `sign_up` (PostHog) is emitted
+ * server-side from the create-user webhook, so every creation path counts
+ * exactly once even if the user never returns to the app. What remains here
+ * is the browser-only half: the ad-platform conversions (Meta pixel, Google
+ * Ads) plus the GA sign_up event, which need the click-id cookies and consent
+ * context that only exist in the browser. The auth service appends
+ * `signed_up=true` to the post-auth redirect; this module consumes that param
+ * once and fires them, regardless of which page or device started the flow.
+ */
+import type { AnalyticsInterface } from './analytics';
+import {
+ SIGNUP_LEAD_VALUE_BY_TIER,
+ SIGNUP_LEAD_VALUE_DEFAULT,
+} from './leadValues';
+
+const SIGNED_UP_PARAM = 'signed_up';
+const TRACKED_STORAGE_PREFIX = 'macro_sign_up_tracked:';
+
+/**
+ * Returns true if the URL carries `signed_up=true`, and removes it (from both
+ * the search string and, for the hash router, the hash query) so refreshes
+ * and copied links don't re-trigger.
+ */
+function readAndStripSignedUpParam(): boolean {
+ try {
+ const url = new URL(window.location.href);
+ let found = false;
+
+ if (url.searchParams.get(SIGNED_UP_PARAM) === 'true') {
+ found = true;
+ url.searchParams.delete(SIGNED_UP_PARAM);
+ }
+
+ // Tauri uses a hash router; the param can end up in the hash query.
+ const hashQueryIndex = url.hash.indexOf('?');
+ if (hashQueryIndex !== -1) {
+ const hashPath = url.hash.slice(0, hashQueryIndex);
+ const hashParams = new URLSearchParams(
+ url.hash.slice(hashQueryIndex + 1)
+ );
+ if (hashParams.get(SIGNED_UP_PARAM) === 'true') {
+ found = true;
+ hashParams.delete(SIGNED_UP_PARAM);
+ const rest = hashParams.toString();
+ url.hash = rest ? `${hashPath}?${rest}` : hashPath;
+ }
+ }
+
+ if (found) {
+ window.history.replaceState(window.history.state, '', url);
+ }
+ return found;
+ } catch {
+ return false;
+ }
+}
+
+function alreadyTracked(userId: string): boolean {
+ try {
+ return localStorage.getItem(TRACKED_STORAGE_PREFIX + userId) != null;
+ } catch {
+ return false;
+ }
+}
+
+function markTracked(userId: string) {
+ try {
+ localStorage.setItem(TRACKED_STORAGE_PREFIX + userId, '1');
+ } catch {
+ // localStorage unavailable — the stripped URL param still prevents most
+ // double-fires, and the Google conversion dedupes on transaction_id.
+ }
+}
+
+/**
+ * Fires the browser-side signup conversions (GA sign_up, Meta
+ * CompleteRegistration, Google Ads signup) exactly once for a freshly created
+ * account. The PostHog `sign_up` product event is NOT fired here — it comes
+ * from the create-user webhook on the backend. Call once the authenticated
+ * user is known (so the events can be attributed and deduped by user id).
+ * No-ops unless the URL carries the backend's `signed_up=true` marker.
+ */
+export function trackSignupCompletion(
+ analytics: AnalyticsInterface,
+ user: { id: string }
+) {
+ if (!readAndStripSignedUpParam()) return;
+ if (alreadyTracked(user.id)) return;
+ markTracked(user.id);
+
+ // GA4 recommended-event name; browser GA has the client id for attribution.
+ analytics.track('sign_up', {}, ['ga']);
+
+ // Paid signups return from Stripe with a `type` param; plain signups have
+ // no tier yet and count at the free-signup lead value. Purchase value is
+ // tracked separately via subscription_success. Checked in both the search
+ // and hash query for the same hash-router reason as the signed_up param.
+ const hashQueryIndex = window.location.hash.indexOf('?');
+ const hashParams =
+ hashQueryIndex !== -1
+ ? new URLSearchParams(window.location.hash.slice(hashQueryIndex + 1))
+ : null;
+ const tier =
+ new URLSearchParams(window.location.search).get('type') ??
+ hashParams?.get('type') ??
+ 'free';
+ const value = SIGNUP_LEAD_VALUE_BY_TIER[tier] ?? SIGNUP_LEAD_VALUE_DEFAULT;
+
+ analytics.trackMeta('CompleteRegistration', {
+ content_name: 'account_created',
+ content_category: tier,
+ value,
+ currency: 'USD',
+ });
+ analytics.trackGoogleConversion('signup', {
+ value,
+ currency: 'USD',
+ // Google dedupes server-side on transaction_id, so a re-fire from another
+ // device or cleared storage still counts once.
+ transaction_id: user.id,
+ });
+}
diff --git a/js/app/packages/block-email/util/makeAttachmentPublic.ts b/js/app/packages/block-email/util/makeAttachmentPublic.ts
index 95db67b7fb..811d340ef4 100644
--- a/js/app/packages/block-email/util/makeAttachmentPublic.ts
+++ b/js/app/packages/block-email/util/makeAttachmentPublic.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { toast } from '@core/component/Toast/Toast';
import { logger } from '@observability';
@@ -24,6 +25,12 @@ export const makeAttachmentPublic = async (attachmentId: string) => {
toast.success('Recipients can now view this file', {
subtext: 'File share permissions have been updated to public view-only',
});
+ analytics.track('share_entity', {
+ entityType: 'email_attachment',
+ entityId: attachmentId,
+ shareMethod: 'attachment_public',
+ accessLevel: 'view',
+ });
} else {
toast.alert('Recipients may not be able to view this file', {
subtext: 'Please consult the document owner to change share permissions',
diff --git a/js/app/packages/channel/Call/CallContext.tsx b/js/app/packages/channel/Call/CallContext.tsx
index 467cdbf656..784ec34933 100644
--- a/js/app/packages/channel/Call/CallContext.tsx
+++ b/js/app/packages/channel/Call/CallContext.tsx
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import {
isKrispNoiseFilterSupported,
KrispNoiseFilter,
@@ -1077,6 +1078,12 @@ function createCallState() {
try {
await r.localParticipant.setScreenShareEnabled(newSharing);
setStore('isScreenSharing', newSharing);
+ analytics.track('call_action', {
+ action: 'screen_share_toggled',
+ channelId: store.activeChannelId ?? '',
+ callId: store.activeCallId ?? undefined,
+ enabled: newSharing,
+ });
} catch (e) {
console.error('failed to toggle screen share', e);
}
diff --git a/js/app/packages/channel/Call/ChannelCallButton.tsx b/js/app/packages/channel/Call/ChannelCallButton.tsx
index 5bdc200b4d..a381d35e7e 100644
--- a/js/app/packages/channel/Call/ChannelCallButton.tsx
+++ b/js/app/packages/channel/Call/ChannelCallButton.tsx
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { useChannelTab } from '@channel/Channel/ChannelTabContext';
import { isMobile } from '@core/mobile/isMobile';
import PhoneIcon from '@icon/wide-call.svg';
@@ -28,8 +29,22 @@ export function ChannelCallButton(props: { channelId: string }) {
const handleClick = async () => {
if (call.isJoining()) return;
+ const wasExistingCall = isCallInProgress();
+ analytics.track('call_action', {
+ action: 'join_clicked',
+ channelId: props.channelId,
+ isExistingCall: wasExistingCall,
+ });
try {
await call.joinCall();
+ // A successful join with no call previously in progress means this user
+ // started the call. Fires once, from the starter's client.
+ if (!wasExistingCall) {
+ analytics.track('call_action', {
+ action: 'started',
+ channelId: props.channelId,
+ });
+ }
} catch (e) {
console.error('Call action failed', e);
}
diff --git a/js/app/packages/channel/Call/use-call.ts b/js/app/packages/channel/Call/use-call.ts
index 7ef268ce0d..4d2d65aaec 100644
--- a/js/app/packages/channel/Call/use-call.ts
+++ b/js/app/packages/channel/Call/use-call.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { useChannelsContext } from '@core/context/channels';
import { throwOnErr } from '@core/util/result';
import {
@@ -196,6 +197,10 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
clearAutoRejoinTimer();
void invalidateActiveCallQueries();
attachDisconnectListener();
+ analytics.track('call_action', {
+ action: 'joined',
+ channelId: channelId(),
+ });
},
// Keep this handler synchronous: we undo the optimistic join and show the
// error message right away. LiveKit disconnect and the server leave call
@@ -266,6 +271,11 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
try {
await callCtx.disconnectSession(leaveOptions);
options?.onLeave?.();
+ analytics.track('call_action', {
+ action: 'left',
+ channelId: id,
+ leaveReason: 'user_initiated',
+ });
} finally {
await leaveMutation.mutateAsync(id);
}
diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.ts
index 7e01b24e95..607239f852 100644
--- a/js/app/packages/core/component/FileList/itemOperations.ts
+++ b/js/app/packages/core/component/FileList/itemOperations.ts
@@ -127,6 +127,12 @@ export async function renameItem(args: {
return false;
}
+ analytics.track('update_entity', {
+ entityType: itemType,
+ entityId: id,
+ property: 'name',
+ });
+
return true;
}
@@ -200,6 +206,12 @@ export async function deleteItem(args: {
if (!removed) return false;
}
+ analytics.track('delete_entity', {
+ entityType: itemType,
+ entityId: id,
+ deleteType: 'soft',
+ });
+
refetchResources();
return true;
}
@@ -287,6 +299,14 @@ export async function moveToFolder(args: {
if (result.isErr()) {
return false;
}
+
+ analytics.track('update_entity', {
+ entityType: itemType,
+ entityId: id,
+ property: 'parent_project',
+ newProjectId: folderId,
+ });
+
refetchResources();
return true;
}
@@ -370,6 +390,13 @@ export async function copyItem(args: {
return null;
}
+ analytics.track('create_entity', {
+ entityType: itemType,
+ entityId: newId,
+ via: 'duplicate',
+ sourceEntityId: id,
+ });
+
refetchResources();
return newId;
}
@@ -507,7 +534,11 @@ export async function permanentlyDelete(args: {
return false;
}
- analytics.track('delete_entity', { entityType: itemType });
+ analytics.track('delete_entity', {
+ entityType: itemType,
+ entityId: id,
+ deleteType: 'permanent',
+ });
return true;
}
diff --git a/js/app/packages/core/component/ForwardToChannel.tsx b/js/app/packages/core/component/ForwardToChannel.tsx
index 84ac583e48..a749e892b9 100644
--- a/js/app/packages/core/component/ForwardToChannel.tsx
+++ b/js/app/packages/core/component/ForwardToChannel.tsx
@@ -287,6 +287,17 @@ export function ForwardToChannel(props: ForwardToChannelProps) {
};
};
+ const trackForwardShare = (targetType: 'channel' | 'user') => {
+ const attachment = asAttachment();
+ analytics.track('share_entity', {
+ entityType: attachment.entity_type,
+ entityId: attachment.entity_id || undefined,
+ shareMethod: 'forward',
+ targetType,
+ location: 'forward_to_channel',
+ });
+ };
+
function handleSubmit() {
let options = selectedOptions();
if (!options || options.length === 0) {
@@ -317,7 +328,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {
},
],
});
- analytics.track('share_entity', { location: 'forward_to_channel' });
+ trackForwardShare('user');
});
} else {
toast.failure('Message failed to send');
@@ -351,9 +362,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {
],
});
}
- analytics.track('share_entity', {
- location: 'forward_to_channel',
- });
+ trackForwardShare('channel');
}),
]);
} else {
@@ -382,7 +391,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {
],
});
}
- analytics.track('share_entity', { location: 'forward_to_channel' });
+ trackForwardShare('user');
});
}
}
diff --git a/js/app/packages/core/component/TopBar/ShareButton.tsx b/js/app/packages/core/component/TopBar/ShareButton.tsx
index 7b7187d47e..bf14f4f1ab 100644
--- a/js/app/packages/core/component/TopBar/ShareButton.tsx
+++ b/js/app/packages/core/component/TopBar/ShareButton.tsx
@@ -785,6 +785,13 @@ export function ShareModal(props: ShareModalProps) {
subtext: accessLevelText(accessLevel),
});
}
+
+ analytics.track('share_entity', {
+ entityType: props.itemType,
+ entityId: props.id,
+ shareMethod: 'channel',
+ accessLevel,
+ });
} else {
toast.alert('Failed to change channel access', {
subtext: 'Please try again',
@@ -828,6 +835,8 @@ export function ShareModal(props: ShareModalProps) {
analytics.track('share_entity', {
entityType: 'chat',
+ entityId: props.id,
+ shareMethod: 'public_link',
accessLevel,
isPublic: true,
});
@@ -859,6 +868,8 @@ export function ShareModal(props: ShareModalProps) {
analytics.track('share_entity', {
entityType: 'document',
+ entityId: props.id,
+ shareMethod: 'public_link',
accessLevel,
isPublic: true,
});
@@ -890,6 +901,8 @@ export function ShareModal(props: ShareModalProps) {
analytics.track('share_entity', {
entityType: 'project',
+ entityId: props.id,
+ shareMethod: 'public_link',
accessLevel,
isPublic: true,
});
diff --git a/js/app/packages/core/internal/BlockLoader.tsx b/js/app/packages/core/internal/BlockLoader.tsx
index ec837f9490..202308918a 100644
--- a/js/app/packages/core/internal/BlockLoader.tsx
+++ b/js/app/packages/core/internal/BlockLoader.tsx
@@ -145,6 +145,10 @@ Check that the load function does not return a preload source when the intent is
});
analytics.pageView(data.__block);
+ analytics.track('open_entity', {
+ entityType: data.__block,
+ entityId: props.id,
+ });
}
setData(() => data);
diff --git a/js/app/packages/core/util/create.ts b/js/app/packages/core/util/create.ts
index 0625c478b1..1c0cfa311f 100644
--- a/js/app/packages/core/util/create.ts
+++ b/js/app/packages/core/util/create.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { DEFAULT_CHAT_NAME } from '@block-chat/definition';
import type { CodeFileExtension } from '@block-code/util/languageSupport';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
@@ -29,6 +30,8 @@ type CreateMarkdownFileArgs = {
title?: string;
content?: string;
projectId?: string;
+ /** UI surface the creation originated from, for analytics. */
+ source?: string;
};
/**
@@ -63,6 +66,14 @@ export async function createMarkdownFile(
fileType: 'md',
});
refetchSoupEntity(documentId, 'document');
+
+ analytics.track('create_entity', {
+ entityType: 'md',
+ entityId: documentId,
+ projectId: args?.projectId,
+ source: args?.source,
+ });
+
return documentId;
}
@@ -71,6 +82,8 @@ type CreateTaskArgs = {
content?: string;
projectId?: string;
propertyValues?: PropertyInput[];
+ /** UI surface the creation originated from, for analytics. */
+ source?: string;
};
/**
@@ -126,6 +139,26 @@ export async function createTask(
subType: { type: 'task', is_completed: false },
});
refetchSoupEntity(documentId, 'document');
+
+ analytics.track('create_entity', {
+ entityType: 'task',
+ entityId: documentId,
+ projectId: args?.projectId,
+ source: args?.source,
+ hasAssignee: propertyValues.some(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.ASSIGNEES
+ ),
+ hasDueDate: propertyValues.some(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.DUE_DATE
+ ),
+ hasPriority: propertyValues.some(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.PRIORITY
+ ),
+ isSubtask: propertyValues.some(
+ (p) => p.propertyId === SYSTEM_PROPERTY_IDS.PARENT_TASK
+ ),
+ });
+
return documentId;
}
@@ -133,6 +166,8 @@ type CreateSnippetArgs = {
title?: string;
content?: string;
projectId?: string;
+ /** UI surface the creation originated from, for analytics. */
+ source?: string;
};
/**
@@ -163,6 +198,14 @@ export async function createSnippet(
subType: { type: 'snippet' },
});
refetchSoupEntity(documentId, 'document');
+
+ analytics.track('create_entity', {
+ entityType: 'snippet',
+ entityId: documentId,
+ projectId: args?.projectId,
+ source: args?.source,
+ });
+
return documentId;
}
@@ -171,11 +214,14 @@ export async function createCodeFileFromText({
extension,
language,
title,
+ source,
}: {
code: string;
title?: string;
extension?: CodeFileExtension;
language?: string;
+ /** UI surface the creation originated from, for analytics. */
+ source?: string;
}) {
const encoder = new TextEncoder();
const buffer = encoder.encode(code);
@@ -244,6 +290,14 @@ export async function createCodeFileFromText({
fileType: finalExtension,
});
refetchSoupEntity(document.metadata.documentId, 'document');
+
+ analytics.track('create_entity', {
+ entityType: 'code',
+ entityId: document.metadata.documentId,
+ source,
+ extension: finalExtension,
+ });
+
return ok({ documentId: document.metadata.documentId });
}
@@ -251,8 +305,10 @@ export async function createCanvasFileFromJsonString(args: {
json: string;
title?: string;
projectId?: string;
+ /** UI surface the creation originated from, for analytics. */
+ source?: string;
}) {
- const { json, title, projectId } = args;
+ const { json, title, projectId, source } = args;
const encoder = new TextEncoder();
const buffer = encoder.encode(json);
const sha = await contentHash(buffer);
@@ -284,10 +340,24 @@ export async function createCanvasFileFromJsonString(args: {
fileType: 'canvas',
});
refetchSoupEntity(canvas.metadata.documentId, 'document');
+
+ analytics.track('create_entity', {
+ entityType: 'canvas',
+ entityId: canvas.metadata.documentId,
+ projectId,
+ source,
+ });
+
return { documentId: canvas.metadata.documentId };
}
-export async function createChat(args?: CreateChatRequest) {
+export async function createChat(
+ args?: CreateChatRequest,
+ opts?: {
+ /** UI surface the creation originated from, for analytics. */
+ source?: string;
+ }
+) {
const { showPaywall } = usePaywallState();
const maybeChat = await cognitionApiServiceClient.createChat(args ?? {});
@@ -307,6 +377,14 @@ export async function createChat(args?: CreateChatRequest) {
name: args?.name ?? DEFAULT_CHAT_NAME,
});
refetchSoupEntity(chat.id, 'chat');
+
+ analytics.track('create_entity', {
+ entityType: 'chat',
+ entityId: chat.id,
+ projectId: args?.projectId,
+ source: opts?.source,
+ });
+
return { chatId: chat.id };
}
diff --git a/js/app/packages/queries/channel/channels.ts b/js/app/packages/queries/channel/channels.ts
index 0d13239e82..5a241d7717 100644
--- a/js/app/packages/queries/channel/channels.ts
+++ b/js/app/packages/queries/channel/channels.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { throwOnErr } from '@core/util/result';
import { queryClient } from '@queries/client';
import { type MutationCallbacks, withCallbacks } from '@queries/utils';
@@ -48,6 +49,12 @@ export function useCreateChannelMutation(
onError(error) {
console.error('failed to create channel', error);
},
+ onSuccess: (data) => {
+ analytics.track('create_entity', {
+ entityType: 'channel',
+ entityId: data.id,
+ });
+ },
onSettled: () => void invalidateListChannels(),
},
callbacks
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
index 7c19394c3c..2f0d637ba5 100644
--- a/js/app/packages/queries/properties/entity.ts
+++ b/js/app/packages/queries/properties/entity.ts
@@ -1,9 +1,11 @@
+import { analytics } from '@app/lib/analytics';
import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/result';
import {
entityPropertyFromApi,
propertyValueToApi,
} from '@property/api/converters';
+import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';
import type {
Property,
PropertyApiValues,
@@ -406,6 +408,61 @@ export function useRemoveEntityPropertyOptionMutation(
}));
}
+/**
+ * Task system property ids → the `property` name reported on `update_entity`.
+ * Non-task properties (custom properties, tags, ...) are not tracked here.
+ */
+const TRACKED_TASK_PROPERTIES: Record<string, string> = {
+ [SYSTEM_PROPERTY_IDS.STATUS]: 'status',
+ [SYSTEM_PROPERTY_IDS.PRIORITY]: 'priority',
+ [SYSTEM_PROPERTY_IDS.ASSIGNEES]: 'assignees',
+ [SYSTEM_PROPERTY_IDS.DUE_DATE]: 'due_date',
+};
+
+/**
+ * Emits a generic `update_entity` event for a saved task system property.
+ * Gated on the property being one of the task system properties, so saves on
+ * other entities/properties never fire. Call only on save success.
+ */
+function trackTaskPropertySave(
+ entityId: string,
+ propertyId: string,
+ apiValues: PropertyApiValues
+) {
+ const property = TRACKED_TASK_PROPERTIES[propertyId];
+ if (!property) return;
+
+ const detail: Record<string, unknown> = {};
+ if (property === 'status') {
+ const newStatus =
+ apiValues.valueType === 'SELECT_STRING'
+ ? (apiValues.values?.[0] ?? undefined)
+ : undefined;
+ if (!newStatus) return;
+ detail.newStatus = newStatus;
+ detail.completed = newStatus === PROPERTY_OPTION_IDS.STATUS.COMPLETED;
+ } else if (property === 'priority') {
+ detail.newPriority =
+ apiValues.valueType === 'SELECT_STRING'
+ ? (apiValues.values?.[0] ?? undefined)
+ : undefined;
+ } else if (property === 'assignees') {
+ detail.assigneeCount =
+ apiValues.valueType === 'ENTITY' ? (apiValues.refs?.length ?? 0) : 0;
+ } else if (property === 'due_date') {
+ detail.hasDueDate =
+ apiValues.valueType === 'DATE' && apiValues.value != null;
+ }
+
+ analytics.track('update_entity', {
+ entityType: 'task',
+ entityId,
+ property,
+ source: 'property_editor',
+ ...detail,
+ });
+}
+
type BulkSaveEntityPropertiesParams = {
properties: Array<{
entityId: string;
@@ -503,6 +560,15 @@ export function useBulkSaveEntityPropertiesMutation(
invalidateSoupEntity(p.entityId);
}
});
+ if (!error) {
+ for (const p of variables.properties) {
+ trackTaskPropertySave(
+ p.entityId,
+ getPropertyDefinitionId(p.property),
+ p.apiValues
+ );
+ }
+ }
},
},
callbacks
diff --git a/js/app/packages/queries/storage/projects.ts b/js/app/packages/queries/storage/projects.ts
index 726f5c4119..e3abdc8243 100644
--- a/js/app/packages/queries/storage/projects.ts
+++ b/js/app/packages/queries/storage/projects.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { ENABLE_PROJECT_SHARING } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { compareDateDesc } from '@core/util/date';
@@ -91,6 +92,8 @@ export async function createProject(params: {
name: string;
parentId?: string;
sharePermission?: null;
+ /** UI surface the creation originated from, for analytics. */
+ source?: string;
}): Promise<string | undefined> {
const result = await storageServiceClient.projects.create({
name: params.name,
@@ -100,6 +103,12 @@ export async function createProject(params: {
if (result.isOk()) {
const projectId = result.value.id;
+ analytics.track('create_entity', {
+ entityType: 'project',
+ entityId: projectId,
+ parentId: params.parentId,
+ source: params.source,
+ });
setPreviewOnCreate({
itemId: projectId,
itemType: 'project',
@@ -148,6 +157,11 @@ function _useCreateProjectMutation(
});
if (result.isOk()) {
+ analytics.track('create_entity', {
+ entityType: 'project',
+ entityId: result.value.id,
+ parentId: params.parentId,
+ });
return result.value.id;
}
return undefined;
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
index 604bc85951..0e8db96126 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth/oauth_redirect.rs
@@ -2,8 +2,8 @@ use crate::api::{
context::ApiContext,
login::sso::SsoState,
utils::{
- create_access_token_cookie, create_refresh_token_cookie, default_redirect_url,
- generate_session_code,
+ append_signed_up_param_if_new_user, create_access_token_cookie,
+ create_refresh_token_cookie, default_redirect_url, generate_session_code,
},
};
use axum::{
@@ -112,25 +112,37 @@ pub async fn handler(
None
};
- let redirect_url = get_redirect_url(&state, write_db)
+ let mut redirect_url = get_redirect_url(&state, write_db)
.await
.map_err(IntoResponse::into_response)?;
tracing::trace!("redirect url {redirect_url}");
+ let decoded_user_id = decode_macro_access_token_allow_expired(&access_token, &ctx.jwt_args);
+
if let Some(state) = state.as_ref()
&& let Some(referral_code) = state.referral_code.as_ref()
{
- let user_id = decode_macro_access_token_allow_expired(&access_token, &ctx.jwt_args)
+ let user_id = decoded_user_id
+ .as_ref()
.map_err(|_| InnerErr::InvalidJwtError.into_response())?;
let _ = ctx
.referral_service
- .track_referral(&user_id, &ReferralCode(referral_code.clone()))
+ .track_referral(user_id, &ReferralCode(referral_code.clone()))
.await
.inspect_err(|e| tracing::error!(error=?e, "unable to complete referral for user"));
}
+ if let Ok(user_id) = decoded_user_id.as_ref() {
+ append_signed_up_param_if_new_user(
+ &ctx.macro_cache_client,
+ user_id.email_str(),
+ &mut redirect_url,
+ )
+ .await;
+ }
+
// Set cookies
cookies.add(create_access_token_cookie(&access_token));
cookies.add(create_refresh_token_cookie(&refresh_token));
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs b/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs
index 8d9d0c5f0d..b443445ea6 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth/passwordless_callback.rs
@@ -9,7 +9,9 @@ use tower_cookies::Cookies;
use crate::api::{
context::ApiContext,
- utils::{create_access_token_cookie, create_refresh_token_cookie},
+ utils::{
+ append_signed_up_param_if_new_user, create_access_token_cookie, create_refresh_token_cookie,
+ },
};
use fusionauth::error::FusionAuthClientError;
@@ -156,5 +158,21 @@ pub async fn handler(
.into_response());
}
- Ok(Redirect::to(&passwordless_response.state.redirect_uri).into_response())
+ let mut redirect_uri = passwordless_response.state.redirect_uri.clone();
+ match url::Url::parse(&redirect_uri) {
+ Ok(mut url) => {
+ append_signed_up_param_if_new_user(
+ &ctx.macro_cache_client,
+ &passwordless_response.user.email.to_lowercase(),
+ &mut url,
+ )
+ .await;
+ redirect_uri = url.to_string();
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "unable to parse redirect uri for signup attribution");
+ }
+ }
+
+ Ok(Redirect::to(&redirect_uri).into_response())
}
diff --git a/rust/cloud-storage/authentication_service/src/api/utils.rs b/rust/cloud-storage/authentication_service/src/api/utils.rs
index 1ef8bb4c2c..14d9de5355 100644
--- a/rust/cloud-storage/authentication_service/src/api/utils.rs
+++ b/rust/cloud-storage/authentication_service/src/api/utils.rs
@@ -122,3 +122,25 @@ pub fn create_refresh_token_cookie(token: &str) -> Cookie<'static> {
));
cookie
}
+
+/// If this account was created during the auth flow that is completing (the
+/// create-user webhook marks it in the cache), appends `signed_up=true` to the
+/// redirect URL so the app can attribute the session as a signup for
+/// analytics. Best-effort: never fails the login.
+pub async fn append_signed_up_param_if_new_user(
+ macro_cache_client: &macro_cache_client::MacroCache,
+ email: &str,
+ redirect_url: &mut Url,
+) {
+ match macro_cache_client.take_user_just_signed_up(email).await {
+ Ok(true) => {
+ redirect_url
+ .query_pairs_mut()
+ .append_pair("signed_up", "true");
+ }
+ Ok(false) => {}
+ Err(e) => {
+ tracing::error!(error=?e, "unable to check just-signed-up marker");
+ }
+ }
+}
diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index dcfc94307f..6a2ae2f0b1 100644
--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -177,6 +177,39 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
tracing::trace!(user_id=?user_id, organization_id=?organization_id, "created user");
+ // Mark the account as freshly created so the auth callback completing this
+ // flow can attribute the login as a signup (analytics). Best-effort.
+ let _ = ctx
+ .macro_cache_client
+ .mark_user_just_signed_up(&email)
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "unable to mark user as just signed up"));
+
+ // Authoritative product-analytics signup event: fired here so every
+ // creation path (SSO, passwordless, iOS) counts exactly once, even if the
+ // user never returns to the app. The browser fires the ad-platform
+ // conversions instead — it holds the click-id cookies. Uses the same
+ // distinct id ("macro|{email}") the app identifies with. Fire-and-forget.
+ tokio::spawn({
+ let analytics_client = ctx.analytics_client.clone();
+ let user_id = user_id.clone();
+ let verified = req.event.user.verified;
+ let has_organization = organization_id.is_some();
+ async move {
+ let _ = analytics_client
+ .track_posthog(
+ &user_id,
+ "sign_up",
+ serde_json::json!({
+ "verified": verified,
+ "hasOrganization": has_organization,
+ }),
+ )
+ .await
+ .inspect_err(|e| tracing::warn!(error=?e, "failed to track PostHog sign_up event"));
+ }
+ });
+
// add user to all active experiments
tokio::spawn({
let db = ctx.db.clone();
diff --git a/rust/cloud-storage/macro_cache_client/src/auth.rs b/rust/cloud-storage/macro_cache_client/src/auth.rs
index 9ac1ea3528..0b52105f4c 100644
--- a/rust/cloud-storage/macro_cache_client/src/auth.rs
+++ b/rust/cloud-storage/macro_cache_client/src/auth.rs
@@ -6,6 +6,11 @@ pub static MACRO_MOBILE_LOGIN_SESSION_EXPIRY_SECONDS: u64 = 5 * 60;
/// This is the length of time a passwordless login code is valid for within FusionAuth
pub static MACRO_PASSWORDLESS_LOGIN_CODE_EXPIRY_SECONDS: u64 = 600;
+/// How long after account creation the first completed login is still
+/// attributed as a signup (the create-user webhook and the auth callback run
+/// within the same auth flow, so this only needs to cover slow IdP round trips).
+pub static MACRO_JUST_SIGNED_UP_EXPIRY_SECONDS: u64 = 30 * 60;
+
/// Generates the rate limit key for channel invites for a given ip
macro_rules! macro_passwordless_login_code {
($email:expr) => {
@@ -13,6 +18,13 @@ macro_rules! macro_passwordless_login_code {
};
}
+/// Generates the "account was just created" marker key for a given email
+macro_rules! macro_just_signed_up {
+ ($email:expr) => {
+ format!("just_signed_up:{}", $email)
+ };
+}
+
impl MacroCache {
/// **LEGACY** removes a user's session from redis
/// This is used for legacy auth only
@@ -73,4 +85,20 @@ impl MacroCache {
let key = macro_passwordless_login_code!(email.to_lowercase());
macro_redis::get::get::<String>(&self.inner, &key).await
}
+
+ /// Marks an account as just created so the auth callback that completes the
+ /// same flow can attribute the login as a signup.
+ pub async fn mark_user_just_signed_up(&self, email: &str) -> anyhow::Result<()> {
+ let key = macro_just_signed_up!(email.to_lowercase());
+ macro_redis::set::set_with_expiry(&self.inner, &key, 1, MACRO_JUST_SIGNED_UP_EXPIRY_SECONDS)
+ .await
+ }
+
+ /// Consumes the just-signed-up marker for an email. Returns true exactly
+ /// once per marker: GETDEL is atomic, so the first caller wins.
+ pub async fn take_user_just_signed_up(&self, email: &str) -> anyhow::Result<bool> {
+ let key = macro_just_signed_up!(email.to_lowercase());
+ let value = macro_redis::get::get_del_optional::<u8>(&self.inner, &key).await?;
+ Ok(value.is_some())
+ }
}
diff --git a/rust/cloud-storage/macro_redis/src/get.rs b/rust/cloud-storage/macro_redis/src/get.rs
index 8cc91cd2d7..f49478a064 100644
--- a/rust/cloud-storage/macro_redis/src/get.rs
+++ b/rust/cloud-storage/macro_redis/src/get.rs
@@ -19,6 +19,26 @@ where
Ok(value)
}
+/// Atomically gets a value from redis and deletes the key (GETDEL).
+/// Returns None if the key did not exist. Unlike a separate get + delete,
+/// only one concurrent caller can observe a given value.
+pub async fn get_del_optional<T>(client: &redis::Client, key: &str) -> anyhow::Result<Option<T>>
+where
+ T: redis::FromRedisValue,
+{
+ let mut redis_connection = client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+
+ let value = redis_connection
+ .get_del::<&str, Option<T>>(key)
+ .await
+ .with_context(|| format!("unable to get and delete value for key {}", key))?;
+
+ Ok(value)
+}
+
/// Gets a value from redis
/// Returns an error if the value is not present
pub async fn get<T>(client: &redis::Client, key: &str) -> anyhow::Result<T>