Skip to content

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

Closed

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.4.32-0
Reproducible in staging?: Yes
Reproducible in production?: No (Update: Yes)
If this was caught during regression testing, add the test name, ID and link from BrowserStack: #95372
Email or phone of affected tester (no customers): testing210790@gmail.com
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:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

Bug7203915_1783626730569.WhatsApp_Video_2026-07-09_at_11.34.01_AM__1_.mp4

View all open jobs on GitHub

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

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @DylanDylann

Activity

  1. added
    Daily
    Bug
    on Jul 10, 2026
  2. applause-bot commented on Jul 10, 2026

    @applause-bot
    Author

    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

  3. MelvinBot commented on Jul 10, 2026

    @MelvinBot
    Contributor

    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)

    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.

  4. added
    External
    on Jul 10, 2026
  5. added
    Help Wanted
    on Jul 10, 2026
  6. MobileMage commented on Jul 10, 2026

    @MobileMage
    Contributor

    🚨 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:

    const initialLocation = useMemo(() => initialState && {longitude: initialState.location[0], latitude: initialState.location[1]}, [initialState]);
    const currentPosition = userLocation ?? initialLocation;

    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:

    let ignore = false;
    getForegroundPermissionsAsync().then(({granted}) => {
    if (ignore) {
    return;
    }

    The effect returns a cleanup that sets ignore = true:

    return () => {
    ignore = true;
    };

    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.

  7. aswin-s commented on Jul 10, 2026

    @aswin-s
    Contributor

    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)

  8. shivang-goliyan commented on Jul 10, 2026

    @shivang-goliyan
    Contributor

    🚨 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.

  9. ahmdshrif commented on Jul 10, 2026

    @ahmdshrif
    Contributor

    🚨 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 —
      if (!shouldInitializeCurrentPosition.current) {
      return;
      }
      shouldInitializeCurrentPosition.current = false;
    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 —
      let ignore = false;
      getForegroundPermissionsAsync().then(({granted}) => {
      if (ignore) {
      return;
      }
      if (!granted) {
      // Pass the permission-denied error so any stale cached location is cleared and the map falls back to initialState.
      setCurrentPositionToInitialState({
      code: GeolocationErrorCode.PERMISSION_DENIED,
      message: 'User denied access to location.',
      });
      return;
      }
      getCurrentPosition((params) => {
      if (ignore) {
      return;
      }
      const currentCoords = {
      longitude: params.coords.longitude,
      latitude: params.coords.latitude,
      };
      setUserLocation(currentCoords);
      }, setCurrentPositionToInitialState);
      });
      return () => {
      ignore = true;
      };
    3. The in-flight window is seconds long: native getCurrentPosition awaits the permission request and a fresh GPS fix —
      const getCurrentPosition: GetCurrentPosition = async (success, error, options) => {
      const foregroundPermissionResponse: PermissionResponse = await requestForegroundPermissionsAsync();
      if (foregroundPermissionResponse.status !== PermissionStatus.GRANTED) {
      error({code: GeolocationErrorCode.PERMISSION_DENIED, message: 'User denied access to location.'});
      return;
      }
      try {
      const currentPosition = await getCurrentPositionAsync(options);
      success(currentPosition);
      } catch (caughtError) {
      const geolocationError = getGeolocationError(caughtError);
      error(geolocationError);
      }
      };
    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) —
      }, [isOffline, shouldPanMapToCurrentPosition, setCurrentPositionToInitialState]),
      — and initialState/waypoints are rebuilt from the draft transaction in DistanceRequestFooter —
      <DistanceMapView
      accessToken={mapboxAccessToken?.token ?? ''}
      mapPadding={CONST.MAPBOX.PADDING}
      pitchEnabled={false}
      initialState={{
      zoom: CONST.MAPBOX.DEFAULT_ZOOM,
      location: waypointMarkers?.at(0)?.coordinate ?? CONST.MAPBOX.DEFAULT_COORDINATE,
      }}
      directionCoordinates={(transaction?.routes?.route0?.geometry?.coordinates as Array<[number, number]>) ?? []}
      style={[styles.mapView, styles.mapEditView]}
      waypoints={waypointMarkers}
      styleURL={CONST.MAPBOX.STYLE_URL}
      overlayStyle={styles.mapEditView}
      distanceInMeters={getDistanceInMeters(transaction, undefined)}
      unit={unit}
      />
    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 —
      const keysToPreserve: OnyxKey[] = [];
      keysToPreserve.push(ONYXKEYS.NVP_PREFERRED_LOCALE);
      keysToPreserve.push(ONYXKEYS.RAM_ONLY_ARE_TRANSLATIONS_LOADING);
      keysToPreserve.push(ONYXKEYS.PREFERRED_THEME);
      keysToPreserve.push(ONYXKEYS.NVP_SEARCH_SIDEBAR);
      keysToPreserve.push(ONYXKEYS.ACTIVE_CLIENTS);
      keysToPreserve.push(ONYXKEYS.DEVICE_ID);
      keysToPreserve.push(ONYXKEYS.SHOULD_USE_STAGING_SERVER);
      keysToPreserve.push(ONYXKEYS.IS_DEBUG_MODE_ENABLED);
      keysToPreserve.push(ONYXKEYS.COLLECTION.PASSKEY_CREDENTIALS);
      ), so currentPosition = userLocation ?? initialLocation falls back to CONST.MAPBOX.DEFAULT_COORDINATE (San Francisco) —
      const initialLocation = useMemo(() => initialState && {longitude: initialState.location[0], latitude: initialState.location[1]}, [initialState]);
      const currentPosition = userLocation ?? initialLocation;
      ,
      DEFAULT_COORDINATE: [-122.4021, 37.7911] as [number, number],

    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 —

    useFocusEffect(
    useCallback(() => {
    if (isOffline) {
    return;
    }
    if (!shouldInitializeCurrentPosition.current) {
    return;
    }
    shouldInitializeCurrentPosition.current = false;
    if (!shouldPanMapToCurrentPosition()) {
    setCurrentPositionToInitialState();
    return;
    }
    getCurrentPosition((params) => {
    const currentCoords = {longitude: params.coords.longitude, latitude: params.coords.latitude};
    setUserLocation(currentCoords);
    }, setCurrentPositionToInitialState);
    }, [isOffline, shouldPanMapToCurrentPosition, setCurrentPositionToInitialState]),
    );
    ), 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) —

    // Check (never request) foreground location permissions to determine if we can use the followUserLocation prop on the map camera.
    // Requesting here would trigger an OS prompt on open without a prior explicit user action, so we only read the current status.
    useFocusEffect(() => {
    if (isOffline) {
    return;
    }
    let ignore = false;
    getForegroundPermissionsAsync().then(({granted}) => {
    if (ignore) {
    return;
    }
    setForegroundLocationPermissionsGranted(granted);
    });
    return () => {
    ignore = true;
    };
    });

    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

    shouldInitializeCurrentPosition.current = false;
    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.
  10. abbasifaizan70 commented on Jul 10, 2026

    @abbasifaizan70
    Contributor

    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:

    DEFAULT_COORDINATE: [-122.4021, 37.7911] as [number, number],

    const [userLocation] = useOnyx(ONYXKEYS.USER_LOCATION);
    const navigation = useNavigation();
    const {isOffline} = useNetwork();
    const {translate} = useLocalize();
    const styles = useThemeStyles();
    const theme = useTheme();
    const expensifyIcons = useMemoizedLazyExpensifyIcons(['Crosshair', 'MapCurrentLocation']);
    const cameraRef = useRef<Mapbox.Camera>(null);
    const [isIdle, setIsIdle] = useState(false);
    const initialLocation = useMemo(() => initialState && {longitude: initialState.location[0], latitude: initialState.location[1]}, [initialState]);
    const currentPosition = userLocation ?? initialLocation;

    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:

    useFocusEffect(
    useCallback(() => {
    if (isOffline) {
    return;
    }
    if (!shouldInitializeCurrentPosition.current) {
    return;
    }
    shouldInitializeCurrentPosition.current = false;
    if (!shouldPanMapToCurrentPosition()) {
    setCurrentPositionToInitialState();
    return;
    }
    // Only read the device location when permission is ALREADY granted. We never request it here,
    // so opening the map cannot trigger an OS permission prompt without a prior explicit user action.
    let ignore = false;
    getForegroundPermissionsAsync().then(({granted}) => {
    if (ignore) {
    return;
    }
    if (!granted) {
    // Pass the permission-denied error so any stale cached location is cleared and the map falls back to initialState.
    setCurrentPositionToInitialState({
    code: GeolocationErrorCode.PERMISSION_DENIED,
    message: 'User denied access to location.',
    });
    return;
    }
    getCurrentPosition((params) => {
    if (ignore) {
    return;
    }
    const currentCoords = {
    longitude: params.coords.longitude,
    latitude: params.coords.latitude,
    };
    setUserLocation(currentCoords);
    }, setCurrentPositionToInitialState);
    });
    return () => {
    ignore = true;
    };
    }, [isOffline, shouldPanMapToCurrentPosition, setCurrentPositionToInitialState]),
    );

    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:

    const getCurrentPosition: GetCurrentPosition = async (success, error, options) => {
    const foregroundPermissionResponse: PermissionResponse = await requestForegroundPermissionsAsync();
    if (foregroundPermissionResponse.status !== PermissionStatus.GRANTED) {
    error({code: GeolocationErrorCode.PERMISSION_DENIED, message: 'User denied access to location.'});
    return;
    }
    try {
    const currentPosition = await getCurrentPositionAsync(options);
    success(currentPosition);
    } catch (caughtError) {
    const geolocationError = getGeolocationError(caughtError);
    error(geolocationError);
    }
    };

    That error callback, setCurrentPositionToInitialState, only takes action for PERMISSION_DENIED errors and silently no-ops for anything else:

    const setCurrentPositionToInitialState: GeolocationErrorCallback = useCallback(
    (error) => {
    if (error?.code !== GeolocationErrorCode.PERMISSION_DENIED || !initialLocation) {
    return;
    }
    clearUserLocation();
    },
    [initialLocation],
    );

    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);

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

                    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);
                    });
  11. samranahm commented on Jul 10, 2026

    @samranahm
    Contributor

    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.

      function IOURequestStepDistanceManual({
      report,
      route: {
      params: {action, iouType, reportID, transactionID, backTo, backToReport},
      },
      transaction,
      currentUserPersonalDetails,
      }: IOURequestStepDistanceManualProps) {
      const {translate} = useLocalize();
      const styles = useThemeStyles();
      const {isBetaEnabled} = usePermissions();
      const {isExtraSmallScreenHeight} = useResponsiveLayout();
      const isArchived = useReportIsArchived(report?.reportID);
      const selfDMReport = useSelfDMReport();
      const {policy} = usePolicyForTransaction({
      reportPolicyID: report?.policyID,
      action,
      iouType,
      transaction,
      });
      const personalPolicy = usePersonalPolicy();
      const defaultExpensePolicy = useDefaultExpensePolicy();
      const {policyForMovingExpenses} = usePolicyForMovingExpenses();
      const reportAttributesDerived = useReportAttributes();
      const [selectedTab] = useOnyx(`${ONYXKEYS.COLLECTION.SELECTED_TAB}${CONST.TAB.DISTANCE_REQUEST_TYPE}`);
      const distanceOriginalPolicy = useDistanceRateOriginalPolicy(transaction?.comment?.customUnit?.customUnitRateID);
      const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policy?.id}`);
      const [policyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policy?.id}`);
      const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST);
      const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED);
      const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END);
      const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END);
      const [skipConfirmation] = useOnyx(`${ONYXKEYS.COLLECTION.SKIP_CONFIRMATION}${transactionID}`);
      const [lastSelectedDistanceRates] = useOnyx(ONYXKEYS.NVP_LAST_SELECTED_DISTANCE_RATES);
      const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
      const [quickAction] = useOnyx(ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE);
      const [policyRecentlyUsedCurrencies] = useOnyx(ONYXKEYS.RECENTLY_USED_CURRENCIES);
      const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
      const [parentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(report?.parentReportID)}`);
      const [parentReportNextStep] = useOnyx(`${ONYXKEYS.COLLECTION.NEXT_STEP}${getNonEmptyStringOnyxID(report?.parentReportID)}`);
      const [betas] = useOnyx(ONYXKEYS.BETAS);
      const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {
      selector: validTransactionDraftIDsSelector,
      });
      const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {
      selector: hasSeenTourSelector,
      });
      const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID);
      const [splitDraftTransaction] = useOnyx(`${ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT}${transactionID}`);
      const [recentWaypoints] = useOnyx(ONYXKEYS.NVP_RECENT_WAYPOINTS);
      const reportIDToCheck = isMoneyRequestReportReportUtils(report) ? report?.chatReportID : report?.reportID;
      const [reportDraft] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_DRAFT}${reportIDToCheck}`);
      const textInput = useRef<BaseTextInputRef | null>(null);
      const numberFormRef = useRef<NumberWithSymbolFormRef | null>(null);
      const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);
      const [formError, setFormError] = useState<string>('');
      const isEditing = action === CONST.IOU.ACTION.EDIT;
      const isEditingSplit = (iouType === CONST.IOU.TYPE.SPLIT || iouType === CONST.IOU.TYPE.SPLIT_EXPENSE) && isEditing;
      const isCreatingNewRequest = !(backTo || isEditing);
      const isTransactionDraft = shouldUseTransactionDraft(action, iouType);
      const currentUserAccountIDParam = currentUserPersonalDetails.accountID;
      const currentUserEmailParam = currentUserPersonalDetails.login ?? '';
      const delegateAccountID = useDelegateAccountID();
      const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT);
      const shouldUseDefaultExpensePolicy = shouldUseDefaultExpensePolicyUtil(
      iouType,
      defaultExpensePolicy,
      amountOwed,
      userBillingGracePeriodEnds,
      ownerBillingGracePeriodEnd,
      currentUserAccountIDParam,
      );
      // to make sure the correct distance amount and unit will be shown we use distance unit
      // from defaultExpensePolicy or current report's policy instead of from transaction and
      // then we use transaction data (distanceUnit and quantity) for conversions

      // 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.

      function IOURequestStepDistanceManual({
      report,
      route: {
      params: {action, iouType, reportID, transactionID, backTo, backToReport},
      },
      transaction,
      currentUserPersonalDetails,
      }: IOURequestStepDistanceManualProps) {
      const {translate} = useLocalize();
      const styles = useThemeStyles();
      const {isBetaEnabled} = usePermissions();
      const {isExtraSmallScreenHeight} = useResponsiveLayout();
      const isArchived = useReportIsArchived(report?.reportID);
      const selfDMReport = useSelfDMReport();
      const {policy} = usePolicyForTransaction({
      reportPolicyID: report?.policyID,
      action,
      iouType,
      transaction,
      });
      const personalPolicy = usePersonalPolicy();
      const defaultExpensePolicy = useDefaultExpensePolicy();
      const {policyForMovingExpenses} = usePolicyForMovingExpenses();
      const reportAttributesDerived = useReportAttributes();
      const [selectedTab] = useOnyx(`${ONYXKEYS.COLLECTION.SELECTED_TAB}${CONST.TAB.DISTANCE_REQUEST_TYPE}`);
      const distanceOriginalPolicy = useDistanceRateOriginalPolicy(transaction?.comment?.customUnit?.customUnitRateID);
      const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policy?.id}`);
      const [policyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policy?.id}`);
      const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST);
      const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED);
      const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END);
      const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END);
      const [skipConfirmation] = useOnyx(`${ONYXKEYS.COLLECTION.SKIP_CONFIRMATION}${transactionID}`);
      const [lastSelectedDistanceRates] = useOnyx(ONYXKEYS.NVP_LAST_SELECTED_DISTANCE_RATES);
      const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
      const [quickAction] = useOnyx(ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE);
      const [policyRecentlyUsedCurrencies] = useOnyx(ONYXKEYS.RECENTLY_USED_CURRENCIES);
      const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
      const [parentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(report?.parentReportID)}`);
      const [parentReportNextStep] = useOnyx(`${ONYXKEYS.COLLECTION.NEXT_STEP}${getNonEmptyStringOnyxID(report?.parentReportID)}`);
      const [betas] = useOnyx(ONYXKEYS.BETAS);
      const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {
      selector: validTransactionDraftIDsSelector,
      });
      const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {
      selector: hasSeenTourSelector,
      });
      const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID);
      const [splitDraftTransaction] = useOnyx(`${ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT}${transactionID}`);
      const [recentWaypoints] = useOnyx(ONYXKEYS.NVP_RECENT_WAYPOINTS);
      const reportIDToCheck = isMoneyRequestReportReportUtils(report) ? report?.chatReportID : report?.reportID;
      const [reportDraft] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_DRAFT}${reportIDToCheck}`);
      const textInput = useRef<BaseTextInputRef | null>(null);
      const numberFormRef = useRef<NumberWithSymbolFormRef | null>(null);
      const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);
      const [formError, setFormError] = useState<string>('');
      const isEditing = action === CONST.IOU.ACTION.EDIT;
      const isEditingSplit = (iouType === CONST.IOU.TYPE.SPLIT || iouType === CONST.IOU.TYPE.SPLIT_EXPENSE) && isEditing;
      const isCreatingNewRequest = !(backTo || isEditing);
      const isTransactionDraft = shouldUseTransactionDraft(action, iouType);
      const currentUserAccountIDParam = currentUserPersonalDetails.accountID;
      const currentUserEmailParam = currentUserPersonalDetails.login ?? '';
      const delegateAccountID = useDelegateAccountID();
      const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT);
      const shouldUseDefaultExpensePolicy = shouldUseDefaultExpensePolicyUtil(
      iouType,
      defaultExpensePolicy,
      amountOwed,
      userBillingGracePeriodEnds,
      ownerBillingGracePeriodEnd,
      currentUserAccountIDParam,
      );
      // to make sure the correct distance amount and unit will be shown we use distance unit
      // from defaultExpensePolicy or current report's policy instead of from transaction and
      // then we use transaction data (distanceUnit and quantity) for conversions

      // 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.

  12. melvin-bot commented on Jul 10, 2026

    @melvin-bot

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

  13. 19 remaining items

  14. pvaghasiya087-has commented on Jul 10, 2026

    @pvaghasiya087-has

    Proposal

    What is the root cause of that problem?

    The issue happens because MapView falls back to the default map coordinate when USER_LOCATION is unavailable after a fresh login.

    The current position selection logic in src/components/MapView/MapView.tsx is:

    const currentPosition = userLocation ?? initialLocation;

    userLocation comes from ONYXKEYS.USER_LOCATION. When the user signs out, this Onyx value is cleared. After signing back in, userLocation is empty, so the map uses initialLocation.

    const [userLocation] = useOnyx(ONYXKEYS.USER_LOCATION);

    For Manual Distance Map, that fallback is created from:

    location: waypointMarkers?.at(0)?.coordinate ?? CONST.MAPBOX.DEFAULT_COORDINATE,

    which points to San Francisco.

    The expected behavior depends on the map calling getCurrentPosition() and saving the result through setUserLocation(), but the current implementation only attempts this during the initial focus lifecycle.

    The relevant flow in MapView.tsx currently looks like:

    const shouldInitializeCurrentPosition = useRef(true);

    useFocusEffect(
    useCallback(() => {
    if (isOffline) {
    return;
    }
    if (!shouldInitializeCurrentPosition.current) {
    return;
    }
    shouldInitializeCurrentPosition.current = false;
    if (!shouldPanMapToCurrentPosition()) {
    setCurrentPositionToInitialState();
    return;
    }
    // Only read the device location when permission is ALREADY granted. We never request it here,
    // so opening the map cannot trigger an OS permission prompt without a prior explicit user action.
    let ignore = false;
    getForegroundPermissionsAsync().then(({granted}) => {
    if (ignore) {
    return;
    }
    if (!granted) {
    // Pass the permission-denied error so any stale cached location is cleared and the map falls back to initialState.
    setCurrentPositionToInitialState({
    code: GeolocationErrorCode.PERMISSION_DENIED,
    message: 'User denied access to location.',
    });
    return;
    }
    getCurrentPosition((params) => {
    if (ignore) {
    return;
    }
    const currentCoords = {
    longitude: params.coords.longitude,
    latitude: params.coords.latitude,
    };
    setUserLocation(currentCoords);
    }, setCurrentPositionToInitialState);
    });

    The problem is that the initialization attempt can happen during the login transition when session data and native location state are still being restored.

    If that first attempt does not update USER_LOCATION, the ref has already changed:

    shouldInitializeCurrentPosition.current = false;

    Future focus events skip the location refresh completely.

    Therefore:

    1. Sign out clears USER_LOCATION.
    2. Sign in recreates the session.
    3. Map opens with no stored location.
    4. First location initialization misses during lifecycle transition.
    5. One-time guard prevents another attempt.
    6. Map remains centered on San Francisco.

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

    Instead of tying location synchronization to a single initialization attempt, make the location refresh depend on the actual state requirement:

    If the map has no user location and permission is available, synchronize the location.

    This keeps the existing permission behavior from PR #95372 (no automatic permission prompt), while making the location recovery reliable.

    1. Replace the one-time initialization guard

    Remove:

    const shouldInitializeCurrentPosition = useRef(true);

    and the early return:

    if (!shouldInitializeCurrentPosition.current) {
    return;
    }
    shouldInitializeCurrentPosition.current = false;

    The map should not permanently disable location recovery after one failed attempt.


    2. Add a reusable location synchronization function

    Inside MapView.tsx, add:

    const syncCurrentLocation = useCallback(async () => {
        const {granted} = await getForegroundPermissionsAsync();
    
        if (!granted) {
            return;
        }
    
        getCurrentPosition(
            ({coords}) => {
                setUserLocation({
                    latitude: coords.latitude,
                    longitude: coords.longitude,
                });
            },
            () => {
                // Keep current fallback behavior when location cannot be fetched.
            },
        );
    }, []);

    This keeps the important behavior:

    • Does not request permission.
    • Uses existing native permission state.
    • Updates Onyx only after a successful location result.

    3. Run synchronization when the map needs a location

    Update the focus effect:

    useFocusEffect(
        useCallback(() => {
            if (!userLocation) {
                syncCurrentLocation();
            }
        }, [syncCurrentLocation, userLocation]),
    );

    Now the flow becomes:

    • Existing location available → keep current map position.
    • Location missing after logout/login → fetch current location.
    • Fetch succeeds → update USER_LOCATION.
    • Map moves away from the San Francisco fallback.

    4. Add app foreground synchronization

    The same logic should run when the app returns to the foreground because location permission or native services can change while the app is inactive.

    Reuse the same helper:

    useAppFocusEvent(() => {
        if (!userLocation) {
            syncCurrentLocation();
        }
    });

    GPSMapView.tsx already follows a similar lifecycle approach, so this makes MapView consistent with the existing location handling pattern.


    Testing changes

    Add a regression test in the MapView test suite covering:

    Case 1: Sign out → sign in → open Manual Distance Map

    Mock:

    USER_LOCATION = undefined
    getForegroundPermissionsAsync = {granted: true}
    getCurrentPosition = returns device coordinates

    Expected:

    setUserLocation({
        latitude: deviceLatitude,
        longitude: deviceLongitude,
    });

    should be called.

    The map should no longer use:

    CONST.MAPBOX.DEFAULT_COORDINATE

    Case 2: Permission denied

    Mock:

    getForegroundPermissionsAsync = {granted: false}

    Expected:

    • No permission prompt.
    • No location request.
    • Existing fallback behavior remains.

    Case 3: Existing user location

    Mock:

    USER_LOCATION = {
        latitude: 10,
        longitude: 20,
    }

    Expected:

    • Do not fetch a new location.
    • Do not move the map unexpectedly.

    Alternative solutions considered

    Preserve USER_LOCATION during logout

    This would avoid the empty state, but it would keep an old location instead of retrieving the current device position. It also risks carrying location data between different sessions.

    Remove the permission check completely

    This would restore the old behavior, but it would reintroduce the permission prompt regression that the previous PR was intended to fix.

    Only change the San Francisco fallback coordinate

    This would hide the symptom but would not solve the missing location synchronization problem.

    The safer fix is to make location restoration reliable after authentication changes while preserving the existing permission model.

  15. MuhammadAhmadKhan-2 commented on Jul 10, 2026

    @MuhammadAhmadKhan-2

    Proposal

    What is the root cause of that problem?

    The regression isn't simply caused by permission checks or the one-time initialization flag. The real issue is that location initialization has no lifecycle state. The map treats "started", "cancelled", "completed", and "failed" as the same state by consuming the initialization flag before the async permission/location flow finishes. After a sign-out/sign-in transition, any interrupted initialization leaves the component believing location has already been initialized, even though no valid location was ever obtained.

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

    Instead of relying on a boolean initialization ref, I'd introduce an explicit initialization state (idle → loading → completed → failed). The map should only transition to completed after successfully updating USER_LOCATION or after handling an actual permission denial. If initialization is cancelled because of navigation, focus changes, or component re-rendering, it should return to idle so the next focus retries automatically. This keeps the permission behavior introduced in #95372 while eliminating race conditions and making the initialization flow deterministic instead of timing-dependent.

    What alternative solutions did you explore? (Optional)

    I considered resetting the initialization flag or removing the cancellation logic entirely, but both approaches only address one race condition. A state-based lifecycle provides a single source of truth for location initialization, avoids duplicate requests, and prevents similar regressions if the permission or navigation flow changes again.

  16. FitseTLT commented on Jul 13, 2026

    @FitseTLT
    Contributor

    Asking question on the regressor pr

  17. added
    Reviewing
    Weekly
    and removed
    Daily
    on Jul 14, 2026
  18. removed
    Help Wanted
    on Jul 14, 2026
  19. melvin-bot commented on Aug 6, 2026

    @melvin-bot

    This issue has not been updated in over 15 days. @Julesssss, @FitseTLT, @DylanDylann eroding to Monthly issue.

    P.S. Is everyone reading this sure this is really a near-term priority? Be brave: if you disagree, go ahead and close it out. If someone disagrees, they'll reopen it, and if they don't: one less thing to do!

  20. DylanDylann commented on Aug 19, 2026

    @DylanDylann
    Contributor

    @Julesssss Let's close this issue

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

Metadata

Metadata

Labels

BugExternalMonthlyReviewing

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions