Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): make registration tracking consent-safe and retryable (#41365)

Coding On Starc6ca39504219
diff --git a/web/app/(commonLayout)/__tests__/external-service-sync.spec.tsx b/web/app/(commonLayout)/__tests__/external-service-sync.spec.tsx
new file mode 100644
index 00000000000..c851acaf03b
--- /dev/null
+++ b/web/app/(commonLayout)/__tests__/external-service-sync.spec.tsx
@@ -0,0 +1,106 @@
+import { render, waitFor } from '@testing-library/react'
+import { REGISTRATION_SUCCESS_STORAGE_KEY } from '@/app/components/base/amplitude/registration-session-state'
+import { rememberRegistrationSuccess } from '@/app/components/base/amplitude/registration-tracking'
+import { AmplitudeIdentitySync } from '../external-service-sync'
+
+const { mockSetUserId, mockSetUserProperties, mockTrackEvent } = vi.hoisted(() => ({
+ mockSetUserId: vi.fn(),
+ mockSetUserProperties: vi.fn(),
+ mockTrackEvent: vi.fn((..._args: unknown[]) => ({
+ promise: Promise.resolve({ code: 200 }),
+ })),
+}))
+
+vi.mock('@tanstack/react-query', async (importOriginal) => {
+ const original = await importOriginal<typeof import('@tanstack/react-query')>()
+ return {
+ ...original,
+ useSuspenseQuery: () => ({
+ data: {
+ id: 'account-id',
+ email: '[email protected]',
+ name: 'Person',
+ is_password_set: true,
+ },
+ }),
+ }
+})
+
+vi.mock('jotai', async (importOriginal) => {
+ const original = await importOriginal<typeof import('jotai')>()
+ return {
+ ...original,
+ useAtomValue: () => ({
+ id: 'workspace-id',
+ name: 'Workspace',
+ plan: 'professional',
+ role: 'owner',
+ }),
+ }
+})
+
+vi.mock('@/features/account-profile/client', () => ({
+ userProfileQueryOptions: () => ({}),
+}))
+
+vi.mock('@/app/components/base/amplitude', () => ({
+ setUserId: (...args: unknown[]) => mockSetUserId(...args),
+ setUserProperties: (...args: unknown[]) => mockSetUserProperties(...args),
+}))
+
+vi.mock('@/app/components/base/amplitude/utils', () => ({
+ trackEvent: (...args: unknown[]) => mockTrackEvent(...args),
+}))
+
+vi.mock('@/app/components/base/amplitude/init', () => ({
+ getIsAmplitudeInitialized: () => true,
+}))
+
+vi.mock('@/app/components/base/analytics-consent/consent-store', async (importOriginal) => {
+ const original =
+ await importOriginal<typeof import('@/app/components/base/analytics-consent/consent-store')>()
+ return {
+ ...original,
+ getAnalyticsConsent: () => 'granted',
+ }
+})
+
+describe('AmplitudeIdentitySync', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ window.sessionStorage.clear()
+ vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue(
+ '11111111-1111-4111-8111-111111111111',
+ )
+ })
+
+ it('sets identity before flushing a marker that already exists', async () => {
+ rememberRegistrationSuccess({ method: 'oauth' })
+
+ render(<AmplitudeIdentitySync />)
+
+ await waitFor(() => expect(mockTrackEvent).toHaveBeenCalledTimes(1))
+ expect(mockSetUserId).toHaveBeenCalledWith('[email protected]')
+ expect(mockSetUserProperties).toHaveBeenCalledTimes(1)
+ expect(mockSetUserId.mock.invocationCallOrder[0]).toBeLessThan(
+ mockTrackEvent.mock.invocationCallOrder[0]!,
+ )
+ expect(mockSetUserProperties.mock.invocationCallOrder[0]).toBeLessThan(
+ mockTrackEvent.mock.invocationCallOrder[0]!,
+ )
+ })
+
+ it('flushes a marker created after identity sync without repeating unchanged identity updates', async () => {
+ render(<AmplitudeIdentitySync />)
+
+ await waitFor(() => expect(mockSetUserId).toHaveBeenCalledTimes(1))
+ expect(mockTrackEvent).not.toHaveBeenCalled()
+
+ rememberRegistrationSuccess({ method: 'email' })
+
+ await waitFor(() => expect(mockTrackEvent).toHaveBeenCalledTimes(1))
+ expect(mockSetUserId).toHaveBeenCalledTimes(1)
+ expect(mockSetUserProperties).toHaveBeenCalledTimes(1)
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ })
+})
diff --git a/web/app/(commonLayout)/external-service-sync.tsx b/web/app/(commonLayout)/external-service-sync.tsx
index cec7155626e..08bb786d379 100644
--- a/web/app/(commonLayout)/external-service-sync.tsx
+++ b/web/app/(commonLayout)/external-service-sync.tsx
@@ -5,9 +5,13 @@ import type { DeploymentEdition } from '@dify/contracts/api/console/system-featu
import type { GetWorkspacesCurrentSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import { skipToken, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { Fragment, useEffect, useRef } from 'react'
+import { Fragment, useEffect, useRef, useSyncExternalStore } from 'react'
import { setUserId, setUserProperties } from '@/app/components/base/amplitude'
-import { flushRegistrationSuccess } from '@/app/components/base/amplitude/registration-tracking'
+import {
+ flushRegistrationSuccess,
+ getRegistrationSuccessSnapshot,
+ subscribeRegistrationSuccess,
+} from '@/app/components/base/amplitude/registration-tracking'
import { useAmplitudeInitialized } from '@/app/components/base/amplitude/use-amplitude-initialized'
import { useAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'
@@ -43,13 +47,18 @@ function buildAmplitudeProperties({
return properties
}
-function AmplitudeIdentitySync() {
+export function AmplitudeIdentitySync() {
const { data: userProfile } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.profile,
})
const currentWorkspace = useAtomValue(currentWorkspaceAtom)
const lastIdentityRef = useRef<string | undefined>(undefined)
+ const registrationSnapshot = useSyncExternalStore(
+ subscribeRegistrationSuccess,
+ getRegistrationSuccessSnapshot,
+ getRegistrationSuccessSnapshot,
+ )
useEffect(() => {
if (!userProfile.id) return
@@ -63,13 +72,14 @@ function AmplitudeIdentitySync() {
properties,
})
- if (identity === lastIdentityRef.current) return
+ if (identity !== lastIdentityRef.current) {
+ setUserId(userProfile.email)
+ setUserProperties(properties)
+ lastIdentityRef.current = identity
+ }
- setUserId(userProfile.email)
- setUserProperties(properties)
- flushRegistrationSuccess()
- lastIdentityRef.current = identity
- }, [currentWorkspace, userProfile])
+ void flushRegistrationSuccess()
+ }, [currentWorkspace, registrationSnapshot, userProfile])
return null
}
diff --git a/web/app/components/__tests__/oauth-registration-analytics.spec.tsx b/web/app/components/__tests__/oauth-registration-analytics.spec.tsx
index eb8f7deacdf..53d18f0d2b9 100644
--- a/web/app/components/__tests__/oauth-registration-analytics.spec.tsx
+++ b/web/app/components/__tests__/oauth-registration-analytics.spec.tsx
@@ -1,12 +1,31 @@
import { render, waitFor } from '@testing-library/react'
import Cookies from 'js-cookie'
+import { StrictMode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { useSearchParams } from '@/next/navigation'
import { OAuthRegistrationAnalytics } from '../oauth-registration-analytics'
-const { mockSendGAEvent, mockRememberRegistrationSuccess } = vi.hoisted(() => ({
- mockSendGAEvent: vi.fn(),
+const {
+ mockConsent,
+ mockNormalizeRegistrationAttribution,
+ mockRememberRegistrationSuccess,
+ mockSendGAEvent,
+} = vi.hoisted(() => ({
+ mockConsent: { value: 'granted' as 'unknown' | 'denied' | 'granted' | 'disabled' },
+ mockNormalizeRegistrationAttribution: vi.fn((value: Record<string, unknown> | null) => {
+ if (!value) return null
+ const allowed = Object.fromEntries(
+ Object.entries(value).filter(
+ ([key, item]) =>
+ ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'slug'].includes(
+ key,
+ ) && typeof item === 'string',
+ ),
+ )
+ return Object.keys(allowed).length ? allowed : null
+ }),
mockRememberRegistrationSuccess: vi.fn(),
+ mockSendGAEvent: vi.fn(),
}))
vi.mock('@/utils/gtag', () => ({
@@ -17,7 +36,14 @@ vi.mock('@/next/navigation', () => ({
useSearchParams: vi.fn(),
}))
+vi.mock('../base/analytics-consent/consent-store', () => ({
+ useAnalyticsConsent: () => mockConsent.value,
+}))
+
vi.mock('../base/amplitude/registration-tracking', () => ({
+ normalizeRegistrationAttribution: (
+ ...args: Parameters<typeof mockNormalizeRegistrationAttribution>
+ ) => mockNormalizeRegistrationAttribution(...args),
rememberRegistrationSuccess: (...args: unknown[]) => mockRememberRegistrationSuccess(...args),
}))
@@ -33,22 +59,74 @@ const setSearchParams = (searchParams = '') => {
describe('OAuthRegistrationAnalytics', () => {
beforeEach(() => {
vi.clearAllMocks()
+ window.sessionStorage.clear()
+ mockConsent.value = 'granted'
+ mockRememberRegistrationSuccess.mockReturnValue(true)
Cookies.remove('utm_info')
vi.spyOn(console, 'error').mockImplementation(() => {})
setSearchParams()
})
- it('should track oauth registration with utm info and clear the query flag', async () => {
+ it('queues the Amplitude marker while consent is unknown and cleans the URL after persist', async () => {
+ mockConsent.value = 'unknown'
+ Cookies.set('utm_info', JSON.stringify({ utm_source: 'linkedin', slug: 'agent-launch' }))
+ setSearchParams('oauth_new_user=true&source=signin')
+
+ render(<OAuthRegistrationAnalytics />)
+
+ await waitFor(() => {
+ expect(mockRememberRegistrationSuccess).toHaveBeenCalledWith({
+ method: 'oauth',
+ utmInfo: { utm_source: 'linkedin', slug: 'agent-launch' },
+ })
+ })
+ expect(mockSendGAEvent).toHaveBeenCalledTimes(1)
+ expect(Cookies.get('utm_info')).toBeUndefined()
+ expect(window.location.search).toBe('?source=signin')
+ })
+
+ it('keeps the recoverable OAuth signal when marker persistence fails', () => {
+ Cookies.set('utm_info', JSON.stringify({ utm_source: 'linkedin' }))
+ setSearchParams('oauth_new_user=true&source=signin')
+ mockRememberRegistrationSuccess.mockReturnValue(false)
+
+ render(<OAuthRegistrationAnalytics />)
+
+ expect(mockRememberRegistrationSuccess).toHaveBeenCalledTimes(1)
+ expect(window.location.search).toBe('?oauth_new_user=true&source=signin')
+ expect(Cookies.get('utm_info')).toBeTruthy()
+ })
+
+ it('keeps the OAuth marker while consent is unknown, then cleans without a second Amplitude queue on denial', async () => {
+ mockConsent.value = 'unknown'
+ Cookies.set('utm_info', JSON.stringify({ utm_source: 'blog' }))
+ setSearchParams('oauth_new_user=true')
+
+ const { rerender } = render(<OAuthRegistrationAnalytics />)
+
+ await waitFor(() => expect(mockRememberRegistrationSuccess).toHaveBeenCalledTimes(1))
+ expect(mockSendGAEvent).toHaveBeenCalledTimes(1)
+
+ mockConsent.value = 'denied'
+ rerender(<OAuthRegistrationAnalytics />)
+
+ await waitFor(() => expect(window.location.search).toBe(''))
+ expect(mockRememberRegistrationSuccess).toHaveBeenCalledTimes(1)
+ expect(mockSendGAEvent).toHaveBeenCalledTimes(1)
+ expect(Cookies.get('utm_info')).toBeUndefined()
+ })
+
+ it('queues immediately with pre-granted consent and keeps only allowlisted UTM fields', async () => {
Cookies.set(
'utm_info',
JSON.stringify({
utm_source: 'linkedin',
slug: 'agent-launch',
+ arbitrary: 'discard-me',
+ utm_term: { nested: true },
}),
)
-
setSearchParams('oauth_new_user=true&source=signin')
- const replaceStateSpy = vi.spyOn(window.history, 'replaceState')
render(<OAuthRegistrationAnalytics />)
@@ -64,16 +142,13 @@ describe('OAuthRegistrationAnalytics', () => {
slug: 'agent-launch',
})
expect(Cookies.get('utm_info')).toBeUndefined()
-
- await waitFor(() => {
- expect(replaceStateSpy).toHaveBeenCalledWith(null, '', '/signin?source=signin')
- })
+ expect(window.location.search).toBe('?source=signin')
})
- it('should fall back to the base registration event when the utm cookie is invalid', async () => {
+ it('uses the base event and cleans up when the UTM cookie is malformed', async () => {
Cookies.set('utm_info', '{invalid-json')
-
setSearchParams('oauth_new_user=true')
+
render(<OAuthRegistrationAnalytics />)
await waitFor(() => {
@@ -89,23 +164,77 @@ describe('OAuthRegistrationAnalytics', () => {
expect(Cookies.get('utm_info')).toBeUndefined()
})
- it('should do nothing without the oauth registration query flag', () => {
+ it('cleans a false OAuth marker immediately without tracking or clearing utm_info', async () => {
+ mockConsent.value = 'unknown'
+ Cookies.set('utm_info', JSON.stringify({ utm_source: 'blog' }))
+ setSearchParams('oauth_new_user=false')
+
render(<OAuthRegistrationAnalytics />)
+ await waitFor(() => expect(window.location.search).toBe(''))
expect(mockRememberRegistrationSuccess).not.toHaveBeenCalled()
expect(mockSendGAEvent).not.toHaveBeenCalled()
+ expect(Cookies.get('utm_info')).toBe(JSON.stringify({ utm_source: 'blog' }))
})
- it('should clear a false oauth registration query flag without tracking', async () => {
- setSearchParams('oauth_new_user=false')
- const replaceStateSpy = vi.spyOn(window.history, 'replaceState')
+ it('tracks GA and Amplitude once across StrictMode effects and rerenders', async () => {
+ setSearchParams('oauth_new_user=true')
+
+ const { rerender } = render(
+ <StrictMode>
+ <OAuthRegistrationAnalytics />
+ </StrictMode>,
+ )
+ rerender(
+ <StrictMode>
+ <OAuthRegistrationAnalytics />
+ </StrictMode>,
+ )
+
+ await waitFor(() => expect(mockRememberRegistrationSuccess).toHaveBeenCalledTimes(1))
+ expect(mockSendGAEvent).toHaveBeenCalledTimes(1)
+ })
+
+ it('tracks GA once across an unknown-consent remount that simulates reload', async () => {
+ mockConsent.value = 'unknown'
+ setSearchParams('oauth_new_user=true')
+
+ const firstRender = render(<OAuthRegistrationAnalytics />)
+ await waitFor(() => expect(mockRememberRegistrationSuccess).toHaveBeenCalledTimes(1))
+ firstRender.unmount()
+ render(<OAuthRegistrationAnalytics />)
+
+ expect(mockSendGAEvent).toHaveBeenCalledTimes(1)
+ })
+
+ it('treats analytics-disabled consent as terminal and cleans without Amplitude', async () => {
+ mockConsent.value = 'disabled'
+ Cookies.set('utm_info', JSON.stringify({ utm_source: 'blog' }))
+ setSearchParams('oauth_new_user=true')
+
+ render(<OAuthRegistrationAnalytics />)
+
+ await waitFor(() => expect(window.location.search).toBe(''))
+ expect(mockRememberRegistrationSuccess).not.toHaveBeenCalled()
+ expect(Cookies.get('utm_info')).toBeUndefined()
+ })
+
+ it('does nothing without the OAuth registration query marker', () => {
render(<OAuthRegistrationAnalytics />)
- await waitFor(() => {
- expect(replaceStateSpy).toHaveBeenCalledWith(null, '', '/signin')
- })
expect(mockRememberRegistrationSuccess).not.toHaveBeenCalled()
expect(mockSendGAEvent).not.toHaveBeenCalled()
})
+
+ it('clears an abandoned flow guard so a later OAuth registration can emit GA', () => {
+ window.sessionStorage.setItem('oauth_registration_ga_sent', 'true')
+ const abandonedFlow = render(<OAuthRegistrationAnalytics />)
+ abandonedFlow.unmount()
+
+ setSearchParams('oauth_new_user=true')
+ render(<OAuthRegistrationAnalytics />)
+
+ expect(mockSendGAEvent).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/web/app/components/base/amplitude/__tests__/registration-tracking.spec.ts b/web/app/components/base/amplitude/__tests__/registration-tracking.spec.ts
index 30c6707a702..e5979a79623 100644
--- a/web/app/components/base/amplitude/__tests__/registration-tracking.spec.ts
+++ b/web/app/components/base/amplitude/__tests__/registration-tracking.spec.ts
@@ -1,55 +1,182 @@
import {
- flushRegistrationSuccess,
+ discardRegistrationSessionState,
REGISTRATION_SUCCESS_STORAGE_KEY,
+} from '../registration-session-state'
+import {
+ coordinateRegistrationConsent,
+ flushRegistrationSuccess,
rememberRegistrationSuccess,
+ subscribeRegistrationSuccess,
} from '../registration-tracking'
const mockTrackEvent = vi.hoisted(() => vi.fn())
+const mockAmplitudeInitialized = vi.hoisted(() => ({ value: true }))
const mockConsent = vi.hoisted(() => ({
- value: 'granted' as 'unknown' | 'denied' | 'granted',
+ value: 'granted' as 'unknown' | 'denied' | 'granted' | 'disabled',
}))
vi.mock('../utils', () => ({
trackEvent: (...args: unknown[]) => mockTrackEvent(...args),
}))
+vi.mock('../init', () => ({
+ getIsAmplitudeInitialized: () => mockAmplitudeInitialized.value,
+}))
+
vi.mock('@/app/components/base/analytics-consent/consent-store', () => ({
getAnalyticsConsent: () => mockConsent.value,
}))
+const successResult = () => ({
+ promise: Promise.resolve({ code: 200 }),
+})
+
+const getStoredMarker = () =>
+ JSON.parse(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)!)
+
describe('registration tracking', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.unstubAllGlobals()
+ vi.useRealTimers()
window.sessionStorage.clear()
mockConsent.value = 'granted'
+ mockAmplitudeInitialized.value = true
+ mockTrackEvent.mockImplementation(successResult)
+ coordinateRegistrationConsent('denied')
+ mockConsent.value = 'granted'
+ vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue(
+ '11111111-1111-4111-8111-111111111111',
+ )
+ })
+
+ afterEach(() => {
+ discardRegistrationSessionState()
+ vi.useRealTimers()
})
- // Captures the registration event for a later flush instead of firing it right away.
describe('rememberRegistrationSuccess', () => {
- it('should store the base event and not track immediately when there is no utm info', () => {
- rememberRegistrationSuccess({ method: 'email' })
+ it('stores a versioned marker with stable delivery metadata and allowlisted attribution', () => {
+ vi.setSystemTime(new Date('2026-08-26T09:00:00.000Z'))
+
+ const persisted = rememberRegistrationSuccess({
+ method: 'email',
+ utmInfo: {
+ utm_source: 'linkedin',
+ utm_medium: 'social',
+ utm_campaign: 'launch',
+ utm_content: 'hero',
+ utm_term: 'agents',
+ slug: 'agent-launch',
+ unexpected: 'discard-me',
+ nested: { unsafe: true },
+ },
+ })
- expect(JSON.parse(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)!)).toEqual({
- eventName: 'user_registration_success',
- properties: { method: 'email' },
+ const occurredAt = Date.now()
+ expect(getStoredMarker()).toEqual({
+ version: 2,
+ registrationId: '11111111-1111-4111-8111-111111111111',
+ occurredAt,
+ expiresAt: occurredAt + 24 * 60 * 60 * 1000,
+ eventName: 'user_registration_success_with_utm',
+ method: 'email',
+ attribution: {
+ utm_source: 'linkedin',
+ utm_medium: 'social',
+ utm_campaign: 'launch',
+ utm_content: 'hero',
+ utm_term: 'agents',
+ slug: 'agent-launch',
+ },
})
expect(mockTrackEvent).not.toHaveBeenCalled()
+ expect(persisted).toBe(true)
})
- it('should store the utm event and merge utm info into properties when utm info is present', () => {
- rememberRegistrationSuccess({
- method: 'oauth',
- utmInfo: { utm_source: 'linkedin', slug: 'agent-launch' },
- })
+ it('persists the latest email marker while consent is unknown so a later grant can flush it', async () => {
+ mockConsent.value = 'unknown'
+ rememberRegistrationSuccess({ method: 'email', utmInfo: { utm_source: 'first' } })
+ rememberRegistrationSuccess({ method: 'email', utmInfo: { utm_source: 'latest' } })
- expect(JSON.parse(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)!)).toEqual({
- eventName: 'user_registration_success_with_utm',
- properties: { method: 'oauth', utm_source: 'linkedin', slug: 'agent-launch' },
+ expect(getStoredMarker()).toMatchObject({
+ version: 2,
+ method: 'email',
+ attribution: { utm_source: 'latest' },
})
+
+ await flushRegistrationSuccess()
+ expect(mockTrackEvent).not.toHaveBeenCalled()
+
+ mockConsent.value = 'granted'
+ await flushRegistrationSuccess()
+
+ expect(mockTrackEvent).toHaveBeenCalledTimes(1)
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ })
+
+ it('discards an unknown-consent marker on denial before a later grant can flush it', async () => {
+ mockConsent.value = 'unknown'
+ rememberRegistrationSuccess({ method: 'email' })
+
+ coordinateRegistrationConsent('denied')
+ mockConsent.value = 'granted'
+ await flushRegistrationSuccess()
+
+ expect(mockTrackEvent).not.toHaveBeenCalled()
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
})
- it('should swallow errors when writing to sessionStorage fails', () => {
+ it('discards a pending marker and GA guard at an account boundary', async () => {
+ mockConsent.value = 'unknown'
+ rememberRegistrationSuccess({ method: 'email' })
+ window.sessionStorage.setItem('oauth_registration_ga_sent', 'true')
+
+ discardRegistrationSessionState()
+ mockConsent.value = 'granted'
+ await flushRegistrationSuccess()
+
+ expect(mockTrackEvent).not.toHaveBeenCalled()
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ expect(window.sessionStorage.getItem('oauth_registration_ga_sent')).toBeNull()
+ })
+
+ it.each(['denied', 'disabled'] as const)(
+ 'discards a stored marker when consent changes to %s',
+ (consent) => {
+ rememberRegistrationSuccess({ method: 'email' })
+
+ coordinateRegistrationConsent(consent)
+
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ },
+ )
+
+ it('persists an oauth marker while consent is unknown so a reload can still flush it', async () => {
+ mockConsent.value = 'unknown'
+ rememberRegistrationSuccess({ method: 'oauth' })
+
+ expect(getStoredMarker()).toMatchObject({ method: 'oauth' })
+
+ mockConsent.value = 'granted'
+ await flushRegistrationSuccess()
+
+ expect(mockTrackEvent).toHaveBeenCalledTimes(1)
+ })
+
+ it('notifies consumers only after a marker is stored', () => {
+ const listener = vi.fn()
+ const unsubscribe = subscribeRegistrationSuccess(listener)
+
+ rememberRegistrationSuccess({ method: 'email' })
+
+ expect(listener).toHaveBeenCalledTimes(1)
+ unsubscribe()
+ })
+
+ it('swallows sessionStorage write errors without notifying consumers', () => {
+ const listener = vi.fn()
+ const unsubscribe = subscribeRegistrationSuccess(listener)
vi.stubGlobal('window', {
sessionStorage: {
getItem: vi.fn(() => null),
@@ -60,158 +187,365 @@ describe('registration tracking', () => {
},
})
- try {
- expect(() => rememberRegistrationSuccess({ method: 'email' })).not.toThrow()
- } finally {
- vi.unstubAllGlobals()
- }
+ expect(rememberRegistrationSuccess({ method: 'email' })).toBe(false)
+ expect(listener).not.toHaveBeenCalled()
+ unsubscribe()
})
+ })
- it.each(['unknown', 'denied'] as const)(
- 'should not cache an event while consent is %s',
- (consent) => {
- mockConsent.value = consent
+ describe('flushRegistrationSuccess', () => {
+ it('waits for a successful SDK result before acknowledging the marker', async () => {
+ let resolveTrack!: (result: { code: number }) => void
+ mockTrackEvent.mockReturnValue({
+ promise: new Promise((resolve) => {
+ resolveTrack = resolve
+ }),
+ })
+ vi.setSystemTime(new Date('2026-08-26T09:00:00.000Z'))
+ rememberRegistrationSuccess({ method: 'oauth', utmInfo: { utm_source: 'blog' } })
+
+ const flushPromise = flushRegistrationSuccess()
+
+ expect(getStoredMarker()).toBeTruthy()
+ expect(mockTrackEvent).toHaveBeenCalledWith(
+ 'user_registration_success_with_utm',
+ {
+ method: 'oauth',
+ utm_source: 'blog',
+ registration_id: '11111111-1111-4111-8111-111111111111',
+ event_version: 2,
+ tracking_contract_version: 'consent_wait_v2',
+ },
+ {
+ insert_id: '11111111-1111-4111-8111-111111111111',
+ time: Date.now(),
+ },
+ )
+ resolveTrack({ code: 200 })
+ await flushPromise
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ })
+
+ it.each([
+ ['unknown consent', () => (mockConsent.value = 'unknown')],
+ ['uninitialized Amplitude', () => (mockAmplitudeInitialized.value = false)],
+ ])('defers without deleting for %s', async (_label, makeIneligible) => {
+ rememberRegistrationSuccess({ method: 'email' })
+ makeIneligible()
+
+ await flushRegistrationSuccess()
+
+ expect(mockTrackEvent).not.toHaveBeenCalled()
+ expect(getStoredMarker()).toBeTruthy()
+ })
+
+ it('discards a pending marker when consent is denied', async () => {
+ rememberRegistrationSuccess({ method: 'oauth' })
+ mockConsent.value = 'denied'
+
+ await flushRegistrationSuccess()
+
+ expect(mockTrackEvent).not.toHaveBeenCalled()
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ })
+
+ it('retains the marker on SDK rejection or a non-success result and reuses its id and time', async () => {
+ vi.setSystemTime(new Date('2026-08-26T09:00:00.000Z'))
+ rememberRegistrationSuccess({ method: 'email' })
+ const marker = getStoredMarker()
+ mockTrackEvent
+ .mockReturnValueOnce({ promise: Promise.reject(new Error('network failed')) })
+ .mockReturnValueOnce({ promise: Promise.resolve({ code: 500 }) })
+ .mockImplementation(successResult)
+
+ await flushRegistrationSuccess()
+ await flushRegistrationSuccess()
+
+ expect(getStoredMarker()).toEqual(marker)
+ expect(mockTrackEvent.mock.calls[0]?.[2]).toEqual({
+ insert_id: marker.registrationId,
+ time: marker.occurredAt,
+ })
+ expect(mockTrackEvent.mock.calls[1]?.[2]).toEqual({
+ insert_id: marker.registrationId,
+ time: marker.occurredAt,
+ })
+ })
+
+ it.each(['rejected acknowledgement', 'non-success acknowledgement'] as const)(
+ 'continues with a replacement marker after a %s',
+ async (oldAcknowledgement) => {
+ const firstRegistrationId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
+ const replacementRegistrationId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
+ vi.spyOn(globalThis.crypto, 'randomUUID')
+ .mockReturnValueOnce(firstRegistrationId)
+ .mockReturnValueOnce(replacementRegistrationId)
+ let resolveOldAcknowledgement!: (result: { code: number }) => void
+ let rejectOldAcknowledgement!: (error: Error) => void
+ const pendingOldAcknowledgement = new Promise<{ code: number }>((resolve, reject) => {
+ resolveOldAcknowledgement = resolve
+ rejectOldAcknowledgement = reject
+ })
+ mockTrackEvent
+ .mockReturnValueOnce({ promise: pendingOldAcknowledgement })
+ .mockImplementation(successResult)
+
+ rememberRegistrationSuccess({ method: 'email' })
+ const firstFlush = flushRegistrationSuccess()
rememberRegistrationSuccess({ method: 'email' })
+ const replacementFlush = flushRegistrationSuccess()
+ expect(replacementFlush).toBe(firstFlush)
+ expect(mockTrackEvent).toHaveBeenCalledTimes(1)
+
+ if (oldAcknowledgement === 'rejected acknowledgement')
+ rejectOldAcknowledgement(new Error('network failed'))
+ else resolveOldAcknowledgement({ code: 500 })
+ await firstFlush
+
+ expect(mockTrackEvent).toHaveBeenCalledTimes(2)
+ expect(mockTrackEvent.mock.calls[1]?.[2]).toEqual({
+ insert_id: replacementRegistrationId,
+ time: expect.any(Number),
+ })
expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
},
)
- })
-
- // Replays the remembered event exactly once, after the user ID has been attached.
- describe('flushRegistrationSuccess', () => {
- it('should track the remembered event and clear it from storage', () => {
- rememberRegistrationSuccess({ method: 'email', utmInfo: { utm_source: 'blog' } })
- flushRegistrationSuccess()
+ it('retries an acknowledgement-failed marker after the backoff delay', async () => {
+ vi.useFakeTimers()
+ rememberRegistrationSuccess({ method: 'email' })
+ const marker = getStoredMarker()
+ mockTrackEvent
+ .mockReturnValueOnce({ promise: Promise.reject(new Error('network failed')) })
+ .mockImplementation(successResult)
+ await flushRegistrationSuccess()
+ expect(getStoredMarker()).toEqual(marker)
expect(mockTrackEvent).toHaveBeenCalledTimes(1)
- expect(mockTrackEvent).toHaveBeenCalledWith('user_registration_success_with_utm', {
- method: 'email',
- utm_source: 'blog',
+
+ await vi.advanceTimersByTimeAsync(1000)
+
+ expect(mockTrackEvent).toHaveBeenCalledTimes(2)
+ expect(mockTrackEvent.mock.calls[1]?.[2]).toEqual({
+ insert_id: marker.registrationId,
+ time: marker.occurredAt,
})
expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
})
- it('should do nothing when there is no pending event', () => {
- flushRegistrationSuccess()
+ it('does not retry an acknowledgement-failed marker after an account boundary', async () => {
+ rememberRegistrationSuccess({ method: 'email' })
+ mockTrackEvent.mockReturnValueOnce({ promise: Promise.reject(new Error('network failed')) })
- expect(mockTrackEvent).not.toHaveBeenCalled()
+ await flushRegistrationSuccess()
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).not.toBeNull()
+
+ discardRegistrationSessionState()
+ await flushRegistrationSuccess()
+
+ expect(mockTrackEvent).toHaveBeenCalledTimes(1)
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
})
- it('should fire the event at most once across repeated flushes', () => {
- rememberRegistrationSuccess({ method: 'oauth' })
+ it.each([
+ ['session discard', 'resolves'] as const,
+ ['session discard', 'rejects'] as const,
+ ['denied consent', 'resolves'] as const,
+ ['disabled analytics', 'resolves'] as const,
+ ])(
+ 'isolates a new registration flush after %s while the old SDK acknowledgement %s',
+ async (invalidation, oldAcknowledgement) => {
+ const accountARegistrationId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
+ const accountBRegistrationId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
+ vi.spyOn(globalThis.crypto, 'randomUUID')
+ .mockReturnValueOnce(accountARegistrationId)
+ .mockReturnValueOnce(accountBRegistrationId)
+
+ let resolveAccountA!: (result: { code: number }) => void
+ let rejectAccountA!: (error: Error) => void
+ let resolveAccountB!: (result: { code: number }) => void
+ const accountAAcknowledgement = new Promise<{ code: number }>((resolve, reject) => {
+ resolveAccountA = resolve
+ rejectAccountA = reject
+ })
+ const accountBAcknowledgement = new Promise<{ code: number }>((resolve) => {
+ resolveAccountB = resolve
+ })
+ mockTrackEvent
+ .mockReturnValueOnce({ promise: accountAAcknowledgement })
+ .mockReturnValueOnce({ promise: accountBAcknowledgement })
+
+ rememberRegistrationSuccess({ method: 'email' })
+ const accountAFlush = flushRegistrationSuccess()
+
+ if (invalidation === 'session discard') {
+ discardRegistrationSessionState()
+ } else {
+ const terminalConsent = invalidation === 'denied consent' ? 'denied' : 'disabled'
+ mockConsent.value = terminalConsent
+ coordinateRegistrationConsent(terminalConsent)
+ mockConsent.value = 'granted'
+ }
+
+ rememberRegistrationSuccess({ method: 'email' })
+ const accountBMarker = window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)
+ const accountBFlush = flushRegistrationSuccess()
+
+ const settleAccountA = () => {
+ if (oldAcknowledgement === 'resolves') resolveAccountA({ code: 200 })
+ else rejectAccountA(new Error('account A request failed'))
+ }
+
+ try {
+ expect(accountBMarker).not.toBeNull()
+ expect(accountBFlush).not.toBe(accountAFlush)
+ expect(mockTrackEvent).toHaveBeenCalledTimes(2)
+ expect(mockTrackEvent.mock.calls.map((call) => call[2])).toEqual([
+ { insert_id: accountARegistrationId, time: expect.any(Number) },
+ { insert_id: accountBRegistrationId, time: expect.any(Number) },
+ ])
+
+ settleAccountA()
+ await accountAFlush
+
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBe(
+ accountBMarker,
+ )
+ expect(flushRegistrationSuccess()).toBe(accountBFlush)
+ expect(mockTrackEvent).toHaveBeenCalledTimes(2)
+
+ resolveAccountB({ code: 200 })
+ await accountBFlush
+
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ } finally {
+ settleAccountA()
+ resolveAccountB({ code: 200 })
+ await Promise.allSettled([accountAFlush, accountBFlush])
+ }
+ },
+ )
- flushRegistrationSuccess()
- flushRegistrationSuccess()
+ it('coalesces concurrent flushes into one SDK send', async () => {
+ let resolveTrack!: (result: { code: number }) => void
+ mockTrackEvent.mockReturnValue({
+ promise: new Promise((resolve) => {
+ resolveTrack = resolve
+ }),
+ })
+ rememberRegistrationSuccess({ method: 'email' })
+
+ const first = flushRegistrationSuccess()
+ const second = flushRegistrationSuccess()
expect(mockTrackEvent).toHaveBeenCalledTimes(1)
+ resolveTrack({ code: 200 })
+ await Promise.all([first, second])
})
- it('should discard a pending event when consent was revoked before flush', () => {
- rememberRegistrationSuccess({ method: 'oauth' })
- mockConsent.value = 'denied'
-
- flushRegistrationSuccess()
+ it('discards expired and malformed markers without tracking', async () => {
+ vi.setSystemTime(new Date('2026-08-26T09:00:00.000Z'))
+ rememberRegistrationSuccess({ method: 'email' })
+ vi.setSystemTime(new Date('2026-08-27T09:00:00.000Z'))
+ await flushRegistrationSuccess()
expect(mockTrackEvent).not.toHaveBeenCalled()
expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+
+ const malformedMarkers = [
+ '{not-json',
+ JSON.stringify({ version: 1, eventName: 'user_registration_success' }),
+ JSON.stringify({
+ version: 2,
+ registrationId: 'id',
+ occurredAt: Date.now(),
+ expiresAt: Date.now() + 1000,
+ eventName: 'arbitrary_event',
+ method: 'email',
+ attribution: {},
+ }),
+ ]
+
+ for (const raw of malformedMarkers) {
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, raw)
+ await flushRegistrationSuccess()
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ }
+ expect(mockTrackEvent).not.toHaveBeenCalled()
})
- it('should clear malformed pending data without tracking', () => {
- window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, '{not-json')
+ it('accepts a persisted timestamp just inside the five-minute clock-skew allowance', async () => {
+ vi.setSystemTime(new Date('2026-08-26T09:04:59.999Z'))
+ rememberRegistrationSuccess({ method: 'email' })
+ vi.setSystemTime(new Date('2026-08-26T09:00:00.000Z'))
- flushRegistrationSuccess()
+ await flushRegistrationSuccess()
- expect(mockTrackEvent).not.toHaveBeenCalled()
- expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ expect(mockTrackEvent).toHaveBeenCalledTimes(1)
})
- it('should clear the pending entry without tracking when it has no event name', () => {
- window.sessionStorage.setItem(
- REGISTRATION_SUCCESS_STORAGE_KEY,
- JSON.stringify({ properties: { method: 'email' } }),
- )
+ it('rejects a persisted timestamp just outside the five-minute clock-skew allowance', async () => {
+ vi.setSystemTime(new Date('2026-08-26T09:05:00.001Z'))
+ rememberRegistrationSuccess({ method: 'email' })
+ vi.setSystemTime(new Date('2026-08-26T09:00:00.000Z'))
- flushRegistrationSuccess()
+ await flushRegistrationSuccess()
expect(mockTrackEvent).not.toHaveBeenCalled()
expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
})
- it('should stop without tracking when reading from sessionStorage throws', () => {
+ it('handles storage read errors without throwing', async () => {
vi.stubGlobal('window', {
sessionStorage: {
getItem: () => {
throw new Error('read failed')
},
setItem: vi.fn(),
- removeItem: vi.fn(),
+ removeItem: () => {
+ throw new Error('remove failed')
+ },
},
})
- try {
- expect(() => flushRegistrationSuccess()).not.toThrow()
- expect(mockTrackEvent).not.toHaveBeenCalled()
- } finally {
- vi.unstubAllGlobals()
- }
+ await expect(flushRegistrationSuccess()).resolves.toBeUndefined()
+ expect(mockTrackEvent).not.toHaveBeenCalled()
})
- it('should still track when clearing the pending entry fails', () => {
- const pending = { eventName: 'user_registration_success', properties: { method: 'email' } }
+ it('retains the same marker when acknowledgement removal fails', async () => {
+ rememberRegistrationSuccess({ method: 'email' })
+ const raw = window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)
+ const removeItem = vi.fn(() => {
+ throw new Error('remove failed')
+ })
vi.stubGlobal('window', {
sessionStorage: {
- getItem: () => JSON.stringify(pending),
+ getItem: () => raw,
setItem: vi.fn(),
- removeItem: () => {
- throw new Error('remove failed')
- },
+ removeItem,
},
})
- try {
- flushRegistrationSuccess()
-
- expect(mockTrackEvent).toHaveBeenCalledWith('user_registration_success', {
- method: 'email',
- })
- } finally {
- vi.unstubAllGlobals()
- }
- })
- })
+ await expect(flushRegistrationSuccess()).resolves.toBeUndefined()
+ await expect(flushRegistrationSuccess()).resolves.toBeUndefined()
- // Both producers and the consumer must degrade gracefully when sessionStorage is
- // missing (SSR) or blocked (privacy mode / disabled storage).
- describe('when sessionStorage is unavailable', () => {
- it('should no-op without throwing when window is undefined', () => {
- vi.stubGlobal('window', undefined)
-
- try {
- expect(() => rememberRegistrationSuccess({ method: 'email' })).not.toThrow()
- expect(() => flushRegistrationSuccess()).not.toThrow()
- expect(mockTrackEvent).not.toHaveBeenCalled()
- } finally {
- vi.unstubAllGlobals()
- }
+ expect(mockTrackEvent).toHaveBeenCalledTimes(2)
+ expect(mockTrackEvent.mock.calls[0]?.[2]).toEqual(mockTrackEvent.mock.calls[1]?.[2])
+ expect(removeItem).toHaveBeenCalledTimes(2)
})
- it('should no-op without throwing when accessing sessionStorage throws', () => {
+ it('no-ops when sessionStorage access is blocked', async () => {
vi.stubGlobal('window', {
get sessionStorage() {
throw new Error('storage disabled')
},
})
- try {
- expect(() => rememberRegistrationSuccess({ method: 'oauth' })).not.toThrow()
- expect(() => flushRegistrationSuccess()).not.toThrow()
- expect(mockTrackEvent).not.toHaveBeenCalled()
- } finally {
- vi.unstubAllGlobals()
- }
+ expect(() => rememberRegistrationSuccess({ method: 'email' })).not.toThrow()
+ await expect(flushRegistrationSuccess()).resolves.toBeUndefined()
+ expect(mockTrackEvent).not.toHaveBeenCalled()
})
})
})
diff --git a/web/app/components/base/amplitude/registration-consent-coordinator.tsx b/web/app/components/base/amplitude/registration-consent-coordinator.tsx
new file mode 100644
index 00000000000..8d19d05cdc2
--- /dev/null
+++ b/web/app/components/base/amplitude/registration-consent-coordinator.tsx
@@ -0,0 +1,15 @@
+'use client'
+
+import { useEffect } from 'react'
+import { useAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
+import { coordinateRegistrationConsent } from './registration-tracking'
+
+export function RegistrationConsentCoordinator() {
+ const consent = useAnalyticsConsent()
+
+ useEffect(() => {
+ coordinateRegistrationConsent(consent)
+ }, [consent])
+
+ return null
+}
diff --git a/web/app/components/base/amplitude/registration-session-state.ts b/web/app/components/base/amplitude/registration-session-state.ts
new file mode 100644
index 00000000000..5eae9390cb1
--- /dev/null
+++ b/web/app/components/base/amplitude/registration-session-state.ts
@@ -0,0 +1,99 @@
+export const REGISTRATION_SUCCESS_STORAGE_KEY = 'pending_registration_success_event'
+export const OAUTH_REGISTRATION_GA_SENT_KEY = 'oauth_registration_ga_sent'
+const FLUSH_RETRY_DELAYS_MS = [1000, 4000, 16000] as const
+
+export const REGISTRATION_METHODS = ['email', 'oauth'] as const
+
+export const ATTRIBUTION_KEYS = [
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_content',
+ 'utm_term',
+ 'slug',
+] as const
+
+export type RegistrationMethod = (typeof REGISTRATION_METHODS)[number]
+export type RegistrationAttribution = Partial<Record<(typeof ATTRIBUTION_KEYS)[number], string>>
+
+export type RegistrationIntent = {
+ registrationId: string
+ occurredAt: number
+ method: RegistrationMethod
+ attribution: RegistrationAttribution
+}
+
+let registrationDeliveryGeneration = 0
+let flushRetryTimer: ReturnType<typeof setTimeout> | null = null
+let flushRetryAttempt = 0
+
+export const getRegistrationSessionStorage = (): Storage | null => {
+ try {
+ if (typeof window === 'undefined') return null
+ return window.sessionStorage
+ } catch {
+ return null
+ }
+}
+
+export const removeStoredRegistrationMarker = (storage = getRegistrationSessionStorage()) => {
+ try {
+ storage?.removeItem(REGISTRATION_SUCCESS_STORAGE_KEY)
+ } catch {}
+}
+
+export const hasSentOAuthRegistrationGA = () => {
+ try {
+ return getRegistrationSessionStorage()?.getItem(OAUTH_REGISTRATION_GA_SENT_KEY) === 'true'
+ } catch {
+ return false
+ }
+}
+
+export const markOAuthRegistrationGASent = () => {
+ try {
+ getRegistrationSessionStorage()?.setItem(OAUTH_REGISTRATION_GA_SENT_KEY, 'true')
+ } catch {}
+}
+
+export const clearOAuthRegistrationGAGuard = () => {
+ try {
+ getRegistrationSessionStorage()?.removeItem(OAUTH_REGISTRATION_GA_SENT_KEY)
+ } catch {}
+}
+
+export const getRegistrationDeliveryGeneration = () => registrationDeliveryGeneration
+
+export const clearRegistrationFlushRetry = () => {
+ if (flushRetryTimer !== null) {
+ clearTimeout(flushRetryTimer)
+ flushRetryTimer = null
+ }
+ flushRetryAttempt = 0
+}
+
+export const scheduleRegistrationFlushRetry = (runFlush: () => void) => {
+ if (flushRetryAttempt >= FLUSH_RETRY_DELAYS_MS.length) return
+
+ const delay = FLUSH_RETRY_DELAYS_MS[flushRetryAttempt]
+ flushRetryAttempt += 1
+ const generation = registrationDeliveryGeneration
+ if (flushRetryTimer !== null) clearTimeout(flushRetryTimer)
+
+ flushRetryTimer = setTimeout(() => {
+ flushRetryTimer = null
+ if (generation !== registrationDeliveryGeneration) return
+ runFlush()
+ }, delay)
+}
+
+export const invalidateRegistrationDeliveryState = () => {
+ registrationDeliveryGeneration += 1
+ clearRegistrationFlushRetry()
+ removeStoredRegistrationMarker()
+}
+
+export const discardRegistrationSessionState = () => {
+ invalidateRegistrationDeliveryState()
+ clearOAuthRegistrationGAGuard()
+}
diff --git a/web/app/components/base/amplitude/registration-tracking.ts b/web/app/components/base/amplitude/registration-tracking.ts
index 5562d2173c4..15c11bc6590 100644
--- a/web/app/components/base/amplitude/registration-tracking.ts
+++ b/web/app/components/base/amplitude/registration-tracking.ts
@@ -1,38 +1,121 @@
+import type {
+ RegistrationAttribution,
+ RegistrationIntent,
+ RegistrationMethod,
+} from './registration-session-state'
+import type { AnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
import { getAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
+import { getIsAmplitudeInitialized } from './init'
+import {
+ ATTRIBUTION_KEYS,
+ clearRegistrationFlushRetry,
+ getRegistrationDeliveryGeneration,
+ getRegistrationSessionStorage,
+ invalidateRegistrationDeliveryState,
+ REGISTRATION_METHODS,
+ REGISTRATION_SUCCESS_STORAGE_KEY,
+ removeStoredRegistrationMarker,
+ scheduleRegistrationFlushRetry,
+} from './registration-session-state'
import { trackEvent } from './utils'
-/**
- * Storage key for a registration success event that is waiting to be sent to
- * Amplitude until a user ID has been attached.
- */
-export const REGISTRATION_SUCCESS_STORAGE_KEY = 'pending_registration_success_event'
+const REGISTRATION_MARKER_VERSION = 2
+const REGISTRATION_MARKER_TTL_MS = 24 * 60 * 60 * 1000
+// Browser clocks may be corrected between registration and delivery. Permit a small
+// correction, but reject timestamps far enough ahead to corrupt Amplitude ordering.
+const REGISTRATION_FUTURE_CLOCK_SKEW_ALLOWANCE_MS = 5 * 60 * 1000
+const SUCCESSFUL_TRACK_RESULT_MIN = 200
+const SUCCESSFUL_TRACK_RESULT_MAX = 299
-type RegistrationMethod = 'email' | 'oauth'
+const REGISTRATION_EVENT_NAMES = [
+ 'user_registration_success',
+ 'user_registration_success_with_utm',
+] as const
-type PendingRegistrationSuccessEvent = {
- eventName: string
- properties: Record<string, unknown>
+type RegistrationEventName = (typeof REGISTRATION_EVENT_NAMES)[number]
+
+type PendingRegistrationSuccessEvent = RegistrationIntent & {
+ version: typeof REGISTRATION_MARKER_VERSION
+ expiresAt: number
+ eventName: RegistrationEventName
+}
+
+let registrationSnapshot = 0
+let activeFlush: { generation: number; promise: Promise<void> } | null = null
+const registrationListeners = new Set<() => void>()
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+
+const isRegistrationMethod = (value: unknown): value is RegistrationMethod =>
+ typeof value === 'string' && REGISTRATION_METHODS.includes(value as RegistrationMethod)
+
+const isRegistrationEventName = (value: unknown): value is RegistrationEventName =>
+ typeof value === 'string' && REGISTRATION_EVENT_NAMES.includes(value as RegistrationEventName)
+
+const notifyRegistrationMarkerStored = () => {
+ registrationSnapshot += 1
+ registrationListeners.forEach((listener) => listener())
}
-const getSessionStorage = (): Storage | null => {
+const createRegistrationId = () => {
try {
- if (typeof window === 'undefined') return null
- return window.sessionStorage
+ return globalThis.crypto.randomUUID()
} catch {
- return null
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`
+ }
+}
+
+export const normalizeRegistrationAttribution = (
+ value?: Record<string, unknown> | null,
+): RegistrationAttribution | null => {
+ if (!value) return null
+
+ const attribution: RegistrationAttribution = {}
+ ATTRIBUTION_KEYS.forEach((key) => {
+ const item = value[key]
+ if (typeof item !== 'string') return
+
+ const normalized = item.trim()
+ if (normalized) attribution[key] = normalized
+ })
+
+ return Object.keys(attribution).length ? attribution : null
+}
+
+const createRegistrationIntent = (
+ method: RegistrationMethod,
+ utmInfo?: Record<string, unknown> | null,
+): RegistrationIntent => ({
+ registrationId: createRegistrationId(),
+ occurredAt: Date.now(),
+ method,
+ attribution: normalizeRegistrationAttribution(utmInfo) ?? {},
+})
+
+const storeRegistrationIntent = (intent: RegistrationIntent) => {
+ const storage = getRegistrationSessionStorage()
+ if (!storage) return false
+
+ const pending: PendingRegistrationSuccessEvent = {
+ ...intent,
+ version: REGISTRATION_MARKER_VERSION,
+ expiresAt: intent.occurredAt + REGISTRATION_MARKER_TTL_MS,
+ eventName: Object.keys(intent.attribution).length
+ ? 'user_registration_success_with_utm'
+ : 'user_registration_success',
+ }
+
+ try {
+ storage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, JSON.stringify(pending))
+ clearRegistrationFlushRetry()
+ notifyRegistrationMarkerStored()
+ return true
+ } catch {
+ return false
}
}
-/**
- * Remember a registration success event after analytics consent so it can be sent
- * to Amplitude *after* the user ID is attached (see `flushRegistrationSuccess`).
- *
- * Amplitude attributes events to whatever identity is active when `track` runs. At
- * registration time the client does not yet know the user ID, so firing the event
- * immediately records it under an anonymous profile. We persist the event here and
- * replay it once `setUserId` runs in the bootstrap effects after the redirect. An
- * event produced before analytics consent is granted is dropped instead of queued.
- */
export const rememberRegistrationSuccess = ({
method,
utmInfo,
@@ -40,49 +123,157 @@ export const rememberRegistrationSuccess = ({
method: RegistrationMethod
utmInfo?: Record<string, unknown> | null
}) => {
- if (getAnalyticsConsent() !== 'granted') return
+ const consent = getAnalyticsConsent()
+ if (consent === 'denied' || consent === 'disabled') {
+ invalidateRegistrationDeliveryState()
+ return false
+ }
- const storage = getSessionStorage()
- if (!storage) return
+ // Persist even while consent is unknown. Flush waits for grant + Amplitude init
+ // + user identity, so a later full-page redirect still has the marker.
+ return storeRegistrationIntent(createRegistrationIntent(method, utmInfo))
+}
- const pending: PendingRegistrationSuccessEvent = {
- eventName: utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success',
- properties: { method, ...utmInfo },
- }
+export const coordinateRegistrationConsent = (consent: AnalyticsConsent) => {
+ if (consent === 'denied' || consent === 'disabled') invalidateRegistrationDeliveryState()
+}
- try {
- storage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, JSON.stringify(pending))
- } catch {}
+export const subscribeRegistrationSuccess = (listener: () => void) => {
+ registrationListeners.add(listener)
+ return () => registrationListeners.delete(listener)
}
-/**
- * Send a previously remembered registration success event to Amplitude.
- *
- * MUST be called after `setUserId` so the event lands on the identified user profile.
- * No-op when nothing is pending. The pending entry is removed before tracking so the
- * event fires at most once even if this runs multiple times.
- */
-export const flushRegistrationSuccess = () => {
- const storage = getSessionStorage()
- if (!storage) return
+export const getRegistrationSuccessSnapshot = () => registrationSnapshot
+
+const isRegistrationAttribution = (value: unknown): value is RegistrationAttribution => {
+ if (!isRecord(value)) return false
+
+ return Object.entries(value).every(
+ ([key, item]) =>
+ ATTRIBUTION_KEYS.includes(key as (typeof ATTRIBUTION_KEYS)[number]) &&
+ typeof item === 'string' &&
+ Boolean(item.trim()),
+ )
+}
- let raw: string | null = null
+const parsePendingRegistration = (raw: string): PendingRegistrationSuccessEvent | null => {
try {
- raw = storage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)
+ const value: unknown = JSON.parse(raw)
+ if (!isRecord(value)) return null
+ if (value.version !== REGISTRATION_MARKER_VERSION) return null
+ if (typeof value.registrationId !== 'string' || !value.registrationId) return null
+ if (typeof value.occurredAt !== 'number' || !Number.isFinite(value.occurredAt)) return null
+ if (typeof value.expiresAt !== 'number' || !Number.isFinite(value.expiresAt)) return null
+ if (value.expiresAt !== value.occurredAt + REGISTRATION_MARKER_TTL_MS) return null
+ if (!isRegistrationEventName(value.eventName)) return null
+ if (!isRegistrationMethod(value.method)) return null
+ if (!isRegistrationAttribution(value.attribution)) return null
+
+ const hasAttribution = Object.keys(value.attribution).length > 0
+ if (hasAttribution !== (value.eventName === 'user_registration_success_with_utm')) return null
+
+ return value as PendingRegistrationSuccessEvent
} catch {
+ return null
+ }
+}
+
+const runRegistrationFlush = async (generation: number) => {
+ const isStale = () => generation !== getRegistrationDeliveryGeneration()
+ if (isStale()) return
+
+ const consent = getAnalyticsConsent()
+ if (consent === 'unknown') return
+
+ const storage = getRegistrationSessionStorage()
+ if (!storage) return
+
+ if (consent === 'denied' || consent === 'disabled') {
+ invalidateRegistrationDeliveryState()
return
}
+ if (!getIsAmplitudeInitialized()) return
- if (!raw) return
+ while (true) {
+ if (isStale()) return
- try {
- storage.removeItem(REGISTRATION_SUCCESS_STORAGE_KEY)
- } catch {}
+ let raw: string | null
+ try {
+ raw = storage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)
+ } catch {
+ return
+ }
+ if (!raw) return
- if (getAnalyticsConsent() !== 'granted') return
+ const pending = parsePendingRegistration(raw)
+ const now = Date.now()
+ if (
+ !pending ||
+ pending.expiresAt <= now ||
+ pending.occurredAt > now + REGISTRATION_FUTURE_CLOCK_SKEW_ALLOWANCE_MS
+ ) {
+ removeStoredRegistrationMarker(storage)
+ return
+ }
- try {
- const pending = JSON.parse(raw) as PendingRegistrationSuccessEvent
- if (pending?.eventName) trackEvent(pending.eventName, pending.properties)
- } catch {}
+ let trackResult: ReturnType<typeof trackEvent>
+ try {
+ trackResult = trackEvent(
+ pending.eventName,
+ {
+ method: pending.method,
+ ...pending.attribution,
+ registration_id: pending.registrationId,
+ event_version: REGISTRATION_MARKER_VERSION,
+ tracking_contract_version: 'consent_wait_v2',
+ },
+ {
+ insert_id: pending.registrationId,
+ time: pending.occurredAt,
+ },
+ )
+ } catch {
+ return
+ }
+ if (!trackResult) return
+
+ let acknowledged = false
+ try {
+ const result: { code?: unknown } = await trackResult.promise
+ acknowledged =
+ typeof result.code === 'number' &&
+ result.code >= SUCCESSFUL_TRACK_RESULT_MIN &&
+ result.code <= SUCCESSFUL_TRACK_RESULT_MAX
+ } catch {}
+ if (isStale()) return
+
+ let currentRaw: string | null
+ try {
+ currentRaw = storage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)
+ } catch {
+ return
+ }
+ if (currentRaw !== raw) continue
+ if (!acknowledged) {
+ scheduleRegistrationFlushRetry(() => {
+ void flushRegistrationSuccess()
+ })
+ return
+ }
+
+ clearRegistrationFlushRetry()
+ removeStoredRegistrationMarker(storage)
+ return
+ }
+}
+
+export function flushRegistrationSuccess() {
+ const generation = getRegistrationDeliveryGeneration()
+ if (activeFlush?.generation === generation) return activeFlush.promise
+
+ const promise = runRegistrationFlush(generation).finally(() => {
+ if (activeFlush?.promise === promise) activeFlush = null
+ })
+ activeFlush = { generation, promise }
+ return promise
}
diff --git a/web/app/components/base/amplitude/utils.ts b/web/app/components/base/amplitude/utils.ts
index 58354463fc1..bb6021d0ad1 100644
--- a/web/app/components/base/amplitude/utils.ts
+++ b/web/app/components/base/amplitude/utils.ts
@@ -9,8 +9,13 @@ const canUseAmplitude = () => getAnalyticsConsent() === 'granted' && getIsAmplit
* @param eventName Event name
* @param eventProperties Event properties (optional)
*/
-export const trackEvent = (eventName: string, eventProperties?: Record<string, unknown>) => {
+export const trackEvent = (
+ eventName: string,
+ eventProperties?: Record<string, unknown>,
+ eventOptions?: amplitude.Types.EventOptions,
+) => {
if (!canUseAmplitude()) return
+ if (eventOptions) return amplitude.track(eventName, eventProperties, eventOptions)
return amplitude.track(eventName, eventProperties)
}
diff --git a/web/app/components/base/analytics-consent/__tests__/analytics-disabled.spec.tsx b/web/app/components/base/analytics-consent/__tests__/analytics-disabled.spec.tsx
new file mode 100644
index 00000000000..65443ba0046
--- /dev/null
+++ b/web/app/components/base/analytics-consent/__tests__/analytics-disabled.spec.tsx
@@ -0,0 +1,26 @@
+import { render, waitFor } from '@testing-library/react'
+import { REGISTRATION_SUCCESS_STORAGE_KEY } from '../../amplitude/registration-session-state'
+import {
+ coordinateRegistrationConsent,
+ rememberRegistrationSuccess,
+} from '../../amplitude/registration-tracking'
+import { AnalyticsDisabled } from '../analytics-disabled'
+import { getAnalyticsConsent, setAnalyticsConsent } from '../consent-store'
+
+describe('AnalyticsDisabled', () => {
+ beforeEach(() => {
+ window.sessionStorage.clear()
+ coordinateRegistrationConsent('denied')
+ setAnalyticsConsent('granted')
+ })
+
+ it('terminally discards a pending registration marker', async () => {
+ rememberRegistrationSuccess({ method: 'email' })
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).not.toBeNull()
+
+ render(<AnalyticsDisabled />)
+
+ await waitFor(() => expect(getAnalyticsConsent()).toBe('disabled'))
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ })
+})
diff --git a/web/app/components/base/analytics-consent/__tests__/analytics-runtimes.spec.tsx b/web/app/components/base/analytics-consent/__tests__/analytics-runtimes.spec.tsx
index bfad2dc720a..d7dabf25264 100644
--- a/web/app/components/base/analytics-consent/__tests__/analytics-runtimes.spec.tsx
+++ b/web/app/components/base/analytics-consent/__tests__/analytics-runtimes.spec.tsx
@@ -14,6 +14,10 @@ vi.mock('@/app/components/base/amplitude/WebAppAmplitudeProvider', () => ({
WebAppAmplitudeProvider: () => <span data-testid="web-app-amplitude-provider" />,
}))
+vi.mock('@/app/components/base/amplitude/registration-consent-coordinator', () => ({
+ RegistrationConsentCoordinator: () => <span data-testid="registration-consent-coordinator" />,
+}))
+
vi.mock('@/app/components/external-attribution-recorder', () => ({
default: () => <span data-testid="external-attribution-recorder" />,
}))
@@ -24,6 +28,7 @@ describe('analytics runtimes', () => {
expect(screen.getByTestId('cookieyes-consent-bridge')).toBeInTheDocument()
expect(screen.getByTestId('console-amplitude-provider')).toBeInTheDocument()
+ expect(screen.getByTestId('registration-consent-coordinator')).toBeInTheDocument()
expect(screen.getByTestId('external-attribution-recorder')).toBeInTheDocument()
expect(screen.queryByTestId('web-app-amplitude-provider')).toBeNull()
})
@@ -34,6 +39,7 @@ describe('analytics runtimes', () => {
expect(screen.getByTestId('cookieyes-consent-bridge')).toBeInTheDocument()
expect(screen.getByTestId('web-app-amplitude-provider')).toBeInTheDocument()
expect(screen.queryByTestId('console-amplitude-provider')).toBeNull()
+ expect(screen.queryByTestId('registration-consent-coordinator')).toBeNull()
expect(screen.queryByTestId('external-attribution-recorder')).toBeNull()
})
})
diff --git a/web/app/components/base/analytics-consent/__tests__/cloud-analytics.spec.tsx b/web/app/components/base/analytics-consent/__tests__/cloud-analytics.spec.tsx
index 2380b7485c0..a4dc0dc299b 100644
--- a/web/app/components/base/analytics-consent/__tests__/cloud-analytics.spec.tsx
+++ b/web/app/components/base/analytics-consent/__tests__/cloud-analytics.spec.tsx
@@ -1,5 +1,6 @@
import { QueryClient } from '@tanstack/react-query'
import { render } from '@testing-library/react'
+import { REGISTRATION_SUCCESS_STORAGE_KEY } from '@/app/components/base/amplitude/registration-session-state'
let queryClient: QueryClient
@@ -55,9 +56,13 @@ vi.mock('../cloud-analytics-layout-boundary', () => ({
),
}))
-async function renderCloudAnalytics() {
+async function getCloudAnalyticsResult() {
const { CloudAnalytics } = await import('../cloud-analytics')
- return render(await CloudAnalytics())
+ return CloudAnalytics()
+}
+
+async function renderCloudAnalytics() {
+ return render(await getCloudAnalyticsResult())
}
describe('CloudAnalytics', () => {
@@ -68,6 +73,7 @@ describe('CloudAnalytics', () => {
configState.isProd = true
configState.webPrefix = 'https://cloud.dify.ai'
queryClient = new QueryClient()
+ window.sessionStorage.clear()
queryClient.setQueryData(systemFeaturesQueryKey, { deployment_edition: 'CLOUD' })
mockHeadersGet.mockImplementation((name: string) => {
const values: Record<string, string> = {
@@ -94,9 +100,13 @@ describe('CloudAnalytics', () => {
return values[name] ?? null
})
- const { queryByTestId } = await renderCloudAnalytics()
+ const result = await getCloudAnalyticsResult()
+ const { queryByTestId } = render(result)
expect(queryByTestId('cloud-analytics-layout-boundary')).toBeNull()
+ expect(result).not.toBeNull()
+ const { getAnalyticsConsent } = await import('../consent-store')
+ expect(getAnalyticsConsent()).toBe('disabled')
})
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
@@ -109,11 +119,16 @@ describe('CloudAnalytics', () => {
},
)
- it('does not render when System Features are unavailable', async () => {
+ it('suspends analytics without deleting pending registration state when System Features are unavailable', async () => {
queryClient.removeQueries({ queryKey: systemFeaturesQueryKey })
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'pending-marker')
- const { queryByTestId } = await renderCloudAnalytics()
+ const result = await getCloudAnalyticsResult()
+ const { queryByTestId } = render(result)
expect(queryByTestId('cloud-analytics-layout-boundary')).toBeNull()
+ const { getAnalyticsConsent } = await import('../consent-store')
+ expect(getAnalyticsConsent()).toBe('unknown')
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBe('pending-marker')
})
})
diff --git a/web/app/components/base/analytics-consent/analytics-disabled.tsx b/web/app/components/base/analytics-consent/analytics-disabled.tsx
new file mode 100644
index 00000000000..a562e67c51a
--- /dev/null
+++ b/web/app/components/base/analytics-consent/analytics-disabled.tsx
@@ -0,0 +1,14 @@
+'use client'
+
+import { useEffect } from 'react'
+import { coordinateRegistrationConsent } from '@/app/components/base/amplitude/registration-tracking'
+import { setAnalyticsConsent } from './consent-store'
+
+export function AnalyticsDisabled() {
+ useEffect(() => {
+ setAnalyticsConsent('disabled')
+ coordinateRegistrationConsent('disabled')
+ }, [])
+
+ return null
+}
diff --git a/web/app/components/base/analytics-consent/cloud-analytics.tsx b/web/app/components/base/analytics-consent/cloud-analytics.tsx
index 9b53224b494..cf4bd0055f7 100644
--- a/web/app/components/base/analytics-consent/cloud-analytics.tsx
+++ b/web/app/components/base/analytics-consent/cloud-analytics.tsx
@@ -1,6 +1,7 @@
import { COOKIEYES_SITE_KEY, IS_PROD, WEB_PREFIX } from '@/config'
import { getCachedSystemFeatures } from '@/features/system-features/server'
import { headers } from '@/next/headers'
+import { AnalyticsDisabled } from './analytics-disabled'
import { CloudAnalyticsLayoutBoundary } from './cloud-analytics-layout-boundary'
import { isCloudAnalyticsRequest } from './request-boundary'
@@ -19,7 +20,7 @@ export async function CloudAnalytics() {
webPrefix: WEB_PREFIX,
})
- if (!enabled) return null
+ if (!enabled) return <AnalyticsDisabled />
const nonce = requestHeaders.get('x-nonce') ?? undefined
diff --git a/web/app/components/base/analytics-consent/consent-store.ts b/web/app/components/base/analytics-consent/consent-store.ts
index 030d3f770b7..b1f77c2eac7 100644
--- a/web/app/components/base/analytics-consent/consent-store.ts
+++ b/web/app/components/base/analytics-consent/consent-store.ts
@@ -2,7 +2,7 @@
import { useSyncExternalStore } from 'react'
-export type AnalyticsConsent = 'unknown' | 'denied' | 'granted'
+export type AnalyticsConsent = 'unknown' | 'denied' | 'granted' | 'disabled'
type CookieYesConsentUpdateDetail = {
accepted: string[]
diff --git a/web/app/components/base/analytics-consent/console-analytics-runtime.tsx b/web/app/components/base/analytics-consent/console-analytics-runtime.tsx
index b0f97e5cd7e..00814fad51c 100644
--- a/web/app/components/base/analytics-consent/console-analytics-runtime.tsx
+++ b/web/app/components/base/analytics-consent/console-analytics-runtime.tsx
@@ -1,6 +1,7 @@
'use client'
import AmplitudeProvider from '@/app/components/base/amplitude'
+import { RegistrationConsentCoordinator } from '@/app/components/base/amplitude/registration-consent-coordinator'
import ExternalAttributionRecorder from '@/app/components/external-attribution-recorder'
import { CookieYesConsentBridge } from './cookieyes-consent-bridge'
@@ -9,6 +10,7 @@ export function ConsoleAnalyticsRuntime() {
<>
<CookieYesConsentBridge />
<AmplitudeProvider />
+ <RegistrationConsentCoordinator />
<ExternalAttributionRecorder />
</>
)
diff --git a/web/app/components/oauth-registration-analytics.tsx b/web/app/components/oauth-registration-analytics.tsx
index fd7eb3bc542..e82adaf2923 100644
--- a/web/app/components/oauth-registration-analytics.tsx
+++ b/web/app/components/oauth-registration-analytics.tsx
@@ -2,9 +2,18 @@
import Cookies from 'js-cookie'
import { useEffect, useRef } from 'react'
+import { useAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
import { useSearchParams } from '@/next/navigation'
import { sendGAEvent } from '@/utils/gtag'
-import { rememberRegistrationSuccess } from './base/amplitude/registration-tracking'
+import {
+ clearOAuthRegistrationGAGuard,
+ hasSentOAuthRegistrationGA,
+ markOAuthRegistrationGASent,
+} from './base/amplitude/registration-session-state'
+import {
+ normalizeRegistrationAttribution,
+ rememberRegistrationSuccess,
+} from './base/amplitude/registration-tracking'
const OAUTH_NEW_USER_PARAM = 'oauth_new_user'
@@ -18,46 +27,75 @@ const removeOAuthNewUserParam = () => {
}
export function OAuthRegistrationAnalytics() {
+ const analyticsConsent = useAnalyticsConsent()
const searchParams = useSearchParams()
const oauthNewUserParam = searchParams.get(OAUTH_NEW_USER_PARAM)
- const handledParamRef = useRef<string | null>(null)
+ const gaHandledRef = useRef(false)
+ const amplitudeHandledRef = useRef(false)
+ const cleanedRef = useRef(false)
+ const utmInfoRef = useRef<ReturnType<typeof normalizeRegistrationAttribution> | undefined>(
+ undefined,
+ )
useEffect(() => {
- if (oauthNewUserParam === null || handledParamRef.current === oauthNewUserParam) return
+ if (oauthNewUserParam === null) {
+ clearOAuthRegistrationGAGuard()
+ return
+ }
- handledParamRef.current = oauthNewUserParam
const oauthNewUser = oauthNewUserParam === 'true'
if (!oauthNewUser) {
- removeOAuthNewUserParam()
+ if (!cleanedRef.current) {
+ cleanedRef.current = true
+ clearOAuthRegistrationGAGuard()
+ removeOAuthNewUserParam()
+ }
return
}
- let utmInfo: Record<string, unknown> | null = null
- const utmInfoStr = Cookies.get('utm_info')
- if (utmInfoStr) {
- try {
- const parsed: unknown = JSON.parse(utmInfoStr)
- if (isRecord(parsed)) utmInfo = parsed
- } catch (e) {
- console.error('Failed to parse utm_info cookie:', e)
+ if (utmInfoRef.current === undefined) {
+ let parsedUtmInfo: Record<string, unknown> | null = null
+ const utmInfoStr = Cookies.get('utm_info')
+ if (utmInfoStr) {
+ try {
+ const parsed: unknown = JSON.parse(utmInfoStr)
+ if (isRecord(parsed)) parsedUtmInfo = parsed
+ } catch (e) {
+ console.error('Failed to parse utm_info cookie:', e)
+ }
}
+ utmInfoRef.current = normalizeRegistrationAttribution(parsedUtmInfo)
}
+ const utmInfo = utmInfoRef.current
const eventName = utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success'
- // Defer the Amplitude event until the user ID is attached. The app context
- // external sync replays it after setUserId runs. Firing it here would record it under an
- // anonymous Amplitude profile (no user ID set yet).
- rememberRegistrationSuccess({ method: 'oauth', utmInfo })
+ if (!gaHandledRef.current) {
+ gaHandledRef.current = true
+ if (!hasSentOAuthRegistrationGA()) {
+ sendGAEvent(eventName, {
+ method: 'oauth',
+ ...utmInfo,
+ })
+ markOAuthRegistrationGASent()
+ }
+ }
- sendGAEvent(eventName, {
- method: 'oauth',
- ...utmInfo,
- })
+ if (
+ (analyticsConsent === 'unknown' || analyticsConsent === 'granted') &&
+ !amplitudeHandledRef.current
+ ) {
+ const persisted = rememberRegistrationSuccess({ method: 'oauth', utmInfo })
+ if (!persisted) return
+ amplitudeHandledRef.current = true
+ }
- Cookies.remove('utm_info')
- removeOAuthNewUserParam()
- }, [oauthNewUserParam])
+ if (!cleanedRef.current) {
+ cleanedRef.current = true
+ Cookies.remove('utm_info')
+ removeOAuthNewUserParam()
+ }
+ }, [analyticsConsent, oauthNewUserParam])
return null
}
diff --git a/web/context/__tests__/console-bootstrap.spec.tsx b/web/context/__tests__/console-bootstrap.spec.tsx
index 9e0e66bbbb1..3287a77cd5a 100644
--- a/web/context/__tests__/console-bootstrap.spec.tsx
+++ b/web/context/__tests__/console-bootstrap.spec.tsx
@@ -186,6 +186,8 @@ vi.mock('@/app/components/base/amplitude/use-amplitude-initialized', () => ({
vi.mock('@/app/components/base/amplitude/registration-tracking', () => ({
flushRegistrationSuccess: vi.fn(),
+ subscribeRegistrationSuccess: () => () => {},
+ getRegistrationSuccessSnapshot: () => 0,
}))
vi.mock('@/app/components/base/zendesk/utils', () => ({
diff --git a/web/service/__tests__/base-request.spec.ts b/web/service/__tests__/base-request.spec.ts
index c324a83cb55..0da529bc10c 100644
--- a/web/service/__tests__/base-request.spec.ts
+++ b/web/service/__tests__/base-request.spec.ts
@@ -1,4 +1,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import {
+ discardRegistrationSessionState,
+ OAUTH_REGISTRATION_GA_SENT_KEY,
+ REGISTRATION_SUCCESS_STORAGE_KEY,
+} from '@/app/components/base/amplitude/registration-session-state'
// oxlint-disable-next-line no-restricted-imports -- This spec directly tests the legacy request owner.
import { request } from '../base'
@@ -51,6 +56,21 @@ const createUnauthorizedResponse = () =>
},
)
+const createForcedLogoutResponse = () =>
+ new Response(
+ JSON.stringify({
+ code: 'unauthorized_and_force_logout',
+ message: 'This account session is no longer valid.',
+ status: 401,
+ }),
+ {
+ status: 401,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ },
+ )
+
type ClientRequestOptions = {
response: Response
refreshError?: Error
@@ -80,9 +100,11 @@ describe('request 401 handling', () => {
writable: true,
configurable: true,
})
+ window.sessionStorage.clear()
})
afterEach(() => {
+ discardRegistrationSessionState()
Object.defineProperty(globalThis, 'location', {
value: originalLocation,
writable: true,
@@ -103,21 +125,42 @@ describe('request 401 handling', () => {
it('should preserve the current URL when a 401 response cannot be parsed', async () => {
const response = new Response('not-json', { status: 401 })
arrangeClientRequest({ response })
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'account-a-marker')
await expect(request('/account/profile')).rejects.toBe(response)
expect(globalThis.location.href).toBe(
`https://example.com/app/signin?redirect_url=${encodeURIComponent('/app/apps?category=agent#recent')}`,
)
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
expect(mocks.refreshAccessTokenOrReLogin).not.toHaveBeenCalled()
})
+ it('clears account A registration state before a forced reload so account B starts clean', async () => {
+ const response = createForcedLogoutResponse()
+ arrangeClientRequest({ response })
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'account-a-marker')
+ window.sessionStorage.setItem(OAUTH_REGISTRATION_GA_SENT_KEY, 'true')
+ const reload = vi.fn(() => {
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ expect(window.sessionStorage.getItem(OAUTH_REGISTRATION_GA_SENT_KEY)).toBeNull()
+ })
+ globalThis.location.reload = reload
+
+ await expect(request('/account/profile')).rejects.toBe(response)
+
+ expect(reload).toHaveBeenCalledOnce()
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'account-b-marker')
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBe('account-b-marker')
+ })
+
it('should preserve the current URL when token refresh fails', async () => {
const response = createUnauthorizedResponse()
arrangeClientRequest({
response,
refreshError: new Error('refresh failed'),
})
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'account-a-marker')
await expect(request('/account/profile')).rejects.toBe(response)
@@ -125,5 +168,16 @@ describe('request 401 handling', () => {
expect(globalThis.location.href).toBe(
`https://example.com/app/signin?redirect_url=${encodeURIComponent('/app/apps?category=agent#recent')}`,
)
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ })
+
+ it('does not clear console registration state for a public-app 401 redirect', async () => {
+ const response = createUnauthorizedResponse()
+ arrangeClientRequest({ response })
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'console-marker')
+
+ await expect(request('/account/profile', {}, { isPublicAPI: true })).rejects.toBe(response)
+
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBe('console-marker')
})
})
diff --git a/web/service/base.ts b/web/service/base.ts
index d5ece4cd7d4..ea2435fdb6b 100644
--- a/web/service/base.ts
+++ b/web/service/base.ts
@@ -30,6 +30,7 @@ import type {
} from '@/types/workflow'
import { toast } from '@langgenius/dify-ui/toast'
import Cookies from 'js-cookie'
+import { discardRegistrationSessionState } from '@/app/components/base/amplitude/registration-session-state'
import {
API_PREFIX,
CSRF_COOKIE_NAME,
@@ -197,6 +198,14 @@ export type IOtherOptions = {
onDataSourceNodeError?: IOnDataSourceNodeError
}
+const discardRegistrationStateForConsoleAuthBoundary = ({
+ isMarketplaceAPI,
+ isPublicAPI,
+}: IOtherOptions) => {
+ if (isMarketplaceAPI || isPublicAPI) return
+ discardRegistrationSessionState()
+}
+
function jumpTo(url: string) {
if (!url || !isClient) return
const targetPath = new URL(url, window.location.origin).pathname
@@ -1008,6 +1017,7 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe
const [parseErr, errRespData] = await asyncRunSafe<ResponseError>(errResp.json())
if (parseErr) {
+ discardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)
window.location.href = buildSigninUrlWithRedirect()
return Promise.reject(err)
}
@@ -1025,6 +1035,7 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe
}
if (code === 'unauthorized_and_force_logout') {
// Cookies will be cleared by the backend
+ discardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)
window.location.reload()
return Promise.reject(err)
}
@@ -1053,6 +1064,7 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe
// there. Redirecting to /signin loses the user_code context and
// the post-login flow lands on /apps instead of returning here.
if (window.location.pathname === `${basePath}/device`) return Promise.reject(err)
+ discardRegistrationStateForConsoleAuthBoundary(otherOptionsForBaseFetch)
if (window.location.pathname !== `${basePath}/signin`) {
jumpTo(buildSigninUrlWithRedirect())
return Promise.reject(err)
diff --git a/web/service/common.spec.ts b/web/service/common.spec.ts
index ef678cb69f9..cfbf09ad331 100644
--- a/web/service/common.spec.ts
+++ b/web/service/common.spec.ts
@@ -1,5 +1,14 @@
+import type { ReactNode } from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, renderHook } from '@testing-library/react'
+import { createElement } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import {
+ OAUTH_REGISTRATION_GA_SENT_KEY,
+ REGISTRATION_SUCCESS_STORAGE_KEY,
+} from '@/app/components/base/amplitude/registration-session-state'
import { emailLoginWithCode, sendEMailLoginCode } from './common'
+import { useLogout } from './use-common'
const mocks = vi.hoisted(() => ({
post: vi.fn(),
@@ -68,3 +77,29 @@ describe('emailLoginWithCode', () => {
})
})
})
+
+describe('useLogout', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ window.sessionStorage.clear()
+ })
+
+ it('discards registration delivery state after a successful logout', async () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(['account-profile'], { id: 'previous-user' })
+ window.sessionStorage.setItem(REGISTRATION_SUCCESS_STORAGE_KEY, 'pending-marker')
+ window.sessionStorage.setItem(OAUTH_REGISTRATION_GA_SENT_KEY, 'true')
+ mocks.post.mockResolvedValueOnce({ result: 'success' })
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(QueryClientProvider, { client: queryClient }, children)
+ const { result } = renderHook(() => useLogout(), { wrapper })
+
+ await act(async () => {
+ await result.current.mutateAsync()
+ })
+
+ expect(window.sessionStorage.getItem(REGISTRATION_SUCCESS_STORAGE_KEY)).toBeNull()
+ expect(window.sessionStorage.getItem(OAUTH_REGISTRATION_GA_SENT_KEY)).toBeNull()
+ expect(queryClient.getQueryData(['account-profile'])).toBeUndefined()
+ })
+})
diff --git a/web/service/use-common.ts b/web/service/use-common.ts
index 95564c5fbea..524a38bfd0f 100644
--- a/web/service/use-common.ts
+++ b/web/service/use-common.ts
@@ -17,6 +17,7 @@ import type {
} from '@/models/common'
import type { RETRIEVE_METHOD } from '@/types/app'
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { discardRegistrationSessionState } from '@/app/components/base/amplitude/registration-session-state'
// oxlint-disable-next-line no-restricted-imports
import { get, post } from './base'
import { consoleQuery } from './client'
@@ -162,6 +163,7 @@ export const useLogout = () => {
mutationKey: [NAME_SPACE, 'logout'],
mutationFn: () => post('/logout'),
onSuccess: () => {
+ discardRegistrationSessionState()
// Drop all cached queries so the post-logout /signin probe doesn't read
// the previous user's profile (the userProfile queryKey is shared with
// the (commonLayout) tree, which keeps observing it during React's