diff --git a/src/libs/Navigation/guards/MigratedUserWelcomeModalGuard.ts b/src/libs/Navigation/guards/MigratedUserWelcomeModalGuard.ts index b3684edafa91..6f4c174b9bbb 100644 --- a/src/libs/Navigation/guards/MigratedUserWelcomeModalGuard.ts +++ b/src/libs/Navigation/guards/MigratedUserWelcomeModalGuard.ts @@ -1,5 +1,7 @@ import Log from '@libs/Log'; +import createScheduleOnce from '@libs/Navigation/helpers/createScheduleOnce'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; +import getValidDynamicRouteBasePath from '@libs/Navigation/helpers/getValidDynamicRouteBasePath'; import Navigation from '@libs/Navigation/Navigation'; import isProductTrainingElementDismissed from '@libs/TooltipUtils'; @@ -30,7 +32,14 @@ let isLoadingApp = true; let hasRedirectedToMigratedUserModal = false; function getMigratedUserWelcomeModalRoute(basePath?: string): Route { - return createDynamicRoute(DYNAMIC_ROUTES.MIGRATED_USER_WELCOME.path, basePath ?? (Navigation.getActiveRoute() || ROUTES.HOME)); + return createDynamicRoute( + DYNAMIC_ROUTES.MIGRATED_USER_WELCOME.path, + basePath ?? + getValidDynamicRouteBasePath({ + entryScreens: DYNAMIC_ROUTES.MIGRATED_USER_WELCOME.entryScreens, + fallbackPath: ROUTES.HOME, + }), + ); } function resetSessionFlag() { @@ -62,6 +71,9 @@ function navigateToMigratedUserWelcomeModalIfReady() { Navigation.navigate(getMigratedUserWelcomeModalRoute()); } +/** Waits until the current Onyx update batch has populated every value used by the guard. */ +const scheduleMigratedUserWelcomeModalEvaluation = createScheduleOnce(navigateToMigratedUserWelcomeModalIfReady); + /** * Called by guards/index.ts when session or loading app state changes. * Reuses the shared Onyx subscriptions from guards/index.ts to avoid duplicate connections. @@ -69,7 +81,7 @@ function navigateToMigratedUserWelcomeModalIfReady() { function onSessionOrLoadingAppChanged(sessionValue: OnyxEntry, isLoadingAppValue: boolean) { session = sessionValue; isLoadingApp = isLoadingAppValue; - navigateToMigratedUserWelcomeModalIfReady(); + scheduleMigratedUserWelcomeModalEvaluation(); } Onyx.connectWithoutView({ @@ -77,7 +89,7 @@ Onyx.connectWithoutView({ callback: (value) => { const result = value ? tryNewDotOnyxSelector(value) : undefined; hasBeenAddedToNudgeMigration = result?.hasBeenAddedToNudgeMigration ?? false; - navigateToMigratedUserWelcomeModalIfReady(); + scheduleMigratedUserWelcomeModalEvaluation(); }, }); @@ -89,7 +101,7 @@ Onyx.connectWithoutView({ if (isProductTrainingElementDismissed('migratedUserWelcomeModal', value)) { hasRedirectedToMigratedUserModal = false; } - navigateToMigratedUserWelcomeModalIfReady(); + scheduleMigratedUserWelcomeModalEvaluation(); }, }); diff --git a/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts b/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts index 7eaa6446b4fd..2463065a59db 100644 --- a/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts +++ b/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts @@ -1,8 +1,7 @@ import getUserSecurityGroup from '@libs/getUserSecurityGroup'; -import Log from '@libs/Log'; +import createScheduleOnce from '@libs/Navigation/helpers/createScheduleOnce'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; -import findFocusedRouteWithOnyxTabGuard from '@libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard'; -import getStateFromPath from '@libs/Navigation/helpers/getStateFromPath'; +import getValidDynamicRouteBasePath from '@libs/Navigation/helpers/getValidDynamicRouteBasePath'; import Navigation from '@libs/Navigation/Navigation'; import {getGroupPoliciesWhereReportCanBeCreated} from '@libs/PolicyUtils'; @@ -37,7 +36,6 @@ let isSubmitMigrationModalShownLoaded = false; let hasLoadedApp = false; let hasRedirectedToSubmitPlanModal = false; -let isEvaluationScheduled = false; // An `intent=submit` deeplink delivers the same outcome as this modal without asking, so the modal must not open on // top of it. Recorded outside Onyx because the deeplink can only mark the modal shown from a React effect, which runs @@ -54,37 +52,15 @@ function releaseWelcomeModalForSubmitDeeplink() { hasPendingSubmitDeeplink = false; } -const SUBMIT_PLAN_WELCOME_ENTRY_SCREENS = new Set(DYNAMIC_ROUTES.SUBMIT_PLAN_WELCOME.entryScreens); - -/** - * The submit-plan-welcome modal is a dynamic route that can only attach to the screens listed in - * DYNAMIC_ROUTES.SUBMIT_PLAN_WELCOME.entryScreens. When we proactively open the modal on app boot, - * the active route can be any screen (e.g. `/settings/troubleshoot` after "Clear cache and restart"), - * and stacking the suffix onto a non-entry screen resolves to NotFound. Fall back to HOME (a valid - * entry screen) whenever the active route isn't an allowed base. - */ -function getValidModalBasePath(): string { - const activeRoute = Navigation.getActiveRoute(); - if (!activeRoute) { - return ROUTES.HOME; - } - try { - // getActiveRoute returns a plain string, while getStateFromPath expects a Route. Any string returned by - // getActiveRoute is a valid route path, and getStateFromPath safely handles paths it cannot parse. - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - const focusedRouteName = findFocusedRouteWithOnyxTabGuard(getStateFromPath(activeRoute as Route) ?? {})?.name; - if (focusedRouteName && SUBMIT_PLAN_WELCOME_ENTRY_SCREENS.has(focusedRouteName)) { - return activeRoute; - } - } catch (error) { - // getStateFromPath can throw for paths it cannot parse; fall back to HOME below. - Log.warn('[SubmitPlanWelcomeModalGuard] Failed to resolve modal base path, falling back to HOME', {activeRoute, error}); - } - return ROUTES.HOME; -} - function getSubmitPlanWelcomeModalRoute(basePath?: string): Route { - return createDynamicRoute(DYNAMIC_ROUTES.SUBMIT_PLAN_WELCOME.path, basePath ?? getValidModalBasePath()); + return createDynamicRoute( + DYNAMIC_ROUTES.SUBMIT_PLAN_WELCOME.path, + basePath ?? + getValidDynamicRouteBasePath({ + entryScreens: DYNAMIC_ROUTES.SUBMIT_PLAN_WELCOME.entryScreens, + fallbackPath: ROUTES.HOME, + }), + ); } function resetSessionFlag() { @@ -150,16 +126,7 @@ function navigateToSubmitPlanWelcomeModalIfReady() { * pre-sign-in-stale IS_LOADING_APP) only flips true once this session's account data — including the shown-flag — * has loaded, covering the sign-in race where eligibility NVPs arrive before the shown-flag. */ -function scheduleSubmitPlanWelcomeModalEvaluation() { - if (isEvaluationScheduled) { - return; - } - isEvaluationScheduled = true; - Promise.resolve().then(() => { - isEvaluationScheduled = false; - navigateToSubmitPlanWelcomeModalIfReady(); - }); -} +const scheduleSubmitPlanWelcomeModalEvaluation = createScheduleOnce(navigateToSubmitPlanWelcomeModalIfReady); // Session/app-load state drive the one-shot proactive redirect: they are the boot-time signal by which point // every eligibility value below has already landed in the same OpenApp batch, so re-evaluating here is safe. diff --git a/src/libs/Navigation/helpers/createScheduleOnce.ts b/src/libs/Navigation/helpers/createScheduleOnce.ts new file mode 100644 index 000000000000..57c8f6793a05 --- /dev/null +++ b/src/libs/Navigation/helpers/createScheduleOnce.ts @@ -0,0 +1,20 @@ +/** + * Creates a scheduler that coalesces calls until the queued microtask runs. + */ +function createScheduleOnce(run: () => void): () => void { + let isScheduled = false; + + return () => { + if (isScheduled) { + return; + } + + isScheduled = true; + Promise.resolve().then(() => { + isScheduled = false; + run(); + }); + }; +} + +export default createScheduleOnce; diff --git a/src/libs/Navigation/helpers/getValidDynamicRouteBasePath.ts b/src/libs/Navigation/helpers/getValidDynamicRouteBasePath.ts new file mode 100644 index 000000000000..c9b758fa9e08 --- /dev/null +++ b/src/libs/Navigation/helpers/getValidDynamicRouteBasePath.ts @@ -0,0 +1,37 @@ +import Log from '@libs/Log'; +import Navigation from '@libs/Navigation/Navigation'; + +import type {Route} from '@src/ROUTES'; +import type {Screen} from '@src/SCREENS'; + +import findFocusedRouteWithOnyxTabGuard from './findFocusedRouteWithOnyxTabGuard'; +import getStateFromPath from './getStateFromPath'; + +type GetValidDynamicRouteBasePathParams = { + entryScreens: ReadonlyArray; + fallbackPath: Route; +}; + +/** Returns the active route when it can host a dynamic route, or a known-valid fallback. */ +function getValidDynamicRouteBasePath({entryScreens, fallbackPath}: GetValidDynamicRouteBasePathParams): Route { + const activeRoute = Navigation.getActiveRoute(); + if (!activeRoute) { + return fallbackPath; + } + + try { + // Navigation builds this path from the current navigation state, so it is a valid app route. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + const activeRoutePath = activeRoute as Route; + const focusedRouteName = findFocusedRouteWithOnyxTabGuard(getStateFromPath(activeRoutePath) ?? {})?.name; + if (focusedRouteName && entryScreens.some((entryScreen) => entryScreen === '*' || entryScreen === focusedRouteName)) { + return activeRoutePath; + } + } catch (error) { + Log.warn('[Navigation] Failed to resolve a dynamic route base path', {activeRoute, error}); + } + + return fallbackPath; +} + +export default getValidDynamicRouteBasePath; diff --git a/src/libs/actions/App.ts b/src/libs/actions/App.ts index be4afeb19268..e03675d9e2b3 100644 --- a/src/libs/actions/App.ts +++ b/src/libs/actions/App.ts @@ -957,8 +957,9 @@ function clearOnyxAndResetApp(shouldNavigateToHomepage?: boolean) { const sequentialQueue = getAll(); Navigation.clearPreloadedRoutes(); - // Seed LAST_FULL_RECONNECT_TIME so subscribeToFullReconnect doesn't fire a duplicate - // ReconnectApp once the openApp() below lands NVP_RECONNECT_APP_IF_FULL_RECONNECT_BEFORE. + // The helper seeds the loading state and LAST_FULL_RECONNECT_TIME so consumers cannot evaluate transient + // post-clear state and subscribeToFullReconnect doesn't fire a duplicate ReconnectApp once the + // openApp() below lands NVP_RECONNECT_APP_IF_FULL_RECONNECT_BEFORE. const resetPromise = clearWorkboxRecoveryCaches().then(() => clearOnyxAndSeedFullReconnect(KEYS_TO_PRESERVE) .then(() => { diff --git a/src/libs/actions/Delegate.ts b/src/libs/actions/Delegate.ts index e51bbde3128b..ca3aa4d82945 100644 --- a/src/libs/actions/Delegate.ts +++ b/src/libs/actions/Delegate.ts @@ -61,18 +61,9 @@ const KEYS_TO_PRESERVE_DELEGATE_ACCESS = [ ONYXKEYS.PERSONAL_DETAILS_LIST, ]; -/** - * Atomically reset Onyx for a delegate-access transition. The IS_LOADING_APP=true - * seed is delegate-specific: without it, consumers observe HAS_LOADED_APP=true and - * IS_LOADING_APP=undefined together, which looks like a stuck app and triggers - * DelegateAccessHandler's recovery effect, queueing a duplicate openApp. - * - * The reconnect-time seed is handled by clearOnyxAndSeedFullReconnect. - */ +/** Atomically reset Onyx for a delegate-access transition. */ function clearOnyxForDelegateTransition(): Promise { - return clearOnyxAndSeedFullReconnect(KEYS_TO_PRESERVE_DELEGATE_ACCESS, { - [ONYXKEYS.IS_LOADING_APP]: true, - }); + return clearOnyxAndSeedFullReconnect(KEYS_TO_PRESERVE_DELEGATE_ACCESS); } type WithDelegatedAccess = { diff --git a/src/libs/actions/Session/index.ts b/src/libs/actions/Session/index.ts index 1cdf9b92c187..84f8d2e2c3d8 100644 --- a/src/libs/actions/Session/index.ts +++ b/src/libs/actions/Session/index.ts @@ -1510,6 +1510,9 @@ function validateTwoFactorAuth(twoFactorAuthCode: string, shouldClearData: boole [ONYXKEYS.NVP_ONBOARDING]: { hasCompletedGuidedSetupFlow: false, }, + // openApp() is intentionally deferred until the user dismisses the success screen, + // so this flow must remain outside the global loading state in the meantime. + [ONYXKEYS.IS_LOADING_APP]: false, }); return; } diff --git a/src/libs/actions/clearOnyxAndSeedFullReconnect.ts b/src/libs/actions/clearOnyxAndSeedFullReconnect.ts index 35748063bd47..f49dee20db6f 100644 --- a/src/libs/actions/clearOnyxAndSeedFullReconnect.ts +++ b/src/libs/actions/clearOnyxAndSeedFullReconnect.ts @@ -15,9 +15,11 @@ import Onyx from 'react-native-onyx'; * response.onyxData before successData, so without the seed the timestamp would * still be empty when the comparison runs and trigger a duplicate reconnect. * - * Pass `extraSeeds` to seed additional keys atomically with the timestamp (e.g. - * IS_LOADING_APP=true for delegate transitions). Seeded keys are appended to the - * preserve list automatically so they survive the clear. + * The reset marks the app as loading so consumers cannot evaluate transient + * post-clear state before the next OpenApp hydrates it. Pass `extraSeeds` to + * override that default or seed additional keys atomically with the timestamp. + * Seeded keys are appended to the preserve list automatically so they survive + * the clear. */ async function clearOnyxAndSeedFullReconnect(keysToPreserve: OnyxKey[], extraSeeds?: OnyxMultiSetInput): Promise { // Any Onyx reset can preserve or replace SESSION/CREDENTIALS while dropping account-scoped data. @@ -25,6 +27,7 @@ async function clearOnyxAndSeedFullReconnect(keysToPreserve: OnyxKey[], extraSee await clearPrefetchOnAppStart(); const seeds: OnyxMultiSetInput = { + [ONYXKEYS.IS_LOADING_APP]: true, ...extraSeeds, [ONYXKEYS.LAST_FULL_RECONNECT_TIME]: DateUtils.getDBTime(), }; diff --git a/tests/actions/ClearOnyxAndSeedFullReconnectTest.ts b/tests/actions/ClearOnyxAndSeedFullReconnectTest.ts index 490ae961820c..269ef7bff55f 100644 --- a/tests/actions/ClearOnyxAndSeedFullReconnectTest.ts +++ b/tests/actions/ClearOnyxAndSeedFullReconnectTest.ts @@ -76,15 +76,16 @@ describe('actions/clearOnyxAndSeedFullReconnect', () => { }); }); - it('applies extraSeeds atomically and keeps seeded keys after the clear', async () => { + it('marks the app as loading by default and keeps the loading state after the clear', async () => { + // Given a fully loaded app before an Onyx reset await Onyx.set(ONYXKEYS.IS_LOADING_APP, false); await waitForBatchedUpdates(); - await clearOnyxAndSeedFullReconnect([], { - [ONYXKEYS.IS_LOADING_APP]: true, - }); + // When Onyx is reset without an explicit loading-state override + await clearOnyxAndSeedFullReconnect([]); await waitForBatchedUpdates(); + // Then the app remains marked as loading until the next OpenApp response arrives await new Promise((resolve) => { const connection = Onyx.connect({ key: ONYXKEYS.IS_LOADING_APP, @@ -109,6 +110,27 @@ describe('actions/clearOnyxAndSeedFullReconnect', () => { }); }); + it('allows extraSeeds to override the default loading state', async () => { + // Given a reset that does not lead to another OpenApp call + // When the caller explicitly overrides the default loading state + await clearOnyxAndSeedFullReconnect([], { + [ONYXKEYS.IS_LOADING_APP]: false, + }); + await waitForBatchedUpdates(); + + // Then the caller-provided loading state survives the clear + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.IS_LOADING_APP, + callback: (value) => { + expect(value).toBe(false); + Onyx.disconnect(connection); + resolve(); + }, + }); + }); + }); + it('does not let extraSeeds override the LAST_FULL_RECONNECT_TIME seed', async () => { // Caller tries to override the timestamp seed with an empty string — the helper must win. await clearOnyxAndSeedFullReconnect([], { @@ -138,10 +160,8 @@ describe('actions/clearOnyxAndSeedFullReconnect', () => { }); await waitForBatchedUpdates(); - // Preserve SESSION, seed IS_LOADING_APP, leave the rest to be cleared. - await clearOnyxAndSeedFullReconnect([ONYXKEYS.SESSION], { - [ONYXKEYS.IS_LOADING_APP]: true, - }); + // Preserve SESSION and leave the rest to be cleared. + await clearOnyxAndSeedFullReconnect([ONYXKEYS.SESSION]); await waitForBatchedUpdates(); await new Promise((resolve) => { diff --git a/tests/actions/SessionTest.ts b/tests/actions/SessionTest.ts index bd0359117cdb..f4a415ea99c4 100644 --- a/tests/actions/SessionTest.ts +++ b/tests/actions/SessionTest.ts @@ -807,6 +807,7 @@ describe('Session', () => { describe('validateTwoFactorAuth', () => { test('forced onboarding path updates auth token before clearing Onyx without openApp', async () => { + // Given a user completing forced-onboarding 2FA while the success screen remains open. const makeRequestSpy = jest.spyOn(API, 'makeRequestWithSideEffects').mockResolvedValue({ authToken: 'newAuthToken', encryptedAuthToken: 'newEncryptedAuthToken', @@ -816,9 +817,11 @@ describe('Session', () => { const clearSpy = jest.spyOn(Onyx, 'clear').mockResolvedValue(undefined); const writeWithNoDuplicatesSpy = jest.spyOn(API, 'writeWithNoDuplicatesConflictAction').mockResolvedValue(undefined); + // When the 2FA validation succeeds. SessionUtil.validateTwoFactorAuth('123456', false, {shouldKeepTwoFactorAuthFlowOpen: true}); await waitForBatchedUpdates(); + // Then the next authenticated state is seeded before Onyx is cleared without entering the global loading state. expect(makeRequestSpy).toHaveBeenCalledWith(SIDE_EFFECT_REQUEST_COMMANDS.TWO_FACTOR_AUTH_VALIDATE, {twoFactorAuthCode: '123456'}, expect.any(Object)); expect(setAuthTokenSpy).toHaveBeenCalledWith('newAuthToken'); expect(setAuthTokenSpy.mock.invocationCallOrder.at(0)).toBeLessThan(multiSetSpy.mock.invocationCallOrder.at(0) ?? Number.MAX_SAFE_INTEGER); @@ -833,6 +836,7 @@ describe('Session', () => { [ONYXKEYS.NVP_ONBOARDING]: { hasCompletedGuidedSetupFlow: false, }, + [ONYXKEYS.IS_LOADING_APP]: false, }), ); expect(clearSpy).toHaveBeenCalled(); diff --git a/tests/unit/AuthPrefetchTest.ts b/tests/unit/AuthPrefetchTest.ts index 379e7a1fc2b1..1dfece97b6b2 100644 --- a/tests/unit/AuthPrefetchTest.ts +++ b/tests/unit/AuthPrefetchTest.ts @@ -55,7 +55,7 @@ describe('auth startup prefetch cleanup', () => { it('clears native startup prefetches before resetting Onyx for an identity transition', async () => { const clearOnyxAndSeedFullReconnect = (await import('@userActions/clearOnyxAndSeedFullReconnect')).default; - await clearOnyxAndSeedFullReconnect([ONYXKEYS.SESSION], {[ONYXKEYS.IS_LOADING_APP]: true}); + await clearOnyxAndSeedFullReconnect([ONYXKEYS.SESSION]); expect(mockClearPrefetchOnAppStart).toHaveBeenCalledTimes(2); expect(mockMultiSet).toHaveBeenCalledWith({ diff --git a/tests/unit/Navigation/createScheduleOnceTest.ts b/tests/unit/Navigation/createScheduleOnceTest.ts new file mode 100644 index 000000000000..b84a3b2e77ac --- /dev/null +++ b/tests/unit/Navigation/createScheduleOnceTest.ts @@ -0,0 +1,22 @@ +import createScheduleOnce from '@libs/Navigation/helpers/createScheduleOnce'; + +describe('createScheduleOnce', () => { + it('coalesces pending calls and can schedule again after the callback runs', async () => { + const run = jest.fn(); + const schedule = createScheduleOnce(run); + + schedule(); + schedule(); + + expect(run).not.toHaveBeenCalled(); + + await Promise.resolve(); + + expect(run).toHaveBeenCalledTimes(1); + + schedule(); + await Promise.resolve(); + + expect(run).toHaveBeenCalledTimes(2); + }); +}); diff --git a/tests/unit/Navigation/guards/MigratedUserWelcomeModalGuard.test.ts b/tests/unit/Navigation/guards/MigratedUserWelcomeModalGuard.test.ts index e2c02b04c28f..bb0291812b0d 100644 --- a/tests/unit/Navigation/guards/MigratedUserWelcomeModalGuard.test.ts +++ b/tests/unit/Navigation/guards/MigratedUserWelcomeModalGuard.test.ts @@ -2,10 +2,13 @@ import MigratedUserWelcomeModalGuard, {onSessionOrLoadingAppChanged, resetDismis import type {GuardContext} from '@libs/Navigation/guards/types'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; +import clearOnyxAndSeedFullReconnect from '@userActions/clearOnyxAndSeedFullReconnect'; + import CONST from '@src/CONST'; import NAVIGATORS from '@src/NAVIGATORS'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; +import type {Route} from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; import type {NavigationAction, NavigationState} from '@react-navigation/native'; @@ -17,11 +20,12 @@ import waitForBatchedUpdates from '../../../utils/waitForBatchedUpdates'; const migratedUserWelcomeRoute = createDynamicRoute(DYNAMIC_ROUTES.MIGRATED_USER_WELCOME.path, ROUTES.HOME); const mockNavigate = jest.fn(); +let mockActiveRoute: Route = ROUTES.HOME; jest.mock('@libs/Navigation/Navigation', () => ({ navigate: (...args: unknown[]) => { mockNavigate(...args); }, - getActiveRoute: () => 'home', + getActiveRoute: () => mockActiveRoute, })); describe('MigratedUserWelcomeModalGuard', () => { @@ -53,6 +57,7 @@ describe('MigratedUserWelcomeModalGuard', () => { onSessionOrLoadingAppChanged(undefined, true); resetSessionFlag(); mockNavigate.mockClear(); + mockActiveRoute = ROUTES.HOME; await Onyx.clear(); await waitForBatchedUpdates(); }); @@ -420,10 +425,67 @@ describe('MigratedUserWelcomeModalGuard', () => { // Now signal that session is ready and app is done loading onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, false); + await waitForBatchedUpdates(); + + expect(mockNavigate).toHaveBeenCalledWith(migratedUserWelcomeRoute); + }); + + it('should use a valid base when the active route cannot host the modal', async () => { + mockActiveRoute = ROUTES.SETTINGS_TROUBLESHOOT; + await Onyx.merge(ONYXKEYS.NVP_TRY_NEW_DOT, { + nudgeMigration: { + timestamp: new Date(), + cohort: 'test', + }, + }); + await waitForBatchedUpdates(); + mockNavigate.mockClear(); + + onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, false); + await waitForBatchedUpdates(); expect(mockNavigate).toHaveBeenCalledWith(migratedUserWelcomeRoute); }); + it('should not navigate while cleared Onyx data is reloading', async () => { + // Given an eligible migrated user who dismissed the welcome modal before the app finished loading. + const session = {authToken: 'test-token', accountID: 123}; + mockActiveRoute = ROUTES.SETTINGS_TROUBLESHOOT; + await Onyx.merge(ONYXKEYS.NVP_TRY_NEW_DOT, { + nudgeMigration: { + timestamp: new Date(), + cohort: 'test', + }, + }); + await Onyx.merge(ONYXKEYS.NVP_DISMISSED_PRODUCT_TRAINING, { + migratedUserWelcomeModal: { + timestamp: new Date().toISOString(), + dismissedMethod: 'click', + }, + }); + await Onyx.set(ONYXKEYS.IS_LOADING_APP, false); + await waitForBatchedUpdates(); + onSessionOrLoadingAppChanged(session, false); + mockNavigate.mockClear(); + + const loadingAppConnection = Onyx.connect({ + key: ONYXKEYS.IS_LOADING_APP, + callback: (isLoadingApp) => onSessionOrLoadingAppChanged(session, isLoadingApp ?? true), + }); + + // When a full reconnect starts and clears the dismissed state. Preserve migration eligibility + // so this test isolates whether the helper raises the loading gate before the clear callbacks. + try { + await clearOnyxAndSeedFullReconnect([ONYXKEYS.IS_LOADING_APP, ONYXKEYS.NVP_TRY_NEW_DOT]); + await waitForBatchedUpdates(); + } finally { + Onyx.disconnect(loadingAppConnection); + } + + // Then the guard must not navigate using the transient post-clear state. + expect(mockNavigate).not.toHaveBeenCalled(); + }); + it('should not navigate when app is still loading', async () => { await Onyx.merge(ONYXKEYS.NVP_TRY_NEW_DOT, { nudgeMigration: { @@ -435,6 +497,7 @@ describe('MigratedUserWelcomeModalGuard', () => { mockNavigate.mockClear(); onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, true); + await waitForBatchedUpdates(); expect(mockNavigate).not.toHaveBeenCalled(); }); @@ -468,6 +531,7 @@ describe('MigratedUserWelcomeModalGuard', () => { mockNavigate.mockClear(); onSessionOrLoadingAppChanged(undefined, false); + await waitForBatchedUpdates(); expect(mockNavigate).not.toHaveBeenCalled(); }); @@ -480,6 +544,7 @@ describe('MigratedUserWelcomeModalGuard', () => { mockNavigate.mockClear(); onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, false); + await waitForBatchedUpdates(); expect(mockNavigate).not.toHaveBeenCalled(); }); @@ -501,6 +566,7 @@ describe('MigratedUserWelcomeModalGuard', () => { mockNavigate.mockClear(); onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, false); + await waitForBatchedUpdates(); expect(mockNavigate).not.toHaveBeenCalled(); }); @@ -517,6 +583,7 @@ describe('MigratedUserWelcomeModalGuard', () => { onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, false); onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, false); + await waitForBatchedUpdates(); expect(mockNavigate).toHaveBeenCalledTimes(1); }); @@ -524,6 +591,7 @@ describe('MigratedUserWelcomeModalGuard', () => { it('should navigate via Onyx NVP_DISMISSED_PRODUCT_TRAINING callback when session is already set', async () => { // Set session first onSessionOrLoadingAppChanged({authToken: 'test-token', accountID: 123}, false); + await waitForBatchedUpdates(); mockNavigate.mockClear(); // Set up nudge migration and dismissed product training (modal not dismissed)