[$175] Android-Spend-Tap device back not navigate to Expenses from Reports tab
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number: 9.5.53-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/102986 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Android 17 App Component: Search
Action Performed:
Precondiions:
- Account with workspace, Enable 3-button-Navigation mode
- Open hybrid app
- Navigate to Spend
- Tap on Reports tab
- Tap on Expenses tab
- Tap on Reports tab
- Tap on device Back button
- Tap on device Back button again
Expected Result:
Step 6: Verify that Expenses is selected and its list is shown. Step 7: Verify that Reports is selected and its list is shown.
Actual Result:
Step 6: Reports is still selected Step 7: User is navigated back to Home (Or the page that user stays before go to Spend)
Workaround:
Unknown
Platforms:
- [x] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [ ] Windows: Chrome
- [ ] MacOS: Chrome Safari
Screenshots/Videos
https://github.com/user-attachments/assets/50d259ec-9ade-4476-b470-c9f178ee4b7f
Applause Internal Information Exported by: Julia Ponikarchuk Bug ID: 7322567
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022125093609565216507
- Upwork Job ID: 2125093609565216507
- Last Price Increase: 2026-11-24
While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/193809c6e3231920dd5dc4c844becbc37948c651d6e88f963f652913a6ae7c33
Triggered auto assignment to Contributor-plus team member for initial proposal review - @Pujan92 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022125093609565216507
Proposal
What is the root cause of that problem?
The navigation-history cursor advances twice per Android Back press. Confidence: medium for this reported issue; the mechanism is reproduced in router tests, but not verified in the hybrid app.
Android checks canGoBack() before calling goBack(). That check evaluates GO_BACK without committing its result. However, App’s router changes a cursor stored outside navigation state during that evaluation. The actual Back action then starts from the already-advanced cursor and skips another tab snapshot.
This explains both symptoms:
- First Back: skips Expenses and restores the earlier Reports snapshot, so Reports appears unchanged.
- Second Back: exhausts Spend’s internal history prematurely, allowing navigation back to Home/the preceding page.
Code evidence and verification
- Spend tab selections dispatch
PUSH_PARAMS: SearchTypeMenuNarrow.tsx:221–234. - Android performs the check followed by navigation: useBackButton.native.tsx:13–26.
- The router mutates its hidden cursor while evaluating Back: addPushParamsRouterExtension.ts:184–230.
Two isolated tests using the actual router passed: the check-plus-dispatch sequence reproduced both symptoms; direct dispatch correctly restored Expenses, then Reports. The history snapshots remained intact, ruling out missing history in this reproduction.
The same cursor mutation exists before the QA refactor. Therefore, the router-history assertion refactor should not be identified as introducing this defect.
Hybrid-specific Back interception remains unverified. No source changes were made.
What changes do you think we should make in order to solve the problem?
Make history replay side-effect-free: store the replay position in returned navigation state rather than mutating a closure-held cursor. A discarded canGoBack() evaluation must not consume history.
Add regression coverage that evaluates and discards GO_BACK before each committed Back action, asserting Expenses → Reports and remaining inside Spend until its history is exhausted. Preserve forward-history coverage as well.
What alternative solutions did you explore? (Optional)
Changing tab selection or removing Android’s Back check would mask the router defect rather than correct it.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/107807) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On Android, after switching Spend tabs Reports -> Expenses -> Reports, pressing the device Back button once does not go back to Expenses (Reports stays selected), and pressing it a second time exits Spend to Home instead of going back to Reports. The video shows both symptoms: Reports is still selected at ~18-20s after the first Back, and the app is on Home at ~22s after the second Back.
What is the root cause of that problem?
The PUSH_PARAMS history cursor advances twice per Android Back press, so each press skips one tab snapshot.
Tab switches dispatch PUSH_PARAMS (SearchTypeMenuNarrow.tsx), and the router extension (src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts) appends a snapshot to its history and moves a closure-held cursor (pushParamsHistoryPosition) to the end. After Reports -> Expenses -> Reports the history is [R0, R1, E, R2] with the cursor at 3.
Android's Back handler (useBackButton.native.tsx in @react-navigation/native) calls navigation.canGoBack() before navigation.goBack(). canGoBack() (@react-navigation/core, useNavigationHelpers.tsx) evaluates router.getStateForAction(state, CommonActions.goBack()) and, for this navigator, only checks whether the result is non-null, discarding it. But the extension's GO_BACK branch reads the closure cursor, finds the previous snapshot, and writes pushParamsHistoryPosition = prevIdx while evaluating. So the discarded check already consumes one step of history, and the real dispatch starts from the advanced cursor and skips another snapshot.
Traced on baseline e91964cb, matching both symptoms exactly. First Back: the check moves the cursor 3 -> 2 and returns the Expenses state, which is discarded; the real dispatch reads cursor 2, moves to 1, and returns Reports, so Reports stays selected. Second Back: the check moves the cursor 1 -> 0; the real dispatch reads cursor 0, finds no previous snapshot, falls through to the underlying StackRouter, which returns null for a single-route stack, so the press bubbles to the parent navigator and the app goes Home. Because getStateForAction is expected to be a pure function of (state, action), a discarded evaluation should be harmless, but this closure mutation makes it consume one step of history. The same mutation predates the PR #102986 refactor, so that refactor did not introduce the defect.
What changes do you think we should make in order to solve the problem?
Make the GO_BACK replay position a pure function of the navigation state, so a discarded canGoBack() evaluation cannot consume history. Only src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts changes.
- New helper
findCurrentHistoryIndex(history, focusedRoute): scans the history from the end and returns the last entry with the same route key and the same compound params (compoundParamsKey, the existing util) as the focused route. If no compound matches, because the focused params drifted from every snapshot after a SET_PARAMS (typing), it returns the last entry for the same route key. If the focused route has no entry in history at all, it returns -1 and the caller falls back to the closure cursor exactly as before. - GO_BACK/POP branch:
currentIdxnow comes fromfindCurrentHistoryIndexinstead of the closure cursor. Everything else in the branch is unchanged: it finds the previous same-key snapshot, fires the backward focus-return notification, pops history only when the cursor was at the end, and keepspushParamsHistoryPosition = prevIdxso later PUSH_PARAMS and RESET handling stay consistent. That write is still there, but the value written is derived from the unchanged state, so the discarded evaluation and the real dispatch write the same value. - No other behavior changes except the mid-cursor edge case in the second question below: PUSH_PARAMS, SET_PARAMS, RESET, and
resolveCursorForResetare untouched, and the fix is scoped to the search fullscreen navigator that owns the PUSH_PARAMS history.
Tests added in tests/unit/Navigation/routerExtensions/addPushParamsRouterExtension.test.ts (Given/When/Then style), with a simulateAndroidBackPress helper that calls getStateForAction(state, GO_BACK) once and discards the result (as canGoBack() does) before dispatching the real GO_BACK: the full issue repro (Reports -> Expenses -> Reports, then Back to Expenses, Back to Reports, Back to the initial Reports snapshot, and a fourth Back returning null so it bubbles to Home); a check that a discarded GO_BACK evaluation does not consume history; a mid-cursor Back that reverts one snapshot and preserves forward entries; and a SET_PARAMS-drift Back that lands on the last pushed snapshot instead of skipping past it.
Evidence: all 4 new tests fail on the clean baseline (the repro fails at the first Back with Reports instead of Expenses, the mid-cursor case returns null, the drift case lands on A instead of B) and all 48 tests in the suite pass after the fix (44 existing + 4 new). spell-changed clean, React Compiler compliance check passed, code-inline-reviewer round returned 0 violations. Full typecheck could not be run on this machine: the TypeScript compiler process is killed before emitting diagnostics (a known limitation of this 6 GB VM; no diagnostics were emitted before the process was killed); the change adds one pure helper returning number and keeps all declared types, and the type-aware lint rules pass on the changed lines. Direct oxlint on the two changed files reports 4 errors, all no-unsafe-type-assertion on lines that already exist in the baseline (identical in HEAD, only shifted by the new helper).
Three points need the author's confirmation. First, this fix is at the shared router-extension level, which the hybrid app and standalone both use, but I could not run the hybrid app here, so please confirm on staging that no separate back handler in the hybrid layer also needs the same treatment. Second, in one narrow edge case (cursor mid-history after a browser-back RESET, then SET_PARAMS typing, then Back), the fallback takes the last same-key entry, which can drop a forward entry from the extension history and land on the current snapshot (typing reverted) instead of stepping back to the previous snapshot; please confirm that trade-off is acceptable, or whether forward entries must be preserved there too. Third, when the history contains duplicate compound snapshots and the cursor is mid-history after a RESET, state alone cannot identify which identical occurrence is current: verified with history [R, R, E, R], RESET to Expenses, Back 1 goes to Reports (correct) but Back 2 jumps forward to Expenses instead of stepping back to the earlier Reports. The reported repro has no RESET, so it is unaffected, but please confirm this corner is acceptable, or whether the replay position should be stored in the navigation state instead.
What alternative solutions did you explore? (Optional)
- Storing the replay position in the returned navigation state, as the earlier analysis suggested: this makes the router pure in the strictest sense, but it threads the cursor through every state the extension returns (
getInitialState,getRehydratedState, PUSH_PARAMS, GO_BACK, RESET, fall-through), changes thePlatformStackNavigationStatetype, and touches state persistence and theuseLinkinghistory-length logic. Deriving the position from the state achieves the same property for GO_BACK except when the history contains duplicate compound snapshots and the cursor is mid-history (after a RESET): state alone cannot identify which identical occurrence is current, so a second Back there can jump forward to the later identical snapshot instead of stepping back (see the third question above). I chose the smaller fix because the reported repro has no RESET; if that corner must also be correct, the state-stored approach is the right one. - Changing tab selection or removing Android's Back check: this would mask the symptom, not fix the cause. The cursor would still advance twice per evaluation, and any other caller that evaluates GO_BACK before dispatching would hit the same double step.
- Fixing it at the
canGoBack/useBackButtoncall site: not possible in this repo. Both live in@react-navigation/nativeand@react-navigation/core, and the check-then-dispatch sequence is the library's own contract. Routers are required to be pure functions of (state, action), so the fix belongs in the router. - Returning null from
getStateForActionfor GO_BACK when only the check runs: there is no way for the router to tell an evaluation apart from a committed dispatch, both call it identically, so any fix that depends on distinguishing them cannot work.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue?
On Android, when navigating between Spend tabs (e.g. Spend > Reports > Expenses > Reports) and pressing the hardware/device Back button, the first Back press fails to return to the Expenses tab (Reports remains selected), and the second Back press exits Spend entirely and returns to Home.
What is the root cause of that problem?
In src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts (lines 180–225):
let pushParamsHistoryPosition = -1;
...
// Inside getStateForAction:
if ((isGoBackAction(action) || isPopAction(action)) && state.history) {
...
const currentIdx = pushParamsHistoryPosition >= 0 && pushParamsHistoryPosition < history.length ? pushParamsHistoryPosition : history.length - 1;
...
if (prevIdx >= 0) {
...
if (focusedRoute.key) {
notifyPushParamsBackward(focusedRoute.key, targetParams);
}
pushParamsHistoryPosition = prevIdx;
return {
...state,
routes,
history: newHistory,
};
}
}
pushParamsHistoryPositionis maintained as a module-level mutable variable outside the navigationstate.- On Android,
useBackButton.native.tsxcallsnavigation.canGoBack()before callingnavigation.goBack(). canGoBack()evaluatesrouter.getStateForAction(state, CommonActions.goBack())as a dry-run check to verify if a valid state transition exists without committing the state.- During this
canGoBack()dry-run,addPushParamsRouterExtensionexecutes line 212 (notifyPushParamsBackward) and mutates line 218 (pushParamsHistoryPosition = prevIdx). - Immediately afterwards,
navigation.goBack()is dispatched, executinggetStateForActiona second time for the actual navigation action. BecausepushParamsHistoryPositionwas already advanced toprevIdxduring thecanGoBack()check, the second execution reads from the already-advanced cursor and steps back a second time. - As a result, the first Android Back press skips the intermediate
Expensestab and restores the earlierReportssnapshot (so Reports appears unchanged), and the second Back press exhausts Spend's history prematurely and navigates back to Home.
What changes do you think we should make in order to solve the problem?
Make getStateForAction pure and side-effect-free:
- Store the history cursor (
pushParamsHistoryPosition) directly inside the returned navigation state (e.g.state.pushParamsHistoryPosition), rather than in a module-level mutable variable. - Only notify listeners (
notifyPushParamsBackward) in a state-change listener / action handler after navigation state is actually committed, rather than during thegetStateForActionrouter evaluation.
In src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts:
type CustomNavigationState = NavigationState & {
pushParamsHistoryPosition?: number;
};
Read the current cursor from state.pushParamsHistoryPosition:
const currentIdx = state.pushParamsHistoryPosition !== undefined && state.pushParamsHistoryPosition >= 0 && state.pushParamsHistoryPosition < history.length
? state.pushParamsHistoryPosition
: history.length - 1;
And return the updated cursor in the new state object:
return {
...state,
routes,
history: newHistory,
pushParamsHistoryPosition: prevIdx,
};
When canGoBack() executes, it receives a new candidate state object that is discarded, leaving state.pushParamsHistoryPosition on the active state completely unchanged for the subsequent goBack() dispatch.
What alternative solutions did you explore? (Optional)?
Deriving the current index solely from history.length - 1 without maintaining a cursor was explored. However, a cursor is required to support forward navigation replay after mid-history resets. Persisting the cursor on state preserves forward/backward history integrity while guaranteeing pure router evaluation.
What specific scenarios should we cover in automated tests to prevent reoccurrence?
Add automated unit tests in tests/unit/addPushParamsRouterExtensionTest.ts:
- Purity of canGoBack(): Call
getStateForActionwithCommonActions.goBack()twice on the same state without applying the intermediate result. Verify the returned state in both calls is identical and points to the exact same previous route parameters. - Sequential Back Navigation: Dispatch sequential
GO_BACKactions for a Spend tab navigation sequence (Reports → Expenses → Reports) and verify that each Back press transitions step-by-step: Reports → Expenses, then Expenses → Reports, and finally exits Spend.
Contributor details?
- Email: [email protected]
- Upwork Profile: https://www.upwork.com/freelancers/~0131dae36abcf59374
Proposal
Please re-state the problem that we are trying to solve in this issue.
On Android, after switching Spend tabs (Reports → Expenses → Reports), pressing the device Back button once leaves Reports selected instead of returning to Expenses, and pressing Back a second time exits Spend completely (back to Home) instead of stepping back through the remaining Spend tab history.
What is the root cause of that problem?
addPushParamsRouterExtension.ts stores the PUSH_PARAMS history cursor in a mutable closure variable (let pushParamsHistoryPosition = -1) and mutates it inside getStateForAction (#L224 on param-revert GO_BACK/POP, and #L243 on the StackRouter fallback):
- On Android,
@react-navigation/native'suseBackButton.native.tsxcallsnavigation.canGoBack()beforenavigation.goBack(). canGoBack()dry-runsrouter.getStateForAction(state, CommonActions.goBack())solely to check whether a non-null state is returned, and discards the returned candidate state without committing it.- Because
getStateForActionmutatespushParamsHistoryPosition = prevIdxduring that dry-run, the cursor advances from index3(Reports) to2(Expenses) while React Navigation still holds the originalstate. - The immediately following real
navigation.goBack()runsgetStateForAction(state, GO_BACK)again on the samestate, reads the already-decremented cursor (2), and steps back a second time to index1(Reports), skippingExpenses. On the next Back press, the same double-advance exhausts Spend's param history and pops Spend back to Home.
Why both earlier proposals have structural flaws:
- Deriving cursor from
statewithout storing a cursor (Proposal 1): As that proposal itself notes, removing the cursor breaks two invariants explicitly designed intoaddPushParamsRouterExtension.ts#L123: duplicate compound snapshots ([R, R, E, R]) after a mid-cursorRESETjump forward instead of backward on the second Back, andSET_PARAMSfollowed by mid-cursor Back drops forward history entries. - Attaching
pushParamsHistoryPositionas a property onNavigationState(Proposal 2): Mutating React Navigation's state shape pollutesPlatformStackNavigationStatetypes, breaks state-equality/serialization assumptions, and is silently stripped whenever the innerrouter.getStateForActionorgetRehydratedStateconstructs a fresh state object (such as onSET_PARAMS,RESET, or StackRouter fall-through). Moreover, unconditionally removingnotifyPushParamsBackwardfromgetStateForActionbreaks existing unit tests inaddPushParamsRouterExtension.test.tswithout migrating them.
What changes do you think we should make in order to solve the problem?
Replace the mutable scalar let pushParamsHistoryPosition = -1 with a per-router WeakMap<object, number> keyed by immutable state reference (const cursorByState = new WeakMap<object, number>()) in addPushParamsRouterExtension.ts:
-
Pure state-to-cursor association (zero state-shape pollution, zero memory leaks):
- Add two small router-local helpers:
getCursor(state): returnscursorByState.get(state) ?? (state.history?.length ? state.history.length - 1 : -1)— preserving exact cursor tracking for every state produced by the router while falling back safely for externally constructed or freshly rehydrated states.withCursor(nextState, cursor): associatescursorByState.set(nextState, cursor)on the newly returned state object and returnsnextState, never mutating the cursor mapped to the inputstate.
- During Android's
canGoBack()dry-run,getStateForAction(S0, GO_BACK)readsgetCursor(S0) === 3, creates a fresh candidate stateS_drywithcursorByState.set(S_dry, 2), and returnsS_dry. WhencanGoBack()discardsS_dry,S_drybecomes eligible for GC andcursorByState.get(S0)remains3. The subsequent realgoBack()callsgetStateForAction(S0, GO_BACK)and transitions cleanly from3 → 2(Reports → Expenses).
- Add two small router-local helpers:
-
Thread
getCursor/withCursorconsistently across every state-returning branch ofaddPushParamsRouterExtension.ts:getInitialState(#L134-L137) &getRehydratedState(#L139-L145): ReplaceseedCursorwithwithCursor(enhanced, enhanced?.history?.length ? enhanced.history.length - 1 : -1).PUSH_PARAMS(#L152-L182): ReadcurrentCursor = getCursor(state)to slicebaseHistorymid-cursor, and returnwithCursor({...stateWithUpdatedParams, history: newHistory}, newHistory.length - 1).GO_BACK/POPparam-revert (#L185-L234): ReadcurrentIdxfromgetCursor(state), computeprevIdx, and returnwithCursor({...state, routes, history: newHistory}, prevIdx)without alteringstate's mapping.GO_BACK/POPfallback (#L236-L248): ReturnwithCursor({...newState, history: preservedHistory}, preservedHistory.length > 0 ? preservedHistory.length - 1 : -1).SET_PARAMS(#L256-L261): Preserve the input state's exact cursor viawithCursor({...newState, history: [...state.history]}, getCursor(state))so mid-cursorSET_PARAMSnever loses its cursor position.RESET(#L266-L314) & fall-through (#L317-L318): PassgetCursor(state)intoresolveCursorForReset, computenextCursoras a local variable (never mutating outer state), remap ifpreservedHistory.length !== history.length, and returnwithCursor(..., nextCursor).
-
Note on
notifyPushParamsBackwardduringcanGoBack()dry-runs:- Notice that
#L218also firesnotifyPushParamsBackwardinsidegetStateForAction, which consumesskipNextRestore/clearStagedPresson native (NavigationFocusReturn/index.native.ts#L307-L316) ifcanGoBack()runs beforegoBack(). - Because
addPushParamsRouterExtension.test.tscurrently assertsnotifyPushParamsBackwarddirectly ongetStateForActioncalls, we can keep this PR focused on theWeakMappure-cursor fix (keeping all 44 existing tests green with zero contract churn) — or, if preferred by C+/CME, defer focus-return notifications via a state-keyed pending-effectWeakMapflushed on committed navigation state change.
- Notice that
-
Tests:
- Extend
tests/unit/Navigation/routerExtensions/addPushParamsRouterExtension.test.tswith:- Idempotent
canGoBack()dry-run: CallinggetStateForAction(state, GO_BACK)multiple times on the samestatewithout committing always returns the exact same previous snapshot. - Full Android Back repro:
Reports → Expenses → Reports, simulatingcanGoBack()+goBack()on every Back press: Back #1 →Expenses, Back #2 →Reports, Back #3 → initialReportssnapshot, Back #4 →null(exits Spend to Home). - Duplicate snapshots + mid-cursor
RESET+ dry-runGO_BACK:[R, R, E, R]afterRESETtoE, dry-run + commit Back #1 →R(index 1), dry-run + commit Back #2 →R(index 0) — proving we do not regress the duplicate-snapshot invariant that stateless derivation breaks. SET_PARAMSmid-cursor preservation: Dry-run + commitGO_BACKafter mid-cursorSET_PARAMSpreserves forward history entries and steps back cleanly.
- Idempotent
- Extend
What alternative solutions did you explore? (Optional)
- Stateless derivation from
state.routes/state.history: Rejected because duplicate compound snapshots (A → B → A) after a mid-cursorRESETare mathematically ambiguous without a cursor, causing a second Back press to jump forward. - Adding a custom
pushParamsHistoryPositionfield directly ontoNavigationState: Rejected because it modifies React Navigation's public state shape, risks stripping in innerStackRouter/getRehydratedState/ persistence paths, and can breakuseLinkingor snapshot equality checks. A per-routerWeakMap<object, number>achieves identical referential purity without mutating state shape.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01aee0111e1a0ae483
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@Pujan92 Whoops! This issue is 2 days overdue. Let's get this updated quick!