App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Android - Distance - Manual map shows wrong location

Open applause-bot[bot] opened this issue 4 months ago • 30 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Version Number: 9.4.32-0 Reproducible in staging?: Yes Reproducible in production?: No If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/95372 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Samsung a31 App Component: Other

Action Performed:

1.Login to the Expensify app 2.Enable location permission for Expensify and select "Allow only while using the app" 3.Tap the FAB button 4.Tap "Track expense" 5.Open the Manual Distance Map 6.Allow the app to load the map 7.Sign out from the account 8.Sign in again with the same account 9.Open the Manual Distance Map again

Expected Result:

The Manual Distance Map displays the user's current location based on the device location permission.

Actual Result:

The Manual Distance Map displays San Francisco as the default location after signing in again, instead of the user's current location.

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [x] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [ ] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/c9a0062c-7ebe-48a9-b0ff-8ec4d26ca33b

View all open jobs on GitHub

Applause Internal Information Exported by: Murugesan Natarajan Bug ID: 7203915

Upwork Automation - Do Not Edit

applause-bot[bot] avatar Jul 10 '26 02:07 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/00eb557ae57873db57f71d1c687852f6f78529c16a01956f4de05e52cd677465

applause-bot[bot] avatar Jul 10 '26 02:07 applause-bot[bot]

Proposal

What is the root cause of that problem?

This is a regression from #95372 (merged 2026-07-08, "Only read foreground location permissions without requesting them at the beginning") — the same PR this bug was caught against. That PR touched only MapView.tsx and GPSMapView.tsx.

The manual distance map centers on userLocation ?? initialLocation, where initialLocation is the hardcoded default (San Francisco). userLocation is stored in Onyx (ONYXKEYS.USER_LOCATION), which is cleared on sign-out — so after re-login the map starts on the SF default and relies entirely on a one-shot useFocusEffect to fetch the real location and update it.

Before #95372, that effect called getCurrentPosition(...) unconditionally, which internally calls the active requestForegroundPermissionsAsync() — this forces expo-location to resolve the true OS authorization status and returns granted when permission is allowed. #95372 replaced this with a passive getForegroundPermissionsAsync() gate that runs first, and if it returns !granted, it clears the location and bails without ever calling getCurrentPosition. Because the effect is guarded by a useRef that flips to false after one run, a single false-negative read is sticky — the map never retries and stays on SF.

The passive read returns not-granted in the re-login scenario (the active request did not), which is why the map worked on the first open of a session but falls back to SF after signing out and back in.

Code evidence (SHA 7e966b4)
  • Center falls back to the SF default when userLocation is null: MapView.tsx:69-70
  • One-shot useRef gate + the new passive-permission check that clears location on !granted: MapView.tsx:107-144
  • getCurrentPosition uses the active requestForegroundPermissionsAsync() (the pre-#95372 path): getCurrentPosition/index.ts:11
  • USER_LOCATION is not in the sign-out keys-to-preserve list, so Onyx.clear wipes it on logout (src/libs/actions/Session/index.ts — no USER_LOCATION reference).

Why first-load works but re-login doesn't: both start with userLocation === null and a fresh MapView mount. The only behavioral difference is the permission call — the active request resolves granted and fetches the position; the passive read reports not-granted, clears the location, and the one-shot ref prevents any retry.

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

Stop treating a passive !granted read as "permission denied → wipe location." The goal of #95372 was only to avoid prompting the user when the map opens — not to stop reading an already-granted location. Preferred fix (in MapView.tsx):

  • On the passive read, only treat an explicit PermissionStatus.DENIED as the fallback trigger. For granted (or an undetermined-but-previously-allowed status), still call getCurrentPosition so an already-allowed permission isn't discarded. This keeps "don't prompt on open" while restoring the location read.

Secondarily (defense-in-depth, not the root fix): consider adding ONYXKEYS.USER_LOCATION to the sign-out keys-to-preserve list so the last known location survives logout instead of resetting to SF.

What alternative solutions did you explore? (Optional)

Making getCurrentPosition itself use the passive getForegroundPermissionsAsync() internally and letting MapView call it unconditionally as before — same "read, don't request" behavior without a separate gate. Note GPSMapView.tsx has the same passive-read pattern but self-heals via a re-check on app focus, so it doesn't exhibit the sticky failure; MapView.tsx has no such re-check.

⚠️ Confidence: Medium. The regression source, the cleared-on-logout behavior, the SF fallback, and the one-shot gate are all code-verified. The exact reason the passive getForegroundPermissionsAsync() read returns not-granted after re-login (vs. the active request) should be confirmed on-device by logging getForegroundPermissionsAsync().then(({granted, status})) at MapView.tsx:121 right after re-login.


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/95774) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.

MelvinBot avatar Jul 10 '26 02:07 MelvinBot

🚨 Edited by proposal-police: This proposal was edited at 2026-07-10 02:20:14 UTC.

Proposal

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

On native (Android and iOS), after signing out and signing back in with the same account, the manual distance map opens centered on San Francisco instead of the device's current location, even though the OS location permission is still granted. Opening the map before signing out works correctly; only the sign-out/sign-in cycle reproduces it. This is a regression introduced by PR #95372 (merged as a31422e), which is why it reproduces in staging but not production.

What is the root cause of that problem?

Sign-out runs Onyx.clear and ONYXKEYS.USER_LOCATION is not in the preserved keys in SignInRedirect.ts, so after signing back in userLocation is null. MapView then falls back to initialLocation, which DistanceRequestFooter builds from CONST.MAPBOX.DEFAULT_COORDINATE ([-122.4021, 37.7911], San Francisco) when there are no waypoints:

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L69-L70

For the map to show the real location, the focus effect must re-fetch it via getCurrentPosition and call setUserLocation. PR #95372 rewrote that effect. It now flips the one-shot guard shouldInitializeCurrentPosition.current = false synchronously (line 111), then defers the actual fetch behind an asynchronous permission read, getForegroundPermissionsAsync().then(...), guarded by an ignore flag:

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L120-L124

The effect returns a cleanup that sets ignore = true:

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L146-L148

useFocusEffect re-runs its callback whenever the useCallback dependencies change while the screen is focused, and on each re-run it first invokes the previous cleanup. setCurrentPositionToInitialState depends on initialLocation (derived from the initialState prop), and shouldPanMapToCurrentPosition depends on waypoints. On a fresh sign-in, Onyx is re-hydrating (transaction, mapbox token, waypoints) so these dependencies change identity within the tens-of-milliseconds native window of getForegroundPermissionsAsync. When that happens the cleanup fires ignore = true, aborting the pending .then before getCurrentPosition runs, and the re-run of the effect immediately returns at line 107 because the one-shot shouldInitializeCurrentPosition guard was already consumed. The location fetch is therefore permanently skipped: setUserLocation is never called, userLocation stays null, and currentPosition remains the SF fallback. Web is unaffected because MapViewImpl.web.tsx was not touched by the PR and still calls getCurrentPosition directly with no async permission gate and no ignore abort, which is exactly why the issue is flagged for Android and iOS but not web.

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

In src/components/MapView/MapView.tsx, remove the ignore cancellation from the focus effect so a focus-effect teardown/re-run no longer aborts the in-flight permission read and location fetch. The async callbacks here only write to Onyx (setUserLocation / clearUserLocation), never React component state, so completing them after a blur or unmount is harmless. This matches the pre-PR behavior, which had no such guard and worked correctly. The getForegroundPermissionsAsync gate is kept, so the PR's goal of never triggering an OS prompt on open is preserved.

getForegroundPermissionsAsync().then(({granted}) => {
    if (!granted) {
        setCurrentPositionToInitialState({code: GeolocationErrorCode.PERMISSION_DENIED, message: 'User denied access to location.'});
        return;
    }
    getCurrentPosition((params) => setUserLocation({longitude: params.coords.longitude, latitude: params.coords.latitude}), setCurrentPositionToInitialState);
});
// remove `let ignore = false`, both `if (ignore) return` checks, and the `return () => { ignore = true }` cleanup

With the abort gone, the first effect run consumes the one-shot guard, kicks off the permission read, and always completes it; later focus re-runs early-return harmlessly at the guard. Once permission is confirmed granted, getCurrentPosition resolves and setUserLocation writes the real coordinates, so the map pans off the SF fallback. This keeps the intended lifecycle contract: sign-out clears USER_LOCATION (correct, since one account's cached location must not persist into another session), and sign-in reliably re-triggers the fetch that repopulates it. Offline behavior is unchanged because the effect still early-returns when isOffline is true.

What alternative solutions did you explore? (Optional)

Preserving USER_LOCATION across sign-out by adding it to keysToPreserve in SignInRedirect.ts was rejected: it would leak one account's location into the next session and still show a stale position rather than the current one. Keeping ignore but deferring shouldInitializeCurrentPosition.current = false into the resolved .then was also rejected because it lets multiple focus re-runs fire concurrent permission reads and fetches; dropping the abort is simpler and mirrors the working web implementation.

MobileMage avatar Jul 10 '26 02:07 MobileMage

Proposal

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

On Android (and iOS), after signing out and signing back in with location permission still set to "Allow only while using the app", opening the Manual Distance Map shows San Francisco as the default location instead of the user's current device location. Expected: the map should center on the user's current location whenever the permission is granted, regardless of whether it is the first sign-in or a re-sign-in during the same app session.

What is the root cause of that problem?

Regression from PR #95372. In src/components/MapView/MapView.tsx:121-143 the useFocusEffect was changed to gate getCurrentPosition on getForegroundPermissionsAsync().then(({granted}) => ...). On the !granted branch (line 125-131) it now synthesizes a PERMISSION_DENIED error and calls setCurrentPositionToInitialState, which at line 91-99 invokes clearUserLocation() — wiping the Onyx USER_LOCATION (src/libs/actions/UserLocation.ts:13-15). On a re-sign-in, getForegroundPermissionsAsync on Android can resolve with granted: false on the first call after the app re-mounts the map (the runtime permission state is not yet re-hydrated in expo-location for the fresh module instance even though the OS grant is still "while in use"). The map then falls back to initialLocation derived from initialState.location, which DistanceRequestFooter.tsx:107-109 sets to CONST.MAPBOX.DEFAULT_COORDINATE = [-122.4021, 37.7911] (San Francisco) when there are no waypoints. Pre-PR code called getCurrentPosition unconditionally, so the OS-level grant was honored directly and the stale/undefined permission read never had a chance to short-circuit the location fetch.

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

  1. src/components/MapView/MapView.tsx:121-131 — do NOT treat !granted from getForegroundPermissionsAsync as a permission denial. Only clear the cached user location when getCurrentPosition's error callback (setCurrentPositionToInitialState) actually receives a real PERMISSION_DENIED error from the geolocation API. Instead, attempt getCurrentPosition and let its native error path decide.
  2. Alternatively, when granted is false, still call getCurrentPosition (it is a no-op / errors cleanly if truly denied) but do NOT synthesize a fake PERMISSION_DENIED error that clears the last-known user location.
  3. src/components/MapView/GPSMapView.tsx:55-70 — apply the same relaxed handling so the GPS-only variant used elsewhere doesn't regress the same way (the PR touched both files symmetrically).
  4. Add a re-check: if the first getForegroundPermissionsAsync returns granted: false on mount, retry once after the map becomes ready (or on next focus) before deciding to clear cached location, since expo-location's cached status can lag the OS grant right after an auth navigation reset.
  5. Preserve USER_LOCATION Onyx key across sign-out (or explicitly clear on sign-in) so the fallback path never lands on the SF default when the OS grant is intact.
  6. Add a regression test that mounts MapView with initialState.location = DEFAULT_COORDINATE, mocks getForegroundPermissionsAsync to resolve granted: false once then granted: true, and asserts setUserLocation is called (not clearUserLocation).

What alternative solutions did you explore? (Optional)

aswin-s avatar Jul 10 '26 02:07 aswin-s

🚨 Edited by proposal-police: This proposal was edited at 2026-07-10 02:37:56 UTC.

Proposal

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

On Android and iOS, opening the Manual Distance Map for a track expense should center on your current location once you've allowed location access. After you sign out and sign back in with the same account, the map instead centers on San Francisco even though the permission is still granted. It only clears up once the map component fully remounts.

What is the root cause of that problem?

The map center comes from src/components/MapView/MapView.tsx:70, const currentPosition = userLocation ?? initialLocation. userLocation is the Onyx USER_LOCATION value; when it's null the map falls back to initialLocation, which for a fresh manual map with no waypoints is CONST.MAPBOX.DEFAULT_COORDINATE ([-122.4021, 37.7911], San Francisco). So "shows SF" means userLocation is null. USER_LOCATION isn't in KEYS_TO_PRESERVE (src/libs/actions/App.ts), so sign-out's Onyx.clear() wipes it. That clear on logout is old and intended. After re-login the map is supposed to re-fetch the location and write it back through setUserLocation, but it doesn't.

The reason it doesn't is the location effect only runs once per mount. shouldInitializeCurrentPosition = useRef(true) is consumed on the first focus (MapView.tsx:107-111), then the effect does a read-only getForegroundPermissionsAsync().then(...) and, if granted, calls getCurrentPosition → setUserLocation. During the HybridApp sign-in transition this first pass gets lost: either the permission read resolves granted: false right after re-init and hits the !granted branch that clears back to SF, or a blur during the transition fires the ignore = true cleanup (MapView.tsx:146-148) and cancels the in-flight fetch. Because the one-shot ref is already spent, the effect early-returns on the next focus and never retries, so USER_LOCATION stays null.

This is a regression from PR #95372 (merge a31422e794d, 2026-07-08), which is the PR named in the issue's QA field and matches "staging: Yes, production: No." That PR replaced the old unconditional getCurrentPosition (which internally called requestForegroundPermissionsAsync and forced a native round-trip that came back granted) with the read-only getForegroundPermissionsAsync gate, to fix #93747 (the map popping an unsolicited OS permission prompt on open). The gate itself is correct; the problem is that combined with the pre-existing one-shot ref, there's no retry when that first read-and-fetch misses. Worth noting the sibling GPSMapView.tsx doesn't have this bug: it has no one-shot ref, re-reads permission on every focus, and re-checks on app-foreground via useAppFocusEvent (GPSMapView.tsx:60-87).

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

Make MapView's location fetch retry-capable instead of one-shot, mirroring GPSMapView, while keeping the read-only permission gate so we don't reopen #93747.

  1. Remove the shouldInitializeCurrentPosition ref (MapView.tsx:72) and its early-return/consume block (MapView.tsx:107-111), so useFocusEffect re-runs the existing getForegroundPermissionsAsync → getCurrentPosition → setUserLocation chain on every focus. The ref's original job was to avoid re-panning the camera on refocus, but that's already handled by shouldPanMapToCurrentPosition() (MapView.tsx:86-89), which returns false once the user has dragged the map or any waypoint exists. So removing the ref won't pan away from user-set state.
  2. Add useAppFocusEvent (src/hooks/useAppFocusEvent, already used by GPSMapView, not yet imported here) to re-read permission and re-fetch when the app returns to the foreground. This covers the background-to-foreground variant and also fixes a smaller existing gap: if you grant permission in OS settings while the map is open, MapView currently never re-checks.

MapView.tsx is the single native file behind both Android and iOS, so both reported platforms are covered. The web renderer (MapViewImpl.web.tsx) still requests location directly and was untouched by #95372, so web/mWeb stay unaffected, matching the unchecked boxes.

I'd also add a Jest test for the retry path, since nothing in src/components/MapView/ currently exercises the permission-then-fetch effect: mock getForegroundPermissionsAsync to resolve {granted: false} first then {granted: true}, mock getCurrentPosition, mount with empty waypoints and null USER_LOCATION, and assert setUserLocation eventually fires so the map isn't left on DEFAULT_COORDINATE.

What alternative solutions did you explore? (Optional)

Adding USER_LOCATION to KEYS_TO_PRESERVE so logout doesn't wipe it. I rejected this because it persists one account's device location across a different sign-in, doesn't restore the "refresh to actual current location" behavior, and has a wider blast radius than a map-only fix.

Reverting #95372 outright. That brings back the unsolicited OS permission prompt on map open, which is exactly the bug #95372 fixed, so keeping the read-only gate and fixing the retry mechanism is the better route. Changing DEFAULT_COORDINATE or the caller fallback isn't right either, since SF is the intended empty-state default and the real defect is the missing re-fetch.

shivang-goliyan avatar Jul 10 '26 02:07 shivang-goliyan

🚨 Edited by proposal-police: This proposal was edited at 2026-07-10 02:21:51 UTC.

Proposal

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

After signing out and back in, the manual distance map on Android/iOS shows the San Francisco default location instead of the user's current location, even though location permission is granted.

What is the root cause of that problem?

Regression from PR #95372 — specifically its commit "Implement cleanup for location permission handling in MapView component" (52fa828), which added a cancellation flag to an effect already guarded by a once-only ref. A cancelled fetch is never retried:

  1. The native map fetches the device location in a useFocusEffect that early-returns if shouldInitializeCurrentPosition.current is false, and sets it false before starting the async fetch — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L107-L111
  2. PR #95372 wrapped the fetch in getForegroundPermissionsAsync().then(...) with let ignore = false plus a cleanup ignore = true; both the permission result and the position callback bail once ignore is set — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L120-L148
  3. The in-flight window is seconds long: native getCurrentPosition awaits the permission request and a fresh GPS fix — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/libs/getCurrentPosition/index.ts#L10-L25
  4. useFocusEffect runs the cleanup and re-runs the effect on blur or whenever the callback identity changes; the callback depends on shouldPanMapToCurrentPosition (new whenever the waypoints array identity changes) and setCurrentPositionToInitialState (new whenever initialState changes) — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L149 — and initialState/waypoints are rebuilt from the draft transaction in DistanceRequestFooter — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/DistanceRequest/DistanceRequestFooter.tsx#L103-L118
  5. Right after sign-in Onyx is cold: the draft transaction, Mapbox token, and policy data hydrate while the fetch is pending, so the effect re-runs — the cleanup kills the pending result, and the re-run dead-ends at the once-only guard. The fetch is permanently cancelled, never retried.
  6. Sign-out clears USER_LOCATION (not in the preserve list — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/libs/actions/SignInRedirect.ts#L53-L62), so currentPosition = userLocation ?? initialLocation falls back to CONST.MAPBOX.DEFAULT_COORDINATE (San Francisco) — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L69-L70, https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/CONST/index.ts#L6046

Structural cause: the cancellation added by #95372 is inconsistent with the pre-existing once-only guard — the guard marks initialization "done" before any result was applied. Pre-PR, an effect re-run was harmless (the un-cancelled callback still wrote the location); now it is fatal.

This explains every symptom: staging-only (the PR isn't in production), Android + iOS App only (web's MapViewImpl.web.tsx still runs the fetch with no cancellation — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapViewImpl.web.tsx#L102-L124), and the sign-out/sign-in precondition (cold Onyx = re-renders mid-fetch, and no cached userLocation left to mask the cancelled fetch — before sign-out the location cached on first map load hides it).

Blast radius: affected — manual distance map on Android and iOS (DistanceMapView/index.android.tsx and index.tsx → native MapView). Verified unaffected — web/mWeb (no cancellation, above); ConfirmedRoute.tsx (always has waypoints → shouldPanMapToCurrentPosition() false → never fetches); the GPS tab's GPSMapView.tsx (re-reads permission every focus, no once-only ref, camera followUserLocation) — https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/GPSMapView.tsx#L58-L76

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

In MapView.tsx, mark initialization done only when a result is actually applied: delete the unconditional shouldInitializeCurrentPosition.current = false; at https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L111 and set it inside each settled branch (keep it in the !shouldPanMapToCurrentPosition() early-return):

getForegroundPermissionsAsync().then(({granted}) => {
    if (ignore) { return; }
    if (!granted) {
        shouldInitializeCurrentPosition.current = false;
        setCurrentPositionToInitialState({code: GeolocationErrorCode.PERMISSION_DENIED, ...});
        return;
    }
    getCurrentPosition((params) => { if (ignore) { return; } shouldInitializeCurrentPosition.current = false; setUserLocation(...); }, ...);
});

If the cleanup fires mid-fetch (dep change or blur), the ref stays true and the effect's next run retries; once a result lands, behavior is exactly today's fetch-once-per-mount. Regression safety: the no-OS-prompt gate, stale-write cancellation, and denied-path cache clearing from #95372 all stay intact; the ref is local to this component; web is untouched.

Why the obvious one-line fix does NOT work: reverting the cleanup commit (dropping ignore) reintroduces exactly what it was added to prevent — a stale in-flight callback writing USER_LOCATION after the screen blurred or a newer run started; and resetting the ref unconditionally in the cleanup changes the working case — after a successful fetch, every blur/refocus (e.g. returning from the waypoint-address RHP) would re-fetch and re-pan the map the once-only ref exists to prevent.

What alternative solutions did you explore? (Optional)

  1. Revert commit 52fa828 — spot fix; reintroduces the stale-write race the PR intentionally guarded (above).
  2. Reset the ref inside the cleanup only when no result was applied (a didSettle local) — functionally equivalent to the headline, slightly larger diff.
  3. Re-check permission and re-fetch on every focus like GPSMapView — removes the ref entirely but changes re-pan behavior on every refocus; broader than the regression warrants.

ahmdshrif avatar Jul 10 '26 02:07 ahmdshrif

Proposal

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

On Android/iOS, when a user opens the Manual Distance Map, signs out, signs back in with the same account, and opens the Manual Distance Map again, the map shows the San Francisco default location instead of the user's actual current location — even though location permission is still granted.

What is the root cause of that problem?

The map's current position comes from the userLocation Onyx key, falling back to a hard-coded San Francisco coordinate when it isn't set yet: https://github.com/Expensify/App/blob/98130124dd6e9330a0f955cb41beaf08470248e5/src/CONST/index.ts#L6046 https://github.com/Expensify/App/blob/98130124dd6e9330a0f955cb41beaf08470248e5/src/components/MapView/MapView.tsx#L60-L70

ONYXKEYS.USER_LOCATION is not in the KEYS_TO_PRESERVE list used when clearing Onyx on sign-out/sign-in, so it is wiped back to null every time the user re-authenticates, meaning the map has to fetch a fresh location again on the next visit.

MapView only ever performs that fetch once per component lifetime, gated by a ref that is flipped to false before the async work even resolves. It calls the native geolocation module a single time via getCurrentPosition, with no retry: https://github.com/Expensify/App/blob/98130124dd6e9330a0f955cb41beaf08470248e5/src/components/MapView/MapView.tsx#L101-L150

getCurrentPosition itself is a one-shot call with no timeout handling or retry logic — any transient failure (e.g. the OS location provider not being warmed up yet right after the app relaunches following sign-in) is simply forwarded to the error callback: https://github.com/Expensify/App/blob/98130124dd6e9330a0f955cb41beaf08470248e5/src/libs/getCurrentPosition/index.ts#L10-L25

That error callback, setCurrentPositionToInitialState, only takes action for PERMISSION_DENIED errors and silently no-ops for anything else: https://github.com/Expensify/App/blob/98130124dd6e9330a0f955cb41beaf08470248e5/src/components/MapView/MapView.tsx#L91-L99

Because shouldInitializeCurrentPosition.current was already consumed (set to false) before the fetch ran, and it is never reset on failure, no further attempt is ever made for the lifetime of that screen. Combined with userLocation having just been cleared by the sign-out/sign-in cycle, currentPosition permanently falls back to initialLocation, which for the Manual Distance Map is the San Francisco DEFAULT_COORDINATE. The very first time the map is opened this doesn't reproduce because the app/GPS provider is already warm from being logged in for a while, so the single location fetch attempt succeeds; right after a fresh sign-in it is more likely to transiently fail, and that one failure is now permanent for the screen.

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

Reset the one-shot initialization guard when the location fetch fails for a reason other than a denied permission, so the map retries fetching the device location on the next focus instead of getting stuck on the San Francisco fallback for the rest of the screen's lifetime:

                getCurrentPosition((params) => {
                    if (ignore) {
                        return;
                    }
                    const currentCoords = {
                        longitude: params.coords.longitude,
                        latitude: params.coords.latitude,
                    };
                    setUserLocation(currentCoords);
                }, setCurrentPositionToInitialState);

https://github.com/Expensify/App/blob/98130124dd6e9330a0f955cb41beaf08470248e5/src/components/MapView/MapView.tsx#L134-L143

                getCurrentPosition((params) => {
                    if (ignore) {
                        return;
                    }
                    const currentCoords = {
                        longitude: params.coords.longitude,
                        latitude: params.coords.latitude,
                    };
                    setUserLocation(currentCoords);
                }, (error) => {
                    if (ignore) {
                        return;
                    }
                    if (error?.code !== GeolocationErrorCode.PERMISSION_DENIED) {
                        // Let the next focus retry the fetch instead of being stuck on the fallback location forever
                        shouldInitializeCurrentPosition.current = true;
                    }
                    setCurrentPositionToInitialState(error);
                });

abbasifaizan70 avatar Jul 10 '26 02:07 abbasifaizan70

Proposal

What is the root cause of that problem?

The IOURequestStepDistanceManual component, which is responsible for displaying the manual distance map, fails to consistently show the user's current location after a sign-out and subsequent sign-in. This occurs because the component, or a sub-component it renders, does not reliably re-fetch or persist the user's last known location across session resets. When the app session is reset, the map component's initialization logic defaults to a hardcoded location (San Francisco) because it does not have access to a persistently stored last known location. Although the provided snippet for IOURequestStepDistanceManual shows extensive use of Onyx for various data, there is no explicit Onyx key or mechanism to store and retrieve the map's last known good coordinates, leading to the fallback default being used instead of the actual current location.

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

  1. Introduce an Onyx key for last known location: Define a new Onyx key, for example, ONYXKEYS.LAST_KNOWN_LOCATION, to store the user's last successfully retrieved geographic coordinates. This key would hold an object like {latitude: number, longitude: number}.

  2. Update and persist location in IOURequestStepDistanceManual: Within the IOURequestStepDistanceManual component, implement logic to fetch the current device location when the component mounts or becomes active. Upon successful retrieval of the current location, update the ONYXKEYS.LAST_KNOWN_LOCATION with these coordinates using Onyx.set(). This ensures that the most recent valid location is always available in persistent storage.

    https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/pages/iou/request/step/IOURequestStepDistanceManual.tsx#L65-L144

    // Inside IOURequestStepDistanceManual, after other Onyx hooks
    const [lastKnownLocation] = useOnyx(ONYXKEYS.LAST_KNOWN_LOCATION);
    
    useEffect(() => {
        // This is a placeholder for the actual location fetching utility call
        // e.g., LocationUtils.getCurrentPosition().then((position) => { ... });
        const fetchAndStoreLocation = async () => {
            try {
                // Assume a utility exists to get current position
                const position = await someLocationUtility.getCurrentPosition();
                const {latitude, longitude} = position.coords;
                Onyx.set(ONYXKEYS.LAST_KNOWN_LOCATION, {latitude, longitude});
            } catch (error) {
                console.error('Failed to get current location:', error);
            }
        };
    
        fetchAndStoreLocation();
    }, []); // Run once on mount to get initial location
    

    This step ensures that the user's current location is fetched and stored in Onyx, making it available across sessions.

  3. Prioritize Onyx-stored location for map initialization: Modify the map component's initialization logic within IOURequestStepDistanceManual to first check the lastKnownLocation from Onyx. If lastKnownLocation is available, use its coordinates to set the map's initial view. The hardcoded San Francisco default should only be used as a last resort if no valid location can be retrieved from Onyx or a fresh fetch.

    https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/pages/iou/request/step/IOURequestStepDistanceManual.tsx#L65-L144

    // Inside IOURequestStepDistanceManual, where map's initial coordinates are determined
    const mapInitialCoordinates = lastKnownLocation
        ? {latitude: lastKnownLocation.latitude, longitude: lastKnownLocation.longitude}
        : CONST.DEFAULT_MAP_CENTER_SAN_FRANCISCO; // Assuming a constant for SF default
    
    // Pass mapInitialCoordinates to the map rendering component
    // e.g., <DistanceMapView initialCoordinates={mapInitialCoordinates} ... />
    

    This change ensures that the map initializes with the last known good location from Onyx, preventing it from defaulting to San Francisco after re-login.

What alternative solutions did you explore? (Optional)

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

samranahm avatar Jul 10 '26 02:07 samranahm

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

melvin-bot[bot] avatar Jul 10 '26 02:07 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022075404316054712715

melvin-bot[bot] avatar Jul 10 '26 02:07 melvin-bot[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-07-10 02:31:00 UTC.

Proposal

What is the root cause of that problem?

PR #95372 changed the native shared MapView so the current-location initialization now runs behind an async getForegroundPermissionsAsync() check with an ignore cleanup. The effect consumes shouldInitializeCurrentPosition.current before that async permission/location work finishes, and the cleanup makes any in-flight result return without calling setUserLocation().

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L101-L149

After sign-out, the normal sign-in redirect path clears Onyx with a preserve list that does not include ONYXKEYS.USER_LOCATION, so the next manual distance map open has no cached current location and must complete that one initialization to avoid the fallback.

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/libs/actions/SignInRedirect.ts#L49-L63 https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/libs/actions/SignInRedirect.ts#L95-L99

For a new manual distance request there are no waypoint coordinates yet, and DistanceRequestFooter passes an inline initialState whose location falls back to CONST.MAPBOX.DEFAULT_COORDINATE. That constant is San Francisco.

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/DistanceRequest/DistanceRequestFooter.tsx#L67-L85 https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/DistanceRequest/DistanceRequestFooter.tsx#L102-L118 https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/CONST/index.ts#L6042-L6047

Right after signing back in, the distance map is still hydrating and re-rendering. Because DistanceRequestFooter rebuilds waypoints and initialState, the native MapView focus-effect callback can be torn down while getForegroundPermissionsAsync() or getCurrentPosition() is still in flight. The previous cleanup sets ignore = true, the re-run immediately exits because the one-shot guard was already consumed, and no later attempt repopulates USER_LOCATION. currentPosition therefore remains userLocation ?? initialLocation, which is the San Francisco fallback.

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L69-L99 https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L120-L149

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

Keep the PR #95372 behavior that opening the map does not request OS permission, but make the native MapView current-location initialization retryable when the async permission/location read is cancelled.

In MapView.tsx, do not set shouldInitializeCurrentPosition.current = false before the async permission read can produce a non-ignored result. Consume that guard only when we intentionally handle the result: after a non-ignored permission response proceeds to getCurrentPosition(), after a real denied-permission fallback, or when the map cannot pan to current location because waypoints/user interaction make that inappropriate. If the focus-effect cleanup runs first and marks the current async branch ignored, leave or restore the guard so the next focused render can retry. Add a .catch() for getForegroundPermissionsAsync() that also leaves the guard retryable.

This preserves the no-prompt gate because the map still starts with getForegroundPermissionsAsync() and only calls getCurrentPosition() after permission is already granted. It also preserves the intended fallback for truly denied permissions by clearing USER_LOCATION only from an active, non-ignored denial path. The change belongs in shared native MapView, because callers such as confirmed route previews already opt out with shouldDisplayCurrentLocation={false} and should not start using the device location.

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/ConfirmedRoute.tsx#L89-L105

Test coverage:

  • Add a native MapView unit test/mock where USER_LOCATION is empty, there are no waypoints, initialState.location is CONST.MAPBOX.DEFAULT_COORDINATE, and the first focused effect is cleaned up before getForegroundPermissionsAsync() resolves. Assert that the next focused render retries and calls setUserLocation() with the mocked device coordinates.
  • Add a denied-permission test proving the guard is consumed and the map falls back to initialState without looping or requesting permission.
  • Add Android/iOS regression QA: allow location while using the app, open the distance Map tab, sign out, sign back in with the same account, and reopen the Map tab. It should center on the device location, not San Francisco.

What alternative solutions did you explore? (Optional)

I considered preserving ONYXKEYS.USER_LOCATION across sign-out, but that can carry a stale location into a new session and still would not fix the native map's lost initialization. I also considered changing DistanceRequestFooter to avoid the San Francisco default when there are no waypoints, but the shared native MapView would still be unable to recover whenever its one-shot current-location read is cancelled.

KJ21-ENG avatar Jul 10 '26 02:07 KJ21-ENG

Proposal [Updated]

Updated my proposal above with a more complete root-cause analysis and the full set of affected call sites.

ahmdshrif avatar Jul 10 '26 02:07 ahmdshrif

Proposal

What is the root cause of that problem?

The manual distance map on native renders its center from ONYXKEYS.USER_LOCATION when available, otherwise it falls back to the initialState location (currentPosition = userLocation ?? initialLocation) in MapView (https://github.com/Expensify/App/blob/main/src/components/MapView/MapView.tsx#L60-L72). For the distance map with no waypoints, DistanceRequestFooter passes CONST.MAPBOX.DEFAULT_COORDINATE as that initial location (https://github.com/Expensify/App/blob/main/src/components/DistanceRequest/DistanceRequestFooter.tsx#L102-L110), and that default coordinate is San Francisco (https://github.com/Expensify/App/blob/main/src/CONST/index.ts#L6003-L6008).

After sign-out/sign-in, Onyx is cleared during the sign-in redirect flow (https://github.com/Expensify/App/blob/main/src/libs/actions/SignInRedirect.ts#L95-L114), so the cached USER_LOCATION value is lost. However, the native MapView only attempts to initialize the current position once per mounted component via shouldInitializeCurrentPosition; it sets that ref to false before checking foreground permission and reading the device location (https://github.com/Expensify/App/blob/main/src/components/MapView/MapView.tsx#L101-L149). If the map component survives the auth transition or the first post-login focus runs while USER_LOCATION is empty, that one-shot guard prevents another location read, so the map stays on the fallback San Francisco coordinate even though foreground location permission is still granted.

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

Make native MapView re-initialize the current location whenever the cached USER_LOCATION source of truth has been cleared and the map is focused, instead of treating current-position initialization as a permanent one-time action for the component lifetime.

Concretely, replace the current shouldInitializeCurrentPosition behavior with a retryable/in-flight guard. The focus effect should still avoid requesting OS permission directly and should continue using getForegroundPermissionsAsync() before calling getCurrentPosition(), but it should only skip initialization when a current-position request is already in flight or when there is already a cached userLocation. When userLocation becomes null/undefined after Onyx.clear(), the next focused map render should be allowed to check the already-granted permission and call getCurrentPosition() again, then store the result with setUserLocation().

This keeps the intent from the previous fix: opening the manual map must not trigger a location permission prompt when permission has not already been granted. But it also makes the map resilient to auth/session transitions that clear Onyx while leaving the native map component or route state alive.

What alternative solutions did you explore? (Optional)

I considered changing DistanceRequestFooter to pass a different fallback coordinate, but that would only hide the symptom and would still leave MapView unable to recover after USER_LOCATION is cleared. I also considered preserving USER_LOCATION across sign-out, but location is user/session-scoped data, so the safer fix is to let the map reacquire it when permission is already granted.

x-dev90 avatar Jul 10 '26 02:07 x-dev90

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

yusufdeveloper2903 avatar Jul 10 '26 02:07 yusufdeveloper2903

⚠️ @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.

github-actions[bot] avatar Jul 10 '26 02:07 github-actions[bot]

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

trasnake87 avatar Jul 10 '26 02:07 trasnake87

⚠️ @trasnake87 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.

github-actions[bot] avatar Jul 10 '26 02:07 github-actions[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-07-10 02:44:23 UTC.

Proposal

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

On native (Android and iOS), the Manual Distance Map centers on the San Francisco default coordinate instead of the device's current location after the user signs out and signs back in with the same account, even though the foreground location permission is still granted.

What is the root cause of that problem?

This is a regression from PR #95372, which replaced a synchronous getCurrentPosition call in the native MapView focus effect with a two-step asynchronous chain: getForegroundPermissionsAsync() resolves first, and only then does getCurrentPosition run. The same commit added a cleanup function that flips an ignore flag to discard whatever is still in flight.

The problem is that the one-shot latch which guards this work, shouldInitializeCurrentPosition, is consumed at the start of the attempt rather than when the attempt finishes:

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L107-L121

The cleanup that cancels the in-flight read is here:

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L146-L148

So if the focus effect re-runs at any point between "latch flipped" and "permission promise resolved", the cleanup sets ignore = true, the resolved promise returns early, getCurrentPosition is never called, and setUserLocation never fires. The re-run itself then hits the !shouldInitializeCurrentPosition.current early return, so nothing ever retries. The location read is lost permanently for that component instance.

The focus effect re-runs easily, because everything in its dependency list — isOffline, shouldPanMapToCurrentPosition, setCurrentPositionToInitialState — can change in the moments right after the map mounts:

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L86-L99

isOffline settles from its initial value shortly after sign-in while the network state rehydrates. shouldPanMapToCurrentPosition is memoized on the waypoints prop, whose array identity changes once the lazily-loaded map-marker icon chunk resolves and useMapMarkers returns a new getMapMarkerIconComponent. And navigating away from the screen and back re-focuses it, which tears the effect down by definition.

Any of these causes useFocusEffect to tear down and re-run the effect within the few tens of milliseconds that the native getForegroundPermissionsAsync bridge call takes to resolve — which is exactly the window that loses the read.

Why this only shows up after signing out and back in: userLocation is persisted in Onyx, and the map falls back to initialState only when it is missing:

https://github.com/Expensify/App/blob/7e966b4a322864cf3addd3b4eff0f8ef55a84454/src/components/MapView/MapView.tsx#L60-L70

On a normal open, a previously cached userLocation centers the map correctly and masks the aborted read. Signing out clears Onyx, so after signing back in there is no cached value left, the aborted read is fully exposed, and currentPosition falls through to initialLocation, which for a distance request with no waypoints yet is CONST.MAPBOX.DEFAULT_COORDINATE — San Francisco.

This also explains why the bug reproduces in staging but not production: PR #95372 has not shipped to production yet.

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

The fix is to make the latch record completion rather than attempt, so an aborted read is retried instead of silently swallowed.

In src/components/MapView/MapView.tsx, stop setting shouldInitializeCurrentPosition.current = false before the asynchronous work begins. Instead, mark the initialization as done only once the read has actually settled — that is, inside the success path after setUserLocation is called, and inside the permission-denied path after the map has been pointed back at initialState. If the effect's cleanup runs while the read is still in flight, leave the latch untouched (or restore it to its un-consumed value) so that the next run of the focus effect starts the read again. The ignore flag stays exactly as it is: its job is to prevent a state update from a stale effect run, and it should keep doing only that.

With that change, the sequence becomes: the effect starts the permission read, a parent re-render tears the effect down mid-flight, the stale promise resolves and is correctly ignored, and the freshly re-run effect — seeing the latch still un-consumed — issues the read again. The second read completes, setUserLocation writes the real coordinates to Onyx, and the camera pans to the user's location. The map never has to fall back to the default coordinate while permission is granted.

The same guard should be applied to the error callback passed to getCurrentPosition, which today runs unconditionally: it should ignore a stale run just like the success callback does, and mark the initialization done when it fires for a live one. That keeps a failed read from being retried on every subsequent render while still letting a cancelled read be retried.

Nothing needs to change at the call sites. It is tempting to also memoize the initialState object literal that DistanceRequestFooter passes, but babel-plugin-react-compiler runs over src/ and already auto-memoizes it, so that would be a no-op. Stabilizing the remaining dependencies would not be sufficient either — isOffline can still flip while the network state rehydrates after sign-in, and re-focusing the screen tears the effect down no matter how stable its dependencies are. The latch simply has to tolerate a cancelled read.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/95774-map-current-position-latch?expand=1

What alternative solutions did you explore? (Optional)

Revert the cleanup added by #95372 and let the in-flight getCurrentPosition callback run to completion the way the pre-regression code did. This restores the old behaviour and fixes the symptom, but it reintroduces the "set state on an unmounted / stale effect" hazard that the ignore flag was added to close, so it trades one defect for another.

Keep consuming the latch at the start of the attempt, and re-arm it from the effect's cleanup whenever the read has not settled yet. This ends up behaviourally equivalent to the proposed fix, but it splits a single decision across the effect body and its cleanup, and it needs a second ref to tell "still in flight" from "already finished" — more moving state for no extra safety.

Stop the effect from tearing down in the first place, by removing isOffline from the dependency list and reading it from a ref instead. This removes one trigger, but it leaves the underlying "consume the latch before the work finishes" defect in place, and it cannot help at all when the teardown comes from the screen genuinely losing focus.

Drop the shouldInitializeCurrentPosition latch entirely and instead skip the read when userLocation is already present in Onyx. This is closer to the real intent ("read the device position once, unless we already know it"), but it changes behaviour for a user who has physically moved since the cached value was written, so it is a larger behavioural change than this regression warrants.

wildan-m avatar Jul 10 '26 02:07 wildan-m

⚠️ @wildan-m 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.

github-actions[bot] avatar Jul 10 '26 02:07 github-actions[bot]

Updated my proposal.

What changed: Updated the proposal to focus on the cancelled one-shot location initialization after sign-in.

Why: This better explains why an already-granted location permission can still leave the manual map on San Francisco.

KJ21-ENG avatar Jul 10 '26 02:07 KJ21-ENG