From 3a124feaac3f6976e328418ff64c9605d4827216 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 11 Aug 2026 12:14:35 +0200 Subject: [PATCH 01/15] Skip search-text normalization in getValidOptions when the search is empty --- src/libs/OptionsListUtils/index.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/libs/OptionsListUtils/index.ts b/src/libs/OptionsListUtils/index.ts index 5b91b5364f86..2bb2d284c454 100644 --- a/src/libs/OptionsListUtils/index.ts +++ b/src/libs/OptionsListUtils/index.ts @@ -2732,6 +2732,10 @@ function getValidOptions( const isSelfDMChat = (report: SearchOption) => shouldSeparateSelfDMChat && report.isSelfDM && !report.private_isArchived; const isSearchTermsFound = (report: SearchOption) => { + // An empty search matches every report, so skip building and normalizing the search text. + if (searchTerms.length === 0) { + return true; + } let searchText = `${report.text ?? ''}${report.login ?? ''}`; if (report.isThread) { searchText += report.alternateText ?? ''; From 5064258fbe3e0bf1fcca9366811986a0559b9d0a Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 11 Aug 2026 12:14:37 +0200 Subject: [PATCH 02/15] Skip the autocomplete parser for blank queries --- src/hooks/useAutocompleteSuggestions.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/hooks/useAutocompleteSuggestions.ts b/src/hooks/useAutocompleteSuggestions.ts index 34e005d8d36d..f15afa394c5c 100644 --- a/src/hooks/useAutocompleteSuggestions.ts +++ b/src/hooks/useAutocompleteSuggestions.ts @@ -133,7 +133,9 @@ function useAutocompleteSuggestions({ const {exportedToFilterOptions} = useExportedToFilterOptions(); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); - const parsedQuery = parseForAutocomplete(autocompleteQueryValue); + // A blank query can't produce an autocomplete key, so don't pay for the parser + // (or its first-use module evaluation) until the user actually types something. + const parsedQuery = autocompleteQueryValue.trim() ? parseForAutocomplete(autocompleteQueryValue) : undefined; const {autocomplete, ranges = []} = parsedQuery ?? {}; let autocompleteKey = autocomplete?.key; From 3d1e807728d099f1b04c50666afc5ceb6f4e9779 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 11 Aug 2026 12:14:37 +0200 Subject: [PATCH 03/15] Cache attachment-message parse results by HTML --- src/libs/isReportMessageAttachment.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/libs/isReportMessageAttachment.ts b/src/libs/isReportMessageAttachment.ts index 8b38d6fa9296..de196cc94ccb 100644 --- a/src/libs/isReportMessageAttachment.ts +++ b/src/libs/isReportMessageAttachment.ts @@ -10,6 +10,11 @@ const ATTACHMENT_SOURCE_TOKEN = ` ${CONST.ATTACHMENT_SOURCE_ATTRIBUTE}="`; // Keyed by Onyx message identity: re-renders pass the same immutable object, so parse at most once per message. const resultCache = new WeakMap(); +// Second-level cache keyed by the HTML itself: Onyx merges produce fresh Message objects for unchanged +// content (which misses the WeakMap), and the parse result is a pure function of the HTML. +const PARSE_RESULT_CACHE_MAX_ENTRIES = 2000; +const parseResultCache = new Map(); + function computeIsReportMessageAttachment(html: string, text: string, translationKey: string | undefined): boolean { // Optimistic attachment-only messages carry this translationKey; the server drops it after sync. if (translationKey === CONST.TRANSLATION_KEYS.ATTACHMENT) { @@ -26,6 +31,11 @@ function computeIsReportMessageAttachment(html: string, text: string, translatio return true; } + const cachedParseResult = parseResultCache.get(html); + if (cachedParseResult !== undefined) { + return cachedParseResult; + } + let hasAttachment = false; let hasOtherContent = false; // Depth >0 = inside the attachment's subtree; its inner nodes (filename/markup) aren't user content. @@ -65,7 +75,12 @@ function computeIsReportMessageAttachment(html: string, text: string, translatio parser.write(html); parser.end(); - return hasAttachment && !hasOtherContent; + const result = hasAttachment && !hasOtherContent; + if (parseResultCache.size >= PARSE_RESULT_CACHE_MAX_ENTRIES) { + parseResultCache.clear(); + } + parseResultCache.set(html, result); + return result; } /** From 50f95338cea46b1052b76cb3884a39278eb1bd0d Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 11 Aug 2026 12:14:38 +0200 Subject: [PATCH 04/15] Warm the SearchRouter open path while the app is idle --- .../Search/SearchAutocompleteList.tsx | 2 +- .../SearchRouterOptionsWarmer.tsx | 40 +++++++++++++++ .../SearchRouter/SearchRouterWarmup.tsx | 51 +++++++++++++++++++ .../Navigation/AppNavigator/AuthScreens.tsx | 2 + 4 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx create mode 100644 src/components/Search/SearchRouter/SearchRouterWarmup.tsx diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index dbc888bf738c..2d76592645fd 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -722,5 +722,5 @@ function SearchAutocompleteList({ SearchAutocompleteList.displayName = 'SearchAutocompleteList'; export default React.memo(SearchAutocompleteList); -export {SearchRouterItem}; +export {SearchRouterItem, INITIAL_MAX_RECENT_REPORTS, RECENT_REPORTS_BATCH_SIZE}; export type {GetAdditionalSectionsCallback, SearchAutocompleteListProps}; diff --git a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx new file mode 100644 index 000000000000..75f0fded28ca --- /dev/null +++ b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx @@ -0,0 +1,40 @@ +import {INITIAL_MAX_RECENT_REPORTS, RECENT_REPORTS_BATCH_SIZE} from '@components/Search/SearchAutocompleteList'; + +import useFilteredOptions from '@hooks/useFilteredOptions'; + +import {useEffect} from 'react'; + +type SearchRouterOptionsWarmerProps = { + /** Called once the option list has been computed and cached; the parent unmounts this component then. */ + onDone: () => void; +}; + +/** + * Computes the SearchRouter's empty-query option list ahead of time so the first open of the + * session hits the module-level cache in `createFilteredOptionList` instead of building it on + * the critical path. The config must stay identical to the `useFilteredOptions` call in + * SearchAutocompleteList — the cache is keyed by it (and by the input references, which these + * hooks resolve from the same Onyx sources). + */ +function SearchRouterOptionsWarmer({onDone}: SearchRouterOptionsWarmerProps) { + const {options} = useFilteredOptions({ + enabled: true, + isSearching: false, + deferContactsUntilSearch: true, + maxRecentReports: INITIAL_MAX_RECENT_REPORTS, + batchSize: RECENT_REPORTS_BATCH_SIZE, + }); + + useEffect(() => { + if (!options) { + return; + } + onDone(); + }, [options, onDone]); + + return null; +} + +SearchRouterOptionsWarmer.displayName = 'SearchRouterOptionsWarmer'; + +export default SearchRouterOptionsWarmer; diff --git a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx new file mode 100644 index 000000000000..07a317cd81a1 --- /dev/null +++ b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx @@ -0,0 +1,51 @@ +import {getSpan} from '@libs/telemetry/activeSpans'; + +import CONST from '@src/CONST'; + +import type {ComponentType} from 'react'; + +import {useEffect, useState} from 'react'; + +type OptionsWarmerProps = { + onDone: () => void; +}; + +// Give the post-launch work (OpenApp/Reconnect processing, derived recomputes) time to drain +// before touching anything, so the warmup never competes with startup or an early user action. +const WARMUP_DELAY_MS = 15000; + +/** + * Warms the SearchRouter open path while the app is idle: + * - evaluates the SearchRouterPage and RightModalNavigator module graphs, moving their first-use + * cost (module factories, generated parsers) off the first search-open of the session; + * - mounts SearchRouterOptionsWarmer once, so the empty-query option list is computed and cached + * ahead of that first open. The warmer unmounts as soon as the list is cached, so no live + * subscription keeps recomputing afterwards. + */ +function SearchRouterWarmup() { + const [OptionsWarmer, setOptionsWarmer] = useState | null>(null); + const [isWarmupDone, setIsWarmupDone] = useState(false); + + useEffect(() => { + const id = setTimeout(() => { + // The router is already opening or open — it is paying these costs right now anyway. + if (getSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER)) { + return; + } + require('@components/Search/SearchRouter/SearchRouterPage'); + require('@libs/Navigation/AppNavigator/Navigators/RightModalNavigator'); + setOptionsWarmer(() => require<{default: ComponentType}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default); + }, WARMUP_DELAY_MS); + return () => clearTimeout(id); + }, []); + + if (!OptionsWarmer || isWarmupDone) { + return null; + } + + return setIsWarmupDone(true)} />; +} + +SearchRouterWarmup.displayName = 'SearchRouterWarmup'; + +export default SearchRouterWarmup; diff --git a/src/libs/Navigation/AppNavigator/AuthScreens.tsx b/src/libs/Navigation/AppNavigator/AuthScreens.tsx index d33ff7a10b95..d647fa9ee3b4 100644 --- a/src/libs/Navigation/AppNavigator/AuthScreens.tsx +++ b/src/libs/Navigation/AppNavigator/AuthScreens.tsx @@ -13,6 +13,7 @@ import {ProductTrainingContextProvider} from '@components/ProductTrainingContext import {SearchContextProvider} from '@components/Search/SearchContextProvider'; import {SearchRouterContextProvider} from '@components/Search/SearchRouter/SearchRouterContext'; import SearchRouterModal from '@components/Search/SearchRouter/SearchRouterModal'; +import SearchRouterWarmup from '@components/Search/SearchRouter/SearchRouterWarmup'; import SupportalPermissionDeniedModal from '@components/SupportalPermissionDeniedModal'; import FullScreenContextProvider from '@components/VideoPlayerContexts/FullScreenContextProvider'; import {PlaybackContextProvider} from '@components/VideoPlayerContexts/PlaybackContext'; @@ -164,6 +165,7 @@ function AuthScreens() { return ( <> + From ff7c1935aa840bfdcd63f97a7f3ef731cf70af8c Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Wed, 12 Aug 2026 15:54:45 +0200 Subject: [PATCH 05/15] Warm the SearchRouter on real signals instead of a fixed delay Replace the 15s timer in SearchRouterWarmup with the state it was approximating: wait for OpenApp to be applied, then for an idle window on the JS thread via Scheduler.scheduleWhenIdle. Build the option list only once its Onyx inputs hold still across a full idle window. createFilteredOptionList keys its cache on the identity of those inputs, so a list built while post-launch writes are still landing is discarded before the user can open the router. A connectWithoutView counter tracks that churn without rendering or rebuilding anything, and a cap on the number of idle windows keeps a chatty account from postponing the build forever. Module evaluation is unaffected by Onyx writes, so it still happens in the first idle window. Also: - evict the attachment-parse cache LRU instead of clearing every entry at the cap - share the useFilteredOptions config between SearchAutocompleteList and SearchRouterOptionsWarmer so the cache key cannot drift apart - share the SearchRouterPage/RightModalNavigator require paths between AuthScreens and the warmup - pick the empty-search predicate once per getValidOptions call instead of testing for it per report --- .../Search/SearchAutocompleteList.tsx | 21 ++-- .../SearchRouterOptionsWarmer.tsx | 13 +- .../SearchRouter/SearchRouterWarmup.tsx | 116 +++++++++++++++--- .../Navigation/AppNavigator/AuthScreens.tsx | 4 +- .../AppNavigator/searchRouterLazyLoaders.ts | 9 ++ src/libs/OptionsListUtils/index.ts | 9 +- src/libs/isReportMessageAttachment.ts | 9 +- 7 files changed, 142 insertions(+), 39 deletions(-) create mode 100644 src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index 2d76592645fd..0f149d7b96ab 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -111,6 +111,18 @@ const EMPTY_RANK_MAP: ReadonlyMap = new Map(); const INITIAL_MAX_RECENT_REPORTS = 100; const RECENT_REPORTS_BATCH_SIZE = 500; +// Shared with SearchRouterOptionsWarmer, which pre-builds the same option list while the app is idle. +// createFilteredOptionList keys its cache on these values, so keeping them in one place stops the two +// call sites from drifting apart and silently building an entry the other one never reads. +// deferContactsUntilSearch is true because the empty-query state renders only recent searches and +// recent reports (no standalone contacts), so contacts can wait until the user types a query. +const SEARCH_ROUTER_OPTIONS_CONFIG = { + enabled: true, + deferContactsUntilSearch: true, + maxRecentReports: INITIAL_MAX_RECENT_REPORTS, + batchSize: RECENT_REPORTS_BATCH_SIZE, +} as const; + // A DM's keyForList changes from the accountID to the reportID once its report loads from search, which would move the // row between sections. To keep it stable, key DMs and personal details by accountID instead. We can't do this for every // account-backed option though: task/expense reports also carry an accountID, and keying them by it would let them @@ -222,13 +234,8 @@ function SearchAutocompleteList({ loadAll: loadAllRecentReports, hasMore: hasMoreRecentReports, } = useFilteredOptions({ - enabled: true, + ...SEARCH_ROUTER_OPTIONS_CONFIG, isSearching: !!autocompleteQueryValue.trim(), - // The empty-query state renders only recent searches and recent reports (no standalone contacts), - // so contacts can be deferred until the user types a query. - deferContactsUntilSearch: true, - maxRecentReports: INITIAL_MAX_RECENT_REPORTS, - batchSize: RECENT_REPORTS_BATCH_SIZE, }); const isRecentSearchesDataLoaded = !isLoadingOnyxValue(recentSearchesMetadata); @@ -722,5 +729,5 @@ function SearchAutocompleteList({ SearchAutocompleteList.displayName = 'SearchAutocompleteList'; export default React.memo(SearchAutocompleteList); -export {SearchRouterItem, INITIAL_MAX_RECENT_REPORTS, RECENT_REPORTS_BATCH_SIZE}; +export {SearchRouterItem, SEARCH_ROUTER_OPTIONS_CONFIG}; export type {GetAdditionalSectionsCallback, SearchAutocompleteListProps}; diff --git a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx index 75f0fded28ca..41cdf09c2146 100644 --- a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx +++ b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx @@ -1,4 +1,4 @@ -import {INITIAL_MAX_RECENT_REPORTS, RECENT_REPORTS_BATCH_SIZE} from '@components/Search/SearchAutocompleteList'; +import {SEARCH_ROUTER_OPTIONS_CONFIG} from '@components/Search/SearchAutocompleteList'; import useFilteredOptions from '@hooks/useFilteredOptions'; @@ -12,17 +12,14 @@ type SearchRouterOptionsWarmerProps = { /** * Computes the SearchRouter's empty-query option list ahead of time so the first open of the * session hits the module-level cache in `createFilteredOptionList` instead of building it on - * the critical path. The config must stay identical to the `useFilteredOptions` call in - * SearchAutocompleteList — the cache is keyed by it (and by the input references, which these - * hooks resolve from the same Onyx sources). + * the critical path. Reuses SEARCH_ROUTER_OPTIONS_CONFIG from SearchAutocompleteList (plus + * `isSearching: false` for the empty-query state) so the cache key cannot drift between the two + * call sites — the cache is keyed by it, and by the identity of the Onyx data these hooks read. */ function SearchRouterOptionsWarmer({onDone}: SearchRouterOptionsWarmerProps) { const {options} = useFilteredOptions({ - enabled: true, + ...SEARCH_ROUTER_OPTIONS_CONFIG, isSearching: false, - deferContactsUntilSearch: true, - maxRecentReports: INITIAL_MAX_RECENT_REPORTS, - batchSize: RECENT_REPORTS_BATCH_SIZE, }); useEffect(() => { diff --git a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx index 07a317cd81a1..8b70a09bdcba 100644 --- a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx +++ b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx @@ -1,43 +1,129 @@ +import useOnyx from '@hooks/useOnyx'; + +import {loadRightModalNavigator, loadSearchRouterPage} from '@libs/Navigation/AppNavigator/searchRouterLazyLoaders'; +import {Scheduler} from '@libs/Scheduler'; +import type {IdleTask} from '@libs/Scheduler'; import {getSpan} from '@libs/telemetry/activeSpans'; import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; import type {ComponentType} from 'react'; import {useEffect, useState} from 'react'; +import Onyx from 'react-native-onyx'; type OptionsWarmerProps = { onDone: () => void; }; -// Give the post-launch work (OpenApp/Reconnect processing, derived recomputes) time to drain -// before touching anything, so the warmup never competes with startup or an early user action. -const WARMUP_DELAY_MS = 15000; +// The option list is only worth building while its inputs hold still, but a chatty account can keep +// writing forever, so stop rescheduling after this many idle windows and build with what we have. +const MAX_QUIET_WAIT_ATTEMPTS = 5; + +/** + * Counts writes to the Onyx data the option-list cache is keyed on. `connectWithoutView` rather than + * `useOnyx` because this must not render or build anything: it only answers "are the inputs still + * settling?", and a subscribed component would rebuild the whole option list on every write. + * The connections live only for the duration of the warmup. + */ +function startTrackingInputChurn(): {getVersion: () => number; stop: () => void} { + let version = 0; + // Collection root keys hand the whole collection to the callback on any member change, so this + // fires once per write batch rather than once per report. + const bump = () => { + version += 1; + }; + const connections = [ + Onyx.connectWithoutView({key: ONYXKEYS.COLLECTION.REPORT, callback: bump}), + Onyx.connectWithoutView({key: ONYXKEYS.COLLECTION.POLICY, callback: bump}), + Onyx.connectWithoutView({key: ONYXKEYS.PERSONAL_DETAILS_LIST, callback: bump}), + Onyx.connectWithoutView({key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, callback: bump}), + Onyx.connectWithoutView({key: ONYXKEYS.DERIVED.RAM_ONLY_SORTED_REPORT_ACTIONS, callback: bump}), + ]; + + return { + getVersion: () => version, + stop: () => { + for (const connection of connections) { + Onyx.disconnect(connection); + } + }, + }; +} /** - * Warms the SearchRouter open path while the app is idle: + * Warms the SearchRouter open path once the app has settled: * - evaluates the SearchRouterPage and RightModalNavigator module graphs, moving their first-use * cost (module factories, generated parsers) off the first search-open of the session; * - mounts SearchRouterOptionsWarmer once, so the empty-query option list is computed and cached * ahead of that first open. The warmer unmounts as soon as the list is cached, so no live * subscription keeps recomputing afterwards. + * + * Both steps wait for OpenApp to be applied (`isLoadingApp === false`) and then for an idle window on + * the JS thread, so they never compete with startup or with an early user action. The option list + * additionally waits for its Onyx inputs to hold still across a full idle window, because + * `createFilteredOptionList` keys its cache on their identity — a list built while post-launch writes + * are still landing is thrown away before the user can open the router. */ function SearchRouterWarmup() { + const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); const [OptionsWarmer, setOptionsWarmer] = useState | null>(null); const [isWarmupDone, setIsWarmupDone] = useState(false); useEffect(() => { - const id = setTimeout(() => { - // The router is already opening or open — it is paying these costs right now anyway. - if (getSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER)) { - return; - } - require('@components/Search/SearchRouter/SearchRouterPage'); - require('@libs/Navigation/AppNavigator/Navigators/RightModalNavigator'); - setOptionsWarmer(() => require<{default: ComponentType}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default); - }, WARMUP_DELAY_MS); - return () => clearTimeout(id); - }, []); + if (isLoadingApp !== false) { + return; + } + + let isCancelled = false; + let task: IdleTask | undefined; + let attempts = 0; + let lastSeenChurn = -1; + let areModulesLoaded = false; + const churn = startTrackingInputChurn(); + + const stop = () => { + isCancelled = true; + task?.cancel(); + churn.stop(); + }; + + const warmWhenIdle = () => { + task = Scheduler.scheduleWhenIdle(() => { + if (isCancelled) { + return; + } + + // The router is already opening or open — it is paying these costs right now anyway. + if (getSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER)) { + stop(); + return; + } + + // Module evaluation is unaffected by Onyx writes, so it never needs to wait for quiet. + if (!areModulesLoaded) { + areModulesLoaded = true; + loadSearchRouterPage(); + loadRightModalNavigator(); + } + + const currentChurn = churn.getVersion(); + if (currentChurn !== lastSeenChurn && attempts < MAX_QUIET_WAIT_ATTEMPTS) { + lastSeenChurn = currentChurn; + attempts += 1; + warmWhenIdle(); + return; + } + + setOptionsWarmer(() => require<{default: ComponentType}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default); + stop(); + }); + }; + + warmWhenIdle(); + return stop; + }, [isLoadingApp]); if (!OptionsWarmer || isWarmupDone) { return null; diff --git a/src/libs/Navigation/AppNavigator/AuthScreens.tsx b/src/libs/Navigation/AppNavigator/AuthScreens.tsx index d647fa9ee3b4..9f674c2f27d8 100644 --- a/src/libs/Navigation/AppNavigator/AuthScreens.tsx +++ b/src/libs/Navigation/AppNavigator/AuthScreens.tsx @@ -71,6 +71,7 @@ import MultifactorAuthenticationModalNavigator from './Navigators/MultifactorAut import OnboardingModalNavigator from './Navigators/OnboardingModalNavigator'; import SubmitPlanWelcomeModalNavigator from './Navigators/SubmitPlanWelcomeModalNavigator'; import TestToolsModalNavigator from './Navigators/TestToolsModalNavigator'; +import {loadRightModalNavigator, loadSearchRouterPage} from './searchRouterLazyLoaders'; import TestDriveDemoNavigator from './TestDriveDemoNavigator'; import ThreeDSAuthHandler from './ThreeDSAuthHandler'; import useModalCardStyleInterpolator from './useModalCardStyleInterpolator'; @@ -87,9 +88,6 @@ const loadTrackExpensePage = () => require('../../../pages const loadSubmitExpensePage = () => require('../../../pages/SubmitExpensePage').default; const loadWorkspaceJoinUser = () => require('@pages/workspace/WorkspaceJoinUserPage').default; -const loadSearchRouterPage = () => require('../../../components/Search/SearchRouter/SearchRouterPage').default; -const loadRightModalNavigator = () => require('./Navigators/RightModalNavigator').default; - const RootStack = createRootStackNavigator(); // We want to delay the re-rendering for components(e.g. ReportActionCompose) diff --git a/src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts b/src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts new file mode 100644 index 000000000000..27ea22e0f6c0 --- /dev/null +++ b/src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts @@ -0,0 +1,9 @@ +import type ReactComponentModule from '@src/types/utils/ReactComponentModule'; + +// Shared between AuthScreens (registers these as the real lazy-loaded screens) and SearchRouterWarmup +// (evaluates the same modules ahead of time while the app is idle). Kept in one place so the two stay +// in sync instead of duplicating the require paths. +const loadSearchRouterPage = () => require('../../../components/Search/SearchRouter/SearchRouterPage').default; +const loadRightModalNavigator = () => require('./Navigators/RightModalNavigator').default; + +export {loadSearchRouterPage, loadRightModalNavigator}; diff --git a/src/libs/OptionsListUtils/index.ts b/src/libs/OptionsListUtils/index.ts index 2bb2d284c454..fbc835e8c36c 100644 --- a/src/libs/OptionsListUtils/index.ts +++ b/src/libs/OptionsListUtils/index.ts @@ -2731,11 +2731,9 @@ function getValidOptions( const isWorkspaceChat = (report: SearchOption) => shouldSeparateWorkspaceChat && report.isPolicyExpenseChat && !report.private_isArchived; const isSelfDMChat = (report: SearchOption) => shouldSeparateSelfDMChat && report.isSelfDM && !report.private_isArchived; - const isSearchTermsFound = (report: SearchOption) => { - // An empty search matches every report, so skip building and normalizing the search text. - if (searchTerms.length === 0) { - return true; - } + // An empty search matches every report, so skip building and normalizing the search text + // entirely rather than testing for it once per report. + const matchesEverySearchTerm = (report: SearchOption) => { let searchText = `${report.text ?? ''}${report.login ?? ''}`; if (report.isThread) { searchText += report.alternateText ?? ''; @@ -2750,6 +2748,7 @@ function getValidOptions( searchText = deburr(searchText.toLocaleLowerCase()); return searchTerms.every((term) => searchText.includes(term)); }; + const isSearchTermsFound = searchTerms.length === 0 ? () => true : matchesEverySearchTerm; const filteringFunction = (report: SearchOption) => { if (excludeHidden) { diff --git a/src/libs/isReportMessageAttachment.ts b/src/libs/isReportMessageAttachment.ts index de196cc94ccb..6d4a9e6d6219 100644 --- a/src/libs/isReportMessageAttachment.ts +++ b/src/libs/isReportMessageAttachment.ts @@ -12,6 +12,8 @@ const resultCache = new WeakMap(); // Second-level cache keyed by the HTML itself: Onyx merges produce fresh Message objects for unchanged // content (which misses the WeakMap), and the parse result is a pure function of the HTML. +// LRU by Map insertion order: a hit re-inserts its key so it sorts last, and eviction below drops the +// first (least-recently-used) key, so the cache never loses every entry at once the way clear() would. const PARSE_RESULT_CACHE_MAX_ENTRIES = 2000; const parseResultCache = new Map(); @@ -33,6 +35,8 @@ function computeIsReportMessageAttachment(html: string, text: string, translatio const cachedParseResult = parseResultCache.get(html); if (cachedParseResult !== undefined) { + parseResultCache.delete(html); + parseResultCache.set(html, cachedParseResult); return cachedParseResult; } @@ -77,7 +81,10 @@ function computeIsReportMessageAttachment(html: string, text: string, translatio const result = hasAttachment && !hasOtherContent; if (parseResultCache.size >= PARSE_RESULT_CACHE_MAX_ENTRIES) { - parseResultCache.clear(); + const oldestKey = parseResultCache.keys().next().value; + if (oldestKey !== undefined) { + parseResultCache.delete(oldestKey); + } } parseResultCache.set(html, result); return result; From d42684e63ba66f6175bd2424213358f5d795f28b Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Wed, 12 Aug 2026 16:28:39 +0200 Subject: [PATCH 06/15] Drop the attachment-message HTML parse cache Measured on the SearchRouter open path with the changes stacked one at a time (Android emulator, high-traffic account, 3 cold opens per state): adding this cache moved the median from 1840ms to 1936ms, i.e. no gain, with the run ranges fully overlapping. The reason is visible in the data: the cache lookup sits behind the `data-expensify-source` fast path, and on the test account only 4 of 635 reports carry that attribute, so the parser barely runs on this path at all. Keeping the cache would mean retaining message HTML strings for a saving that does not exist here. If it is worth having, it belongs in a change aimed at the report view, justified by measurements of that path. --- src/libs/isReportMessageAttachment.ts | 24 +----------------------- 1 file changed, 1 insertion(+), 23 deletions(-) diff --git a/src/libs/isReportMessageAttachment.ts b/src/libs/isReportMessageAttachment.ts index 6d4a9e6d6219..8b38d6fa9296 100644 --- a/src/libs/isReportMessageAttachment.ts +++ b/src/libs/isReportMessageAttachment.ts @@ -10,13 +10,6 @@ const ATTACHMENT_SOURCE_TOKEN = ` ${CONST.ATTACHMENT_SOURCE_ATTRIBUTE}="`; // Keyed by Onyx message identity: re-renders pass the same immutable object, so parse at most once per message. const resultCache = new WeakMap(); -// Second-level cache keyed by the HTML itself: Onyx merges produce fresh Message objects for unchanged -// content (which misses the WeakMap), and the parse result is a pure function of the HTML. -// LRU by Map insertion order: a hit re-inserts its key so it sorts last, and eviction below drops the -// first (least-recently-used) key, so the cache never loses every entry at once the way clear() would. -const PARSE_RESULT_CACHE_MAX_ENTRIES = 2000; -const parseResultCache = new Map(); - function computeIsReportMessageAttachment(html: string, text: string, translationKey: string | undefined): boolean { // Optimistic attachment-only messages carry this translationKey; the server drops it after sync. if (translationKey === CONST.TRANSLATION_KEYS.ATTACHMENT) { @@ -33,13 +26,6 @@ function computeIsReportMessageAttachment(html: string, text: string, translatio return true; } - const cachedParseResult = parseResultCache.get(html); - if (cachedParseResult !== undefined) { - parseResultCache.delete(html); - parseResultCache.set(html, cachedParseResult); - return cachedParseResult; - } - let hasAttachment = false; let hasOtherContent = false; // Depth >0 = inside the attachment's subtree; its inner nodes (filename/markup) aren't user content. @@ -79,15 +65,7 @@ function computeIsReportMessageAttachment(html: string, text: string, translatio parser.write(html); parser.end(); - const result = hasAttachment && !hasOtherContent; - if (parseResultCache.size >= PARSE_RESULT_CACHE_MAX_ENTRIES) { - const oldestKey = parseResultCache.keys().next().value; - if (oldestKey !== undefined) { - parseResultCache.delete(oldestKey); - } - } - parseResultCache.set(html, result); - return result; + return hasAttachment && !hasOtherContent; } /** From 2a79e79ee6e8182240d4264b27429769a690c12a Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Wed, 12 Aug 2026 16:28:47 +0200 Subject: [PATCH 07/15] Drop the empty-search text-normalization skip Same stacked measurement as the previous commit: adding this step moved the median from 1957ms (main) to 1985ms, with the run ranges fully overlapping main's, so it buys nothing on the SearchRouter open path. Building and deburring the search text for an empty query is genuinely redundant, but at this size it does not show up next to the option-list build that dominates the open, so it is not worth the review surface in a perf PR. --- src/libs/OptionsListUtils/index.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/libs/OptionsListUtils/index.ts b/src/libs/OptionsListUtils/index.ts index fbc835e8c36c..5b91b5364f86 100644 --- a/src/libs/OptionsListUtils/index.ts +++ b/src/libs/OptionsListUtils/index.ts @@ -2731,9 +2731,7 @@ function getValidOptions( const isWorkspaceChat = (report: SearchOption) => shouldSeparateWorkspaceChat && report.isPolicyExpenseChat && !report.private_isArchived; const isSelfDMChat = (report: SearchOption) => shouldSeparateSelfDMChat && report.isSelfDM && !report.private_isArchived; - // An empty search matches every report, so skip building and normalizing the search text - // entirely rather than testing for it once per report. - const matchesEverySearchTerm = (report: SearchOption) => { + const isSearchTermsFound = (report: SearchOption) => { let searchText = `${report.text ?? ''}${report.login ?? ''}`; if (report.isThread) { searchText += report.alternateText ?? ''; @@ -2748,7 +2746,6 @@ function getValidOptions( searchText = deburr(searchText.toLocaleLowerCase()); return searchTerms.every((term) => searchText.includes(term)); }; - const isSearchTermsFound = searchTerms.length === 0 ? () => true : matchesEverySearchTerm; const filteringFunction = (report: SearchOption) => { if (excludeHidden) { From e7f08dad02c35268e615f1953090126bc499e348 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Wed, 12 Aug 2026 16:57:40 +0200 Subject: [PATCH 08/15] Trim the comments in the SearchRouter warmup changes --- .../Search/SearchAutocompleteList.tsx | 7 ++-- .../SearchRouterOptionsWarmer.tsx | 9 ++---- .../SearchRouter/SearchRouterWarmup.tsx | 32 ++++++------------- src/hooks/useAutocompleteSuggestions.ts | 3 +- .../AppNavigator/searchRouterLazyLoaders.ts | 4 +-- 5 files changed, 17 insertions(+), 38 deletions(-) diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index 0f149d7b96ab..e028cfb1bbb7 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -111,11 +111,8 @@ const EMPTY_RANK_MAP: ReadonlyMap = new Map(); const INITIAL_MAX_RECENT_REPORTS = 100; const RECENT_REPORTS_BATCH_SIZE = 500; -// Shared with SearchRouterOptionsWarmer, which pre-builds the same option list while the app is idle. -// createFilteredOptionList keys its cache on these values, so keeping them in one place stops the two -// call sites from drifting apart and silently building an entry the other one never reads. -// deferContactsUntilSearch is true because the empty-query state renders only recent searches and -// recent reports (no standalone contacts), so contacts can wait until the user types a query. +// Shared with SearchRouterOptionsWarmer: createFilteredOptionList keys its cache on these values, so +// the two call sites must not drift. Contacts can be deferred because the empty-query state shows none. const SEARCH_ROUTER_OPTIONS_CONFIG = { enabled: true, deferContactsUntilSearch: true, diff --git a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx index 41cdf09c2146..b015cc575654 100644 --- a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx +++ b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx @@ -5,16 +5,13 @@ import useFilteredOptions from '@hooks/useFilteredOptions'; import {useEffect} from 'react'; type SearchRouterOptionsWarmerProps = { - /** Called once the option list has been computed and cached; the parent unmounts this component then. */ + /** Called once the option list is cached, so the parent can unmount this component. */ onDone: () => void; }; /** - * Computes the SearchRouter's empty-query option list ahead of time so the first open of the - * session hits the module-level cache in `createFilteredOptionList` instead of building it on - * the critical path. Reuses SEARCH_ROUTER_OPTIONS_CONFIG from SearchAutocompleteList (plus - * `isSearching: false` for the empty-query state) so the cache key cannot drift between the two - * call sites — the cache is keyed by it, and by the identity of the Onyx data these hooks read. + * Builds the SearchRouter's empty-query option list so the first open of the session hits + * `createFilteredOptionList`'s cache instead of building it on the critical path. */ function SearchRouterOptionsWarmer({onDone}: SearchRouterOptionsWarmerProps) { const {options} = useFilteredOptions({ diff --git a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx index 8b70a09bdcba..944efc3aa3fe 100644 --- a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx +++ b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx @@ -17,20 +17,15 @@ type OptionsWarmerProps = { onDone: () => void; }; -// The option list is only worth building while its inputs hold still, but a chatty account can keep -// writing forever, so stop rescheduling after this many idle windows and build with what we have. +// Stop waiting for quiet after this many idle windows; a chatty account never fully stops writing. const MAX_QUIET_WAIT_ATTEMPTS = 5; /** - * Counts writes to the Onyx data the option-list cache is keyed on. `connectWithoutView` rather than - * `useOnyx` because this must not render or build anything: it only answers "are the inputs still - * settling?", and a subscribed component would rebuild the whole option list on every write. - * The connections live only for the duration of the warmup. + * Counts writes to the Onyx data the option-list cache is keyed on. `connectWithoutView` because a + * subscribed component would rebuild the whole option list on every write; this only counts. */ function startTrackingInputChurn(): {getVersion: () => number; stop: () => void} { let version = 0; - // Collection root keys hand the whole collection to the callback on any member change, so this - // fires once per write batch rather than once per report. const bump = () => { version += 1; }; @@ -53,18 +48,11 @@ function startTrackingInputChurn(): {getVersion: () => number; stop: () => void} } /** - * Warms the SearchRouter open path once the app has settled: - * - evaluates the SearchRouterPage and RightModalNavigator module graphs, moving their first-use - * cost (module factories, generated parsers) off the first search-open of the session; - * - mounts SearchRouterOptionsWarmer once, so the empty-query option list is computed and cached - * ahead of that first open. The warmer unmounts as soon as the list is cached, so no live - * subscription keeps recomputing afterwards. - * - * Both steps wait for OpenApp to be applied (`isLoadingApp === false`) and then for an idle window on - * the JS thread, so they never compete with startup or with an early user action. The option list - * additionally waits for its Onyx inputs to hold still across a full idle window, because - * `createFilteredOptionList` keys its cache on their identity — a list built while post-launch writes - * are still landing is thrown away before the user can open the router. + * Moves the first search-open of the session off the critical path: evaluates the SearchRouterPage and + * RightModalNavigator module graphs, then mounts SearchRouterOptionsWarmer to build the empty-query + * option list into `createFilteredOptionList`'s cache. Runs after OpenApp is applied and the JS thread + * is idle. The option list also waits for its Onyx inputs to hold still, because the cache is keyed on + * their identity and a list built mid-write is discarded. */ function SearchRouterWarmup() { const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); @@ -95,13 +83,13 @@ function SearchRouterWarmup() { return; } - // The router is already opening or open — it is paying these costs right now anyway. + // Already opening or open, so these costs are being paid live. if (getSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER)) { stop(); return; } - // Module evaluation is unaffected by Onyx writes, so it never needs to wait for quiet. + // Unaffected by Onyx writes, so no need to wait for quiet. if (!areModulesLoaded) { areModulesLoaded = true; loadSearchRouterPage(); diff --git a/src/hooks/useAutocompleteSuggestions.ts b/src/hooks/useAutocompleteSuggestions.ts index f15afa394c5c..30d8e2353627 100644 --- a/src/hooks/useAutocompleteSuggestions.ts +++ b/src/hooks/useAutocompleteSuggestions.ts @@ -133,8 +133,7 @@ function useAutocompleteSuggestions({ const {exportedToFilterOptions} = useExportedToFilterOptions(); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); - // A blank query can't produce an autocomplete key, so don't pay for the parser - // (or its first-use module evaluation) until the user actually types something. + // A blank query can't produce an autocomplete key, so skip the parser and its module evaluation. const parsedQuery = autocompleteQueryValue.trim() ? parseForAutocomplete(autocompleteQueryValue) : undefined; const {autocomplete, ranges = []} = parsedQuery ?? {}; diff --git a/src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts b/src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts index 27ea22e0f6c0..d147e6ec91c4 100644 --- a/src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts +++ b/src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts @@ -1,8 +1,6 @@ import type ReactComponentModule from '@src/types/utils/ReactComponentModule'; -// Shared between AuthScreens (registers these as the real lazy-loaded screens) and SearchRouterWarmup -// (evaluates the same modules ahead of time while the app is idle). Kept in one place so the two stay -// in sync instead of duplicating the require paths. +// Shared by AuthScreens (lazy screen registration) and SearchRouterWarmup (idle pre-evaluation). const loadSearchRouterPage = () => require('../../../components/Search/SearchRouter/SearchRouterPage').default; const loadRightModalNavigator = () => require('./Navigators/RightModalNavigator').default; From 3c32afa20a46b95a7a47a560f1c5a30f2fca065e Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Thu, 13 Aug 2026 10:04:53 +0200 Subject: [PATCH 09/15] Track warmup input churn through useOnyx and gate on an explicit open flag --- .../Search/SearchAutocompleteList.tsx | 22 +---- .../SearchRouter/SearchRouterContext.tsx | 25 ++++- .../SearchRouterOptionsWarmer.tsx | 67 ++++++++++++- .../SearchRouter/SearchRouterWarmup.tsx | 99 +++---------------- .../SearchRouter/searchRouterOptionsConfig.ts | 21 ++++ 5 files changed, 124 insertions(+), 110 deletions(-) create mode 100644 src/components/Search/SearchRouter/searchRouterOptionsConfig.ts diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index e028cfb1bbb7..cebf133328fe 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -54,6 +54,7 @@ import getAutocompleteInitialFocus from './getAutocompleteInitialFocus'; import AvatarWithTextCell from './SearchList/ListItem/AvatarWithTextCell'; import SearchQueryListItem, {isSearchQueryItem} from './SearchList/ListItem/SearchQueryListItem'; import {getSubstitutionMapKey} from './SearchRouter/getQueryWithSubstitutions'; +import SEARCH_ROUTER_OPTIONS_CONFIG from './SearchRouter/searchRouterOptionsConfig'; type AutocompleteListItem = NewListItem & Partial> & Partial>; @@ -101,25 +102,6 @@ const defaultListOptions = { const EMPTY_RANK_MAP: ReadonlyMap = new Map(); -// The list shows at most MAX_AMOUNT_OF_SUGGESTIONS recent reports, so building full option data for the -// default 500-report list every time is unnecessary. Start from a smaller raw cap and only expand to the -// full set if that batch filters down below the visible cap (see the loadAll effect below); typing a -// query bypasses this cap entirely (isSearching drops the limit in createFilteredOptionList). -// 100 leaves buffer for hidden/muted chats getting filtered out after the raw-recency slice. -// The batch size stays at 500 (not smaller) because createFilteredOptionList rebuilds its whole -// top-N slice from scratch each call, so a small batch would mean repeated rebuilds. -const INITIAL_MAX_RECENT_REPORTS = 100; -const RECENT_REPORTS_BATCH_SIZE = 500; - -// Shared with SearchRouterOptionsWarmer: createFilteredOptionList keys its cache on these values, so -// the two call sites must not drift. Contacts can be deferred because the empty-query state shows none. -const SEARCH_ROUTER_OPTIONS_CONFIG = { - enabled: true, - deferContactsUntilSearch: true, - maxRecentReports: INITIAL_MAX_RECENT_REPORTS, - batchSize: RECENT_REPORTS_BATCH_SIZE, -} as const; - // A DM's keyForList changes from the accountID to the reportID once its report loads from search, which would move the // row between sections. To keep it stable, key DMs and personal details by accountID instead. We can't do this for every // account-backed option though: task/expense reports also carry an accountID, and keying them by it would let them @@ -726,5 +708,5 @@ function SearchAutocompleteList({ SearchAutocompleteList.displayName = 'SearchAutocompleteList'; export default React.memo(SearchAutocompleteList); -export {SearchRouterItem, SEARCH_ROUTER_OPTIONS_CONFIG}; +export {SearchRouterItem}; export type {GetAdditionalSectionsCallback, SearchAutocompleteListProps}; diff --git a/src/components/Search/SearchRouter/SearchRouterContext.tsx b/src/components/Search/SearchRouter/SearchRouterContext.tsx index d3cc4dbd651d..be7d3f2e1496 100644 --- a/src/components/Search/SearchRouter/SearchRouterContext.tsx +++ b/src/components/Search/SearchRouter/SearchRouterContext.tsx @@ -7,7 +7,7 @@ import {close} from '@userActions/Modal'; import CONST from '@src/CONST'; import type ChildrenProps from '@src/types/utils/ChildrenProps'; -import React, {useContext, useRef, useState} from 'react'; +import React, {useContext, useEffect, useRef, useState} from 'react'; import {closeSearch, openSearch} from './toggleSearch'; @@ -27,6 +27,16 @@ function clearPendingRouterState() { export {peekPendingRouterState, clearPendingRouterState}; +// Mirrors whether the SearchRouter is open or mid-open at module level, so logic outside the provider +// tree (e.g. SearchRouterWarmup's idle callbacks) can check it without a context subscription. +let isSearchRouterOpenOrOpening = false; + +function getIsSearchRouterOpenOrOpening() { + return isSearchRouterOpenOrOpening; +} + +export {getIsSearchRouterOpenOrOpening}; + type SearchRouterStateContextType = { isSearchRouterDisplayed: boolean; }; @@ -55,6 +65,15 @@ function SearchRouterContextProvider({children}: ChildrenProps) { const [isSearchRouterDisplayed, setIsSearchRouterDisplayed] = useState(false); const searchRouterDisplayedRef = useRef(false); + // The provider unmounts on sign-out without going through closeSearchRouter, so reset the module-level + // flag to keep an open router from leaking the "open" state into the next session. + useEffect( + () => () => { + isSearchRouterOpenOrOpening = false; + }, + [], + ); + // Registers a browser-history entry when the SearchRouter is open, so browser Back closes it // and browser Forward (after Back) reopens it. Uses the same back-guard mechanism as other modals // rather than direct window.history calls, avoiding misalignment with other guard-tracked overlays. @@ -62,10 +81,12 @@ function SearchRouterContextProvider({children}: ChildrenProps) { isVisible: isSearchRouterDisplayed, shouldHandleNavigationBack: true, onClose: () => { + isSearchRouterOpenOrOpening = false; closeSearch(setIsSearchRouterDisplayed); searchRouterDisplayedRef.current = false; }, onOpen: () => { + isSearchRouterOpenOrOpening = true; openSearch(setIsSearchRouterDisplayed); searchRouterDisplayedRef.current = true; }, @@ -80,6 +101,7 @@ function SearchRouterContextProvider({children}: ChildrenProps) { }; const openSearchRouter = (query?: string, isFromSearchPageSearchButton?: boolean) => { + isSearchRouterOpenOrOpening = true; pendingRouterQuery = query ?? ''; pendingIsFromSearchPageSearchButton = isFromSearchPageSearchButton ?? false; startSpan(CONST.TELEMETRY.SPAN_SEARCH_ROUTER_MODAL_CLOSE_WAIT, { @@ -100,6 +122,7 @@ function SearchRouterContextProvider({children}: ChildrenProps) { }; const closeSearchRouter = (afterTransition?: () => void) => { + isSearchRouterOpenOrOpening = false; cancelSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER); cancelSpan(CONST.TELEMETRY.SPAN_SEARCH_ROUTER_MODAL_CLOSE_WAIT); cancelSpan(CONST.TELEMETRY.SPAN_SEARCH_PAGE_VISIBLE); diff --git a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx index b015cc575654..3072af2817b1 100644 --- a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx +++ b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx @@ -1,22 +1,79 @@ -import {SEARCH_ROUTER_OPTIONS_CONFIG} from '@components/Search/SearchAutocompleteList'; - import useFilteredOptions from '@hooks/useFilteredOptions'; +import useOnyx from '@hooks/useOnyx'; +import useReportAttributes from '@hooks/useReportAttributes'; +import useSortedActions from '@hooks/useSortedActions'; + +import {Scheduler} from '@libs/Scheduler'; +import type {IdleTask} from '@libs/Scheduler'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +import {useEffect, useRef, useState} from 'react'; -import {useEffect} from 'react'; +import {getIsSearchRouterOpenOrOpening} from './SearchRouterContext'; +import SEARCH_ROUTER_OPTIONS_CONFIG from './searchRouterOptionsConfig'; type SearchRouterOptionsWarmerProps = { - /** Called once the option list is cached, so the parent can unmount this component. */ + /** Called once the option list is cached (or the warm is no longer needed), so the parent can unmount this component. */ onDone: () => void; }; +// Stop waiting for quiet after this many idle windows; a chatty account never fully stops writing. +const MAX_QUIET_WAIT_ATTEMPTS = 5; + /** * Builds the SearchRouter's empty-query option list so the first open of the session hits - * `createFilteredOptionList`'s cache instead of building it on the critical path. + * `createFilteredOptionList`'s cache instead of building it on the critical path. The build waits until + * the list's Onyx inputs hold still across idle windows, because the cache is keyed on the identity of + * the `useOnyx` snapshots and a list built mid-write is discarded. */ function SearchRouterOptionsWarmer({onDone}: SearchRouterOptionsWarmerProps) { + const [shouldBuild, setShouldBuild] = useState(false); + + // The high-churn inputs of the option-list cache, read through the same `useOnyx` layer that keys it. + const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); + const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); + const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); + const reportAttributes = useReportAttributes(); + const sortedActions = useSortedActions(); + + const churnVersionRef = useRef(0); + useEffect(() => { + churnVersionRef.current += 1; + }, [reports, policies, personalDetails, reportAttributes, sortedActions]); + + useEffect(() => { + let attempts = 0; + let lastSeenChurn = -1; + let task: IdleTask | undefined; + + const waitForQuiet = () => { + task = Scheduler.scheduleWhenIdle(() => { + // The real screen builds (and caches) the list itself, so warming would only compete with it. + if (getIsSearchRouterOpenOrOpening()) { + onDone(); + return; + } + + if (churnVersionRef.current !== lastSeenChurn && attempts < MAX_QUIET_WAIT_ATTEMPTS) { + lastSeenChurn = churnVersionRef.current; + attempts += 1; + waitForQuiet(); + return; + } + + setShouldBuild(true); + }); + }; + + waitForQuiet(); + return () => task?.cancel(); + }, [onDone]); + const {options} = useFilteredOptions({ ...SEARCH_ROUTER_OPTIONS_CONFIG, isSearching: false, + enabled: shouldBuild, }); useEffect(() => { diff --git a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx index 944efc3aa3fe..d74849b7d8b1 100644 --- a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx +++ b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx @@ -2,122 +2,53 @@ import useOnyx from '@hooks/useOnyx'; import {loadRightModalNavigator, loadSearchRouterPage} from '@libs/Navigation/AppNavigator/searchRouterLazyLoaders'; import {Scheduler} from '@libs/Scheduler'; -import type {IdleTask} from '@libs/Scheduler'; -import {getSpan} from '@libs/telemetry/activeSpans'; -import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ComponentType} from 'react'; import {useEffect, useState} from 'react'; -import Onyx from 'react-native-onyx'; + +import {getIsSearchRouterOpenOrOpening} from './SearchRouterContext'; type OptionsWarmerProps = { onDone: () => void; }; -// Stop waiting for quiet after this many idle windows; a chatty account never fully stops writing. -const MAX_QUIET_WAIT_ATTEMPTS = 5; - -/** - * Counts writes to the Onyx data the option-list cache is keyed on. `connectWithoutView` because a - * subscribed component would rebuild the whole option list on every write; this only counts. - */ -function startTrackingInputChurn(): {getVersion: () => number; stop: () => void} { - let version = 0; - const bump = () => { - version += 1; - }; - const connections = [ - Onyx.connectWithoutView({key: ONYXKEYS.COLLECTION.REPORT, callback: bump}), - Onyx.connectWithoutView({key: ONYXKEYS.COLLECTION.POLICY, callback: bump}), - Onyx.connectWithoutView({key: ONYXKEYS.PERSONAL_DETAILS_LIST, callback: bump}), - Onyx.connectWithoutView({key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, callback: bump}), - Onyx.connectWithoutView({key: ONYXKEYS.DERIVED.RAM_ONLY_SORTED_REPORT_ACTIONS, callback: bump}), - ]; - - return { - getVersion: () => version, - stop: () => { - for (const connection of connections) { - Onyx.disconnect(connection); - } - }, - }; -} - /** * Moves the first search-open of the session off the critical path: evaluates the SearchRouterPage and * RightModalNavigator module graphs, then mounts SearchRouterOptionsWarmer to build the empty-query * option list into `createFilteredOptionList`'s cache. Runs after OpenApp is applied and the JS thread - * is idle. The option list also waits for its Onyx inputs to hold still, because the cache is keyed on - * their identity and a list built mid-write is discarded. + * is idle. */ function SearchRouterWarmup() { const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); const [OptionsWarmer, setOptionsWarmer] = useState | null>(null); - const [isWarmupDone, setIsWarmupDone] = useState(false); useEffect(() => { if (isLoadingApp !== false) { return; } - let isCancelled = false; - let task: IdleTask | undefined; - let attempts = 0; - let lastSeenChurn = -1; - let areModulesLoaded = false; - const churn = startTrackingInputChurn(); - - const stop = () => { - isCancelled = true; - task?.cancel(); - churn.stop(); - }; - - const warmWhenIdle = () => { - task = Scheduler.scheduleWhenIdle(() => { - if (isCancelled) { - return; - } - - // Already opening or open, so these costs are being paid live. - if (getSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER)) { - stop(); - return; - } - - // Unaffected by Onyx writes, so no need to wait for quiet. - if (!areModulesLoaded) { - areModulesLoaded = true; - loadSearchRouterPage(); - loadRightModalNavigator(); - } - - const currentChurn = churn.getVersion(); - if (currentChurn !== lastSeenChurn && attempts < MAX_QUIET_WAIT_ATTEMPTS) { - lastSeenChurn = currentChurn; - attempts += 1; - warmWhenIdle(); - return; - } + const task = Scheduler.scheduleWhenIdle(() => { + // Already opening or open, so these costs are being paid live. + if (getIsSearchRouterOpenOrOpening()) { + return; + } - setOptionsWarmer(() => require<{default: ComponentType}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default); - stop(); - }); - }; + loadSearchRouterPage(); + loadRightModalNavigator(); + setOptionsWarmer(() => require<{default: ComponentType}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default); + }); - warmWhenIdle(); - return stop; + return () => task.cancel(); }, [isLoadingApp]); - if (!OptionsWarmer || isWarmupDone) { + if (!OptionsWarmer) { return null; } - return setIsWarmupDone(true)} />; + return setOptionsWarmer(null)} />; } SearchRouterWarmup.displayName = 'SearchRouterWarmup'; diff --git a/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts b/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts new file mode 100644 index 000000000000..ee0479d0c38b --- /dev/null +++ b/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts @@ -0,0 +1,21 @@ +// The list shows at most MAX_AMOUNT_OF_SUGGESTIONS recent reports, so building full option data for the +// default 500-report list every time is unnecessary. Start from a smaller raw cap and only expand to the +// full set if that batch filters down below the visible cap (see the loadAll effect in SearchAutocompleteList); +// typing a query bypasses this cap entirely (isSearching drops the limit in createFilteredOptionList). +// 100 leaves buffer for hidden/muted chats getting filtered out after the raw-recency slice. +// The batch size stays at 500 (not smaller) because createFilteredOptionList rebuilds its whole +// top-N slice from scratch each call, so a small batch would mean repeated rebuilds. +const INITIAL_MAX_RECENT_REPORTS = 100; +const RECENT_REPORTS_BATCH_SIZE = 500; + +// Shared by SearchAutocompleteList and SearchRouterOptionsWarmer: createFilteredOptionList keys its cache +// on these values, so the two call sites must not drift. Contacts can be deferred because the empty-query +// state shows none. +const SEARCH_ROUTER_OPTIONS_CONFIG = { + enabled: true, + deferContactsUntilSearch: true, + maxRecentReports: INITIAL_MAX_RECENT_REPORTS, + batchSize: RECENT_REPORTS_BATCH_SIZE, +} as const; + +export default SEARCH_ROUTER_OPTIONS_CONFIG; From ab916e5f2a3dab52ed86710f300835a1e42114fe Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Thu, 13 Aug 2026 10:08:32 +0200 Subject: [PATCH 10/15] Shorten the recent-reports cap comment --- .../Search/SearchRouter/searchRouterOptionsConfig.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts b/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts index ee0479d0c38b..936501532582 100644 --- a/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts +++ b/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts @@ -1,10 +1,6 @@ -// The list shows at most MAX_AMOUNT_OF_SUGGESTIONS recent reports, so building full option data for the -// default 500-report list every time is unnecessary. Start from a smaller raw cap and only expand to the -// full set if that batch filters down below the visible cap (see the loadAll effect in SearchAutocompleteList); -// typing a query bypasses this cap entirely (isSearching drops the limit in createFilteredOptionList). -// 100 leaves buffer for hidden/muted chats getting filtered out after the raw-recency slice. -// The batch size stays at 500 (not smaller) because createFilteredOptionList rebuilds its whole -// top-N slice from scratch each call, so a small batch would mean repeated rebuilds. +// The list renders at most MAX_AMOUNT_OF_SUGGESTIONS rows, so start from a small raw cap (100 leaves +// buffer for chats filtered out later) and let SearchAutocompleteList's loadAll effect expand it when +// needed. The batch stays large because createFilteredOptionList rebuilds its whole top-N slice each call. const INITIAL_MAX_RECENT_REPORTS = 100; const RECENT_REPORTS_BATCH_SIZE = 500; From 6864931e127c6a2479bdcbb8e48169efcd5c49dc Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 14 Aug 2026 11:10:05 +0200 Subject: [PATCH 11/15] Parse the autocomplete query unconditionally again The blank-query short-circuit skipped the parser's first-use module evaluation, which measured at ~76ms on an Android dev build. That cost is Hermes compiling the generated parser at runtime, which a release build does not pay - its bundle is precompiled to bytecode. The parsing itself is 0.07ms per call, so the guard is not worth the extra branch. --- src/hooks/useAutocompleteSuggestions.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/hooks/useAutocompleteSuggestions.ts b/src/hooks/useAutocompleteSuggestions.ts index 30d8e2353627..34e005d8d36d 100644 --- a/src/hooks/useAutocompleteSuggestions.ts +++ b/src/hooks/useAutocompleteSuggestions.ts @@ -133,8 +133,7 @@ function useAutocompleteSuggestions({ const {exportedToFilterOptions} = useExportedToFilterOptions(); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); - // A blank query can't produce an autocomplete key, so skip the parser and its module evaluation. - const parsedQuery = autocompleteQueryValue.trim() ? parseForAutocomplete(autocompleteQueryValue) : undefined; + const parsedQuery = parseForAutocomplete(autocompleteQueryValue); const {autocomplete, ranges = []} = parsedQuery ?? {}; let autocompleteKey = autocomplete?.key; From 8cd9dcca95c4e52b308298c822c4a20e47df1fd8 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 17 Aug 2026 16:18:18 +0200 Subject: [PATCH 12/15] Track the native SearchRouter route as the open flag The native route mounts on a deep link or a restored last-visited path without openSearchRouter, and hardware Back and the iOS gesture pop it without closeSearchRouter, so set and reset the module-level flag from the page itself. --- .../Search/SearchRouter/SearchRouterContext.tsx | 6 +++++- .../SearchRouter/SearchRouterOptionsWarmer.tsx | 2 +- .../SearchRouter/SearchRouterPage/index.native.tsx | 13 +++++++++++-- .../Search/SearchRouter/SearchRouterWarmup.tsx | 1 + 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/components/Search/SearchRouter/SearchRouterContext.tsx b/src/components/Search/SearchRouter/SearchRouterContext.tsx index be7d3f2e1496..bcadae313545 100644 --- a/src/components/Search/SearchRouter/SearchRouterContext.tsx +++ b/src/components/Search/SearchRouter/SearchRouterContext.tsx @@ -35,7 +35,11 @@ function getIsSearchRouterOpenOrOpening() { return isSearchRouterOpenOrOpening; } -export {getIsSearchRouterOpenOrOpening}; +function setIsSearchRouterOpenOrOpening(isOpenOrOpening: boolean) { + isSearchRouterOpenOrOpening = isOpenOrOpening; +} + +export {getIsSearchRouterOpenOrOpening, setIsSearchRouterOpenOrOpening}; type SearchRouterStateContextType = { isSearchRouterDisplayed: boolean; diff --git a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx index 3072af2817b1..b518af2e6825 100644 --- a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx +++ b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx @@ -18,7 +18,7 @@ type SearchRouterOptionsWarmerProps = { onDone: () => void; }; -// Stop waiting for quiet after this many idle windows; a chatty account never fully stops writing. +// Stop waiting for quiet after this many idle windows. A chatty account never fully stops writing. const MAX_QUIET_WAIT_ATTEMPTS = 5; /** diff --git a/src/components/Search/SearchRouter/SearchRouterPage/index.native.tsx b/src/components/Search/SearchRouter/SearchRouterPage/index.native.tsx index 60a248bd5ab3..b1cb71c4b029 100644 --- a/src/components/Search/SearchRouter/SearchRouterPage/index.native.tsx +++ b/src/components/Search/SearchRouter/SearchRouterPage/index.native.tsx @@ -1,6 +1,6 @@ import ScreenWrapper from '@components/ScreenWrapper'; import SearchRouter from '@components/Search/SearchRouter/SearchRouter'; -import {useSearchRouterActions, useSearchRouterState} from '@components/Search/SearchRouter/SearchRouterContext'; +import {setIsSearchRouterOpenOrOpening, useSearchRouterActions, useSearchRouterState} from '@components/Search/SearchRouter/SearchRouterContext'; import useKeyboardState from '@hooks/useKeyboardState'; import useNetwork from '@hooks/useNetwork'; @@ -12,7 +12,7 @@ import useWindowDimensions from '@hooks/useWindowDimensions'; import getKeyboardHeight from '@libs/getKeyboardHeight'; -import React from 'react'; +import React, {useEffect} from 'react'; import {View} from 'react-native'; type GetAvailableHeightParams = { @@ -40,6 +40,15 @@ function SearchRouterPage() { const {windowHeight} = useWindowDimensions(); const StyleUtils = useStyleUtils(); const styles = useThemeStyles(); + + // The presence of this route is the source of truth for "the router is open" on native: it mounts on a deep link + // or a restored last-visited path without openSearchRouter, and hardware Back and the iOS gesture pop it without + // closeSearchRouter. + useEffect(() => { + setIsSearchRouterOpenOrOpening(true); + return () => setIsSearchRouterOpenOrOpening(false); + }, []); + const shouldConstrainForOfflineKeyboard = isOffline && isKeyboardActive; // Keep the router between the top safe area and the keyboard; ScreenWrapper and the // list already handle bottom safe-area and offline-indicator spacing. diff --git a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx index d74849b7d8b1..e2eb4ad29be5 100644 --- a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx +++ b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx @@ -12,6 +12,7 @@ import {useEffect, useState} from 'react'; import {getIsSearchRouterOpenOrOpening} from './SearchRouterContext'; type OptionsWarmerProps = { + /** Called once the option list is cached (or the warm is no longer needed), so this component can unmount the warmer. */ onDone: () => void; }; From 824ce95d44bad9180eab5d3c93bfed107bb75ff2 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 18 Aug 2026 12:08:33 +0200 Subject: [PATCH 13/15] Share the warmer prop type and drop the display names --- .../SearchRouter/SearchRouterOptionsWarmer.tsx | 3 +-- .../Search/SearchRouter/SearchRouterWarmup.tsx | 13 ++++--------- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx index b518af2e6825..590e8d542345 100644 --- a/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx +++ b/src/components/Search/SearchRouter/SearchRouterOptionsWarmer.tsx @@ -86,6 +86,5 @@ function SearchRouterOptionsWarmer({onDone}: SearchRouterOptionsWarmerProps) { return null; } -SearchRouterOptionsWarmer.displayName = 'SearchRouterOptionsWarmer'; - export default SearchRouterOptionsWarmer; +export type {SearchRouterOptionsWarmerProps}; diff --git a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx index e2eb4ad29be5..d27205737a3b 100644 --- a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx +++ b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx @@ -9,12 +9,9 @@ import type {ComponentType} from 'react'; import {useEffect, useState} from 'react'; -import {getIsSearchRouterOpenOrOpening} from './SearchRouterContext'; +import type {SearchRouterOptionsWarmerProps} from './SearchRouterOptionsWarmer'; -type OptionsWarmerProps = { - /** Called once the option list is cached (or the warm is no longer needed), so this component can unmount the warmer. */ - onDone: () => void; -}; +import {getIsSearchRouterOpenOrOpening} from './SearchRouterContext'; /** * Moves the first search-open of the session off the critical path: evaluates the SearchRouterPage and @@ -24,7 +21,7 @@ type OptionsWarmerProps = { */ function SearchRouterWarmup() { const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); - const [OptionsWarmer, setOptionsWarmer] = useState | null>(null); + const [OptionsWarmer, setOptionsWarmer] = useState | null>(null); useEffect(() => { if (isLoadingApp !== false) { @@ -39,7 +36,7 @@ function SearchRouterWarmup() { loadSearchRouterPage(); loadRightModalNavigator(); - setOptionsWarmer(() => require<{default: ComponentType}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default); + setOptionsWarmer(() => require<{default: ComponentType}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default); }); return () => task.cancel(); @@ -52,6 +49,4 @@ function SearchRouterWarmup() { return setOptionsWarmer(null)} />; } -SearchRouterWarmup.displayName = 'SearchRouterWarmup'; - export default SearchRouterWarmup; From 8ab2d7375a7251dcc560db054526dae28bcf000b Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 18 Aug 2026 15:14:59 +0200 Subject: [PATCH 14/15] Keep every shared option-list value in the search-router config --- src/components/Search/SearchAutocompleteList.tsx | 6 ------ .../Search/SearchRouter/searchRouterOptionsConfig.ts | 1 + 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index 1184fe9d4b58..cd1eb862a629 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -216,12 +216,6 @@ function SearchAutocompleteList({ } = useFilteredOptions({ ...SEARCH_ROUTER_OPTIONS_CONFIG, isSearching: !!autocompleteQueryValue.trim(), - includeP2P: true, - // The empty-query state renders only recent searches and recent reports (no standalone contacts), - // so contacts can be deferred until the user types a query. - deferContactsUntilSearch: true, - maxRecentReports: INITIAL_MAX_RECENT_REPORTS, - batchSize: RECENT_REPORTS_BATCH_SIZE, }); const isRecentSearchesDataLoaded = !isLoadingOnyxValue(recentSearchesMetadata); diff --git a/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts b/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts index 936501532582..0d72b490ea04 100644 --- a/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts +++ b/src/components/Search/SearchRouter/searchRouterOptionsConfig.ts @@ -9,6 +9,7 @@ const RECENT_REPORTS_BATCH_SIZE = 500; // state shows none. const SEARCH_ROUTER_OPTIONS_CONFIG = { enabled: true, + includeP2P: true, deferContactsUntilSearch: true, maxRecentReports: INITIAL_MAX_RECENT_REPORTS, batchSize: RECENT_REPORTS_BATCH_SIZE, From 403eb77ffc812e3db819fa07e41f47d0510d9913 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 21 Aug 2026 14:14:45 +0200 Subject: [PATCH 15/15] Pin the SearchRouter warm-up's cache-hit invariant Assert that a second build with the router's empty-query config is served from createFilteredOptionList's cache rather than rebuilt, that the empty-query build keeps contacts deferred, and that typing is a separate entry. Assert the live list asks for the shared config too, so the warm build and the first open cannot drift apart on the values that cache is keyed on. Also document that isLoadingApp only gates the fresh sign-in launch, and drop the JSDoc claim that the callback runs on an idle thread when the scheduler's fallback timer can force it. --- .../SearchRouter/SearchRouterWarmup.tsx | 8 +++-- tests/unit/OptionsListUtilsTest.tsx | 30 +++++++++++++++++++ tests/unit/SearchAutocompleteListTest.tsx | 9 ++++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx index d27205737a3b..d7a4c3c0b402 100644 --- a/src/components/Search/SearchRouter/SearchRouterWarmup.tsx +++ b/src/components/Search/SearchRouter/SearchRouterWarmup.tsx @@ -16,14 +16,18 @@ import {getIsSearchRouterOpenOrOpening} from './SearchRouterContext'; /** * Moves the first search-open of the session off the critical path: evaluates the SearchRouterPage and * RightModalNavigator module graphs, then mounts SearchRouterOptionsWarmer to build the empty-query - * option list into `createFilteredOptionList`'s cache. Runs after OpenApp is applied and the JS thread - * is idle. + * option list into `createFilteredOptionList`'s cache. Runs in the first idle window after OpenApp is + * applied, or after the scheduler's starvation fallback if the thread never goes idle. */ function SearchRouterWarmup() { const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); const [OptionsWarmer, setOptionsWarmer] = useState | null>(null); useEffect(() => { + // Only OpenApp raises this flag, so it gates the fresh sign-in launch, where the account holds no data + // to build from yet. A relaunch runs ReconnectApp and reads the flag as false from disk, so the warm-up + // builds from the persisted collections; writes landing afterwards only invalidate the cache entry and + // the first open rebuilds the list, as it does without the warm-up. if (isLoadingApp !== false) { return; } diff --git a/tests/unit/OptionsListUtilsTest.tsx b/tests/unit/OptionsListUtilsTest.tsx index a88ed8798b74..d513c0d3d7c7 100644 --- a/tests/unit/OptionsListUtilsTest.tsx +++ b/tests/unit/OptionsListUtilsTest.tsx @@ -5,6 +5,7 @@ import ComposeProviders from '@components/ComposeProviders'; import type {LocalizedTranslate} from '@components/LocaleContextProvider'; import {LocaleContextProvider} from '@components/LocaleContextProvider'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import SEARCH_ROUTER_OPTIONS_CONFIG from '@components/Search/SearchRouter/searchRouterOptionsConfig'; import type {PrivateIsArchivedMap} from '@hooks/usePrivateIsArchivedMap'; import useReportIsArchived from '@hooks/useReportIsArchived'; @@ -2111,6 +2112,35 @@ describe('OptionsListUtils', () => { expect(cachedResults.personalDetails).toEqual(eagerResults.personalDetails); }); + it('serves the SearchRouter empty-query list from the cache on the second build', () => { + // Given the config the SearchRouter warm-up and SearchAutocompleteList both build with + const {maxRecentReports, includeP2P, deferContactsUntilSearch} = SEARCH_ROUTER_OPTIONS_CONFIG; + const options = { + currentUserAccountID: CURRENT_USER_ACCOUNT_ID, + dateFnsLocale: undefined, + conciergeReportID: undefined, + maxRecentReports, + includeP2P, + deferContactsUntilSearch, + isSearching: false, + }; + clearFilteredOptionListCache(); + + // When the warm-up builds the list and the first open builds it again from the same Onyx snapshots + const warmed = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, options); + const opened = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, options); + + // Then the open gets a clone of the warm build instead of rebuilding it, contacts stay deferred, + // and typing is a separate entry that still builds them + expect(opened.reports.at(0)).not.toBe(warmed.reports.at(0)); + expect(opened.reports.at(0)?.icons).toBe(warmed.reports.at(0)?.icons); + expect(warmed.personalDetails).toHaveLength(0); + expect( + createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {...options, isSearching: true}) + .personalDetails.length, + ).toBeGreaterThan(0); + }); + it('should hydrate with the build-time inputs, keeping brickRoadIndicator without any caller-provided data', () => { // Given a contact whose 1:1 DM report has a brick road status in the derived report attributes const {lazyList: baseList} = buildOptionLists(); diff --git a/tests/unit/SearchAutocompleteListTest.tsx b/tests/unit/SearchAutocompleteListTest.tsx index 382ae480a235..9d422662c385 100644 --- a/tests/unit/SearchAutocompleteListTest.tsx +++ b/tests/unit/SearchAutocompleteListTest.tsx @@ -5,6 +5,7 @@ import OnyxListItemProvider from '@components/OnyxListItemProvider'; import ScreenWrapperOfflineIndicatorContext from '@components/ScreenWrapper/ScreenWrapperOfflineIndicatorContext'; import type {SearchQueryItem} from '@components/Search/SearchList/ListItem/SearchQueryListItem'; import SearchRouter from '@components/Search/SearchRouter/SearchRouter'; +import SEARCH_ROUTER_OPTIONS_CONFIG from '@components/Search/SearchRouter/searchRouterOptionsConfig'; import Text from '@components/Text'; import type {PrivateIsArchivedMap} from '@hooks/usePrivateIsArchivedMap'; @@ -261,6 +262,14 @@ describe('SearchAutocompleteList', () => { expect(mockUseNavigationSuggestions).toHaveBeenCalledWith(expect.any(String), shouldWatchForApprovals); }); + it('asks for the option list with the config shared with the SearchRouter warm-up', () => { + render(); + + // createFilteredOptionList keys its cache on these values, so the empty-query list this screen asks for + // has to be the one SearchRouterOptionsWarmer built, or the warm build is never reused. + expect(mockUseFilteredOptions).toHaveBeenCalledWith(expect.objectContaining({...SEARCH_ROUTER_OPTIONS_CONFIG, isSearching: false})); + }); + it('should display and select navigation suggestion rows', async () => { const navigationAction = jest.fn(); mockUseNavigationSuggestions.mockReturnValue([