: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): preserve android notification taps during startup (#127878)
Chris Volzerc86631abbc58
diff --git a/products/mobile/app.config.ts b/products/mobile/app.config.tsindex 12fd28b8e4e9..fa7ea7f8f0a3 100644--- a/products/mobile/app.config.ts+++ b/products/mobile/app.config.ts@@ -154,6 +154,7 @@ export default ({ config, projectRoot }: ConfigContext): ExpoConfig => {],['./plugins/withAndroidLoopbackNetworking', { allowLoopback: variant !== 'production' }],'./plugins/withAndroidAdaptiveIconInsets',+ './plugins/withAndroidNotificationIntents','./plugins/withIosSceneLifecycle','@bacons/apple-targets',],diff --git a/products/mobile/docs/PUSH.md b/products/mobile/docs/PUSH.mdindex dbd6e1383b73..c09b49633bfe 100644--- a/products/mobile/docs/PUSH.md+++ b/products/mobile/docs/PUSH.md@@ -96,8 +96,21 @@ Kinds: `completed`, `failed`, `cancelled`, `awaiting`, `turn_completed`, `thread`useNotificationRouting()` handles taps that start the app (`getLastNotificationResponse`) and taps while it runs (`addNotificationResponseReceivedListener`).It waits until the navigator is mounted and the session has loaded, and handles each notification id once.+A signed-out tap waits for sign-in. On Android, the most recent push or snooze reminder tap survives+process death and opens once routing is ready. On iOS, Expo keeps the response in memory. If the+process dies before sign-in finishes, reopen the target from the inbox or chats.The pure resolver is `resolveNotificationRoute()` in `notificationRouting.ts`.+On Android, Firebase and Expo open a private activity alias when the user taps a notification.+The native handoff records the tap before Expo SDK 57's startup delegate can drop it.+Both push and local reminder taps replace the same pending destination, so tapping a reminder+after a push opens the reminder even if Expo later replays the earlier response.+The store keeps only the notification identifier and routing fields. It clears the destination+when JavaScript acknowledges that identifier. It also remembers the original launch identifier+so restoring the task from Recents does not replay it.+This workaround requires a new Android build.+Recheck the workaround when upgrading Expo ([upstream issue](https://github.com/expo/expo/issues/49254)).+Chat taps reuse the single chat screen. If the target task is already open in the same accountand project, the tap leaves its session and draft intact. Otherwise it replaces the open chatwith the target conversation. The comparison uses the live session's task, so it also works fordiff --git a/products/mobile/docs/TESTING.md b/products/mobile/docs/TESTING.mdindex 47059694b514..7efb416109b6 100644--- a/products/mobile/docs/TESTING.md+++ b/products/mobile/docs/TESTING.md@@ -287,6 +287,40 @@ On a development build with notifications enabled:6. Repeat a delivery with the app backgrounded or terminated. App-side filtering does **not** provide the sameguarantees there; server consolidation and synchronized snoozes remain follow-ups in [GAPS.md](GAPS.md).+### Android notification taps after process death++Use a rebuilt Android development client. Keep the app's task in Recents when killing its+process; force-stop and removing the task test different startup paths.+Send test pushes as described in [Push notifications](PUSH.md#testing) and tap them in the+system tray. Use different reports in a project the test account can access. To kill the process+without removing the task, substitute the installed variant's package in these commands.++```sh+adb shell input keyevent KEYCODE_HOME+adb shell am kill com.posthog.mobile+adb shell pidof com.posthog.mobile # must print nothing+```++Disconnect the debugger if it keeps the development build alive.++Verify these sequences against both base and proposed builds:++1. Open report A, background the app, and tap a notification for report B with the process alive.+2. Repeat after killing the background process while retaining its task. B must open once.+3. Start a fresh task by tapping a notification for A, navigate to another report, background+ and kill the process, then tap a notification for B. B must open without reopening A.+4. Repeat the notification-launched task sequence but reopen from Recents with no new tap.+ The original notification must not replay.+5. Tap a notification to start a fresh task, then kill its process before JavaScript routes it.+ Reopen from Recents without another tap. The pending target must open once.+ Repeat while signed out, kill and reopen, then sign in. The pending target must still open.+6. Background the app and tap a local snooze reminder, then open a report deep link.+ Both must still reach their targets.+7. While routing is waiting for sign-in, tap a push for A and then a snooze reminder for B.+ Sign in and verify only B opens. Repeat with the tap order reversed and verify only A opens.++Also perform real push delivery checks on physical Android and iOS devices before marking the PR ready.+## Demo walkthrough on the iOS simulator`.argent/flows/demo-smoke.yaml` drives the demo end to end with [Argent](https://docs.expo.dev/agents/argent/), a device automation CLI from Software Mansion.diff --git a/products/mobile/modules/notification-intents/android/build.gradle b/products/mobile/modules/notification-intents/android/build.gradlenew file mode 100644index 000000000000..5aba2fc8e264--- /dev/null+++ b/products/mobile/modules/notification-intents/android/build.gradle@@ -0,0 +1,20 @@+plugins {+ id 'com.android.library'+ id 'expo-module-gradle-plugin'+}++group = 'com.posthog.mobile'+version = '1.0.0'++android {+ namespace "com.posthog.mobile.notifications"+ defaultConfig {+ versionCode 1+ versionName '1.0.0'+ }+}++dependencies {+ implementation project(':expo-notifications')+ implementation 'com.google.firebase:firebase-messaging:25.0.1'+}diff --git a/products/mobile/modules/notification-intents/android/src/main/AndroidManifest.xml b/products/mobile/modules/notification-intents/android/src/main/AndroidManifest.xmlnew file mode 100644index 000000000000..e4b9d880fc7f--- /dev/null+++ b/products/mobile/modules/notification-intents/android/src/main/AndroidManifest.xml@@ -0,0 +1,21 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">+ <application>+ <service android:name="expo.modules.notifications.service.ExpoFirebaseMessagingService" tools:node="remove" />+ <service android:name="com.posthog.mobile.notifications.NotificationMessagingService" android:exported="false">+ <intent-filter>+ <action android:name="com.google.firebase.MESSAGING_EVENT" />+ </intent-filter>+ </service>+ <meta-data android:name="firebase_messaging_notification_delegation_enabled" android:value="false" tools:replace="android:value" />+ <activity-alias+ android:name="com.posthog.mobile.notifications.NotificationTapActivity"+ android:targetActivity="${applicationId}.MainActivity"+ android:exported="false">+ <intent-filter>+ <action android:name="com.posthog.mobile.notifications.OPEN_FCM_NOTIFICATION" />+ <action android:name="expo.modules.notifications.OPEN_APP_ACTION" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ </activity-alias>+ </application>+</manifest>diff --git a/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationIntentsModule.kt b/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationIntentsModule.ktnew file mode 100644index 000000000000..3bbfa277f7bb--- /dev/null+++ b/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationIntentsModule.kt@@ -0,0 +1,87 @@+package com.posthog.mobile.notifications++import android.content.Context+import android.content.Intent+import android.os.Bundle+import expo.modules.kotlin.exception.Exceptions+import expo.modules.kotlin.modules.Module+import expo.modules.kotlin.modules.ModuleDefinition+import expo.modules.notifications.notifications.NotificationManager+import expo.modules.notifications.notifications.model.NotificationResponse+import expo.modules.notifications.service.NotificationsService+import org.json.JSONObject++object NotificationIntentStore {+ private fun preferences(context: Context) =+ context.getSharedPreferences("posthog_notification_intents_v2", Context.MODE_PRIVATE)++ private val routingKeys = listOf("type", "report_id", "project_id", "taskId", "projectId", "notificationKind")++ fun handleIntent(context: Context, intent: Intent, initial: Boolean) {+ if (intent.component?.className == "com.posthog.mobile.notifications.NotificationTapActivity") {+ val response = NotificationsService.getNotificationResponseFromOpenIntent(intent)+ if (capture(context, intent, initial, response)) {+ if (response != null) {+ NotificationManager.onNotificationResponseReceived(response)+ } else {+ intent.extras?.let { NotificationManager.onNotificationResponseFromExtras(Bundle(it)) }+ }+ }+ }+ intent.removeExtra("google.message_id")+ }++ // Android restores the original launch intent even after a newer tap has replaced it in the activity.+ @Synchronized+ private fun capture(context: Context, intent: Intent, initial: Boolean, response: NotificationResponse?): Boolean {+ val extras = intent.extras ?: return false+ val remoteId = extras.getString("google.message_id")+ val id = remoteId ?: response?.notification?.notificationRequest?.identifier ?: return false+ val preferences = preferences(context)+ if (preferences.getString("initial_message_id", null) == id) return false+ val source = response?.notification?.notificationRequest?.content?.body ?: try {+ JSONObject(extras.getString("body") ?: "")+ } catch (_: org.json.JSONException) {+ JSONObject().apply {+ for (key in routingKeys) {+ if (extras.containsKey(key)) put(key, extras.get(key))+ }+ }+ }+ val data = JSONObject()+ for (key in routingKeys) {+ if (source.has(key)) data.put(key, source.get(key))+ }+ val pending = JSONObject().put("identifier", id).put("data", data.toString())+ val editor = preferences.edit().putString("pending_response", pending.toString())+ if (initial) editor.putString("initial_message_id", id)+ // Persist before handing off to Expo; its in-memory queue cannot survive process death.+ editor.commit()+ return true+ }++ @Synchronized+ fun pending(context: Context): Map<String, String>? {+ val json = preferences(context).getString("pending_response", null) ?: return null+ val pending = JSONObject(json)+ return mapOf("identifier" to pending.getString("identifier"), "data" to pending.getString("data"))+ }++ @Synchronized+ fun acknowledge(context: Context, identifier: String) {+ if (pending(context)?.get("identifier") == identifier) {+ preferences(context).edit().remove("pending_response").commit()+ }+ }+}++class NotificationIntentsModule : Module() {+ override fun definition() = ModuleDefinition {+ Name("NotificationIntents")+ Function("getPending") { NotificationIntentStore.pending(context()) }+ Function("acknowledge") { identifier: String -> NotificationIntentStore.acknowledge(context(), identifier) }+ }++ private fun context(): Context =+ appContext.reactContext?.applicationContext ?: throw Exceptions.ReactContextLost()+}diff --git a/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationIntentsPackage.kt b/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationIntentsPackage.ktnew file mode 100644index 000000000000..5b05a968e558--- /dev/null+++ b/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationIntentsPackage.kt@@ -0,0 +1,23 @@+package com.posthog.mobile.notifications++import android.app.Application+import android.app.NotificationManager+import android.content.Context+import android.os.Build+import expo.modules.core.interfaces.ApplicationLifecycleListener+import expo.modules.core.interfaces.Package++class NotificationIntentsPackage : Package {+ override fun createApplicationLifecycleListeners(context: Context): List<ApplicationLifecycleListener> =+ listOf(object : ApplicationLifecycleListener {+ override fun onCreate(application: Application) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ val manager = application.getSystemService(NotificationManager::class.java)+ // The manifest opt-out does not revoke delegation initialized by an older binary.+ if (manager.notificationDelegate == "com.google.android.gms") {+ manager.setNotificationDelegate(null)+ }+ }+ }+ })+}diff --git a/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationMessagingService.kt b/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationMessagingService.ktnew file mode 100644index 000000000000..fa27bbb06d15--- /dev/null+++ b/products/mobile/modules/notification-intents/android/src/main/java/com/posthog/mobile/notifications/NotificationMessagingService.kt@@ -0,0 +1,18 @@+package com.posthog.mobile.notifications++import android.content.Intent+import com.google.firebase.messaging.RemoteMessage+import expo.modules.notifications.service.ExpoFirebaseMessagingService++class NotificationMessagingService : ExpoFirebaseMessagingService() {+ override fun handleIntent(intent: Intent) {+ if (intent.action == "com.google.android.c2dm.intent.RECEIVE") {+ val notification = intent.extras?.let { RemoteMessage(it).notification }+ if (notification != null && notification.clickAction.isNullOrEmpty() && notification.link == null) {+ // Firebase creates this PendingIntent as our UID, so it can open the private alias.+ intent.putExtra("gcm.n.click_action", "com.posthog.mobile.notifications.OPEN_FCM_NOTIFICATION")+ }+ }+ super.handleIntent(intent)+ }+}diff --git a/products/mobile/modules/notification-intents/expo-module.config.json b/products/mobile/modules/notification-intents/expo-module.config.jsonnew file mode 100644index 000000000000..fdbd2877ef16--- /dev/null+++ b/products/mobile/modules/notification-intents/expo-module.config.json@@ -0,0 +1,6 @@+{+ "platforms": ["android"],+ "android": {+ "modules": ["com.posthog.mobile.notifications.NotificationIntentsModule"]+ }+}diff --git a/products/mobile/package.json b/products/mobile/package.jsonindex bb8c94114e9d..6ce93c0be073 100644--- a/products/mobile/package.json+++ b/products/mobile/package.json@@ -33,7 +33,8 @@"expo": {"autolinking": {"buildFromSource": [- "react-native-worklets"+ "react-native-worklets",+ "expo-notifications"]},"install": {diff --git a/products/mobile/plugins/withAndroidNotificationIntents.js b/products/mobile/plugins/withAndroidNotificationIntents.jsnew file mode 100644index 000000000000..a775a3826635--- /dev/null+++ b/products/mobile/plugins/withAndroidNotificationIntents.js@@ -0,0 +1,43 @@+const { withMainActivity } = require('expo/config-plugins')++// Expo SDK 57 drops onNewIntent while expo-updates is loading the app. Hand FCM taps to its+// notification queue before that delegate can drop them: https://github.com/expo/expo/issues/49254.+const INTENT_HANDLER = `+ override fun onNewIntent(intent: android.content.Intent) {+ com.posthog.mobile.notifications.NotificationIntentStore.handleIntent(this, intent, false)+ setIntent(intent)+ super.onNewIntent(intent)+ }+`++// Replay suppression and the pending tap have separate lifetimes: routing acknowledges only the pending tap.+const INITIAL_INTENT = `+ com.posthog.mobile.notifications.NotificationIntentStore.handleIntent(this, intent, true)+`++const CREATE_ANCHOR = 'super.onCreate(null)'+const CLASS_ANCHOR = 'class MainActivity : ReactActivity() {'+const MARKER = '// posthog-notification-intents'++module.exports = function withAndroidNotificationIntents(config) {+ return withMainActivity(config, (cfg) => {+ const { contents, language } = cfg.modResults+ if (contents.includes(MARKER)) {+ return cfg+ }+ if (+ language !== 'kt' ||+ !contents.includes(CLASS_ANCHOR) ||+ !contents.includes(CREATE_ANCHOR) ||+ contents.includes('override fun onNewIntent(')+ ) {+ throw new Error(+ 'withAndroidNotificationIntents: MainActivity does not match the Expo SDK 57 template. Update or remove this plugin.'+ )+ }+ cfg.modResults.contents = contents+ .replace(CLASS_ANCHOR, `${CLASS_ANCHOR}\n ${MARKER}\n${INTENT_HANDLER}`)+ .replace(CREATE_ANCHOR, `${INITIAL_INTENT}\n ${CREATE_ANCHOR}`)+ return cfg+ })+}diff --git a/products/mobile/src/features/notifications/notificationIntents.ts b/products/mobile/src/features/notifications/notificationIntents.tsnew file mode 100644index 000000000000..656ad7497c6d--- /dev/null+++ b/products/mobile/src/features/notifications/notificationIntents.ts@@ -0,0 +1,25 @@+import { requireOptionalNativeModule } from 'expo-modules-core'++export interface NotificationTap {+ identifier: string+ data: unknown+}++interface NotificationIntentsNativeModule {+ getPending(): { identifier: string; data: string } | null+ acknowledge(identifier: string): void+}++const native = requireOptionalNativeModule<NotificationIntentsNativeModule>('NotificationIntents')++export function getPendingNotificationTap(): NotificationTap | null | undefined {+ if (!native) {+ return undefined+ }+ const pending = native.getPending()+ return pending ? { identifier: pending.identifier, data: JSON.parse(pending.data) } : null+}++export function acknowledgeNotificationTap(identifier: string): void {+ native?.acknowledge(identifier)+}diff --git a/products/mobile/src/features/notifications/useNotificationRouting.test.tsx b/products/mobile/src/features/notifications/useNotificationRouting.test.tsxindex 3d8ecb125bc2..9dd541ce4f05 100644--- a/products/mobile/src/features/notifications/useNotificationRouting.test.tsx+++ b/products/mobile/src/features/notifications/useNotificationRouting.test.tsx@@ -5,6 +5,7 @@ import { AppState } from 'react-native'import { useAuthStore } from '@/auth/authStore'import { foregroundNotificationBehavior, setViewedNotificationTask } from './foregroundNotifications'+import { acknowledgeNotificationTap, getPendingNotificationTap } from './notificationIntents'import { findTask } from './taskLookup'import { useNotificationRouting } from './useNotificationRouting'@@ -23,6 +24,10 @@ jest.mock('expo-router', () => ({usePathname: jest.fn(() => '/inbox'),}))jest.mock('@/demo/demoMode', () => ({ useDemoMode: { getState: () => ({ enabled: false }) } }))+jest.mock('./notificationIntents', () => ({+ getPendingNotificationTap: jest.fn(),+ acknowledgeNotificationTap: jest.fn(),+}))jest.mock('./pushSupport', () => ({ notificationsSupported: () => true }))jest.mock('./taskLookup', () => ({ findTask: jest.fn() }))@@ -49,6 +54,7 @@ function notification(identifier: string): Notifications.Notification {beforeEach(() => {jest.clearAllMocks()jest.mocked(Notifications.getLastNotificationResponse).mockReturnValue(null)+ jest.mocked(getPendingNotificationTap).mockReturnValue(undefined)jest.mocked(usePathname).mockReturnValue('/inbox')mockNavigation.getCurrentRoute.mockReturnValue({ name: 'inbox' })setViewedNotificationTask(null)@@ -62,24 +68,39 @@ beforeEach(() => {})})-test('keeps a cold-start tap pending until sign-in, then opens its report once', async () => {- const response = { notification: notification('pending-sign-in'), actionIdentifier: 'default' }- jest.mocked(Notifications.getLastNotificationResponse).mockReturnValue(response)- useAuthStore.setState({ status: 'signed_out' })- renderHook(useNotificationRouting)- expect(Notifications.clearLastNotificationResponse).not.toHaveBeenCalled()- expect(router.push).not.toHaveBeenCalled()+test.each(['expo', 'persisted'] as const)(+ 'keeps a %s cold-start tap pending until sign-in, then opens its report once',+ async (source) => {+ const response = { notification: notification(`pending-sign-in-${source}`), actionIdentifier: 'default' }+ jest.mocked(Notifications.getLastNotificationResponse).mockReturnValue(response)+ if (source === 'persisted') {+ jest.mocked(getPendingNotificationTap).mockReturnValue({+ identifier: response.notification.request.identifier,+ data: reportData,+ })+ const stale = { notification: notification('stale-launch'), actionIdentifier: 'default' }+ stale.notification.request.content.data = { ...reportData, report_id: 'stale-report' }+ jest.mocked(Notifications.getLastNotificationResponse).mockReturnValue(stale)+ }+ useAuthStore.setState({ status: 'signed_out' })+ renderHook(useNotificationRouting)+ expect(Notifications.clearLastNotificationResponse).not.toHaveBeenCalled()+ expect(router.push).not.toHaveBeenCalled()+ expect(acknowledgeNotificationTap).not.toHaveBeenCalled()- act(() => useAuthStore.setState({ status: 'signed_in' }))- await waitFor(() => expect(router.push).toHaveBeenCalledWith('/report/report-1?from=push'))- const listener = jest.mocked(Notifications.addNotificationResponseReceivedListener).mock.calls[0]?.[0]- if (!listener) {- throw new Error('Notification tap listener was not registered')+ act(() => useAuthStore.setState({ status: 'signed_in' }))+ await waitFor(() => expect(router.push).toHaveBeenCalledWith('/report/report-1?from=push'))+ const listener = jest.mocked(Notifications.addNotificationResponseReceivedListener).mock.calls[0]?.[0]+ if (!listener) {+ throw new Error('Notification tap listener was not registered')+ }+ act(() => listener(response))+ expect(router.push).toHaveBeenCalledTimes(1)+ expect(Notifications.clearLastNotificationResponse).toHaveBeenCalledTimes(source === 'expo' ? 1 : 0)+ expect(acknowledgeNotificationTap).toHaveBeenCalledWith(response.notification.request.identifier)+ expect(acknowledgeNotificationTap).toHaveBeenCalledTimes(2)}- act(() => listener(response))- expect(router.push).toHaveBeenCalledTimes(1)- expect(Notifications.clearLastNotificationResponse).toHaveBeenCalledTimes(1)-})+)test('suppresses the viewed report only while that route is on screen', () => {jest.mocked(usePathname).mockReturnValue('/report/report-1')@@ -105,19 +126,83 @@ test('opens a standalone task chat from a notification', async () => {await waitFor(() => expect(router.push).toHaveBeenCalledWith('/chat?taskId=task-1&from=push'))})-test('does not route a task lookup into an account that signed in while it was pending', async () => {- let resolveLookup!: (value: { found: true; reportId: null }) => void- jest.mocked(findTask).mockReturnValue(- new Promise((resolve) => {- resolveLookup = resolve+test.each(['same-account', 'changed-account', 'newer-tap'] as const)(+ 'acknowledges a task tap only after routing: %s',+ async (scenario) => {+ let resolveLookup!: (value: { found: true; reportId: null }) => void+ jest.mocked(findTask).mockReturnValue(+ new Promise((resolve) => {+ resolveLookup = resolve+ })+ )+ const response = { notification: notification(`changed-account-${scenario}`), actionIdentifier: 'default' }+ response.notification.request.content.data = { taskId: 'task-1', projectId: 2 }+ jest.mocked(Notifications.getLastNotificationResponse).mockReturnValue(response)+ renderHook(useNotificationRouting)+ expect(acknowledgeNotificationTap).not.toHaveBeenCalled()+ expect(Notifications.clearLastNotificationResponse).not.toHaveBeenCalled()+ if (scenario === 'changed-account') {+ act(() => useAuthStore.setState({ host: 'https://another.example.com' }))+ } else if (scenario === 'newer-tap') {+ jest.mocked(getPendingNotificationTap).mockReturnValue({ identifier: 'newer-tap', data: reportData })+ }+ await act(async () => resolveLookup({ found: true, reportId: null }))+ expect(router.push).toHaveBeenCalledTimes(scenario === 'same-account' ? 1 : 0)+ expect(acknowledgeNotificationTap).toHaveBeenCalledTimes(scenario === 'same-account' ? 1 : 0)+ expect(router.replace).not.toHaveBeenCalled()+ }+)++test.each(['before', 'after'] as const)(+ 'ignores older Expo replay %s the newest response across sign-in',+ async (replayOrder) => {+ const older = { notification: notification(`older-${replayOrder}`), actionIdentifier: 'default' }+ older.notification.request.content.data = { ...reportData, report_id: 'older-report' }+ const latest = { notification: notification(`latest-${replayOrder}`), actionIdentifier: 'default' }+ latest.notification.request.content.data = { ...reportData, report_id: 'latest-report' }+ const latestId = latest.notification.request.identifier+ jest.mocked(getPendingNotificationTap).mockReturnValue({+ identifier: latestId,+ data: latest.notification.request.content.data,})- )- const response = { notification: notification('changed-account'), actionIdentifier: 'default' }- response.notification.request.content.data = { taskId: 'task-1', projectId: 2 }+ jest.mocked(Notifications.getLastNotificationResponse).mockReturnValue(+ replayOrder === 'before' ? older : latest+ )+ useAuthStore.setState({ status: 'signed_out' })+ renderHook(useNotificationRouting)+ expect(router.push).not.toHaveBeenCalled()++ act(() => useAuthStore.setState({ status: 'signed_in' }))+ const listener = jest.mocked(Notifications.addNotificationResponseReceivedListener).mock.calls[0]?.[0]+ if (!listener) {+ throw new Error('Notification tap listener was not registered')+ }+ act(() => {+ if (replayOrder === 'before') {+ listener(older)+ }+ listener(latest)+ if (replayOrder === 'after') {+ listener(older)+ }+ })+ await waitFor(() => expect(router.push).toHaveBeenCalledWith('/report/latest-report?from=push'))+ act(() => listener(older))+ expect(router.push).toHaveBeenCalledTimes(1)+ expect(acknowledgeNotificationTap).not.toHaveBeenCalledWith(older.notification.request.identifier)+ }+)++test('ignores Expo responses when the supported native tap store is empty', async () => {+ const response = { notification: notification('untrusted-expo'), actionIdentifier: 'default' }+ jest.mocked(getPendingNotificationTap).mockReturnValue(null)jest.mocked(Notifications.getLastNotificationResponse).mockReturnValue(response)renderHook(useNotificationRouting)- act(() => useAuthStore.setState({ host: 'https://another.example.com' }))- await act(async () => resolveLookup({ found: true, reportId: null }))+ const listener = jest.mocked(Notifications.addNotificationResponseReceivedListener).mock.calls[0]?.[0]+ if (!listener) {+ throw new Error('Notification tap listener was not registered')+ }+ await act(async () => listener(response))expect(router.push).not.toHaveBeenCalled()- expect(router.replace).not.toHaveBeenCalled()+ expect(acknowledgeNotificationTap).not.toHaveBeenCalled()})diff --git a/products/mobile/src/features/notifications/useNotificationRouting.ts b/products/mobile/src/features/notifications/useNotificationRouting.tsindex 2de3e4bb8236..c54b828bbd56 100644--- a/products/mobile/src/features/notifications/useNotificationRouting.ts+++ b/products/mobile/src/features/notifications/useNotificationRouting.ts@@ -8,82 +8,101 @@ import { track } from '@/lib/analytics'import { withAppReloadBlocked } from '@/lib/appReload'import { isViewedNotificationTask, setViewedNotificationReport } from './foregroundNotifications'+import { acknowledgeNotificationTap, getPendingNotificationTap, type NotificationTap } from './notificationIntents'import { notificationKind, notificationTarget, resolveNotificationRoute } from './notificationRouting'import { notificationsSupported } from './pushSupport'import { findTask } from './taskLookup'/** A cold-start tap can arrive both as the last response and through the listener. */const handled = new Set<string>()+const inFlight = new Set<string>()-async function openFromNotification(- response: Notifications.NotificationResponse,- isChatOpen: () => boolean-): Promise<void> {+function finishNotificationTap(identifier: string): void {+ acknowledgeNotificationTap(identifier)+ handled.add(identifier)+ if (Notifications.getLastNotificationResponse()?.notification.request.identifier === identifier) {+ Notifications.clearLastNotificationResponse()+ }+}++async function openFromNotification(tap: NotificationTap, isChatOpen: () => boolean): Promise<void> {const auth = useAuthStore.getState()if (auth.status !== 'signed_in') {return}- const id = response.notification.request.identifier+ const id = tap.identifierif (handled.has(id)) {+ acknowledgeNotificationTap(id)return}- handled.add(id)- Notifications.clearLastNotificationResponse()- const data: unknown = response.notification.request.content.data- track('mobile_push_opened', { kind: notificationKind(data) })- const route = await resolveNotificationRoute(data, {- currentProjectId: auth.projectId,- projectIds: auth.projects.map((project) => project.id),- findTask,- })- const currentAuth = useAuthStore.getState()- if (- currentAuth.status !== 'signed_in' ||- currentAuth.host !== auth.host ||- currentAuth.user?.uuid !== auth.user?.uuid- ) {- return- }- if (!route) {+ if (inFlight.has(id)) {return}- // A push is about live data, which demo mode would hide behind fixtures.- if (useDemoMode.getState().enabled) {- track('mobile_demo_ended', { from: 'push' })- useDemoMode.getState().setEnabled(false)- }- if (route.switchToProjectId !== null) {- useAuthStore.getState().selectProject(route.switchToProjectId, 'push')- }- const target = notificationTarget(data)- const chatOpen = isChatOpen()- const isChatRoute = route.pathname.startsWith('/chat?')- const projectId = route.switchToProjectId ?? auth.projectId- // Creating a task or tapping New chat changes the live session without changing the route's taskId.- if (- chatOpen &&- isChatRoute &&- target?.type === 'task' &&- auth.host &&- auth.user &&- projectId !== null &&- isViewedNotificationTask({- accountKey: `${auth.host.replace(/\/$/, '')}|${auth.user.uuid}`,- projectId,- taskId: target.id,+ inFlight.add(id)+ try {+ const data = tap.data+ track('mobile_push_opened', { kind: notificationKind(data) })+ const route = await resolveNotificationRoute(data, {+ currentProjectId: auth.projectId,+ projectIds: auth.projects.map((project) => project.id),+ findTask,})- ) {- return- }- if (route.pathname === '/inbox') {- router.navigate('/inbox')- } else {- const href = `${route.pathname}${route.pathname.includes('?') ? '&' : '?'}from=push`- if (chatOpen && isChatRoute) {- router.replace(href)+ const currentAuth = useAuthStore.getState()+ const pending = getPendingNotificationTap()+ if (+ (pending !== undefined && pending?.identifier !== id) ||+ currentAuth.status !== 'signed_in' ||+ currentAuth.host !== auth.host ||+ currentAuth.user?.uuid !== auth.user?.uuid+ ) {+ return+ }+ if (!route) {+ finishNotificationTap(id)+ return+ }+ // A push is about live data, which demo mode would hide behind fixtures.+ if (useDemoMode.getState().enabled) {+ track('mobile_demo_ended', { from: 'push' })+ useDemoMode.getState().setEnabled(false)+ }+ if (route.switchToProjectId !== null) {+ useAuthStore.getState().selectProject(route.switchToProjectId, 'push')+ }+ const target = notificationTarget(data)+ const chatOpen = isChatOpen()+ const isChatRoute = route.pathname.startsWith('/chat?')+ const projectId = route.switchToProjectId ?? auth.projectId+ // Creating a task or tapping New chat changes the live session without changing the route's taskId.+ if (+ chatOpen &&+ isChatRoute &&+ target?.type === 'task' &&+ auth.host &&+ auth.user &&+ projectId !== null &&+ isViewedNotificationTask({+ accountKey: `${auth.host.replace(/\/$/, '')}|${auth.user.uuid}`,+ projectId,+ taskId: target.id,+ })+ ) {+ finishNotificationTap(id)+ return+ }+ if (route.pathname === '/inbox') {+ router.navigate('/inbox')} else {- router.push(href)+ const href = `${route.pathname}${route.pathname.includes('?') ? '&' : '?'}from=push`+ if (chatOpen && isChatRoute) {+ router.replace(href)+ } else {+ router.push(href)+ }}+ finishNotificationTap(id)+ } finally {+ inFlight.delete(id)}}@@ -111,16 +130,26 @@ export function useNotificationRouting(): void {if (!navigationReady || !signedIn || !notificationsSupported()) {return}- const open = (response: Notifications.NotificationResponse): void => {+ const open = (tap: NotificationTap): void => {void withAppReloadBlocked(() =>- openFromNotification(response, () => navigation.getCurrentRoute()?.name === 'chat')+ openFromNotification(tap, () => navigation.getCurrentRoute()?.name === 'chat')).catch(() => undefined)}- const last = Notifications.getLastNotificationResponse()- if (last) {- open(last)+ const fromResponse = (response?: Notifications.NotificationResponse): void => {+ const pending = getPendingNotificationTap()+ if (pending !== undefined) {+ if (pending) {+ open(pending)+ }+ } else if (response) {+ open({+ identifier: response.notification.request.identifier,+ data: response.notification.request.content.data,+ })+ }}- const subscription = Notifications.addNotificationResponseReceivedListener(open)+ fromResponse(Notifications.getLastNotificationResponse() ?? undefined)+ const subscription = Notifications.addNotificationResponseReceivedListener(fromResponse)return () => subscription.remove()}, [navigationReady, signedIn, navigation])}