App icon indicating copy to clipboard operation
App copied to clipboard

Search - Creating a new saved search also updates the previously saved search

Open applause-bot[bot] opened this issue 3 weeks ago • 13 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: v9.5.36-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/App/pull/106391 Email or phone of affected tester (no customers): n/a Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Mac 26.5.1 Safari/Chrome App Component: Search

Action Performed:

  1. Go to https://staging.new.expensify.com
  2. Navigate to Spend
  3. Open Filters, set a Merchant filter to Alpha, and select Save
  4. Save as QA Original, reopen it, and verify the Alpha filter is retained 5, With QA Original selected, change the Merchant filter to Beta
  5. select Save, and
  6. choose Create new
  7. Save as QA Copy
  8. Reopen the QA Original saved search

Expected Result:

Creating a new saved search should not modify any previously saved searches

Actual Result:

Creating a new saved search also updates the previously saved search

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/b8bf9f38-ceb3-4272-9b2e-9541db748130

View all open jobs on GitHub

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

Issue OwnerCurrent Issue Owner: @ZhenjaHorbach

applause-bot[bot] avatar Nov 11 '26 02:11 applause-bot[bot]

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

applause-bot[bot] avatar Nov 11 '26 02:11 applause-bot[bot]

🤖 Web test steps verification results: ❌ fail

Reopening QA Original displayed Beta after creating QA Copy, but Reset restored Alpha, indicating remembered unsaved filters rather than an overwritten saved definition. QA has also closed the issue after rechecking.

Reset restores QA Original to Alpha
Step Status
1. Navigate to SpendSpend and Expenses headings were visible.
✅
2. Set Merchant to AlphaFilters displayed Merchant: Contains “Alpha”.
Merchant filter set to Alpha
✅
3. Save as QA Original and reopenQA Original reopened with Alpha retained.
✅
4. Change Merchant to BetaQA Original displayed Merchant: Contains “Beta”.
✅
5. Select SaveThe dialog offered updating QA Original or creating a new search.
✅
6. Choose Create newThe naming page opened.
✅
7. Save as QA CopyQA Copy displayed Beta; both saved searches were available.
✅
8. Reopen QA Original and verify Alpha remainsQA Original displayed Beta, failing the reported expectation.
Root cause of the displayed behavior: executing the edited query remembers Beta under the original search’s key in SEARCH_FILTERS (Search.ts:1479–1492). Reopening a saved search prefers that remembered query (SearchNavigationUtils.ts:39–49).
Alternative checked: Create new does not update the original ID. Its branch opens the naming page, which saves using a fresh ID (SearchFiltersSaveButton.tsx:46–66, SearchSavePage.tsx:201–211). Server persistence was not independently inspected.
QA Original displays remembered Beta after creating QA Copy
❌
9. Reset QA Original to distinguish remembered edits from its saved definitionReset restored Alpha and removed the Reset/Save controls.
Recommendation: No code fix is justified for the withdrawn overwrite report. Remembering unsaved refinements is explicitly covered by an existing navigation test. If creating a copy should also reset the original’s remembered filters, confirm that product requirement separately and add regression coverage distinguishing saved definitions from remembered state.
Related context: Add a Save button when a search differs from its default view defines the create/update flow; it is not a confirmed duplicate.
Reset restores QA Original to Alpha
✅

view run · no recording available

MelvinBot avatar Nov 11 '26 03:11 MelvinBot

Sorry for the confusion. We have decided to reopen the issue after double-checking all the steps once again.

mitarachim avatar Nov 11 '26 03:11 mitarachim

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

Proposal

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

When editing filters on an existing saved search and selecting "Save" -> "Create new" to save the modified filters as a separate new saved search, the previously saved search also retains the modified filters instead of preserving its original saved criteria.

What is the root cause of that problem?

  1. When modifying filters on an active saved search (e.g. changing merchant from Alpha to Beta while viewing QA Original), src/libs/actions/Search.ts optimistically updates the uncommitted draft query into ONYXKEYS.SEARCH_FILTERS[savedSearch_<originalID>].
  2. When the user clicks "Save" and selects "Create new" in SearchFiltersSaveButton.tsx, the user navigates to SearchSavePage.tsx, generating a new saved search ID (rand64()) with the new query and switching the active search key to savedSearch_<newID>.
  3. However, ONYXKEYS.SEARCH_FILTERS[savedSearch_<originalID>] is never cleared or reset back to the original saved search query (item.query).
  4. Consequently, when the user navigates back to the previous saved search, SavedSearchList.tsx:146 resolves the query via:
    const itemQuery = normalizeDatePresetsInQuery(getValidLastQuery(getLastSearchQuery(searchFilters, savedSearchIDToSearchKey(key)), item.query));
    
    Because getLastSearchQuery(searchFilters, ...) returns the uncommitted draft query (Beta), SavedSearchList loads the modified query rather than the saved query (Alpha), causing the original saved search to appear modified.

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

  1. In src/pages/Search/SearchSavePage.tsx (inside onSaveSearch):
    • When a new saved search is created branching off an existing active saved search (activeSavedSearchID), reset or remove the draft uncommitted query from ONYXKEYS.SEARCH_FILTERS for that savedSearchIDToSearchKey(activeSavedSearchID) (e.g., reverting searchFilters[savedSearchKey] back to activeSavedSearch.query or setting it to null).
  2. Alternatively, in SearchFiltersSaveButton.tsx:
    • When decision.action === ModalActions.CONFIRM ("Create new") is selected, clear or reset the temporary search filters draft for activeSavedSearchID before calling openSaveSearchPage().

What alternative solutions did you explore? (Optional)

  • Bypassing getLastSearchQuery in SavedSearchList.tsx: Rejected because draft filter caching is intentional for active exploration, but draft filters should not bleed across when explicitly choosing to fork into a new saved search.

What automated tests can you add to prevent this from re-occurring?

In tests/unit/SearchSavePageTest.tsx or SearchFiltersSaveButtonTest.tsx:

  • Add a test verifying that when modifying filters on an active saved search and choosing "Create new", the original saved search's draft in ONYXKEYS.SEARCH_FILTERS is reset so that reopening the original saved search retains its original query criteria.

tranvanminhnhat avatar Nov 11 '26 05:11 tranvanminhnhat

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

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

Okay Looks like this issue is in prod also But I will check!

https://github.com/user-attachments/assets/d19c4d93-399c-4d1c-9ef9-a3d55d6b2340

ZhenjaHorbach avatar Nov 11 '26 07:11 ZhenjaHorbach

Proposal

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

When a user opens an existing saved search (e.g. QA Original with merchant:Alpha), modifies a filter (e.g. changing merchant to Beta), clicks Save -> Create new, and saves the new search as QA Copy, reopening QA Original from the Saved Searches menu displays the modified Beta filter instead of its original Alpha filter.

What is the root cause of that problem?

  1. While viewing QA Original (searchKey = savedSearch_<originalID>), editing a filter dispatches search() (src/libs/actions/Search.ts:1504-1514), which optimistically caches the modified inputQuery (merchant:Beta) under ONYXKEYS.SEARCH_FILTERS[savedSearch_<originalID>].query.
  2. When the user clicks Save and selects Create new in src/components/Search/SearchPageHeader/SearchFiltersSaveButton.tsx:57-60, SearchSavePage.tsx (onSaveSearch, lines 201-212) creates a new saved search ID (const id = rand64()), calls saveSearch({id, queryJSON: currentSearchQueryJSON, newName}), and updates the route parameter searchKey to savedSearchIDToSearchKey(id).
  3. However, neither SearchSavePage.tsx nor saveSearch() clears or resets the uncommitted draft query stored at ONYXKEYS.SEARCH_FILTERS[currentSearchKey] (the source saved search from which the user branched Create new).
  4. Worse still, there is a second side effect in src/components/Search/hooks/useSearchKeyParam.ts:70-82:
    const savedSearchID = savedSearchIDs.find((id) => {
        const savedSearchQuery = savedSearches?.[id].query;
        const lastSavedSearchQuery = getLastSearchQuery(searchFilters, savedSearchIDToSearchKey(id));
    
        return (
            (savedSearchQuery ? buildSearchQueryJSON(normalizeDatePresetsInQuery(savedSearchQuery))?.hash === queryJSON?.hash : false) ||
            (lastSavedSearchQuery ? buildSearchQueryJSON(lastSavedSearchQuery)?.hash === queryJSON?.hash : false)
        );
    });
    
    Because searchFilters[savedSearch_<originalID>].query still has the exact same Beta query hash as the newly created QA Copy, Array.prototype.find matches <originalID> first whenever searchKey is resolved from the query! And when the user clicks QA Original in src/pages/Search/SavedSearchList.tsx:146 (or navigateToFlatNavItem in src/libs/SearchNavigationUtils.ts:49), getLastSearchQuery(searchFilters, savedSearchIDToSearchKey(key)) returns the stale Beta draft instead of item.query (Alpha).

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

Clear the remembered draft entry in ONYXKEYS.SEARCH_FILTERS whenever a saved search is saved (both for the target savedSearchIDToSearchKey(id) and, when branching via Create new from an existing saved search, for the source sourceSearchKey):

  1. In src/libs/actions/Search.ts (saveSearch, lines 935-977), accept an optional sourceSearchKey?: SearchKey parameter and clear the corresponding ONYXKEYS.SEARCH_FILTERS entry (or entries) in optimisticData:

    function saveSearch({
        id,
        queryJSON,
        newName,
        sourceSearchKey,
    }: {
        id: string;
        queryJSON: Readonly<SearchQueryJSON>;
        newName?: string;
        sourceSearchKey?: SearchKey;
    }) {
        const normalizedQuery = normalizeDatePresetsInQuery(queryJSON.inputQuery);
        const savedQueryJSON = normalizedQuery === queryJSON.inputQuery ? queryJSON : (buildSearchQueryJSON(normalizedQuery) ?? queryJSON);
        const saveSearchName = newName ?? savedQueryJSON?.inputQuery ?? '';
        const jsonQuery = JSON.stringify(savedQueryJSON);
        const targetSearchKey = savedSearchIDToSearchKey(id);
    
        const searchFiltersToClear: Record<string, null> = {
            [targetSearchKey]: null,
            ...(sourceSearchKey && searchKeyToSavedSearchID(sourceSearchKey) ? {[sourceSearchKey]: null} : {}),
        };
    
        const optimisticData: Array<OnyxUpdate<typeof ONYXKEYS.SAVED_SEARCHES | typeof ONYXKEYS.SEARCH_FILTERS>> = [
            {
                onyxMethod: Onyx.METHOD.MERGE,
                key: `${ONYXKEYS.SAVED_SEARCHES}`,
                value: {
                    [id]: {
                        pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
                        name: saveSearchName,
                        query: savedQueryJSON.inputQuery,
                    },
                },
            },
            {
                onyxMethod: Onyx.METHOD.MERGE,
                key: ONYXKEYS.SEARCH_FILTERS,
                value: searchFiltersToClear,
            },
        ];
    
  2. In src/pages/Search/SearchSavePage.tsx (lines 198-212), destructure currentSearchKey from useSearchQueryContext() and pass sourceSearchKey: currentSearchKey into saveSearch:

    const {currentDefaultSearchQueryFilterKeys, currentSearchQueryJSON, currentSearchKey} = useSearchQueryContext();
    ...
    const onSaveSearch = (values: FormOnyxValues<typeof ONYXKEYS.FORMS.SEARCH_SAVE_FORM>) => {
        if (!currentSearchQueryJSON) {
            Navigation.goBack();
            return;
        }
    
        const id = rand64();
        saveSearch({
            id,
            queryJSON: currentSearchQueryJSON,
            newName: values[INPUT_IDS.NAME].trim(),
            sourceSearchKey: currentSearchKey,
        });
        Navigation.dismissModal({afterTransition: () => Navigation.setParams({searchKey: savedSearchIDToSearchKey(id)})});
    };
    
    • If the user opens the Create new page (SearchSavePage) and presses Back/Cancel without submitting the form, ONYXKEYS.SEARCH_FILTERS[currentSearchKey] remains intact so their in-progress filter edits on the original search are not lost.
    • Once the user submits Save view on SearchSavePage, the uncommitted draft on sourceSearchKey (savedSearch_<originalID>) is cleared in ONYXKEYS.SEARCH_FILTERS, so reopening QA Original loads its saved Alpha query cleanly.

What alternative solutions did you explore? (Optional)

  • Clearing ONYXKEYS.SEARCH_FILTERS inside SearchFiltersSaveButton.tsx as soon as the user clicks Create new in the decision modal: rejected because if the user subsequently cancels/closes SearchSavePage without saving the new view, they would lose their unsaved filter edits on the current screen. Clearing sourceSearchKey inside saveSearch upon actual submission of SearchSavePage avoids data loss on cancel.

cocvn157 avatar Nov 15 '26 14:11 cocvn157

Not overdue Will check today

ZhenjaHorbach avatar Nov 16 '26 08:11 ZhenjaHorbach

@cocvn157 Stop posting proposals without Help Wanted label Otherwise, you will be banned soon

ZhenjaHorbach avatar Nov 16 '26 08:11 ZhenjaHorbach

@ZhenjaHorbach Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

@ZhenjaHorbach Still overdue 6 days?! Let's take care of this!

Not overdue Will check tomorrow

ZhenjaHorbach avatar Nov 23 '26 22:11 ZhenjaHorbach

@roryabraham @ZhenjaHorbach this issue was created 2 weeks ago. Are we close to a solution? Let's make sure we're treating this as a top priority. Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!