Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions config/eslint/eslint.seatbelt.tsv

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions src/hooks/useChatWithAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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;
Expand Down
90 changes: 90 additions & 0 deletions src/hooks/useOpenDMWithCreatedAgent.ts
Original file line number Diff line number Diff line change
@@ -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<number> | 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<PendingCreatedAgent | null>(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;
7 changes: 4 additions & 3 deletions src/libs/actions/Report/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2412,6 +2412,7 @@ function navigateToAndOpenReportWithAccountIDs(
betas: OnyxEntry<Beta[]>,
personalDetails: OnyxEntry<PersonalDetailsList>,
shouldRevalidateExistingChat = false,
shouldDismissModal = false,
) {
const participants = participantAccountIDs.map((accountID): ParticipantInfo => {
return {
Expand Down Expand Up @@ -2441,7 +2442,7 @@ function navigateToAndOpenReportWithAccountIDs(
betas,
});

navigateToReport(fallbackChat.reportID, {shouldDismissModal: false});
navigateToReport(fallbackChat.reportID, {shouldDismissModal});
};

if (!chat || isReportNotFound(chat)) {
Expand All @@ -2450,7 +2451,7 @@ function navigateToAndOpenReportWithAccountIDs(
}

if (!shouldRevalidateExistingChat) {
navigateToReport(chat.reportID, {shouldDismissModal: false});
navigateToReport(chat.reportID, {shouldDismissModal});
return;
}

Expand All @@ -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});
}

/**
Expand Down
27 changes: 19 additions & 8 deletions src/pages/settings/Agents/AddAgentPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'
import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOpenDMWithCreatedAgent from '@hooks/useOpenDMWithCreatedAgent';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';

Expand All @@ -21,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';
Expand All @@ -47,12 +49,14 @@ function AddAgentPage({route}: AddAgentPageProps) {
const {windowWidth, windowHeight} = useWindowDimensions();
const shouldUseScrollableLayout = useIsInLandscapeMode() || (isMobile() && windowWidth > windowHeight);
const {displayName} = useCurrentUserPersonalDetails();
const watchForCreatedAgent = useOpenDMWithCreatedAgent();
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<AgentAvatarID | null>(() => AGENT_AVATARS.ordered.at(Math.floor(Math.random() * AGENT_AVATARS.ordered.length))?.id ?? null);
const [uploadedURI, setUploadedURI] = useState<string | null>(null);
const [isCreatingAgent, setIsCreatingAgent] = useState(false);
const pendingFileRef = useRef<{file: File | CustomRNImageManipulatorResult; uri: string} | null>(null);

useFocusEffect(
Expand Down Expand Up @@ -97,16 +101,22 @@ 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 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);
// 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 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;
}

Navigation.goBack();
// Online: stay here with the submit spinner until the created agent appears, then its DM opens.
watchForCreatedAgent(optimisticAccountID);
setIsCreatingAgent(true);
};

return (
Expand All @@ -125,6 +135,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}
Expand Down
172 changes: 172 additions & 0 deletions tests/unit/hooks/useOpenDMWithCreatedAgent.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading
Loading