App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Changes to 'Expenses from' are auto-saved when going back.

Open applause-bot[bot] opened this issue 2 weeks ago • 25 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: v9.5.40-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: https://github.com/Expensify/App/pull/106776 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Google Pixel 8 - Android 16; Windows 10-Chrome App Component: Left Hand Navigation (LHN)

Action Performed:

Precondition: the account has a workspace that invites some members

  1. Open Expensify app
  2. Log in with the account at the preconditions
  3. Tap on the Workspaces tab> Workflows
  4. Tap on the 'Add approval workflow'
  5. Choose one or some member from the 'Expenses from' page, then tap on the Next button
  6. Choose any member from the 'Approver' page
  7. Tap on the 'Add workflow' from the 'Confirm' button
  8. Tap on the workflow that was created at step 7> 'Expense from'
  9. Choose some other members, then tap on the back button

Expected Result:

After step 9, the previously saved members in the 'Expenses from' field remain unchanged.

Actual Result:

After step 9, the selected members appear in the 'Expenses from' field even though the user hasn't tapped the 'Save' button. This contradicts step 2 of PR 106776.

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/fb67cb5f-74f1-421a-b707-68be5c1b2136

View all open jobs on GitHub

Applause Internal Information Exported by: Julia Ponikarchuk Bug ID: 7316934

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

applause-bot[bot] avatar Nov 17 '26 19:11 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/29a0bec78616db7d5da4f2e04a13db0224a95ac5625e483658ddb783f721c5a5

applause-bot[bot] avatar Nov 17 '26 19:11 applause-bot[bot]

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

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

Proposal

Updated 2026-11-26: Revised based on feedback from hoangzinh and comparison with other selection pages.

Confidence: Medium — supported by source inspection; runtime navigation and invitation round-trips have not been verified.

What is the root cause of that problem?

The “Expenses from” picker writes each tentative selection into the shared workflow draft before Save. Back removes unconfirmed invitees but retains changes involving existing workspace members. The parent editor reads that same draft, so it displays the canceled selection.

This is draft leakage, not evidence of server-side autosaving. Saving the parent workflow afterward can persist those unintended changes.

Code evidence

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

Keep tentative selections local and commit them at the explicit Save/Next boundary.

  1. Initialize local selection from the current parent draft, including previously accepted edits—not the workflow’s original persisted members. Accommodate draft data arriving after mount without overwriting user interaction.
  2. Update only local state on toggles and select-all. Retain non-workspace invitees’ identity/display data locally so search or Onyx updates do not lose them. Derive selection-dependent warnings and validation from this tentative state.
  3. On Save/Next, publish the accepted members through the existing confirmation path. Preserve initial creation, normal nested editing, and fast-edit persistence behavior. Ordinary Back or route removal should not need a shared-member rollback because toggles never changed the parent draft.
  4. Treat the invitation-message detour separately: publish the shared members and invitation draft required by that screen before navigating. Distinguish successful confirmation from returning without inviting. If the user returns and then cancels the picker, discard only this session’s provisional handoff changes, preserving earlier accepted edits. Do not treat starting the handoff as irrevocable success, or undo invitations already confirmed. Preserve existing creation/fast-edit abandonment cleanup without treating every unmount as cancellation.
Existing patterns supporting this approach
Required regression coverage
  • Select/deselect existing members, then header Back or browser Back: parent members remain unchanged.
  • Verify toggles themselves do not mutate shared members or the invitation draft.
  • Save → reopen → change → cancel: retain the last accepted selection.
  • Normal nested Save updates the parent draft; final parent Save persists the workflow.
  • Select a non-member, open invitation message, return without inviting, then cancel: no provisional selection leaks.
  • Successful invitation handoff, initial creation, and fast-edit Save/cancel retain their existing behavior.
  • Search/personal-details updates retain tentative invitees and existing selection warnings still work.

Verify web navigation lifecycle during implementation; source inspection alone does not establish whether the picker stays mounted throughout the invitation round-trip.

What alternative solutions did you explore? (Optional)

  • Eager shared writes plus snapshot rollback: not the preferred approach. It exposes tentative edits to the parent and requires cancellation bookkeeping for every exit. Keep any restoration narrowly scoped to provisional invitation handoff state, rather than using it for ordinary toggles.
  • Restore original persisted members or clear the whole workflow: risks losing previously accepted parent-draft changes.

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


view original run

MelvinBot avatar Nov 17 '26 19:11 MelvinBot

Proposal

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

When editing an existing approval workflow, changing the members on the "Expenses from" page and then pressing Back (without Save) still applies the new selection to the workflow.

What is the root cause of that problem?

In src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx, every toggle writes straight into the shared workflow draft. toggleMember → applySelection ends with:

setWorkspaceInviteMembersDraft(route.params.policyID, nextDraft);
setApprovalWorkflowMembers(workflowMembers);

So approvalWorkflow.members in Onyx (which ApprovalWorkflowEditor reads for the "Expenses from" field) changes on each tap, before Save.

On Back, goBack only calls dropUnconfirmedStagedMembers(), which filters out people who aren't in policy.employeeList yet. Existing workspace members that were added or removed stay in the draft, and the unmount cleanup only calls clearApprovalWorkflow() for the initial create flow or fast edit. That's why the edit page shows the unsaved selection, and saving the workflow afterward would persist it.

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

Give the page a cancel point for the regular edit flow (not initial creation, not fast edit, which already clear the draft):

  1. Add const membersOnEntryRef = useRef<Member[] | undefined>(undefined) and set it once, the first time approvalWorkflow?.members is available on mount.
  2. Add const didSaveRef = useRef(false) and set it to true at the start of nextStep (Save/Next), and when handing off to the invite-message page (the same place isHandingOffToInviteRef.current = true is set).
  3. In goBack, if !didSaveRef.current and we're in the edit flow, call setApprovalWorkflowMembers(membersOnEntryRef.current) and restore the invite draft to its entry value, instead of only dropping unconfirmed invitees.
  4. Do the same restore in the existing unmount cleanup effect, so browser/Android hardware back (which doesn't go through onBackButtonPress) behaves the same.

Using the snapshot from page entry (not the server's members) means that if the user saved a selection, reopened the page and then backed out, they keep the last selection they saved into the parent draft.

What specific scenarios should we cover in automated tests?

In a UI test for DynamicWorkspaceWorkflowsApprovalsExpensesFromPage, with an edit-action approvalWorkflow draft:

  • Toggle an existing member on/off, press Back → approvalWorkflow.members equals the original list.
  • Toggle a member, press Save → draft has the new list.
  • Save, reopen, toggle again, Back → draft keeps the saved list from the first Save.
  • Initial creation and fast-edit flows still clear the draft on unmount as they do today.

What alternative solutions did you explore?

Keep the selection in local useState and only call setApprovalWorkflowMembers in nextStep. That's cleaner, but selectedMembers currently relies on the Onyx draft so non-policy invitees survive Onyx re-renders (see the comment in applySelection), so it's a larger change with more risk to the invite flow.

fitzyracing1 avatar Nov 17 '26 20:11 fitzyracing1

Proposal

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

When editing an existing approval workflow (or re-opening Expenses from from the workflow confirm screen), toggling members on DynamicWorkspaceWorkflowsApprovalsExpensesFromPage and pressing Back without tapping Save still keeps the modified member list in ONYXKEYS.APPROVAL_WORKFLOW.members on the parent screen.

What is the root cause of that problem?

In src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx, toggleMember -> applySelection writes every selection change straight to Onyx (setWorkspaceInviteMembersDraft and setApprovalWorkflowMembers) before the user confirms with Save / Next:

https://github.com/Expensify/App/blob/main/src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx#L502-L503

Meanwhile, goBack only invokes dropUnconfirmedStagedMembers(), which strips non-policy invitees (!policy?.employeeList?.[normalizeLogin(m.email)]) while leaving added/removed workspace members in ONYXKEYS.APPROVAL_WORKFLOW.members, and the unmount cleanup only calls clearApprovalWorkflow() when isInitialCreationFlow || isFastEdit.

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

Keep tentative member edits local to the picker until nextStep commits them, and guard the invite-message round-trip against cancellation:

  1. Stage selections in local component state instead of mutating shared Onyx on every tap:
    • Add draftMembers (useState<Member[] | undefined>) and draftInviteDraft (useState<Record<string, number> | undefined>) in DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.
    • Use const activeMembers = draftMembers ?? approvalWorkflow?.members; and const activeInviteDraft = draftInviteDraft ?? invitedEmailsToAccountIDsDraft; in usePersonalDetailsByLogins, selectedMembers, and nextStep. That way FastEditSaveTest cases that seed ONYXKEYS.APPROVAL_WORKFLOW.members before pressing Save work identically, and non-policy search selections still survive Onyx re-renders from searchInServer / personalDetails.
    • Update applySelection to update draftInviteDraft and draftMembers only (removing premature setWorkspaceInviteMembersDraft / setApprovalWorkflowMembers writes on toggle).
  2. Commit to Onyx only inside nextStep:
    • nextStep already calls setApprovalWorkflowMembers(allMembers) (and setWorkspaceInviteMembersDraft(...) when usersToInvite.length > 0). Only that confirmation path should write back to shared Onyx.
  3. Handle the WORKSPACE_INVITE_MESSAGE back-then-cancel edge case & entry snapshot:
    • Capture membersOnEntryRef (and inviteDraftOnEntryRef) once when approvalWorkflow?.members is first loaded.
    • Because nextStep writes allMembers to Onyx before navigating to DYNAMIC_ROUTES.WORKSPACE_INVITE_MESSAGE, track didCommitInviteHandoffRef and reset isHandingOffToInviteRef.current = false when focus returns (useIsFocused transition false -> true).
    • If the user backs out of the invite-message page back to Expenses from and then presses header Back or browser/hardware Back (unmount cleanup while !isHandingOffToInviteRef.current), restore membersOnEntryRef.current (for non-initial, non-fast-edit flows) and clear/restore the invite draft so canceled invite round-trips never leak earlier toggles either.

What specific scenarios should we cover in automated tests?

Extend tests/ui/ coverage (alongside DynamicWorkspaceWorkflowsApprovalsExpensesFromPageFastEditSaveTest.tsx) to verify:

  1. Opening DynamicWorkspaceWorkflowsApprovalsExpensesFromPage in edit mode (isFastEdit: false), toggling workspace members, and triggering onBackButtonPress or unmount (browser/hardware back) leaves ONYXKEYS.APPROVAL_WORKFLOW.members unchanged.
  2. Toggling members, pressing Save, reopening Expenses from, toggling again, and backing out preserves the members from step 1's Save (not the original persisted server list, and not the canceled toggles).
  3. Selecting a non-member + workspace member, pressing Save (handing off to invite-message), returning focus without inviting, and backing out restores the entry approvalWorkflow.members.
  4. Existing initial creation, fast-edit save, fast-edit discard on unmount, and fast-edit invite handoff tests continue to pass unchanged.

What alternative solutions did you explore?

Always writing to ONYXKEYS.APPROVAL_WORKFLOW.members inside applySelection and rolling back to membersOnEntryRef on goBack/unmount. That leaves two subtle rough edges:

  • On hardware/browser back, ApprovalWorkflowEditor on the underlying edit page renders during unmount before the async Onyx rollback completes, whereas keeping applySelection in local state means ONYXKEYS.APPROVAL_WORKFLOW.members is never dirtied at all during normal cancel.
  • Marking a single didSaveRef = true when handing off to WORKSPACE_INVITE_MESSAGE breaks rollback if the user navigates back from the invite screen and then cancels out of Expenses from. Keeping edits local until nextStep and clearing isHandingOffToInviteRef on refocus avoids both issues cleanly.

cocvn157 avatar Nov 18 '26 05:11 cocvn157

Proposal

What is the root cause of that problem?

The Expenses from picker writes tentative selections into the shared approval-workflow draft before the user confirms them.

In DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx, applySelection calls setApprovalWorkflowMembers and updates the invitation draft during selection. setApprovalWorkflowMembers merges members into Onyx; this is not itself a backend save.

The Back path removes unconfirmed non-workspace invitees but does not restore changes involving existing workspace members. Since ApprovalWorkflowEditor reads that same shared draft, canceled selections remain visible in the parent editor.

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

Keep tentative member selection local to the picker, initialized from the entry draft. Do not update shared workflow members on each toggle.

Apply the selection through the existing explicit Save/Next contract, preserving creation, normal editing and fast-edit behavior. Do not save the parent workflow prematurely.

Handle the invitation handoff explicitly: abandoning the flow must discard only changes staged by this picker, without deleting previously confirmed members or invitations.

Extend the existing picker UI tests to cover:

  • Selecting or removing existing members, then returning without Save.
  • Header Back and route removal.
  • Save, reopen, change and cancel.
  • Invitation handoff, return and cancellation.
  • Existing creation and fast-edit behavior.

The draft mutation is confirmed in source; backend autosaving and the complete reported flow have not been independently reproduced.

What alternative solutions did you explore? (Optional)

An entry snapshot with rollback is smaller, but exposes intermediate shared-state changes and requires careful navigation cleanup. A local tentative selection provides a clearer confirmation boundary. Clearing the entire workflow draft would risk losing valid parent-editor changes.

Vallejo1921 avatar Nov 18 '26 22:11 Vallejo1921

@hoangzinh Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

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

Proposal

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

In the Workflows approval editor, opening "Expenses from" for an existing workflow, picking different members, and then tapping Back changes the members shown in the editor even though Save was never tapped. The previously saved members should remain unchanged until the admin explicitly saves.

What is the root cause of that problem?

This is draft leakage in the picker, not a server-side autosave. Every consumer reads and writes one shared Onyx draft, APPROVAL_WORKFLOW, and the picker writes into it on every toggle:

  1. toggleMember in DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx calls applySelection on every tap, and applySelection calls setApprovalWorkflowMembers(workflowMembers) immediately. setApprovalWorkflowMembers (src/libs/actions/Workflow.ts) is just Onyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, {members, errors: null}), so the new selection lands in the shared draft before any Save.
  2. goBack only calls dropUnconfirmedStagedMembers, which removes non-policy members that were staged for invite but never confirmed. It does not undo the member change itself.
  3. The parent editor (ApprovalWorkflowEditor.tsx) renders its member pills straight from approvalWorkflow.members in the same draft, so it shows the changed members the moment the admin returns. A later Save on the parent would then persist the unintended change with updateApprovalWorkflow / updateApprovalWorkflowRules, using the edit page's own snapshot as the diff baseline.

So in the plain edit flow, Save (nextStep) and Back (goBack) are indistinguishable for members: both end with the draft holding the new selection. The same leak exists on the create Confirm page, which reads the same draft.

I checked the two alternative explanations and ruled them out: the MenuItem migration in PR #106776 did not touch this picker, the parent edit page, or the workflow editor, and its multi-select QA step concerns a different setup-field component; and nothing in this flow makes an API request on toggle, so no server-side autosave is involved.

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

Give the picker an explicit cancellation boundary: capture the member selection when the picker opens, and restore it when leaving without Save. Keep the changed selection only after Save.

src/pages/workspace/workflows/approvals/DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx (+55 lines, no other file changed):

  • Capture the entry selection once in entryMembersRef, the first time the draft has members. The anchor is the picker-entry selection, not originalMembers: a selection the parent already saved in an earlier round must survive a later cancel. Restoring originalMembers would undo that earlier save, since the edit page does not re-seed originalMembers when it resumes after a sub-page round-trip.
  • Restore the entry selection in goBack (header back button), and again in the unmount cleanup, which covers browser back and swipe back, both of which leave the page without calling goBack.
  • Skip the restore when the new selection is intentional: nextStep sets a didSaveRef flag, which covers Save in the edit flow, Next in the create flow, and the invite hand-off. The initial create step and the fast edit keep their existing behavior of discarding the whole draft on unmount.
  • Preserve the existing rule that an unconfirmed invitee never survives a back navigation: the restore filters the entry selection to policy members plus members still in the invite draft, using the latest values (kept in refs for the cleanup, which only sees the first render's closure).

Tests. New tests/ui/DynamicWorkspaceWorkflowsApprovalsExpensesFromPageBackCancelTest.tsx, 5 tests, all passing (4 fail on baseline, 5 pass with the fix):

  • Change members then press Back: the draft returns to the entry members.
  • Change members then leave without a Back press (browser back): the draft returns to the entry members.
  • Change members then press Save: the new members stay in the draft for the parent to save.
  • Save, reopen, change, Back: the last saved selection remains, not the original members.
  • An unconfirmed staged member in the entry selection is dropped when backing out.

Related suites still green: DynamicWorkspaceWorkflowsApprovalsExpensesFromPageTest, DynamicWorkspaceWorkflowsApprovalsExpensesFromPageFastEditSaveTest, and WorkspaceWorkflowsApprovalsEditPageTest (22 tests total).

What alternative solutions did you explore? (Optional)

  • Restore originalMembers on Back. Rejected: originalMembers is seeded once when the edit page first mounts and is not refreshed when the parent saves. Canceling a later edit would undo a selection the parent already saved.
  • Keep the selection in local state and write the draft only on Save. A bigger refactor: the selection list, the invite-draft sync, and both cross-workflow warnings all derive from the draft today. The snapshot-restore keeps the same behavior with a much smaller change.
  • Fix it in the parent edit page instead. Rejected: the leak is created in the picker, and the parent cannot tell a saved selection from a leaked one, since both live in the same draft. The picker is also the only place that knows when the session started.
  • Restore only in goBack, not in the unmount cleanup. Rejected: browser back and swipe back leave the page without calling goBack, so the leak would remain on those paths.

Verification notes. The fix is verified by the UI tests above, which render the real page against Onyx and drive the selection the way the list does. A real-device run of the Applause steps (create a workflow, reopen "Expense from", pick other members, tap Back, confirm the saved members are unchanged) is still worth doing before merge, since the tests run under jsdom. Lint and full typecheck could not be run to green on the prep VM: lint-changed timed out fetching origin/main and direct oxlint fails on the known environment breakage (the hosted-rules plugin cannot load through the symlinked node_modules); the full typecheck was OOM-killed three times, which is a machine limit, not a type error report. The targeted checks that could run are clean: cspell reports 0 issues on both changed files, esbuild parses both files, and the invite-draft value passed to the new helper is typed Record<string, number> | undefined, matching the helper's parameter, since OnyxEntry<T> is T | undefined in this codebase. Lint and typecheck should be re-run on a machine with enough memory before the PR is opened.

dankezo avatar Nov 21 '26 15:11 dankezo

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

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

@hoangzinh Still overdue 6 days?! Let's take care of this!

Sorry for the delay. Let me review this issue today

hoangzinh avatar Nov 25 '26 14:11 hoangzinh

@MelvinBot I'm not feeling strong with your solution. Can you check how we are handling in other pages?

hoangzinh avatar Nov 26 '26 10:11 hoangzinh

Yes—the closer comparisons support local selection until Save, rather than my earlier snapshot-and-rollback proposal.

Page Existing behavior
Merchant-rule Submitter Initializes local selection from the shared draft; toggles stay local, and Save updates the parent draft. Back only navigates. See useRuleConditionSelection.ts:25–43 and RuleConditionMultiSelectPage.tsx:95–148.
Category “Visible to” Member toggles update local selection; only Save applies the changes. See DynamicCategoryVisibleToPage.tsx:132–166.
Workspace invitations Selection stays local; Next publishes the invitation draft before navigating. See DynamicWorkspaceInvitePage.tsx:180–199.

The nearest counterexample is the workflow Approver picker, which writes directly to the workflow draft. However, selecting an approver immediately finishes that step—there is no separate Save. Its interaction contract is different: WorkspaceWorkflowsApprovalsApproverPage.tsx:164–237.

I would revise my recommendation:

  • Initialize tentative selection from the current parent draft, including previously accepted edits.
  • Keep member toggles and tentative invitees local.
  • Commit through explicit Save/Next, preserving existing creation and fast-edit behavior.
  • Publish the required shared state before the invitation-message handoff.

That avoids dirtying the parent draft during ordinary selection and needing asynchronous rollback on cancellation.

The invitation detour still needs explicit cancellation handling: it requires shared state, so local selection alone does not establish that returning from that screen and then canceling is safe.

This comparison is source-verified; I haven’t runtime-tested the navigation paths.


view run

MelvinBot avatar Nov 26 '26 11:11 MelvinBot

@MelvinBot update your original proposal please

hoangzinh avatar Nov 26 '26 14:11 hoangzinh

Updated the original proposal to recommend local selection until Save/Next, with supporting examples from other pages, explicit invitation-handoff handling, and regression coverage.


view run

MelvinBot avatar Nov 26 '26 15:11 MelvinBot

I think we can go with MelvinBot's proposal https://github.com/Expensify/App/issues/107156#issuecomment-6958707972

🎀👀🎀 C+ reviewed

hoangzinh avatar Nov 26 '26 15:11 hoangzinh

Triggered auto assignment to @mountiny, see https://stackoverflow.com/c/expensify/questions/7972 for more details.

Go ahead

mountiny avatar Nov 27 '26 04:11 mountiny

@MelvinBot implement this

hoangzinh avatar Nov 27 '26 08:11 hoangzinh