Skip to content

[Due for payment 2026-10-23] [$250] Copilot-User is logged out after remove copilot then kill app and open again #93458

Closed

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.4.6-0
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: #91989
Email or phone of affected tester (no customers): duytestnguyen+242@gmail.com
Issue reported by: Applause Internal Team
Bug source: Exploratory - Critical User Impact
Device used: Android 16 / Pixel 7A
App Component: User Settings

Action Performed:

Preconditions:

  • Account A add Account B as a full copilot
  • Log in to Account B
  1. Open hybrid app
  2. Switch into A's account via the copilot dropdown
  3. Go the copilot page
  4. Remove B as the copilot
  5. After the app loading, kill the app
  6. Reopen the app
  7. Do some action

Expected Result:

User stay in ND expenience as Account B

Actual Result:

User is in OD experience, then logged out
In prod, user is logged out only

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

Bug7179080_1781280841171.Screenrecording_06-12-2026_22-38-22_1.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Svetlana Lazutkina
Bug ID: 7179080

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @jmusial

Activity

  1. added
    Daily
    Bug
    on Jun 12, 2026
  2. MelvinBot commented on Jun 12, 2026

    @MelvinBot
    Contributor

    Proposal

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

    When a copilot (delegate B) is acting as the delegator (account A) and removes themselves from A's copilot list, killing and reopening the app leaves B logged out (on HybridApp: briefly in the OldDot experience, then logged out).

    What is the root cause of that problem?

    Removing yourself as a copilot while connected as that account is meant to drop you back to your own account, but the recovery is asynchronous and interruptible, and the repro kills the app right inside that window.

    1. While B acts as A, CopilotPage explicitly allows B to remove their own row — the "no access" guard only blocks removing other delegates: CopilotPage.tsx:329 / :344-348 (the condition selectedDelegate?.email !== account?.delegatedAccess?.delegate is false for self-removal).
    2. The safety net that returns B to their own account is DelegateAccessHandler.tsx:31-40: when B is no longer in the delegates list, it calls disconnect(). But it only fires after REMOVE_DELEGATE succeeds — removeDelegate's optimistic data only marks a pending DELETE, and B is filtered from the list in successData: Delegate.ts:506-576.
    3. disconnect() is itself a long async transition (another server round-trip, then it rewrites SESSION from the stashed session and re-opens the app): Delegate.ts:243-343.

    So there is a wide window where the persisted SESSION still holds A's restricted token (now revoked server-side) while B's stashed session hasn't been restored yet. Killing the app here (step 5 of the repro) persists that broken delegated session. On cold start, the App's reauth fallback (Reauthentication.ts:210-216 → restoreDelegateSession) is supposed to recover B using the still-present CREDENTIALS, but in the HybridApp build the OldDot layer initializes against the invalid token first (hence the OD experience) and the user ends up signed out instead of restored.

    Investigation details & evidence chain
    • connect() stashes B's credentials/session and swaps the live SESSION authToken to A's restrictedToken, but never overwrites CREDENTIALS — so B's autoGeneratedLogin/Password remain available for cold-start reauth: Delegate.ts:137-241.
    • account.delegatedAccess.delegate = the acting delegate's email (B); delegatedAccess.delegates = A's copilot list. The handler check delegates.some(d => d.email === delegate) is correct for this scenario and does fire once B is filtered out — the problem is timing/persistence, not the check itself.
    • Cold-start path: reconnectApp/openApp runs with A's revoked restricted token → NOT_AUTHENTICATED → reauthenticate() re-Authenticates with B's CREDENTIALS → isConnectedAsDelegate → restoreDelegateSession. This recovers B on standalone NewDot in principle, but the reported end-state is still logout, and the OD-experience flash points to the HybridApp/OldDot layer signing out first.
    • Confidence: Medium. The App-side race + persisted-invalid-token mechanism is well supported by code. The exact cold-start logout step lives partly in HybridApp (Mobile-Expensify), which I can't inspect, so the failure mode there is unconfirmed without production logs.

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

    App-side mitigation (narrows the race): when the user removes their own row while acting as the delegator (selectedDelegate.email === account?.delegatedAccess?.delegate), trigger the return-to-own-account flow immediately/optimistically instead of waiting on REMOVE_DELEGATE success — e.g. call disconnect() (or fold B out of the list in removeDelegate's optimisticData) at Delegate.ts:506-576 so DelegateAccessHandler fires without the extra round-trip.

    ⚠️ This App-side change shrinks but does not fully close the window, and it does not address the core symptom: a persisted, invalidated delegated session logging the user out on cold start. That recovery happens in the HybridApp/OldDot layer (Mobile-Expensify), which is outside this repo — an internal engineer should investigate why cold start signs the user out instead of falling back to the stashed (own-account) session. Production logs are recommended to confirm which reauth branch fires (look for [Reauthenticate] and [Delegate] lines for the affected tester).

    What alternative solutions did you explore?

    Blocking self-removal entirely while acting as the delegator (show the no-access modal) — rejected, since removing your own copilot access is a legitimate action; the fix should make it safe, not forbid it.

    Possibly related


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/93458) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.

  3. added
    External
    on Jun 12, 2026
  4. aswin-s commented on Jun 12, 2026

    @aswin-s
    Contributor

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

    On Android and iOS hybrid app, when a copilot (Account B) is acting as Account A and removes themselves as A's copilot from the Copilot page, the app keeps the now-revoked restricted auth token in the active session instead of restoring B's own stashed session. After killing and reopening the app, the user lands in OD experience and is then logged out (in production, immediately logged out). Expected: B stays signed in under their own ND session.

    What is the root cause of that problem?

    In src/pages/settings/Copilot/CopilotPage.tsx:329-348, the "Remove copilot" handler explicitly permits the acting delegate to remove their own copilot row (selectedDelegate?.email !== account?.delegatedAccess?.delegate && isActingAsDelegate — the inverse branch lets it through), and then calls removeDelegate(...) at line 348. removeDelegate in src/libs/actions/Delegate.ts:506-576 only fires the REMOVE_DELEGATE API and mutates the delegates list — it never restores the stashed delegate-owner session. The active ONYXKEYS.SESSION still holds A's restricted token (granted to B as A's copilot), but the server-side delegation has just been revoked. On next cold start, that restricted token is no longer valid for B, so the persisted session reauths into A's OD context and then fails out / logs the user out, while B's real session sits unused in ONYXKEYS.STASHED_SESSION.

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

    1. In src/pages/settings/Copilot/CopilotPage.tsx around line 348, detect the self-removal case (isActingAsDelegate && selectedDelegate?.email === session?.email) and call disconnect({stashedCredentials, stashedSession}) from @libs/actions/Delegate before calling removeDelegate. This restores ONYXKEYS.SESSION and ONYXKEYS.CREDENTIALS to B's own stashed values and triggers HybridAppModule.switchAccount back to B — mirroring the existing copilot-dropdown "switch back" flow that already uses disconnect.

    2. The key sequencing constraint: removeDelegate must be issued after disconnect completes and B's own session is active. The reason is that removeDelegate sends only delegateEmail in its API payload and authenticates using whichever session is currently active in ONYXKEYS.SESSION. If removeDelegate ran while A's restricted token were still active, the request would authenticate as A removing B — which is semantically correct for the server call but happens under a token that the server has not yet invalidated. More importantly, the Onyx optimistic data in removeDelegate targets A's delegate list, so the call must still reference A's delegatedAccess data. To satisfy both requirements, pass A's delegatedAccess snapshot into removeDelegate explicitly before switching sessions, and issue the API.write call after disconnect under B's restored token:

    // CopilotPage.tsx — self-removal path
    if (isActingAsDelegate && selectedDelegate?.email === session?.email) {
        // Capture A's delegatedAccess before disconnect clears it from Onyx
        const delegatedAccessSnapshot = account?.delegatedAccess;
        await disconnect({stashedCredentials, stashedSession});
        // Now running under B's own session; pass the captured snapshot so
        // removeDelegate can build optimistic data against A's delegate list
        removeDelegate({email: selectedDelegate.email, delegatedAccess: delegatedAccessSnapshot});
    } else {
        removeDelegate({email: selectedDelegate.email, delegatedAccess: account?.delegatedAccess});
    }
    1. In src/libs/actions/Delegate.ts removeDelegate (line 506), as a defense-in-depth guard, accept an optional currentDelegateEmail/session arg and, when removing the currently-acting delegate, invoke the same disconnect path internally so any other callsite is also safe.

    2. Verify on both Android and iOS hybrid app that after self-removal the HybridAppModule.switchAccount call restores B's OD bridge account and that STASHED_SESSION/STASHED_CREDENTIALS are cleared, matching the post-condition of the normal disconnect flow at Delegate.ts:319-336.

    What alternative solutions did you explore? (Optional)

    Forcing a signOut on self-removal would log B out cleanly but loses B's session unnecessarily; restoring via disconnect keeps B signed in, which matches the Expected Result.

    An alternative ordering — calling removeDelegate first under A's token and then disconnect — keeps the authenticated account consistent for the API call, but leaves the app in the revoked-token state until disconnect completes. If the user kills the app in that window (exactly the bug scenario), the same logout occurs. The disconnect-first approach eliminates that window entirely by making B's session active before any network round-trip completes.

  5. added
    Help Wanted
    on Jun 12, 2026
  6. yusufdeveloper2903 commented on Jun 12, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

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

    When a copilot (Account B) is switched into the delegator's account (Account A) and removes themselves as A's copilot from the copilot page, the app keeps running on the now-revoked delegated session. After killing and reopening the app, the user is dropped into OldDot and then logged out, instead of staying in NewDot as Account B.

    What is the root cause of that problem?

    When B switches into A, connect() overwrites the persisted ONYXKEYS.SESSION with A's restricted delegated token and stashes B's original session/credentials separately:

    return SequentialQueue.waitForIdle()
    .then(() => {
    // Update authToken in Onyx so it persists if the further flow does not complete for any reason.
    return updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken);
    })
    .then(() => {
    NetworkStore.setAuthToken(response?.restrictedToken ?? null);
    return clearOnyxForDelegateTransition();
    })
    .then(() => {
    confirmReadyToOpenApp();
    return openApp().then(() => {
    if (!CONFIG.IS_HYBRID_APP || !policyID) {
    return true;
    }
    HybridAppModule.switchAccount({
    newDotCurrentAccountEmail: email,
    authToken: restrictedToken,
    policyID,
    accountID: String(session?.accountID ?? CONST.DEFAULT_NUMBER_ID),
    });
    return true;
    });
    });

    So from that point on, the session written to disk is A's restricted token, while B's real session lives only in STASHED_SESSION / STASHED_CREDENTIALS.

    The copilot page explicitly allows the connected delegate to remove their own access. The guard only blocks removing other delegates while acting as a delegate — removing yourself (selectedDelegate.email === account.delegatedAccess.delegate) falls straight through to removeDelegate:

    onPress: () => {
    if (selectedDelegate?.email !== account?.delegatedAccess?.delegate && isActingAsDelegate) {
    modalClose(() => showDelegateNoAccessModal());
    return;
    }
    if (isAccountLocked) {
    modalClose(() => showLockedAccountModal());
    return;
    }
    modalClose(() => {
    setShouldShowDelegatePopoverMenu(false);
    setSelectedEmail(undefined);
    showRemoveCopilotModal().then((result) => {
    if (result.action === ModalActions.CLOSE) {
    setSelectedDelegate(undefined);
    } else {
    if (selectedDelegate?.email !== account?.delegatedAccess?.delegate && isActingAsDelegate) {
    showDelegateNoAccessModal();
    return;
    }
    removeDelegate({email: selectedDelegate?.email ?? '', delegatedAccess: account?.delegatedAccess});
    setSelectedDelegate(undefined);
    }
    });
    });
    },

    removeDelegate then fires REMOVE_DELEGATE and updates the delegates list, but does nothing to tear down the delegated session it is running inside:

    function removeDelegate({email, delegatedAccess}: RemoveDelegateParams) {
    if (!email || !delegatedAccess?.delegates) {
    return;
    }
    const optimisticData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    delegatedAccess: {
    errorFields: {
    removeDelegate: {
    [email]: null,
    },
    },
    delegates: delegatedAccess.delegates?.map((delegate) =>
    delegate.email === email
    ? {
    ...delegate,
    pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
    pendingFields: {email: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, role: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE},
    }
    : delegate,
    ),
    },
    },
    },
    ];
    const successData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    delegatedAccess: {
    delegates: delegatedAccess.delegates?.filter((delegate) => delegate.email !== email),
    },
    },
    },
    ];
    const failureData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    delegatedAccess: {
    errorFields: {
    removeDelegate: {
    [email]: null,
    },
    },
    delegates: delegatedAccess.delegates?.map((delegate) =>
    delegate.email === email
    ? {
    ...delegate,
    pendingAction: null,
    pendingFields: undefined,
    }
    : delegate,
    ),
    },
    },
    },
    ];
    const parameters: APIRemoveDelegateParams = {delegateEmail: email};
    API.write(WRITE_COMMANDS.REMOVE_DELEGATE, parameters, {optimisticData, successData, failureData});
    }

    Once the server processes the removal, A's restricted token is revoked. The app keeps working only because NetworkStore still holds the cached restricted token in memory — nothing forces a re-auth while the app stays open. That is why the symptom only appears after a cold restart: on relaunch, HybridApp boots from the persisted ONYXKEYS.SESSION, which is still A's now-invalid restricted token. Re-authentication with that dead token fails → the app falls back to OldDot → logout. (account.delegatedAccess.delegate is "the email of the original user when they are acting as a delegate", i.e. B — confirming the removed email is the current operator:

    /** The email of original user when they are acting as a delegate for another account */
    delegate?: string;
    )

    In short: self-removal while connected as a delegate orphans the delegated session. The client revokes its own token but never restores B's stashed session, so the persisted session is left pointing at a token that dies on the next launch.

    For comparison, the normal "switch back" path (disconnect) does the teardown correctly — it restores the stashed session and even has a fallback to restoreDelegateSession(stashedSession) when no fresh token comes back:

    API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.DISCONNECT_AS_DELEGATE, {}, {optimisticData, successData, failureData})
    .then((response) => {
    if (!response?.authToken || !response?.encryptedAuthToken) {
    Log.alert('[Delegate] No auth token returned while disconnecting as a delegate');
    restoreDelegateSession(stashedSession ?? {});
    return;
    }
    if (!response?.requesterID || !response?.requesterEmail) {
    Log.alert('[Delegate] No requester data returned while disconnecting as a delegate');
    restoreDelegateSession(stashedSession ?? {});
    return;

    removeDelegate is missing that teardown for the self-removal case.

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

    When the delegate being removed is the user we are currently connected as, we must return to the original (stashed) account after the removal — exactly what disconnect() already does. I'd detect this case in removeDelegate and, once the REMOVE_DELEGATE write has drained, run disconnect():

    -function removeDelegate({email, delegatedAccess}: RemoveDelegateParams) {
    +function removeDelegate({email, delegatedAccess, stashedCredentials, stashedSession}: RemoveDelegateParams) {
         if (!email || !delegatedAccess?.delegates) {
             return;
         }
    +
    +    // True when the connected delegate is removing their own copilot access.
    +    const isRemovingOwnDelegateAccess = isConnectedAsDelegate({delegatedAccess}) && delegatedAccess.delegate === email;
         ...
         API.write(WRITE_COMMANDS.REMOVE_DELEGATE, parameters, {optimisticData, successData, failureData});
    +
    +    // Wait for REMOVE_DELEGATE to be sent (so it is still authenticated as the delegator) before
    +    // swapping back to the original session, otherwise the delegated token would be torn down first.
    +    if (isRemovingOwnDelegateAccess) {
    +        SequentialQueue.waitForIdle().then(() => disconnect({stashedCredentials, stashedSession}));
    +    }
    }

    Supporting changes (described, not full diffs):

    • Extend RemoveDelegateParams to also carry stashedCredentials / stashedSession (WithStashedCredentials & WithStashedSession), and pass them from the removeDelegate(...) call site in CopilotPage via useOnyx(ONYXKEYS.STASHED_CREDENTIALS) / useOnyx(ONYXKEYS.STASHED_SESSION) — the same values AccountSwitcher already feeds into disconnect().

    Why this is robust:

    • Ordering / no auth race: SequentialQueue.waitForIdle() (already imported in this file) guarantees the REMOVE_DELEGATE write is flushed while we are still authenticated as A, before disconnect() swaps NetworkStore/SESSION to B. So the removal can't accidentally run under B's token.
    • No dependence on a fresh token: after self-removal the delegate link is gone, so DISCONNECT_AS_DELEGATE may not return a usable token — but disconnect() already falls back to restoreDelegateSession(stashedSession) in that exact case (L284-L293), which clears Onyx, restores B's session and calls openApp(). Either way the persisted SESSION ends up as B's valid token, so the next cold start boots cleanly into NewDot as B.
    • Offline: the removal modal is already gated behind the offline/locked-account checks at the call site; if a user manages to trigger it offline, disconnect() resolves once connectivity returns and the queue drains, and the stashed session is preserved meanwhile via KEYS_TO_PRESERVE_DELEGATE_ACCESS.
    • Platforms: the fix is in shared JS (Delegate.ts / CopilotPage.tsx), so it covers both iOS and Android App, which are the affected platforms.

    What alternative solutions did you explore? (Optional)

    • Block self-removal while acting as a delegate (show the "no access" modal like the existing guard does for other delegates). Rejected — the expected result is that the user can remove their own copilot access and is returned to their own account, not that the action is forbidden.
    • Backend-only fix (have the server invalidate/redirect the session on self-removal). Even if the backend cooperates, the client still has A's restricted token persisted in ONYXKEYS.SESSION; without a client-side restore of the stashed session the orphaned token is what gets loaded on the next launch. So a client change is required regardless.
  7. lorretheboy commented on Jun 12, 2026

    @lorretheboy
    Contributor

    Proposal

    What is the root cause of that problem?

    When you connect as a copilot, connect stashes your own credentials into STASHED_CREDENTIALS and then runs clearOnyxForDelegateTransition, which wipes Onyx while preserving only the delegate keys. ONYXKEYS.CREDENTIALS is not in that preserve list, so while you are acting as the copilot your own login lives only in STASHED_CREDENTIALS and CREDENTIALS is empty:

    const KEYS_TO_PRESERVE_DELEGATE_ACCESS = [
    ONYXKEYS.NVP_TRY_FOCUS_MODE,
    ONYXKEYS.PREFERRED_THEME,
    ONYXKEYS.NVP_PREFERRED_LOCALE,
    ONYXKEYS.RAM_ONLY_ARE_TRANSLATIONS_LOADING,
    ONYXKEYS.SESSION,
    ONYXKEYS.STASHED_SESSION,
    ONYXKEYS.HAS_LOADED_APP,
    ONYXKEYS.STASHED_CREDENTIALS,
    ONYXKEYS.HYBRID_APP,
    // We need to preserve the sidebar loaded state since we never unmount the sidebar when connecting as a delegate
    // This allows the report screen to load correctly when the delegate token expires and the delegate is returned to their original account.
    ONYXKEYS.RAM_ONLY_IS_SIDEBAR_LOADED,
    ONYXKEYS.NETWORK,
    ONYXKEYS.SHOULD_USE_STAGING_SERVER,
    ONYXKEYS.IS_DEBUG_MODE_ENABLED,
    ONYXKEYS.COLLECTION.PASSKEY_CREDENTIALS,
    ONYXKEYS.COLLECTION.DEVICE_BIOMETRICS,
    ];

    Removing yourself (B) as the delegator's (A) copilot revokes A's restricted token on the backend. Returning you to your own account is handled only reactively and asynchronously: DelegateAccessHandler notices the delegate is gone from the list and calls disconnect, and disconnect restores SESSION/CREDENTIALS from the stashed copies only at the very end of a network round-trip.

    // Disconnect delegate when the delegate is no longer in the delegates list
    useEffect(() => {
    if (!account?.delegatedAccess?.delegate) {
    return;
    }
    if (account?.delegatedAccess?.delegates?.some((d) => d.email === account?.delegatedAccess?.delegate)) {
    return;
    }
    disconnect({stashedCredentials, stashedSession});
    }, [account?.delegatedAccess?.delegates, account?.delegatedAccess?.delegate, stashedCredentials, stashedSession]);

    return SequentialQueue.waitForIdle()
    .then(() => {
    return Promise.all([
    Onyx.set(ONYXKEYS.SESSION, {
    ...stashedSession,
    accountID: response.requesterID,
    email: requesterEmail,
    authToken,
    encryptedAuthToken: response.encryptedAuthToken,
    }),
    Onyx.merge(ONYXKEYS.ACCOUNT, {
    primaryLogin: requesterEmail,
    }),
    ]);
    })
    .then(() => {
    NetworkStore.setAuthToken(response?.authToken ?? null);
    return clearOnyxForDelegateTransition();
    })
    .then(() => {
    Onyx.set(ONYXKEYS.CREDENTIALS, {
    ...stashedCredentials,
    accountID: response.requesterID,
    });
    Onyx.set(ONYXKEYS.STASHED_CREDENTIALS, {});
    Onyx.set(ONYXKEYS.STASHED_SESSION, {});

    If you kill the app during this "loading" window, persisted Onyx still holds A's now-revoked restricted token in SESSION and an empty CREDENTIALS. On relaunch the first request is rejected, reauthenticate runs, finds no credentials, and signs you out:

    // Prevent reauthentication if credentials are missing (e.g. after sign out)
    if (!credentials?.autoGeneratedLogin || !credentials?.autoGeneratedPassword) {
    Log.info('[Reauthenticate] No credentials available, redirecting to sign in');
    setIsAuthenticating(false);
    redirectToSignIn('No credentials available');
    return false;
    }

    Note that reauthenticate already has a branch designed to handle exactly "the delegate token is no longer valid → restore the original account", but it can never run here because the missing-credentials guard above bails out first:

    // If we reauthenticate due to an expired delegate token, restore the delegate's original account.
    // This is because the credentials used to reauthenticate were for the delegate's original account, and not for the account they were connected as.
    if (isConnectedAsDelegate({delegatedAccess: account?.delegatedAccess})) {
    Log.info('[Reauthenticate] Reauthenticate while connected as a delegate. Restoring original account.');
    restoreDelegateSession(response);
    return true;
    }

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

    Preserve the user's own credentials across the delegate transition by adding ONYXKEYS.CREDENTIALS to KEYS_TO_PRESERVE_DELEGATE_ACCESS:

    const KEYS_TO_PRESERVE_DELEGATE_ACCESS = [
    ONYXKEYS.NVP_TRY_FOCUS_MODE,
    ONYXKEYS.PREFERRED_THEME,
    ONYXKEYS.NVP_PREFERRED_LOCALE,
    ONYXKEYS.RAM_ONLY_ARE_TRANSLATIONS_LOADING,
    ONYXKEYS.SESSION,
    ONYXKEYS.STASHED_SESSION,
    ONYXKEYS.HAS_LOADED_APP,
    ONYXKEYS.STASHED_CREDENTIALS,
    ONYXKEYS.HYBRID_APP,
    // We need to preserve the sidebar loaded state since we never unmount the sidebar when connecting as a delegate
    // This allows the report screen to load correctly when the delegate token expires and the delegate is returned to their original account.
    ONYXKEYS.RAM_ONLY_IS_SIDEBAR_LOADED,
    ONYXKEYS.NETWORK,
    ONYXKEYS.SHOULD_USE_STAGING_SERVER,
    ONYXKEYS.IS_DEBUG_MODE_ENABLED,
    ONYXKEYS.COLLECTION.PASSKEY_CREDENTIALS,
    ONYXKEYS.COLLECTION.DEVICE_BIOMETRICS,
    ];

    With CREDENTIALS surviving the clear, a relaunch with the revoked restricted token reauthenticates successfully as the original user, and because the delegate field is still set, the existing isConnectedAsDelegate branch in reauthenticate calls restoreDelegateSession and returns the user to their own (ND) account instead of logging them out. This is safe credential-wise since the same credentials are already kept in STASHED_CREDENTIALS.

    What alternative solutions did you explore? (Optional)

    Make the recovery explicit rather than relying on the credentials guard: in reauthenticate, before redirecting to sign-in for missing credentials, detect a stashed delegate session (STASHED_SESSION/STASHED_CREDENTIALS still present) and restore the original account from the stash. This handles the interrupted-disconnect state directly even if credentials were unavailable for any other reason.

  8. ahmdshrif commented on Jun 12, 2026

    @ahmdshrif
    Contributor

    Proposal

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

    After Account A removes Account B as a copilot, if Account B force-kills and reopens the (hybrid) app, B is bounced into the OldDot experience and then logged out, instead of staying signed into their own account in NewDot.

    What is the root cause of that problem?

    1. On app start HybridApp registers Onyx listeners that re-run signInToOldDotAndChooseExperience whenever nvp_tryNewDot/account change:

      Onyx.connectWithoutView({
      key: ONYXKEYS.NVP_TRY_NEW_DOT,
      callback: (tryNewDot) => {
      currentTryNewDot = tryNewDot;
      signInToOldDotAndChooseExperience(currentHybridApp, tryNewDot, currentCredentials, currentSession, currentAccount);
      },
      });

    2. The only guard before the OldDot redirect is tryNewDot !== undefined — an empty object {} passes it and calls closeReactNativeApp:

      App/src/libs/HybridApp.ts

      Lines 115 to 122 in 71d4330

      if (tryNewDot !== undefined) {
      setUseNewDotSignInPage(false).then(() => {
      if (shouldUseOldApp(tryNewDot) && (!account?.needsTwoFactorAuthSetup || account?.requiresTwoFactorAuth)) {
      closeReactNativeApp({shouldSetNVP: false, isTrackingGPS: false});
      } else {
      setReadyToShowAuthScreens(true);
      }
      });

    3. shouldUseOldApp returns true for any empty tryNewDot, since isEmptyObject(tryNewDot) short-circuits to true:

      function shouldUseOldApp(tryNewDot: TryNewDot): boolean | undefined {
      if (isLockedToNewApp(tryNewDot)) {
      return false;
      }
      if (isEmptyObject(tryNewDot) || isEmptyObject(tryNewDot.classicRedirect)) {
      return true;
      }
      return tryNewDot.classicRedirect.dismissed;
      }

    When the copilot link is torn down, B's nvp_tryNewDot is cleared and on cold reopen the Onyx callback fires with {} before the real NVP is re-fetched. So shouldUseOldApp({}) === true, closeReactNativeApp force-redirects B to OldDot, and because the delegate session was just severed the OldDot auto-auth fails → logout. This explains every detail: staging shows the splash then logout ("OD experience, then logged out"), prod skips the splash ("logged out only"), and only Android App / iOS App are affected (mWeb/desktop unchecked) because closeReactNativeApp only runs in the native hybrid app.

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

    In signInToOldDotAndChooseExperience, require the NVP to be hydrated (non-empty) — not merely !== undefined — before allowing the closeReactNativeApp redirect:

    if (tryNewDot !== undefined && !isEmptyObject(tryNewDot)) {
        setUseNewDotSignInPage(false).then(() => { ... });
    }

    While empty we keep the user in NewDot (setReadyToShowAuthScreens) and let the refetched NVP drive the decision on its next callback. Safe because genuine OldDot users have a populated tryNewDot (classicRedirect set during onboarding); the only case this changes is the transient post-disconnect {} that today wrongly forces the redirect.

    What alternative solutions did you explore? (Optional)

  9. David-2002065 commented on Jun 12, 2026

    @David-2002065
    Contributor

    Proposal

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

    When a copilot, while connected to the requester's account, removes themselves from the requester's copilots and then kills and reopens the app, they are dropped into the OldDot experience and logged out instead of staying in NewDot as their own account.

    What is the root cause of that problem?

    Removing yourself as the currently connected delegate and the session restore are two decoupled, asynchronous steps.

    1. On the copilot page, removeDelegate only fires REMOVE_DELEGATE (which invalidates the connected delegate's restricted token server-side) and updates the delegates list. It never restores the session:

      const parameters: APIAddDelegateParams = {delegateEmail: email, validateCode, role};
      API.write(WRITE_COMMANDS.ADD_DELEGATE, parameters, {optimisticData, successData, failureData});
      }
      function removeDelegate({email, delegatedAccess}: RemoveDelegateParams) {
      if (!email || !delegatedAccess?.delegates) {
      return;
      }
      const optimisticData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: ONYXKEYS.ACCOUNT,
      value: {
      delegatedAccess: {
      errorFields: {
      removeDelegate: {
      [email]: null,
      },
      },
      delegates: delegatedAccess.delegates?.map((delegate) =>
      delegate.email === email
      ? {
      ...delegate,
      pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
      pendingFields: {email: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, role: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE},
      }
      : delegate,
      ),
      },
      },
      },
      ];
      const successData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: ONYXKEYS.ACCOUNT,
      value: {
      delegatedAccess: {
      delegates: delegatedAccess.delegates?.filter((delegate) => delegate.email !== email),
      },
      },
      },
      ];
      const failureData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: ONYXKEYS.ACCOUNT,
      value: {
      delegatedAccess: {
      errorFields: {
      removeDelegate: {
      [email]: null,
      },
      },
      delegates: delegatedAccess.delegates?.map((delegate) =>
      delegate.email === email
      ? {
      ...delegate,
      pendingAction: null,
      pendingFields: undefined,
      }
      : delegate,
      ),
      },
      },
      },
      ];

    2. The actual session restore happens reactively, afterwards, in DelegateAccessHandler: once the success data drops the delegate from delegates, the effect calls disconnect():

      // Disconnect delegate when the delegate is no longer in the delegates list
      useEffect(() => {
      if (!account?.delegatedAccess?.delegate) {
      return;
      }
      if (account?.delegatedAccess?.delegates?.some((d) => d.email === account?.delegatedAccess?.delegate)) {
      return;
      }
      disconnect({stashedCredentials, stashedSession});
      }, [account?.delegatedAccess?.delegates, account?.delegatedAccess?.delegate, stashedCredentials, stashedSession]);

    3. disconnect() is itself a second network round-trip (DISCONNECT_AS_DELEGATE) and only restores SESSION/credentials inside its .then():

      },
      ];
      // We need to access the authToken directly from the response to update the session
      // eslint-disable-next-line rulesdir/no-api-side-effects-method
      API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.DISCONNECT_AS_DELEGATE, {}, {optimisticData, successData, failureData})
      .then((response) => {
      if (!response?.authToken || !response?.encryptedAuthToken) {
      Log.alert('[Delegate] No auth token returned while disconnecting as a delegate');
      restoreDelegateSession(stashedSession ?? {});
      return;
      }
      if (!response?.requesterID || !response?.requesterEmail) {
      Log.alert('[Delegate] No requester data returned while disconnecting as a delegate');
      restoreDelegateSession(stashedSession ?? {});
      return;
      }
      clearPreservedSearchNavigatorStates();
      const requesterEmail = response.requesterEmail;
      const authToken = response.authToken;
      return SequentialQueue.waitForIdle()
      .then(() => {
      return Promise.all([
      Onyx.set(ONYXKEYS.SESSION, {
      ...stashedSession,
      accountID: response.requesterID,
      email: requesterEmail,
      authToken,
      encryptedAuthToken: response.encryptedAuthToken,
      }),
      Onyx.merge(ONYXKEYS.ACCOUNT, {
      primaryLogin: requesterEmail,
      }),
      ]);
      })
      .then(() => {
      NetworkStore.setAuthToken(response?.authToken ?? null);
      return clearOnyxForDelegateTransition();
      })
      .then(() => {
      Onyx.set(ONYXKEYS.CREDENTIALS, {
      ...stashedCredentials,
      accountID: response.requesterID,
      });
      Onyx.set(ONYXKEYS.STASHED_CREDENTIALS, {});
      Onyx.set(ONYXKEYS.STASHED_SESSION, {});
      confirmReadyToOpenApp();
      openApp().then(() => {
      if (!CONFIG.IS_HYBRID_APP) {
      return;
      }
      HybridAppModule.switchAccount({
      newDotCurrentAccountEmail: requesterEmail,
      authToken,

    Between step 1 and the completion of step 3, the persisted SESSION still holds the requester's delegate token that the server has already invalidated. The repro deliberately kills the app in exactly this window (step 5). On the next launch openApp runs with that invalid delegate token, and on HybridApp the OldDot session is still pointed at the requester's account — so the user lands in OD and is signed out. The reactive disconnect/restore cannot run before openApp fires, and because the restore depends on a DISCONNECT_AS_DELEGATE request that itself uses the now-invalid token, it is not resilient to the kill.

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

    Make the session restore for self-removal happen locally and immediately, so we never persist (and never boot with) an invalidated delegate token, rather than gating it on a network DISCONNECT_AS_DELEGATE response.

    In DelegateAccessHandler's effect, when the connected delegate is no longer in the delegates list, restore the stashed (original) session right away via restoreDelegateSession, which clears the delegate Onyx state and re-seeds the original authToken synchronously before openApp:

    if (!account?.delegatedAccess?.delegates?.some((d) => d.email === account?.delegatedAccess?.delegate)) {
        restoreDelegateSession(stashedSession ?? {});
        disconnect({stashedCredentials, stashedSession}); // server-side cleanup, no longer gates the local restore
    }

    restoreDelegateSession already does exactly the local, network-independent restore we need (it does not depend on the live delegate token):

    isLoading: true,
    delegatedAccess: {
    errorFields: {
    updateDelegateRole: {
    [email]: null,
    },
    },
    delegates: delegatedAccess.delegates.map((delegate) =>
    delegate.email === email
    ? {
    ...delegate,
    isLoading: true,

    Because the original session is committed before openApp, the persisted state after the kill is the user's own valid account, so reopening keeps them in NewDot.

    Alternatively, we can handle this at the source in removeDelegate: when the removed email is the connected delegate (delegatedAccess.delegate === email), trigger the local restoreDelegateSession(stashedSession) as part of the same user action instead of relying on the post-success reactive effect, keeping REMOVE_DELEGATE/DISCONNECT_AS_DELEGATE purely for server-side bookkeeping.

    Note: there is already a boot-time safety net in reauthenticate that calls restoreDelegateSession when reauthenticating while connected as a delegate (

    // If we reauthenticate due to an expired delegate token, restore the delegate's original account.
    // This is because the credentials used to reauthenticate were for the delegate's original account, and not for the account they were connected as.
    if (isConnectedAsDelegate({delegatedAccess: account?.delegatedAccess})) {
    Log.info('[Reauthenticate] Reauthenticate while connected as a delegate. Restoring original account.');
    restoreDelegateSession(response);
    return true;
    }
    ); it does not catch this case because the kill leaves the invalid delegate token live before reauth can classify it, so restoring locally at the moment of self-removal is the robust fix.

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    Add a test for DelegateAccessHandler (and/or removeDelegate) asserting that when the connected delegate is removed from the delegates list, SESSION/CREDENTIALS are synchronously restored to the stashed original account and STASHED_* is cleared, without depending on a DISCONNECT_AS_DELEGATE response — i.e. the post-restore persisted session is the original account, not the invalidated delegate token.

    What alternative solutions did you explore? (Optional)

    Persist a "disconnect pending" marker before REMOVE_DELEGATE and, on boot, restore from STASHED_SESSION whenever that marker is present before openApp runs. This also survives the kill but adds new persisted state and a boot-order dependency, whereas restoring locally at the moment of self-removal reuses the existing restoreDelegateSession path with no new state.

  10. mukhrr commented on Jun 12, 2026

    @mukhrr
    Contributor

    Proposal

    What is the root cause of that problem?

    This is another hybrid copilot session-restore edge case. Prior fixes show this area has repeatedly broken when a removed/deleted copilot session is treated like a normal logout instead of restoring the stashed original user:

    • 81054f6 handled deleted copilot responses by forcing stashed-session restoration.
    • 87dc9a0 switched the hybrid app back to the stashed user instead of killing NewDot.
    • 2afcee1 reopened NewDot after the hybrid account switch to prevent stale UI/state after Account A removes Account B.
    • f1333d6 preserved STASHED_SESSION / STASHED_CREDENTIALS during clears to avoid returning to login after copilot removal.

    The current flow has the same shape, but the self-removal path still has an unsafe gap.

    When Account B is acting as Account A, Account B is stored in STASHED_SESSION / STASHED_CREDENTIALS. After B removes itself from A’s copilots, DelegateAccessHandler sees that the active delegate is no longer in delegatedAccess.delegates and calls disconnect():

    // Disconnect delegate when the delegate is no longer in the delegates list
    useEffect(() => {
    if (!account?.delegatedAccess?.delegate) {
    return;
    }
    if (account?.delegatedAccess?.delegates?.some((d) => d.email === account?.delegatedAccess?.delegate)) {
    return;
    }
    disconnect({stashedCredentials, stashedSession});
    }, [account?.delegatedAccess?.delegates, account?.delegatedAccess?.delegate, stashedCredentials, stashedSession]);

    disconnect() waits for DisconnectAsDelegate, restores the requester session, clears Onyx, and only after openApp() calls HybridAppModule.switchAccount():

    API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.DISCONNECT_AS_DELEGATE, {}, {optimisticData, successData, failureData})
    .then((response) => {
    if (!response?.authToken || !response?.encryptedAuthToken) {
    Log.alert('[Delegate] No auth token returned while disconnecting as a delegate');
    restoreDelegateSession(stashedSession ?? {});
    return;
    }
    if (!response?.requesterID || !response?.requesterEmail) {
    Log.alert('[Delegate] No requester data returned while disconnecting as a delegate');
    restoreDelegateSession(stashedSession ?? {});
    return;
    }
    clearPreservedSearchNavigatorStates();
    const requesterEmail = response.requesterEmail;
    const authToken = response.authToken;
    return SequentialQueue.waitForIdle()
    .then(() => {
    return Promise.all([
    Onyx.set(ONYXKEYS.SESSION, {
    ...stashedSession,
    accountID: response.requesterID,
    email: requesterEmail,
    authToken,
    encryptedAuthToken: response.encryptedAuthToken,
    }),
    Onyx.merge(ONYXKEYS.ACCOUNT, {
    primaryLogin: requesterEmail,
    }),
    ]);
    })
    .then(() => {
    NetworkStore.setAuthToken(response?.authToken ?? null);
    return clearOnyxForDelegateTransition();
    })
    .then(() => {
    Onyx.set(ONYXKEYS.CREDENTIALS, {
    ...stashedCredentials,
    accountID: response.requesterID,
    });
    Onyx.set(ONYXKEYS.STASHED_CREDENTIALS, {});
    Onyx.set(ONYXKEYS.STASHED_SESSION, {});
    confirmReadyToOpenApp();
    openApp().then(() => {
    if (!CONFIG.IS_HYBRID_APP) {
    return;
    }
    HybridAppModule.switchAccount({
    newDotCurrentAccountEmail: requesterEmail,
    authToken,
    policyID: '',
    accountID: '',
    });
    });

    If the user kills the app during this loading window, native hybrid state can still point to Account A’s delegate token. On the next launch, hybrid startup trusts hybridApp.delegateAccessData, stashes the current ND session, writes oldDotCurrentAuthToken into SESSION, and opens the app as that OldDot account:

    const stashedData = hybridApp?.delegateAccessData?.isDelegateAccess
    ? {
    [ONYXKEYS.STASHED_CREDENTIALS]: credentials,
    [ONYXKEYS.STASHED_SESSION]: session,
    }
    : {
    [ONYXKEYS.STASHED_CREDENTIALS]: {},
    [ONYXKEYS.STASHED_SESSION]: {},
    };
    // Don't clear Onyx when using imported state to preserve imported data (reports, transactions, etc.)
    // Just update the session and credentials without clearing
    if (isUsingImportedState) {
    Log.info('[HybridApp] Skipping Onyx clear because using imported state. Updating session only.');
    return Onyx.multiSet({
    ...stashedData,
    [ONYXKEYS.SESSION]: {
    email: hybridApp?.delegateAccessData?.oldDotCurrentUserEmail,
    authToken: hybridApp?.delegateAccessData?.oldDotCurrentAuthToken,
    encryptedAuthToken: decodeURIComponent(hybridApp?.delegateAccessData?.oldDotCurrentEncryptedAuthToken ?? ''),
    accountID: hybridApp?.delegateAccessData?.oldDotCurrentAccountID,
    },
    [ONYXKEYS.CREDENTIALS]: {
    autoGeneratedLogin: credentials?.autoGeneratedLogin ?? hybridApp.delegateAccessData?.oldDotAutoGeneratedLogin,
    autoGeneratedPassword: credentials?.autoGeneratedPassword ?? hybridApp.delegateAccessData?.oldDotAutoGeneratedPassword,
    },
    })
    .then(() => Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: hybridApp?.delegateAccessData?.oldDotCurrentUserEmail}))
    .then(() => {
    confirmReadyToOpenApp();
    return openApp();
    });
    }
    Log.info('[HybridApp] User switched account on OldDot side. Clearing onyx and applying delegate data');
    return clearOnyxForDelegateTransition()
    .then(() =>
    Onyx.multiSet({
    ...stashedData,
    [ONYXKEYS.SESSION]: {
    email: hybridApp?.delegateAccessData?.oldDotCurrentUserEmail,
    authToken: hybridApp?.delegateAccessData?.oldDotCurrentAuthToken,
    encryptedAuthToken: decodeURIComponent(hybridApp?.delegateAccessData?.oldDotCurrentEncryptedAuthToken ?? ''),
    accountID: hybridApp?.delegateAccessData?.oldDotCurrentAccountID,
    },
    // When a logged-in user opens NewDot for the first time after migrating to the new SignInPage, there will be no credentials on the NewDot side.
    // After migration, NewDot is responsible for creating credentials, but this only happens during sign-in.
    // To avoid blocking the transition, we fall back to credentials from OldDot in this scenario.
    // The `delegateAccessData` key is misleading in this context because, in the past, this code only handled Copilot. We are reusing the same logic here for this scenario.
    [ONYXKEYS.CREDENTIALS]: {
    autoGeneratedLogin: credentials?.autoGeneratedLogin ?? hybridApp.delegateAccessData?.oldDotAutoGeneratedLogin,
    autoGeneratedPassword: credentials?.autoGeneratedPassword ?? hybridApp.delegateAccessData?.oldDotAutoGeneratedPassword,
    },
    }),
    )
    .then(() => Onyx.merge(ONYXKEYS.ACCOUNT, {primaryLogin: hybridApp?.delegateAccessData?.oldDotCurrentUserEmail}))
    .then(() => {
    Log.info('[HybridApp] Calling openApp to get delegate account details');
    confirmReadyToOpenApp();
    return openApp();
    });

    That token now represents removed copilot access. The next request can hit the existing deleted/copilot-invalid middleware and sign the user out:

    const handleDeletedAccount: Middleware = (requestResponse) =>
    requestResponse.then((response) => {
    if (response?.jsonCode !== 408 || !response?.message?.includes('The account you are trying to use is deleted.')) {
    return response;
    }
    signOutAndRedirectToSignIn(true, false, true, true);
    });

    So the root cause is: self-removing the active copilot relies on a later asynchronous disconnect()/native switch to recover Account B, but the hybrid app can be killed before the native and Onyx session are made consistent.

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

    Handle active-copilot self-removal as an account restoration, not as a generic DisconnectAsDelegate recovery.

    When removeDelegate() succeeds for email === delegatedAccess.delegate, restore the already-stashed original user immediately and update the hybrid native account before reopening the app. Keep the current behavior for removing any other delegate, so normal owner-side delegate removal does not regress.

    Small illustrative diff:

    -function removeDelegate({email, delegatedAccess}: RemoveDelegateParams) {
    +function removeDelegate({email, delegatedAccess, stashedCredentials, stashedSession}: RemoveDelegateParams & Partial<DisconnectParams>) {
         if (!email || !delegatedAccess?.delegates) {
             return;
         }
    +
    +    const isRemovingCurrentDelegate = email === delegatedAccess.delegate;
         const successData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT>> = [
             {
                 onyxMethod: Onyx.METHOD.MERGE,
                 key: ONYXKEYS.ACCOUNT,
                 value: {
                     delegatedAccess: {
                         delegates: delegatedAccess.delegates?.filter((delegate) => delegate.email !== email),
                     },
                 },
             },
         ];

    Then use the side-effect request path only for this self-removal case, so we can run restoration after success:

    -    API.write(WRITE_COMMANDS.REMOVE_DELEGATE, parameters, {optimisticData, successData, failureData});
    +    if (!isRemovingCurrentDelegate) {
    +        API.write(WRITE_COMMANDS.REMOVE_DELEGATE, parameters, {optimisticData, successData, failureData});
    +        return;
    +    }
    +
    +    API.write(WRITE_COMMANDS.REMOVE_DELEGATE, parameters, {optimisticData, successData, failureData}).then(() => {
    +        restoreOriginalDelegateAccount({stashedCredentials, stashedSession});
    +    });

    restoreOriginalDelegateAccount() should reuse the same operations already used by disconnect() / prior history: set SESSION and CREDENTIALS from the stashed original user, clear STASHED_SESSION and STASHED_CREDENTIALS, update NetworkStore, call clearOnyxForDelegateTransition(), call HybridAppModule.switchAccount() for hybrid, then openApp().

    To avoid regressions:

    • Only run this path when removing delegatedAccess.delegate.
    • Keep regular removeDelegate() behavior for account owners removing other copilots.
    • Keep DelegateAccessHandler as a fallback for server-driven delegate removal.
    • Do not change HandleDeletedAccount; that middleware should remain a last-resort recovery, not the primary self-removal flow.
    • Add coverage for active self-removal preserving/restoring stashed session and for non-active delegate removal not switching accounts.

    What alternative solutions did you explore? (Optional)

    We could move HybridAppModule.switchAccount() earlier inside disconnect(), but that still depends on a DisconnectAsDelegate response after the copilot access was already removed. The safer fix is to make the self-removal success path restore Account B directly from the stashed session, which is exactly the state saved for this purpose.

  11. MobileMage commented on Jun 12, 2026

    @MobileMage
    Contributor

    Proposal

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

    On HybridApp, Account B logs in, switches into Account A's account as a full copilot, and then (acting as A) removes B from A's copilot list. After the app finishes its reload, killing and reopening the app drops B into the OldDot experience and then logs B out entirely (in production, B is logged out directly). The expected behavior is that B is cleanly returned to their own NewDot session as Account B.

    What is the root cause of that problem?

    Removing yourself-as-acting-delegate is an allowed action, and it relies on a purely asynchronous, NewDot-driven recovery to put both apps back into B's own session. When B is acting as A and removes the delegate row for B, CopilotPage permits it because the selected delegate equals the currently acting delegate, so the "no access" guard is skipped and removeDelegate runs:

    if (selectedDelegate?.email !== account?.delegatedAccess?.delegate && isActingAsDelegate) {
    showDelegateNoAccessModal();
    return;
    }
    removeDelegate({email: selectedDelegate?.email ?? '', delegatedAccess: account?.delegatedAccess});

    removeDelegate only writes the REMOVE_DELEGATE command and optimistically strips B out of account.delegatedAccess.delegates. Crucially, it does not touch OldDot — there is no HybridAppModule.switchAccount call in that action. The actual session restoration is delegated to a self-healing effect in DelegateAccessHandler, which notices that the acting delegate (B) is no longer present in the delegates array and calls disconnect():

    // Disconnect delegate when the delegate is no longer in the delegates list
    useEffect(() => {
    if (!account?.delegatedAccess?.delegate) {
    return;
    }
    if (account?.delegatedAccess?.delegates?.some((d) => d.email === account?.delegatedAccess?.delegate)) {
    return;
    }
    disconnect({stashedCredentials, stashedSession});
    }, [account?.delegatedAccess?.delegates, account?.delegatedAccess?.delegate, stashedCredentials, stashedSession]);

    disconnect() is the only thing that tells OldDot to switch back to B, and it does so very late: it fires a DISCONNECT_AS_DELEGATE side-effect request, waits for the response, rebuilds the NewDot session from stashedSession, runs openApp(), and only then calls HybridAppModule.switchAccount({newDotCurrentAccountEmail: requesterEmail, ...}) (Delegate.ts L331). The repro kills the app during "app loading" — i.e. inside this multi-step async chain, before the switchAccount back to B reaches OldDot. So the kill leaves a torn state: NewDot's persisted SESSION still holds B's restricted token scoped to A, and OldDot still has A as its current account with isDelegateAccess=true. On reopen, setupNewDotAfterTransitionFromOldDot trusts OldDot's delegateAccessData and rehydrates SESSION from oldDotCurrentUserEmail/oldDotCurrentAuthToken (A's now-revoked restricted token), which is why the user lands in the OldDot/delegated experience first:

    [ONYXKEYS.SESSION]: {
    email: hybridApp?.delegateAccessData?.oldDotCurrentUserEmail,
    authToken: hybridApp?.delegateAccessData?.oldDotCurrentAuthToken,
    encryptedAuthToken: decodeURIComponent(hybridApp?.delegateAccessData?.oldDotCurrentEncryptedAuthToken ?? ''),
    accountID: hybridApp?.delegateAccessData?.oldDotCurrentAccountID,
    },

    Because B was just removed as A's delegate, that restricted token is no longer valid. The restart does not re-trigger the auto-disconnect effect either — openApp repopulates account from the server without delegatedAccess.delegate set, so the if (!account?.delegatedAccess?.delegate) return; early-out at DelegateAccessHandler L33 short-circuits and never calls disconnect(). The first authenticated request then returns 407 NOT_AUTHENTICATED; reauthentication can't recover because the session email is A while the live credentials are B's, so after retries it hits redirectToSignIn('passwordForm.error.fallback') and logs the user out (Reauthentication.ts L39-L40).

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

    Fix it at the source so OldDot is switched back to B synchronously the moment B removes itself, instead of depending on the late disconnect() chain surviving an app kill. In removeDelegate (src/libs/actions/Delegate.ts), detect the self-removal-while-acting case and proactively switch OldDot back to the stashed (own) account before/independently of the API round-trip, so the OldDot delegateAccessData no longer points at A even if the JS process is killed mid-flow. Concretely, when email === delegatedAccess?.delegate and we have a valid stashed session, route through the existing disconnect({stashedCredentials, stashedSession}) helper (or call HybridAppModule.switchAccount to the stashed account up front), e.g.:

    function removeDelegate({email, delegatedAccess}: RemoveDelegateParams) {
        if (!email || !delegatedAccess?.delegates) {
            return;
        }
        const isRemovingSelfWhileActing = email === delegatedAccess?.delegate;
        // ... existing optimistic/success/failure data + API.write(REMOVE_DELEGATE, ...)
        if (isRemovingSelfWhileActing) {
            disconnect({stashedCredentials, stashedSession});
        }
    }

    This reuses the established disconnect path (which already restores SESSION/CREDENTIALS from the stash and calls switchAccount back to B) rather than leaving recovery to a UI effect that the kill can interrupt. It is safe for the normal case (a non-acting admin removing some other delegate) because the new branch is gated on email === delegatedAccess.delegate, so it only runs in the exact self-removal scenario the DelegateAccessHandler effect was already handling — we're just making that handoff happen eagerly and on the OldDot side too, not duplicating it. To also harden the restart path, setupNewDotAfterTransitionFromOldDot should treat a delegated OldDot session whose delegate relationship no longer exists as invalid and fall back to the stashed own-session restore instead of authenticating with the dead restricted token, so an interrupted kill never strands the user in A's revoked session.

    What alternative solutions did you explore? (Optional)

    I considered only patching the restart path — making DelegateAccessHandler re-detect a stale delegated session on reopen and call disconnect() — but after restart account.delegatedAccess.delegate is no longer set, so that effect can't fire and we'd have to reconstruct the "am I a dangling delegate" signal from stashedSession + a failed auth, which is fragile. Fixing removeDelegate to hand OldDot back to B synchronously addresses the torn state at its origin and matches how disconnect()/connect() already keep both apps in sync.

  12. melvin-bot commented on Jun 12, 2026

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @eVoloshchak (External)

  13. 78 remaining items

  14. melvin-bot commented on Oct 22, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  15. melvin-bot commented on Oct 22, 2026

    @melvin-bot

    Payment Summary

    Resolving PRs:

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • I have confirmed assignees, roles, and Upwork contracts look correct
    • I have paid out Upwork contracts / manual NewDot requests
    • [BugZero Assignee] I have created a GH issue for creating/updating the regression test once above steps have been agreed upon
  16. chuckdries commented on Oct 23, 2026

    @chuckdries
    Contributor

    This was fixed by @jmusial

  17. mvtglobally commented on Oct 24, 2026

    @mvtglobally

    Issue not reproducible during KI retests. (First week)

  18. eVoloshchak commented on Oct 26, 2026

    @eVoloshchak
    Contributor

    Contributor+ Checklist:

    • [Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      Link to the comment on the PR: N/A
      Link to the comment on the Issue:

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion: regression wasn't critical

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    Regression Test Proposal

    Precondition:

    • Account A add Account B as a full copilot
    • Log in to Account B

    Test:

    1. Open the hybrid app
    2. Switch into A's account via the copilot dropdown
    3. Go to the copilot page
    4. Remove B as the copilot
    5. After the app loading, kill the app
    6. Reopen the app
    7. Verify that user stays in ND experience as Account B

    Do we agree 👍 or 👎

  19. mallenexpensify commented on Oct 26, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @eVoloshchak due $250 via NewDot

  20. JmillsExpensify commented on Nov 10, 2026

    @JmillsExpensify
    Contributor

    $250 approved for @eVoloshchak

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentBugDailyInternalretest-weekly

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions