[Due for payment 2026-11-26] [$175] Copilot - "From" filter on Spend > Drafts defaults to the copilot (Alice) instead of the account holder (Bob)
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number: 9.5.32-3 Reproducible in staging?: Y Reproducible in production?: Y If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @dubielzyk-expensify Slack conversation (hyperlinked to channel name): #Expensify Bugs
Action Performed:
- Set up two accounts: Account A (Alice) and Account B (Bob).
- Make Alice a copilot of Bob.
- As Alice, Copilot into Bob's account.
- Go to Spend > Drafts.
- Click the From filter.
- Observe which user is selected.
Expected Result:
While copiloting, the From filter should default to Bob (the account holder), since the Drafts shown belong to Bob's account.
Actual Result:
The From filter is set to Alice (the copilot), not Bob.
Workaround:
Unknown
Platforms:
Select the officially supported platforms where the issue was reproduced:
- [ ] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [x] Windows: Chrome
- [x] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/2abf8aa3-1ff1-41e6-b7ca-f7e4b320ac01
https://github.com/user-attachments/assets/5f60b728-9936-401b-bcda-b83854718699
https://github.com/user-attachments/assets/a4934506-10f3-47c3-a72f-87f27732ff74
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022118367402292021507
- Upwork Job ID: 2118367402292021507
- Last Price Increase: 2026-11-05
Issue Owner
Current Issue Owner: @mallenexpensify
Issue Analysis
⚠️ Preliminary analysis (low confidence) — the incorrect selection is reported, but its upstream cause is not yet confirmed.
Finding: The current Drafts preset already uses the active session’s account ID—not an explicit copilot ID. Two plausible explanations remain: an existing Drafts query containing Alice overrides Bob’s default, or a query is created before the delegated session finishes updating. Neither is verified in the affected flow.
Code evidence and alternatives checked
- Default construction: The menu reads the current session identity in useSearchTypeMenuSections.ts:53–56. Drafts embeds the supplied ID directly as its From filter in SearchSuggestionUtils.ts:192–203. With Bob’s session ID, this should select Bob.
- Restored-query alternative: Navigation can prefer a previous query over the default. Validation checks filter keys and search type, not the From identity, so an existing Alice query can qualify against Bob’s default: SearchNavigationUtils.ts:9–13, SearchQueryUtils.ts:3351–3380. However, delegation clears account-scoped local state and preserved Search navigation, so ordinary cross-account cache leakage is not established: Delegate.ts:251–291.
- Display-only alternative: Query-to-form conversion preserves explicit account IDs; only literal
meis resolved to the current user. Changingmehandling would not repair an explicit Alice ID: SearchQueryUtils.ts:2087–2097.
What will confirm the cause: In an affected copilot session, compare the active session account ID, the Drafts URL query, the stored Drafts query, and the From form value immediately after switching and after opening Drafts:
- Session is Alice: investigate delegation/session-update ordering.
- Session is Bob, query contains Alice: trace restored query or navigation state; check whether resetting filters selects Bob.
- Query contains Bob, picker selects Alice: investigate filter-form synchronization or selector state instead.
Recommendation: Do not replace the identity source or force every From filter to Bob yet; that could overwrite intentionally selected filters. Once the failing branch is identified, add an Alice → Bob → Drafts regression covering the default query, picker selection, and submitted search filter.
Verification limit: Web testing could not reach a delegated account because the available session had no accessible copilot fixture. No runtime reproduction or production-log confirmation was obtained. The quick open-issue scan found no clear duplicate.
Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis, ideally with the affected-flow state checks above (keep account-specific identifiers out of this public issue).
🤖 Web test steps verification results: ⚠️ partial
Blocked on dev NewDot web: the existing session exposes only the signed-in test account, with no accessible Alice/Bob copilot fixture. No additional account or session was created.
| Step | Status |
|---|---|
1: Two accounts with Alice configured as Bob's copilot are availableAccount opened the test user's Profile. No Copilot entry or delegated-account selector was exposed; required fixture availability could not be established.![]() |
⚠️ |
2: Alice can copilot into BobNot executed: required copilot fixture was unavailable. |
⚠️ |
3: Open Spend > DraftsNot executed in Bob's account: blocked by unavailable copilot fixture. |
⚠️ |
4: Click From filterNot executed: prerequisite copilot context was unavailable. |
⚠️ |
5: Selected user is Bob (account holder), not Alice (copilot)Not verified: prerequisite copilot context was unavailable. The reported issue was neither reproduced nor disproved. |
⚠️ |
Triggered auto assignment to Contributor-plus team member for initial proposal review - @nkdengineer (External)
Job added to Upwork: https://www.upwork.com/jobs/~022118367402292021507
Proposal
Please re-state the problem that we are trying to solve in this issue.
Dictamen: insuficiente para una propuesta verificable. No se ha identificado la función, archivo ni línea defectuosa.
Según el reporte, al operar Alice como copilot de Bob, Spend > Drafts selecciona a Alice en From, aunque debería seleccionar a Bob.
What is the root cause of that problem?
No demostrada. Confundir la identidad autenticada con la cuenta representada es una hipótesis, no una RCA.
Faltan código de la versión afectada y trazas que distingan entre un default incorrecto, estado persistido de Alice o una selección visual incorrecta. No hay evidencia de fuga de datos ni bypass de autorización; no corresponde asignar CVSS.
What changes do you think we should make in order to solve the problem?
Primero hay que localizar quién inicializa From y comprobar qué identidad recibe durante la delegación. El cambio debe corregir ese origen y preservar las selecciones explícitas del usuario.
No presento un diff ficticio de 3–10 líneas: no hay checkout local de Expensify/App y no pude consultar el issue ni verificar la rama.
Compare branch: https://github.com/Expensify/App/compare/main...camesenin:App:fix-issue-106117?expand=1
Ese enlace no acredita que exista un parche válido.
What alternative solutions did you explore? (Optional)
No se proporcionó propuesta de MelvinBot; atacarla sería inventar evidencia. Cambiar únicamente la etiqueta podría ocultar un valor incorrecto; sustituir globalmente la identidad podría alterar búsquedas explícitas.
What automated tests can you add to prevent this from re-occurring?
En el test existente del componente o hook responsable, verificar Alice→Bob, sesión normal y salida/cambio de cuenta delegada, preservando filtros explícitos. Debe fallar antes del parche y pasar después; no se ejecutaron tests ni se verificó el archivo correspondiente.
Contributor details
Your Expensify account email: [email protected]
Upwork Profile Link: https://www.upwork.com/freelancers/~01b60d704ba377be83
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue
When Alice copilots into Bob's account and navigates to Spend > Drafts, clicking the From filter defaults to selecting Alice (the copilot) rather than Bob (the account holder).
What is the root cause of that problem?
In src/libs/actions/Delegate.ts, when connecting as a delegate via connect(), the response returns the delegated account credentials: response.accountID and response.email (Bob's details) along with response.restrictedToken.
However, in the connection transition flow:
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, CONST.AUTH_TOKEN_TYPES.DELEGATE);
})
.then(() => {
NetworkStore.setAuthToken(response?.restrictedToken ?? null);
Pusher.disconnect();
return clearOnyxForDelegateTransition();
})
updateSessionAuthTokens only updates the tokens and authTokenType:
return Onyx.merge(ONYXKEYS.SESSION, {authToken, encryptedAuthToken, authTokenType, creationDate: new Date().getTime()});
Notice that KEYS_TO_PRESERVE_DELEGATE_ACCESS preserves ONYXKEYS.SESSION. Because SESSION.accountID and SESSION.email were never updated to response.accountID and response.email, the session in Onyx retains Alice's accountID and email!
Consequently:
src/hooks/useSearchTypeMenuSections.tsreadsONYXKEYS.SESSIONto obtaincurrentUserLoginAndAccountID.- When building the canned Drafts query in
SearchSuggestionUtils.ts(or initializing filter selectors inUserSelector), the query embedsfrom:<Alice's accountID/email>instead of Bob's. - Upon disconnect,
restoreDelegateSessionalready correctly restores Alice's original session fromstashedSession.
What changes do you think we should make in order to solve the problem?
In src/libs/actions/Delegate.ts, when saving the delegate tokens prior to the transition, also update accountID and email on ONYXKEYS.SESSION to match the delegated account holder (response.accountID and response.email):
diff --git a/src/libs/actions/Delegate.ts b/src/libs/actions/Delegate.ts
index c6b812a..e38947b 100644
--- a/src/libs/actions/Delegate.ts
+++ b/src/libs/actions/Delegate.ts
@@ -270,6 +270,12 @@ function connect({email, activePolicyID, credentials, session}: ConnectParams) {
return SequentialQueue.waitForIdle()
.then(() => {
// Update authToken in Onyx so it persists if the further flow does not complete for any reason.
+ if (response?.accountID && response?.email) {
+ Onyx.merge(ONYXKEYS.SESSION, {
+ accountID: response.accountID,
+ email: response.email,
+ });
+ }
return updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE);
})
.then(() => {
This ensures ONYXKEYS.SESSION accurately reflects the active delegated identity (Bob) throughout the app while operating under delegated access. When disconnected, restoreDelegateSession cleanly restores the original session via stashedSession.
What alternative solutions did you explore? (Optional)
We also evaluated overriding the current user in useSearchTypeMenuSections or UserSelector by checking account.delegatedAccess?.delegate. However, updating SESSION.accountID and SESSION.email at transition time is far cleaner, more surgical, and ensures consistency across all session-dependent queries and selectors in the app without risk of regressions.
Unit Tests / Automated Tests
Add a unit test in tests/unit/DelegateTest.ts:
- Verify that upon
Delegate.connect(),ONYXKEYS.SESSIONhas itsaccountIDandemailupdated to the target delegator account (response.accountID,response.email). - Verify that
useSearchTypeMenuSectionsconstructs the Drafts query using the delegator's account ID/email. - Verify that on
Delegate.disconnect(),restoreDelegateSessionrestoresONYXKEYS.SESSIONback to the original user'saccountIDandemail.
Visual Evidence
Reproduction / verification video reference from issue attachment: https://github.com/user-attachments/assets/2abf8aa3-1ff1-41e6-b7ca-f7e4b320ac01
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~017a671f901fafe3a1
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
While copiloting into Bob's account, Spend > Drafts opens with the From filter set to the copilot (Alice) instead of Bob.
What is the root cause of that problem?
Clicking Drafts does not open the canned Drafts query directly. That query is built from the session account, from:<accountID> (src/libs/SearchSuggestionUtils.ts:197-201). Instead, the click goes through getValidLastQuery:
- the wide menu:
SearchTypeMenuWide.tsx:102→SearchNavigationUtils.ts:12; - the router:
useNavigationSuggestions.tsx:439→SearchNavigationUtils.ts:12; - the narrow tabs:
SearchTypeMenuNarrow.tsx:217.
getValidLastQuery prefers the last Drafts query saved in nvp_searchFilters. That is written per searchKey in Search.ts:1454-1462 and read in SearchUIUtils.ts:5022-5025.
getValidLastQuery accepts the saved query whenever it has the same filter keys and type as the default (doesQueryMatchDefaultFilterKeysAndType, SearchQueryUtils.ts:3346-3357, used at :3376). It never compares the values. So a saved from:<Alice> passes against the default from:<Bob>, and UserSelector shows Alice selected. similarSearchHash also ignores the from value (SearchQueryUtils.ts:1031-1067), so the page still highlights as Drafts.
The canned Approve (to:), Pay (payer:) and Export (exporter:) searches have the same gap.
One case this does not cover: if SESSION.accountID is still Alice while copiloting, the default is itself from:Alice. connect only merges tokens into SESSION (Delegate.ts:269-277, updateSessionAuthTokens.ts:18).
To tell the two cases apart, read session.accountID and nvp_searchFilters.submit.query while copiloting.
session.accountIDis Bob and the saved query has Alice's ID: the cause is the saved query above.session.accountIDis Alice: the default itself is wrong.
What changes do you think we should make in order to solve the problem?
- In
SearchQueryUtils.ts, addgetValidCannedLastQuery(searchKey, lastQuery, defaultQuery). It first runsgetValidLastQuery. Then, only forSUBMIT,APPROVE,PAYandEXPORT, it returns the default when the saved query'sfrom/to/payer/exporter(eqoperator) does not contain the default's account ID. The check is skipped while that ID isCONST.DEFAULT_NUMBER_ID, so a cold start does not drop a valid query. - Call it in
SearchNavigationUtils.ts:12(which covers the wide menu and the router) and inSearchTypeMenuNarrow.tsx:217. - Leave
getValidLastQueryitself, saved searches (SavedSearchList.tsx:149) and the Expenses tab default unchanged.
Behaviour:
- Copilot into Bob: a saved
from:Alicefalls back tofrom:Bob. - Back in Alice's own account,
from:Aliceis kept. from:Bob,Carolis kept.-from:Bobandfrom:Carolalone reset to the default.- Saved searches are unaffected; the check is local, so it also works offline.
If the session reading shows SESSION.accountID is Alice, also write accountID and email from the connect response into SESSION inside the promise chain before clearOnyxForDelegateTransition (Delegate.ts:269-273).
Tests: unit-test getValidCannedLastQuery for each case above, for each of the four keys.
What alternative solutions did you explore? (Optional)
- Run the check only while acting as a delegate (
isActingAsDelegateSelector). This keeps every narrowed canned filter, but a stale value would survive into Bob's own login. - Compare all filter values in
getValidLastQuery. This would discard every user customisation, saved searches included.
📣 @symposia-gi! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01455f651d6c6c04f1
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that the issue is trying to solve.
When a copilot (e.g. Alice) connects to an account holder's account (e.g. Bob) via Copilot mode, navigating to Search > Spend > Drafts defaults the From search filter to the copilot's account ID (Alice) instead of the account holder's account ID (Bob).
What is the root cause of that problem?
In src/libs/actions/Delegate.ts, when connecting as a copilot, connect() clears Onyx keys via clearOnyxForDelegateTransition() while preserving a subset of keys defined in KEYS_TO_PRESERVE_DELEGATE_ACCESS (which includes ONYXKEYS.SESSION):
https://github.com/Expensify/App/blob/main/src/libs/actions/Delegate.ts#L270-L282
After the API response is received in connect(), updateSessionAuthTokens is called to update authentication tokens:
updateSessionAuthTokens(response.authToken, response.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE);
However, updateSessionAuthTokens only updates authToken, encryptedAuthToken, and authTokenType. It never updates ONYXKEYS.SESSION.accountID and ONYXKEYS.SESSION.email to the delegator's credentials (response.accountID, response.email).
In contrast, observe disconnect() in src/libs/actions/Delegate.ts:1004-1011:
Onyx.merge(ONYXKEYS.SESSION, {
authToken: response.authToken,
encryptedAuthToken: response.encryptedAuthToken,
accountID: response.accountID,
email: response.email,
});
When disconnecting, Delegate.ts explicitly updates accountID and email on ONYXKEYS.SESSION. But when connect() executes, ONYXKEYS.SESSION.accountID and ONYXKEYS.SESSION.email are left holding Alice's original IDs!
Consequently:
src/hooks/useSearchTypeMenuSections.ts:53-56readssession?.accountID:
const currentUserLoginAndAccountID = useMemo(
() => ({
currentUserAccountID: session?.accountID ?? CONST.DEFAULT_NUMBER_ID,
currentUserEmail: session?.email ?? '',
}),
[session?.accountID, session?.email],
);
- When building the
SUBMIT(Drafts) search suggestion inSearchSuggestionUtils.ts:197-201, it setsfrom: [currentUserAccountID]:
[CONST.SEARCH.SEARCH_KEYS.SUBMIT]: {
type: CONST.SEARCH.DATA_TYPES.EXPENSE,
status: CONST.SEARCH.STATUS.EXPENSE.DRAFTS,
from: [currentUserAccountID],
},
Because session.accountID still holds Alice's ID rather than Bob's, the filter defaults to Alice.
(Note on previous comments: NVP_SEARCH_FILTERS is NOT the cause here. KEYS_TO_PRESERVE_DELEGATE_ACCESS does not preserve NVP_SEARCH_FILTERS, so it is already cleared during delegate transition. The root cause is strictly that ONYXKEYS.SESSION is preserved without updating accountID and email to the target delegator).
What changes do you think we should make in order to solve the problem?
In src/libs/actions/Delegate.ts inside connect(), update ONYXKEYS.SESSION with the delegator's accountID and email when setting tokens:
- updateSessionAuthTokens(response.authToken, response.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE);
+ Onyx.merge(ONYXKEYS.SESSION, {
+ authToken: response.authToken,
+ encryptedAuthToken: response.encryptedAuthToken,
+ authTokenType: CONST.AUTH_TOKEN_TYPES.DELEGATE,
+ accountID: response.accountID,
+ email: response.email,
+ });
(Alternatively, updateSessionAuthTokens can accept optional accountID and email parameters to perform this merge centrally).
This guarantees that all hooks and providers reading active session identity (such as useSearchTypeMenuSections and CurrentUserPersonalDetailsProvider) correctly resolve the account holder's identity while in Copilot mode.
What alternative solutions did you explore? (Optional)
None needed, updating ONYXKEYS.SESSION aligns connect() directly with the existing pattern already used in disconnect().
Proposal
Please re-state the problem that we are trying to solve in this issue
When Alice copilots into Bob's account and opens Spend > Drafts, the From filter defaults to Alice (the copilot) instead of Bob (the account holder). The Drafts "From" value is built from the active session's accountID, so if the session still carries Alice's identity during delegation, the canned query is from:<Alice>.
What is the root cause of that problem?
Delegate.connect() switches the auth token to the delegator but never switches the identity fields on the preserved session.
Trace, src/libs/actions/Delegate.ts:
connect()calls the API and, on the success response, runs (lines 269–273):
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, CONST.AUTH_TOKEN_TYPES.DELEGATE);
})
updateSessionAuthTokens(src/libs/actions/Session/updateSessionAuthTokens.ts:17) only merges token fields — it does not writeaccountIDoremail:
return Onyx.merge(ONYXKEYS.SESSION, {authToken, encryptedAuthToken, authTokenType, creationDate: new Date().getTime()});
-
ONYXKEYS.SESSIONis inKEYS_TO_PRESERVE_DELEGATE_ACCESS(Delegate.ts:39), so the subsequentclearOnyxForDelegateTransition()preserves it instead of clearing it — the comment atDelegate.ts:993confirms "SESSION is preserved acrossclearOnyxForDelegateTransitionviaKEYS_TO_PRESERVE_DELEGATE_ACCESS". SoSESSION.accountIDandSESSION.emailstill hold Alice's values after the transition. -
loadAccountAfterDelegateTransition(Delegate.ts:86–97) receivesresponse.accountID/response.emailbut only forwards them torequestPusherReinitialize(...)and (hybrid-only)HybridAppModule.switchAccount(...); it never merges them intoONYXKEYS.SESSION. -
The Drafts query is then built from that still-Alice session:
useSearchTypeMenuSectionsselectssession?.accountID(src/hooks/useSearchTypeMenuSections.ts:53–55) and passes it intocreateTypeMenuSections, which builds the SUBMIT/Drafts suggestion withfrom: [\${accountID}`](src/libs/SearchSuggestionUtils.ts:197–201). Result:from:`.
Contrast with disconnect() — which does the right thing. restoreDelegateSession (Delegate.ts ~line 1004, and the disconnect success path) explicitly merges accountID and email back into ONYXKEYS.SESSION:
Onyx.merge(ONYXKEYS.SESSION, {
authToken: response.authToken,
encryptedAuthToken: response.encryptedAuthToken,
accountID: response.accountID,
email: response.email,
});
So connect() is the asymmetric half: tokens updated, identity forgotten.
On the alternative root cause (restored last-query): a prior proposal argues getValidLastQuery (SearchNavigationUtils.ts) accepts a stale saved from:<Alice> because it only compares filter keys/types, not values, against the default. While that gap is real, it is not the trigger here because ONYXKEYS.NVP_SEARCH_FILTERS is not in KEYS_TO_PRESERVE_DELEGATE_ACCESS (Delegate.ts:34–64) — it is wiped by clearOnyxForDelegateTransition(). With no saved query, getValidLastQuery returns the default, which itself is from:<Alice> because of the SESSION defect above. So the saved-query path is a defensible defense-in-depth hardening (and I'd add it as a guard), but the root cause is the preserved-SESSION identity mismatch in connect().
What changes do you think we should make in order to solve the problem?
Primary fix — update SESSION.accountID/email on delegate connect, mirroring disconnect(). In Delegate.connect()'s promise chain, before clearOnyxForDelegateTransition() (so the new identity survives the preserve-and-clear step), merge the delegator's identity into the preserved session:
return SequentialQueue.waitForIdle()
.then(() => {
// Update authToken in Onyx so it persists if the further flow does not complete for any reason.
+ // Mirror disconnect(): switch the SESSION identity to the delegator alongside the token,
+ // so account-scoped queries (e.g. Drafts `from:`) build against the account holder.
+ Onyx.merge(ONYXKEYS.SESSION, {
+ accountID: response?.accountID,
+ email: response?.email,
+ });
return updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE);
})
(Alternatively, extend updateSessionAuthTokens to accept optional accountID/email and do the merge centrally — cleaner if other call sites need the same guarantee, but a direct Onyx.merge here keeps the diff surgical and matches the existing disconnect() pattern.)
On disconnect: restoreDelegateSession/restoreOriginalSession already restores the stashed session identity, so leaving the delegate session correctly reverts to Alice. I'll verify restoreDelegateSession (Delegate.ts ~349–354) reads stashedSession?.accountID/email (it does in the current code) so no change is needed there.
Defense-in-depth (optional, recommended): add the getValidLastQuery value-check for canned SUBMIT/APPROVE/PAY/EXPORT keys described in a prior proposal, so a stale from: value can't survive even if some other path re-introduces it. I'd scope this to when session.accountID differs from the saved query's from account.
What specific scenarios should be covered by automated tests?
tests/unit/DelegateTest.ts:- After
connect(),ONYXKEYS.SESSION.accountIDand.emailequal the delegator's (response.accountID/response.email), whileauthToken/authTokenTypeare the delegated token/type. - After
disconnect(),SESSION.accountID/.emailrevert to the original stashed user. - After
connect(),useSearchTypeMenuSectionsbuilds the Drafts query withfrom:<delegator accountID>.
- After
- Add an Alice → Bob → Drafts UI test asserting the From filter pre-selects Bob, and that returning to Alice's own account keeps
from:<Alice>.
What alternative solutions did you explore? (Optional)
- Override the identity at the read site (
useSearchTypeMenuSections/UserSelector) usingaccount.delegatedAccess. Rejected: it scatters the fix across every session-consuming hook and risks other account-scoped queries still using Alice; fixing the session identity at the transition is the single source of truth. - Force every canned
from:to the account holder globally. Rejected: would override intentional user filters; the session fix makes the default correct without touching explicit selections.
PR
PR will be linked here once created.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b6a593fd295a20bf
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
When user Alice connects as a Copilot (delegate) to account holder Bob's account and navigates to Reports > Spend > Drafts, the default From filter is set to Alice (the copilot) instead of Bob (the account holder whose account is being accessed).
What is the root cause of that problem?
There are two parts to this root cause:
- In
src/libs/SearchQueryUtils.ts/src/libs/SearchUIUtils.ts(where theSpend > Draftscanned querybuildCannedSearchQuery/ type-menu item forDraftsis constructed), theDraftssearch query defaults itsfromfilter using the current user'saccountIDread fromONYXKEYS.SESSION(currentUserAccountID/session?.accountIDor cached module-levelcurrentUserAccountIDinSearchQueryUtils.ts). - In
src/libs/actions/Delegate.tsinsideconnect(email: string)(lines 61–95), when switching into a delegated account:clearOnyxForDelegateTransition()preservesONYXKEYS.SESSION(becauseONYXKEYS.SESSIONis inKEYS_TO_PRESERVE_DELEGATE_ACCESS).- In the
.then((response)callback ofAPI.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.CONNECT_AS_DELEGATE, ...),updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE)only mergesauthToken,encryptedAuthToken, andauthTokenTypeintoONYXKEYS.SESSIONwithout updatingaccountIDandemailbefore the optimistic/initial transition completes (or module-levelONYXKEYS.SESSIONsubscribers inSearchQueryUtils.ts/PersonalDetailsUtils.tsstill hold the copilot'saccountIDor resolvedelegateAccountID).
Specifically, let's also check how SearchQueryUtils.ts sanitizes or builds from: for Drafts: when building the Drafts query (status:draft), from is populated with the copilot's accountID (or session.email / delegatedAccess) instead of the target account holder's accountID (PersonalDetailsUtils.getAccountIDsByLogins([email]) / session.accountID).
What changes do you think we should make in order to solve the problem?
- In
src/libs/actions/Delegate.tsinsideconnect()(anddisconnect()), ensure that whenCONNECT_AS_DELEGATEsucceeds (or via theonyxDatareturned byConnectAsDelegate),ONYXKEYS.SESSIONhas itsaccountIDandemailupdated to the account holder'saccountIDandemailalongsiderestrictedTokenandencryptedAuthToken, and clear any persistedONYXKEYS.NVP_SEARCH_FILTERS/ cached search filter state duringclearOnyxForDelegateTransition(). - In
src/libs/SearchQueryUtils.ts/src/components/Search/SearchPageHeader/useSearchFiltersBar.ts, ensure the defaultfromfilter forDraftsreads the active account holder'saccountIDfrom the liveuseCurrentUserPersonalDetails()/ONYXKEYS.SESSIONhook value rather than a stale pre-delegate session reference.
What alternative solutions did you explore? (Optional)
We also considered omitting the from filter entirely on Spend > Drafts when acting as a copilot, but Drafts is scoped to the current account holder's draft expenses (from:<accountHolderAccountID>), so updating the session/active accountID used by Drafts to Bob's accountID matches the expected behavior in the issue description.
📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Proposal
Please re-state the problem that we are trying to solve in this issue.
When Alice connects as a Copilot (delegate) into Bob's account and navigates to Spend > Drafts, opening the From filter shows Alice (the copilot) selected by default instead of Bob (the account holder).
What is the root cause of that problem?
- In
src/libs/actions/Delegate.ts:38-68,ONYXKEYS.SESSIONis listed inKEYS_TO_PRESERVE_DELEGATE_ACCESS, soclearOnyxForDelegateTransition()(line 300) preservesONYXKEYS.SESSIONacross the delegate account switch. - In
connect()(src/libs/actions/Delegate.ts:276-306), whenSIDE_EFFECT_REQUEST_COMMANDS.CONNECT_AS_DELEGATEresolves withresponse.restrictedToken,response.encryptedAuthToken,response.accountID, andresponse.email(Bob's account ID and email),line 294calls:
However,return updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE);updateSessionAuthTokens(src/libs/actions/Session/updateSessionAuthTokens.ts) only merges{authToken, encryptedAuthToken, authTokenType, creationDate}intoONYXKEYS.SESSION—it never updatesaccountIDoremailonONYXKEYS.SESSION(unlikedisconnect()atsrc/libs/actions/Delegate.ts:368-402, which explicitly restoresaccountID: response.requesterIDandemail: requesterEmailviarestoreDelegateSession). Meanwhile,loadAccountAfterDelegateTransition(lines 105-116, 303-305) only passesresponse.accountIDandresponse.emailtorequestPusherReinitialize. - Because
ONYXKEYS.SESSIONstill holds Alice'saccountIDandemail,src/hooks/useSearchTypeMenuSections.ts:53-56, 72, 113-116(currentUserLoginAndAccountIDSelector) passes Alice'saccountIDintocreateTypeMenuSections->SearchSuggestionUtils.ts:197-201, which builds theCONST.SEARCH.SEARCH_KEYS.SUBMIT(Drafts) query withfrom: [currentUserAccountID]set to Alice instead of Bob.
What changes do you think we should make in order to solve the problem?
- In
src/libs/actions/Delegate.ts:291-295, updateaccountIDandemailonONYXKEYS.SESSIONfromresponse.accountIDandresponse.emailwhen saving the delegated session tokens (matching howdisconnect()restoresaccountIDandemailfromresponse.requesterID/stashedSession):return SequentialQueue.waitForIdle() .then(() => { // Update authToken and delegated account identity in Onyx so it persists if the further flow does not complete for any reason. return updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE).then(() => Onyx.merge(ONYXKEYS.SESSION, { ...(response?.accountID ? {accountID: response.accountID} : {}), ...(response?.email ? {email: response.email} : {}), }), ); }) - Add a unit test in
tests/unit/DelegateTest.tsverifying thatDelegate.connect()updatesONYXKEYS.SESSION.accountIDandONYXKEYS.SESSION.emailto the delegator's account ID and email, andDelegate.disconnect()restores them back to the original user's session.
What alternative solutions did you explore? (Optional)
Overriding the current user identity inside useSearchTypeMenuSections by looking up account.delegatedAccess was considered, but updating ONYXKEYS.SESSION during Delegate.connect() (symmetric with Delegate.disconnect()) ensures all session-scoped hooks and queries across the app resolve the active account holder's identity consistently.
📣 @ronanchnlps-bit! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>