You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Due for payment 2026-10-23] [$250] Copilot-User is logged out after remove copilot then kill app and open again #93458
Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2InternalRequires API changes or must be handled by Expensify staffretest-weeklyApply this label if you want this issue tested on a Weekly basis by Applause
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
Open hybrid app
Switch into A's account via the copilot dropdown
Go the copilot page
Remove B as the copilot
After the app loading, kill the app
Reopen the app
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
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.
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).
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 afterREMOVE_DELEGATE succeeds — removeDelegate's optimistic data only marks a pending DELETE, and B is filtered from the list in successData: Delegate.ts:506-576.
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.
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.
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?
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/Delegatebefore 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.
The key sequencing constraint: removeDelegate must be issued afterdisconnect 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 pathif(isActingAsDelegate&&selectedDelegate?.email===session?.email){// Capture A's delegatedAccess before disconnect clears it from OnyxconstdelegatedAccessSnapshot=account?.delegatedAccess;awaitdisconnect({stashedCredentials, stashedSession});// Now running under B's own session; pass the captured snapshot so// removeDelegate can build optimistic data against A's delegate listremoveDelegate({email: selectedDelegate.email,delegatedAccess: delegatedAccessSnapshot});}else{removeDelegate({email: selectedDelegate.email,delegatedAccess: account?.delegatedAccess});}
In src/libs/actions/Delegate.tsremoveDelegate (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.
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.
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 persistedONYXKEYS.SESSION with A's restricted delegated token and stashes B's original session/credentials separately:
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:
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:
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, beforedisconnect() 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.
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:
// 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.
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:
Log.info('[Reauthenticate] No credentials available, redirecting to sign in');
setIsAuthenticating(false);
redirectToSignIn('No credentials available');
returnfalse;
}
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:
// 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.
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?
On app start HybridApp registers Onyx listeners that re-run signInToOldDotAndChooseExperience whenever nvp_tryNewDot/account change:
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:
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)
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.
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:
The actual session restore happens reactively, afterwards, in DelegateAccessHandler: once the success data drops the delegate from delegates, the effect calls disconnect():
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):
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 (
Log.info('[Reauthenticate] Reauthenticate while connected as a delegate. Restoring original account.');
restoreDelegateSession(response);
returntrue;
}
); 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.
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() waits for DisconnectAsDelegate, restores the requester session, clears Onyx, and only after openApp() calls HybridAppModule.switchAccount():
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:
// 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.
if(response?.jsonCode!==408||!response?.message?.includes('The account you are trying to use is deleted.')){
returnresponse;
}
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.
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.
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:
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() 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:
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.:
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.
[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:
Open the hybrid app
Switch into A's account via the copilot dropdown
Go to the copilot page
Remove B as the copilot
After the app loading, kill the app
Reopen the app
Verify that user stays in ND experience as Account B
Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2InternalRequires API changes or must be handled by Expensify staffretest-weeklyApply this label if you want this issue tested on a Weekly basis by Applause
Activity
applause-bot commentedon Jun 12, 2026
While Applause doesn't embed attachments for this bug, here are the links for quick view:
https://platform.applause.com/services/links/v1/external/fede156c6515ff38e5153dbb4f1b897f876a6b467d98ca17efffc4a0f64b06d3
https://platform.applause.com/services/links/v1/external/946340649d0a505dd9141c398aa700643a0b6dd026bcc4e5958b3324f0c48c6c
MelvinBot commentedon Jun 12, 2026
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.
CopilotPageexplicitly allows B to remove their own row — the "no access" guard only blocks removing other delegates:CopilotPage.tsx:329/:344-348(the conditionselectedDelegate?.email !== account?.delegatedAccess?.delegateis false for self-removal).DelegateAccessHandler.tsx:31-40: when B is no longer in the delegates list, it callsdisconnect(). But it only fires afterREMOVE_DELEGATEsucceeds —removeDelegate's optimistic data only marks a pending DELETE, and B is filtered from the list insuccessData:Delegate.ts:506-576.disconnect()is itself a long async transition (another server round-trip, then it rewritesSESSIONfrom the stashed session and re-opens the app):Delegate.ts:243-343.So there is a wide window where the persisted
SESSIONstill 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-presentCREDENTIALS, 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 liveSESSIONauthToken to A'srestrictedToken, but never overwritesCREDENTIALS— so B'sautoGeneratedLogin/Passwordremain 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 checkdelegates.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.reconnectApp/openAppruns with A's revoked restricted token →NOT_AUTHENTICATED→reauthenticate()re-Authenticates with B'sCREDENTIALS→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.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 onREMOVE_DELEGATEsuccess — e.g. calldisconnect()(or fold B out of the list inremoveDelegate'soptimisticData) atDelegate.ts:506-576soDelegateAccessHandlerfires without the extra round-trip.[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.
aswin-s commentedon Jun 12, 2026
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 callsremoveDelegate(...)at line 348.removeDelegateinsrc/libs/actions/Delegate.ts:506-576only fires the REMOVE_DELEGATE API and mutates the delegates list — it never restores the stashed delegate-owner session. The activeONYXKEYS.SESSIONstill 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 inONYXKEYS.STASHED_SESSION.What changes do you think we should make in order to solve the problem?
In
src/pages/settings/Copilot/CopilotPage.tsxaround line 348, detect the self-removal case (isActingAsDelegate && selectedDelegate?.email === session?.email) and calldisconnect({stashedCredentials, stashedSession})from@libs/actions/Delegatebefore callingremoveDelegate. This restoresONYXKEYS.SESSIONandONYXKEYS.CREDENTIALSto B's own stashed values and triggersHybridAppModule.switchAccountback to B — mirroring the existing copilot-dropdown "switch back" flow that already usesdisconnect.The key sequencing constraint:
removeDelegatemust be issued afterdisconnectcompletes and B's own session is active. The reason is thatremoveDelegatesends onlydelegateEmailin its API payload and authenticates using whichever session is currently active inONYXKEYS.SESSION. IfremoveDelegateran 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 inremoveDelegatetargets A's delegate list, so the call must still reference A'sdelegatedAccessdata. To satisfy both requirements, pass A'sdelegatedAccesssnapshot intoremoveDelegateexplicitly before switching sessions, and issue theAPI.writecall afterdisconnectunder B's restored token:In
src/libs/actions/Delegate.tsremoveDelegate(line 506), as a defense-in-depth guard, accept an optionalcurrentDelegateEmail/session arg and, when removing the currently-acting delegate, invoke the same disconnect path internally so any other callsite is also safe.Verify on both Android and iOS hybrid app that after self-removal the
HybridAppModule.switchAccountcall restores B's OD bridge account and thatSTASHED_SESSION/STASHED_CREDENTIALSare cleared, matching the post-condition of the normaldisconnectflow atDelegate.ts:319-336.What alternative solutions did you explore? (Optional)
Forcing a
signOuton self-removal would log B out cleanly but loses B's session unnecessarily; restoring viadisconnectkeeps B signed in, which matches the Expected Result.An alternative ordering — calling
removeDelegatefirst under A's token and thendisconnect— keeps the authenticated account consistent for the API call, but leaves the app in the revoked-token state untildisconnectcompletes. 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.yusufdeveloper2903 commentedon Jun 12, 2026
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 persistedONYXKEYS.SESSIONwith A's restricted delegated token and stashes B's original session/credentials separately:App/src/libs/actions/Delegate.ts
Lines 211 to 234 in 103cd4a
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 toremoveDelegate:App/src/pages/settings/Copilot/CopilotPage.tsx
Lines 328 to 353 in 103cd4a
removeDelegatethen firesREMOVE_DELEGATEand updates the delegates list, but does nothing to tear down the delegated session it is running inside:App/src/libs/actions/Delegate.ts
Lines 506 to 576 in 103cd4a
Once the server processes the removal, A's restricted token is revoked. The app keeps working only because
NetworkStorestill 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 persistedONYXKEYS.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.delegateis "the email of the original user when they are acting as a delegate", i.e. B — confirming the removedemailis the current operator:App/src/types/onyx/Account.ts
Lines 56 to 57 in 103cd4a
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 torestoreDelegateSession(stashedSession)when no fresh token comes back:App/src/libs/actions/Delegate.ts
Lines 282 to 293 in 103cd4a
removeDelegateis 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 inremoveDelegateand, once theREMOVE_DELEGATEwrite has drained, rundisconnect():Supporting changes (described, not full diffs):
RemoveDelegateParamsto also carrystashedCredentials/stashedSession(WithStashedCredentials & WithStashedSession), and pass them from theremoveDelegate(...)call site inCopilotPageviauseOnyx(ONYXKEYS.STASHED_CREDENTIALS)/useOnyx(ONYXKEYS.STASHED_SESSION)— the same valuesAccountSwitcheralready feeds intodisconnect().Why this is robust:
SequentialQueue.waitForIdle()(already imported in this file) guarantees theREMOVE_DELEGATEwrite is flushed while we are still authenticated as A, beforedisconnect()swapsNetworkStore/SESSIONto B. So the removal can't accidentally run under B's token.DISCONNECT_AS_DELEGATEmay not return a usable token — butdisconnect()already falls back torestoreDelegateSession(stashedSession)in that exact case (L284-L293), which clears Onyx, restores B's session and callsopenApp(). Either way the persistedSESSIONends up as B's valid token, so the next cold start boots cleanly into NewDot as B.disconnect()resolves once connectivity returns and the queue drains, and the stashed session is preserved meanwhile viaKEYS_TO_PRESERVE_DELEGATE_ACCESS.Delegate.ts/CopilotPage.tsx), so it covers both iOS and Android App, which are the affected platforms.What alternative solutions did you explore? (Optional)
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.lorretheboy commentedon Jun 12, 2026
Proposal
What is the root cause of that problem?
When you connect as a copilot,
connectstashes your own credentials intoSTASHED_CREDENTIALSand then runsclearOnyxForDelegateTransition, which wipes Onyx while preserving only the delegate keys.ONYXKEYS.CREDENTIALSis not in that preserve list, so while you are acting as the copilot your own login lives only inSTASHED_CREDENTIALSandCREDENTIALSis empty:App/src/libs/actions/Delegate.ts
Lines 29 to 48 in 71d4330
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:
DelegateAccessHandlernotices the delegate is gone from the list and callsdisconnect, anddisconnectrestoresSESSION/CREDENTIALSfrom the stashed copies only at the very end of a network round-trip.App/src/DelegateAccessHandler.tsx
Lines 31 to 40 in 71d4330
App/src/libs/actions/Delegate.ts
Lines 300 to 325 in 71d4330
If you kill the app during this "loading" window, persisted Onyx still holds A's now-revoked restricted token in
SESSIONand an emptyCREDENTIALS. On relaunch the first request is rejected,reauthenticateruns, finds no credentials, and signs you out:App/src/libs/Reauthentication.ts
Lines 147 to 153 in 71d4330
Note that
reauthenticatealready 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:App/src/libs/Reauthentication.ts
Lines 210 to 216 in 71d4330
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.CREDENTIALStoKEYS_TO_PRESERVE_DELEGATE_ACCESS:App/src/libs/actions/Delegate.ts
Lines 29 to 48 in 71d4330
With
CREDENTIALSsurviving the clear, a relaunch with the revoked restricted token reauthenticates successfully as the original user, and because thedelegatefield is still set, the existingisConnectedAsDelegatebranch inreauthenticatecallsrestoreDelegateSessionand 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 inSTASHED_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_CREDENTIALSstill present) and restore the original account from the stash. This handles the interrupted-disconnectstate directly even if credentials were unavailable for any other reason.ahmdshrif commentedon Jun 12, 2026
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?
On app start HybridApp registers Onyx listeners that re-run
signInToOldDotAndChooseExperiencewhenevernvp_tryNewDot/account change:App/src/libs/HybridApp.ts
Lines 30 to 37 in 71d4330
The only guard before the OldDot redirect is
tryNewDot !== undefined— an empty object{}passes it and callscloseReactNativeApp:App/src/libs/HybridApp.ts
Lines 115 to 122 in 71d4330
shouldUseOldAppreturnstruefor any emptytryNewDot, sinceisEmptyObject(tryNewDot)short-circuits totrue:App/src/libs/TryNewDotUtils.ts
Lines 38 to 48 in 71d4330
When the copilot link is torn down, B's
nvp_tryNewDotis cleared and on cold reopen the Onyx callback fires with{}before the real NVP is re-fetched. SoshouldUseOldApp({}) === true,closeReactNativeAppforce-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) becausecloseReactNativeApponly 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 thecloseReactNativeAppredirect: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 populatedtryNewDot(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)
isCopilotUser(account)guard from [$250] iOS - Copilot - A new account added as a Copilot is redirected to OD after signing in #75477 — rejected: after removal B'sdelegatedAccess.delegatorsis already empty, so it wouldn't catch this state.nvp_tryNewDotsynchronously on disconnect — rejected: larger surface, races with the redirect that has already fired.David-2002065 commentedon Jun 12, 2026
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.
On the copilot page,
removeDelegateonly firesREMOVE_DELEGATE(which invalidates the connected delegate's restricted token server-side) and updates thedelegateslist. It never restores the session:App/src/libs/actions/Delegate.ts
Lines 501 to 571 in 71d4330
The actual session restore happens reactively, afterwards, in
DelegateAccessHandler: once the success data drops the delegate fromdelegates, the effect callsdisconnect():App/src/DelegateAccessHandler.tsx
Lines 31 to 40 in 71d4330
disconnect()is itself a second network round-trip (DISCONNECT_AS_DELEGATE) and only restoresSESSION/credentials inside its.then():App/src/libs/actions/Delegate.ts
Lines 277 to 333 in 71d4330
Between step 1 and the completion of step 3, the persisted
SESSIONstill 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 launchopenAppruns 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 beforeopenAppfires, and because the restore depends on aDISCONNECT_AS_DELEGATErequest 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_DELEGATEresponse.In
DelegateAccessHandler's effect, when the connected delegate is no longer in thedelegateslist, restore the stashed (original) session right away viarestoreDelegateSession, which clears the delegate Onyx state and re-seeds the originalauthTokensynchronously beforeopenApp:restoreDelegateSessionalready does exactly the local, network-independent restore we need (it does not depend on the live delegate token):App/src/libs/actions/Delegate.ts
Lines 680 to 691 in 71d4330
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 removedemailis the connected delegate (delegatedAccess.delegate === email), trigger the localrestoreDelegateSession(stashedSession)as part of the same user action instead of relying on the post-success reactive effect, keepingREMOVE_DELEGATE/DISCONNECT_AS_DELEGATEpurely for server-side bookkeeping.Note: there is already a boot-time safety net in
reauthenticatethat callsrestoreDelegateSessionwhen reauthenticating while connected as a delegate (App/src/libs/Reauthentication.ts
Lines 210 to 216 in 71d4330
What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?
Add a test for
DelegateAccessHandler(and/orremoveDelegate) asserting that when the connected delegate is removed from thedelegateslist,SESSION/CREDENTIALSare synchronously restored to the stashed original account andSTASHED_*is cleared, without depending on aDISCONNECT_AS_DELEGATEresponse — 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_DELEGATEand, on boot, restore fromSTASHED_SESSIONwhenever that marker is present beforeopenAppruns. 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 existingrestoreDelegateSessionpath with no new state.mukhrr commentedon Jun 12, 2026
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:
STASHED_SESSION/STASHED_CREDENTIALSduring 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,DelegateAccessHandlersees that the active delegate is no longer indelegatedAccess.delegatesand callsdisconnect():App/src/DelegateAccessHandler.tsx
Lines 31 to 40 in 6e5c4fa
disconnect()waits forDisconnectAsDelegate, restores the requester session, clears Onyx, and only afteropenApp()callsHybridAppModule.switchAccount():App/src/libs/actions/Delegate.ts
Lines 282 to 337 in 6e5c4fa
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, writesoldDotCurrentAuthTokenintoSESSION, and opens the app as that OldDot account:App/src/libs/actions/Session/index.ts
Lines 703 to 763 in 6e5c4fa
That token now represents removed copilot access. The next request can hit the existing deleted/copilot-invalid middleware and sign the user out:
App/src/libs/Middleware/HandleDeletedAccount.ts
Lines 10 to 16 in 6e5c4fa
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
DisconnectAsDelegaterecovery.When
removeDelegate()succeeds foremail === 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:
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:
restoreOriginalDelegateAccount()should reuse the same operations already used bydisconnect()/ prior history: setSESSIONandCREDENTIALSfrom the stashed original user, clearSTASHED_SESSIONandSTASHED_CREDENTIALS, updateNetworkStore, callclearOnyxForDelegateTransition(), callHybridAppModule.switchAccount()for hybrid, thenopenApp().To avoid regressions:
delegatedAccess.delegate.removeDelegate()behavior for account owners removing other copilots.DelegateAccessHandleras a fallback for server-driven delegate removal.HandleDeletedAccount; that middleware should remain a last-resort recovery, not the primary self-removal flow.What alternative solutions did you explore? (Optional)
We could move
HybridAppModule.switchAccount()earlier insidedisconnect(), but that still depends on aDisconnectAsDelegateresponse 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.MobileMage commentedon Jun 12, 2026
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,
CopilotPagepermits it because the selected delegate equals the currently acting delegate, so the "no access" guard is skipped andremoveDelegateruns:App/src/pages/settings/Copilot/CopilotPage.tsx
Lines 344 to 348 in 71d4330
removeDelegateonly writes theREMOVE_DELEGATEcommand and optimistically strips B out ofaccount.delegatedAccess.delegates. Crucially, it does not touch OldDot — there is noHybridAppModule.switchAccountcall in that action. The actual session restoration is delegated to a self-healing effect inDelegateAccessHandler, which notices that the actingdelegate(B) is no longer present in thedelegatesarray and callsdisconnect():App/src/DelegateAccessHandler.tsx
Lines 31 to 40 in 71d4330
disconnect()is the only thing that tells OldDot to switch back to B, and it does so very late: it fires aDISCONNECT_AS_DELEGATEside-effect request, waits for the response, rebuilds the NewDot session fromstashedSession, runsopenApp(), and only then callsHybridAppModule.switchAccount({newDotCurrentAccountEmail: requesterEmail, ...})(Delegate.ts L331). The repro kills the app during "app loading" — i.e. inside this multi-step async chain, before theswitchAccountback to B reaches OldDot. So the kill leaves a torn state: NewDot's persistedSESSIONstill holds B's restricted token scoped to A, and OldDot still has A as its current account withisDelegateAccess=true. On reopen,setupNewDotAfterTransitionFromOldDottrusts OldDot'sdelegateAccessDataand rehydratesSESSIONfromoldDotCurrentUserEmail/oldDotCurrentAuthToken(A's now-revoked restricted token), which is why the user lands in the OldDot/delegated experience first:App/src/libs/actions/Session/index.ts
Lines 742 to 747 in 71d4330
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 —
openApprepopulatesaccountfrom the server withoutdelegatedAccess.delegateset, so theif (!account?.delegatedAccess?.delegate) return;early-out at DelegateAccessHandler L33 short-circuits and never callsdisconnect(). The first authenticated request then returns407 NOT_AUTHENTICATED; reauthentication can't recover because the session email is A while the live credentials are B's, so after retries it hitsredirectToSignIn('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. InremoveDelegate(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 OldDotdelegateAccessDatano longer points at A even if the JS process is killed mid-flow. Concretely, whenemail === delegatedAccess?.delegateand we have a valid stashed session, route through the existingdisconnect({stashedCredentials, stashedSession})helper (or callHybridAppModule.switchAccountto the stashed account up front), e.g.:This reuses the established disconnect path (which already restores
SESSION/CREDENTIALSfrom the stash and callsswitchAccountback 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 onemail === delegatedAccess.delegate, so it only runs in the exact self-removal scenario theDelegateAccessHandlereffect 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,setupNewDotAfterTransitionFromOldDotshould 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
DelegateAccessHandlerre-detect a stale delegated session on reopen and calldisconnect()— but after restartaccount.delegatedAccess.delegateis no longer set, so that effect can't fire and we'd have to reconstruct the "am I a dangling delegate" signal fromstashedSession+ a failed auth, which is fragile. FixingremoveDelegateto hand OldDot back to B synchronously addresses the torn state at its origin and matches howdisconnect()/connect()already keep both apps in sync.melvin-bot commentedon Jun 12, 2026
Triggered auto assignment to Contributor-plus team member for initial proposal review - @eVoloshchak (
External)78 remaining items
melvin-bot commentedon Oct 22, 2026
Triggered auto assignment to @mallenexpensify (
Awaiting Payment)melvin-bot commentedon Oct 22, 2026
Payment Summary
Resolving PRs:
Upwork Job
BugZero Checklist (@mallenexpensify)
chuckdries commentedon Oct 23, 2026
This was fixed by @jmusial
mvtglobally commentedon Oct 24, 2026
Issue not reproducible during KI retests. (First week)
eVoloshchak commentedon Oct 26, 2026
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:
Test:
Do we agree 👍 or 👎
mallenexpensify commentedon Oct 26, 2026
Payment Summary
Contributor+: @eVoloshchak due $250 via NewDot
JmillsExpensify commentedon Nov 10, 2026
$250 approved for @eVoloshchak