Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
20 changes: 16 additions & 4 deletions src/libs/Navigation/guards/MigratedUserWelcomeModalGuard.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -62,22 +71,25 @@ 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.
*/
function onSessionOrLoadingAppChanged(sessionValue: OnyxEntry<Session>, isLoadingAppValue: boolean) {
session = sessionValue;
isLoadingApp = isLoadingAppValue;
navigateToMigratedUserWelcomeModalIfReady();
scheduleMigratedUserWelcomeModalEvaluation();
}

Onyx.connectWithoutView({
key: ONYXKEYS.NVP_TRY_NEW_DOT,
callback: (value) => {
const result = value ? tryNewDotOnyxSelector(value) : undefined;
hasBeenAddedToNudgeMigration = result?.hasBeenAddedToNudgeMigration ?? false;
navigateToMigratedUserWelcomeModalIfReady();
scheduleMigratedUserWelcomeModalEvaluation();
},
});

Expand All @@ -89,7 +101,7 @@ Onyx.connectWithoutView({
if (isProductTrainingElementDismissed('migratedUserWelcomeModal', value)) {
hasRedirectedToMigratedUserModal = false;
}
navigateToMigratedUserWelcomeModalIfReady();
scheduleMigratedUserWelcomeModalEvaluation();
},
});

Expand Down
55 changes: 11 additions & 44 deletions src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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
Expand All @@ -54,37 +52,15 @@ function releaseWelcomeModalForSubmitDeeplink() {
hasPendingSubmitDeeplink = false;
}

const SUBMIT_PLAN_WELCOME_ENTRY_SCREENS = new Set<string>(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() {
Expand Down Expand Up @@ -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.
Expand Down
20 changes: 20 additions & 0 deletions src/libs/Navigation/helpers/createScheduleOnce.ts
Original file line number Diff line number Diff line change
@@ -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;
37 changes: 37 additions & 0 deletions src/libs/Navigation/helpers/getValidDynamicRouteBasePath.ts
Original file line number Diff line number Diff line change
@@ -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<Screen | '*'>;
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;
5 changes: 3 additions & 2 deletions src/libs/actions/App.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down
13 changes: 2 additions & 11 deletions src/libs/actions/Delegate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
return clearOnyxAndSeedFullReconnect(KEYS_TO_PRESERVE_DELEGATE_ACCESS, {
[ONYXKEYS.IS_LOADING_APP]: true,
});
return clearOnyxAndSeedFullReconnect(KEYS_TO_PRESERVE_DELEGATE_ACCESS);
}

type WithDelegatedAccess = {
Expand Down
3 changes: 3 additions & 0 deletions src/libs/actions/Session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
9 changes: 6 additions & 3 deletions src/libs/actions/clearOnyxAndSeedFullReconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,19 @@ 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<void> {
// Any Onyx reset can preserve or replace SESSION/CREDENTIALS while dropping account-scoped data.
// Clear native startup prefetches so a cold start cannot replay requests from the previous identity.
await clearPrefetchOnAppStart();

const seeds: OnyxMultiSetInput = {
[ONYXKEYS.IS_LOADING_APP]: true,
...extraSeeds,
[ONYXKEYS.LAST_FULL_RECONNECT_TIME]: DateUtils.getDBTime(),
};
Expand Down
36 changes: 28 additions & 8 deletions tests/actions/ClearOnyxAndSeedFullReconnectTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>((resolve) => {
const connection = Onyx.connect({
key: ONYXKEYS.IS_LOADING_APP,
Expand All @@ -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<void>((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([], {
Expand Down Expand Up @@ -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<void>((resolve) => {
Expand Down
4 changes: 4 additions & 0 deletions tests/actions/SessionTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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);
Expand All @@ -833,6 +836,7 @@ describe('Session', () => {
[ONYXKEYS.NVP_ONBOARDING]: {
hasCompletedGuidedSetupFlow: false,
},
[ONYXKEYS.IS_LOADING_APP]: false,
}),
);
expect(clearSpy).toHaveBeenCalled();
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/AuthPrefetchTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/Navigation/createScheduleOnceTest.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading