App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-26] [$175] Copilot - "From" filter on Spend > Drafts defaults to the copilot (Alice) instead of the account holder (Bob)

Open m-natarajan opened this issue 3 weeks ago • 47 comments

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:

  1. Set up two accounts: Account A (Alice) and Account B (Bob).
  2. Make Alice a copilot of Bob.
  3. As Alice, Copilot into Bob's account.
  4. Go to Spend > Drafts.
  5. Click the From filter.
  6. 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

View all open jobs on GitHub

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

m-natarajan avatar Nov 05 '26 15:11 m-natarajan

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 me is resolved to the current user. Changing me handling 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:

  1. Session is Alice: investigate delegation/session-update ordering.
  2. Session is Bob, query contains Alice: trace restored query or navigation state; check whether resetting filters selects Bob.
  3. 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).


view run

MelvinBot avatar Nov 05 '26 15:11 MelvinBot

🤖 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.

Existing account Profile with no accessible copilot fixture
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.
Existing account Profile with no accessible copilot fixture
⚠️
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.
⚠️

view run · view recording

MelvinBot avatar Nov 05 '26 15:11 MelvinBot

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

melvin-bot[bot] avatar Nov 05 '26 15:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022118367402292021507

melvin-bot[bot] avatar Nov 05 '26 15:11 melvin-bot[bot]

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

camesenin avatar Nov 05 '26 16:11 camesenin

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 05 '26 16:11 melvin-bot[bot]

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:

  1. src/hooks/useSearchTypeMenuSections.ts reads ONYXKEYS.SESSION to obtain currentUserLoginAndAccountID.
  2. When building the canned Drafts query in SearchSuggestionUtils.ts (or initializing filter selectors in UserSelector), the query embeds from:<Alice's accountID/email> instead of Bob's.
  3. Upon disconnect, restoreDelegateSession already correctly restores Alice's original session from stashedSession.

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:

  1. Verify that upon Delegate.connect(), ONYXKEYS.SESSION has its accountID and email updated to the target delegator account (response.accountID, response.email).
  2. Verify that useSearchTypeMenuSections constructs the Drafts query using the delegator's account ID/email.
  3. Verify that on Delegate.disconnect(), restoreDelegateSession restores ONYXKEYS.SESSION back to the original user's accountID and email.

Visual Evidence

Reproduction / verification video reference from issue attachment: https://github.com/user-attachments/assets/2abf8aa3-1ff1-41e6-b7ca-f7e4b320ac01

Hazem20wosis avatar Nov 05 '26 16:11 Hazem20wosis

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~017a671f901fafe3a1

Hazem20wosis avatar Nov 05 '26 16:11 Hazem20wosis

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 05 '26 16:11 melvin-bot[bot]

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.accountID is Bob and the saved query has Alice's ID: the cause is the saved query above.
  • session.accountID is Alice: the default itself is wrong.

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

  1. In SearchQueryUtils.ts, add getValidCannedLastQuery(searchKey, lastQuery, defaultQuery). It first runs getValidLastQuery. Then, only for SUBMIT, APPROVE, PAY and EXPORT, it returns the default when the saved query's from/to/payer/exporter (eq operator) does not contain the default's account ID. The check is skipped while that ID is CONST.DEFAULT_NUMBER_ID, so a cold start does not drop a valid query.
  2. Call it in SearchNavigationUtils.ts:12 (which covers the wide menu and the router) and in SearchTypeMenuNarrow.tsx:217.
  3. Leave getValidLastQuery itself, saved searches (SavedSearchList.tsx:149) and the Expenses tab default unchanged.

Behaviour:

  • Copilot into Bob: a saved from:Alice falls back to from:Bob.
  • Back in Alice's own account, from:Alice is kept.
  • from:Bob,Carol is kept.
  • -from:Bob and from:Carol alone 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 avatar Nov 05 '26 16:11 symposia-gi

📣 @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:

  1. Make sure you've read and understood the contributing guidelines.
  2. 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.
  3. 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.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 05 '26 16:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01455f651d6c6c04f1

symposia-gi avatar Nov 05 '26 17:11 symposia-gi

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 05 '26 17:11 melvin-bot[bot]

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:

  1. src/hooks/useSearchTypeMenuSections.ts:53-56 reads session?.accountID:
const currentUserLoginAndAccountID = useMemo(
    () => ({
        currentUserAccountID: session?.accountID ?? CONST.DEFAULT_NUMBER_ID,
        currentUserEmail: session?.email ?? '',
    }),
    [session?.accountID, session?.email],
);
  1. When building the SUBMIT (Drafts) search suggestion in SearchSuggestionUtils.ts:197-201, it sets from: [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().

Enes2553 avatar Nov 05 '26 21:11 Enes2553

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:

  1. 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);
    })
  1. updateSessionAuthTokens (src/libs/actions/Session/updateSessionAuthTokens.ts:17) only merges token fields — it does not write accountID or email:
return Onyx.merge(ONYXKEYS.SESSION, {authToken, encryptedAuthToken, authTokenType, creationDate: new Date().getTime()});
  1. ONYXKEYS.SESSION is in KEYS_TO_PRESERVE_DELEGATE_ACCESS (Delegate.ts:39), so the subsequent clearOnyxForDelegateTransition() preserves it instead of clearing it — the comment at Delegate.ts:993 confirms "SESSION is preserved across clearOnyxForDelegateTransition via KEYS_TO_PRESERVE_DELEGATE_ACCESS". So SESSION.accountID and SESSION.email still hold Alice's values after the transition.

  2. loadAccountAfterDelegateTransition (Delegate.ts:86–97) receives response.accountID / response.email but only forwards them to requestPusherReinitialize(...) and (hybrid-only) HybridAppModule.switchAccount(...); it never merges them into ONYXKEYS.SESSION.

  3. The Drafts query is then built from that still-Alice session: useSearchTypeMenuSections selects session?.accountID (src/hooks/useSearchTypeMenuSections.ts:53–55) and passes it into createTypeMenuSections, which builds the SUBMIT/Drafts suggestion with from: [\${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:
    1. After connect(), ONYXKEYS.SESSION.accountID and .email equal the delegator's (response.accountID/response.email), while authToken/authTokenType are the delegated token/type.
    2. After disconnect(), SESSION.accountID/.email revert to the original stashed user.
    3. After connect(), useSearchTypeMenuSections builds the Drafts query with from:<delegator accountID>.
  • 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) using account.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

vanshshah11 avatar Nov 07 '26 00:11 vanshshah11

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 07 '26 00:11 melvin-bot[bot]

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:

  1. In src/libs/SearchQueryUtils.ts / src/libs/SearchUIUtils.ts (where the Spend > Drafts canned query buildCannedSearchQuery / type-menu item for Drafts is constructed), the Drafts search query defaults its from filter using the current user's accountID read from ONYXKEYS.SESSION (currentUserAccountID / session?.accountID or cached module-level currentUserAccountID in SearchQueryUtils.ts).
  2. In src/libs/actions/Delegate.ts inside connect(email: string) (lines 61–95), when switching into a delegated account:
    • clearOnyxForDelegateTransition() preserves ONYXKEYS.SESSION (because ONYXKEYS.SESSION is in KEYS_TO_PRESERVE_DELEGATE_ACCESS).
    • In the .then((response) callback of API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.CONNECT_AS_DELEGATE, ...), updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE) only merges authToken, encryptedAuthToken, and authTokenType into ONYXKEYS.SESSION without updating accountID and email before the optimistic/initial transition completes (or module-level ONYXKEYS.SESSION subscribers in SearchQueryUtils.ts / PersonalDetailsUtils.ts still hold the copilot's accountID or resolve delegateAccountID).

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?

  1. In src/libs/actions/Delegate.ts inside connect() (and disconnect()), ensure that when CONNECT_AS_DELEGATE succeeds (or via the onyxData returned by ConnectAsDelegate), ONYXKEYS.SESSION has its accountID and email updated to the account holder's accountID and email alongside restrictedToken and encryptedAuthToken, and clear any persisted ONYXKEYS.NVP_SEARCH_FILTERS / cached search filter state during clearOnyxForDelegateTransition().
  2. In src/libs/SearchQueryUtils.ts / src/components/Search/SearchPageHeader/useSearchFiltersBar.ts, ensure the default from filter for Drafts reads the active account holder's accountID from the live useCurrentUserPersonalDetails() / ONYXKEYS.SESSION hook 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 avatar Nov 07 '26 01:11 jeffrey-graham

📣 @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:

  1. Make sure you've read and understood the contributing guidelines.
  2. 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.
  3. 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.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 01:11 melvin-bot[bot]

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?

  1. In src/libs/actions/Delegate.ts:38-68, ONYXKEYS.SESSION is listed in KEYS_TO_PRESERVE_DELEGATE_ACCESS, so clearOnyxForDelegateTransition() (line 300) preserves ONYXKEYS.SESSION across the delegate account switch.
  2. In connect() (src/libs/actions/Delegate.ts:276-306), when SIDE_EFFECT_REQUEST_COMMANDS.CONNECT_AS_DELEGATE resolves with response.restrictedToken, response.encryptedAuthToken, response.accountID, and response.email (Bob's account ID and email), line 294 calls:
    return updateSessionAuthTokens(response?.restrictedToken, response?.encryptedAuthToken, CONST.AUTH_TOKEN_TYPES.DELEGATE);
    
    However, updateSessionAuthTokens (src/libs/actions/Session/updateSessionAuthTokens.ts) only merges {authToken, encryptedAuthToken, authTokenType, creationDate} into ONYXKEYS.SESSION—it never updates accountID or email on ONYXKEYS.SESSION (unlike disconnect() at src/libs/actions/Delegate.ts:368-402, which explicitly restores accountID: response.requesterID and email: requesterEmail via restoreDelegateSession). Meanwhile, loadAccountAfterDelegateTransition (lines 105-116, 303-305) only passes response.accountID and response.email to requestPusherReinitialize.
  3. Because ONYXKEYS.SESSION still holds Alice's accountID and email, src/hooks/useSearchTypeMenuSections.ts:53-56, 72, 113-116 (currentUserLoginAndAccountIDSelector) passes Alice's accountID into createTypeMenuSections -> SearchSuggestionUtils.ts:197-201, which builds the CONST.SEARCH.SEARCH_KEYS.SUBMIT (Drafts) query with from: [currentUserAccountID] set to Alice instead of Bob.

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

  1. In src/libs/actions/Delegate.ts:291-295, update accountID and email on ONYXKEYS.SESSION from response.accountID and response.email when saving the delegated session tokens (matching how disconnect() restores accountID and email from response.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} : {}),
                }),
            );
        })
    
  2. Add a unit test in tests/unit/DelegateTest.ts verifying that Delegate.connect() updates ONYXKEYS.SESSION.accountID and ONYXKEYS.SESSION.email to the delegator's account ID and email, and Delegate.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.

tungnguyen84 avatar Nov 07 '26 06:11 tungnguyen84

📣 @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:

  1. Make sure you've read and understood the contributing guidelines.
  2. 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.
  3. 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.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 10:11 melvin-bot[bot]