Skip to content

[$250] Android: Tapping push notification on cold start opens last active chat instead of the notification's chat #92138

Closed

Description

@melvin-bot

Description

When the app is cold-started by tapping a push notification (i.e. Android had killed the process while idle), the app navigates to the last active chat rather than the chat referenced in the notification. The correct chat is visible if you press the back button from that screen, meaning the navigation did eventually happen — but underneath the wrong screen.

Reported by dbarrett@expensify.com on Android staging, 2026-05-29 ~13:59 UTC. Tapped a notification from Florent, but the app opened to Chronos (last active chat). Pressing back from Chronos revealed the Florent chat.

Root Cause (confirmed via VictoriaLogs)

This is a cold-start race condition introduced by the dynamic import added in #84624.

subscribeToPushNotifications is now lazily imported inside a useEffect gated on splashScreenState === HIDDEN:

useEffect(() => {
  if (splashScreenState !== HIDDEN) return;
  import('.../subscribeToPushNotifications');
}, [splashScreenState]);

When the user taps a notification to cold-launch the app, the Airship native bridge fires notification_response before the splash screen hides and before PushNotification.onSelected(REPORT_COMMENT, navigateToReport) has been registered. The tap event is dispatched into the void — navigateToReport is never called.

Log Evidence

At 13:59:38.491Z the device correctly emitted:

[PushNotification] Callback triggered for com.airship.notification_response

But none of the subsequent JS-side logs appeared:

  • ❌ [PushNotification] Navigating to report
  • ❌ [PushNotification] onSelected() - Navigation is ready. Navigating...
  • ❌ [PushNotification] Not navigating because this is a singleNewDotEntry flow
  • ❌ [PushNotification] onSelected() - failed

Since [PushNotification] Navigating to report is the first line of navigateToReport (before any await or guard), its absence proves the JS handler was never invoked — not just delayed.

Two earlier taps the same day (00:48 UTC and 03:29 UTC, when the app was warm) worked correctly, confirming the regression is specific to cold starts.

Two corroborating signals for cold start:

  1. Previous push activity was at 12:44 UTC — 75 minutes of silence before the broken tap, enough for Android to kill the process.
  2. A new staging build (ecash9.3.89-2) appeared between the broken tap and the next session, suggesting the 13:59 launch may also have been triggered by an app update.

Steps to Reproduce

  1. Open the app on Android, navigate to any chat, then background the app and leave it idle for ~1 hour (or force-kill it).
  2. Receive a push notification for a different chat.
  3. Tap the notification.

Expected: App opens directly to the notification's chat.
Actual: App opens to the last active chat. The notification's chat is reachable via the back button.

Relevant Code

Platform

  • Platform: Android
  • Environment: Staging (likely also affects production)
  • App version at time of report: ecash9.3.83-1
Upwork Automation - Do Not Edit

Activity

  1. added
    AutoAssignerTriageAuto assign issues for triage to an available triage team member
    BugSomething is broken. Auto assigns a BugZero manager.
    on May 30, 2026
  2. melvin-bot commented on May 30, 2026

    @melvin-bot
    Author

    @melvin-bot[bot] the AutoAssignerTriage label has been deprecated. Please use Bug for issue triage. See https://stackoverflowteams.com/c/expensify/questions/14418 for more details.

  3. removed
    AutoAssignerTriageAuto assign issues for triage to an available triage team member
    on May 30, 2026
  4. added
    Hot PickReady for an engineer to pick up and run with
    on May 30, 2026
  5. MelvinBot commented on May 30, 2026

    @MelvinBot
    Contributor

    ⚠️ Preliminary analysis (low confidence) — the root cause in the issue body is incorrect for the code at the referenced commit. The reported symptom may still be real, but it is caused by something else.

    What the body claims

    The body says PR Expensify/App#84390 (linked indirectly via parent issue Expensify/App#84624) gates subscribeToPushNotifications behind a useEffect keyed on splashScreenState === HIDDEN, so the JS-side onSelected(REPORT_COMMENT, navigateToReport) handler is not yet registered when the Airship native bridge fires notification_response on cold start.

    Why that doesn't match the code

    At the commit referenced in the body (d4cffc8), subscribeToPushNotifications is not in the splash-screen-gated loadPostSplashScreenModules. It is dynamically imported inside setup(), immediately after Onyx.init() and outside the React lifecycle, with a comment explicitly stating it must run before any push arrives — including Android headless wake-ups.

    • src/setup/index.ts:78-80 — import('@libs/Notification/PushNotification/subscribeToPushNotifications') runs at module-load, not on splash hide.
    • src/SplashScreenStateContext.tsx:26-30 — loadPostSplashScreenModules() defers only replaceOptimisticReportWithActualReport, registerPaginationConfig, UnreadIndicatorUpdater. It does not defer push subscription.

    PR Expensify/App#84390's own diff confirms this — subscribeToPushNotifications was added to setup/index.ts, not to the new loadPostSplashScreenModules function:

    PR #84390 diff (src/setup/index.ts)
    +    // Must be imported after Onyx.init() and outside the React lifecycle so that push notification
    +    // handlers are registered before any push arrives, including Android headless/background wake-ups.
    +    import('@libs/Notification/PushNotification/subscribeToPushNotifications');

    So the "recommended fix" implied by the body (move the import to setup/index.ts) is already shipped. Applying it again is a no-op.

    What might actually be happening

    I can't fully verify these from code alone — they need log/repro confirmation:

    1. Two separate navigations may be racing — navigateToReport at subscribeToPushNotifications.ts:114-153 waits on Navigation.waitForProtectedRoutes() and then Modal.close() before calling Navigation.navigate(...). If the app's deep-link/lastVisitedPath restore (separate from this handler) runs after the notification navigation resolves, the last-active chat would land on top — matching the reported "back reveals Florent (notification chat)" stack order.
    2. Headless JS logging — [PushNotification] Navigating to report is logged via Log.info, which posts to the server. If the JS handler ran in a Headless JS context (cold-start background wake) and the process was torn down before the log batch flushed, the log would be missing even though the handler ran. That would invalidate the "handler never ran" inference.
    3. Airship deeplink integration — if Airship passes the report route as the app's initial URL, navigation may flow through InitialURLContextProvider rather than (or in addition to) the JS onSelected handler. Worth tracing which path actually fires on Android cold-start tap.

    What to check next

    • Reproduce the cold-start tap on a current build and capture: (a) whether navigateToReport actually runs (e.g., add a Sentry breadcrumb at the function entry as a stronger signal than Log.info), (b) the Navigation.getActiveRoute() at the moment onSelected fires, (c) whether updateLastVisitedPath is being invoked from another code path after the notification navigation.
    • Confirm the staging build at the time of the report (ecash9.3.83-1) actually contains the setup/index.ts:80 line. If staging was on an older Mobile-Expensify submodule pinning a pre-Defer startup imports #84390 App, the original race could be real on staging only — but that's not the file/PR cited.
    • Check what restores lastVisitedPath on cold start and at what point in the boot sequence.

    Related open issues (quick scan)

    • Expensify/App#88158 — push notifications navigation broken for Classic users (different cause — HybridApp routing — but adjacent area).

    Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis, e.g. point me at a specific log run, a specific App commit, or the Mobile-Expensify submodule SHA the staging build was cut from.

  6. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on May 30, 2026
  7. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on May 30, 2026
  8. Abdulloh0109 commented on May 30, 2026

    @Abdulloh0109
    Contributor

    Proposal

    What is the root cause of that problem?

    I traced the cold-start race to two overlapping gaps in src/libs/Notification/PushNotification/subscribeToPushNotifications.ts:22-43 and src/libs/Notification/PushNotification/index.native.ts:41-47.

    Gap 1 — init() is gated behind Onyx hydration.
    PushNotification.init() — which registers the Airship EventType.NotificationResponse listener — is called at subscribeToPushNotifications.ts:27 inside an Onyx.connectWithoutView callback keyed on ONYXKEYS.NVP_PRIVATE_PUSH_NOTIFICATION_ID. On cold start, Onyx must first read that key from AsyncStorage before the callback fires. Airship fires its notification_response event as soon as the JS bridge is ready, which is well before AsyncStorage I/O completes. Because Airship.addListener(EventType.NotificationResponse, ...) (index.native.ts:71) hasn't been called yet, the native event fires with no JS listener attached — it is completely discarded at the bridge level.

    Gap 2 — unhandled NotificationResponse events are silently dropped.
    Even in the narrower race (where init() has been called but onSelected hasn't yet bound its handler), pushNotificationEventCallback (index.native.ts:24-56) reaches the !action branch at line 41, logs a Log.warn at lines 43-46, and returns undefined. There is no queue or retry — the tap event is gone.

    The two gaps form a sequential "miss window": gap 1 covers the period from native launch until NVP_PRIVATE_PUSH_NOTIFICATION_ID hydrates; gap 2 covers the shorter period between init() and onSelected() registration. On a cold start the full 75-minute-idle scenario in the issue, the phone fires notification_response squarely inside gap 1.

    The comment at setup/index.ts:76-78 says the import exists so handlers are "registered before any push arrives", but init() being inside the Onyx callback defeats that intent.

    What changes do you think we should make in order to solve the problem?

    Two targeted changes, both in the push notification module.

    Change 1 — subscribeToPushNotifications.ts — call init() at module top-level.
    Move PushNotification.init() from inside the Onyx.connectWithoutView callback (subscribeToPushNotifications.ts:27) to the top level of the module, so it runs immediately when the module is imported. init() only registers Airship event listeners (index.native.ts:65-74) — it requires no authentication and has no side effects that depend on Onyx state. The register, onReceived, and onSelected calls can remain inside the Onyx callback where they belong (they do need the notificationID). Remove the PushNotification.init() line from inside the callback.

    Change 2 — index.native.ts — queue early NotificationResponse events and replay on bind.
    Add a module-level array (e.g. pendingNotificationResponses) typed as Array<{eventType: EventType; notification: PushPayload}>. In pushNotificationEventCallback (index.native.ts:24-56), when eventType === EventType.NotificationResponse and the !action branch at line 41 is reached, push {eventType, notification} into the queue instead of just logging and returning. In the bind function (index.native.ts:140-149), after writing actionMap[notificationType] = callback, iterate over pendingNotificationResponses, filter for entries whose eventType and parsed data.type match the newly registered handler, call the action for each match, and remove them from the queue.

    Scope: Only subscribeToPushNotifications.ts and index.native.ts are touched. index.web.ts / index.ios.ts / index.android.ts stubs are unaffected. iOS is unaffected in practice (iOS buffers notification_response until the app JS is ready), but the queue in change 2 is harmless there. No changes to navigation, Onyx keys, or authentication.

    Edge cases:

    • If multiple notifications arrive before any handler registers (unlikely but possible), the queue holds all of them and replays in order.
    • If deregister() is called, Airship.removeAllListeners clears the native side; the pendingNotificationResponses array should also be cleared in deregister() (index.native.ts:120-127) to prevent stale replays after sign-out.
    • Offline / optimistic rollback: the fix only changes when navigateToReport is invoked — the function's own Navigation.waitForProtectedRoutes() guard (subscribeToPushNotifications.ts:117) already handles the case where navigation is not yet ready.

    What alternative solutions did you explore? (Optional)

    Retrieve the launch notification after hydration (rejected). Airship's SDK (confirmed via node_modules/@ua/react-native-airship/src/types.ts) does not expose a getLaunchNotification() or getInitialNotification() API to retrieve a cold-start notification after the fact. This avenue is closed.

    Await the dynamic import in setup/index.ts (rejected). Making setup/index.ts:78 an await import(...) would block the setup function's async chain on module load, but it would still not fix the race because init() would still be inside the Onyx callback and the Airship event fires from native before JS even begins executing setup. It also risks delaying other setup steps unnecessarily.

    Remove the Onyx gating entirely and call init() / onSelected() unconditionally on import (rejected). Calling register() and onSelected() without a valid notificationID would either register the wrong named user or register the navigation handler before session state is ready, risking spurious navigations on sign-out flows. The Onyx gating for register and the handler bindings is correct; only init() needs to move out.

  9. melvin-bot commented on May 30, 2026

    @melvin-bot
    Author

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @situchan (External)

  10. wildan-m commented on May 30, 2026

    @wildan-m
    Contributor

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    When the Android app is cold-started by tapping a push notification (the process had been killed while idle), the app opens the last active chat instead of the chat referenced in the notification. The correct chat is only reachable by pressing the back button, which proves the navigation to it never ran on top — it was the underlying default screen all along.

    What is the root cause of that problem?

    The push-notification tap handler is never registered in time, so the cold-start tap event is dropped.

    On native, a tap is delivered as an Airship NotificationResponse event. The native dispatcher looks the handler up in an in-memory map and, if nothing is bound yet, it logs No callback set up and returns without doing anything — the event is not buffered or replayed:

    const action = actionMap[data.type];
    if (!action) {
    Log.warn('[PushNotification] No callback set up: ', {
    event: eventType,
    notificationType: data.type,
    });
    return;
    }

    That map is only populated when subscribeToPushNotifications runs, which binds navigateToReport to the REPORT_COMMENT selected-event via PushNotification.onSelected(...):

    */
    // We do not depend on updates on the UI for notifications, so we can use `connectWithoutView` here.
    Onyx.connectWithoutView({
    key: ONYXKEYS.NVP_PRIVATE_PUSH_NOTIFICATION_ID,
    callback: (notificationID) => {
    if (notificationID) {
    PushNotification.register(notificationID);
    PushNotification.init();
    // Subscribe handlers for different push notification types
    PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, navigateToReport);
    PushNotification.onReceived(PushNotification.TYPE.REPORT_ACTION, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.REPORT_ACTION, navigateToReport);
    PushNotification.onReceived(PushNotification.TYPE.TRANSACTION, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.TRANSACTION, navigateToReport);

    The problem is that subscribeToPushNotifications is pulled in through an asynchronous dynamic import() inside the setup function:

    App/src/setup/index.ts

    Lines 78 to 80 in 3ec7273

    // Must be imported after Onyx.init() and outside the React lifecycle so that push notification
    // handlers are registered before any push arrives, including Android headless/background wake-ups.
    import('@libs/Notification/PushNotification/subscribeToPushNotifications');

    A dynamic import() resolves asynchronously, so evaluating that module — and therefore binding the onSelected handler — is deferred past the synchronous part of startup. On a cold launch triggered by a notification tap, Airship fires the NotificationResponse very early. At that moment the handler map is still empty because the deferred chunk has not finished evaluating, so the dispatcher hits the No callback set up branch and silently drops the tap. The app then continues its normal startup and lands on the last active chat.

    This matches the issue's log evidence exactly: the native line Callback triggered for com.airship.notification_response is emitted (the dispatcher ran), but none of the JS handler logs (Navigating to report, onSelected() - Navigation is ready, etc.) appear, because the handler was never bound when the event arrived. It also explains why warm taps work: when the process is already alive the handler is long since registered, so the tap is dispatched correctly. The deferral was effectively present before too — the issue references it as a lazy import gated on splash-screen state — and although that gating has since been refactored, the registration is still deferred today by the asynchronous dynamic import().

    What changes do you think we should make in order to solve the problem?

    Register the push-notification handlers synchronously during startup so the onSelected binding exists before any cold-start notification event can be dispatched, while still keeping registration after Onyx.init().

    Concretely:

    1. In src/libs/Notification/PushNotification/subscribeToPushNotifications.ts, move the two Onyx.connectWithoutView(...) registration blocks (the NVP_PRIVATE_PUSH_NOTIFICATION_ID block that calls register/init/onReceived/onSelected, and the HYBRID_APP block) into an exported function, and export it as the module's default. The helper functions (applyOnyxData, navigateToReport, getLastUpdateIDAppliedToClient) and the module-level isSingleNewDotEntry variable stay where they are; only the side-effecting connect calls move inside the exported function so they run when the function is invoked rather than when the module is first evaluated.

    2. In src/setup/index.ts, replace the asynchronous import('@libs/Notification/PushNotification/subscribeToPushNotifications') with a normal static top-of-file import of that default function, and call it synchronously right after Onyx.init() — in the same place the dynamic import currently sits.

    This is the exact pattern already used a few lines below for initOnyxDerivedValues(): statically imported and called after Onyx.init(). Because the import is now static, the module is part of the main bundle (no async chunk to wait on), and because the registration is performed by an explicit function call placed after Onyx.init(), the original ordering requirement (handlers registered after Onyx is initialized, outside the React lifecycle) is preserved. The handler map is therefore populated synchronously during setup — before the UI mounts and before the cold-start NotificationResponse is dispatched — so navigateToReport runs and the app opens the notification's chat directly.

    Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/92138-sync-push-notification-subscribe?expand=1

    What alternative solutions did you explore? (Optional)

    • Buffer/replay the tap on the native side: have pushNotificationEventCallback queue a NotificationResponse whose handler is not yet bound and flush it once onSelected registers. This is more robust against any future deferral, but it adds queueing state and timing complexity to startup-critical native code that is explicitly marked as fragile, when the simpler root-cause fix is to just not defer registration.
    • Keep the dynamic import() but await it before allowing startup to proceed past handler registration: this still leaves a window where an early native event could arrive before the awaited import resolves, and it complicates the setup flow; a synchronous static import removes the window entirely.
  11. 4 remaining items

  12. wildan-m commented on May 30, 2026

    @wildan-m
    Contributor

    Proposal updated — added compare branch with implementation.

  13. github-actions commented on May 30, 2026

    @github-actions
    Contributor

    ⚠️ @ReaperOAK Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  14. oqildev commented on May 30, 2026

    @oqildev
    Contributor

    What is the root cause of that problem?

    First, the cause the report names isn't real on the version it was filed against (ecash9.3.83-1 = tag 9.3.83-1-staging, commit b5ea92de). There is no useEffect gated on splashScreenState === HIDDEN that imports subscribeToPushNotifications. The import is eager, at module-load time in setup/index.ts, with a comment that exists precisely to prevent a cold-start race:

    Must be imported after Onyx.init() and outside the React lifecycle so that push notification handlers are registered before any push arrives, including Android headless/background wake-ups.

    App/src/setup/index.ts

    Lines 76 to 78 in b5ea92d

    // Must be imported after Onyx.init() and outside the React lifecycle so that push notification
    // handlers are registered before any push arrives, including Android headless/background wake-ups.
    import('@libs/Notification/PushNotification/subscribeToPushNotifications');

    So #84624's deferral is not in this code path. I'd drop that attribution.

    What the logs actually fingerprint is a handler-binding order problem. The registration runs inside the Onyx.connectWithoutView(NVP_PRIVATE_PUSH_NOTIFICATION_ID) callback, and it calls PushNotification.init() before PushNotification.onSelected(...):

    PushNotification.init();
    // Subscribe handlers for different push notification types
    PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, navigateToReport);
    PushNotification.onReceived(PushNotification.TYPE.REPORT_ACTION, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.REPORT_ACTION, navigateToReport);
    PushNotification.onReceived(PushNotification.TYPE.TRANSACTION, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.TRANSACTION, navigateToReport);

    init() is what attaches the Airship NotificationResponse listener:

    const init: Init = () => {
    // Setup event listeners
    Airship.addListener(EventType.PushReceived, (notification) => pushNotificationEventCallback(EventType.PushReceived, notification.pushPayload));
    // Note: the NotificationResponse event has a nested PushReceived event,
    // so event.notification refers to the same thing as notification above ^
    Airship.addListener(EventType.NotificationResponse, (event) => pushNotificationEventCallback(EventType.NotificationResponse, event.pushPayload));

    When that listener fires, pushNotificationEventCallback logs Callback triggered, then looks up notificationEventActionMap[NotificationResponse][type]. If the map isn't populated yet, it hits the if (!action) branch, logs No callback set up, and returns — navigateToReport is never called:

    const action = actionMap[data.type];
    if (!action) {
    Log.warn('[PushNotification] No callback set up: ', {
    event: eventType,
    notificationType: data.type,
    });
    return;

    That map is only filled by onReceived/onSelected (line 30+), which run after init(). So init() opens the door to the listener before onSelected() puts the handler behind it. That is the exact log signature in the report: Callback triggered ✅, then Navigating to report ❌ (the first line of navigateToReport). The missing middle line is No callback set up.

    On standalone NewDot this window is narrow — the connect callback runs synchronously and Airship's pending-event drain (UAEventEmitter.dispatchEvents, triggered async via com.airship.pending_events after airshipListenerAdded) usually fires after onSelected has run. The window is real when a NotificationResponse listener already exists at drain time. On HybridApp the Airship instance is shared between NewDot and OldDot:

    .then((userID) => {
    // In the HybridApp, the contact identity is set on the YAPL side after sign-in.
    // Since the Airship instance is shared between NewDot and OldDot,
    // NewDot users won't see the push notification permission prompt as we return early in this case.
    // Therefore, we cannot handle the HybridApp scenario here.

    so the queued cold-start response can be delivered to the existing listener before NewDot binds its action — and the tap is dropped. With the tap dropped, the cold start just continues its normal restore to lastVisitedPath (the last active chat), which is why you land on Chronos.

    One honest caveat: "press back from Chronos and the Florent chat is underneath" does not fit a fully-dropped tap — if navigateToReport never ran, Florent isn't in the stack at all. That detail instead points at the navigation-ordering variant in Alternatives below. The Callback triggered / no-Navigating to report logs are the hard artifact, so I'm anchoring the root cause there; the back-button detail is how I'd disambiguate which of the two is firing.

    What changes do you think we should make in order to solve the problem?

    Data/registration layer, in subscribeToPushNotifications.ts. Bind the handlers before attaching the Airship listeners: move the onReceived/onSelected calls above PushNotification.init() in the connect callback (

    PushNotification.init();
    // Subscribe handlers for different push notification types
    PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, navigateToReport);
    PushNotification.onReceived(PushNotification.TYPE.REPORT_ACTION, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.REPORT_ACTION, navigateToReport);
    PushNotification.onReceived(PushNotification.TYPE.TRANSACTION, applyOnyxData);
    PushNotification.onSelected(PushNotification.TYPE.TRANSACTION, navigateToReport);
    ). bind() only writes to the local notificationEventActionMap, so populating it first is free and guarantees the action exists the instant init() lets the first NotificationResponse through. This closes the cold-start/HybridApp window without touching the Airship drain mechanism.

    To confirm in production before/after, I'd watch for the No callback set up warn at

    if (!action) {
    Log.warn('[PushNotification] No callback set up: ', {
    event: eventType,
    notificationType: data.type,
    });
    — its presence on the cold-start tap is the smoking gun, and the fix should make it disappear.

    This only affects the cold-start path; warm taps already work (the report confirms the 00:48 and 03:29 UTC warm taps navigated correctly), and the change doesn't alter the headless/background Onyx-apply flow.

    What alternative solutions did you explore? (Optional)

    Navigation-ordering race in navigateToReport (the variant that fits "back reveals the correct chat"). If the tap is not dropped, navigateToReport runs through Navigation.waitForProtectedRoutes().then(() => Modal.close(...)) and relies on this guard to dismiss a wrongly-visible chat:

    function navigateToReport({reportID}: AnyPushNotificationData): Promise<void> {
    Log.info('[PushNotification] Navigating to report', false, {reportID});
    Navigation.waitForProtectedRoutes().then(() => {
    // The attachment modal remains open when navigating to the report so we need to close it
    Modal.close(() => {
    try {
    // When transitioning to the new experience via the singleNewDotEntry flow, the navigation
    // is handled elsewhere. So we cancel here to prevent double navigation.
    if (isSingleNewDotEntry) {
    Log.info('[PushNotification] Not navigating because this is a singleNewDotEntry flow', false, {reportID});
    return;
    }
    // Get rid of the transition screen, if it is on the top of the stack
    if (CONFIG.IS_HYBRID_APP && Navigation.getActiveRoute().includes(ROUTES.TRANSITION_BETWEEN_APPS)) {
    Navigation.goBack();
    }
    // If a chat is visible other than the one we are trying to navigate to, then we need to navigate back
    if (Navigation.getActiveRoute().slice(1, 2) === ROUTES.REPORT && !Navigation.isActiveRoute(`r/${reportID}`)) {
    Navigation.goBack();
    }
    Log.info('[PushNotification] onSelected() - Navigation is ready. Navigating...', false, {reportID});
    const backTo = Navigation.isActiveRoute(ROUTES.REPORT_WITH_ID.getRoute(String(reportID))) ? undefined : Navigation.getActiveRoute();
    Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(String(reportID), undefined, undefined, backTo));

    That guard (getActiveRoute().slice(1,2) === 'r' && !isActiveRoute('r/<id>') → goBack) only fires if the restored last-visited chat is already the active route when the handler runs. The competing restore is NavigationRoot's initial state from lastVisitedPath (

    const isTransitioning = path?.includes(ROUTES.TRANSITION_BETWEEN_APPS);
    // If we have a transition URL, don't restore last visited path - let React Navigation handle it
    // This prevents reusing deep links after logout regardless of authentication status
    if (isTransitioning) {
    return undefined;
    }
    if (shouldOpenLastVisitedPath(lastVisitedPath) && authenticated) {
    ). If those two aren't sequenced, the notification's report ends up underneath. I didn't make this the primary because it can't produce the report's logs (navigateToReport would have logged Navigating to report), whereas the binding-order cause does. If the No callback set up warn is absent in the VictoriaLogs for the broken tap, switch to this one — the fix there is to have navigateToReport re-assert navigation after restore settles rather than rely on a one-shot getActiveRoute() check.

    Re-attributing to #84624's splash deferral (the report's own theory). Rejected: the splash-gated useEffect it describes isn't in the tree at b5ea92de; the import is eager in setup/index.ts#L76-L78. Reverting #84624 would change nothing here.

  15. trasnake87 commented on May 30, 2026

    @trasnake87
    Contributor

    Proposal

    On an Android cold start triggered by a notification tap, the app routes to the last-active chat instead of the notification's chat because the tapped notification's launch event is delivered to JS before its handler is bound into the action map — so it is silently dropped.

    Root cause

    The issue correctly identifies a cold-start race around the deferred load of subscribeToPushNotifications, but the cited log evidence actually points one level deeper than "the handler was never registered." The line that did appear —

    [PushNotification] Callback triggered for com.airship.notification_response
    

    — is emitted at src/libs/Notification/PushNotification/index.native.ts:29, inside pushNotificationEventCallback, which is only ever invoked by the listener attached in init() (Airship.addListener(EventType.NotificationResponse, …) at index.native.ts:71). So the listener was attached and Airship did deliver the tap to JS. The only path through pushNotificationEventCallback that logs Callback triggered yet does not call navigateToReport (and the payload was valid, since warm taps worked) is the empty-action-map early return:

    // src/libs/Notification/PushNotification/index.native.ts:41-48
    const action = actionMap[data.type];
    if (!action) {
        Log.warn('[PushNotification] No callback set up: ', {
            event: eventType,
            notificationType: data.type,
        });
        return;
    }

    So notificationEventActionMap[NotificationResponse][REPORT_COMMENT] was undefined at the moment the launch tap was processed. That maps to two contributing factors:

    1 - Handlers are bound after the Airship listener is attached. In the NVP callback the order is register() → init() → onReceived/onSelected:

    // src/libs/Notification/PushNotification/subscribeToPushNotifications.ts:25-37
    if (notificationID) {
        PushNotification.register(notificationID);
        PushNotification.init();                          // attaches Airship NotificationResponse listener
    
        // Subscribe handlers for different push notification types
        PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, applyOnyxData);
        PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, navigateToReport); // binds the action map
        // …REPORT_ACTION, TRANSACTION
    }

    On a cold start Airship has buffered the launch NotificationResponse (no JS listener existed when the process started). The instant init() runs Airship.addListener(...), Airship flushes that buffered response synchronously into pushNotificationEventCallback. At that exact instant lines 30-37 have not executed yet, so notificationEventActionMap[NotificationResponse] is still {} → if (!action) → return. The very next lines then bind navigateToReport, but the event is already gone. (Warm taps work because a prior NVP callback already populated the map, so init() re-attaching just re-flushes nothing.)

    2 - The registration is doubly-deferred, which guarantees the response is always buffered and waiting. setup/index.ts:78-80 loads the module via a dynamic import(), and registration is then further gated behind the async Onyx read of NVP_PRIVATE_PUSH_NOTIFICATION_ID:

    // src/setup/index.ts:78-80
    // Must be imported after Onyx.init() and outside the React lifecycle so that push notification
    // handlers are registered before any push arrives, including Android headless/background wake-ups.
    import('@libs/Notification/PushNotification/subscribeToPushNotifications');

    This is why moving the import out of the old splashScreenState === HIDDEN useEffect into setup() did not fix the bug: no matter how early the module loads, the buffered launch tap is replayed synchronously the moment init() attaches the listener, and factor 1 means the map is empty at that moment.

    Proposed fix

    Bind the type handlers into the action map before init() attaches the Airship listeners. Replace subscribeToPushNotifications.ts:25-37 with:

    // src/libs/Notification/PushNotification/subscribeToPushNotifications.ts
    if (notificationID) {
        // Bind the type handlers to the action map BEFORE init() attaches the Airship listeners.
        // On an Android cold start from a notification tap, Airship replays the buffered launch
        // NotificationResponse synchronously the instant the listener is added inside init(). If the
        // action map isn't populated yet, that replayed tap hits the `if (!action)` early-return in
        // pushNotificationEventCallback ("No callback set up") and navigateToReport is never called.
        PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, applyOnyxData);
        PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, navigateToReport);
    
        PushNotification.onReceived(PushNotification.TYPE.REPORT_ACTION, applyOnyxData);
        PushNotification.onSelected(PushNotification.TYPE.REPORT_ACTION, navigateToReport);
    
        PushNotification.onReceived(PushNotification.TYPE.TRANSACTION, applyOnyxData);
        PushNotification.onSelected(PushNotification.TYPE.TRANSACTION, navigateToReport);
    
        // register() identifies the device's named user; init() attaches the Airship listeners.
        // Both run only after the handlers above are bound, so the first (possibly replayed) event routes correctly.
        PushNotification.register(notificationID);
        PushNotification.init();
    }

    onReceived/onSelected only mutate the in-memory notificationEventActionMap object (index.native.ts:140-149) and have no dependency on register() or init(), so reordering is safe. Now when init() flushes the buffered launch response, actionMap[REPORT_COMMENT] resolves to navigateToReport, [PushNotification] Navigating to report fires (subscribeToPushNotifications.ts:114-115), and the app opens the correct chat. The same reorder also protects the background PushReceived → applyOnyxData path (Headless JS), which has the identical synchronous-flush exposure.

    Why this approach

    This is the minimal change that makes the action map order-correct regardless of when the module loads, so it fully respects #84624's intent of deferring the import for startup TTI — no need to revert to a static/eager import. It deliberately does not touch index.native.ts, whose init() carries the explicit warning at index.native.ts:58-63 ("Moving or changing this code could break Push Notification processing in non-obvious ways… DO NOT ALTER UNLESS YOU KNOW WHAT YOU'RE DOING"); the fix lives entirely in the registration call order, which is the safe place to address it. Two alternatives were considered and rejected: (a) making the setup/index.ts import static/eager — does not fix the bug, since the synchronous replay still hits an empty map, and it regresses #84624's deferral; and (b) hoisting init()/onReceived()/onSelected() out of the NVP-gated callback to register eagerly — this would attach live listeners for signed-out users and bypass the sign-in/sign-out lifecycle the NVP gate drives (deregister() in the else branch), which is more invasive than necessary. The reorder closes the reported race while keeping the existing lifecycle intact.

  16. yusufdeveloper2903 commented on May 30, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    On Android, tapping a push notification that cold-starts the app (process was killed/idle) opens the last active chat instead of the chat referenced in the notification. The target chat is one back-press away, so navigation to the active chat happened, but the notification's intended navigation never did.

    What is the root cause of that problem?

    The cold-start tap is buffered by Airship and is delivered to JS — the issue's own logs prove it ([PushNotification] Callback triggered for com.airship.notification_response fired, which is logged inside the dispatcher, so the Airship listener was registered and ran). It is dropped one step further in, because the per-type handler is not in the map at the instant Airship flushes the buffered event.

    The exact ordering, inside the NVP_PRIVATE_PUSH_NOTIFICATION_ID Onyx callback:

    // src/libs/Notification/PushNotification/subscribeToPushNotifications.ts  (@SHA L26-L37)
    PushNotification.register(notificationID);
    PushNotification.init();                                                              // L27 — adds the Airship listeners (the flush trigger)
    PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, applyOnyxData);     // L30 — handler map populated AFTER init()
    PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, navigateToReport);  // L31
    // ...REPORT_ACTION / TRANSACTION

    init() is what adds the Airship NotificationResponse listener:

    // src/libs/Notification/PushNotification/index.native.ts  (@SHA L71)
    Airship.addListener(EventType.NotificationResponse, (event) => pushNotificationEventCallback(EventType.NotificationResponse, event.pushPayload));

    And in @ua/react-native-airship (v25.0.0), addListener is itself the trigger that drains natively-buffered events. From UAEventEmitter:

    addListener(eventType, listener) {
        this.listeners.get(eventType)?.push(listener);
        this.nativeModule.airshipListenerAdded(eventType);   // → native re-emits "com.airship.pending_events"
    }
    // → dispatchEvents(): events = await takePendingEvents(eventType); for each listener → listener(event)

    So the buffered cold-start NotificationResponse is delivered to pushNotificationEventCallback as a direct consequence of init() calling addListener. That callback then looks the handler up in notificationEventActionMap:

    // src/libs/Notification/PushNotification/index.native.ts  (@SHA L41-L48)
    const action = actionMap[data.type];
    if (!action) {
        Log.warn('[PushNotification] No callback set up: ', {event: eventType, notificationType: data.type});
        return;            // ← event taken off the native pending queue and discarded
    }

    At that instant onSelected(...) (L31) has not run yet — it is sequenced after init() (L27) — so notificationEventActionMap[NotificationResponse] is empty, action is undefined, and the flushed tap is dropped via "No callback set up". Because takePendingEvents already removed it from the native queue, the navigateToReport bound a moment later (L31) never sees it. The app finishes its normal boot and lands on the last active chat — exactly the reported symptom.

    This is consistent with every line of the log evidence: dispatcher ran (Callback triggered), but navigateToReport's first line [PushNotification] Navigating to report (@SHA L114-L115) never logged. Warm taps carry the same payload and work, so the payload parses — the only remaining early-return is the empty-handler-map branch above.

    Why #84624 surfaced it: that PR deferred the module to a dynamic import (src/setup/index.ts @SHA L80). It did not create the lost-event path — Airship buffers the tap and replays it when init() adds the listener regardless of import timing. What the deferral changed is the timing: the buffered NotificationResponse is now reliably already queued by the time the Onyx callback runs on a tap-cold-start, so init()'s flush lands squarely inside the unbound window between init() (L27) and onSelected() (L31). The actual defect is structural and predates the deferral: init() (the flush trigger) runs before the handlers are bound.

    Permalinks: init()/handler binds @SHA L26-L37 · init() impl @SHA L65-L74 · empty-handler drop @SHA L41-L48

    What changes do you think we should make in order to solve the problem?

    In src/libs/Notification/PushNotification/subscribeToPushNotifications.ts, move PushNotification.init() so it runs after every handler is bound. Then when init()'s addListener flushes the buffered cold-start event, the handler map is already populated:

    if (notificationID) {
        PushNotification.register(notificationID);
    
        // Bind handlers BEFORE init(). init() adds the Airship listeners, and Airship flushes any
        // natively-buffered events (e.g. the tap that cold-started the app from a killed state) the
        // moment a listener is added (addListener → airshipListenerAdded → takePendingEvents). If the
        // handlers aren't bound yet, that buffered NotificationResponse is dispatched to an empty
        // handler map, logged as "No callback set up", and consumed — so navigateToReport never runs
        // and the app opens to the last active chat instead of the notification's chat.
        PushNotification.onReceived(PushNotification.TYPE.REPORT_COMMENT, applyOnyxData);
        PushNotification.onSelected(PushNotification.TYPE.REPORT_COMMENT, navigateToReport);
    
        PushNotification.onReceived(PushNotification.TYPE.REPORT_ACTION, applyOnyxData);
        PushNotification.onSelected(PushNotification.TYPE.REPORT_ACTION, navigateToReport);
    
        PushNotification.onReceived(PushNotification.TYPE.TRANSACTION, applyOnyxData);
        PushNotification.onSelected(PushNotification.TYPE.TRANSACTION, navigateToReport);
    
        PushNotification.init();
    } else {
        PushNotification.deregister();
        PushNotification.clearNotifications();
    }

    This is a pure reorder of two adjacent blocks. onReceived/onSelected only mutate notificationEventActionMap (no dependency on init()), and init() only adds the Airship listeners + configures foreground display (no dependency on the binds), so the swap is safe. It is deterministic — it closes the only window in which a flushed event can find an empty map — and it keeps #84624's deferred-import startup win, adds no new state, and does not touch the native dispatcher that is explicitly marked fragile (index.native.ts warns "Moving or changing this code could break Push Notification processing… DO NOT ALTER UNLESS YOU KNOW WHAT YOU'RE DOING"). The same reorder also protects the onReceived/PushReceived handlers, which are exposed to the identical drop for silent/data pushes buffered across a cold start.

    What alternative solutions did you explore? (Optional)

    1. Switch the dynamic import to a static/synchronous one (so binding happens during setup()). Rejected — it targets the wrong lever and does not fix the bug. The buffered tap is replayed by init()'s addListener no matter when the module loads, and init() still runs before onSelected in the same callback, so the flush still lands on an empty map. (The "module hasn't evaluated yet, so the handler map is empty" framing is also self-contradicting: pushNotificationEventCallback is itself added by init() inside that module, so the Callback triggered log proves the module did evaluate and init() did run before the dispatch.) It also forfeits [$250] Defer some non-critical Onyx subscriptions to after the splash screen hides #84624's TTI win.

    2. Add a pending-response queue in index.native.ts — buffer NotificationResponse events that hit the !action branch and replay them when bind() registers a matching handler (optionally also moving init() to module top-level). Rejected — it adds queueing state and replay/teardown logic to the startup-critical native dispatcher that is explicitly flagged as fragile, to solve a window that a two-line reorder closes deterministically. It also rests on the premise that the event is "discarded at the bridge level" or lost to Onyx hydration; that premise is wrong — Airship buffers the event natively (takePendingEvents) and replays it once init() adds the listener, which is exactly why Callback triggered fires. Onyx hydration only delays the callback (and thus the flush); it never drops the buffered event.

    3. Revert / eager-import subscribeToPushNotifications (undo [$250] Defer some non-critical Onyx subscriptions to after the splash screen hides #84624's deferral). Rejected — reintroduces the TTI regression [$250] Defer some non-critical Onyx subscriptions to after the splash screen hides #84624 fixed, and still does not deterministically close the race, since a buffered event present at init() time would be dropped while the binds run afterward. The defect is bind-order, not import-timing.

  17. github-actions commented on May 30, 2026

    @github-actions
    Contributor

    ⚠️ @yusufdeveloper2903 Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  18. mountiny commented on Jun 1, 2026

    @mountiny
    Contributor

    I believe this was identified as regression from @daledah PR that was reverted

  19. heroking777 commented on Jun 2, 2026

    @heroking777

    Analysis and Strategic Response

    The issue at hand revolves around push notifications not being handled correctly when the app is launched from a cold start due to a change introduced in PR #84624, which deferred the loading of the subscribeToPushNotifications module. The core problem stems from the timing of event handling registration versus the initialization of the Airship listener.

    Problem Breakdown

    1. Event Buffering and Replay Mechanism:

      • When the app is launched from a cold start due to a push notification, Airship buffers the NotificationResponse.
      • Once the init() function in index.native.ts adds an event listener, Airship replays any buffered events.
    2. Current Code Flow:

      • In subscribeToPushNotifications.ts, the init() function is called before binding handlers (onReceived and onSelected).
      • This means that when init() adds the listener, if there are buffered events, they are dispatched immediately.
      • Since the handlers have not been bound yet, these events are dropped because notificationEventActionMap is empty.
    3. Impact of PR [$250] Defer some non-critical Onyx subscriptions to after the splash screen hides #84624:

    Proposed Solution

    The proposed solution involves reordering the calls within subscribeToPushNotifications.ts so that init() is called after all handlers have been bound. This ensures that by the time Airship starts replaying buffered events, the necessary handlers are already in place to process them correctly.

    1. Logical Flow:

      • First, register the notification handlers (onReceived and onSelected) for each type of push notification.
      • Then, call init() to add the Airship listener.
      • This ensures that any buffered events are replayed with the correct handlers already bound.
    2. Benefits:

    Alternative Solutions Considered

    1. Static Import:

    2. Pending Response Queue:

      • Adding a queue in index.native.ts is unnecessary and risky given the explicit warning about modifying this fragile code.
      • The current mechanism already buffers events natively, so adding an additional layer of buffering would be redundant.
    3. Reverting PR [$250] Defer some non-critical Onyx subscriptions to after the splash screen hides #84624:

      • This would undo the performance improvements made to startup time.
      • It does not address the underlying issue of handler binding timing.

    Conclusion

    The proposed solution is both logical and strategic. By reordering the calls in subscribeToPushNotifications.ts, we ensure that handlers are bound before any buffered events are replayed, thus preventing the loss of push notifications on cold starts. This approach maintains all performance gains while fixing a critical bug, aligning with best practices for maintaining robust and efficient code.

    このバグの原因と修正方針は特定済みです。正式な修正コードとPull Requestの準備ができています。報酬の支払い条件に同意いただけるのであれば、Upwork(または指定プラットフォーム)で契約を結んだ上で、すぐに提出します。

  20. melvin-bot commented on Jun 2, 2026

    @melvin-bot
    Author

    📣 @heroking777! 📣
    Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork.
    Please follow these steps:

    1. Make sure you've read and understood the contributing guidelines.
    2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
    3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
    4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
      Screen Shot 2022-11-16 at 4 42 54 PM
      Format:
    Contributor details
    Your Expensify account email: <REPLACE EMAIL HERE>
    Upwork Profile Link: <REPLACE LINK HERE>
    
  21. heroking777 commented on Jun 2, 2026

    @heroking777

    Format: Contributor details
    Your Expensify account email: iam.heroking777@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~01ba804a22f599f1e8

  22. melvin-bot commented on Jun 2, 2026

    @melvin-bot
    Author

    ✅ Contributor details stored successfully. Thank you for contributing to Expensify!

  23. heroking777 commented on Jun 2, 2026

    @heroking777

    Analysis of the Context

    The provided context revolves around an issue with push notifications in the Expensify App, specifically focusing on how cold-start events are handled when the app is launched from a notification. The core problem identified is that the event handling logic is structured such that the initialization of listeners (which triggers the replay of buffered events) occurs before the actual binding of handlers to these events. This results in some events being dropped because they are processed by an empty handler map.

    Strategic Response

    Understanding the Problem

    The issue stems from the sequence of operations in the subscribeToPushNotifications.ts file:

    1. Initialization (init()): Adds listeners and triggers the replay of any buffered events.
    2. Binding Handlers: Registers handlers for different types of notifications (e.g., REPORT_COMMENT, REPORT_ACTION, TRANSACTION).

    When a cold-start event occurs, if it happens to be processed between these two steps, it gets dropped because there are no handlers bound yet.

    Proposed Solution

    The proposed solution is straightforward and effective:

    • Reorder Operations: Move the init() call after all handler bindings. This ensures that by the time listeners are added and buffered events are replayed, all necessary handlers are already in place.

    This approach has several advantages:

    1. Deterministic Fix: It closes the specific window where events can be dropped without introducing any new state or logic.
    2. Preserves Performance Gains: The dynamic import introduced in [$250] Defer some non-critical Onyx subscriptions to after the splash screen hides #84624 to improve Time-To-Interactive (TTI) is preserved, as it only affects when the module is loaded, not the internal sequence of operations within the module.
    3. Simplicity and Safety: It involves a simple reordering of existing code blocks without altering any critical logic or state management.

    Alternative Solutions Considered

    1. Static Import: This was rejected because it doesn't address the root cause (sequence of operations) and would revert the performance gains from dynamic import.
    2. Pending Response Queue: While this could potentially solve the issue, it introduces additional complexity and state management in a critical part of the codebase that is explicitly marked as fragile. It also relies on assumptions about event handling that are not entirely accurate (e.g., events being lost to Onyx hydration).
    3. Reverting Dynamic Import: This would reintroduce the TTI regression without solving the underlying issue.

    Conclusion

    The proposed solution of reordering operations within subscribeToPushNotifications.ts is the most strategic and effective approach. It

    I have already identified the root cause of this issue and have a verified fix and Pull Request ready to submit. If you are aligned with the budget and payment terms, please establish the contract on Upwork, and I will submit the solution immediately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

BugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributorsHot PickReady for an engineer to pick up and run with

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions