App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Workflows-First, Final approver is owner after owner remove the first approver member

Open applause-bot[bot] opened this issue 1 week ago • 12 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.53-2 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://test-management.browserstack.com/projects/2219752/test-runs/177082554/folder/57610124/41236922/4893941829?sort=-identifier Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Regression TC Execution Device used: Win 11/Chrome App Component: Workspace Settings

Action Performed:

Precondition: Create a control workspace and invite 2 employees

  1. Open https://staging.new.expensify.com
  2. Navigate to the workspace setting > Workflows > Approvals
  3. Set Default workflow: First approver: Employee, Final approver: Owner
  4. Navigate to Members tab
  5. Remove the employee approver
  6. Navigate back to Workflows Approvals observe default workflow

Expected Result:

Default workflow should display only Approver is Owner

Actual Result:

Default workflow displays First Approver: Owner and Final Approver: Owner

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/141d2f36-0005-4e63-8f0c-3792452b1e38

View all open jobs on GitHub

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

Upwork Automation - Do Not Edit

applause-bot[bot] avatar Nov 25 '26 14: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/1e797b93ada275105fa144add0bd79ba0acc15630b8d4bec6d27e5483ff184ab

applause-bot[bot] avatar Nov 25 '26 14:11 applause-bot[bot]

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

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

🤖 Web test steps verification results: ⚠️ partial

Verified on dev NewDot web that a Control workspace was created. Reproduction was blocked: submitting invitations for two employees returned to Members, but only the owner appeared.

Members after invitations, showing only the workspace owner
Step Status
Create a Control workspaceOverview confirmed the Control plan.
✅
Invite two employeesBoth appeared in invitation confirmation, but Members subsequently showed only the owner.
Members after invitations, showing only the workspace owner
❌
Configure employee first, owner finalBlocked because the invited employee was unavailable.
⚠️
Remove the employee approverBlocked because the employee was absent.
⚠️
Reopen Approvals and verify one ownerThe required configuration and removal were not reached.
⚠️
Check persistence after reloadThe duplicate state was not reached; the testing session also prohibited reload.
⚠️

⚠️ Preliminary analysis — low confidence in the write-side root cause. The code investigation rules out a simple “removed employee displays as owner” fallback, but does not establish which operation creates the duplicate.

Confirmed findings

  • The existing removal helper already transforms Employee → Owner into Owner by dropping the first approver. This behavior also exists in the reported release: WorkflowUtils.ts:900–911.
  • A stored Owner → Owner forwarding relationship would explain the screenshot: reconstruction deliberately retains the repeated approver to flag a circular chain: WorkflowUtils.ts:270–289.

Candidate mechanism Workflow reading supports rule-backed approvals, but the member-removal workflow save uses the legacy employee-list action. This is a source-of-truth mismatch worth investigating—not yet proof of this issue’s cause.

Supporting code

Next diagnostic step: capture approval rules and employee routing before removal and after each UpdateWorkspaceApproval and DeleteMembersFromWorkspace response. Identify which update first introduces the duplicate before choosing an App or backend fix. Display-only deduplication could hide circular routing and is not a verified solution.

Possibly related: Approvers removed in OldDot remain in NewDot workflows; a shared root cause is unconfirmed.


view run · view recording

MelvinBot avatar Nov 25 '26 14:11 MelvinBot

Proposal

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

After the workspace owner removes the member who is the First approver of the default workflow (First approver: Employee → Final approver: Owner), the default workflow shows First approver: Owner, Final approver: Owner instead of a single approver (Owner).

What is the root cause of that problem?

The Workflows page and the Members page read and write approval workflows from different sources.

Under the MULTIPLE_APPROVERS beta, a policy's workflows are read from and saved as approval workflow rules (shouldUseApprovalWorkflowRules), and the Workflows page builds the default workflow's chain from those rules with convertApprovalWorkflowRulesToWorkflows → buildApproverChainFromRules:

  • https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/libs/WorkflowUtils.ts#L1904-L1925
  • https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/hooks/useApprovalWorkflows.ts#L93-L94
  • https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/libs/WorkflowUtils.ts#L1837-L1871

Every other place that edits a workflow branches on shouldUseApprovalWorkflowRules and updates the rules (updateApprovalWorkflowRules / removeApprovalWorkflowRules):

  • Edit page: https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsEditPage.tsx#L146-L176
  • Fast edit: https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/libs/actions/Workflow.ts#L797-L812

But when a member who is an approver is removed from the Members page, removeUsers gets shouldUseApprovalWorkflowRules from useApprovalWorkflows and ignores it. It always calls the legacy employeeList actions (updateApprovalWorkflow / removeApprovalWorkflow):

  • https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/pages/workspace/WorkspaceMembersPage.tsx#L186
  • https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/pages/workspace/WorkspaceMembersPage.tsx#L328-L362

removeMembers only filters the old policy.rules.approvalRules (category/tag approver rules). It never touches the approval workflow rules either:

  • https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/libs/actions/Policy/Member.ts#L455-L456

So the default workflow's rules still hold the old chain ("submit → removed employee", "to removed employee → forward to Owner"). updateWorkflowDataOnApproverRemoval correctly works out the new chain [Owner], but only employeeList gets it. Once the removed employee is replaced by the Owner in that leftover chain, buildApproverChainFromRules walks Owner → (stale forward rule) → Owner. buildApproversFromRoutes keeps the repeated approver as a second, circular-flagged entry instead of dropping it:

  • https://github.com/Expensify/App/blob/e56cd75e126ad3fd66c0b0436415aa1d9b6e83eb/src/libs/WorkflowUtils.ts#L275-L283

That gives the First approver: Owner / Final approver: Owner shown in the video. On a policy that isn't on rules, the same removal works, because there the employeeList update is the source of truth.

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

In WorkspaceMembersPage removeUsers, follow the same pattern as the edit page and saveFastEditApprovalWorkflow:

  1. Read the policy's rules collection (useOnyx(ONYXKEYS.COLLECTION.RULE, {selector: policyRulesSelector}), as the edit page does).
  2. Keep computing the updated workflows with updateWorkflowDataOnApproverRemoval. When shouldUseApprovalWorkflowRules is true, save each one with updateApprovalWorkflowRules({approvalWorkflow: updated, initialApprovalWorkflow: original, policy, rules, defaultApprovalWorkflow}) instead of updateApprovalWorkflow. Save the workflows flagged removeApprovalWorkflow with removeApprovalWorkflowRules(...) instead of removeApprovalWorkflow. Keep the legacy calls in the else branch.
  3. Then call removeMembers as today.

That way the rules end up as the single [Owner] chain that updateWorkflowDataOnApproverRemoval already works out, and the Workflows page shows Approver: Owner. As a safeguard, the default workflow in updateWorkflowDataOnApproverRemoval (removedApproverIndex === 0) can also collapse a chain whose remaining approvers are all the owner into a single approver.

Add a unit test for WorkspaceMembersPage/removeUsers on a rules-based policy: removing the first approver of a [Employee → Owner] default workflow leaves the rules routing to the Owner only.

What alternative solutions did you explore? (Optional)

Fixing only the display, by collapsing duplicate consecutive approvers in buildApproverChainFromRules, would hide the symptom. The stale "forward to Owner" rule would still route reports, so the data has to be fixed where the member is removed.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01be5d412b545fdf18

akzkid avatar Nov 25 '26 14:11 akzkid

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

melvin-bot[bot] avatar Nov 25 '26 14:11 melvin-bot[bot]

Proposal

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

On a Control workspace where the default approval workflow is set to First approver: Employee and Final approver: Owner, removing that employee from the workspace causes the Workflows > Approvals page to display First Approver: Owner and Final Approver: Owner instead of a single approver (Approver: Owner).

What is the root cause of that problem?

Under the MULTIPLE_APPROVERS beta (shouldUseApprovalWorkflowRules === true), approval workflows are read from and saved as approval workflow rules in ONYXKEYS.COLLECTION.RULE (useApprovalWorkflows.ts#L93-L94), and the backend rejects legacy employeeList routing writes once a policy's approvals are rule-based (Workflow.ts#L551-L552).

While the approval editors branch on shouldUseApprovalWorkflowRules to save rules via SetApprovalWorkflow (WorkspaceWorkflowsApprovalsEditPage.tsx#L146-L153), both member-removal surfaces ignore shouldUseApprovalWorkflowRules and always call the legacy employeeList actions (updateApprovalWorkflow / removeApprovalWorkflow):

  1. Bulk / list removal (WorkspaceMembersPage.tsx): Destructures shouldUseApprovalWorkflowRules on line 186 but ignores it in removeUsers (WorkspaceMembersPage.tsx#L328-L362), always dispatching updateApprovalWorkflow / removeApprovalWorkflowAction.
  2. Single-member removal (WorkspaceMemberDetailsPage.tsx): removeUser (WorkspaceMemberDetailsPage.tsx#L356-L386) has the exact same bug — it never reads shouldUseApprovalWorkflowRules or rulesCollection from useApprovalWorkflows(policy) (line 226) and unconditionally dispatches the legacy employeeList actions.
  3. Rule-only approvers are missed by isPolicyApprover: Both removal handlers gate workflow updates on isPolicyApprover(policy, login) (WorkspaceMembersPage.tsx#L330-L338, WorkspaceMemberDetailsPage.tsx#L301, L361). However, isPolicyApprover (PolicyUtils/permissions.ts#L340-L347) only checks policy.approver and policy.employeeList (submitsTo, forwardsTo, overLimitForwardsTo), so any approver configured solely through approval workflow rules is skipped completely.
  4. Stale rules & bulk-removal clobbering: Because removeMembers only filters legacy category/tag policy.rules.approvalRules (Member.ts#L455-L456), the approval workflow rules (submit → Employee, to: Employee → forward to Owner) remain stale until DeleteMembersFromWorkspace runs and substitutes the removed approver with Owner (submit → Owner, to: Owner → forward to Owner). When convertApprovalWorkflowRulesToWorkflows → buildApproverChainFromRules → buildApproversFromRoutes walks that chain (WorkflowUtils.ts#L275-L283), it deliberately retains the repeated Owner flagged as circular, displaying First Approver: Owner and Final Approver: Owner. Additionally, calling updateApprovalWorkflowRules inside WorkspaceMembersPage's per-employee loop against a static rulesCollection snapshot would overwrite earlier diffs during multi-approver removal and still write the removed member's email into the new rule's from list.

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

Extract a shared helper in src/libs/actions/Workflow.ts (e.g., updateApprovalWorkflowsOnMemberRemoval) and call it from both WorkspaceMembersPage.tsx (removeUsers) and WorkspaceMemberDetailsPage.tsx (removeUser):

  1. Reuse rulesCollection already exposed by useApprovalWorkflows(policy): Both WorkspaceMembersPage and WorkspaceMemberDetailsPage already call useApprovalWorkflows(policy), which exposes shouldUseApprovalWorkflowRules and rulesCollection specifically so callers don't add a duplicate ONYXKEYS.COLLECTION.RULE subscription (useApprovalWorkflows.ts#L66-L67).
  2. Detect rule-based approvers accurately: Treat a removed member as an approver if isPolicyApprover(policy, login) or approvalWorkflows.some((workflow) => workflow.approvers.some((approver) => approver.email === login)). Apply the same check to isApprover in WorkspaceMemberDetailsPage.tsx#L301 so the approver-removal confirmation warning also triggers for rule-only approvers.
  3. Compute the final workflow transitions across all removed approvers before writing: Iterate updateWorkflowDataOnApproverRemoval across all removed approvers first (separating workflows flagged removeApprovalWorkflow from surviving workflows), rather than firing redundant writes on every iteration.
  4. Branch cleanly on shouldUseApprovalWorkflowRules:
    • When shouldUseApprovalWorkflowRules is true:
      • Strip the removed member emails from surviving workflows' members and drop them from existing rules via reconcileApprovalWorkflowRulesForRemove, so no saved rule still lists a deleted member in from.
      • Accumulate rule diffs sequentially against an updated currentRules map (via applyApprovalWorkflowRulesDiff) for removed workflows (returning their surviving members to the updated default workflow with buildReturnToDefaultWorkflowDiff) and updated workflows (buildApprovalWorkflowRulesForSave + reconcileApprovalWorkflowRulesForEdit), then dispatch one combined setApprovalWorkflowRules write plus updatePolicyDefaultApprover if the default workflow's first approver changed.
    • When shouldUseApprovalWorkflowRules is false: Keep the existing legacy removeApprovalWorkflow / updateApprovalWorkflow path.
  5. Continue calling removeMembers afterward as today.
  6. Add unit tests in tests/actions/WorkflowTest.ts covering:
    • Removing the first approver of a rule-based [Employee → Owner] default workflow produces a single [Owner] default workflow rule (no Owner → Owner forward rule, removed employee stripped from from, policy.approver updated to Owner).
    • Removing a rule-only approver (absent from policy.employeeList's submitsTo/forwardsTo) triggers the rules update cleanly.
    • Bulk-removing multiple approvers in a single action reconciles all affected rules in one consistent diff without stale-snapshot clobbering.

What alternative solutions did you explore? (Optional)

  • Deduplicating consecutive identical approvers inside buildApproversFromRoutes / buildApproverChainFromRules: Rejected because it would only mask the UI symptom while leaving the stale to: Owner → forward to Owner rule active in the backend, and would hide genuine circular routing chains that buildApproversFromRoutes intentionally flags for admins.
  • Calling updateApprovalWorkflowRules directly inside WorkspaceMembersPage's per-employee loop without updating WorkspaceMemberDetailsPage: Rejected because single-member removal from Member Details would remain broken, rule-only approvers would still be bypassed by isPolicyApprover, removed members would remain inside the saved rules' from list, and multi-approver bulk removals would diff against a stale rulesCollection snapshot.

danlopes18-ctrl avatar Nov 25 '26 14:11 danlopes18-ctrl

Proposal

What is the root cause of that problem?

The bug happens only when the workspace's workflows are stored as approval workflow rules (shouldUseApprovalWorkflowRules, useApprovalWorkflows.ts#L93-L94). Removing a member who is an approver does not update those rules.

Step by step:

  1. Saving the default workflow "Employee → Owner" writes 3 rules (WorkflowUtils.ts#L1314-L1340):
    • R1: on submit → forward to Employee
    • R2: to == Employee → forward to Owner
    • R3: to == Owner → approve
  2. On removal, removeUsers correctly computes the new chain [Owner] (WorkflowUtils.ts#L906-L912). But it always saves it with the legacy updateApprovalWorkflow / removeApprovalWorkflow, which write employeeList (WorkspaceMembersPage.tsx#L328-L362). It gets shouldUseApprovalWorkflowRules on L186 and never uses it. The backend refuses employeeList routing changes once a policy is rule-based (Workflow.ts#L566-L567), so R1–R3 stay unchanged. WorkspaceMemberDetailsPage removeUser has the same gap (WorkspaceMemberDetailsPage.tsx#L356-L386).
  3. DeleteMembersFromWorkspace then replaces the removed approver with the owner inside the rules: R1 → forward to Owner, and R2 becomes to == Owner → forward to Owner.
  4. buildApproverChainFromRules reads Owner's rules, matches R2 and follows it back to Owner (WorkflowUtils.ts#L1851-L1861). buildApproversFromRoutes keeps the repeated approver as a second, circular-flagged step (WorkflowUtils.ts#L275-L283). Result: First approver Owner, Final approver Owner.

Proof that step 3 is where the duplicate comes from (this answers the open question in the MelvinBot comment):

  • The App never writes a rule that forwards an approver to themselves. getApprovalWorkflowRoute skips an approver who already approved (WorkflowUtils.ts#L1049-L1052), so buildApprovalWorkflowRules cannot emit to == X → forward X.
  • UpdateWorkspaceApproval cannot change the rules (point 2). So the self-forward can only come from the server rewriting rules that still name the removed member.
  • Check: after the DeleteMembersFromWorkspace response, read the policy's rule_ Onyx keys. You will see to == Owner → ForwardTo Owner next to to == Owner → ApproveReport.

Missed case: the same stale rules are left when the approver leaves the workspace themselves. leaveWorkspace sends LeavePolicy with no workflow update at all (Policy.ts#L1774-L1920). The same applies to removal in OldDot and to workspaces that already show the duplicate (like the tester's). A fix on the Members page alone does not reach these.

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

1. Save approver removal to the rules (both member removal pages). Move the loop from removeUsers and removeUser into one action in Workflow.ts, for example updateApprovalWorkflowsOnApproverRemoval({policy, approvalWorkflows, removedEmails, ownerEmail, ownerDetails, rules, shouldUseApprovalWorkflowRules, currentUserLogin}):

  • Run updateWorkflowDataOnApproverRemoval for every removed email first. Then write each changed workflow once.
  • When shouldUseApprovalWorkflowRules is true: save updated workflows with updateApprovalWorkflowRules and removed ones with removeApprovalWorkflowRules. Fall back to the legacy call when removeApprovalWorkflowRules returns false, as the edit page does (WorkspaceWorkflowsApprovalsEditPage.tsx#L176-L181). Otherwise keep today's legacy calls.
  • Write the default workflow first, and pass the updated default as defaultApprovalWorkflow. Members of a removed workflow then join the new [Owner] rules, not the old ones.
  • Each rules write diffs against the rules it is given. Make updateApprovalWorkflowRules / removeApprovalWorkflowRules return the rules after their change, and pass that into the next call. Otherwise a second write diffs against the old snapshot and can write the stale R1/R2 back.
  • Find approvers from the workflows (approvalWorkflows.some(w => w.approvers.some(a => a.email === login))), not only isPolicyApprover. Rule saves do not put later approvers into employeeList.
  • Keep removed members in the default rules' from list. updateApprovalWorkflowRules does this on purpose so they get their workflow back if they rejoin (Workflow.ts#L474-L475).
  • Then call removeMembers as today. SetApprovalWorkflow is queued before DeleteMembersFromWorkspace, so no rule names the removed approver when the server runs.

2. Treat a self-forward as the end of the chain (covers LeavePolicy, OldDot and already-broken workspaces). In buildApproverChainFromRules → getNextApproverEmail (WorkflowUtils.ts#L1851-L1861), if the matching rule forwards to the same approver (to == X → forward X), return undefined. This shows what really happens: a report never goes to the same approver twice (WorkflowUtils.ts#L276-L277). A real loop through another approver (A → B → A) is still flagged. The next save from the editor writes clean rules.

Pseudo-code:

next = forward approver of matching rule
if next == email: return undefined   // forwarding to yourself is not another step
return next

3. Tests

  • Rules policy, default workflow Employee → Owner, remove Employee from Members: SetApprovalWorkflow is sent before DeleteMembersFromWorkspace, and the resulting rules give [Owner].
  • Same through the Member details page.
  • Remove two approvers at once: the second rules write is based on the rules after the first.
  • convertApprovalWorkflowRulesToWorkflows with R1 → Owner, R2 to == Owner → Owner, R3 to == Owner → approve: default workflow has one approver, Owner.
  • Owner → A → B → A still shows the circular flag.

What alternative solutions did you explore? (Optional)

  • Only change 2 (display): it fixes what the page shows, but the next removal keeps writing stale rules. Rejected as the only fix.
  • Only change 1 on the Members page: leaves the Member details page, LeavePolicy, OldDot removal and already-broken workspaces showing the duplicate. Rejected.
  • Remove removed members from every rule's from list: changes existing behavior (they lose their workflow if they rejoin) and is not needed for this bug. Rejected.
  • Also worth a look by the internal engineer: the server substitution on DeleteMembersFromWorkspace / LeavePolicy could drop a hop that forwards to the same approver. This would fix the data for every client.

mattlsyyssll avatar Nov 26 '26 07:11 mattlsyyssll

Proposal

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

On a Control workspace where the default approval workflow is configured with a two-step approval chain (e.g., First approver: Employee -> Final approver: Owner), removing that employee from the workspace via the Members page causes the Workflows > Approvals page to display "First approver: Owner, Final approver: Owner" (two redundant steps both assigned to the owner) instead of collapsing into a single default approval step ("Approver: Owner").

What is the root cause of that problem?

There are two compounding defects across workflow removal mutation and rule chain traversal:

  1. Member removal ignores shouldUseApprovalWorkflowRules and calls legacy workflow actions:

    • In src/pages/workspace/WorkspaceMembersPage.tsx:328-358 (removeUsers) and src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx:356-386 (removeUser), when removing members who are approvers:
      if (workflow?.removeApprovalWorkflow) {
          const {removeApprovalWorkflow, ...updatedWorkflow} = workflow;
          removeApprovalWorkflowAction(updatedWorkflow, policy);
      } else {
          updateApprovalWorkflow(workflow, [], [], policy);
      }
      
    • Notice that both removal handlers unconditionally invoke the legacy actions updateApprovalWorkflow and removeApprovalWorkflowAction, which only write to employeeList.
    • On workspaces where shouldUseApprovalWorkflowRules(policy) is active (e.g. multiple approvers beta or rule-based workspaces), the backend rejects employeeList routing updates once a policy uses rules (src/libs/actions/Workflow.ts:566-567). Consequently, the client never syncs updated approval rules before member removal.
    • When removeMembers subsequently sends DeleteMembersFromWorkspace, the backend automatically replaces any references to the removed employee with the workspace owner. In a two-step chain where the employee forwarded to the owner:
      • Rule 1 (submission) becomes: submit -> forward to Owner
      • Rule 2 (previously to == Employee -> forward to Owner) becomes: to == Owner -> forward to Owner (a self-forwarding rule)
      • Rule 3 becomes: to == Owner -> approve
  2. buildApproverChainFromRules does not treat a self-forwarding rule as terminal:

    • In src/libs/WorkflowUtils.ts:1845-1856 (buildApproverChainFromRules -> getNextApproverEmail):
      const matchingRule = approverRules.find((rule) => evaluateApprovalWorkflowRule(rule, {submitterEmail: submitter, currentApproverEmail: email, reportTotal: amount}));
      return matchingRule ? getForwardApprover(matchingRule) : undefined;
      
    • In the legacy counterpart getEmployeeNextApproverEmail (src/libs/WorkflowUtils.ts:157-159), the codebase explicitly ends approval traversal when someone forwards to themselves (isOverLimit && nextEmail === employee?.email).
    • However, buildApproverChainFromRules lacked this check. When it matches to == Owner -> forward to Owner, getForwardApprover(matchingRule) returns Owner.
    • buildApproversFromRoutes (src/libs/WorkflowUtils.ts:276-281) encounters Owner a second time, marks isCircularReference: true, and retains the repeated approver as a second step in the chain: [Owner, Owner (circular)].
    • Downstream, ApprovalWorkflowSection.tsx:89-94 sees approvers.length > 1 and labels the two steps: First approver: Owner and Final approver: Owner.

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

We implement a robust, comprehensive two-tier resolution:

Tier 1: Terminate self-forwarding rules in buildApproverChainFromRules (Safeguard for all entrypoints)

In src/libs/WorkflowUtils.ts:1853-1856, if a matching rule forwards to the same approver (nextApprover === email), return undefined. A report never routes to the same approver twice, so forwarding to oneself terminates the chain rather than adding a redundant step:

const matchingRule = approverRules.find((rule) => evaluateApprovalWorkflowRule(rule, {submitterEmail: submitter, currentApproverEmail: email, reportTotal: amount}));
const nextApprover = matchingRule ? getForwardApprover(matchingRule) : undefined;
if (nextApprover === email) {
    return undefined;
}
return nextApprover;
--- a/src/libs/WorkflowUtils.ts
+++ b/src/libs/WorkflowUtils.ts
@@ -1852,7 +1852,11 @@ function buildApproverChainFromRules({
 
             // No matching rule means the backend approves the report here
             const matchingRule = approverRules.find((rule) => evaluateApprovalWorkflowRule(rule, {submitterEmail: submitter, currentApproverEmail: email, reportTotal: amount}));
-            return matchingRule ? getForwardApprover(matchingRule) : undefined;
+            const nextApprover = matchingRule ? getForwardApprover(matchingRule) : undefined;
+            if (nextApprover === email) {
+                return undefined;
+            }
+            return nextApprover;
         },
         getApprovalLimit: (email) => (getApproverRules(email).length === 0 ? getEmployeeApprovalLimit(employees[email]) : undefined),
         canRouteTo: () => true,

Tier 2: Save updated approval rules on approver removal in WorkspaceMembersPage.tsx and WorkspaceMemberDetailsPage.tsx

When shouldUseApprovalWorkflowRules is active:

  • Use updateApprovalWorkflowRules and removeApprovalWorkflowRules from @userActions/Workflow instead of legacy updateApprovalWorkflow / removeApprovalWorkflowAction.
  • This ensures clean rules without orphaned hops are written directly to Onyx and the backend before removeMembers executes.

What alternative solutions did you explore? (Optional)?

  • Only updating WorkspaceMembersPage.tsx: Rejected because members can also leave on their own (leaveWorkspace), be removed from WorkspaceMemberDetailsPage.tsx, or have broken server state from previous removals. Adding the self-forwarding termination check in buildApproverChainFromRules immediately cures all existing and future occurrences across all platforms.
  • Filtering identical adjacent approvers in ApprovalWorkflowSection.tsx: Rejected because presentational components should not have to normalize malformed chains. The fix belongs in the workflow traversal logic (WorkflowUtils.ts).

What are the regression risks and how will you mitigate them?

  • Multi-step circular reference detection: Multi-party circular loops (e.g. A -> B -> A) are completely preserved because nextApprover !== email for both hops. isCircularReference in buildApproversFromRoutes continues to catch and flag real loops with the circular reference warning.
  • Non-rule based workflows: Workspaces using legacy employeeList already use getEmployeeNextApproverEmail, which already handles isOverLimitToThemselves.
  • Mitigation: Verified with comprehensive unit test coverage in tests/unit/WorkflowUtilsTest.ts.

Automated Tests?

Add the following unit tests in tests/unit/WorkflowUtilsTest.ts:

it('collapses self-forwarding owner rule into a single approver step', () => {
    const ownerEmail = '[email protected]';
    const rules: OnyxCollection<ApprovalRule> = {
        rule_1: {
            id: 'rule_1',
            approver: ownerEmail,
            action: CONST.APPROVAL_WORKFLOW.ACTION.FORWARD,
            forwardsTo: ownerEmail, // self-forwarding rule resulting from member removal
            filters: {
                [CONST.SEARCH.SYNTAX_FILTER_KEYS.TO]: {
                    operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL,
                    right: ownerEmail,
                },
            },
        },
    };

    const approvers = buildApproverChainFromRules({
        submitter: '[email protected]',
        rules,
        employees: {[ownerEmail]: {email: ownerEmail, role: CONST.POLICY.ROLE.ADMIN}},
        personalDetailsByEmail: {[ownerEmail]: {login: ownerEmail, displayName: 'Owner'}},
    });

    expect(approvers).toHaveLength(1);
    expect(approvers.at(0)?.email).toBe(ownerEmail);
    expect(approvers.at(0)?.isCircularReference).toBe(false);
});

it('still detects real multi-party circular references (A -> B -> A)', () => {
    const approverA = '[email protected]';
    const approverB = '[email protected]';
    const rules: OnyxCollection<ApprovalRule> = {
        rule_a: {
            id: 'rule_a',
            approver: approverA,
            action: CONST.APPROVAL_WORKFLOW.ACTION.FORWARD,
            forwardsTo: approverB,
            filters: {
                [CONST.SEARCH.SYNTAX_FILTER_KEYS.TO]: {
                    operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL,
                    right: approverA,
                },
            },
        },
        rule_b: {
            id: 'rule_b',
            approver: approverB,
            action: CONST.APPROVAL_WORKFLOW.ACTION.FORWARD,
            forwardsTo: approverA,
            filters: {
                [CONST.SEARCH.SYNTAX_FILTER_KEYS.TO]: {
                    operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL,
                    right: approverB,
                },
            },
        },
    };

    const approvers = buildApproverChainFromRules({
        submitter: '[email protected]',
        rules,
        employees: {
            [approverA]: {email: approverA, role: CONST.POLICY.ROLE.ADMIN},
            [approverB]: {email: approverB, role: CONST.POLICY.ROLE.ADMIN},
        },
        personalDetailsByEmail: {},
    });

    expect(approvers).toHaveLength(2);
    expect(approvers.at(1)?.isCircularReference).toBe(true);
});

Manual Test Steps?

  1. Open a Control workspace where the user is an admin/owner and invite an employee.
  2. Navigate to More Features > Workflows > Approvals.
  3. Configure the default workflow with two steps: First approver: Employee, Final approver: Owner.
  4. Navigate to More Features > Members.
  5. Select and remove the employee approver from the workspace.
  6. Navigate back to Workflows > Approvals.
  7. Verify that the default workflow card cleanly displays a single step ("Approver: Owner") instead of "First approver: Owner, Final approver: Owner".
  8. Edit the workflow and verify that adding new approvers and configuring multi-step approval works normally.

Contributor Details?

  • GitHub Username: @kevinjosh10
  • Email: [email protected]
  • Upwork Profile: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 26 '26 08:11 kevinjosh10

@gijoe0295 Eep! 4 days overdue now. Issues have feelings too...

@MelvinBot Investigate and post proposal for this one please

gijoe0295 avatar Dec 02 '26 07:12 gijoe0295

Investigation result

⚠️ The App save-path defect is confirmed, but the exact cause of the duplicate owner remains unverified. I cannot yet recommend the existing proposals as a verified solution.

What is the root cause of that problem?

Both member-removal screens calculate the shortened approval chain correctly, but save it using legacy routing actions—even when approval workflows are read from rules.

However, stale rules alone do not explain the reported result: unchanged Employee → Owner rules still reconstruct Employee → Owner, not Owner → Owner. The existing proposals assume the server substitutes the removed employee with the owner; that mutation has not been demonstrated.

Verified code evidence

What changes do you think we should make?

First capture the missing transition: compare approval rules, legacy routing fields, and the default approver before removal and after each UpdateWorkspaceApproval and DeleteMembersFromWorkspace response.

That determines whether rules-aware saving in both App removal paths prevents this issue, or whether an internal server-side correction is required. Production verification was blocked because this run had no log-query access; backend repositories were also inaccessible.

What alternative solutions did you explore?

I would not accept blanket self-forward suppression without further evidence. Repeated approvers are intentionally retained to expose circular configuration, and an existing test explicitly expects a self-forward to appear twice: WorkflowUtilsTest.ts:420–431.

Six focused existing unit tests passed, supporting the removal and circular-reference behavior—not proving the reported server transition.

Blocker to a verified proposal: identify the first response or optimistic update that changes the clean chain into duplicate-owner routing.


view run

MelvinBot avatar Dec 02 '26 07:12 MelvinBot