Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
3a124fe
Skip search-text normalization in getValidOptions when the search is …
sumo-slonik Aug 11, 2026
5064258
Skip the autocomplete parser for blank queries
sumo-slonik Aug 11, 2026
3d1e807
Cache attachment-message parse results by HTML
sumo-slonik Aug 11, 2026
50f9533
Warm the SearchRouter open path while the app is idle
sumo-slonik Aug 11, 2026
ff7c193
Warm the SearchRouter on real signals instead of a fixed delay
sumo-slonik Aug 12, 2026
d42684e
Drop the attachment-message HTML parse cache
sumo-slonik Aug 12, 2026
2a79e79
Drop the empty-search text-normalization skip
sumo-slonik Aug 12, 2026
e7f08da
Trim the comments in the SearchRouter warmup changes
sumo-slonik Aug 12, 2026
3c32afa
Track warmup input churn through useOnyx and gate on an explicit open…
sumo-slonik Aug 13, 2026
ab916e5
Shorten the recent-reports cap comment
sumo-slonik Aug 13, 2026
6864931
Parse the autocomplete query unconditionally again
sumo-slonik Aug 14, 2026
8cd9dcc
Track the native SearchRouter route as the open flag
sumo-slonik Aug 17, 2026
bb473ea
Merge branch 'main' into perf/search-router-p95-tail
sumo-slonik Aug 18, 2026
824ce95
Share the warmer prop type and drop the display names
sumo-slonik Aug 18, 2026
e43ec01
Merge branch 'main' into perf/search-router-p95-tail
sumo-slonik Aug 18, 2026
8ab2d73
Keep every shared option-list value in the search-router config
sumo-slonik Aug 18, 2026
d5bac35
Merge remote-tracking branch 'upstream/main' into perf/search-router-…
sumo-slonik Aug 18, 2026
403eb77
Pin the SearchRouter warm-up's cache-hit invariant
sumo-slonik Aug 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 2 additions & 17 deletions src/components/Search/SearchAutocompleteList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,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<Omit<OptionData, keyof NewListItem>> & Partial<Omit<SearchQueryItem, keyof NewListItem>>;

Expand Down Expand Up @@ -102,16 +103,6 @@ const defaultListOptions = {

const EMPTY_RANK_MAP: ReadonlyMap<string, number> = 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;

// 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
Expand Down Expand Up @@ -223,14 +214,8 @@ function SearchAutocompleteList({
loadAll: loadAllRecentReports,
hasMore: hasMoreRecentReports,
} = useFilteredOptions({
enabled: true,
...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);
Expand Down
29 changes: 28 additions & 1 deletion src/components/Search/SearchRouter/SearchRouterContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -27,6 +27,20 @@ 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;
}

function setIsSearchRouterOpenOrOpening(isOpenOrOpening: boolean) {
isSearchRouterOpenOrOpening = isOpenOrOpening;
}

export {getIsSearchRouterOpenOrOpening, setIsSearchRouterOpenOrOpening};

type SearchRouterStateContextType = {
isSearchRouterDisplayed: boolean;
};
Expand Down Expand Up @@ -55,17 +69,28 @@ 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.
useSyncModalWithHistory({
isVisible: isSearchRouterDisplayed,
shouldHandleNavigationBack: true,
onClose: () => {
isSearchRouterOpenOrOpening = false;
closeSearch(setIsSearchRouterDisplayed);
searchRouterDisplayedRef.current = false;
},
onOpen: () => {
isSearchRouterOpenOrOpening = true;
openSearch(setIsSearchRouterDisplayed);
searchRouterDisplayedRef.current = true;
},
Expand All @@ -80,6 +105,7 @@ function SearchRouterContextProvider({children}: ChildrenProps) {
};

const openSearchRouter = (query?: string, isFromSearchPageSearchButton?: boolean) => {
isSearchRouterOpenOrOpening = true;
Comment thread
mountiny marked this conversation as resolved.
Resolved
pendingRouterQuery = query ?? '';
pendingIsFromSearchPageSearchButton = isFromSearchPageSearchButton ?? false;
startSpan(CONST.TELEMETRY.SPAN_SEARCH_ROUTER_MODAL_CLOSE_WAIT, {
Expand All @@ -100,6 +126,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);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
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 {getIsSearchRouterOpenOrOpening} from './SearchRouterContext';
import SEARCH_ROUTER_OPTIONS_CONFIG from './searchRouterOptionsConfig';

type SearchRouterOptionsWarmerProps = {
/** Called once the option list is cached (or the warm is no longer needed), so the parent can unmount this component. */
onDone: () => void;
};
Comment thread
sumo-slonik marked this conversation as resolved.
Resolved

// 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. 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();
Comment on lines +58 to +61

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Yield between quiet-period checks

When React Scheduler still has budget, an idle-priority callback scheduled from a currently running idle callback can execute in the same scheduler work loop; Scheduler.scheduleWhenIdle only adds a competing 300 ms fallback and does not guarantee a new event-loop window. Consequently, this recursive call can immediately observe the same churnVersionRef, enable the build, and unmount the warmer before queued post-OpenApp Onyx deliveries run. On accounts whose updates arrive just after that scheduler flush, the next delivery invalidates the transient cache entry, so the first Search open still performs the full build while startup also paid for the discarded warmup. Introduce an actual yield between checks or restart a quiet-period timer when an input changes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: a recursive scheduleWhenIdle re-runs inside the same scheduler work loop (8 recursions in one macrotask, 0.085 ms), so the quiet-wait barely waits. I built the real debounce (300 ms per watched input, 2 s cap) and A/B'd it against this branch on Android — interleaved variants, 6 paired rounds, cold launch, tap after a 25 s settle: the debounce variant lands +8.6% slower than this branch (median 1028 ms vs 943 ms, slower in 5/6 rounds), so making the wait real buys nothing and I'd rather not grow the warm-up code for it here.
Cache hit rate is the remaining gap and I'll take it in a follow-up: the warm entry is still invalidated by Onyx writes right after launch, exactly as you point out, so this is better than before but not yet ideal.

return;
}

setShouldBuild(true);
});
};

waitForQuiet();
return () => task?.cancel();
}, [onDone]);

const {options} = useFilteredOptions({
...SEARCH_ROUTER_OPTIONS_CONFIG,
isSearching: false,
enabled: shouldBuild,
});

useEffect(() => {
if (!options) {
return;
}
onDone();
}, [options, onDone]);

return null;
}

export default SearchRouterOptionsWarmer;
export type {SearchRouterOptionsWarmerProps};
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 = {
Expand Down Expand Up @@ -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.
Expand Down
56 changes: 56 additions & 0 deletions src/components/Search/SearchRouter/SearchRouterWarmup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import useOnyx from '@hooks/useOnyx';

import {loadRightModalNavigator, loadSearchRouterPage} from '@libs/Navigation/AppNavigator/searchRouterLazyLoaders';
import {Scheduler} from '@libs/Scheduler';

import ONYXKEYS from '@src/ONYXKEYS';

import type {ComponentType} from 'react';

import {useEffect, useState} from 'react';

import type {SearchRouterOptionsWarmerProps} from './SearchRouterOptionsWarmer';

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 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<ComponentType<SearchRouterOptionsWarmerProps> | 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;
}
Comment on lines +23 to +33

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a user-visible regression but this guard only works on the very first launch after logging in.
Once logged in, on every relaunch (force-quit and reopen), isLoadingApp is always false and lets the warm-up run before the data arrives.
Maybe it's fine assuming that data already arrived?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, you're right that it's inert on a relaunch. I'd still keep it as-is: the collections are already on disk by then, and if reconnect data lands after the build we only lose the cache hit, so the first open rebuilds the list exactly as it does today. The stricter gates I looked at are worse — IS_LOADING_REPORT_DATA never clears while offline, so the warm-up would never run at all, and HAS_LOADED_APP stays true after the first launch. I've added a comment at the guard so it doesn't surprise the next reader.


const task = Scheduler.scheduleWhenIdle(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we reuse TransitionTracker.runAfterTransitions which is purpose-built for "schedules a callback to run after all transitions complete", firing synchronously when nothing is active?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, but I don't think it fits this spot: at launch nothing has started a transition yet, so runAfterTransitions would fire synchronously inside the Onyx commit we're trying to step out of, and waitForUpcomingTransition would instead wait for the user's next navigation and fire at the end of it, in the middle of the incoming screen's render. They're really meant to nest rather than replace scheduleWhenIdle (see usePreMountDestination), and here there's no transition to wait for .

// Already opening or open, so these costs are being paid live.
if (getIsSearchRouterOpenOrOpening()) {
return;
}

loadSearchRouterPage();
loadRightModalNavigator();
setOptionsWarmer(() => require<{default: ComponentType<SearchRouterOptionsWarmerProps>}>('@components/Search/SearchRouter/SearchRouterOptionsWarmer').default);
});

return () => task.cancel();
}, [isLoadingApp]);

if (!OptionsWarmer) {
return null;
}

return <OptionsWarmer onDone={() => setOptionsWarmer(null)} />;
}

export default SearchRouterWarmup;
18 changes: 18 additions & 0 deletions src/components/Search/SearchRouter/searchRouterOptionsConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// 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;

// 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,
includeP2P: true,
deferContactsUntilSearch: true,
maxRecentReports: INITIAL_MAX_RECENT_REPORTS,
batchSize: RECENT_REPORTS_BATCH_SIZE,
} as const;

export default SEARCH_ROUTER_OPTIONS_CONFIG;
6 changes: 3 additions & 3 deletions src/libs/Navigation/AppNavigator/AuthScreens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -70,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';
Expand All @@ -86,9 +88,6 @@ const loadTrackExpensePage = () => require<ReactComponentModule>('../../../pages
const loadSubmitExpensePage = () => require<ReactComponentModule>('../../../pages/SubmitExpensePage').default;
const loadWorkspaceJoinUser = () => require<ReactComponentModule>('@pages/workspace/WorkspaceJoinUserPage').default;

const loadSearchRouterPage = () => require<ReactComponentModule>('../../../components/Search/SearchRouter/SearchRouterPage').default;
const loadRightModalNavigator = () => require<ReactComponentModule>('./Navigators/RightModalNavigator').default;

const RootStack = createRootStackNavigator<AuthScreensParamList>();

// We want to delay the re-rendering for components(e.g. ReportActionCompose)
Expand Down Expand Up @@ -164,6 +163,7 @@ function AuthScreens() {
return (
<>
<AuthScreensInitHandler />
<SearchRouterWarmup />
<ThreeDSAuthHandler />
<UserStatusHandler />
<SupportalPermissionDeniedModal />
Expand Down
7 changes: 7 additions & 0 deletions src/libs/Navigation/AppNavigator/searchRouterLazyLoaders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type ReactComponentModule from '@src/types/utils/ReactComponentModule';

// Shared by AuthScreens (lazy screen registration) and SearchRouterWarmup (idle pre-evaluation).
const loadSearchRouterPage = () => require<ReactComponentModule>('../../../components/Search/SearchRouter/SearchRouterPage').default;
const loadRightModalNavigator = () => require<ReactComponentModule>('./Navigators/RightModalNavigator').default;

export {loadSearchRouterPage, loadRightModalNavigator};
Loading
Loading