[$250] Another search show in recent search after go back to Home tab
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
- Sign in and land on Home.
- Open the Search router, submit a query, then go back to Home.
- 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
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022122816709073066654
- Upwork Job ID: 2122816709073066654
- Last Price Increase: 2026-11-26
Issue Owner
Current Issue Owner: @lakchote
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
- Returning to Home triggers automatic searches, matching the reported navigation sequence: useInsightData.ts:43–62.
- In the
9.5.40-0-stagingrelease, searches default to not saving, and that boolean is explicitly included in the request: Search.ts:1383–1487. - The recent-search UI sorts stored entries by timestamp and displays five. It does not generate Home queries itself: SearchAutocompleteList.tsx:468–496.
- All 11 focused persistence-flag tests passed: searchSaveRecentSearchFlagTest.ts.
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:
- The exact unexpected query and reproduction time.
- Search request payloads, particularly
jsonQuery.shouldSaveRecentSearch. - 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.
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?
- In
src/libs/actions/Search.ts(orSearchRouter.tsx), ensure that only user-initiated search submissions (e.g. pressing enter or explicitly clicking a search tag) persist toONYXKEYS.RECENT_SEARCHES. - Add a guard check (
isUserInitiated: trueor 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! 📣 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:
- Make sure you've read and understood the contributing guidelines.
- 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.
- 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.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0191be403aefe984cc
⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0191be403aefe984cc
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
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?
- When the user lands on Home (
TAB_NAVIGATOR#1), the Spend tab (NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR, routeK1) is idle-preloaded in the background (tabState.preloadedRouteKeyscontainsK1andidlePreloadedRouteKeyis set toK1).K1mountsSCREENS.SEARCH.ROOT(SearchPage) withinitialParams={{q: SearchQueryUtils.buildSearchQueryString()}}(type:expense), anduseSearchPageSetupsetsisFirstOpenOfPreloadedTabRef.current = true(src/hooks/useSearchPageSetup.ts:108-113). - When the user opens
SearchRouterfrom Home and submits a query,Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute(...))pushes a newTAB_NAVIGATOR(#2) whose active tab isSEARCH_FULLSCREEN_NAVIGATOR(routeK2) with the user's query:- Because
K2hasisInPreloadedTab === false,K2's mount effect (src/libs/Navigation/AppNavigator/Navigators/SearchFullscreenNavigator.tsx:55-60) and unmount cleanup (lines 63-70) unconditionally callclearIdlePreloadedSearchTabRouteKey(), wiping the globalidlePreloadedRouteKeythat belongs toTAB_NAVIGATOR#1's still-preloaded routeK1. - At the same time,
useHasTabBeenShown(NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR)(src/hooks/useHasTabBeenShown.ts:14-32) inspectsgetTabNavigatorState(rootState)(the topmostTAB_NAVIGATOR) rather than the screen's own parentTAB_NAVIGATOR, so openingTAB_NAVIGATOR#2 latcheshasSpendBeenShown = trueinsideK1'sSearchPagetoo.
- Because
- When the user goes back to Home (
TAB_NAVIGATOR#2 is popped, returning toTAB_NAVIGATOR#1 onSCREENS.HOME):getSearchRootParamsFromTabNavigator(src/libs/SearchQueryUtils.ts:3137-3146) readssearchNavigator.stateeven whensearchNavigatoris still intabState.preloadedRouteKeys(isTabRoutePreloaded(tabState, searchNavigator.key)istrue). Instead of returningundefinedsousePreviousDefinedinSearchQueryProvider.tsx:60keeps the user's submitted query, it resolvescurrentSearchQueryJSONtoK1's unvisited preloaded defaultinitialParams(type:expense).- Because
K2clearedidlePreloadedRouteKey,isIdlePreloadedSearchTabRoute(tabState, K1)onK1evaluates tofalse, unfreezingK1while the user is on Home. K1'suseSearchPageSetupeffect (src/hooks/useSearchPageSetup.ts:117-177) then runs withhasSpendBeenShown === true,isInPreloadedTab === false, andisFirstOpenOfPreloadedTabRef.current === true(which bypasses theisSnapshotDataLoadedearly return at line144), and firessearch({queryJSON, ..., shouldSaveRecentSearch: true})for the defaulttype:expensequery while the user is on Home.
What changes do you think we should make in order to solve the problem?
- Scope preload state clearing to the preloaded route key (
src/libs/Navigation/helpers/searchTabPreloadStore.ts&src/libs/Navigation/AppNavigator/Navigators/SearchFullscreenNavigator.tsx):- Pass
route.keytoclearIdlePreloadedSearchTabRouteKey(route.key)(or only clearidlePreloadedRouteKeyandisContentReadywhenidlePreloadedRouteKey === route.key) so mounting or unmounting a separateSearchFullscreenNavigator(K2) in anotherTAB_NAVIGATORdoes not clear the preload mark of an unopened preloaded Spend tab (K1).
- Pass
- Skip unopened preloaded Spend tabs when resolving Search query params (
src/libs/SearchQueryUtils.ts):- In
getSearchRootParamsFromTabNavigator(lines 3137-3146), ifsearchNavigator?.key && isTabRoutePreloaded(tabState, searchNavigator.key), returnundefinedso an unvisited preloaded Spend tab does not overrideSearchQueryProvider'susePreviousDefined(queryParams)with its defaultinitialParamswhen returning to Home.
- In
- Guard
useSearchPageSetupanduseHasTabBeenShownagainst background tab navigators (src/hooks/useSearchPageSetup.ts&src/hooks/useHasTabBeenShown.ts):- In
useSearchPageSetup.ts(line 119), requireisSearchTopmostFullScreenRoute()before firing the page-levelsearch({..., shouldSaveRecentSearch: true})request (matching line146andsrc/components/Search/index.tsx:483), so a backgroundSearchPagenever sends ashouldSaveRecentSearch: truerequest while another tab (Home) is topmost.
- In
What alternative solutions did you explore? (Optional)
- Only guarding
shouldSaveRecentSearchonisSearchTopmostFullScreenRoute()insideuseSearchPageSetup: that prevents the backend from saving the recent search, but without scopingclearIdlePreloadedSearchTabRouteKey(route.key)and skipping preloaded routes ingetSearchRootParamsFromTabNavigator, returning to Home still unfreezes the preloaded Spend tab and overwriteslastSavedSearchHash/SearchQueryProviderwith the default query.
📣 @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:
- Make sure you've read and understood the contributing guidelines.
- 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.
- 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.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~015070efd014931f3e
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
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.
-
In
src/hooks/useSearchPageSetup.ts: subscribe toONYXKEYS.REPORT_NAVIGATION_LAST_SEARCH_QUERYwith 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 passshouldSaveRecentSearch: lastSearchParamsHashRef.current !== hashinstead of the unconditionaltrue. 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. -
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 becomessearchRequestOffset === 0 && !shouldUseLiveData && lastSearchParamsHashRef.current !== queryJSON.hash. The error-retry button is left astruebecause 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()inSearch.ts): already correct. Every Home caller sendsfalse, 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
lastSavedSearchHashinuseSearchPageSetup.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.tsand 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 withshouldSaveRecentSearch: false, and a newly submitted query (persisted params are a different query) is fired withshouldSaveRecentSearch: true. The restore test fails on baseline (the flag istrue) and passes with the fix. Full file: 9/9 pass. - New
tests/unit/Search/searchSaveRecentSearchFlagRepro107177Test.ts(1 test): replays the exact video sequence at thesearch()level (Home approval search in flight, user submitstype: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 flagfalseand the chat query exactly once with the flagtrue. 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).
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@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.
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!
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.
I'm unable to reproduce this issue. Let me try to ask if other C+ can