App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Another search show in recent search after go back to Home tab

Open nlemma opened this issue 2 weeks ago • 46 comments

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


Version Number: v9.5.40-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/Expensify/issues/676490 Email or phone of affected tester (no customers): - Issue reported by: Applause Internal Team Bug source: Regression TC Execution Device used: Windows 11 Enterprise - Chrome

Action Performed:

Precondtions; Have search for multiples to have a 5 search in recent

  1. Sign in and land on Home.
  2. Open the Search router, submit a query, then go back to Home.
  3. Immediately reopen the Search router.

Expected Result:

Verify the recent searches list does not reorder and does not gain entries the user never typed (Home-section queries).

Actual Result:

Another search show in recent search after go back to Home tab and open the search router

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/147c0931-4ca3-4658-8c7e-50a51934ea85

View all open jobs on GitHub

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

nlemma avatar Nov 17 '26 22:11 nlemma

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

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

Issue Analysis

⚠️ Preliminary analysis — root cause not yet confirmed.

Finding: Home’s automatic searches are a plausible source of the unexpected entry, but the reported release already contains protection against saving those searches. Recommending that same protection as a new fix would be premature.

Evidence and hypothesis checks

A delayed legitimate search response could explain reordering, but would not establish that an unrelated Home query was newly saved. Browser reproduction and production confirmation remain unavailable.

What is needed to confirm the cause?

Capture the reproduction with:

  1. The exact unexpected query and reproduction time.
  2. Search request payloads, particularly jsonQuery.shouldSaveRecentSearch.
  3. Response updates to nvp_recentSearches.

This distinguishes an incorrectly flagged request, persistence despite false, and a delayed update to an existing entry. No new code fix is justified yet. If persistence occurs despite false, escalate to an internal engineer to investigate outside App.


Next Steps: Reply with @MelvinBot <your feedback> and the reproduction evidence to refine this analysis.


view run

MelvinBot avatar Nov 17 '26 22:11 MelvinBot

Proposal

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

When navigating from Home to Search, executing a query, going back to Home, and then re-entering Search, an unexpected query appears in Recent Searches or the recent searches order is prematurely corrupted.

What is the root cause of that problem?

When navigating back to Home, the SearchRouter / SearchPage switches context or unmounts, and the default home route triggers an internal query sync or background prefetch in SearchRouter.tsx / useSearchContext. This background fetch unintentionally commits the default Home filter state into Onyx recentSearches storage, causing an unintended search to appear at the top of Recent Searches.

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

  1. In src/libs/actions/Search.ts (or SearchRouter.tsx), ensure that only user-initiated search submissions (e.g. pressing enter or explicitly clicking a search tag) persist to ONYXKEYS.RECENT_SEARCHES.
  2. Add a guard check (isUserInitiated: true or checking navigation action type) so that route-restoration / background queries triggered when returning to the Home tab are skipped from being saved into the recent searches history list.

What alternative solutions did you explore?

Filter out default empty/home queries when rendering RecentSearchesList, but preventing the write at the Onyx action level in Search.ts is cleaner and prevents stale state accumulation.

zainrizvi0611-cmd avatar Nov 18 '26 04:11 zainrizvi0611-cmd

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

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

melvin-bot[bot] avatar Nov 18 '26 04:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0191be403aefe984cc

zainrizvi0611-cmd avatar Nov 18 '26 05:11 zainrizvi0611-cmd

⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.

melvin-bot[bot] avatar Nov 18 '26 05:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0191be403aefe984cc

zainrizvi0611-cmd avatar Nov 18 '26 05:11 zainrizvi0611-cmd

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

melvin-bot[bot] avatar Nov 18 '26 05:11 melvin-bot[bot]

Proposal

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

After signing in on Home, opening the Search router, submitting a query, and navigating back to Home, reopening the Search router shows an extra default search entry (Expenses / type:expense) at the top of Recent Searches that the user never submitted.

What is the root cause of that problem?

  1. When the user lands on Home (TAB_NAVIGATOR #1), the Spend tab (NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR, route K1) is idle-preloaded in the background (tabState.preloadedRouteKeys contains K1 and idlePreloadedRouteKey is set to K1). K1 mounts SCREENS.SEARCH.ROOT (SearchPage) with initialParams={{q: SearchQueryUtils.buildSearchQueryString()}} (type:expense), and useSearchPageSetup sets isFirstOpenOfPreloadedTabRef.current = true (src/hooks/useSearchPageSetup.ts:108-113).
  2. When the user opens SearchRouter from Home and submits a query, Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute(...)) pushes a new TAB_NAVIGATOR (#2) whose active tab is SEARCH_FULLSCREEN_NAVIGATOR (route K2) with the user's query:
    • Because K2 has isInPreloadedTab === false, K2's mount effect (src/libs/Navigation/AppNavigator/Navigators/SearchFullscreenNavigator.tsx:55-60) and unmount cleanup (lines 63-70) unconditionally call clearIdlePreloadedSearchTabRouteKey(), wiping the global idlePreloadedRouteKey that belongs to TAB_NAVIGATOR #1's still-preloaded route K1.
    • At the same time, useHasTabBeenShown(NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR) (src/hooks/useHasTabBeenShown.ts:14-32) inspects getTabNavigatorState(rootState) (the topmost TAB_NAVIGATOR) rather than the screen's own parent TAB_NAVIGATOR, so opening TAB_NAVIGATOR #2 latches hasSpendBeenShown = true inside K1's SearchPage too.
  3. When the user goes back to Home (TAB_NAVIGATOR #2 is popped, returning to TAB_NAVIGATOR #1 on SCREENS.HOME):
    • getSearchRootParamsFromTabNavigator (src/libs/SearchQueryUtils.ts:3137-3146) reads searchNavigator.state even when searchNavigator is still in tabState.preloadedRouteKeys (isTabRoutePreloaded(tabState, searchNavigator.key) is true). Instead of returning undefined so usePreviousDefined in SearchQueryProvider.tsx:60 keeps the user's submitted query, it resolves currentSearchQueryJSON to K1's unvisited preloaded default initialParams (type:expense).
    • Because K2 cleared idlePreloadedRouteKey, isIdlePreloadedSearchTabRoute(tabState, K1) on K1 evaluates to false, unfreezing K1 while the user is on Home.
    • K1's useSearchPageSetup effect (src/hooks/useSearchPageSetup.ts:117-177) then runs with hasSpendBeenShown === true, isInPreloadedTab === false, and isFirstOpenOfPreloadedTabRef.current === true (which bypasses the isSnapshotDataLoaded early return at line 144), and fires search({queryJSON, ..., shouldSaveRecentSearch: true}) for the default type:expense query while the user is on Home.

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

  1. Scope preload state clearing to the preloaded route key (src/libs/Navigation/helpers/searchTabPreloadStore.ts & src/libs/Navigation/AppNavigator/Navigators/SearchFullscreenNavigator.tsx):
    • Pass route.key to clearIdlePreloadedSearchTabRouteKey(route.key) (or only clear idlePreloadedRouteKey and isContentReady when idlePreloadedRouteKey === route.key) so mounting or unmounting a separate SearchFullscreenNavigator (K2) in another TAB_NAVIGATOR does not clear the preload mark of an unopened preloaded Spend tab (K1).
  2. Skip unopened preloaded Spend tabs when resolving Search query params (src/libs/SearchQueryUtils.ts):
    • In getSearchRootParamsFromTabNavigator (lines 3137-3146), if searchNavigator?.key && isTabRoutePreloaded(tabState, searchNavigator.key), return undefined so an unvisited preloaded Spend tab does not override SearchQueryProvider's usePreviousDefined(queryParams) with its default initialParams when returning to Home.
  3. Guard useSearchPageSetup and useHasTabBeenShown against background tab navigators (src/hooks/useSearchPageSetup.ts & src/hooks/useHasTabBeenShown.ts):
    • In useSearchPageSetup.ts (line 119), require isSearchTopmostFullScreenRoute() before firing the page-level search({..., shouldSaveRecentSearch: true}) request (matching line 146 and src/components/Search/index.tsx:483), so a background SearchPage never sends a shouldSaveRecentSearch: true request while another tab (Home) is topmost.

What alternative solutions did you explore? (Optional)

  • Only guarding shouldSaveRecentSearch on isSearchTopmostFullScreenRoute() inside useSearchPageSetup: that prevents the backend from saving the recent search, but without scoping clearIdlePreloadedSearchTabRouteKey(route.key) and skipping preloaded routes in getSearchRootParamsFromTabNavigator, returning to Home still unfreezes the preloaded Spend tab and overwrites lastSavedSearchHash / SearchQueryProvider with the default query.

Vallejo1921 avatar Nov 18 '26 06:11 Vallejo1921

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

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

melvin-bot[bot] avatar Nov 18 '26 06:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~015070efd014931f3e

Vallejo1921 avatar Nov 18 '26 17:11 Vallejo1921

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

melvin-bot[bot] avatar Nov 18 '26 17:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

Proposal

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

After submitting a search, going back to the Home tab, and reopening the Search router, the recent searches list reorders on its own and gains a Home-section query the user never typed. In the repro video, the user submits type:chat from:me, goes back to Home, and reopens the router. The list first shows the new query on top, then about one second later, with no user action, the Your Spend approval query (type:expense status:outstanding from:me reimbursable:yes workspace:"Fir...) jumps from third place to first, above the query just submitted. The expected result is that the list never reorders by itself and never gains entries the user never typed, including Home-section queries.

What is the root cause of that problem?

There are two parts to this, and the App-side investigation separates them cleanly.

First, the App's request layer is not the source of the reorder in the video. I verified by reading every call site and by test that every Home-section search is sent with shouldSaveRecentSearch: false. Only three call sites ever pass true, and all three send the Search page's own route query: the page setup in useSearchPageSetup.ts, the first-page fetch in src/components/Search/index.tsx, and the error-retry button in the same component. Every Home caller passes false or the default, including the Your Spend approval search (useYourSpendData.ts), the insight searches, and the recently-added search. The request layer always serializes the flag into jsonQuery, and there is no client-side writer of nvp_recentSearches other than the backend. A new test that replays the exact video sequence at the search() level (Home approval search in flight, user submits type:chat from:me, Home re-fires the approval search, Search page re-fires the chat query) passes on baseline, which proves the App sends the right flag for every request in that sequence. So the late re-save of the approval query in the video, about one second after the router reopened, can only come from the backend's save path: the Home approval search's response (or its async Pusher update, the same mechanism as in #102195) carries the approval query with a fresh timestamp even though the App sent shouldSaveRecentSearch: false. That is a backend-side defect, and an App-only change cannot fully prevent it. It needs a backend follow-up to make the save path honor the flag on the async path.

Second, there is a genuine App-side leak in the same symptom class, and that is what this fix addresses. The Search page saves ANY route query it displays as a recent search, because the save flag is tied to displaying a query rather than to the user submitting it. Both the page setup (useSearchPageSetup.ts) and the first-page fetch (src/components/Search/index.tsx) pass shouldSaveRecentSearch: true unconditionally for a non-live first page. So when the Search page shows a query the user already submitted, a restore from the preloaded tab, or a revisit of the same query, it re-saves that query with a fresh timestamp. That bumps it above newer real searches, which is exactly the reorder the issue reports. The persisted signal that distinguishes a restore from a new submission already exists: the last search params in Onyx (REPORT_NAVIGATION_LAST_SEARCH_QUERY), which the page saves on every hash change. If the displayed query matches those persisted params, it is a restore or a revisit, not a new submission, and displaying it must not re-save it.

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

Gate the save flag on the query being newly submitted, using the persisted last search params as the signal, in both places that fire the Search page's first page. The change is minimal and fail-safe toward saving.

  1. In src/hooks/useSearchPageSetup.ts: subscribe to ONYXKEYS.REPORT_NAVIGATION_LAST_SEARCH_QUERY with a selector that returns only the query hash (a primitive, so the subscription does not re-render on unrelated writes), keep the render-time value in a ref so the search effect reads the hash that was current when it was scheduled without re-running when the save it performs updates the key, and pass shouldSaveRecentSearch: lastSearchParamsHashRef.current !== hash instead of the unconditional true. When the signal is absent (no saved params), the comparison is true and the query is saved, which preserves the current behavior for a genuine first search.

  2. In src/components/Search/index.tsx: apply the same gating to the first-page fetch, so a cached restore is not saved by the component after the page setup fires without saving it. The flag becomes searchRequestOffset === 0 && !shouldUseLiveData && lastSearchParamsHashRef.current !== queryJSON.hash. The error-retry button is left as true because pressing retry is an explicit user action to run that search.

The backend follow-up is separate and still needed: the save path must honor shouldSaveRecentSearch: false on the async Pusher update for Home-section searches, or the video's exact reorder (a Home search response re-saving the approval query) can still occur. This App change closes the Search-page re-save path; it does not change what the backend does with a false-flagged Home search.

What alternative solutions did you explore? (Optional)

  • Fixing only the request layer (search() in Search.ts): already correct. Every Home caller sends false, the flag is always serialized, and the replay test passes on baseline. There is nothing to fix there, and changing it would not stop the re-save.
  • Filtering Home canned queries out of the displayed recent searches (SearchAutocompleteList.tsx): this would hide the symptom in the router, but it is a symptom-reader fix, not a source fix. It also needs fragile string matching against date-dependent Home queries (the payment query embeds a 30-day window), and it would hide a query even when the user deliberately opened it. Rejected.
  • Comparing against the module-level lastSavedSearchHash in useSearchPageSetup.ts: this variable is undefined on a fresh load, so a restored query looks new and is still saved. It cannot distinguish a restore from a new submission across sessions. The persisted Onyx params can, which is why the fix reads them.
  • Gating only useSearchPageSetup.ts and not the Search component: insufficient. For a cached restore the page setup does not claim the page (it only marks when the snapshot is not loaded), so the component's first-page fetch is the one that saves it. Both must be gated consistently.

Tests.

  • New tests/unit/hooks/useSearchPageSetup.test.ts (2 tests): a restored query (persisted last search params equal the page query) is fired with shouldSaveRecentSearch: false, and a newly submitted query (persisted params are a different query) is fired with shouldSaveRecentSearch: true. The restore test fails on baseline (the flag is true) and passes with the fix. Full file: 9/9 pass.
  • New tests/unit/Search/searchSaveRecentSearchFlagRepro107177Test.ts (1 test): replays the exact video sequence at the search() level (Home approval search in flight, user submits type:chat from:me, Home re-fires the approval search, Search page re-fires the chat query) and asserts the approval search is dispatched exactly once with the flag false and the chat query exactly once with the flag true. This passes on baseline (1/1) and is kept as a regression guard proving the App request layer is correct.
  • Existing tests/unit/Search/searchSaveRecentSearchFlagTest.ts: 10/10 pass.
  • Related suites: tests/ui/SearchPageTest.tsx + tests/ui/SearchTabPreloadTest.tsx (59/59 pass), tests/unit/Search/ExpenseFlatSearchViewTest.tsx + tests/unit/Search/DeferredSearchAutocompleteListTest.tsx (9/9 pass).

Caveats.

  • The video's exact reorder also needs the backend save-path fix described above; this App change alone does not stop a false-flagged Home search response from re-saving the approval query.
  • Real-device and manual QA were not run on this VM; the change was verified by the automated suites listed above.
  • Lint and typecheck could not be run cleanly on this VM (the repo's lint/typecheck tooling fails here for environment reasons, not code reasons). The change follows the repo's house rules (useOnyx subscription with a primitive selector, comments explaining why, Given/When/Then test comments).

dankezo avatar Nov 21 '26 15:11 dankezo

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

melvin-bot[bot] avatar Nov 21 '26 15:11 melvin-bot[bot]

@situchan Huh... This is 4 days overdue. Who can take care of this?

Claude posting on behalf of Matt:

@hoangzinh you're now the C+ on this issue. The previous C+ is no longer in the Contributor program. Next step: review the proposals.

mallenexpensify avatar Nov 23 '26 22:11 mallenexpensify

Hi @hoangzinh, welcome to the issue!

Looking forward to working with you. My earlier proposal from Nov 18 is first in the review queue, addressing the search state persistence issue cleanly. Contributor details are already verified and on file. Ready to open the PR immediately upon review!

zainrizvi0611-cmd avatar Nov 23 '26 22:11 zainrizvi0611-cmd

Hello @zainrizvi0611-cmd, thanks for posting your proposals, but according to Expensify's contributingGuidlines, this issue is not yet open for proposals from external contributors. Anyway, let me review this issue and MelvinBot's proposal first.

hoangzinh avatar Nov 25 '26 12:11 hoangzinh

I'm unable to reproduce this issue. Let me try to ask if other C+ can

image

hoangzinh avatar Nov 25 '26 13:11 hoangzinh