From d73a815bb8d3cdca1d703f78783b3e03589b00d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Tue, 7 Jul 2026 10:20:54 +0000 Subject: [PATCH 01/14] Open the DM with the new agent right after creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- src/pages/settings/Agents/AddAgentPage.tsx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index ff0eb09dd6c0..520b22d33f8c 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -7,6 +7,7 @@ import ScreenWrapper from '@components/ScreenWrapper'; import Text from '@components/Text'; import TextInput from '@components/TextInput'; +import useChatWithAgent from '@hooks/useChatWithAgent'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; @@ -47,6 +48,7 @@ function AddAgentPage({route}: AddAgentPageProps) { const {windowWidth, windowHeight} = useWindowDimensions(); const shouldUseScrollableLayout = useIsInLandscapeMode() || (isMobile() && windowWidth > windowHeight); const {displayName} = useCurrentUserPersonalDetails(); + const chatWithAgent = useChatWithAgent(); const defaultAgentName = displayName ? translate('addAgentPage.defaultAgentName', displayName) : undefined; const defaultPrompt = translate('addAgentPage.defaultPrompt'); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Pencil']); @@ -98,15 +100,13 @@ function AddAgentPage({route}: AddAgentPageProps) { const pendingFile = pendingFileRef.current; // Pure optimistic flow — no waiting on the server, online or offline. `createAgent` - // returns the optimistic accountID it wrote into Onyx so we can hand it to the next - // screen and let it render the agent with opacity until CREATE_AGENT resolves. - if (pendingFile) { - createAgent(firstName, prompt, undefined, pendingFile.file, pendingFile.uri, policyID); - } else { - createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID); - } + // returns the optimistic accountID it wrote into Onyx so we can open the DM with the + // new agent right away and let it render with opacity until CREATE_AGENT resolves. + const {optimisticAccountID} = pendingFile + ? createAgent(firstName, prompt, undefined, pendingFile.file, pendingFile.uri, policyID) + : createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID); - Navigation.goBack(); + chatWithAgent(optimisticAccountID); }; return ( From 70efad1d663d1cd6e41d763f0859d22741ea8b6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Tue, 7 Jul 2026 10:26:14 +0000 Subject: [PATCH 02/14] Update AddAgentPage tests for opening the agent DM after creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- tests/unit/pages/settings/AddAgentPageTest.tsx | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index a98ddb358ba5..534320ff5b9d 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -24,6 +24,10 @@ jest.mock('@hooks/useLocalize', () => jest.fn(() => ({translate: mockTranslate}) jest.mock('@hooks/useCurrentUserPersonalDetails', () => jest.fn(() => ({}))); +const mockChatWithAgent = jest.fn(); + +jest.mock('@hooks/useChatWithAgent', () => jest.fn(() => mockChatWithAgent)); + jest.mock('@hooks/useTheme', () => jest.fn(() => ({textLight: '#fff'}))); jest.mock('@hooks/useThemeStyles', () => @@ -235,7 +239,7 @@ describe('AddAgentPage', () => { mockFormOnSubmit = undefined; }); - it('goes back when policyID is absent in route params', () => { + it('opens the DM with the new agent when policyID is absent in route params', () => { render( { mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); - expect(mockGoBack).toHaveBeenCalledTimes(1); - expect(mockNavigate).not.toHaveBeenCalled(); + expect(mockChatWithAgent).toHaveBeenCalledTimes(1); + expect(mockChatWithAgent).toHaveBeenCalledWith(-123456); + expect(mockGoBack).not.toHaveBeenCalled(); }); - it('goes back when policyID is present without navigating to a workflow editor', () => { + it('opens the DM with the new agent when policyID is present', () => { render( { mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); - expect(mockGoBack).toHaveBeenCalledTimes(1); - expect(mockNavigate).not.toHaveBeenCalled(); + expect(mockChatWithAgent).toHaveBeenCalledTimes(1); + expect(mockChatWithAgent).toHaveBeenCalledWith(-123456); + expect(mockGoBack).not.toHaveBeenCalled(); }); }); }); From c83ef991899c01a6e19bc3024395049e8e9cf8c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Tue, 7 Jul 2026 11:18:02 +0000 Subject: [PATCH 03/14] Dismiss the add-agent modal before opening the new agent DM MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- src/hooks/useChatWithAgent.ts | 6 ++++-- src/libs/actions/Report/index.ts | 7 ++++--- src/pages/settings/Agents/AddAgentPage.tsx | 4 +++- tests/unit/pages/settings/AddAgentPageTest.tsx | 4 ++-- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/hooks/useChatWithAgent.ts b/src/hooks/useChatWithAgent.ts index c9d305cb0f59..e3a9deec2565 100644 --- a/src/hooks/useChatWithAgent.ts +++ b/src/hooks/useChatWithAgent.ts @@ -10,6 +10,8 @@ import useOnyx from './useOnyx'; /** * Encapsulates the data fetching and navigation logic for opening a DM chat with an agent. * Returns a function that, given an accountID, navigates to the DM report with that agent. + * Pass `shouldDismissModal` when the caller lives on the RHP/modal stack (e.g. the add-agent + * flow) so the modal is dismissed before navigating and the new DM is actually shown. */ function useChatWithAgent() { const currentUserPersonalDetails = useCurrentUserPersonalDetails(); @@ -18,8 +20,8 @@ function useChatWithAgent() { const [betas] = useOnyx(ONYXKEYS.BETAS); const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); - const chatWithAgent = (accountID: number) => { - navigateToAndOpenReportWithAccountIDs([accountID], currentUserPersonalDetails.accountID, introSelected, isSelfTourViewed, betas, personalDetails); + const chatWithAgent = (accountID: number, {shouldDismissModal = false}: {shouldDismissModal?: boolean} = {}) => { + navigateToAndOpenReportWithAccountIDs([accountID], currentUserPersonalDetails.accountID, introSelected, isSelfTourViewed, betas, personalDetails, false, shouldDismissModal); }; return chatWithAgent; diff --git a/src/libs/actions/Report/index.ts b/src/libs/actions/Report/index.ts index a05ceb1827e4..f80cee774308 100644 --- a/src/libs/actions/Report/index.ts +++ b/src/libs/actions/Report/index.ts @@ -2412,6 +2412,7 @@ function navigateToAndOpenReportWithAccountIDs( betas: OnyxEntry, personalDetails: OnyxEntry, shouldRevalidateExistingChat = false, + shouldDismissModal = false, ) { const participants = participantAccountIDs.map((accountID): ParticipantInfo => { return { @@ -2441,7 +2442,7 @@ function navigateToAndOpenReportWithAccountIDs( betas, }); - navigateToReport(fallbackChat.reportID, {shouldDismissModal: false}); + navigateToReport(fallbackChat.reportID, {shouldDismissModal}); }; if (!chat || isReportNotFound(chat)) { @@ -2450,7 +2451,7 @@ function navigateToAndOpenReportWithAccountIDs( } if (!shouldRevalidateExistingChat) { - navigateToReport(chat.reportID, {shouldDismissModal: false}); + navigateToReport(chat.reportID, {shouldDismissModal}); return; } @@ -2476,7 +2477,7 @@ function navigateToAndOpenReportWithAccountIDs( // Re-open existing chats to re-validate server-side access and refresh stale local state. openReport({reportID: chat.reportID, introSelected, isSelfTourViewed, betas}); - navigateToReport(chat.reportID, {shouldDismissModal: false}); + navigateToReport(chat.reportID, {shouldDismissModal}); } /** diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index 520b22d33f8c..8cb2bb35b923 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -106,7 +106,9 @@ function AddAgentPage({route}: AddAgentPageProps) { ? createAgent(firstName, prompt, undefined, pendingFile.file, pendingFile.uri, policyID) : createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID); - chatWithAgent(optimisticAccountID); + // This page lives on the RHP/modal stack, so dismiss the modal before navigating — + // otherwise the modal stays on top and the new DM is never shown to the user. + chatWithAgent(optimisticAccountID, {shouldDismissModal: true}); }; return ( diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 534320ff5b9d..47eda5c03675 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -250,7 +250,7 @@ describe('AddAgentPage', () => { mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); - expect(mockChatWithAgent).toHaveBeenCalledWith(-123456); + expect(mockChatWithAgent).toHaveBeenCalledWith(-123456, {shouldDismissModal: true}); expect(mockGoBack).not.toHaveBeenCalled(); }); @@ -265,7 +265,7 @@ describe('AddAgentPage', () => { mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); - expect(mockChatWithAgent).toHaveBeenCalledWith(-123456); + expect(mockChatWithAgent).toHaveBeenCalledWith(-123456, {shouldDismissModal: true}); expect(mockGoBack).not.toHaveBeenCalled(); }); }); From 15834192bc635424f2a4b3c4c628da3f48354cc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Tue, 7 Jul 2026 13:12:17 +0000 Subject: [PATCH 04/14] Open agent DM using the real server-assigned accountID after CreateAgent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- src/libs/actions/Agent.ts | 39 ++++++++++++++++++- src/pages/settings/Agents/AddAgentPage.tsx | 15 +++---- .../unit/pages/settings/AddAgentPageTest.tsx | 25 ++++++++---- 3 files changed, 63 insertions(+), 16 deletions(-) diff --git a/src/libs/actions/Agent.ts b/src/libs/actions/Agent.ts index 8dd3a1fd0956..b95345459c36 100644 --- a/src/libs/actions/Agent.ts +++ b/src/libs/actions/Agent.ts @@ -101,7 +101,44 @@ function createAgent( {optimisticData, successData, failureData}, ); - return {optimisticAccountID, avatarURI}; + return {optimisticAccountID, avatarURI, createdAgentAccountID: waitForCreatedAgentAccountID(optimisticAccountID)}; +} + +/** + * Resolves with the real, server-assigned accountID of the agent just created by `createAgent`. + * + * Account IDs (unlike report IDs) can't be generated optimistically on the client, so the optimistic + * accountID above is never the agent's real identity — CREATE_AGENT nulls it out on success and writes + * the agent under a real accountID instead. We therefore watch the agent-prompt collection and resolve + * with the first agent that appears after this call that isn't the optimistic placeholder or an agent + * that already existed. Callers use it to open the DM with the newly created agent once it's real. + */ +function waitForCreatedAgentAccountID(optimisticAccountID: number): Promise { + return new Promise((resolve) => { + let knownAgentAccountIDs: Set | undefined; + const connection = Onyx.connectWithoutView({ + key: ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT, + waitForCollectionCallback: true, + callback: (agentPrompts) => { + const currentAgentAccountIDs = Object.keys(agentPrompts ?? {}).map((key) => Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length))); + + // The first callback runs before CREATE_AGENT can respond, so it establishes the baseline + // (agents that already existed plus the optimistic placeholder). The real agent is whatever shows up after. + if (!knownAgentAccountIDs) { + knownAgentAccountIDs = new Set(currentAgentAccountIDs); + return; + } + + const createdAgentAccountID = currentAgentAccountIDs.find((accountID) => accountID !== optimisticAccountID && !knownAgentAccountIDs?.has(accountID)); + if (createdAgentAccountID === undefined) { + return; + } + + Onyx.disconnect(connection); + resolve(createdAgentAccountID); + }, + }); + }); } function clearAgentError(optimisticAccountID: number) { diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index 8cb2bb35b923..6e8b5adcd9d2 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -99,16 +99,17 @@ function AddAgentPage({route}: AddAgentPageProps) { const prompt = values[INPUT_IDS.PROMPT].trim(); const pendingFile = pendingFileRef.current; - // Pure optimistic flow — no waiting on the server, online or offline. `createAgent` - // returns the optimistic accountID it wrote into Onyx so we can open the DM with the - // new agent right away and let it render with opacity until CREATE_AGENT resolves. - const {optimisticAccountID} = pendingFile + // `createAgent` writes the agent optimistically (works offline) and returns a promise that + // resolves with the agent's real, server-assigned accountID once CREATE_AGENT responds. + const {createdAgentAccountID} = pendingFile ? createAgent(firstName, prompt, undefined, pendingFile.file, pendingFile.uri, policyID) : createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID); - // This page lives on the RHP/modal stack, so dismiss the modal before navigating — - // otherwise the modal stays on top and the new DM is never shown to the user. - chatWithAgent(optimisticAccountID, {shouldDismissModal: true}); + // Leave the add-agent modal right away so the optimistic agent shows in the Agents list + // (this also keeps the flow usable offline). We can't open the DM with the optimistic + // accountID — account IDs are server-assigned — so open it as soon as the real one resolves. + Navigation.goBack(); + createdAgentAccountID.then((accountID) => chatWithAgent(accountID, {shouldDismissModal: true})); }; return ( diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 47eda5c03675..2db7c059c677 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -1,4 +1,4 @@ -import {render} from '@testing-library/react-native'; +import {render, waitFor} from '@testing-library/react-native'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; @@ -9,15 +9,19 @@ import type {SettingsNavigatorParamList} from '@libs/Navigation/types'; import AddAgentPage from '@pages/settings/Agents/AddAgentPage'; import {setInitialPresetID, setNavigationToken} from '@pages/settings/Agents/pendingAgentAvatarStore'; +import {createAgent} from '@userActions/Agent'; + import ROUTES from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; import React from 'react'; jest.mock('@userActions/Agent', () => ({ - createAgent: jest.fn(() => ({optimisticAccountID: -123456, avatarURI: undefined})), + createAgent: jest.fn(), })); +const mockCreateAgent = jest.mocked(createAgent); + const mockTranslate = jest.fn().mockImplementation((key: string, param?: string) => (param !== undefined ? `${key}(${param})` : key)); jest.mock('@hooks/useLocalize', () => jest.fn(() => ({translate: mockTranslate}))); @@ -131,6 +135,7 @@ describe('AddAgentPage', () => { beforeEach(() => { jest.clearAllMocks(); mockUseCurrentUserPersonalDetails.mockReturnValue({accountID: 0}); + mockCreateAgent.mockReturnValue({optimisticAccountID: -123456, avatarURI: undefined, createdAgentAccountID: Promise.resolve(22542959)}); mockAvatarOnPress = undefined; }); @@ -239,7 +244,7 @@ describe('AddAgentPage', () => { mockFormOnSubmit = undefined; }); - it('opens the DM with the new agent when policyID is absent in route params', () => { + it('dismisses the modal and opens the DM with the real accountID once it resolves when policyID is absent', async () => { render( { mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + // The modal is dismissed immediately so the optimistic agent shows in the Agents list. + expect(mockGoBack).toHaveBeenCalledTimes(1); + + // The DM opens with the agent's real, server-assigned accountID — never the optimistic one. + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(22542959, {shouldDismissModal: true})); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); - expect(mockChatWithAgent).toHaveBeenCalledWith(-123456, {shouldDismissModal: true}); - expect(mockGoBack).not.toHaveBeenCalled(); }); - it('opens the DM with the new agent when policyID is present', () => { + it('dismisses the modal and opens the DM with the real accountID once it resolves when policyID is present', async () => { render( { mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + expect(mockGoBack).toHaveBeenCalledTimes(1); + + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(22542959, {shouldDismissModal: true})); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); - expect(mockChatWithAgent).toHaveBeenCalledWith(-123456, {shouldDismissModal: true}); - expect(mockGoBack).not.toHaveBeenCalled(); }); }); }); From 0e020c24cd8d8fe3b49527fd6b34145d50f55834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Tue, 7 Jul 2026 19:26:07 +0000 Subject: [PATCH 05/14] Only resolve created-agent DM with a real server agent, not another optimistic placeholder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- src/libs/actions/Agent.ts | 22 +++++++++++++++++----- tests/unit/AgentActionTest.ts | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/src/libs/actions/Agent.ts b/src/libs/actions/Agent.ts index b95345459c36..dae2dd8e9e25 100644 --- a/src/libs/actions/Agent.ts +++ b/src/libs/actions/Agent.ts @@ -120,22 +120,34 @@ function waitForCreatedAgentAccountID(optimisticAccountID: number): Promise { - const currentAgentAccountIDs = Object.keys(agentPrompts ?? {}).map((key) => Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length))); + const entries = Object.entries(agentPrompts ?? {}); // The first callback runs before CREATE_AGENT can respond, so it establishes the baseline // (agents that already existed plus the optimistic placeholder). The real agent is whatever shows up after. if (!knownAgentAccountIDs) { - knownAgentAccountIDs = new Set(currentAgentAccountIDs); + knownAgentAccountIDs = new Set(entries.map(([key]) => Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length)))); return; } - const createdAgentAccountID = currentAgentAccountIDs.find((accountID) => accountID !== optimisticAccountID && !knownAgentAccountIDs?.has(accountID)); - if (createdAgentAccountID === undefined) { + const createdAgentEntry = entries.find(([key, agentPrompt]) => { + const accountID = Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length)); + + // Skip agents that already existed at baseline and this request's own optimistic placeholder. + if (accountID === optimisticAccountID || knownAgentAccountIDs?.has(accountID)) { + return false; + } + + // Skip any *other* agent still pending creation — e.g. a second agent the user created before this + // one's CREATE_AGENT responded (its optimistic accountID is also new and not our optimistic ID). + // Only a real, server-created agent has no ADD pending action, and that's the accountID we can open a DM with. + return agentPrompt?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD; + }); + if (createdAgentEntry === undefined) { return; } Onyx.disconnect(connection); - resolve(createdAgentAccountID); + resolve(Number(createdAgentEntry[0].slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length))); }, }); }); diff --git a/tests/unit/AgentActionTest.ts b/tests/unit/AgentActionTest.ts index 18b90279d991..75a40474a949 100644 --- a/tests/unit/AgentActionTest.ts +++ b/tests/unit/AgentActionTest.ts @@ -15,6 +15,7 @@ import Onyx from 'react-native-onyx'; import createRandomPolicy from '../utils/collections/policies'; import createMock from '../utils/createMock'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; jest.mock('@libs/API'); jest.mock('@libs/Navigation/Navigation', () => ({navigate: jest.fn(), goBack: jest.fn()})); @@ -255,6 +256,40 @@ describe('createAgent', () => { }); expect(promptValue?.errors).toBeTruthy(); }); + + it('resolves createdAgentAccountID with the real server agent, ignoring other pending optimistic agents', async () => { + await Onyx.clear(); + + const {optimisticAccountID, createdAgentAccountID} = createAgent('Bot', 'My prompt'); + + // Let waitForCreatedAgentAccountID establish its baseline from the (empty) collection. + await waitForBatchedUpdates(); + + let resolvedAccountID: number | undefined; + void createdAgentAccountID.then((id) => { + resolvedAccountID = id; + }); + + // A second agent the user creates before this one's CREATE_AGENT responds shows up as a *new* + // optimistic prompt entry (pendingAction ADD). It must NOT be mistaken for the created agent. + const otherOptimisticAccountID = optimisticAccountID + 1; + await Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${otherOptimisticAccountID}`, { + prompt: 'Another prompt', + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, + }); + await waitForBatchedUpdates(); + + // Still unresolved — the only new entry is another optimistic placeholder. + expect(resolvedAccountID).toBeUndefined(); + + // The real, server-created agent arrives without an ADD pending action. + const realAccountID = 22542959; + await Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${realAccountID}`, {prompt: 'My prompt'}); + await waitForBatchedUpdates(); + + await expect(createdAgentAccountID).resolves.toBe(realAccountID); + expect(resolvedAccountID).toBe(realAccountID); + }); }); const TEST_ACCOUNT_ID = 42; From ba746a5abbd16f3bb72c697c260931030c95d2bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Tue, 7 Jul 2026 19:46:53 +0000 Subject: [PATCH 06/14] Only auto-open agent DM on reconnect if still on the Agents list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- src/pages/settings/Agents/AddAgentPage.tsx | 12 +++- .../unit/pages/settings/AddAgentPageTest.tsx | 57 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index 6e8b5adcd9d2..3918f0a50b07 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -22,6 +22,7 @@ import type {CustomRNImageManipulatorResult} from '@libs/cropOrRotateImage/types import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {SettingsNavigatorParamList} from '@libs/Navigation/types'; +import {getIsOffline} from '@libs/NetworkState'; import type {AvatarSource} from '@libs/UserAvatarUtils'; import {createAgent} from '@userActions/Agent'; @@ -108,8 +109,17 @@ function AddAgentPage({route}: AddAgentPageProps) { // Leave the add-agent modal right away so the optimistic agent shows in the Agents list // (this also keeps the flow usable offline). We can't open the DM with the optimistic // accountID — account IDs are server-assigned — so open it as soon as the real one resolves. + const wasOffline = getIsOffline(); Navigation.goBack(); - createdAgentAccountID.then((accountID) => chatWithAgent(accountID, {shouldDismissModal: true})); + createdAgentAccountID.then((accountID) => { + // When created offline, the promise only resolves once we're back online — by which point the user + // may have navigated somewhere else entirely. Only pull them into the DM if they created it online, + // or they're still on the Agents list, so we don't yank them out of an unrelated screen on reconnect. + if (wasOffline && !Navigation.isActiveRoute(ROUTES.SETTINGS_AGENTS)) { + return; + } + chatWithAgent(accountID, {shouldDismissModal: true}); + }); }; return ( diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 2db7c059c677..148c241a5fac 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -5,6 +5,7 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails' import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import type {SettingsNavigatorParamList} from '@libs/Navigation/types'; +import {getIsOffline} from '@libs/NetworkState'; import AddAgentPage from '@pages/settings/Agents/AddAgentPage'; import {setInitialPresetID, setNavigationToken} from '@pages/settings/Agents/pendingAgentAvatarStore'; @@ -16,6 +17,8 @@ import type SCREENS from '@src/SCREENS'; import React from 'react'; +import waitForBatchedUpdates from '../../../utils/waitForBatchedUpdates'; + jest.mock('@userActions/Agent', () => ({ createAgent: jest.fn(), })); @@ -56,8 +59,19 @@ jest.mock('@hooks/useOnyx', () => jest.fn(() => [undefined, {status: 'loaded'}]) jest.mock('@libs/Navigation/Navigation', () => ({ goBack: jest.fn(), navigate: jest.fn(), + isActiveRoute: jest.fn(() => true), })); +jest.mock('@libs/NetworkState', () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const actual = jest.requireActual('@libs/NetworkState'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return { + ...actual, + getIsOffline: jest.fn(() => false), + }; +}); + jest.mock('@react-navigation/native', () => { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const actual = jest.requireActual('@react-navigation/native'); @@ -123,6 +137,8 @@ const mockSetInitialPresetID = jest.mocked(setInitialPresetID); const mockSetNavigationToken = jest.mocked(setNavigationToken); const mockNavigate = jest.mocked(Navigation.navigate); const mockGoBack = jest.mocked(Navigation.goBack); +const mockIsActiveRoute = jest.mocked(Navigation.isActiveRoute); +const mockGetIsOffline = jest.mocked(getIsOffline); const mockUseCurrentUserPersonalDetails = jest.mocked(useCurrentUserPersonalDetails); type AddAgentRouteProp = PlatformStackRouteProp; @@ -136,6 +152,8 @@ describe('AddAgentPage', () => { jest.clearAllMocks(); mockUseCurrentUserPersonalDetails.mockReturnValue({accountID: 0}); mockCreateAgent.mockReturnValue({optimisticAccountID: -123456, avatarURI: undefined, createdAgentAccountID: Promise.resolve(22542959)}); + mockGetIsOffline.mockReturnValue(false); + mockIsActiveRoute.mockReturnValue(true); mockAvatarOnPress = undefined; }); @@ -277,5 +295,44 @@ describe('AddAgentPage', () => { await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(22542959, {shouldDismissModal: true})); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); }); + + it('does not open the DM on reconnect when created offline and the user has navigated away from the Agents list', async () => { + mockGetIsOffline.mockReturnValue(true); + mockIsActiveRoute.mockReturnValue(false); + + render( + , + ); + + mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + + expect(mockGoBack).toHaveBeenCalledTimes(1); + + // The real accountID resolves (reconnect), but the user is no longer on the Agents list, so we stay put. + await waitForBatchedUpdates(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + }); + + it('opens the DM on reconnect when created offline but the user is still on the Agents list', async () => { + mockGetIsOffline.mockReturnValue(true); + mockIsActiveRoute.mockReturnValue(true); + + render( + , + ); + + mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + + expect(mockGoBack).toHaveBeenCalledTimes(1); + + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(22542959, {shouldDismissModal: true})); + expect(mockIsActiveRoute).toHaveBeenCalledWith(ROUTES.SETTINGS_AGENTS); + }); }); }); From 944e1e82e5e64b1f8cbc1b9bc142f5bf08bba179 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Tue, 7 Jul 2026 20:18:15 +0000 Subject: [PATCH 07/14] Don't auto-open the agent DM for offline-created agents on reconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- src/pages/settings/Agents/AddAgentPage.tsx | 18 +++++++------ .../unit/pages/settings/AddAgentPageTest.tsx | 27 +++---------------- 2 files changed, 14 insertions(+), 31 deletions(-) diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index 3918f0a50b07..9dde3afb3453 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -107,17 +107,19 @@ function AddAgentPage({route}: AddAgentPageProps) { : createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID); // Leave the add-agent modal right away so the optimistic agent shows in the Agents list - // (this also keeps the flow usable offline). We can't open the DM with the optimistic - // accountID — account IDs are server-assigned — so open it as soon as the real one resolves. + // (this also keeps the flow usable offline). const wasOffline = getIsOffline(); Navigation.goBack(); + + // Opening the DM is the immediate continuation of tapping "Create" — but it needs the real, + // server-assigned accountID, which doesn't exist until CREATE_AGENT responds. When created offline + // that response only arrives after reconnect, long after the user has moved on, so auto-opening the + // DM then would yank them out of whatever they're doing. Only continue into the DM for agents created + // online; offline creations just leave the new agent in the list for the user to open when they choose. + if (wasOffline) { + return; + } createdAgentAccountID.then((accountID) => { - // When created offline, the promise only resolves once we're back online — by which point the user - // may have navigated somewhere else entirely. Only pull them into the DM if they created it online, - // or they're still on the Agents list, so we don't yank them out of an unrelated screen on reconnect. - if (wasOffline && !Navigation.isActiveRoute(ROUTES.SETTINGS_AGENTS)) { - return; - } chatWithAgent(accountID, {shouldDismissModal: true}); }); }; diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 148c241a5fac..fd0514465034 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -296,9 +296,9 @@ describe('AddAgentPage', () => { expect(mockChatWithAgent).toHaveBeenCalledTimes(1); }); - it('does not open the DM on reconnect when created offline and the user has navigated away from the Agents list', async () => { + it('does not open the DM when created offline, even if the user is still on the Agents list', async () => { mockGetIsOffline.mockReturnValue(true); - mockIsActiveRoute.mockReturnValue(false); + mockIsActiveRoute.mockReturnValue(true); render( { mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + // We return to the Agents list but never open the DM — the real accountID only arrives on reconnect, + // long after the user has moved on, so we don't yank them into the DM. expect(mockGoBack).toHaveBeenCalledTimes(1); - - // The real accountID resolves (reconnect), but the user is no longer on the Agents list, so we stay put. await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); }); - - it('opens the DM on reconnect when created offline but the user is still on the Agents list', async () => { - mockGetIsOffline.mockReturnValue(true); - mockIsActiveRoute.mockReturnValue(true); - - render( - , - ); - - mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); - - expect(mockGoBack).toHaveBeenCalledTimes(1); - - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(22542959, {shouldDismissModal: true})); - expect(mockIsActiveRoute).toHaveBeenCalledWith(ROUTES.SETTINGS_AGENTS); - }); }); }); From 67da023ccfc8dff3e0551d34b2e1acb68629487f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Wed, 8 Jul 2026 09:10:20 +0000 Subject: [PATCH 08/14] Fix no-void ESLint error: capture and await the created-agent promise instead of voiding it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- tests/unit/AgentActionTest.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/unit/AgentActionTest.ts b/tests/unit/AgentActionTest.ts index 75a40474a949..fc5389197f79 100644 --- a/tests/unit/AgentActionTest.ts +++ b/tests/unit/AgentActionTest.ts @@ -266,7 +266,7 @@ describe('createAgent', () => { await waitForBatchedUpdates(); let resolvedAccountID: number | undefined; - void createdAgentAccountID.then((id) => { + const settledCreatedAgentAccountID = createdAgentAccountID.then((id) => { resolvedAccountID = id; }); @@ -286,6 +286,7 @@ describe('createAgent', () => { const realAccountID = 22542959; await Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${realAccountID}`, {prompt: 'My prompt'}); await waitForBatchedUpdates(); + await settledCreatedAgentAccountID; await expect(createdAgentAccountID).resolves.toBe(realAccountID); expect(resolvedAccountID).toBe(realAccountID); From 37ffb1ee72c1a76d046b49b420d98da74f0ff113 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Wed, 8 Jul 2026 09:50:10 +0000 Subject: [PATCH 09/14] Fix no-unsafe-type-assertion in AddAgentPageTest: build route via createMock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- tests/unit/pages/settings/AddAgentPageTest.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index fd0514465034..43325c7c5708 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -13,10 +13,11 @@ import {setInitialPresetID, setNavigationToken} from '@pages/settings/Agents/pen import {createAgent} from '@userActions/Agent'; import ROUTES from '@src/ROUTES'; -import type SCREENS from '@src/SCREENS'; +import SCREENS from '@src/SCREENS'; import React from 'react'; +import createMock from '../../../utils/createMock'; import waitForBatchedUpdates from '../../../utils/waitForBatchedUpdates'; jest.mock('@userActions/Agent', () => ({ @@ -144,7 +145,7 @@ const mockUseCurrentUserPersonalDetails = jest.mocked(useCurrentUserPersonalDeta type AddAgentRouteProp = PlatformStackRouteProp; function makeRoute(params: AddAgentRouteProp['params'] = {}): AddAgentRouteProp { - return {name: '', key: '', params} as unknown as AddAgentRouteProp; + return createMock({name: SCREENS.SETTINGS.AGENTS.ADD, key: '', params}); } describe('AddAgentPage', () => { From 066f0903c7c6dada33e21b69b4b0287b3c0b988d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski=20=28via=20MelvinBot=29?= Date: Wed, 8 Jul 2026 11:54:49 +0000 Subject: [PATCH 10/14] Grandfather pre-existing no-deprecated Icon-size violations in eslint-seatbelt baseline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michał Jasikowski --- config/eslint/eslint.seatbelt.tsv | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/config/eslint/eslint.seatbelt.tsv b/config/eslint/eslint.seatbelt.tsv index 4bcd11676429..f689394506aa 100644 --- a/config/eslint/eslint.seatbelt.tsv +++ b/config/eslint/eslint.seatbelt.tsv @@ -81,6 +81,7 @@ "../../src/components/AmountTextInput.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/AnchorForAttachmentsOnly/index.tsx" "no-restricted-syntax" 1 "../../src/components/AnchorForCommentsOnly/index.tsx" "no-restricted-syntax" 1 +"../../src/components/AnimatedCollapsible/index.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/AnimatedFlatListWithCellRenderer.tsx" "@typescript-eslint/no-deprecated/Animated.createAnimatedComponent" 1 "../../src/components/AnimatedFlatListWithCellRenderer.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/AnimatedFlatListWithCellRenderer.tsx" "react-hooks/refs" 2 @@ -88,6 +89,7 @@ "../../src/components/AnimatedSubmitButton/index.tsx" "no-restricted-imports" 1 "../../src/components/AnimatedSubmitButton/index.tsx" "react-hooks/refs" 6 "../../src/components/AnimatedSubmitButton/index.tsx" "react-hooks/set-state-in-effect" 1 +"../../src/components/ApprovalWorkflowSection.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/AttachmentPicker/index.native.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/AttachmentPicker/index.native.tsx" "react-hooks/refs" 1 "../../src/components/AttachmentPicker/index.tsx" "react-hooks/refs" 1 @@ -114,9 +116,18 @@ "../../src/components/AvatarWithImagePicker.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/AvatarWithImagePicker.tsx" "react-hooks/set-state-in-effect" 2 "../../src/components/BookTravelButton.tsx" "no-restricted-imports" 1 +"../../src/components/Button/index.tsx" "@typescript-eslint/no-deprecated/extraSmall" 2 +"../../src/components/Button/index.tsx" "@typescript-eslint/no-deprecated/large" 2 +"../../src/components/Button/index.tsx" "@typescript-eslint/no-deprecated/medium" 2 +"../../src/components/Button/index.tsx" "@typescript-eslint/no-deprecated/small" 2 "../../src/components/Button/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/components/Button/validateSubmitShortcut/index.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/ButtonComposed/Button.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 +"../../src/components/ButtonComposed/primitives/ButtonIcon.tsx" "@typescript-eslint/no-deprecated/large" 1 +"../../src/components/ButtonComposed/primitives/ButtonIcon.tsx" "@typescript-eslint/no-deprecated/medium" 1 +"../../src/components/ButtonComposed/primitives/ButtonIcon.tsx" "@typescript-eslint/no-deprecated/small" 1 +"../../src/components/ButtonWithDropdownMenu/index.tsx" "@typescript-eslint/no-deprecated/medium" 1 +"../../src/components/ButtonWithDropdownMenu/index.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/ButtonWithDropdownMenu/index.tsx" "react-hooks/preserve-manual-memoization" 1 "../../src/components/ButtonWithDropdownMenu/index.tsx" "react-hooks/refs" 3 "../../src/components/ButtonWithDropdownMenu/index.tsx" "react-hooks/set-state-in-effect" 1 @@ -143,6 +154,7 @@ "../../src/components/ConnectToXeroFlow/index.tsx" "react-hooks/set-state-in-effect" 1 "../../src/components/ContactPermissionModal/index.native.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 1 "../../src/components/ContactPermissionModal/index.native.tsx" "@typescript-eslint/no-deprecated/InteractionManager.runAfterInteractions" 2 +"../../src/components/ContextMenuItem.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/CountryPicker/CountrySelectorModal.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/CountryPicker/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/DatePicker/CalendarPicker/MonthPickerModal.tsx" "react-hooks/set-state-in-effect" 1 @@ -192,6 +204,7 @@ "../../src/components/Form/FormProvider.tsx" "react-hooks/refs" 2 "../../src/components/Form/InputWrapper.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/components/Form/InputWrapper.tsx" "react-hooks/refs" 1 +"../../src/components/FormHelpMessage.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/FullscreenLoadingIndicator.tsx" "@typescript-eslint/no-deprecated/StyleSheet.absoluteFillObject" 1 "../../src/components/GPSInProgressModal/index.native.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 1 "../../src/components/GPSTripStateChecker/index.native.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 1 @@ -235,6 +248,7 @@ "../../src/components/InteractiveStepSubPageHeader.tsx" "no-restricted-syntax" 1 "../../src/components/KYCWall/BaseKYCWall.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/components/KYCWall/BaseKYCWall.tsx" "react-hooks/refs" 2 +"../../src/components/LHNOptionsList/LHNEmptyState.tsx" "@typescript-eslint/no-deprecated/small" 2 "../../src/components/LHNOptionsList/LHNEmptyState.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/LHNOptionsList/OptionRowLHN/OptionRow/Pressable.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/LoadingIndicator.tsx" "@typescript-eslint/no-deprecated/StyleSheet.absoluteFillObject" 1 @@ -320,6 +334,7 @@ "../../src/components/PDFView/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/PDFView/index.tsx" "react-hooks/set-state-in-effect" 1 "../../src/components/ParentNavigationSubtitle.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 +"../../src/components/PaymentCardDetails.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/components/Picker/BasePicker.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/components/Picker/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/PlanTypeSelector.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 @@ -333,6 +348,7 @@ "../../src/components/PressableWithSecondaryInteraction/index.native.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/components/PressableWithSecondaryInteraction/index.native.tsx" "no-restricted-syntax" 1 "../../src/components/PressableWithSecondaryInteraction/index.tsx" "no-restricted-syntax" 1 +"../../src/components/ProductTrainingContext/index.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/components/RNMarkdownTextInput.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/RNMaskedTextInput.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/RadioButtonWithLabel.tsx" "no-restricted-syntax" 1 @@ -392,12 +408,16 @@ "../../src/components/Search/SearchList/ListItem/BaseListItemHeader.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Search/SearchList/ListItem/CardListItemHeader.tsx" "@typescript-eslint/no-unsafe-type-assertion" 4 "../../src/components/Search/SearchList/ListItem/ChatListItem.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 +"../../src/components/Search/SearchList/ListItem/ExpandCollapseArrowButton.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx" "@typescript-eslint/no-unsafe-type-assertion" 5 "../../src/components/Search/SearchList/ListItem/ExpenseReportListItemRow/ExpenseReportListItemRowWide.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 +"../../src/components/Search/SearchList/ListItem/ExportedIconCell.tsx" "@typescript-eslint/no-deprecated/small" 2 "../../src/components/Search/SearchList/ListItem/GroupChildrenContent.tsx" "@typescript-eslint/no-unsafe-type-assertion" 4 "../../src/components/Search/SearchList/ListItem/GroupHeader.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/components/Search/SearchList/ListItem/MemberListItemHeader.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 +"../../src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx" "@typescript-eslint/no-unsafe-type-assertion" 4 +"../../src/components/Search/SearchList/ListItem/SearchQueryListItem.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/components/Search/SearchList/ListItem/TaskListItem.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Search/SearchList/ListItem/TaskListItemRow.tsx" "no-restricted-imports" 1 "../../src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 @@ -410,8 +430,15 @@ "../../src/components/Search/SearchMultipleSelectionPicker.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Search/SearchPageHeader/SearchActionsBarCreateButton.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Search/SearchPageHeader/SearchActionsBarCreateButton.tsx" "no-restricted-imports" 1 +"../../src/components/Search/SearchPageHeader/SearchAdvancedFiltersButton.tsx" "@typescript-eslint/no-deprecated/extraSmall" 1 +"../../src/components/Search/SearchPageHeader/SearchAdvancedFiltersButton.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/Search/SearchPageHeader/SearchAdvancedFiltersButton.tsx" "no-restricted-imports" 1 +"../../src/components/Search/SearchPageHeader/SearchDisplayDropdownButton.tsx" "@typescript-eslint/no-deprecated/extraSmall" 1 +"../../src/components/Search/SearchPageHeader/SearchDisplayDropdownButton.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/Search/SearchPageHeader/SearchFilterBar.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 +"../../src/components/Search/SearchPageHeader/SearchFiltersClearButton.tsx" "@typescript-eslint/no-deprecated/extraSmall" 1 +"../../src/components/Search/SearchPageHeader/SearchSaveButton.tsx" "@typescript-eslint/no-deprecated/extraSmall" 1 +"../../src/components/Search/SearchPageHeader/SearchSaveButton.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/Search/SearchPageHeader/SearchSaveButton.tsx" "no-restricted-imports" 1 "../../src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Search/SearchPageHeader/useSearchPageInput.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 @@ -452,6 +479,7 @@ "../../src/components/SoftKillTestToolRow/index.native.tsx" "no-restricted-imports" 1 "../../src/components/SpendRules/SpendRuleRestrictionTypeToggle.tsx" "no-restricted-imports" 1 "../../src/components/SpendRules/SpendRuleRestrictionTypeToggleRevamp.tsx" "no-restricted-imports" 1 +"../../src/components/SpendRules/configuration/SpendRulesCurrencyBase.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/components/StatePicker/StateSelectorModal.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/components/StatePicker/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/StatusBadge.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 @@ -466,14 +494,18 @@ "../../src/components/SubStepForms/PushRowFieldsStep.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/components/SubStepForms/RegistrationNumberStep.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/components/SwipeableView/index.native.tsx" "react-hooks/refs" 2 +"../../src/components/SymbolButton.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/SymbolButton.tsx" "no-restricted-syntax" 1 +"../../src/components/TabSelector/TabIcon.tsx" "@typescript-eslint/no-deprecated/small" 2 "../../src/components/TabSelector/getBackground.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Table/Table.tsx" "@typescript-eslint/no-unsafe-type-assertion" 4 "../../src/components/Table/TableContext.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 +"../../src/components/Table/TableFilterBar/TableFilterTrigger.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/Table/middlewares/filtering.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Tables/WorkspaceCompanyCardsTable/WorkspaceCompanyCardsTableRow.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Tables/WorkspaceCompanyCardsTable/WorkspaceCompanyCardsTableRow.tsx" "no-restricted-imports" 1 "../../src/components/Tables/WorkspaceCompanyCardsTable/index.tsx" "no-restricted-imports" 1 +"../../src/components/Tables/WorkspaceExpensifyCardsTable/WorkspaceExpensifyCardsTableRow.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/TagPicker/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/TaxPicker.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/TestCrash/index.native.tsx" "no-restricted-imports" 1 @@ -509,13 +541,16 @@ "../../src/components/Tooltip/PopoverAnchorTooltip.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/Tooltip/PopoverAnchorTooltip.tsx" "react-hooks/refs" 7 "../../src/components/TransactionItemRow/DataCells/MerchantCell.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 +"../../src/components/TransactionItemRow/EditableCell/EditableCell.tsx" "@typescript-eslint/no-deprecated/extraSmall" 1 "../../src/components/UpdateAppModal.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 1 +"../../src/components/UploadFile.tsx" "@typescript-eslint/no-deprecated/medium" 2 "../../src/components/UploadFile.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/ValidateCodeActionModal/ValidateCodeForm/BaseValidateCodeForm.tsx" "no-restricted-imports" 1 "../../src/components/VideoPlayer/BaseVideoPlayer.tsx" "@typescript-eslint/no-unsafe-type-assertion" 7 "../../src/components/VideoPlayer/BaseVideoPlayer.tsx" "no-restricted-syntax" 1 "../../src/components/VideoPlayer/BaseVideoPlayer.tsx" "react-hooks/refs" 13 "../../src/components/VideoPlayer/BaseVideoPlayer.tsx" "react-hooks/set-state-in-effect" 2 +"../../src/components/VideoPlayer/IconButton.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/components/VideoPlayer/useHandleNativeVideoControls/index.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/VideoPlayerContexts/PlaybackContext/playbackContextReportIDUtils.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/WalletStatementModal/index.native.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 @@ -1124,6 +1159,7 @@ "../../src/pages/ReimbursementAccount/USD/ConnectBankAccount/components/BankAccountValidationForm.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/ReimbursementAccount/USD/KYBDocuments/index.tsx" "no-restricted-imports" 1 "../../src/pages/ReimbursementAccount/USD/USDVerifiedBankAccountFlowPage.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 +"../../src/pages/ReimbursementAccount/VerifiedBankAccountFlowEntryPoint.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/pages/ReimbursementAccount/utils/getSubStepValues.ts" "@typescript-eslint/no-unsafe-type-assertion" 4 "../../src/pages/ReportDescriptionPage.tsx" "no-restricted-imports" 1 "../../src/pages/ReportDescriptionPage.tsx" "no-restricted-syntax" 1 @@ -1152,6 +1188,7 @@ "../../src/pages/Search/SearchEditMultiple/SearchEditMultipleUtils.ts" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/pages/Search/SearchMoneyRequestReportPage.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/Search/SearchPage.tsx" "react-hooks/set-state-in-effect" 1 +"../../src/pages/Search/SearchPageNarrow/StaticSearchActionsBar.tsx" "@typescript-eslint/no-deprecated/small" 3 "../../src/pages/Search/SearchSavePage.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/pages/Search/SearchTransactionsChangeReport.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/Share/ShareButton.tsx" "no-restricted-imports" 1 @@ -1185,6 +1222,7 @@ "../../src/pages/ValidateLoginPage/index.web.tsx" "react-hooks/set-state-in-effect" 1 "../../src/pages/domain/Admins/DomainAdminsPage.tsx" "no-restricted-imports" 1 "../../src/pages/domain/BaseDomainRequireTwoFactorAuthPage.tsx" "no-restricted-imports" 1 +"../../src/pages/domain/BaseVerifyDomainPage.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/pages/domain/DomainAccessRestrictedPage.tsx" "no-restricted-imports" 1 "../../src/pages/domain/DomainsListPage.tsx" "no-restricted-imports" 1 "../../src/pages/domain/Groups/DomainGroupsPage.tsx" "no-restricted-imports" 1 @@ -1216,6 +1254,7 @@ "../../src/pages/inbox/report/ContextMenu/PopoverReportActionContextMenu.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/inbox/report/ContextMenu/PopoverReportActionContextMenu.tsx" "react-hooks/refs" 30 "../../src/pages/inbox/report/EnableNotificationsBanner.tsx" "no-restricted-imports" 1 +"../../src/pages/inbox/report/FloatingMessageCounter.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/pages/inbox/report/FloatingMessageCounter.tsx" "no-restricted-imports" 1 "../../src/pages/inbox/report/ListBoundaryLoader.tsx" "react-hooks/set-state-in-effect" 1 "../../src/pages/inbox/report/ReactionList/HeaderReactionList.tsx" "no-restricted-syntax" 1 @@ -1239,6 +1278,7 @@ "../../src/pages/inbox/report/ReportActionsList.tsx" "react-hooks/refs" 1 "../../src/pages/inbox/report/ShowPreviousMessagesButton.tsx" "no-restricted-imports" 1 "../../src/pages/inbox/report/TripSummary.tsx" "rulesdir/no-default-id-values" 1 +"../../src/pages/inbox/report/WhisperBanner.tsx" "@typescript-eslint/no-deprecated/small" 1 "../../src/pages/inbox/report/WhisperBanner.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/pages/inbox/report/actionContents/ActionContentRouter.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/inbox/report/actionContents/ChatMessageContent.tsx" "no-restricted-imports" 1 @@ -1384,6 +1424,7 @@ "../../src/pages/settings/Subscription/CardAuthenticationModal/index.tsx" "react-hooks/set-state-in-effect" 1 "../../src/pages/settings/Subscription/CardSection/BillingBanner/EarlyDiscountBanner.tsx" "no-restricted-imports" 1 "../../src/pages/settings/Subscription/CardSection/CardSectionButton/index.tsx" "no-restricted-imports" 1 +"../../src/pages/settings/Subscription/CardSection/CardSectionDataEmpty/index.native.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/pages/settings/Subscription/CardSection/CardSectionDataEmpty/index.tsx" "no-restricted-imports" 1 "../../src/pages/settings/Subscription/FreeTrial.tsx" "no-restricted-imports" 1 "../../src/pages/settings/Subscription/PaymentCard/ChangeBillingCurrency/index.tsx" "no-restricted-syntax" 1 @@ -1407,6 +1448,7 @@ "../../src/pages/settings/Wallet/InternationalDepositAccount/PersonalInfo/PersonalInfo.tsx" "@typescript-eslint/no-deprecated/useSubStep" 1 "../../src/pages/settings/Wallet/InternationalDepositAccount/PersonalInfo/substeps/AddressStep.tsx" "@typescript-eslint/no-unsafe-type-assertion" 6 "../../src/pages/settings/Wallet/InternationalDepositAccount/PersonalInfo/substeps/AddressStep.tsx" "react-hooks/set-state-in-effect" 1 +"../../src/pages/settings/Wallet/InternationalDepositAccount/subPages/AccountFlowEntryPoint.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/pages/settings/Wallet/InternationalDepositAccount/subPages/Confirmation.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/settings/Wallet/InternationalDepositAccount/utils.ts" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/settings/Wallet/PaymentMethodList.tsx" "@typescript-eslint/no-unsafe-type-assertion" 7 @@ -1442,6 +1484,7 @@ "../../src/pages/signin/SignInPageLayout/FooterRow/index.native.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/pages/signin/SignUpWelcomeForm.tsx" "no-restricted-imports" 1 "../../src/pages/signin/UnlinkLoginForm.tsx" "no-restricted-imports" 1 +"../../src/pages/signin/ValidateCodeForm/BaseValidateCodeForm.tsx" "@typescript-eslint/no-deprecated/medium" 1 "../../src/pages/signin/ValidateCodeForm/BaseValidateCodeForm.tsx" "no-restricted-imports" 1 "../../src/pages/signin/ValidateCodeForm/BaseValidateCodeForm.tsx" "react-hooks/set-state-in-effect" 4 "../../src/pages/tasks/TaskShareDestinationSelectorModal.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 @@ -1654,6 +1697,7 @@ "../../src/pages/workspace/withPolicyAndFullscreenLoading.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/pages/workspace/workflows/WorkspaceAutoReportingFrequencyPage.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/workspace/workflows/WorkspaceAutoReportingMonthlyOffsetPage.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 +"../../src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx" "@typescript-eslint/no-deprecated/extraSmall" 1 "../../src/pages/workspace/workflows/WorkspaceWorkflowsPage.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/pages/workspace/workflows/WorkspaceWorkflowsPayerPage.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 2 "../../src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApprovalLimitPage.tsx" "no-restricted-imports" 1 From b533a0b98c74b688ba4ae950c9a0c7239ff285f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski?= Date: Wed, 8 Jul 2026 15:07:31 +0200 Subject: [PATCH 11/14] Open agent DM reactively via useOnyx instead of Onyx.connectWithoutView Replace the action-layer connectWithoutView watcher with a useOnyx subscription in AddAgentPage. When online, the page stays mounted (showing the submit spinner) until the newly created agent appears in the agent-prompt collection, then opens the DM with its real accountID; creation failures and offline creations dismiss without opening a DM. --- src/libs/actions/Agent.ts | 51 +------ src/pages/settings/Agents/AddAgentPage.tsx | 88 +++++++++--- tests/unit/AgentActionTest.ts | 36 ----- .../unit/pages/settings/AddAgentPageTest.tsx | 125 +++++++++++++----- 4 files changed, 162 insertions(+), 138 deletions(-) diff --git a/src/libs/actions/Agent.ts b/src/libs/actions/Agent.ts index dae2dd8e9e25..8dd3a1fd0956 100644 --- a/src/libs/actions/Agent.ts +++ b/src/libs/actions/Agent.ts @@ -101,56 +101,7 @@ function createAgent( {optimisticData, successData, failureData}, ); - return {optimisticAccountID, avatarURI, createdAgentAccountID: waitForCreatedAgentAccountID(optimisticAccountID)}; -} - -/** - * Resolves with the real, server-assigned accountID of the agent just created by `createAgent`. - * - * Account IDs (unlike report IDs) can't be generated optimistically on the client, so the optimistic - * accountID above is never the agent's real identity — CREATE_AGENT nulls it out on success and writes - * the agent under a real accountID instead. We therefore watch the agent-prompt collection and resolve - * with the first agent that appears after this call that isn't the optimistic placeholder or an agent - * that already existed. Callers use it to open the DM with the newly created agent once it's real. - */ -function waitForCreatedAgentAccountID(optimisticAccountID: number): Promise { - return new Promise((resolve) => { - let knownAgentAccountIDs: Set | undefined; - const connection = Onyx.connectWithoutView({ - key: ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT, - waitForCollectionCallback: true, - callback: (agentPrompts) => { - const entries = Object.entries(agentPrompts ?? {}); - - // The first callback runs before CREATE_AGENT can respond, so it establishes the baseline - // (agents that already existed plus the optimistic placeholder). The real agent is whatever shows up after. - if (!knownAgentAccountIDs) { - knownAgentAccountIDs = new Set(entries.map(([key]) => Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length)))); - return; - } - - const createdAgentEntry = entries.find(([key, agentPrompt]) => { - const accountID = Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length)); - - // Skip agents that already existed at baseline and this request's own optimistic placeholder. - if (accountID === optimisticAccountID || knownAgentAccountIDs?.has(accountID)) { - return false; - } - - // Skip any *other* agent still pending creation — e.g. a second agent the user created before this - // one's CREATE_AGENT responded (its optimistic accountID is also new and not our optimistic ID). - // Only a real, server-created agent has no ADD pending action, and that's the accountID we can open a DM with. - return agentPrompt?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD; - }); - if (createdAgentEntry === undefined) { - return; - } - - Onyx.disconnect(connection); - resolve(Number(createdAgentEntry[0].slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length))); - }, - }); - }); + return {optimisticAccountID, avatarURI}; } function clearAgentError(optimisticAccountID: number) { diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index 9dde3afb3453..aa9f7d3ed0aa 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -12,6 +12,7 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails' import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; +import useOnyx from '@hooks/useOnyx'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; @@ -35,13 +36,22 @@ import INPUT_IDS from '@src/types/form/AddAgentForm'; import type {Errors} from '@src/types/onyx/OnyxCommon'; import {useFocusEffect} from '@react-navigation/native'; -import React, {useCallback, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useRef, useState} from 'react'; import {View} from 'react-native'; import {clearPendingAvatar, getPendingAvatar, setInitialPresetID, setNavigationToken, setReturnRoute} from './pendingAgentAvatarStore'; type AddAgentPageProps = PlatformStackScreenProps; +type PendingCreatedAgent = { + optimisticAccountID: number; + knownAgentAccountIDs: Set; +}; + +function getAgentAccountIDFromKey(key: string): number { + return Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length)); +} + function AddAgentPage({route}: AddAgentPageProps) { const policyID = route.params?.policyID; const {translate} = useLocalize(); @@ -50,14 +60,56 @@ function AddAgentPage({route}: AddAgentPageProps) { const shouldUseScrollableLayout = useIsInLandscapeMode() || (isMobile() && windowWidth > windowHeight); const {displayName} = useCurrentUserPersonalDetails(); const chatWithAgent = useChatWithAgent(); + const [agentPrompts] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT); const defaultAgentName = displayName ? translate('addAgentPage.defaultAgentName', displayName) : undefined; const defaultPrompt = translate('addAgentPage.defaultPrompt'); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Pencil']); const avatarStyle = [styles.avatarXLarge, styles.alignSelfCenter]; const [selectedPresetID, setSelectedPresetID] = useState(() => AGENT_AVATARS.ordered.at(Math.floor(Math.random() * AGENT_AVATARS.ordered.length))?.id ?? null); const [uploadedURI, setUploadedURI] = useState(null); + const [isCreatingAgent, setIsCreatingAgent] = useState(false); const pendingFileRef = useRef<{file: File | CustomRNImageManipulatorResult; uri: string} | null>(null); + // Account IDs can't be generated optimistically (unlike report IDs), so an agent's real accountID only + // exists once CREATE_AGENT responds. When creating online we keep this page mounted until that happens, + // then open the DM. This holds the agents that already existed at submit time plus this request's + // optimistic placeholder, both of which we ignore when spotting the newly created agent. + const pendingCreatedAgentRef = useRef(null); + + useEffect(() => { + const pendingCreatedAgent = pendingCreatedAgentRef.current; + if (!pendingCreatedAgent) { + return; + } + + // Creation failed: the optimistic entry now carries an error. Dismiss and let the Agents list surface it. + const optimisticPrompt = agentPrompts?.[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${pendingCreatedAgent.optimisticAccountID}`]; + if (optimisticPrompt?.errors) { + pendingCreatedAgentRef.current = null; + Navigation.goBack(); + return; + } + + const createdAgentKey = Object.keys(agentPrompts ?? {}).find((key) => { + const accountID = getAgentAccountIDFromKey(key); + + // Ignore agents that already existed at submit time and this request's own optimistic placeholder. + if (accountID === pendingCreatedAgent.optimisticAccountID || pendingCreatedAgent.knownAgentAccountIDs.has(accountID)) { + return false; + } + + // A real, server-created agent has no ADD pending action — that's the one we can open a DM with. + // Another agent the user created in the meantime is still an optimistic ADD placeholder. + return agentPrompts?.[key]?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD; + }); + if (!createdAgentKey) { + return; + } + + pendingCreatedAgentRef.current = null; + chatWithAgent(getAgentAccountIDFromKey(createdAgentKey), {shouldDismissModal: true}); + }, [agentPrompts, chatWithAgent]); + useFocusEffect( useCallback(() => { const pending = getPendingAvatar(); @@ -100,28 +152,27 @@ function AddAgentPage({route}: AddAgentPageProps) { const prompt = values[INPUT_IDS.PROMPT].trim(); const pendingFile = pendingFileRef.current; - // `createAgent` writes the agent optimistically (works offline) and returns a promise that - // resolves with the agent's real, server-assigned accountID once CREATE_AGENT responds. - const {createdAgentAccountID} = pendingFile + // `createAgent` writes the agent optimistically (works offline) and returns the optimistic + // accountID it wrote into Onyx. The real, server-assigned accountID only arrives once CREATE_AGENT responds. + const {optimisticAccountID} = pendingFile ? createAgent(firstName, prompt, undefined, pendingFile.file, pendingFile.uri, policyID) : createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID); - // Leave the add-agent modal right away so the optimistic agent shows in the Agents list - // (this also keeps the flow usable offline). - const wasOffline = getIsOffline(); - Navigation.goBack(); - - // Opening the DM is the immediate continuation of tapping "Create" — but it needs the real, - // server-assigned accountID, which doesn't exist until CREATE_AGENT responds. When created offline - // that response only arrives after reconnect, long after the user has moved on, so auto-opening the - // DM then would yank them out of whatever they're doing. Only continue into the DM for agents created - // online; offline creations just leave the new agent in the list for the user to open when they choose. - if (wasOffline) { + // Offline: the real accountID only arrives after reconnect, long after the user has moved on, so we + // don't wait — just return to the list with the optimistic agent for the user to open when they choose. + if (getIsOffline()) { + Navigation.goBack(); return; } - createdAgentAccountID.then((accountID) => { - chatWithAgent(accountID, {shouldDismissModal: true}); - }); + + // Online: opening the DM is the immediate continuation of tapping "Create", but it needs the real + // accountID. Stay on this page (showing the submit spinner) until the created agent appears in the + // collection, then the effect opens the DM. Snapshot the existing agents so we can tell the new one apart. + pendingCreatedAgentRef.current = { + optimisticAccountID, + knownAgentAccountIDs: new Set(Object.keys(agentPrompts ?? {}).map(getAgentAccountIDFromKey)), + }; + setIsCreatingAgent(true); }; return ( @@ -140,6 +191,7 @@ function AddAgentPage({route}: AddAgentPageProps) { onSubmit={handleSubmit} validate={validate} submitButtonText={translate('addAgentPage.createAgent')} + isLoading={isCreatingAgent} style={[styles.flex1, styles.ph5]} shouldUseScrollView={shouldUseScrollableLayout} submitFlexEnabled={shouldUseScrollableLayout ? undefined : false} diff --git a/tests/unit/AgentActionTest.ts b/tests/unit/AgentActionTest.ts index fc5389197f79..18b90279d991 100644 --- a/tests/unit/AgentActionTest.ts +++ b/tests/unit/AgentActionTest.ts @@ -15,7 +15,6 @@ import Onyx from 'react-native-onyx'; import createRandomPolicy from '../utils/collections/policies'; import createMock from '../utils/createMock'; -import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; jest.mock('@libs/API'); jest.mock('@libs/Navigation/Navigation', () => ({navigate: jest.fn(), goBack: jest.fn()})); @@ -256,41 +255,6 @@ describe('createAgent', () => { }); expect(promptValue?.errors).toBeTruthy(); }); - - it('resolves createdAgentAccountID with the real server agent, ignoring other pending optimistic agents', async () => { - await Onyx.clear(); - - const {optimisticAccountID, createdAgentAccountID} = createAgent('Bot', 'My prompt'); - - // Let waitForCreatedAgentAccountID establish its baseline from the (empty) collection. - await waitForBatchedUpdates(); - - let resolvedAccountID: number | undefined; - const settledCreatedAgentAccountID = createdAgentAccountID.then((id) => { - resolvedAccountID = id; - }); - - // A second agent the user creates before this one's CREATE_AGENT responds shows up as a *new* - // optimistic prompt entry (pendingAction ADD). It must NOT be mistaken for the created agent. - const otherOptimisticAccountID = optimisticAccountID + 1; - await Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${otherOptimisticAccountID}`, { - prompt: 'Another prompt', - pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, - }); - await waitForBatchedUpdates(); - - // Still unresolved — the only new entry is another optimistic placeholder. - expect(resolvedAccountID).toBeUndefined(); - - // The real, server-created agent arrives without an ADD pending action. - const realAccountID = 22542959; - await Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${realAccountID}`, {prompt: 'My prompt'}); - await waitForBatchedUpdates(); - await settledCreatedAgentAccountID; - - await expect(createdAgentAccountID).resolves.toBe(realAccountID); - expect(resolvedAccountID).toBe(realAccountID); - }); }); const TEST_ACCOUNT_ID = 42; diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 43325c7c5708..4d5557a59b44 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -1,4 +1,4 @@ -import {render, waitFor} from '@testing-library/react-native'; +import {act, render, waitFor} from '@testing-library/react-native'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; @@ -12,6 +12,7 @@ import {setInitialPresetID, setNavigationToken} from '@pages/settings/Agents/pen import {createAgent} from '@userActions/Agent'; +import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; @@ -55,7 +56,11 @@ jest.mock('@hooks/useLazyAsset', () => ({ useMemoizedLazyExpensifyIcons: jest.fn(() => ({Pencil: 1})), })); -jest.mock('@hooks/useOnyx', () => jest.fn(() => [undefined, {status: 'loaded'}])); +// AddAgentPage subscribes to the agent-prompt collection to detect the newly created agent. Tests drive +// this value directly and re-render to simulate the collection updating (useOnyx here is not reactive). +let mockAgentPrompts: Record}> | undefined; + +jest.mock('@hooks/useOnyx', () => jest.fn(() => [mockAgentPrompts, {status: 'loaded'}])); jest.mock('@libs/Navigation/Navigation', () => ({ goBack: jest.fn(), @@ -148,14 +153,41 @@ function makeRoute(params: AddAgentRouteProp['params'] = {}): AddAgentRouteProp return createMock({name: SCREENS.SETTINGS.AGENTS.ADD, key: '', params}); } +const OPTIMISTIC_ACCOUNT_ID = -123456; +const REAL_ACCOUNT_ID = 22542959; +const realAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${REAL_ACCOUNT_ID}`; +const optimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${OPTIMISTIC_ACCOUNT_ID}`; +const otherOptimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}999`; +const mockNavigation = undefined as never; + +function renderAddAgentPage(params: AddAgentRouteProp['params'] = {}) { + const utils = render( + , + ); + return { + ...utils, + rerenderPage: () => + utils.rerender( + , + ), + }; +} + describe('AddAgentPage', () => { beforeEach(() => { jest.clearAllMocks(); mockUseCurrentUserPersonalDetails.mockReturnValue({accountID: 0}); - mockCreateAgent.mockReturnValue({optimisticAccountID: -123456, avatarURI: undefined, createdAgentAccountID: Promise.resolve(22542959)}); + mockCreateAgent.mockReturnValue({optimisticAccountID: OPTIMISTIC_ACCOUNT_ID, avatarURI: undefined}); mockGetIsOffline.mockReturnValue(false); mockIsActiveRoute.mockReturnValue(true); mockAvatarOnPress = undefined; + mockAgentPrompts = {}; }); it('renders page title', () => { @@ -263,55 +295,80 @@ describe('AddAgentPage', () => { mockFormOnSubmit = undefined; }); - it('dismisses the modal and opens the DM with the real accountID once it resolves when policyID is absent', async () => { - render( - , - ); + it('stays on the page until the created agent appears, then opens the DM with its real accountID (policyID absent)', async () => { + const {rerenderPage} = renderAddAgentPage({}); - mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // The modal is dismissed immediately so the optimistic agent shows in the Agents list. - expect(mockGoBack).toHaveBeenCalledTimes(1); + // Online we don't dismiss immediately — we wait for the real, server-assigned accountID. + expect(mockGoBack).not.toHaveBeenCalled(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); - // The DM opens with the agent's real, server-assigned accountID — never the optimistic one. - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(22542959, {shouldDismissModal: true})); + // The real, server-created agent arrives in the collection (no ADD pending action). + mockAgentPrompts = {[realAgentKey]: {}}; + rerenderPage(); + + // The DM opens with the agent's real accountID — never the optimistic one — and dismisses the modal. + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); + expect(mockGoBack).not.toHaveBeenCalled(); }); - it('dismisses the modal and opens the DM with the real accountID once it resolves when policyID is present', async () => { - render( - , - ); + it('opens the DM with the real accountID once the created agent appears (policyID present)', async () => { + const {rerenderPage} = renderAddAgentPage({policyID: 'POL_42'}); - mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - expect(mockGoBack).toHaveBeenCalledTimes(1); + mockAgentPrompts = {[realAgentKey]: {}}; + rerenderPage(); - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(22542959, {shouldDismissModal: true})); + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); }); + it('ignores another optimistic (pending ADD) agent and waits for the real one', async () => { + const {rerenderPage} = renderAddAgentPage({}); + + act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); + + // A second agent the user created shows up as a *new* optimistic placeholder (pendingAction ADD). + // It must NOT be mistaken for the created agent. + mockAgentPrompts = {[otherOptimisticAgentKey]: {pendingAction: 'add'}}; + rerenderPage(); + await waitForBatchedUpdates(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // The real, server-created agent arrives without an ADD pending action. + mockAgentPrompts = {[otherOptimisticAgentKey]: {pendingAction: 'add'}, [realAgentKey]: {}}; + rerenderPage(); + + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); + }); + + it('dismisses the page and does not open the DM when creation fails', async () => { + const {rerenderPage} = renderAddAgentPage({}); + + act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); + + // Creation failed: the optimistic entry now carries an error. + mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add', errors: {error: 'genericAdd'}}}; + rerenderPage(); + + // We dismiss and let the Agents list surface the error, without opening any DM. + await waitFor(() => expect(mockGoBack).toHaveBeenCalledTimes(1)); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + }); + it('does not open the DM when created offline, even if the user is still on the Agents list', async () => { mockGetIsOffline.mockReturnValue(true); mockIsActiveRoute.mockReturnValue(true); - render( - , - ); + renderAddAgentPage({}); - mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'}); + act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // We return to the Agents list but never open the DM — the real accountID only arrives on reconnect, - // long after the user has moved on, so we don't yank them into the DM. + // We return to the Agents list right away but never open the DM — the real accountID only arrives on + // reconnect, long after the user has moved on, so we don't yank them into the DM. expect(mockGoBack).toHaveBeenCalledTimes(1); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); From fc78d48c63a73addfefdf8447a05e5c2c94ff1d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski?= Date: Wed, 8 Jul 2026 16:32:04 +0200 Subject: [PATCH 12/14] Guard created-agent matching against a partially-hydrated collection On a cold open or direct link, the agent-prompt collection may not have hydrated when the user submits, so the baseline snapshot of existing agents was empty. Agents hydrating before the CREATE_AGENT response were then mistaken for the newly created one, opening the wrong DM. Gate matching on the useOnyx load status and capture the baseline lazily from the first fully-loaded snapshot that already includes our optimistic placeholder, so late-hydrating existing agents are never matched. --- src/pages/settings/Agents/AddAgentPage.tsx | 43 +++++++--- .../unit/pages/settings/AddAgentPageTest.tsx | 78 ++++++++++++++++++- 2 files changed, 106 insertions(+), 15 deletions(-) diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index aa9f7d3ed0aa..5cc9cb5be12c 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -45,7 +45,9 @@ type AddAgentPageProps = PlatformStackScreenProps; + // Captured lazily from the first fully-loaded collection snapshot that includes our optimistic entry, + // so agents that hydrate late aren't mistaken for the one we just created. Null until then. + knownAgentAccountIDs: Set | null; }; function getAgentAccountIDFromKey(key: string): number { @@ -60,7 +62,7 @@ function AddAgentPage({route}: AddAgentPageProps) { const shouldUseScrollableLayout = useIsInLandscapeMode() || (isMobile() && windowWidth > windowHeight); const {displayName} = useCurrentUserPersonalDetails(); const chatWithAgent = useChatWithAgent(); - const [agentPrompts] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT); + const [agentPrompts, agentPromptsMetadata] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT); const defaultAgentName = displayName ? translate('addAgentPage.defaultAgentName', displayName) : undefined; const defaultPrompt = translate('addAgentPage.defaultPrompt'); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Pencil']); @@ -72,8 +74,7 @@ function AddAgentPage({route}: AddAgentPageProps) { // Account IDs can't be generated optimistically (unlike report IDs), so an agent's real accountID only // exists once CREATE_AGENT responds. When creating online we keep this page mounted until that happens, - // then open the DM. This holds the agents that already existed at submit time plus this request's - // optimistic placeholder, both of which we ignore when spotting the newly created agent. + // then open the DM. const pendingCreatedAgentRef = useRef(null); useEffect(() => { @@ -82,9 +83,28 @@ function AddAgentPage({route}: AddAgentPageProps) { return; } + // Never match against a partially-hydrated collection — an existing agent that hydrates late could be + // mistaken for the one we just created and open its DM instead. + if (agentPromptsMetadata.status !== 'loaded') { + return; + } + + const optimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${pendingCreatedAgent.optimisticAccountID}`; + + // Establish the baseline from the first fully-loaded snapshot that already includes our optimistic entry. + // Every agent present alongside our placeholder at that point genuinely pre-existed, so capturing here + // (rather than at submit time, when the collection may not have hydrated) avoids false matches. + if (!pendingCreatedAgent.knownAgentAccountIDs) { + if (!agentPrompts?.[optimisticAgentKey]) { + return; + } + pendingCreatedAgent.knownAgentAccountIDs = new Set(Object.keys(agentPrompts).map(getAgentAccountIDFromKey)); + return; + } + const {knownAgentAccountIDs} = pendingCreatedAgent; + // Creation failed: the optimistic entry now carries an error. Dismiss and let the Agents list surface it. - const optimisticPrompt = agentPrompts?.[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${pendingCreatedAgent.optimisticAccountID}`]; - if (optimisticPrompt?.errors) { + if (agentPrompts?.[optimisticAgentKey]?.errors) { pendingCreatedAgentRef.current = null; Navigation.goBack(); return; @@ -93,8 +113,8 @@ function AddAgentPage({route}: AddAgentPageProps) { const createdAgentKey = Object.keys(agentPrompts ?? {}).find((key) => { const accountID = getAgentAccountIDFromKey(key); - // Ignore agents that already existed at submit time and this request's own optimistic placeholder. - if (accountID === pendingCreatedAgent.optimisticAccountID || pendingCreatedAgent.knownAgentAccountIDs.has(accountID)) { + // Ignore agents that already existed at baseline and this request's own optimistic placeholder. + if (accountID === pendingCreatedAgent.optimisticAccountID || knownAgentAccountIDs.has(accountID)) { return false; } @@ -108,7 +128,7 @@ function AddAgentPage({route}: AddAgentPageProps) { pendingCreatedAgentRef.current = null; chatWithAgent(getAgentAccountIDFromKey(createdAgentKey), {shouldDismissModal: true}); - }, [agentPrompts, chatWithAgent]); + }, [agentPrompts, agentPromptsMetadata.status, chatWithAgent]); useFocusEffect( useCallback(() => { @@ -167,10 +187,11 @@ function AddAgentPage({route}: AddAgentPageProps) { // Online: opening the DM is the immediate continuation of tapping "Create", but it needs the real // accountID. Stay on this page (showing the submit spinner) until the created agent appears in the - // collection, then the effect opens the DM. Snapshot the existing agents so we can tell the new one apart. + // collection, then the effect opens the DM. The baseline of existing agents is captured later, once the + // collection has loaded, so a partial snapshot here can't cause us to match an already-existing agent. pendingCreatedAgentRef.current = { optimisticAccountID, - knownAgentAccountIDs: new Set(Object.keys(agentPrompts ?? {}).map(getAgentAccountIDFromKey)), + knownAgentAccountIDs: null, }; setIsCreatingAgent(true); }; diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 4d5557a59b44..436c25a84c12 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -57,10 +57,12 @@ jest.mock('@hooks/useLazyAsset', () => ({ })); // AddAgentPage subscribes to the agent-prompt collection to detect the newly created agent. Tests drive -// this value directly and re-render to simulate the collection updating (useOnyx here is not reactive). +// this value and its load status directly and re-render to simulate the collection updating (useOnyx here is +// not reactive). let mockAgentPrompts: Record}> | undefined; +let mockAgentPromptsStatus: 'loading' | 'loaded' = 'loaded'; -jest.mock('@hooks/useOnyx', () => jest.fn(() => [mockAgentPrompts, {status: 'loaded'}])); +jest.mock('@hooks/useOnyx', () => jest.fn(() => [mockAgentPrompts, {status: mockAgentPromptsStatus}])); jest.mock('@libs/Navigation/Navigation', () => ({ goBack: jest.fn(), @@ -188,6 +190,7 @@ describe('AddAgentPage', () => { mockIsActiveRoute.mockReturnValue(true); mockAvatarOnPress = undefined; mockAgentPrompts = {}; + mockAgentPromptsStatus = 'loaded'; }); it('renders page title', () => { @@ -304,7 +307,13 @@ describe('AddAgentPage', () => { expect(mockGoBack).not.toHaveBeenCalled(); expect(mockChatWithAgent).not.toHaveBeenCalled(); - // The real, server-created agent arrives in the collection (no ADD pending action). + // The optimistic placeholder lands; the effect captures its baseline from this loaded snapshot. + mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; + rerenderPage(); + await waitForBatchedUpdates(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // The real, server-created agent arrives (no ADD pending action). mockAgentPrompts = {[realAgentKey]: {}}; rerenderPage(); @@ -319,6 +328,9 @@ describe('AddAgentPage', () => { act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); + mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; + rerenderPage(); + mockAgentPrompts = {[realAgentKey]: {}}; rerenderPage(); @@ -331,9 +343,13 @@ describe('AddAgentPage', () => { act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); + // Our optimistic placeholder lands and sets the baseline. + mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; + rerenderPage(); + // A second agent the user created shows up as a *new* optimistic placeholder (pendingAction ADD). // It must NOT be mistaken for the created agent. - mockAgentPrompts = {[otherOptimisticAgentKey]: {pendingAction: 'add'}}; + mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}, [otherOptimisticAgentKey]: {pendingAction: 'add'}}; rerenderPage(); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); @@ -345,11 +361,65 @@ describe('AddAgentPage', () => { await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); }); + it('does not treat an agent that hydrates after submit as the newly created one', async () => { + // Cold open / direct link: the collection has not hydrated yet at submit time. + mockAgentPrompts = {}; + const {rerenderPage} = renderAddAgentPage({}); + + act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); + + // An existing agent hydrates before our optimistic placeholder / the CREATE_AGENT response. It must + // NOT be matched — the baseline isn't established until our placeholder is present. + mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}}; + rerenderPage(); + await waitForBatchedUpdates(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // Our optimistic placeholder lands; the baseline now includes the pre-existing agent. + mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [optimisticAgentKey]: {pendingAction: 'add'}}; + rerenderPage(); + await waitForBatchedUpdates(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // Only the actual created agent opens the DM. + mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [realAgentKey]: {}}; + rerenderPage(); + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); + }); + + it('does not match while the collection is still loading', async () => { + mockAgentPromptsStatus = 'loading'; + mockAgentPrompts = {}; + const {rerenderPage} = renderAddAgentPage({}); + + act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); + + // While loading, even a real-looking agent alongside our placeholder must not be matched. + mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}, [`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}}; + rerenderPage(); + await waitForBatchedUpdates(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // Once loaded, the baseline is captured (existing agent + our placeholder) and the created agent matches. + mockAgentPromptsStatus = 'loaded'; + rerenderPage(); + await waitForBatchedUpdates(); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [realAgentKey]: {}}; + rerenderPage(); + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); + }); + it('dismisses the page and does not open the DM when creation fails', async () => { const {rerenderPage} = renderAddAgentPage({}); act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); + // Our optimistic placeholder lands and sets the baseline. + mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; + rerenderPage(); + // Creation failed: the optimistic entry now carries an error. mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add', errors: {error: 'genericAdd'}}}; rerenderPage(); From 459dcb4ebf103c92648faae3cc8a25effdb0bca3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski?= Date: Wed, 8 Jul 2026 16:35:14 +0200 Subject: [PATCH 13/14] Simplify comments in the add-agent DM flow Reword the comments to be plainer and more direct, without changing any behavior. --- src/pages/settings/Agents/AddAgentPage.tsx | 39 +++++++--------- .../unit/pages/settings/AddAgentPageTest.tsx | 45 +++++++++---------- 2 files changed, 39 insertions(+), 45 deletions(-) diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index 5cc9cb5be12c..294f9b85edc7 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -45,8 +45,8 @@ type AddAgentPageProps = PlatformStackScreenProps | null; }; @@ -72,9 +72,8 @@ function AddAgentPage({route}: AddAgentPageProps) { const [isCreatingAgent, setIsCreatingAgent] = useState(false); const pendingFileRef = useRef<{file: File | CustomRNImageManipulatorResult; uri: string} | null>(null); - // Account IDs can't be generated optimistically (unlike report IDs), so an agent's real accountID only - // exists once CREATE_AGENT responds. When creating online we keep this page mounted until that happens, - // then open the DM. + // The client can't pick an agent's real accountID; it's set by the server. When creating online, keep this + // page open until the created agent shows up in the collection, then open its DM. const pendingCreatedAgentRef = useRef(null); useEffect(() => { @@ -83,17 +82,15 @@ function AddAgentPage({route}: AddAgentPageProps) { return; } - // Never match against a partially-hydrated collection — an existing agent that hydrates late could be - // mistaken for the one we just created and open its DM instead. + // Wait for the collection to finish loading, or an existing agent could be matched as the new one. if (agentPromptsMetadata.status !== 'loaded') { return; } const optimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${pendingCreatedAgent.optimisticAccountID}`; - // Establish the baseline from the first fully-loaded snapshot that already includes our optimistic entry. - // Every agent present alongside our placeholder at that point genuinely pre-existed, so capturing here - // (rather than at submit time, when the collection may not have hydrated) avoids false matches. + // Record which agents already exist, using the first loaded snapshot that includes our optimistic entry. + // Doing it here instead of on submit means agents that load later aren't treated as the new one. if (!pendingCreatedAgent.knownAgentAccountIDs) { if (!agentPrompts?.[optimisticAgentKey]) { return; @@ -103,7 +100,7 @@ function AddAgentPage({route}: AddAgentPageProps) { } const {knownAgentAccountIDs} = pendingCreatedAgent; - // Creation failed: the optimistic entry now carries an error. Dismiss and let the Agents list surface it. + // Creation failed: the optimistic entry now has an error. Go back so the error shows on the Agents list. if (agentPrompts?.[optimisticAgentKey]?.errors) { pendingCreatedAgentRef.current = null; Navigation.goBack(); @@ -113,13 +110,13 @@ function AddAgentPage({route}: AddAgentPageProps) { const createdAgentKey = Object.keys(agentPrompts ?? {}).find((key) => { const accountID = getAgentAccountIDFromKey(key); - // Ignore agents that already existed at baseline and this request's own optimistic placeholder. + // Skip agents that already existed and this request's own optimistic entry. if (accountID === pendingCreatedAgent.optimisticAccountID || knownAgentAccountIDs.has(accountID)) { return false; } - // A real, server-created agent has no ADD pending action — that's the one we can open a DM with. - // Another agent the user created in the meantime is still an optimistic ADD placeholder. + // The created agent is the one from the server, which has no ADD pending action. Another agent the + // user just created still has one. return agentPrompts?.[key]?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD; }); if (!createdAgentKey) { @@ -172,23 +169,21 @@ function AddAgentPage({route}: AddAgentPageProps) { const prompt = values[INPUT_IDS.PROMPT].trim(); const pendingFile = pendingFileRef.current; - // `createAgent` writes the agent optimistically (works offline) and returns the optimistic - // accountID it wrote into Onyx. The real, server-assigned accountID only arrives once CREATE_AGENT responds. + // createAgent writes the agent right away (works offline) and returns the optimistic accountID. The real + // accountID comes from the server once CREATE_AGENT responds. const {optimisticAccountID} = pendingFile ? createAgent(firstName, prompt, undefined, pendingFile.file, pendingFile.uri, policyID) : createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID); - // Offline: the real accountID only arrives after reconnect, long after the user has moved on, so we - // don't wait — just return to the list with the optimistic agent for the user to open when they choose. + // Offline: the real accountID won't arrive until reconnect, so don't wait. Go back to the list; the user + // can open the agent themselves. if (getIsOffline()) { Navigation.goBack(); return; } - // Online: opening the DM is the immediate continuation of tapping "Create", but it needs the real - // accountID. Stay on this page (showing the submit spinner) until the created agent appears in the - // collection, then the effect opens the DM. The baseline of existing agents is captured later, once the - // collection has loaded, so a partial snapshot here can't cause us to match an already-existing agent. + // Online: stay here with the submit spinner until the created agent appears, then the effect opens its DM. + // knownAgentAccountIDs is set later (see the effect), not now, in case the collection hasn't loaded yet. pendingCreatedAgentRef.current = { optimisticAccountID, knownAgentAccountIDs: null, diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 436c25a84c12..75c4d3cc0d2f 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -56,9 +56,8 @@ jest.mock('@hooks/useLazyAsset', () => ({ useMemoizedLazyExpensifyIcons: jest.fn(() => ({Pencil: 1})), })); -// AddAgentPage subscribes to the agent-prompt collection to detect the newly created agent. Tests drive -// this value and its load status directly and re-render to simulate the collection updating (useOnyx here is -// not reactive). +// AddAgentPage reads the agent-prompt collection to find the newly created agent. The mocked useOnyx does not +// update on its own, so tests set this value and its load status and re-render to simulate collection updates. let mockAgentPrompts: Record}> | undefined; let mockAgentPromptsStatus: 'loading' | 'loaded' = 'loaded'; @@ -303,21 +302,21 @@ describe('AddAgentPage', () => { act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // Online we don't dismiss immediately — we wait for the real, server-assigned accountID. + // Online we don't go back yet. We wait for the real accountID from the server. expect(mockGoBack).not.toHaveBeenCalled(); expect(mockChatWithAgent).not.toHaveBeenCalled(); - // The optimistic placeholder lands; the effect captures its baseline from this loaded snapshot. + // The optimistic entry appears, so the effect records which agents already exist. mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; rerenderPage(); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); - // The real, server-created agent arrives (no ADD pending action). + // The created agent arrives from the server (no ADD pending action). mockAgentPrompts = {[realAgentKey]: {}}; rerenderPage(); - // The DM opens with the agent's real accountID — never the optimistic one — and dismisses the modal. + // The DM opens with the real accountID, not the optimistic one, and closes the modal. await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); expect(mockChatWithAgent).toHaveBeenCalledTimes(1); expect(mockGoBack).not.toHaveBeenCalled(); @@ -343,18 +342,18 @@ describe('AddAgentPage', () => { act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // Our optimistic placeholder lands and sets the baseline. + // The optimistic entry appears and records which agents already exist. mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; rerenderPage(); - // A second agent the user created shows up as a *new* optimistic placeholder (pendingAction ADD). - // It must NOT be mistaken for the created agent. + // A second agent the user created shows up as a new optimistic entry (pendingAction ADD). + // It must not be picked as the created agent. mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}, [otherOptimisticAgentKey]: {pendingAction: 'add'}}; rerenderPage(); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); - // The real, server-created agent arrives without an ADD pending action. + // The created agent arrives from the server without an ADD pending action. mockAgentPrompts = {[otherOptimisticAgentKey]: {pendingAction: 'add'}, [realAgentKey]: {}}; rerenderPage(); @@ -362,26 +361,26 @@ describe('AddAgentPage', () => { }); it('does not treat an agent that hydrates after submit as the newly created one', async () => { - // Cold open / direct link: the collection has not hydrated yet at submit time. + // Cold open or direct link: the collection has not loaded yet at submit time. mockAgentPrompts = {}; const {rerenderPage} = renderAddAgentPage({}); act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // An existing agent hydrates before our optimistic placeholder / the CREATE_AGENT response. It must - // NOT be matched — the baseline isn't established until our placeholder is present. + // An existing agent loads before our optimistic entry and before the CREATE_AGENT response. It must + // not be picked, since we don't record existing agents until our entry is present. mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}}; rerenderPage(); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); - // Our optimistic placeholder lands; the baseline now includes the pre-existing agent. + // The optimistic entry appears, so the existing agent is now recorded as already existing. mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [optimisticAgentKey]: {pendingAction: 'add'}}; rerenderPage(); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); - // Only the actual created agent opens the DM. + // Only the created agent opens the DM. mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [realAgentKey]: {}}; rerenderPage(); await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); @@ -394,13 +393,13 @@ describe('AddAgentPage', () => { act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // While loading, even a real-looking agent alongside our placeholder must not be matched. + // While loading, an agent next to our entry must not be picked. mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}, [`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}}; rerenderPage(); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); - // Once loaded, the baseline is captured (existing agent + our placeholder) and the created agent matches. + // Once loaded, existing agents are recorded (agent 555 and our entry), and the created agent matches. mockAgentPromptsStatus = 'loaded'; rerenderPage(); await waitForBatchedUpdates(); @@ -416,15 +415,15 @@ describe('AddAgentPage', () => { act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // Our optimistic placeholder lands and sets the baseline. + // The optimistic entry appears and records the existing agents. mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; rerenderPage(); - // Creation failed: the optimistic entry now carries an error. + // Creation failed: the optimistic entry now has an error. mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add', errors: {error: 'genericAdd'}}}; rerenderPage(); - // We dismiss and let the Agents list surface the error, without opening any DM. + // We go back so the error shows on the Agents list, and no DM opens. await waitFor(() => expect(mockGoBack).toHaveBeenCalledTimes(1)); expect(mockChatWithAgent).not.toHaveBeenCalled(); }); @@ -437,8 +436,8 @@ describe('AddAgentPage', () => { act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // We return to the Agents list right away but never open the DM — the real accountID only arrives on - // reconnect, long after the user has moved on, so we don't yank them into the DM. + // We go back to the Agents list right away and never open the DM. The real accountID only arrives on + // reconnect, after the user has moved on. expect(mockGoBack).toHaveBeenCalledTimes(1); await waitForBatchedUpdates(); expect(mockChatWithAgent).not.toHaveBeenCalled(); From 1f992649c0cbc925ed3e6877164b8967968dc633 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Jasikowski?= Date: Wed, 8 Jul 2026 17:02:43 +0200 Subject: [PATCH 14/14] Extract the created-agent DM logic into useOpenDMWithCreatedAgent Move the matching and navigation logic out of AddAgentPage's render body into a dedicated hook. AddAgentPage now just calls the hook's returned function on submit, and its test only covers that wiring; the matching logic (collection load status, recording existing agents, skipping other optimistic entries, handling failures) has its own focused test. --- src/hooks/useOpenDMWithCreatedAgent.ts | 90 +++++++++ src/pages/settings/Agents/AddAgentPage.tsx | 82 +------- .../hooks/useOpenDMWithCreatedAgent.test.ts | 172 +++++++++++++++++ .../unit/pages/settings/AddAgentPageTest.tsx | 178 +++--------------- 4 files changed, 291 insertions(+), 231 deletions(-) create mode 100644 src/hooks/useOpenDMWithCreatedAgent.ts create mode 100644 tests/unit/hooks/useOpenDMWithCreatedAgent.test.ts diff --git a/src/hooks/useOpenDMWithCreatedAgent.ts b/src/hooks/useOpenDMWithCreatedAgent.ts new file mode 100644 index 000000000000..25f0794f1ab8 --- /dev/null +++ b/src/hooks/useOpenDMWithCreatedAgent.ts @@ -0,0 +1,90 @@ +import Navigation from '@libs/Navigation/Navigation'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import {useEffect, useRef} from 'react'; + +import useChatWithAgent from './useChatWithAgent'; +import useOnyx from './useOnyx'; + +type PendingCreatedAgent = { + optimisticAccountID: number; + // The agents that already existed before this one was created. Null until the collection has loaded and + // includes our optimistic entry, so agents that load later aren't treated as the new one. + knownAgentAccountIDs: Set | null; +}; + +function getAgentAccountIDFromKey(key: string): number { + return Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length)); +} + +/** + * Waits for the agent created by the most recent `createAgent` call to appear in Onyx, then opens its DM. + * The client can't pick an agent's real accountID; it's set by the server, so we watch for it to arrive. + * If creation fails, we go back instead so the error shows on the Agents list. + * + * Returns a function to start watching, given the optimistic accountID that `createAgent` returned. + */ +function useOpenDMWithCreatedAgent() { + const chatWithAgent = useChatWithAgent(); + const [agentPrompts, agentPromptsMetadata] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT); + const pendingCreatedAgentRef = useRef(null); + + useEffect(() => { + const pendingCreatedAgent = pendingCreatedAgentRef.current; + if (!pendingCreatedAgent) { + return; + } + + // Wait for the collection to finish loading, or an existing agent could be matched as the new one. + if (agentPromptsMetadata.status !== 'loaded') { + return; + } + + const optimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${pendingCreatedAgent.optimisticAccountID}`; + + // Record which agents already exist, using the first loaded snapshot that includes our optimistic entry. + // Doing it here instead of when watching starts means agents that load later aren't treated as the new one. + if (!pendingCreatedAgent.knownAgentAccountIDs) { + if (!agentPrompts?.[optimisticAgentKey]) { + return; + } + pendingCreatedAgent.knownAgentAccountIDs = new Set(Object.keys(agentPrompts).map(getAgentAccountIDFromKey)); + return; + } + const {knownAgentAccountIDs} = pendingCreatedAgent; + + // Creation failed: the optimistic entry now has an error. Go back so the error shows on the Agents list. + if (agentPrompts?.[optimisticAgentKey]?.errors) { + pendingCreatedAgentRef.current = null; + Navigation.goBack(); + return; + } + + const createdAgentKey = Object.keys(agentPrompts ?? {}).find((key) => { + const accountID = getAgentAccountIDFromKey(key); + + // Skip agents that already existed and this request's own optimistic entry. + if (accountID === pendingCreatedAgent.optimisticAccountID || knownAgentAccountIDs.has(accountID)) { + return false; + } + + // The created agent is the one from the server, which has no ADD pending action. Another agent the + // user just created still has one. + return agentPrompts?.[key]?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD; + }); + if (!createdAgentKey) { + return; + } + + pendingCreatedAgentRef.current = null; + chatWithAgent(getAgentAccountIDFromKey(createdAgentKey), {shouldDismissModal: true}); + }, [agentPrompts, agentPromptsMetadata.status, chatWithAgent]); + + return (optimisticAccountID: number) => { + pendingCreatedAgentRef.current = {optimisticAccountID, knownAgentAccountIDs: null}; + }; +} + +export default useOpenDMWithCreatedAgent; diff --git a/src/pages/settings/Agents/AddAgentPage.tsx b/src/pages/settings/Agents/AddAgentPage.tsx index 294f9b85edc7..1e7b059381c8 100644 --- a/src/pages/settings/Agents/AddAgentPage.tsx +++ b/src/pages/settings/Agents/AddAgentPage.tsx @@ -7,12 +7,11 @@ import ScreenWrapper from '@components/ScreenWrapper'; import Text from '@components/Text'; import TextInput from '@components/TextInput'; -import useChatWithAgent from '@hooks/useChatWithAgent'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; -import useOnyx from '@hooks/useOnyx'; +import useOpenDMWithCreatedAgent from '@hooks/useOpenDMWithCreatedAgent'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; @@ -36,24 +35,13 @@ import INPUT_IDS from '@src/types/form/AddAgentForm'; import type {Errors} from '@src/types/onyx/OnyxCommon'; import {useFocusEffect} from '@react-navigation/native'; -import React, {useCallback, useEffect, useRef, useState} from 'react'; +import React, {useCallback, useRef, useState} from 'react'; import {View} from 'react-native'; import {clearPendingAvatar, getPendingAvatar, setInitialPresetID, setNavigationToken, setReturnRoute} from './pendingAgentAvatarStore'; type AddAgentPageProps = PlatformStackScreenProps; -type PendingCreatedAgent = { - optimisticAccountID: number; - // The agents that already existed before this one was created. Null until the collection has loaded and - // includes our optimistic entry, so agents that load later aren't treated as the new one. - knownAgentAccountIDs: Set | null; -}; - -function getAgentAccountIDFromKey(key: string): number { - return Number(key.slice(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT.length)); -} - function AddAgentPage({route}: AddAgentPageProps) { const policyID = route.params?.policyID; const {translate} = useLocalize(); @@ -61,8 +49,7 @@ function AddAgentPage({route}: AddAgentPageProps) { const {windowWidth, windowHeight} = useWindowDimensions(); const shouldUseScrollableLayout = useIsInLandscapeMode() || (isMobile() && windowWidth > windowHeight); const {displayName} = useCurrentUserPersonalDetails(); - const chatWithAgent = useChatWithAgent(); - const [agentPrompts, agentPromptsMetadata] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT); + const watchForCreatedAgent = useOpenDMWithCreatedAgent(); const defaultAgentName = displayName ? translate('addAgentPage.defaultAgentName', displayName) : undefined; const defaultPrompt = translate('addAgentPage.defaultPrompt'); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Pencil']); @@ -72,61 +59,6 @@ function AddAgentPage({route}: AddAgentPageProps) { const [isCreatingAgent, setIsCreatingAgent] = useState(false); const pendingFileRef = useRef<{file: File | CustomRNImageManipulatorResult; uri: string} | null>(null); - // The client can't pick an agent's real accountID; it's set by the server. When creating online, keep this - // page open until the created agent shows up in the collection, then open its DM. - const pendingCreatedAgentRef = useRef(null); - - useEffect(() => { - const pendingCreatedAgent = pendingCreatedAgentRef.current; - if (!pendingCreatedAgent) { - return; - } - - // Wait for the collection to finish loading, or an existing agent could be matched as the new one. - if (agentPromptsMetadata.status !== 'loaded') { - return; - } - - const optimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${pendingCreatedAgent.optimisticAccountID}`; - - // Record which agents already exist, using the first loaded snapshot that includes our optimistic entry. - // Doing it here instead of on submit means agents that load later aren't treated as the new one. - if (!pendingCreatedAgent.knownAgentAccountIDs) { - if (!agentPrompts?.[optimisticAgentKey]) { - return; - } - pendingCreatedAgent.knownAgentAccountIDs = new Set(Object.keys(agentPrompts).map(getAgentAccountIDFromKey)); - return; - } - const {knownAgentAccountIDs} = pendingCreatedAgent; - - // Creation failed: the optimistic entry now has an error. Go back so the error shows on the Agents list. - if (agentPrompts?.[optimisticAgentKey]?.errors) { - pendingCreatedAgentRef.current = null; - Navigation.goBack(); - return; - } - - const createdAgentKey = Object.keys(agentPrompts ?? {}).find((key) => { - const accountID = getAgentAccountIDFromKey(key); - - // Skip agents that already existed and this request's own optimistic entry. - if (accountID === pendingCreatedAgent.optimisticAccountID || knownAgentAccountIDs.has(accountID)) { - return false; - } - - // The created agent is the one from the server, which has no ADD pending action. Another agent the - // user just created still has one. - return agentPrompts?.[key]?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD; - }); - if (!createdAgentKey) { - return; - } - - pendingCreatedAgentRef.current = null; - chatWithAgent(getAgentAccountIDFromKey(createdAgentKey), {shouldDismissModal: true}); - }, [agentPrompts, agentPromptsMetadata.status, chatWithAgent]); - useFocusEffect( useCallback(() => { const pending = getPendingAvatar(); @@ -182,12 +114,8 @@ function AddAgentPage({route}: AddAgentPageProps) { return; } - // Online: stay here with the submit spinner until the created agent appears, then the effect opens its DM. - // knownAgentAccountIDs is set later (see the effect), not now, in case the collection hasn't loaded yet. - pendingCreatedAgentRef.current = { - optimisticAccountID, - knownAgentAccountIDs: null, - }; + // Online: stay here with the submit spinner until the created agent appears, then its DM opens. + watchForCreatedAgent(optimisticAccountID); setIsCreatingAgent(true); }; diff --git a/tests/unit/hooks/useOpenDMWithCreatedAgent.test.ts b/tests/unit/hooks/useOpenDMWithCreatedAgent.test.ts new file mode 100644 index 000000000000..138a9028be68 --- /dev/null +++ b/tests/unit/hooks/useOpenDMWithCreatedAgent.test.ts @@ -0,0 +1,172 @@ +import {act, renderHook, waitFor} from '@testing-library/react-native'; + +import useChatWithAgent from '@hooks/useChatWithAgent'; +import useOpenDMWithCreatedAgent from '@hooks/useOpenDMWithCreatedAgent'; + +import Navigation from '@libs/Navigation/Navigation'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +import type {OnyxKey} from 'react-native-onyx'; + +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + +jest.mock('@hooks/useChatWithAgent'); +jest.mock('@libs/Navigation/Navigation', () => ({goBack: jest.fn()})); + +const mockChatWithAgent = jest.fn(); +const mockUseChatWithAgent = jest.mocked(useChatWithAgent); +const mockGoBack = jest.mocked(Navigation.goBack); + +const OPTIMISTIC_ACCOUNT_ID = -123456; +const REAL_ACCOUNT_ID = 22542959; +const optimisticAgentKey: OnyxKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${OPTIMISTIC_ACCOUNT_ID}`; +const realAgentKey: OnyxKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${REAL_ACCOUNT_ID}`; + +describe('useOpenDMWithCreatedAgent', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + jest.clearAllMocks(); + mockUseChatWithAgent.mockReturnValue(mockChatWithAgent); + await Onyx.clear(); + await waitForBatchedUpdates(); + }); + + it('does nothing until asked to watch for a created agent', async () => { + renderHook(() => useOpenDMWithCreatedAgent()); + + await act(async () => { + await Onyx.merge(realAgentKey, {}); + await waitForBatchedUpdates(); + }); + + expect(mockChatWithAgent).not.toHaveBeenCalled(); + expect(mockGoBack).not.toHaveBeenCalled(); + }); + + it('opens the DM with the created agent once it appears, ignoring the optimistic entry', async () => { + const {result} = renderHook(() => useOpenDMWithCreatedAgent()); + + act(() => result.current(OPTIMISTIC_ACCOUNT_ID)); + await act(async () => { + await Onyx.merge(optimisticAgentKey, {pendingAction: 'add'}); + await waitForBatchedUpdates(); + }); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + await act(async () => { + await Onyx.merge(realAgentKey, {}); + await waitForBatchedUpdates(); + }); + + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); + expect(mockChatWithAgent).toHaveBeenCalledTimes(1); + expect(mockGoBack).not.toHaveBeenCalled(); + }); + + it('ignores another agent that is still an optimistic (pending ADD) entry', async () => { + const {result} = renderHook(() => useOpenDMWithCreatedAgent()); + const otherOptimisticAgentKey: OnyxKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}999`; + + act(() => result.current(OPTIMISTIC_ACCOUNT_ID)); + await act(async () => { + await Onyx.merge(optimisticAgentKey, {pendingAction: 'add'}); + await waitForBatchedUpdates(); + }); + + // A second agent the user created shows up as a new optimistic entry (pendingAction ADD). + // It must not be picked as the created agent. + await act(async () => { + await Onyx.merge(otherOptimisticAgentKey, {pendingAction: 'add'}); + await waitForBatchedUpdates(); + }); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // The created agent arrives from the server without an ADD pending action. + await act(async () => { + await Onyx.merge(realAgentKey, {}); + await waitForBatchedUpdates(); + }); + + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); + }); + + it('does not treat an agent that loads after watching starts as the newly created one', async () => { + // Cold open or direct link: the collection has not loaded yet when watching starts. + const {result} = renderHook(() => useOpenDMWithCreatedAgent()); + const preExistingAgentKey: OnyxKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`; + + act(() => result.current(OPTIMISTIC_ACCOUNT_ID)); + + // An existing agent loads before our optimistic entry. It must not be picked, since we don't record + // existing agents until our entry is present. + await act(async () => { + await Onyx.merge(preExistingAgentKey, {}); + await waitForBatchedUpdates(); + }); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // The optimistic entry appears, so the existing agent is now recorded as already existing. + await act(async () => { + await Onyx.merge(optimisticAgentKey, {pendingAction: 'add'}); + await waitForBatchedUpdates(); + }); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + + // Only the created agent opens the DM. + await act(async () => { + await Onyx.merge(realAgentKey, {}); + await waitForBatchedUpdates(); + }); + + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); + }); + + it('goes back instead of opening a DM when creation fails', async () => { + const {result} = renderHook(() => useOpenDMWithCreatedAgent()); + + act(() => result.current(OPTIMISTIC_ACCOUNT_ID)); + await act(async () => { + await Onyx.merge(optimisticAgentKey, {pendingAction: 'add'}); + await waitForBatchedUpdates(); + }); + + // Creation failed: the optimistic entry now has an error. + await act(async () => { + await Onyx.merge(optimisticAgentKey, {pendingAction: 'add', errors: {error: 'genericAdd'}}); + await waitForBatchedUpdates(); + }); + + await waitFor(() => expect(mockGoBack).toHaveBeenCalledTimes(1)); + expect(mockChatWithAgent).not.toHaveBeenCalled(); + }); + + it('stops watching after opening a DM, and does not react to further collection changes', async () => { + const {result} = renderHook(() => useOpenDMWithCreatedAgent()); + + act(() => result.current(OPTIMISTIC_ACCOUNT_ID)); + await act(async () => { + await Onyx.merge(optimisticAgentKey, {pendingAction: 'add'}); + await waitForBatchedUpdates(); + }); + await act(async () => { + await Onyx.merge(realAgentKey, {}); + await waitForBatchedUpdates(); + }); + await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledTimes(1)); + + const unrelatedAgentKey: OnyxKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}777`; + await act(async () => { + await Onyx.merge(unrelatedAgentKey, {}); + await waitForBatchedUpdates(); + }); + + expect(mockChatWithAgent).toHaveBeenCalledTimes(1); + expect(mockGoBack).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/pages/settings/AddAgentPageTest.tsx b/tests/unit/pages/settings/AddAgentPageTest.tsx index 75c4d3cc0d2f..89087bd9c894 100644 --- a/tests/unit/pages/settings/AddAgentPageTest.tsx +++ b/tests/unit/pages/settings/AddAgentPageTest.tsx @@ -1,6 +1,7 @@ -import {act, render, waitFor} from '@testing-library/react-native'; +import {act, render} from '@testing-library/react-native'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; +import useOpenDMWithCreatedAgent from '@hooks/useOpenDMWithCreatedAgent'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; @@ -12,7 +13,6 @@ import {setInitialPresetID, setNavigationToken} from '@pages/settings/Agents/pen import {createAgent} from '@userActions/Agent'; -import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; @@ -33,9 +33,9 @@ jest.mock('@hooks/useLocalize', () => jest.fn(() => ({translate: mockTranslate}) jest.mock('@hooks/useCurrentUserPersonalDetails', () => jest.fn(() => ({}))); -const mockChatWithAgent = jest.fn(); +const mockWatchForCreatedAgent = jest.fn(); -jest.mock('@hooks/useChatWithAgent', () => jest.fn(() => mockChatWithAgent)); +jest.mock('@hooks/useOpenDMWithCreatedAgent', () => jest.fn(() => mockWatchForCreatedAgent)); jest.mock('@hooks/useTheme', () => jest.fn(() => ({textLight: '#fff'}))); @@ -56,13 +56,6 @@ jest.mock('@hooks/useLazyAsset', () => ({ useMemoizedLazyExpensifyIcons: jest.fn(() => ({Pencil: 1})), })); -// AddAgentPage reads the agent-prompt collection to find the newly created agent. The mocked useOnyx does not -// update on its own, so tests set this value and its load status and re-render to simulate collection updates. -let mockAgentPrompts: Record}> | undefined; -let mockAgentPromptsStatus: 'loading' | 'loaded' = 'loaded'; - -jest.mock('@hooks/useOnyx', () => jest.fn(() => [mockAgentPrompts, {status: mockAgentPromptsStatus}])); - jest.mock('@libs/Navigation/Navigation', () => ({ goBack: jest.fn(), navigate: jest.fn(), @@ -106,10 +99,12 @@ jest.mock('@components/HeaderWithBackButton', () => { }); let mockFormOnSubmit: ((values: {firstName: string; prompt: string}) => void) | undefined; +let mockFormIsLoading: boolean | undefined; jest.mock('@components/Form/FormProvider', () => { - function MockFormProvider({children, onSubmit}: {children: React.ReactNode; onSubmit: (values: {firstName: string; prompt: string}) => void}) { + function MockFormProvider({children, onSubmit, isLoading}: {children: React.ReactNode; onSubmit: (values: {firstName: string; prompt: string}) => void; isLoading?: boolean}) { mockFormOnSubmit = onSubmit; + mockFormIsLoading = isLoading; return children; } return MockFormProvider; @@ -147,6 +142,7 @@ const mockGoBack = jest.mocked(Navigation.goBack); const mockIsActiveRoute = jest.mocked(Navigation.isActiveRoute); const mockGetIsOffline = jest.mocked(getIsOffline); const mockUseCurrentUserPersonalDetails = jest.mocked(useCurrentUserPersonalDetails); +const mockUseOpenDMWithCreatedAgent = jest.mocked(useOpenDMWithCreatedAgent); type AddAgentRouteProp = PlatformStackRouteProp; @@ -155,41 +151,27 @@ function makeRoute(params: AddAgentRouteProp['params'] = {}): AddAgentRouteProp } const OPTIMISTIC_ACCOUNT_ID = -123456; -const REAL_ACCOUNT_ID = 22542959; -const realAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${REAL_ACCOUNT_ID}`; -const optimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${OPTIMISTIC_ACCOUNT_ID}`; -const otherOptimisticAgentKey = `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}999`; const mockNavigation = undefined as never; function renderAddAgentPage(params: AddAgentRouteProp['params'] = {}) { - const utils = render( + return render( , ); - return { - ...utils, - rerenderPage: () => - utils.rerender( - , - ), - }; } describe('AddAgentPage', () => { beforeEach(() => { jest.clearAllMocks(); mockUseCurrentUserPersonalDetails.mockReturnValue({accountID: 0}); + mockUseOpenDMWithCreatedAgent.mockReturnValue(mockWatchForCreatedAgent); mockCreateAgent.mockReturnValue({optimisticAccountID: OPTIMISTIC_ACCOUNT_ID, avatarURI: undefined}); mockGetIsOffline.mockReturnValue(false); mockIsActiveRoute.mockReturnValue(true); mockAvatarOnPress = undefined; - mockAgentPrompts = {}; - mockAgentPromptsStatus = 'loaded'; + mockFormIsLoading = undefined; }); it('renders page title', () => { @@ -292,155 +274,43 @@ describe('AddAgentPage', () => { expect(mockSetInitialPresetID).toHaveBeenCalledTimes(1); }); + // Matching the created agent and opening its DM is covered by useOpenDMWithCreatedAgent.test.ts. + // These tests only cover how AddAgentPage wires into that hook. describe('submit branching', () => { beforeEach(() => { mockFormOnSubmit = undefined; }); - it('stays on the page until the created agent appears, then opens the DM with its real accountID (policyID absent)', async () => { - const {rerenderPage} = renderAddAgentPage({}); + it('starts watching for the created agent and shows the loading state when online (policyID absent)', () => { + renderAddAgentPage({}); act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // Online we don't go back yet. We wait for the real accountID from the server. + expect(mockWatchForCreatedAgent).toHaveBeenCalledWith(OPTIMISTIC_ACCOUNT_ID); + expect(mockFormIsLoading).toBe(true); expect(mockGoBack).not.toHaveBeenCalled(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); - - // The optimistic entry appears, so the effect records which agents already exist. - mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; - rerenderPage(); - await waitForBatchedUpdates(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); - - // The created agent arrives from the server (no ADD pending action). - mockAgentPrompts = {[realAgentKey]: {}}; - rerenderPage(); - - // The DM opens with the real accountID, not the optimistic one, and closes the modal. - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); - expect(mockChatWithAgent).toHaveBeenCalledTimes(1); - expect(mockGoBack).not.toHaveBeenCalled(); - }); - - it('opens the DM with the real accountID once the created agent appears (policyID present)', async () => { - const {rerenderPage} = renderAddAgentPage({policyID: 'POL_42'}); - - act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - - mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; - rerenderPage(); - - mockAgentPrompts = {[realAgentKey]: {}}; - rerenderPage(); - - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); - expect(mockChatWithAgent).toHaveBeenCalledTimes(1); }); - it('ignores another optimistic (pending ADD) agent and waits for the real one', async () => { - const {rerenderPage} = renderAddAgentPage({}); + it('starts watching for the created agent when online (policyID present)', () => { + renderAddAgentPage({policyID: 'POL_42'}); act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // The optimistic entry appears and records which agents already exist. - mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; - rerenderPage(); - - // A second agent the user created shows up as a new optimistic entry (pendingAction ADD). - // It must not be picked as the created agent. - mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}, [otherOptimisticAgentKey]: {pendingAction: 'add'}}; - rerenderPage(); - await waitForBatchedUpdates(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); - - // The created agent arrives from the server without an ADD pending action. - mockAgentPrompts = {[otherOptimisticAgentKey]: {pendingAction: 'add'}, [realAgentKey]: {}}; - rerenderPage(); - - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); - }); - - it('does not treat an agent that hydrates after submit as the newly created one', async () => { - // Cold open or direct link: the collection has not loaded yet at submit time. - mockAgentPrompts = {}; - const {rerenderPage} = renderAddAgentPage({}); - - act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - - // An existing agent loads before our optimistic entry and before the CREATE_AGENT response. It must - // not be picked, since we don't record existing agents until our entry is present. - mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}}; - rerenderPage(); - await waitForBatchedUpdates(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); - - // The optimistic entry appears, so the existing agent is now recorded as already existing. - mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [optimisticAgentKey]: {pendingAction: 'add'}}; - rerenderPage(); - await waitForBatchedUpdates(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); - - // Only the created agent opens the DM. - mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [realAgentKey]: {}}; - rerenderPage(); - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); - }); - - it('does not match while the collection is still loading', async () => { - mockAgentPromptsStatus = 'loading'; - mockAgentPrompts = {}; - const {rerenderPage} = renderAddAgentPage({}); - - act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - - // While loading, an agent next to our entry must not be picked. - mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}, [`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}}; - rerenderPage(); - await waitForBatchedUpdates(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); - - // Once loaded, existing agents are recorded (agent 555 and our entry), and the created agent matches. - mockAgentPromptsStatus = 'loaded'; - rerenderPage(); - await waitForBatchedUpdates(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); - - mockAgentPrompts = {[`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}555`]: {}, [realAgentKey]: {}}; - rerenderPage(); - await waitFor(() => expect(mockChatWithAgent).toHaveBeenCalledWith(REAL_ACCOUNT_ID, {shouldDismissModal: true})); - }); - - it('dismisses the page and does not open the DM when creation fails', async () => { - const {rerenderPage} = renderAddAgentPage({}); - - act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - - // The optimistic entry appears and records the existing agents. - mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add'}}; - rerenderPage(); - - // Creation failed: the optimistic entry now has an error. - mockAgentPrompts = {[optimisticAgentKey]: {pendingAction: 'add', errors: {error: 'genericAdd'}}}; - rerenderPage(); - - // We go back so the error shows on the Agents list, and no DM opens. - await waitFor(() => expect(mockGoBack).toHaveBeenCalledTimes(1)); - expect(mockChatWithAgent).not.toHaveBeenCalled(); + expect(mockWatchForCreatedAgent).toHaveBeenCalledWith(OPTIMISTIC_ACCOUNT_ID); + expect(mockFormIsLoading).toBe(true); }); - it('does not open the DM when created offline, even if the user is still on the Agents list', async () => { + it('goes back right away and does not start watching when created offline', async () => { mockGetIsOffline.mockReturnValue(true); - mockIsActiveRoute.mockReturnValue(true); renderAddAgentPage({}); act(() => mockFormOnSubmit?.({firstName: 'Bot', prompt: 'Reject gambling.'})); - // We go back to the Agents list right away and never open the DM. The real accountID only arrives on - // reconnect, after the user has moved on. expect(mockGoBack).toHaveBeenCalledTimes(1); await waitForBatchedUpdates(); - expect(mockChatWithAgent).not.toHaveBeenCalled(); + expect(mockWatchForCreatedAgent).not.toHaveBeenCalled(); + expect(mockFormIsLoading).toBeFalsy(); }); }); });