Skip to content

[Due for payment 2026-07-13] [$250] Safari - Spend - The LHN within the Spend tab is not remembered when navigating to Inbox #92460

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.3.97-0
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/test-runs/TR-37539/folder/13176922/43675713/1457880515?sort=%2Bidentifier
Email or phone of affected tester (no customers): n/a
Issue reported by: Applause Internal Team
Bug source: Regression TC Execution
Device used: Mac 15.4.1 Safari
App Component: Search

Action Performed:

  1. Go to https://staging.new.expensify.com
  2. Open the "Spend" tab
  3. Navigate to any item within the Reports LHN, for example, the "Drafts" section
  4. Navigate to the Inbox tab
  5. Navigate back to the "Spend" tab
  6. Navigate to any item within the Reports LHN, for example, the "Drafts" section
  7. Navigate back to the "Spend" tab

Expected Result:

After navigating to an item in the Spend LHN (e.g., "Drafts"), this new selection should be remembered.

Actual Result:

The LHN within the Spend tab is not remembered when navigating to Inbox

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

Bug7170081_1780451236713.111.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Mita Rachim
Bug ID: 7170081

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

Activity

  1. applause-bot commented on Jun 3, 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/1ab476c202cea102d94a764534899f3ca644f5d58e9b881f6a1dc4c05748e67b

  2. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Jun 3, 2026
  3. MelvinBot commented on Jun 3, 2026

    @MelvinBot
    Contributor

    Issue Analysis

    TL;DR — this is almost certainly not Safari-specific. The Spend tab restores its selected LHN item from an in-memory map (no sessionStorage/Onyx persistence like the Workspaces/Settings tabs have), and that map is browser-agnostic. The "MacOS: Safari" box is just the platform Applause tested — QA should re-verify on Chrome/Firefox too.

    Most likely root cause: when you switch to Inbox, the Search tab's preserved navigation state gets pruned and isn't restored on the way back, so the Spend tab falls back to its default search instead of "Drafts". Likely regressed in PR #89907 (2026-05-07), which rewrote the preserve/clean logic.

    ⚠️ Confidence: medium. The mechanism and cross-browser conclusion are well-supported by code. The exact failure point has two candidates (see below) and should be confirmed with a quick runtime check before implementing.

    What is the root cause of that problem?

    Tapping the Spend tab runs navigateToSearch() in SearchTabButton.tsx:36-68, which calls getLastRoute(...SEARCH_FULLSCREEN_NAVIGATOR, SCREENS.SEARCH.ROOT) to rebuild the last Search query. That route comes from an in-memory object, preservedNavigatorStates, in usePreserveNavigatorState.ts.

    On every navigation change, cleanPreservedNavigatorStates (called from NavigationRoot.tsx:259) deletes any preserved key not present in the current nav tree. collectAllRouteKeys only recurses into a route's children when route.state.stale === false, so when the Search tab's nested state is sliced/dropped during the Inbox switch, its key isn't collected and its preserved entry is pruned. restoreTabNavigatorRoutes is meant to re-seed it, but it skips any tab route whose .state is already gone (if (!tabRoute.state) continue). With no preserved route, getLastRoute returns undefined and SearchTabButton falls back to the Onyx last-query / default canned query → the default selection, not "Drafts".

    Critically, the Search/Spend tab has no sessionStorage fallback, unlike Workspaces/Settings — lastVisitedTabPathUtils only defines Workspaces/Settings variants, and Workspaces additionally restores via useRestoreWorkspacesTabOnNavigate. So the Spend tab depends entirely on the fragile in-memory map.

    Secondary candidate (verify at runtime)

    The Onyx fallback (REPORT_NAVIGATION_LAST_SEARCH_QUERY) is updated when you open a section like Drafts (via useSearchPageSetup → saveLastSearchParams). So an alternative is that getLastRoute does return a route, but buildSearchQueryString(buildSearchQueryJSON(q)) canonicalizes the query and drops the searchKey/filters that useSearchSections uses to highlight the active LHN row.

    To disambiguate: add a temporary log in navigateToSearch. If getLastRoute returns undefined → it's the preserved-state pruning above. If it returns a route but the rebuilt query string differs from the originally-clicked one → it's the query round-trip.

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

    • Preferred — give the Spend tab durable persistence: mirror the Workspaces pattern by saving the last Search path to sessionStorage (extend lastVisitedTabPathUtils) and restoring it on tab press, so the selection survives in-memory pruning.
    • Or — fix the regression: ensure the Search tab's nested state isn't pruned in cleanPreservedNavigatorStates/restoreTabNavigatorRoutes when its parent tab route is temporarily sliced during a tab switch.

    Confirm with the runtime check above before picking, since the secondary candidate would instead require fixing the query reconstruction in SearchTabButton.

    Why not Safari-specific

    The entire restore path is in-memory JS (preservedNavigatorStates) plus Onyx — both browser-agnostic. There is no userAgent/webkit/popstate-conditional code in this path. The only sessionStorage usage (a Safari-quirky API) is scoped to the Workspaces/Settings tabs and is not on the Spend tab's code path. Expect the same repro on Chrome and Firefox.


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

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Jun 3, 2026
  5. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Jun 3, 2026
  6. mukhrr commented on Jun 3, 2026

    @mukhrr
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-06-03 02:47:11 UTC.

    Proposal

    What is the root cause of that problem?

    Drafts in the Spend LHN is a TODO/live-data search. SearchResultsProvider marks TODO searches as shouldUseLiveData, so they use useTodos() instead of the normal snapshot search data.

    When the user selects Drafts, useSearchPageSetup exits early because shouldUseLiveData is true. Because of that, it never calls saveLastSearchParams(...) for the Drafts query.

    Then, when the user switches to Inbox and comes back to Spend, SearchTabButton restores Spend from REPORT_NAVIGATION_LAST_SEARCH_QUERY if it cannot restore a route from preserved navigator state. Since the Drafts query was never saved there, it falls back to the previous saved query or the default All expenses query, so the LHN selection is lost.

    Relevant code:

    • Drafts/Submit is a suggested TODO search:
      [CONST.SEARCH.SEARCH_KEYS.SUBMIT]: {
      key: CONST.SEARCH.SEARCH_KEYS.SUBMIT,
      translationPath: 'search.tabs.submit',
      type: CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT,
      icon: 'Pencil',
      searchQuery: buildQueryStringFromFilterFormValues({
      type: CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT,
      action: CONST.SEARCH.ACTION_FILTERS.SUBMIT,
      from: [`${accountID}`],
      }),
      get searchQueryJSON() {
      return buildSearchQueryJSON(this.searchQuery);
      },
      get hash() {
      return this.searchQueryJSON?.hash ?? CONST.DEFAULT_NUMBER_ID;
      },
      get similarSearchHash() {
      return this.searchQueryJSON?.similarSearchHash ?? CONST.DEFAULT_NUMBER_ID;
      },
      get recentSearchHash() {
      return this.searchQueryJSON?.recentSearchHash ?? CONST.DEFAULT_NUMBER_ID;
      },
      },
    • TODO searches use live data:
      const {currentSearchHash, currentSearchKey, currentSearchQueryJSON, suggestedSearches} = useSearchQueryContext();
      const currentRecentSearchHash = currentSearchQueryJSON?.recentSearchHash ?? -1;
      const todoSearchResultsData = useTodos();
      const [snapshotSearchResults] = useOnyx(`${ONYXKEYS.COLLECTION.SNAPSHOT}${currentSearchHash}`);
      const shouldUseLiveData = !!currentSearchKey && isTodoSearch(currentRecentSearchHash, suggestedSearches);
      // If viewing a to-do search, use live data from useTodos, otherwise return the snapshot data
      // We do this so that we can show the counters for the to-do search results without visiting the specific to-do page, e.g. show `Approve [3]` while viewing the `Submit` to-do search.
      let currentSearchResults;
      if (shouldUseLiveData) {
      const liveData = todoSearchResultsData[currentSearchKey as keyof typeof todoSearchResultsData];
    • useSearchPageSetup currently returns before saving last search params when shouldUseLiveData is true:
      useEffect(() => {
      if (!queryJSON || hash === undefined || shouldUseLiveData || isOffline) {
      return;
      }
      // Must run even on cached snapshots, else SearchTabButton's Onyx fallback restores
      // a stale query after a tab switch (e.g. filter reappears after Reset).
      if (lastSavedSearchHash !== hash) {
      saveLastSearchParams({queryJSON, offset: 0, searchKey: currentSearchKey, hasMoreResults: false, allowPostSearchRecount: false});
    • SearchTabButton uses that saved Onyx query as its fallback:
      const lastSearchRoute = getLastRoute(navigationRef.getRootState(), NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR, SCREENS.SEARCH.ROOT);
      if (lastSearchRoute) {
      const {q, ...rest} = lastSearchRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT];
      const queryJSON = buildSearchQueryJSON(q);
      if (queryJSON) {
      const query = buildSearchQueryString(queryJSON);
      Navigation.navigate(
      ROUTES.SEARCH_ROOT.getRoute({
      query,
      ...rest,
      }),
      );
      return;
      }
      }
      const lastQueryJSON = lastSearchParams?.queryJSON;
      const lastQueryFromOnyx = lastQueryJSON ? buildSearchQueryString(lastQueryJSON) : undefined;
      const defaultSearchQuery = buildCannedSearchQuery({type: CONST.SEARCH.DATA_TYPES.EXPENSE});
      Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: lastQueryFromOnyx ?? defaultSearchQuery}));

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

    Move the saveLastSearchParams(...) update before the shouldUseLiveData early return in useSearchPageSetup.

    Small diff:

     useEffect(() => {
    -    if (!queryJSON || hash === undefined || shouldUseLiveData || isOffline) {
    +    if (!queryJSON || hash === undefined) {
             return;
         }
    
         if (lastSavedSearchHash !== hash) {
             saveLastSearchParams({queryJSON, offset: 0, searchKey: currentSearchKey, hasMoreResults: false, allowPostSearchRecount: false});
             lastSavedSearchHash = hash;
         }
    
    +    if (shouldUseLiveData || isOffline) {
    +        return;
    +    }
    +
         if (isSnapshotDataLoaded || isSnapshotSearchLoading) {
             return;
         }

    This keeps the existing behavior of not calling search() for live-data TODO searches, but still records the current query for SearchTabButton to restore later. It is scoped to the already-existing last-search fallback and does not change the search result source, API request behavior, or LHN matching logic.

    Manual QA:

    1. Open Spend.
    2. Select Drafts.
    3. Switch to Inbox.
    4. Switch back to Spend.
    5. Verify Drafts is still selected.
    6. Repeat with another TODO Spend item if available.
    7. Verify first-time opening Spend still defaults to All expenses.

    What alternative solutions did you explore? (Optional)

    n/a

    Demo:

    REC-20260603081051.mp4
  7. yusufdeveloper2903 commented on Jun 3, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

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

    In the Spend tab, after opening the "Drafts" item in the Reports LHN, switching to Inbox and back to Spend does not restore "Drafts" — the tab reverts to a previous/default search instead of remembering the last selection.

    What is the root cause of that problem?

    The "Drafts" item is a live‑data (Todo) search, and the code path that persists "the last search you were looking at" is skipped for live‑data searches. So when the Spend tab is re‑opened, there is no saved record of "Drafts" to restore.

    1. "Drafts" is the Submit suggested search, which is a Todo search.

    In the Reports LHN the label "Drafts" is the translation of search.tabs.submit:

    App/src/languages/en.ts

    Lines 7980 to 7996 in 2d8b35e

    tabs: {
    expenseReports: 'Expense reports',
    reports: 'Reports',
    expenses: 'Expenses',
    submit: 'Drafts',
    approve: 'Needs approval',
    pay: 'Ready to pay',
    accounting: 'Accounting',
    export: 'Awaiting export',
    unapprovedCash: 'Cash accruals',
    unapprovedCard: 'Card accruals',
    statements: 'Card statements',
    reconciliation: 'Bank reconciliation',
    insights: 'Insights',
    topSpenders: 'Top spenders',
    topCategories: 'Top categories',
    topMerchants: 'Top merchants',

    So clicking "Drafts" opens the CONST.SEARCH.SEARCH_KEYS.SUBMIT suggested search, and SUBMIT is one of the Todo search keys:

    const TODO_SEARCH_KEYS: ReadonlySet<SearchKey> = new Set([CONST.SEARCH.SEARCH_KEYS.SUBMIT, CONST.SEARCH.SEARCH_KEYS.APPROVE, CONST.SEARCH.SEARCH_KEYS.PAY, CONST.SEARCH.SEARCH_KEYS.EXPORT]);

    App/src/libs/SearchUIUtils.ts

    Lines 4353 to 4356 in 2d8b35e

    function isTodoSearch(recentSearchHash: number, suggestedSearches: Record<string, SearchTypeMenuItem>) {
    const matchedSearchKey = Object.values(suggestedSearches).find((search) => search.recentSearchHash === recentSearchHash)?.key;
    return !!matchedSearchKey && TODO_SEARCH_KEYS.has(matchedSearchKey);
    }

    2. Todo searches are served from live data, which flips shouldUseLiveData to true.

    const shouldUseLiveData = !!currentSearchKey && isTodoSearch(currentRecentSearchHash, suggestedSearches);

    3. The "remember last search" write is gated behind !shouldUseLiveData, so it never runs for "Drafts".

    useSearchPageSetup is the place that records the currently‑viewed search into the durable Onyx key used to restore the Spend tab. Its effect returns early when shouldUseLiveData (or isOffline) is true, before it reaches saveLastSearchParams:

    useEffect(() => {
    if (!queryJSON || hash === undefined || shouldUseLiveData || isOffline) {
    return;
    }
    // Must run even on cached snapshots, else SearchTabButton's Onyx fallback restores
    // a stale query after a tab switch (e.g. filter reappears after Reset).
    if (lastSavedSearchHash !== hash) {
    saveLastSearchParams({queryJSON, offset: 0, searchKey: currentSearchKey, hasMoreResults: false, allowPostSearchRecount: false});
    lastSavedSearchHash = hash;
    }
    if (isSnapshotDataLoaded || isSnapshotSearchLoading) {
    return;
    }
    const shouldSkipWaitForWrites = hasDeferredWrite(CONST.DEFERRED_LAYOUT_WRITE_KEYS.SEARCH);
    search({queryJSON, searchKey: currentSearchKey, offset: 0, shouldCalculateTotals, isLoading: false, skipWaitForWrites: shouldSkipWaitForWrites});
    }, [hash, isOffline, shouldUseLiveData, queryJSON, isSnapshotDataLoaded, isSnapshotSearchLoading, currentSearchKey, shouldCalculateTotals]);

    So for a Todo search like "Drafts"/Submit, line 57 returns and the saveLastSearchParams(...) on line 64 is never called. The durable fallback key ONYXKEYS.REPORT_NAVIGATION_LAST_SEARCH_QUERY keeps whatever non‑Todo query was last viewed.

    function saveLastSearchParams(value: LastSearchParams) {
    Onyx.set(ONYXKEYS.REPORT_NAVIGATION_LAST_SEARCH_QUERY, value);
    }
    function clearLastSearchParams() {
    Onyx.set(ONYXKEYS.REPORT_NAVIGATION_LAST_SEARCH_QUERY, {});
    }

    REPORT_NAVIGATION_LAST_SEARCH_QUERY: 'ReportNavigationLastSearchQuery',

    4. When re‑opening the Spend tab, the restore falls back to that stale Onyx value.

    Tapping the Spend tab runs SearchTabButton.navigateToSearch, which restores the last search in this order: (a) the in‑memory navigator state via getLastRoute, then (b) the Onyx fallback lastSearchParams.queryJSON, then (c) a canned default:

    if (selectedTab === NAVIGATION_TABS.SEARCH) {
    return;
    }
    clearSelectedText();
    interceptAnonymousUser(() => {
    startSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_REPORTS, {
    name: CONST.TELEMETRY.SPAN_NAVIGATE_TO_REPORTS,
    op: CONST.TELEMETRY.SPAN_NAVIGATE_TO_REPORTS,
    forceTransaction: true,
    });
    const lastSearchRoute = getLastRoute(navigationRef.getRootState(), NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR, SCREENS.SEARCH.ROOT);
    if (lastSearchRoute) {
    const {q, ...rest} = lastSearchRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT];
    const queryJSON = buildSearchQueryJSON(q);
    if (queryJSON) {
    const query = buildSearchQueryString(queryJSON);
    Navigation.navigate(
    ROUTES.SEARCH_ROOT.getRoute({
    query,
    ...rest,
    }),
    );
    return;
    }
    }
    const lastQueryJSON = lastSearchParams?.queryJSON;
    const lastQueryFromOnyx = lastQueryJSON ? buildSearchQueryString(lastQueryJSON) : undefined;
    const defaultSearchQuery = buildCannedSearchQuery({type: CONST.SEARCH.DATA_TYPES.EXPENSE});
    Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: lastQueryFromOnyx ?? defaultSearchQuery}));

    After a tab switch the in‑memory preservedNavigatorStates entry for the Search navigator is gone (it is cleared by cleanPreservedNavigatorStates once the navigator leaves the navigation tree), so getLastRoute returns nothing and step (b) takes over. Because step 3 never updated that Onyx value to "Drafts", (b) restores the previous non‑Todo query (e.g. Expenses) — i.e. the "Drafts" selection is not remembered.

    The existing comment in the same effect already calls out this exact fragility — that SearchTabButton's Onyx fallback restores a stale query after a tab switch when the save is skipped:

    // Must run even on cached snapshots, else SearchTabButton's Onyx fallback restores
    // a stale query after a tab switch (e.g. filter reappears after Reset).

    Why it shows up on Safari: the defect itself is browser‑agnostic — live‑data searches are simply never written to the durable Onyx fallback. It only becomes visible when the in‑memory preserved navigator state (the step‑(a) lifeline) is dropped on the tab switch, which is timing/engine dependent; the regression run that filed this caught it on Mac Safari. The fix below removes the dependency on that in‑memory copy entirely, so the selection is remembered regardless of platform.

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

    Persist the last‑viewed search before the live‑data / offline gate in useSearchPageSetup, so the durable Onyx fallback always reflects the current selection (including Todo searches like "Drafts"). Only the search() API request needs to stay gated — live‑data searches come from useTodos and offline can't hit the API.

    // src/hooks/useSearchPageSetup.ts
    useEffect(() => {
        if (!queryJSON || hash === undefined) {
            return;
        }
    
        // Persist the last viewed search so SearchTabButton can restore it after a tab switch.
        // Must run for live-data (Todo) searches like "Drafts"/Submit and while offline too,
        // otherwise REPORT_NAVIGATION_LAST_SEARCH_QUERY keeps a stale query and the selection
        // is forgotten once the in-memory navigator state is dropped on a tab switch.
        if (lastSavedSearchHash !== hash) {
            saveLastSearchParams({queryJSON, offset: 0, searchKey: currentSearchKey, hasMoreResults: false, allowPostSearchRecount: false});
            lastSavedSearchHash = hash;
        }
    
        // Only the API request is gated: live-data is served from useTodos and offline can't fire search().
        if (shouldUseLiveData || isOffline) {
            return;
        }
    
        if (isSnapshotDataLoaded || isSnapshotSearchLoading) {
            return;
        }
        const shouldSkipWaitForWrites = hasDeferredWrite(CONST.DEFERRED_LAYOUT_WRITE_KEYS.SEARCH);
        search({queryJSON, searchKey: currentSearchKey, offset: 0, shouldCalculateTotals, isLoading: false, skipWaitForWrites: shouldSkipWaitForWrites});
    }, [hash, isOffline, shouldUseLiveData, queryJSON, isSnapshotDataLoaded, isSnapshotSearchLoading, currentSearchKey, shouldCalculateTotals]);

    With this change, opening "Drafts" writes its queryJSON to REPORT_NAVIGATION_LAST_SEARCH_QUERY; returning to the Spend tab then restores it through SearchTabButton.navigateToSearch's Onyx fallback, and SearchTypeMenuWide re‑highlights "Drafts" via its hash match.

    Edge cases / impact:

    • Other Todo tabs ("Needs approval"/Approve, "Ready to pay"/Pay, "Awaiting export"/Export) share the same shouldUseLiveData gate and have the identical bug — this fixes all of them, not just "Drafts".
    • Offline: persisting while offline is correct for tab‑restore and harmless (it only writes an Onyx record); the search() API call remains gated behind !isOffline.
    • No behavior change for non‑Todo searches: they already hit saveLastSearchParams; the lastSavedSearchHash !== hash guard still de‑dupes repeated saves of the same hash, so snapshot re‑fires don't wipe the report‑browsing fields (the original reason that guard exists).
    • Cross‑platform: the durable Onyx fallback now always holds the selection, so restoration no longer depends on the in‑memory preservedNavigatorStates surviving the tab switch — fixing Safari and any other engine/timing where that copy is dropped.

    What alternative solutions did you explore? (Optional)

    1. Save the last search at the click site (in SearchTypeMenuWide.onItemPress / SearchTabButton) instead of in useSearchPageSetup. This works but spreads the persistence logic across components and duplicates what useSearchPageSetup already owns; centralizing it in the existing effect is cleaner and covers every entry point (deep links, in‑page filter changes), not just LHN clicks.

    2. Make getLastRoute / preservedNavigatorStates survive tab switches for the Search navigator. This targets the step‑(a) lifeline, but it is navigation‑internals heavy, platform‑sensitive, and still leaves the durable fallback wrong for Todo searches. Fixing the persistence is the smaller, more robust change.

  8. melvin-bot commented on Jun 3, 2026

    @melvin-bot

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

  9. wildan-m commented on Jun 3, 2026

    @wildan-m
    Contributor

    Proposal

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

    In the Spend tab, after selecting an item in the Reports LHN (for example the "Drafts" search), navigating to the Inbox tab and then back to Spend does not restore that last selection. The Spend tab reopens on the default search instead of the search the user last had open.

    What is the root cause of that problem?

    When the Spend tab button is pressed, it tries to restore the last search the user had open. It does this in two ways, and both miss the case in the repro.

    The button first reads the last route from the in‑memory preserved navigator state for the Search fullscreen navigator, and if that is missing, falls back to the REPORT_NAVIGATION_LAST_SEARCH_QUERY Onyx value:

    const navigateToSearch = () => {
    if (selectedTab === NAVIGATION_TABS.SEARCH) {
    return;
    }
    clearSelectedText();
    interceptAnonymousUser(() => {
    startSpan(CONST.TELEMETRY.SPAN_NAVIGATE_TO_REPORTS, {
    name: CONST.TELEMETRY.SPAN_NAVIGATE_TO_REPORTS,
    op: CONST.TELEMETRY.SPAN_NAVIGATE_TO_REPORTS,
    forceTransaction: true,
    });
    const lastSearchRoute = getLastRoute(navigationRef.getRootState(), NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR, SCREENS.SEARCH.ROOT);
    if (lastSearchRoute) {
    const {q, ...rest} = lastSearchRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT];
    const queryJSON = buildSearchQueryJSON(q);
    if (queryJSON) {
    const query = buildSearchQueryString(queryJSON);
    Navigation.navigate(
    ROUTES.SEARCH_ROOT.getRoute({
    query,
    ...rest,
    }),
    );
    return;
    }
    }
    const lastQueryJSON = lastSearchParams?.queryJSON;
    const lastQueryFromOnyx = lastQueryJSON ? buildSearchQueryString(lastQueryJSON) : undefined;
    const defaultSearchQuery = buildCannedSearchQuery({type: CONST.SEARCH.DATA_TYPES.EXPENSE});
    Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: lastQueryFromOnyx ?? defaultSearchQuery}));
    });

    The in‑memory preserved state is not durable across a tab switch. cleanPreservedNavigatorStates deletes the preserved state of any navigator whose route key is no longer present in the live navigation tree, which is what happens when the Search navigator unmounts after switching to Inbox:

    const cleanPreservedNavigatorStates = (state: NavigationState) => {
    const allRouteKeys = collectAllRouteKeys(state);
    for (const key of Object.keys(preservedNavigatorStates)) {
    if (!allRouteKeys.has(key)) {
    delete preservedNavigatorStates[key];
    }
    }
    };
    const clearPreservedSearchNavigatorStates = () => {
    for (const key of Object.keys(preservedNavigatorStates)) {
    if (key.startsWith(NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR)) {
    delete preservedNavigatorStates[key];
    }
    }
    };

    The Onyx fallback does not cover this case either, because REPORT_NAVIGATION_LAST_SEARCH_QUERY is written only when a report is opened from the results list (so the report RHP prev/next arrows have context) — it is not updated when the user merely selects a different search/type in the LHN such as "Drafts":

    // in the report RHP can reference the correct result set.
    saveLastSearchParams({
    queryJSON,
    offset,
    searchKey: currentSearchKey,
    hasMoreResults: !!searchResults?.search?.hasMoreResults,
    allowPostSearchRecount: true,
    });

    So after selecting "Drafts" (without opening a report) and bouncing through Inbox, the preserved state is gone and the Onyx fallback still holds a stale/empty query, so the button lands on the default canned search.

    The reason this is a Spend‑tab–specific gap is that the Workspaces and Settings tabs solve exactly this "remember my last sub‑route across tab switches" problem with a durable session‑storage layer, and the Spend/Search tab was never added to it. The save side only handles those two navigators:

    if (!isFocusedOnEmptyNavigator) {
    if (activeTabName === NAVIGATORS.WORKSPACE_NAVIGATOR) {
    saveWorkspacesTabPathToSessionStorage(currentPath);
    } else if (activeTabName === NAVIGATORS.SETTINGS_SPLIT_NAVIGATOR) {
    saveSettingsTabPathToSessionStorage(currentPath);
    }
    }

    and the helpers only expose Workspaces/Settings getters and setters:

    function saveWorkspacesTabPathToSessionStorage(url: string) {
    saveTabPathToSessionStorage(CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH.WORKSPACES_TAB, url);
    }
    function getWorkspacesTabStateFromSessionStorage() {
    return getTabStateFromSessionStorage(CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH.WORKSPACES_TAB);
    }
    function saveSettingsTabPathToSessionStorage(url: string) {
    saveTabPathToSessionStorage(CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH.SETTINGS_TAB, url);
    }

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

    Extend the existing durable "last visited tab path" mechanism — already used by the Workspaces and Settings tabs — to cover the Spend/Search tab, so the last‑selected LHN search survives a tab switch even after the in‑memory preserved state is cleaned.

    Concretely:

    1. Add a SEARCH_TAB entry to CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH (alongside the existing WORKSPACES_TAB and SETTINGS_TAB).

    2. In src/libs/Navigation/helpers/lastVisitedTabPathUtils/index.ts (and the matching index.native.ts), add saveSearchTabPathToSessionStorage and getSearchTabStateFromSessionStorage, mirroring the existing Workspaces/Settings helpers that use the generic saveTabPathToSessionStorage / getTabStateFromSessionStorage pair.

    3. In NavigationRoot's path‑saving block, add a branch so that when the active tab is the Search fullscreen navigator, the current path is persisted with saveSearchTabPathToSessionStorage(currentPath) — exactly like the Workspaces and Settings branches a few lines above. Because this writes on every navigation within the Spend tab (including selecting "Drafts"), the last LHN selection is captured even when no report is opened.

    4. In SearchTabButton, add the session‑storage state as a durable fallback. When the fast in‑memory preserved‑state check yields nothing, read getSearchTabStateFromSessionStorage(), pull the SEARCH.ROOT route's q/params out of it (it is nested under TAB_NAVIGATOR → SEARCH_FULLSCREEN_NAVIGATOR), and navigate to that search. This fallback is consulted before the existing REPORT_NAVIGATION_LAST_SEARCH_QUERY Onyx fallback, because the session‑storage value is written on every Spend‑tab navigation (so it reflects the most recent LHN selection such as "Drafts"), whereas the Onyx value is only written when a report is opened and may hold a stale query that would otherwise win. The default canned search remains the last resort when none of the three sources yield a query.

    This keeps the fast in‑memory path as the primary restore and only relies on the durable session‑storage value when the preserved state has been cleaned by a tab switch — matching how Workspaces and Settings already behave.

    Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/92460-restore-spend-tab-search?expand=1

    What alternative solutions did you explore? (Optional)

    An alternative is to keep the existing Onyx fallback but broaden when REPORT_NAVIGATION_LAST_SEARCH_QUERY is written, so that selecting a search/type in the LHN (not just opening a report) updates it. This would make the existing SearchTabButton Onyx fallback restore "Drafts" with no new restore path. It was not chosen as the primary approach because that Onyx key is shared with the report RHP prev/next navigation, which expects report‑result context (offset, hasMoreResults, search key); widening its write sites risks regressing that flow. Reusing the established per‑tab session‑storage mechanism keeps the Spend tab consistent with Workspaces/Settings and avoids overloading a key that has a different consumer.

  10. melvin-bot commented on Jun 3, 2026

    @melvin-bot
  11. changed the title [-]Safari - Spend - The LHN within the Spend tab is not remembered when navigating to Inbox[/-] [+][$250] Safari - Spend - The LHN within the Spend tab is not remembered when navigating to Inbox[/+] on Jun 3, 2026
  12. ReaperOAK commented on Jun 3, 2026

    @ReaperOAK
    Contributor

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  13. 38 remaining items

  14. added
    Awaiting PaymentAuto-added when associated PR is deployed to production
    and removed on Jul 7, 2026
  15. melvin-bot commented on Jul 12, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  16. melvin-bot commented on Jul 12, 2026

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants/2062002202717580170/hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  17. mallenexpensify commented on Jul 13, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @nkdengineer due $250 via NewDot
    Contributor+: @mkhutornyi due $250 via NewDot

    ^ Test case created. Thx

  18. twisterdotcom commented on Jul 15, 2026

    @twisterdotcom
    Contributor

    $250 approved for @nkdengineer in Report ID: R00ADLX8s1gJ.

    Zapier Logs Run ID: 00040eee-7b0e-a569-b5cf-ec94d6f2c884

    SO: https://stackoverflowteams.com/c/expensify/questions/7582

  19. trjExpensify commented on Aug 3, 2026

    @trjExpensify
    Contributor

    approved $250 for @mkhutornyi

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

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions