From 0da19f9ff01bfdc0b15ab2697335fa6327a348d4 Mon Sep 17 00:00:00 2001 From: Nicolas Bonet Date: Mon, 1 Jun 2026 16:48:33 -0500 Subject: [PATCH 1/4] Enhance agent deletion process to optimistically mark agent as pending delete in associated policies --- src/libs/WorkflowUtils.ts | 1 + src/libs/actions/Agent.ts | 30 ++++++++- src/pages/settings/Agents/EditAgentPage.tsx | 5 +- tests/unit/AgentActionTest.ts | 74 +++++++++++++++++++++ 4 files changed, 107 insertions(+), 3 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 559eae99da31..91acae480d08 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -77,6 +77,7 @@ function calculateApprovers({employees, firstEmail, personalDetailsByEmail}: Get approvalLimit: employee.approvalLimit, overLimitForwardsTo: employee.overLimitForwardsTo, overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(employee.overLimitForwardsTo, personalDetailsByEmail), + pendingAction: employee.pendingAction, }); // If we've already seen this approver, break to prevent infinite loop diff --git a/src/libs/actions/Agent.ts b/src/libs/actions/Agent.ts index c9c625c0721d..088e5c9b2155 100644 --- a/src/libs/actions/Agent.ts +++ b/src/libs/actions/Agent.ts @@ -1,4 +1,5 @@ import Onyx from 'react-native-onyx'; +import type {OnyxCollection, OnyxCollectionInputValue} from 'react-native-onyx'; import {read, write} from '@libs/API'; import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; import {resolveAvatarURI} from '@libs/Avatars/PresetAvatarCatalog'; @@ -10,6 +11,8 @@ import type {AvatarSource} from '@libs/UserAvatarUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; +import type {Policy} from '@src/types/onyx'; +import type PolicyEmployee from '@src/types/onyx/PolicyEmployee'; import type {AnyOnyxUpdate} from '@src/types/onyx/Request'; function openAgentsPage() { @@ -315,7 +318,7 @@ function updateAgentAvatar( write(WRITE_COMMANDS.UPDATE_AGENT_AVATAR, params, {optimisticData, successData, failureData}); } -function deleteAgent(accountID: number) { +function deleteAgent(accountID: number, agentEmail?: string, allPolicies?: OnyxCollection) { const optimisticData: AnyOnyxUpdate[] = [ { onyxMethod: Onyx.METHOD.MERGE, @@ -348,6 +351,31 @@ function deleteAgent(accountID: number) { }, ]; + // Mark the agent's row pending-delete on every policy it belongs to so workflow cards render + // the agent's approver row with strikethrough/RBR while DELETE_AGENT is in flight. + if (agentEmail && allPolicies) { + for (const policy of Object.values(allPolicies)) { + if (!policy?.id || !policy.employeeList?.[agentEmail]) { + continue; + } + const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policy.id}` as const; + const optimisticEmployees: OnyxCollectionInputValue = { + [agentEmail]: {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}, + }; + const successEmployees: OnyxCollectionInputValue = {[agentEmail]: null}; + const failureEmployees: OnyxCollectionInputValue = { + [agentEmail]: { + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + errors: getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage'), + }, + }; + + optimisticData.push({onyxMethod: Onyx.METHOD.MERGE, key: policyKey, value: {employeeList: optimisticEmployees}}); + successData.push({onyxMethod: Onyx.METHOD.MERGE, key: policyKey, value: {employeeList: successEmployees}}); + failureData.push({onyxMethod: Onyx.METHOD.MERGE, key: policyKey, value: {employeeList: failureEmployees}}); + } + } + write(WRITE_COMMANDS.DELETE_AGENT, {agentAccountID: accountID}, {optimisticData, successData, failureData}); Navigation.goBack(ROUTES.SETTINGS_AGENTS); } diff --git a/src/pages/settings/Agents/EditAgentPage.tsx b/src/pages/settings/Agents/EditAgentPage.tsx index 6dc1e4444ea9..4be95425cd77 100644 --- a/src/pages/settings/Agents/EditAgentPage.tsx +++ b/src/pages/settings/Agents/EditAgentPage.tsx @@ -35,12 +35,14 @@ function EditAgentPage({route}: EditAgentPageProps) { const accountID = route.params.accountID; const [agent, agentMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${accountID}`); const [personalDetails, personalDetailsMetadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]}); + const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); const {showConfirmModal} = useConfirmModal(); const chatWithAgent = useChatWithAgent(); const switchToDelegator = useSwitchToDelegator(); const isOnyxLoaded = agentMetadata.status === 'loaded' && personalDetailsMetadata.status === 'loaded'; const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails; + const agentLogin = personalDetails?.login ?? ''; const handleBackPress = () => Navigation.goBack(); const handleEditAvatarPress = () => Navigation.navigate(ROUTES.SETTINGS_AGENTS_EDIT_AVATAR.getRoute(accountID)); const handleEditNamePress = () => Navigation.navigate(ROUTES.SETTINGS_AGENTS_EDIT_NAME.getRoute(accountID)); @@ -57,9 +59,8 @@ function EditAgentPage({route}: EditAgentPageProps) { if (result.action !== ModalActions.CONFIRM) { return; } - deleteAgent(accountID); + deleteAgent(accountID, agentLogin, allPolicies); }; - const agentLogin = personalDetails?.login ?? ''; const isPendingAddOrDelete = agent?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || agent?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE; const areActionsDisabled = isPendingAddOrDelete || accountID <= 0 || !agentLogin; const handleChatPress = () => { diff --git a/tests/unit/AgentActionTest.ts b/tests/unit/AgentActionTest.ts index e24547edf7fb..f9421142b369 100644 --- a/tests/unit/AgentActionTest.ts +++ b/tests/unit/AgentActionTest.ts @@ -467,6 +467,80 @@ describe('deleteAgent', () => { expect(mockGoBack).toHaveBeenCalledTimes(1); }); + + describe('cascade to policies containing the agent', () => { + const AGENT_EMAIL = 'agent@expensifail.com'; + const OTHER_EMAIL = 'submitter@expensifail.com'; + const OWNER_EMAIL = 'owner@expensifail.com'; + const POLICY_ID = 'POLICY1'; + const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`; + + const buildPolicies = () => ({ + [policyKey]: { + id: POLICY_ID, + owner: OWNER_EMAIL, + approver: OWNER_EMAIL, + employeeList: { + [AGENT_EMAIL]: {email: AGENT_EMAIL, submitsTo: AGENT_EMAIL, forwardsTo: OWNER_EMAIL}, + [OTHER_EMAIL]: {email: OTHER_EMAIL, submitsTo: AGENT_EMAIL}, + }, + }, + }); + + it('marks agent employeeList entry as pending DELETE optimistically', () => { + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + + const {optimisticData} = getWriteOptions(); + const policyUpdate = optimisticData.find((u) => u.key === policyKey); + const employees = (policyUpdate?.value as {employeeList: Record})?.employeeList; + expect(employees?.[AGENT_EMAIL]).toEqual({pendingAction: 'delete'}); + }); + + it('leaves other employees and approver chains untouched so the workflow card still renders', () => { + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + + const {optimisticData} = getWriteOptions(); + const policyUpdate = optimisticData.find((u) => u.key === policyKey); + const value = policyUpdate?.value as {employeeList: Record; approver?: string; rules?: unknown}; + expect(value?.employeeList[OTHER_EMAIL]).toBeUndefined(); + expect(value?.approver).toBeUndefined(); + expect(value?.rules).toBeUndefined(); + }); + + it('nulls the agent employeeList entry on success', () => { + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + + const {successData} = getWriteOptions(); + const policyUpdate = successData.find((u) => u.key === policyKey); + const employees = (policyUpdate?.value as {employeeList: Record})?.employeeList; + expect(employees?.[AGENT_EMAIL]).toBeNull(); + }); + + it('restores agent pendingAction with errors on failure', () => { + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + + const {failureData} = getWriteOptions(); + const policyUpdate = failureData.find((u) => u.key === policyKey); + const agentEntry = (policyUpdate?.value as {employeeList: Record})?.employeeList[AGENT_EMAIL]; + expect(agentEntry?.pendingAction).toBe('delete'); + expect(agentEntry?.errors).toBeTruthy(); + }); + + it('skips policies that do not contain the agent', () => { + const policies = { + [policyKey]: { + id: POLICY_ID, + owner: OWNER_EMAIL, + approver: OWNER_EMAIL, + employeeList: {[OWNER_EMAIL]: {email: OWNER_EMAIL}}, + }, + }; + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, policies as never); + + const {optimisticData} = getWriteOptions(); + expect(optimisticData.find((u) => u.key === policyKey)).toBeUndefined(); + }); + }); }); describe('clearAgentUpdateError', () => { From 1e55186840bb28fc6c3e10461a851695b7d45845 Mon Sep 17 00:00:00 2001 From: Nicolas Bonet Date: Fri, 5 Jun 2026 15:06:06 -0500 Subject: [PATCH 2/4] Add regression test for DELETE pendingAction on approver Co-Authored-By: Claude Opus 4.7 (1M context) --- tests/unit/WorkflowUtilsTest.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/unit/WorkflowUtilsTest.ts b/tests/unit/WorkflowUtilsTest.ts index 046a1cfced57..132ac40c4683 100644 --- a/tests/unit/WorkflowUtilsTest.ts +++ b/tests/unit/WorkflowUtilsTest.ts @@ -209,6 +209,24 @@ describe('WorkflowUtils', () => { ]); }); + it('Should surface a DELETE pendingAction from the employee onto the approver row so the workflow card renders with strikethrough', () => { + const employees: PolicyEmployeeList = { + '1@example.com': { + email: '1@example.com', + forwardsTo: '2@example.com', + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + }, + '2@example.com': { + email: '2@example.com', + forwardsTo: undefined, + }, + }; + + const approvers = calculateApprovers({employees, firstEmail: '1@example.com', personalDetailsByEmail}); + + expect(approvers).toEqual([buildApprover(1, {forwardsTo: '2@example.com', pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}), buildApprover(2)]); + }); + it('Should include approvalLimit and overLimitForwardsTo in approver objects', () => { const employees: PolicyEmployeeList = { '1@example.com': { From bf67f2e99b0a448c7c6cd7ad1e6464feefbf5bf5 Mon Sep 17 00:00:00 2001 From: Nicolas Bonet Date: Tue, 9 Jun 2026 09:57:15 -0500 Subject: [PATCH 3/4] Address Neil's review comments - Propagate employee.errors onto Approver so failed DELETE_AGENT surfaces an RBR on the approver row instead of hiding it. - Rename deleteAgent's agentEmail param to agentLogin (login may be a phone number, not always an email). - Build deleteAgent test policies with createRandomPolicy so we assert Policy at build time instead of `as never`. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/libs/WorkflowUtils.ts | 1 + src/libs/actions/Agent.ts | 12 ++++++------ tests/unit/AgentActionTest.ts | 19 ++++++++++++------- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/libs/WorkflowUtils.ts b/src/libs/WorkflowUtils.ts index 91acae480d08..fe355b114ad9 100644 --- a/src/libs/WorkflowUtils.ts +++ b/src/libs/WorkflowUtils.ts @@ -78,6 +78,7 @@ function calculateApprovers({employees, firstEmail, personalDetailsByEmail}: Get overLimitForwardsTo: employee.overLimitForwardsTo, overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(employee.overLimitForwardsTo, personalDetailsByEmail), pendingAction: employee.pendingAction, + errors: employee.errors, }); // If we've already seen this approver, break to prevent infinite loop diff --git a/src/libs/actions/Agent.ts b/src/libs/actions/Agent.ts index 088e5c9b2155..3e492adc4834 100644 --- a/src/libs/actions/Agent.ts +++ b/src/libs/actions/Agent.ts @@ -318,7 +318,7 @@ function updateAgentAvatar( write(WRITE_COMMANDS.UPDATE_AGENT_AVATAR, params, {optimisticData, successData, failureData}); } -function deleteAgent(accountID: number, agentEmail?: string, allPolicies?: OnyxCollection) { +function deleteAgent(accountID: number, agentLogin?: string, allPolicies?: OnyxCollection) { const optimisticData: AnyOnyxUpdate[] = [ { onyxMethod: Onyx.METHOD.MERGE, @@ -353,18 +353,18 @@ function deleteAgent(accountID: number, agentEmail?: string, allPolicies?: OnyxC // Mark the agent's row pending-delete on every policy it belongs to so workflow cards render // the agent's approver row with strikethrough/RBR while DELETE_AGENT is in flight. - if (agentEmail && allPolicies) { + if (agentLogin && allPolicies) { for (const policy of Object.values(allPolicies)) { - if (!policy?.id || !policy.employeeList?.[agentEmail]) { + if (!policy?.id || !policy.employeeList?.[agentLogin]) { continue; } const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policy.id}` as const; const optimisticEmployees: OnyxCollectionInputValue = { - [agentEmail]: {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}, + [agentLogin]: {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}, }; - const successEmployees: OnyxCollectionInputValue = {[agentEmail]: null}; + const successEmployees: OnyxCollectionInputValue = {[agentLogin]: null}; const failureEmployees: OnyxCollectionInputValue = { - [agentEmail]: { + [agentLogin]: { pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, errors: getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage'), }, diff --git a/tests/unit/AgentActionTest.ts b/tests/unit/AgentActionTest.ts index f9421142b369..6b5c0847442d 100644 --- a/tests/unit/AgentActionTest.ts +++ b/tests/unit/AgentActionTest.ts @@ -1,11 +1,14 @@ import Onyx from 'react-native-onyx'; +import type {OnyxCollection} from 'react-native-onyx'; import {write} from '@libs/API'; import {WRITE_COMMANDS} from '@libs/API/types'; import Navigation from '@libs/Navigation/Navigation'; import {clearAgentAvatarUpdateError, clearAgentUpdateError, createAgent, deleteAgent, updateAgentAvatar, updateAgentName, updateAgentPrompt} from '@userActions/Agent'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {Policy} from '@src/types/onyx'; import type {AnyOnyxUpdate} from '@src/types/onyx/Request'; +import createRandomPolicy from '../utils/collections/policies'; jest.mock('@libs/API'); jest.mock('@libs/Navigation/Navigation', () => ({navigate: jest.fn(), goBack: jest.fn()})); @@ -475,8 +478,9 @@ describe('deleteAgent', () => { const POLICY_ID = 'POLICY1'; const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`; - const buildPolicies = () => ({ + const buildPolicies = (): OnyxCollection => ({ [policyKey]: { + ...createRandomPolicy(1), id: POLICY_ID, owner: OWNER_EMAIL, approver: OWNER_EMAIL, @@ -488,7 +492,7 @@ describe('deleteAgent', () => { }); it('marks agent employeeList entry as pending DELETE optimistically', () => { - deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies()); const {optimisticData} = getWriteOptions(); const policyUpdate = optimisticData.find((u) => u.key === policyKey); @@ -497,7 +501,7 @@ describe('deleteAgent', () => { }); it('leaves other employees and approver chains untouched so the workflow card still renders', () => { - deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies()); const {optimisticData} = getWriteOptions(); const policyUpdate = optimisticData.find((u) => u.key === policyKey); @@ -508,7 +512,7 @@ describe('deleteAgent', () => { }); it('nulls the agent employeeList entry on success', () => { - deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies()); const {successData} = getWriteOptions(); const policyUpdate = successData.find((u) => u.key === policyKey); @@ -517,7 +521,7 @@ describe('deleteAgent', () => { }); it('restores agent pendingAction with errors on failure', () => { - deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies() as never); + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies()); const {failureData} = getWriteOptions(); const policyUpdate = failureData.find((u) => u.key === policyKey); @@ -527,15 +531,16 @@ describe('deleteAgent', () => { }); it('skips policies that do not contain the agent', () => { - const policies = { + const policies: OnyxCollection = { [policyKey]: { + ...createRandomPolicy(1), id: POLICY_ID, owner: OWNER_EMAIL, approver: OWNER_EMAIL, employeeList: {[OWNER_EMAIL]: {email: OWNER_EMAIL}}, }, }; - deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, policies as never); + deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, policies); const {optimisticData} = getWriteOptions(); expect(optimisticData.find((u) => u.key === policyKey)).toBeUndefined(); From 074d983b26c348d2761efadeee1cd2b6fe334bbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Bonet=20=28via=20MelvinBot=29?= Date: Tue, 9 Jun 2026 20:12:27 +0000 Subject: [PATCH 4/4] Update eslint-seatbelt baseline for AgentActionTest type assertions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Nicolás Bonet --- config/eslint/eslint.seatbelt.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/eslint/eslint.seatbelt.tsv b/config/eslint/eslint.seatbelt.tsv index 39cecb0e33ad..92056d915018 100644 --- a/config/eslint/eslint.seatbelt.tsv +++ b/config/eslint/eslint.seatbelt.tsv @@ -1735,7 +1735,7 @@ "../../tests/ui/hooks/useHtmlPasteTest/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 10 "../../tests/unit/APITest.ts" "@typescript-eslint/no-unsafe-type-assertion" 74 "../../tests/unit/AddExistingExpenseSearchTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 6 -"../../tests/unit/AgentActionTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 57 +"../../tests/unit/AgentActionTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 61 "../../tests/unit/AgentZeroStatusContextTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 5 "../../tests/unit/AvatarButtonWithIconTest.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../tests/unit/AvatarUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 2