:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mobile): stop notification registration from spinning forever (#130629)
Chris Volzer057b675e1f14
diff --git a/products/mobile/docs/PUSH.md b/products/mobile/docs/PUSH.mdindex c09b49633bfe..598d0319e7dc 100644--- a/products/mobile/docs/PUSH.md+++ b/products/mobile/docs/PUSH.md@@ -21,6 +21,8 @@ An expired session cannot authenticate an unregister request. Until the device sThe app saves a newly issued token before its registration POST, because a lost response does not prove the server rejected it. Registration and unregistration requests have bounded deadlines. A failed storage read lets the launch gate settle with default push state.+Fetching the Expo push token has a 15-second deadline. If the device or Expo does not respond, Settings stops spinning and shows an error with **Try again**. A late response cannot overwrite a later retry. Sign-out can continue once the token request times out.+Push is unavailable, and the app skips it without errors, on the web, in simulators and emulators, and in Expo Go.Settings shows which one applies.diff --git a/products/mobile/src/features/notifications/pushRegistration.test.ts b/products/mobile/src/features/notifications/pushRegistration.test.tsindex dce015c3c0b2..f3036be92c8e 100644--- a/products/mobile/src/features/notifications/pushRegistration.test.ts+++ b/products/mobile/src/features/notifications/pushRegistration.test.ts@@ -29,6 +29,8 @@ async function tick(): Promise<void> {}describe('push registration across session transitions', () => {+ afterEach(() => jest.useRealTimers())+beforeEach(async () => {await waitForPushHydration()setSessionTokens({@@ -60,6 +62,68 @@ describe('push registration across session transitions', () => {expoToken.mockReset().mockResolvedValue({ data: 'ExponentPushToken[new]' } as never)})+ test.each(['resolve', 'reject'] as const)(+ 'a stalled token request stops loading, allows a retry and ignores a late %s',+ async (outcome) => {+ jest.useFakeTimers()+ let finishToken!: (token: Notifications.ExpoPushToken) => void+ let failToken!: (error: Error) => void+ expoToken.mockImplementationOnce(+ () =>+ new Promise((resolve, reject) => {+ finishToken = resolve+ failToken = reject+ })+ )+ const syncing = syncPushRegistration('never')+ await jest.advanceTimersByTimeAsync(0)+ expect(usePushStore.getState().registering).toBe(true)++ await jest.advanceTimersByTimeAsync(15_000)+ expect(usePushStore.getState()).toMatchObject({+ registering: false,+ token: null,+ error: 'Push request timed out',+ })+ await syncing+ expect(register).not.toHaveBeenCalled()++ await syncPushRegistration('always')+ expect(usePushStore.getState()).toMatchObject({+ registering: false,+ token: 'ExponentPushToken[new]',+ error: null,+ })+ if (outcome === 'resolve') {+ finishToken({ type: 'expo', data: 'ExponentPushToken[late]' })+ } else {+ failToken(new Error('Late token failure'))+ }+ await jest.advanceTimersByTimeAsync(0)+ expect(register).toHaveBeenCalledTimes(1)+ expect(usePushStore.getState()).toMatchObject({ token: 'ExponentPushToken[new]', error: null })+ }+ )++ test('sign out completes after a stalled token request times out', async () => {+ jest.useFakeTimers()+ expoToken.mockImplementationOnce(() => new Promise(() => undefined))+ const syncing = syncPushRegistration('never')+ await jest.advanceTimersByTimeAsync(0)+ const cleanup = unregisterPush()++ await jest.advanceTimersByTimeAsync(15_000)+ expect(usePushStore.getState().registering).toBe(false)+ await syncing+ const recover = await cleanup+ expect(register).not.toHaveBeenCalled()+ expect(usePushStore.getState()).toMatchObject({ token: null, registeredFor: null, error: null })+ setSessionTokens(null)+ useAuthStore.setState({ status: 'signed_out', signedIn: false })+ recover()+ await jest.advanceTimersByTimeAsync(0)+ })+test('sign out waits for a first registration POST and then deletes its possibly accepted token', async () => {let finishPost: () => void = () => undefinedlet postStarted: () => void = () => undefineddiff --git a/products/mobile/src/features/notifications/pushRegistration.ts b/products/mobile/src/features/notifications/pushRegistration.tsindex 81926c7c1476..5da3faac5950 100644--- a/products/mobile/src/features/notifications/pushRegistration.ts+++ b/products/mobile/src/features/notifications/pushRegistration.ts@@ -19,6 +19,7 @@ export const ANDROID_CHANNEL_ID = 'default'const UNREGISTER_TIMEOUT_MS = 4_000const REGISTER_TIMEOUT_MS = 4_000+const TOKEN_TIMEOUT_MS = 15_000let closingSession: number | null = null/** `never`: register only if already granted. `once`: ask the first time after sign in. `always`: ask while allowed. */@@ -88,11 +89,11 @@ function isCurrentRegistration(session: number, key: string): boolean {return sessionGeneration() === session && registrationKey() === key && closingSession !== session}-async function withTimeout(work: (signal: AbortSignal) => Promise<void>, timeoutMs: number): Promise<void> {+async function withTimeout<T>(work: (signal: AbortSignal) => Promise<T>, timeoutMs: number): Promise<T> {const controller = new AbortController()let timer: ReturnType<typeof setTimeout> | undefinedtry {- await Promise.race([+ return await Promise.race([work(controller.signal),new Promise<never>((_resolve, reject) => {timer = setTimeout(() => {@@ -144,8 +145,9 @@ async function syncOnce(policy: PromptPolicy): Promise<void> {let gotToken = falsetry {const projectId: unknown = Constants.expoConfig?.extra?.eas?.projectId- const { data: token } = await Notifications.getExpoPushTokenAsync(- typeof projectId === 'string' ? { projectId } : {}+ const { data: token } = await withTimeout(+ () => Notifications.getExpoPushTokenAsync(typeof projectId === 'string' ? { projectId } : {}),+ TOKEN_TIMEOUT_MS)gotToken = trueif (!isCurrentRegistration(session, key)) {